View.java revision 3d5286983447262f12b78785391681b20a71f6b2
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.annotation.UiThread; 32import android.content.ClipData; 33import android.content.Context; 34import android.content.ContextWrapper; 35import android.content.Intent; 36import android.content.res.ColorStateList; 37import android.content.res.Configuration; 38import android.content.res.Resources; 39import android.content.res.TypedArray; 40import android.graphics.Bitmap; 41import android.graphics.Canvas; 42import android.graphics.Insets; 43import android.graphics.Interpolator; 44import android.graphics.LinearGradient; 45import android.graphics.Matrix; 46import android.graphics.Outline; 47import android.graphics.Paint; 48import android.graphics.PixelFormat; 49import android.graphics.Point; 50import android.graphics.PorterDuff; 51import android.graphics.PorterDuffXfermode; 52import android.graphics.Rect; 53import android.graphics.RectF; 54import android.graphics.Region; 55import android.graphics.Shader; 56import android.graphics.drawable.ColorDrawable; 57import android.graphics.drawable.Drawable; 58import android.hardware.display.DisplayManagerGlobal; 59import android.os.Bundle; 60import android.os.Handler; 61import android.os.IBinder; 62import android.os.Parcel; 63import android.os.Parcelable; 64import android.os.RemoteException; 65import android.os.SystemClock; 66import android.os.SystemProperties; 67import android.os.Trace; 68import android.text.TextUtils; 69import android.util.AttributeSet; 70import android.util.FloatProperty; 71import android.util.LayoutDirection; 72import android.util.Log; 73import android.util.LongSparseLongArray; 74import android.util.Pools.SynchronizedPool; 75import android.util.Property; 76import android.util.SparseArray; 77import android.util.StateSet; 78import android.util.SuperNotCalledException; 79import android.util.TypedValue; 80import android.view.ContextMenu.ContextMenuInfo; 81import android.view.AccessibilityIterators.TextSegmentIterator; 82import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 83import android.view.AccessibilityIterators.WordTextSegmentIterator; 84import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 85import android.view.accessibility.AccessibilityEvent; 86import android.view.accessibility.AccessibilityEventSource; 87import android.view.accessibility.AccessibilityManager; 88import android.view.accessibility.AccessibilityNodeInfo; 89import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction; 90import android.view.accessibility.AccessibilityNodeProvider; 91import android.view.animation.Animation; 92import android.view.animation.AnimationUtils; 93import android.view.animation.Transformation; 94import android.view.inputmethod.EditorInfo; 95import android.view.inputmethod.InputConnection; 96import android.view.inputmethod.InputMethodManager; 97import android.widget.Checkable; 98import android.widget.ScrollBarDrawable; 99 100import static android.os.Build.VERSION_CODES.*; 101import static java.lang.Math.max; 102 103import com.android.internal.R; 104import com.android.internal.util.Predicate; 105import com.android.internal.view.menu.MenuBuilder; 106import com.google.android.collect.Lists; 107import com.google.android.collect.Maps; 108 109import java.lang.annotation.Retention; 110import java.lang.annotation.RetentionPolicy; 111import java.lang.ref.WeakReference; 112import java.lang.reflect.Field; 113import java.lang.reflect.InvocationTargetException; 114import java.lang.reflect.Method; 115import java.lang.reflect.Modifier; 116import java.util.ArrayList; 117import java.util.Arrays; 118import java.util.Collections; 119import java.util.HashMap; 120import java.util.List; 121import java.util.Locale; 122import java.util.Map; 123import java.util.concurrent.CopyOnWriteArrayList; 124import java.util.concurrent.atomic.AtomicInteger; 125 126/** 127 * <p> 128 * This class represents the basic building block for user interface components. A View 129 * occupies a rectangular area on the screen and is responsible for drawing and 130 * event handling. View is the base class for <em>widgets</em>, which are 131 * used to create interactive UI components (buttons, text fields, etc.). The 132 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 133 * are invisible containers that hold other Views (or other ViewGroups) and define 134 * their layout properties. 135 * </p> 136 * 137 * <div class="special reference"> 138 * <h3>Developer Guides</h3> 139 * <p>For information about using this class to develop your application's user interface, 140 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 141 * </div> 142 * 143 * <a name="Using"></a> 144 * <h3>Using Views</h3> 145 * <p> 146 * All of the views in a window are arranged in a single tree. You can add views 147 * either from code or by specifying a tree of views in one or more XML layout 148 * files. There are many specialized subclasses of views that act as controls or 149 * are capable of displaying text, images, or other content. 150 * </p> 151 * <p> 152 * Once you have created a tree of views, there are typically a few types of 153 * common operations you may wish to perform: 154 * <ul> 155 * <li><strong>Set properties:</strong> for example setting the text of a 156 * {@link android.widget.TextView}. The available properties and the methods 157 * that set them will vary among the different subclasses of views. Note that 158 * properties that are known at build time can be set in the XML layout 159 * files.</li> 160 * <li><strong>Set focus:</strong> The framework will handled moving focus in 161 * response to user input. To force focus to a specific view, call 162 * {@link #requestFocus}.</li> 163 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 164 * that will be notified when something interesting happens to the view. For 165 * example, all views will let you set a listener to be notified when the view 166 * gains or loses focus. You can register such a listener using 167 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 168 * Other view subclasses offer more specialized listeners. For example, a Button 169 * exposes a listener to notify clients when the button is clicked.</li> 170 * <li><strong>Set visibility:</strong> You can hide or show views using 171 * {@link #setVisibility(int)}.</li> 172 * </ul> 173 * </p> 174 * <p><em> 175 * Note: The Android framework is responsible for measuring, laying out and 176 * drawing views. You should not call methods that perform these actions on 177 * views yourself unless you are actually implementing a 178 * {@link android.view.ViewGroup}. 179 * </em></p> 180 * 181 * <a name="Lifecycle"></a> 182 * <h3>Implementing a Custom View</h3> 183 * 184 * <p> 185 * To implement a custom view, you will usually begin by providing overrides for 186 * some of the standard methods that the framework calls on all views. You do 187 * not need to override all of these methods. In fact, you can start by just 188 * overriding {@link #onDraw(android.graphics.Canvas)}. 189 * <table border="2" width="85%" align="center" cellpadding="5"> 190 * <thead> 191 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 192 * </thead> 193 * 194 * <tbody> 195 * <tr> 196 * <td rowspan="2">Creation</td> 197 * <td>Constructors</td> 198 * <td>There is a form of the constructor that are called when the view 199 * is created from code and a form that is called when the view is 200 * inflated from a layout file. The second form should parse and apply 201 * any attributes defined in the layout file. 202 * </td> 203 * </tr> 204 * <tr> 205 * <td><code>{@link #onFinishInflate()}</code></td> 206 * <td>Called after a view and all of its children has been inflated 207 * from XML.</td> 208 * </tr> 209 * 210 * <tr> 211 * <td rowspan="3">Layout</td> 212 * <td><code>{@link #onMeasure(int, int)}</code></td> 213 * <td>Called to determine the size requirements for this view and all 214 * of its children. 215 * </td> 216 * </tr> 217 * <tr> 218 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 219 * <td>Called when this view should assign a size and position to all 220 * of its children. 221 * </td> 222 * </tr> 223 * <tr> 224 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 225 * <td>Called when the size of this view has changed. 226 * </td> 227 * </tr> 228 * 229 * <tr> 230 * <td>Drawing</td> 231 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 232 * <td>Called when the view should render its content. 233 * </td> 234 * </tr> 235 * 236 * <tr> 237 * <td rowspan="4">Event processing</td> 238 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 239 * <td>Called when a new hardware key event occurs. 240 * </td> 241 * </tr> 242 * <tr> 243 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 244 * <td>Called when a hardware key up event occurs. 245 * </td> 246 * </tr> 247 * <tr> 248 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 249 * <td>Called when a trackball motion event occurs. 250 * </td> 251 * </tr> 252 * <tr> 253 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 254 * <td>Called when a touch screen motion event occurs. 255 * </td> 256 * </tr> 257 * 258 * <tr> 259 * <td rowspan="2">Focus</td> 260 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 261 * <td>Called when the view gains or loses focus. 262 * </td> 263 * </tr> 264 * 265 * <tr> 266 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 267 * <td>Called when the window containing the view gains or loses focus. 268 * </td> 269 * </tr> 270 * 271 * <tr> 272 * <td rowspan="3">Attaching</td> 273 * <td><code>{@link #onAttachedToWindow()}</code></td> 274 * <td>Called when the view is attached to a window. 275 * </td> 276 * </tr> 277 * 278 * <tr> 279 * <td><code>{@link #onDetachedFromWindow}</code></td> 280 * <td>Called when the view is detached from its window. 281 * </td> 282 * </tr> 283 * 284 * <tr> 285 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 286 * <td>Called when the visibility of the window containing the view 287 * has changed. 288 * </td> 289 * </tr> 290 * </tbody> 291 * 292 * </table> 293 * </p> 294 * 295 * <a name="IDs"></a> 296 * <h3>IDs</h3> 297 * Views may have an integer id associated with them. These ids are typically 298 * assigned in the layout XML files, and are used to find specific views within 299 * the view tree. A common pattern is to: 300 * <ul> 301 * <li>Define a Button in the layout file and assign it a unique ID. 302 * <pre> 303 * <Button 304 * android:id="@+id/my_button" 305 * android:layout_width="wrap_content" 306 * android:layout_height="wrap_content" 307 * android:text="@string/my_button_text"/> 308 * </pre></li> 309 * <li>From the onCreate method of an Activity, find the Button 310 * <pre class="prettyprint"> 311 * Button myButton = (Button) findViewById(R.id.my_button); 312 * </pre></li> 313 * </ul> 314 * <p> 315 * View IDs need not be unique throughout the tree, but it is good practice to 316 * ensure that they are at least unique within the part of the tree you are 317 * searching. 318 * </p> 319 * 320 * <a name="Position"></a> 321 * <h3>Position</h3> 322 * <p> 323 * The geometry of a view is that of a rectangle. A view has a location, 324 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 325 * two dimensions, expressed as a width and a height. The unit for location 326 * and dimensions is the pixel. 327 * </p> 328 * 329 * <p> 330 * It is possible to retrieve the location of a view by invoking the methods 331 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 332 * coordinate of the rectangle representing the view. The latter returns the 333 * top, or Y, coordinate of the rectangle representing the view. These methods 334 * both return the location of the view relative to its parent. For instance, 335 * when getLeft() returns 20, that means the view is located 20 pixels to the 336 * right of the left edge of its direct parent. 337 * </p> 338 * 339 * <p> 340 * In addition, several convenience methods are offered to avoid unnecessary 341 * computations, namely {@link #getRight()} and {@link #getBottom()}. 342 * These methods return the coordinates of the right and bottom edges of the 343 * rectangle representing the view. For instance, calling {@link #getRight()} 344 * is similar to the following computation: <code>getLeft() + getWidth()</code> 345 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 346 * </p> 347 * 348 * <a name="SizePaddingMargins"></a> 349 * <h3>Size, padding and margins</h3> 350 * <p> 351 * The size of a view is expressed with a width and a height. A view actually 352 * possess two pairs of width and height values. 353 * </p> 354 * 355 * <p> 356 * The first pair is known as <em>measured width</em> and 357 * <em>measured height</em>. These dimensions define how big a view wants to be 358 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 359 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 360 * and {@link #getMeasuredHeight()}. 361 * </p> 362 * 363 * <p> 364 * The second pair is simply known as <em>width</em> and <em>height</em>, or 365 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 366 * dimensions define the actual size of the view on screen, at drawing time and 367 * after layout. These values may, but do not have to, be different from the 368 * measured width and height. The width and height can be obtained by calling 369 * {@link #getWidth()} and {@link #getHeight()}. 370 * </p> 371 * 372 * <p> 373 * To measure its dimensions, a view takes into account its padding. The padding 374 * is expressed in pixels for the left, top, right and bottom parts of the view. 375 * Padding can be used to offset the content of the view by a specific amount of 376 * pixels. For instance, a left padding of 2 will push the view's content by 377 * 2 pixels to the right of the left edge. Padding can be set using the 378 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 379 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 380 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 381 * {@link #getPaddingEnd()}. 382 * </p> 383 * 384 * <p> 385 * Even though a view can define a padding, it does not provide any support for 386 * margins. However, view groups provide such a support. Refer to 387 * {@link android.view.ViewGroup} and 388 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 389 * </p> 390 * 391 * <a name="Layout"></a> 392 * <h3>Layout</h3> 393 * <p> 394 * Layout is a two pass process: a measure pass and a layout pass. The measuring 395 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 396 * of the view tree. Each view pushes dimension specifications down the tree 397 * during the recursion. At the end of the measure pass, every view has stored 398 * its measurements. The second pass happens in 399 * {@link #layout(int,int,int,int)} and is also top-down. During 400 * this pass each parent is responsible for positioning all of its children 401 * using the sizes computed in the measure pass. 402 * </p> 403 * 404 * <p> 405 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 406 * {@link #getMeasuredHeight()} values must be set, along with those for all of 407 * that view's descendants. A view's measured width and measured height values 408 * must respect the constraints imposed by the view's parents. This guarantees 409 * that at the end of the measure pass, all parents accept all of their 410 * children's measurements. A parent view may call measure() more than once on 411 * its children. For example, the parent may measure each child once with 412 * unspecified dimensions to find out how big they want to be, then call 413 * measure() on them again with actual numbers if the sum of all the children's 414 * unconstrained sizes is too big or too small. 415 * </p> 416 * 417 * <p> 418 * The measure pass uses two classes to communicate dimensions. The 419 * {@link MeasureSpec} class is used by views to tell their parents how they 420 * want to be measured and positioned. The base LayoutParams class just 421 * describes how big the view wants to be for both width and height. For each 422 * dimension, it can specify one of: 423 * <ul> 424 * <li> an exact number 425 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 426 * (minus padding) 427 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 428 * enclose its content (plus padding). 429 * </ul> 430 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 431 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 432 * an X and Y value. 433 * </p> 434 * 435 * <p> 436 * MeasureSpecs are used to push requirements down the tree from parent to 437 * child. A MeasureSpec can be in one of three modes: 438 * <ul> 439 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 440 * of a child view. For example, a LinearLayout may call measure() on its child 441 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 442 * tall the child view wants to be given a width of 240 pixels. 443 * <li>EXACTLY: This is used by the parent to impose an exact size on the 444 * child. The child must use this size, and guarantee that all of its 445 * descendants will fit within this size. 446 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 447 * child. The child must guarantee that it and all of its descendants will fit 448 * within this size. 449 * </ul> 450 * </p> 451 * 452 * <p> 453 * To initiate a layout, call {@link #requestLayout}. This method is typically 454 * called by a view on itself when it believes that is can no longer fit within 455 * its current bounds. 456 * </p> 457 * 458 * <a name="Drawing"></a> 459 * <h3>Drawing</h3> 460 * <p> 461 * Drawing is handled by walking the tree and recording the drawing commands of 462 * any View that needs to update. After this, the drawing commands of the 463 * entire tree are issued to screen, clipped to the newly damaged area. 464 * </p> 465 * 466 * <p> 467 * The tree is largely recorded and drawn in order, with parents drawn before 468 * (i.e., behind) their children, with siblings drawn in the order they appear 469 * in the tree. If you set a background drawable for a View, then the View will 470 * draw it before calling back to its <code>onDraw()</code> method. The child 471 * drawing order can be overridden with 472 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 473 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 474 * </p> 475 * 476 * <p> 477 * To force a view to draw, call {@link #invalidate()}. 478 * </p> 479 * 480 * <a name="EventHandlingThreading"></a> 481 * <h3>Event Handling and Threading</h3> 482 * <p> 483 * The basic cycle of a view is as follows: 484 * <ol> 485 * <li>An event comes in and is dispatched to the appropriate view. The view 486 * handles the event and notifies any listeners.</li> 487 * <li>If in the course of processing the event, the view's bounds may need 488 * to be changed, the view will call {@link #requestLayout()}.</li> 489 * <li>Similarly, if in the course of processing the event the view's appearance 490 * may need to be changed, the view will call {@link #invalidate()}.</li> 491 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 492 * the framework will take care of measuring, laying out, and drawing the tree 493 * as appropriate.</li> 494 * </ol> 495 * </p> 496 * 497 * <p><em>Note: The entire view tree is single threaded. You must always be on 498 * the UI thread when calling any method on any view.</em> 499 * If you are doing work on other threads and want to update the state of a view 500 * from that thread, you should use a {@link Handler}. 501 * </p> 502 * 503 * <a name="FocusHandling"></a> 504 * <h3>Focus Handling</h3> 505 * <p> 506 * The framework will handle routine focus movement in response to user input. 507 * This includes changing the focus as views are removed or hidden, or as new 508 * views become available. Views indicate their willingness to take focus 509 * through the {@link #isFocusable} method. To change whether a view can take 510 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 511 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 512 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 513 * </p> 514 * <p> 515 * Focus movement is based on an algorithm which finds the nearest neighbor in a 516 * given direction. In rare cases, the default algorithm may not match the 517 * intended behavior of the developer. In these situations, you can provide 518 * explicit overrides by using these XML attributes in the layout file: 519 * <pre> 520 * nextFocusDown 521 * nextFocusLeft 522 * nextFocusRight 523 * nextFocusUp 524 * </pre> 525 * </p> 526 * 527 * 528 * <p> 529 * To get a particular view to take focus, call {@link #requestFocus()}. 530 * </p> 531 * 532 * <a name="TouchMode"></a> 533 * <h3>Touch Mode</h3> 534 * <p> 535 * When a user is navigating a user interface via directional keys such as a D-pad, it is 536 * necessary to give focus to actionable items such as buttons so the user can see 537 * what will take input. If the device has touch capabilities, however, and the user 538 * begins interacting with the interface by touching it, it is no longer necessary to 539 * always highlight, or give focus to, a particular view. This motivates a mode 540 * for interaction named 'touch mode'. 541 * </p> 542 * <p> 543 * For a touch capable device, once the user touches the screen, the device 544 * will enter touch mode. From this point onward, only views for which 545 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 546 * Other views that are touchable, like buttons, will not take focus when touched; they will 547 * only fire the on click listeners. 548 * </p> 549 * <p> 550 * Any time a user hits a directional key, such as a D-pad direction, the view device will 551 * exit touch mode, and find a view to take focus, so that the user may resume interacting 552 * with the user interface without touching the screen again. 553 * </p> 554 * <p> 555 * The touch mode state is maintained across {@link android.app.Activity}s. Call 556 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 557 * </p> 558 * 559 * <a name="Scrolling"></a> 560 * <h3>Scrolling</h3> 561 * <p> 562 * The framework provides basic support for views that wish to internally 563 * scroll their content. This includes keeping track of the X and Y scroll 564 * offset as well as mechanisms for drawing scrollbars. See 565 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 566 * {@link #awakenScrollBars()} for more details. 567 * </p> 568 * 569 * <a name="Tags"></a> 570 * <h3>Tags</h3> 571 * <p> 572 * Unlike IDs, tags are not used to identify views. Tags are essentially an 573 * extra piece of information that can be associated with a view. They are most 574 * often used as a convenience to store data related to views in the views 575 * themselves rather than by putting them in a separate structure. 576 * </p> 577 * 578 * <a name="Properties"></a> 579 * <h3>Properties</h3> 580 * <p> 581 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 582 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 583 * available both in the {@link Property} form as well as in similarly-named setter/getter 584 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 585 * be used to set persistent state associated with these rendering-related properties on the view. 586 * The properties and methods can also be used in conjunction with 587 * {@link android.animation.Animator Animator}-based animations, described more in the 588 * <a href="#Animation">Animation</a> section. 589 * </p> 590 * 591 * <a name="Animation"></a> 592 * <h3>Animation</h3> 593 * <p> 594 * Starting with Android 3.0, the preferred way of animating views is to use the 595 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 596 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 597 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 598 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 599 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 600 * makes animating these View properties particularly easy and efficient. 601 * </p> 602 * <p> 603 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 604 * You can attach an {@link Animation} object to a view using 605 * {@link #setAnimation(Animation)} or 606 * {@link #startAnimation(Animation)}. The animation can alter the scale, 607 * rotation, translation and alpha of a view over time. If the animation is 608 * attached to a view that has children, the animation will affect the entire 609 * subtree rooted by that node. When an animation is started, the framework will 610 * take care of redrawing the appropriate views until the animation completes. 611 * </p> 612 * 613 * <a name="Security"></a> 614 * <h3>Security</h3> 615 * <p> 616 * Sometimes it is essential that an application be able to verify that an action 617 * is being performed with the full knowledge and consent of the user, such as 618 * granting a permission request, making a purchase or clicking on an advertisement. 619 * Unfortunately, a malicious application could try to spoof the user into 620 * performing these actions, unaware, by concealing the intended purpose of the view. 621 * As a remedy, the framework offers a touch filtering mechanism that can be used to 622 * improve the security of views that provide access to sensitive functionality. 623 * </p><p> 624 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 625 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 626 * will discard touches that are received whenever the view's window is obscured by 627 * another visible window. As a result, the view will not receive touches whenever a 628 * toast, dialog or other window appears above the view's window. 629 * </p><p> 630 * For more fine-grained control over security, consider overriding the 631 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 632 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 633 * </p> 634 * 635 * @attr ref android.R.styleable#View_alpha 636 * @attr ref android.R.styleable#View_background 637 * @attr ref android.R.styleable#View_clickable 638 * @attr ref android.R.styleable#View_contentDescription 639 * @attr ref android.R.styleable#View_drawingCacheQuality 640 * @attr ref android.R.styleable#View_duplicateParentState 641 * @attr ref android.R.styleable#View_id 642 * @attr ref android.R.styleable#View_requiresFadingEdge 643 * @attr ref android.R.styleable#View_fadeScrollbars 644 * @attr ref android.R.styleable#View_fadingEdgeLength 645 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 646 * @attr ref android.R.styleable#View_fitsSystemWindows 647 * @attr ref android.R.styleable#View_isScrollContainer 648 * @attr ref android.R.styleable#View_focusable 649 * @attr ref android.R.styleable#View_focusableInTouchMode 650 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 651 * @attr ref android.R.styleable#View_keepScreenOn 652 * @attr ref android.R.styleable#View_layerType 653 * @attr ref android.R.styleable#View_layoutDirection 654 * @attr ref android.R.styleable#View_longClickable 655 * @attr ref android.R.styleable#View_minHeight 656 * @attr ref android.R.styleable#View_minWidth 657 * @attr ref android.R.styleable#View_nextFocusDown 658 * @attr ref android.R.styleable#View_nextFocusLeft 659 * @attr ref android.R.styleable#View_nextFocusRight 660 * @attr ref android.R.styleable#View_nextFocusUp 661 * @attr ref android.R.styleable#View_onClick 662 * @attr ref android.R.styleable#View_padding 663 * @attr ref android.R.styleable#View_paddingBottom 664 * @attr ref android.R.styleable#View_paddingLeft 665 * @attr ref android.R.styleable#View_paddingRight 666 * @attr ref android.R.styleable#View_paddingTop 667 * @attr ref android.R.styleable#View_paddingStart 668 * @attr ref android.R.styleable#View_paddingEnd 669 * @attr ref android.R.styleable#View_saveEnabled 670 * @attr ref android.R.styleable#View_rotation 671 * @attr ref android.R.styleable#View_rotationX 672 * @attr ref android.R.styleable#View_rotationY 673 * @attr ref android.R.styleable#View_scaleX 674 * @attr ref android.R.styleable#View_scaleY 675 * @attr ref android.R.styleable#View_scrollX 676 * @attr ref android.R.styleable#View_scrollY 677 * @attr ref android.R.styleable#View_scrollbarSize 678 * @attr ref android.R.styleable#View_scrollbarStyle 679 * @attr ref android.R.styleable#View_scrollbars 680 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 681 * @attr ref android.R.styleable#View_scrollbarFadeDuration 682 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 683 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 684 * @attr ref android.R.styleable#View_scrollbarThumbVertical 685 * @attr ref android.R.styleable#View_scrollbarTrackVertical 686 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 687 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 688 * @attr ref android.R.styleable#View_stateListAnimator 689 * @attr ref android.R.styleable#View_transitionName 690 * @attr ref android.R.styleable#View_soundEffectsEnabled 691 * @attr ref android.R.styleable#View_tag 692 * @attr ref android.R.styleable#View_textAlignment 693 * @attr ref android.R.styleable#View_textDirection 694 * @attr ref android.R.styleable#View_transformPivotX 695 * @attr ref android.R.styleable#View_transformPivotY 696 * @attr ref android.R.styleable#View_translationX 697 * @attr ref android.R.styleable#View_translationY 698 * @attr ref android.R.styleable#View_translationZ 699 * @attr ref android.R.styleable#View_visibility 700 * 701 * @see android.view.ViewGroup 702 */ 703@UiThread 704public class View implements Drawable.Callback, KeyEvent.Callback, 705 AccessibilityEventSource { 706 private static final boolean DBG = false; 707 708 /** 709 * The logging tag used by this class with android.util.Log. 710 */ 711 protected static final String VIEW_LOG_TAG = "View"; 712 713 /** 714 * When set to true, apps will draw debugging information about their layouts. 715 * 716 * @hide 717 */ 718 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 719 720 /** 721 * When set to true, this view will save its attribute data. 722 * 723 * @hide 724 */ 725 public static boolean mDebugViewAttributes = false; 726 727 /** 728 * Used to mark a View that has no ID. 729 */ 730 public static final int NO_ID = -1; 731 732 /** 733 * Signals that compatibility booleans have been initialized according to 734 * target SDK versions. 735 */ 736 private static boolean sCompatibilityDone = false; 737 738 /** 739 * Use the old (broken) way of building MeasureSpecs. 740 */ 741 private static boolean sUseBrokenMakeMeasureSpec = false; 742 743 /** 744 * Ignore any optimizations using the measure cache. 745 */ 746 private static boolean sIgnoreMeasureCache = false; 747 748 /** 749 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 750 * calling setFlags. 751 */ 752 private static final int NOT_FOCUSABLE = 0x00000000; 753 754 /** 755 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 756 * setFlags. 757 */ 758 private static final int FOCUSABLE = 0x00000001; 759 760 /** 761 * Mask for use with setFlags indicating bits used for focus. 762 */ 763 private static final int FOCUSABLE_MASK = 0x00000001; 764 765 /** 766 * This view will adjust its padding to fit sytem windows (e.g. status bar) 767 */ 768 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 769 770 /** @hide */ 771 @IntDef({VISIBLE, INVISIBLE, GONE}) 772 @Retention(RetentionPolicy.SOURCE) 773 public @interface Visibility {} 774 775 /** 776 * This view is visible. 777 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 778 * android:visibility}. 779 */ 780 public static final int VISIBLE = 0x00000000; 781 782 /** 783 * This view is invisible, but it still takes up space for layout purposes. 784 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 785 * android:visibility}. 786 */ 787 public static final int INVISIBLE = 0x00000004; 788 789 /** 790 * This view is invisible, and it doesn't take any space for layout 791 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 792 * android:visibility}. 793 */ 794 public static final int GONE = 0x00000008; 795 796 /** 797 * Mask for use with setFlags indicating bits used for visibility. 798 * {@hide} 799 */ 800 static final int VISIBILITY_MASK = 0x0000000C; 801 802 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 803 804 /** 805 * This view is enabled. Interpretation varies by subclass. 806 * Use with ENABLED_MASK when calling setFlags. 807 * {@hide} 808 */ 809 static final int ENABLED = 0x00000000; 810 811 /** 812 * This view is disabled. Interpretation varies by subclass. 813 * Use with ENABLED_MASK when calling setFlags. 814 * {@hide} 815 */ 816 static final int DISABLED = 0x00000020; 817 818 /** 819 * Mask for use with setFlags indicating bits used for indicating whether 820 * this view is enabled 821 * {@hide} 822 */ 823 static final int ENABLED_MASK = 0x00000020; 824 825 /** 826 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 827 * called and further optimizations will be performed. It is okay to have 828 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 829 * {@hide} 830 */ 831 static final int WILL_NOT_DRAW = 0x00000080; 832 833 /** 834 * Mask for use with setFlags indicating bits used for indicating whether 835 * this view is will draw 836 * {@hide} 837 */ 838 static final int DRAW_MASK = 0x00000080; 839 840 /** 841 * <p>This view doesn't show scrollbars.</p> 842 * {@hide} 843 */ 844 static final int SCROLLBARS_NONE = 0x00000000; 845 846 /** 847 * <p>This view shows horizontal scrollbars.</p> 848 * {@hide} 849 */ 850 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 851 852 /** 853 * <p>This view shows vertical scrollbars.</p> 854 * {@hide} 855 */ 856 static final int SCROLLBARS_VERTICAL = 0x00000200; 857 858 /** 859 * <p>Mask for use with setFlags indicating bits used for indicating which 860 * scrollbars are enabled.</p> 861 * {@hide} 862 */ 863 static final int SCROLLBARS_MASK = 0x00000300; 864 865 /** 866 * Indicates that the view should filter touches when its window is obscured. 867 * Refer to the class comments for more information about this security feature. 868 * {@hide} 869 */ 870 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 871 872 /** 873 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 874 * that they are optional and should be skipped if the window has 875 * requested system UI flags that ignore those insets for layout. 876 */ 877 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 878 879 /** 880 * <p>This view doesn't show fading edges.</p> 881 * {@hide} 882 */ 883 static final int FADING_EDGE_NONE = 0x00000000; 884 885 /** 886 * <p>This view shows horizontal fading edges.</p> 887 * {@hide} 888 */ 889 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 890 891 /** 892 * <p>This view shows vertical fading edges.</p> 893 * {@hide} 894 */ 895 static final int FADING_EDGE_VERTICAL = 0x00002000; 896 897 /** 898 * <p>Mask for use with setFlags indicating bits used for indicating which 899 * fading edges are enabled.</p> 900 * {@hide} 901 */ 902 static final int FADING_EDGE_MASK = 0x00003000; 903 904 /** 905 * <p>Indicates this view can be clicked. When clickable, a View reacts 906 * to clicks by notifying the OnClickListener.<p> 907 * {@hide} 908 */ 909 static final int CLICKABLE = 0x00004000; 910 911 /** 912 * <p>Indicates this view is caching its drawing into a bitmap.</p> 913 * {@hide} 914 */ 915 static final int DRAWING_CACHE_ENABLED = 0x00008000; 916 917 /** 918 * <p>Indicates that no icicle should be saved for this view.<p> 919 * {@hide} 920 */ 921 static final int SAVE_DISABLED = 0x000010000; 922 923 /** 924 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 925 * property.</p> 926 * {@hide} 927 */ 928 static final int SAVE_DISABLED_MASK = 0x000010000; 929 930 /** 931 * <p>Indicates that no drawing cache should ever be created for this view.<p> 932 * {@hide} 933 */ 934 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 935 936 /** 937 * <p>Indicates this view can take / keep focus when int touch mode.</p> 938 * {@hide} 939 */ 940 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 941 942 /** @hide */ 943 @Retention(RetentionPolicy.SOURCE) 944 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 945 public @interface DrawingCacheQuality {} 946 947 /** 948 * <p>Enables low quality mode for the drawing cache.</p> 949 */ 950 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 951 952 /** 953 * <p>Enables high quality mode for the drawing cache.</p> 954 */ 955 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 956 957 /** 958 * <p>Enables automatic quality mode for the drawing cache.</p> 959 */ 960 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 961 962 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 963 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 964 }; 965 966 /** 967 * <p>Mask for use with setFlags indicating bits used for the cache 968 * quality property.</p> 969 * {@hide} 970 */ 971 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 972 973 /** 974 * <p> 975 * Indicates this view can be long clicked. When long clickable, a View 976 * reacts to long clicks by notifying the OnLongClickListener or showing a 977 * context menu. 978 * </p> 979 * {@hide} 980 */ 981 static final int LONG_CLICKABLE = 0x00200000; 982 983 /** 984 * <p>Indicates that this view gets its drawable states from its direct parent 985 * and ignores its original internal states.</p> 986 * 987 * @hide 988 */ 989 static final int DUPLICATE_PARENT_STATE = 0x00400000; 990 991 /** 992 * <p> 993 * Indicates this view can be stylus button pressed. When stylus button 994 * pressable, a View reacts to stylus button presses by notifiying 995 * the OnStylusButtonPressListener. 996 * </p> 997 * {@hide} 998 */ 999 static final int STYLUS_BUTTON_PRESSABLE = 0x00800000; 1000 1001 1002 /** @hide */ 1003 @IntDef({ 1004 SCROLLBARS_INSIDE_OVERLAY, 1005 SCROLLBARS_INSIDE_INSET, 1006 SCROLLBARS_OUTSIDE_OVERLAY, 1007 SCROLLBARS_OUTSIDE_INSET 1008 }) 1009 @Retention(RetentionPolicy.SOURCE) 1010 public @interface ScrollBarStyle {} 1011 1012 /** 1013 * The scrollbar style to display the scrollbars inside the content area, 1014 * without increasing the padding. The scrollbars will be overlaid with 1015 * translucency on the view's content. 1016 */ 1017 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 1018 1019 /** 1020 * The scrollbar style to display the scrollbars inside the padded area, 1021 * increasing the padding of the view. The scrollbars will not overlap the 1022 * content area of the view. 1023 */ 1024 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1025 1026 /** 1027 * The scrollbar style to display the scrollbars at the edge of the view, 1028 * without increasing the padding. The scrollbars will be overlaid with 1029 * translucency. 1030 */ 1031 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1032 1033 /** 1034 * The scrollbar style to display the scrollbars at the edge of the view, 1035 * increasing the padding of the view. The scrollbars will only overlap the 1036 * background, if any. 1037 */ 1038 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1039 1040 /** 1041 * Mask to check if the scrollbar style is overlay or inset. 1042 * {@hide} 1043 */ 1044 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1045 1046 /** 1047 * Mask to check if the scrollbar style is inside or outside. 1048 * {@hide} 1049 */ 1050 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1051 1052 /** 1053 * Mask for scrollbar style. 1054 * {@hide} 1055 */ 1056 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1057 1058 /** 1059 * View flag indicating that the screen should remain on while the 1060 * window containing this view is visible to the user. This effectively 1061 * takes care of automatically setting the WindowManager's 1062 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1063 */ 1064 public static final int KEEP_SCREEN_ON = 0x04000000; 1065 1066 /** 1067 * View flag indicating whether this view should have sound effects enabled 1068 * for events such as clicking and touching. 1069 */ 1070 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1071 1072 /** 1073 * View flag indicating whether this view should have haptic feedback 1074 * enabled for events such as long presses. 1075 */ 1076 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1077 1078 /** 1079 * <p>Indicates that the view hierarchy should stop saving state when 1080 * it reaches this view. If state saving is initiated immediately at 1081 * the view, it will be allowed. 1082 * {@hide} 1083 */ 1084 static final int PARENT_SAVE_DISABLED = 0x20000000; 1085 1086 /** 1087 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1088 * {@hide} 1089 */ 1090 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1091 1092 /** @hide */ 1093 @IntDef(flag = true, 1094 value = { 1095 FOCUSABLES_ALL, 1096 FOCUSABLES_TOUCH_MODE 1097 }) 1098 @Retention(RetentionPolicy.SOURCE) 1099 public @interface FocusableMode {} 1100 1101 /** 1102 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1103 * should add all focusable Views regardless if they are focusable in touch mode. 1104 */ 1105 public static final int FOCUSABLES_ALL = 0x00000000; 1106 1107 /** 1108 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1109 * should add only Views focusable in touch mode. 1110 */ 1111 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1112 1113 /** @hide */ 1114 @IntDef({ 1115 FOCUS_BACKWARD, 1116 FOCUS_FORWARD, 1117 FOCUS_LEFT, 1118 FOCUS_UP, 1119 FOCUS_RIGHT, 1120 FOCUS_DOWN 1121 }) 1122 @Retention(RetentionPolicy.SOURCE) 1123 public @interface FocusDirection {} 1124 1125 /** @hide */ 1126 @IntDef({ 1127 FOCUS_LEFT, 1128 FOCUS_UP, 1129 FOCUS_RIGHT, 1130 FOCUS_DOWN 1131 }) 1132 @Retention(RetentionPolicy.SOURCE) 1133 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1134 1135 /** 1136 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1137 * item. 1138 */ 1139 public static final int FOCUS_BACKWARD = 0x00000001; 1140 1141 /** 1142 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1143 * item. 1144 */ 1145 public static final int FOCUS_FORWARD = 0x00000002; 1146 1147 /** 1148 * Use with {@link #focusSearch(int)}. Move focus to the left. 1149 */ 1150 public static final int FOCUS_LEFT = 0x00000011; 1151 1152 /** 1153 * Use with {@link #focusSearch(int)}. Move focus up. 1154 */ 1155 public static final int FOCUS_UP = 0x00000021; 1156 1157 /** 1158 * Use with {@link #focusSearch(int)}. Move focus to the right. 1159 */ 1160 public static final int FOCUS_RIGHT = 0x00000042; 1161 1162 /** 1163 * Use with {@link #focusSearch(int)}. Move focus down. 1164 */ 1165 public static final int FOCUS_DOWN = 0x00000082; 1166 1167 /** 1168 * Bits of {@link #getMeasuredWidthAndState()} and 1169 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1170 */ 1171 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1172 1173 /** 1174 * Bits of {@link #getMeasuredWidthAndState()} and 1175 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1176 */ 1177 public static final int MEASURED_STATE_MASK = 0xff000000; 1178 1179 /** 1180 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1181 * for functions that combine both width and height into a single int, 1182 * such as {@link #getMeasuredState()} and the childState argument of 1183 * {@link #resolveSizeAndState(int, int, int)}. 1184 */ 1185 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1186 1187 /** 1188 * Bit of {@link #getMeasuredWidthAndState()} and 1189 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1190 * is smaller that the space the view would like to have. 1191 */ 1192 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1193 1194 /** 1195 * Base View state sets 1196 */ 1197 // Singles 1198 /** 1199 * Indicates the view has no states set. States are used with 1200 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1201 * view depending on its state. 1202 * 1203 * @see android.graphics.drawable.Drawable 1204 * @see #getDrawableState() 1205 */ 1206 protected static final int[] EMPTY_STATE_SET; 1207 /** 1208 * Indicates the view is enabled. States are used with 1209 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1210 * view depending on its state. 1211 * 1212 * @see android.graphics.drawable.Drawable 1213 * @see #getDrawableState() 1214 */ 1215 protected static final int[] ENABLED_STATE_SET; 1216 /** 1217 * Indicates the view is focused. States are used with 1218 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1219 * view depending on its state. 1220 * 1221 * @see android.graphics.drawable.Drawable 1222 * @see #getDrawableState() 1223 */ 1224 protected static final int[] FOCUSED_STATE_SET; 1225 /** 1226 * Indicates the view is selected. States are used with 1227 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1228 * view depending on its state. 1229 * 1230 * @see android.graphics.drawable.Drawable 1231 * @see #getDrawableState() 1232 */ 1233 protected static final int[] SELECTED_STATE_SET; 1234 /** 1235 * Indicates the view is pressed. States are used with 1236 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1237 * view depending on its state. 1238 * 1239 * @see android.graphics.drawable.Drawable 1240 * @see #getDrawableState() 1241 */ 1242 protected static final int[] PRESSED_STATE_SET; 1243 /** 1244 * Indicates the view's window has focus. States are used with 1245 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1246 * view depending on its state. 1247 * 1248 * @see android.graphics.drawable.Drawable 1249 * @see #getDrawableState() 1250 */ 1251 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1252 // Doubles 1253 /** 1254 * Indicates the view is enabled and has the focus. 1255 * 1256 * @see #ENABLED_STATE_SET 1257 * @see #FOCUSED_STATE_SET 1258 */ 1259 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1260 /** 1261 * Indicates the view is enabled and selected. 1262 * 1263 * @see #ENABLED_STATE_SET 1264 * @see #SELECTED_STATE_SET 1265 */ 1266 protected static final int[] ENABLED_SELECTED_STATE_SET; 1267 /** 1268 * Indicates the view is enabled and that its window has focus. 1269 * 1270 * @see #ENABLED_STATE_SET 1271 * @see #WINDOW_FOCUSED_STATE_SET 1272 */ 1273 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1274 /** 1275 * Indicates the view is focused and selected. 1276 * 1277 * @see #FOCUSED_STATE_SET 1278 * @see #SELECTED_STATE_SET 1279 */ 1280 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1281 /** 1282 * Indicates the view has the focus and that its window has the focus. 1283 * 1284 * @see #FOCUSED_STATE_SET 1285 * @see #WINDOW_FOCUSED_STATE_SET 1286 */ 1287 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1288 /** 1289 * Indicates the view is selected and that its window has the focus. 1290 * 1291 * @see #SELECTED_STATE_SET 1292 * @see #WINDOW_FOCUSED_STATE_SET 1293 */ 1294 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1295 // Triples 1296 /** 1297 * Indicates the view is enabled, focused and selected. 1298 * 1299 * @see #ENABLED_STATE_SET 1300 * @see #FOCUSED_STATE_SET 1301 * @see #SELECTED_STATE_SET 1302 */ 1303 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1304 /** 1305 * Indicates the view is enabled, focused and its window has the focus. 1306 * 1307 * @see #ENABLED_STATE_SET 1308 * @see #FOCUSED_STATE_SET 1309 * @see #WINDOW_FOCUSED_STATE_SET 1310 */ 1311 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1312 /** 1313 * Indicates the view is enabled, selected and its window has the focus. 1314 * 1315 * @see #ENABLED_STATE_SET 1316 * @see #SELECTED_STATE_SET 1317 * @see #WINDOW_FOCUSED_STATE_SET 1318 */ 1319 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1320 /** 1321 * Indicates the view is focused, selected and its window has the focus. 1322 * 1323 * @see #FOCUSED_STATE_SET 1324 * @see #SELECTED_STATE_SET 1325 * @see #WINDOW_FOCUSED_STATE_SET 1326 */ 1327 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1328 /** 1329 * Indicates the view is enabled, focused, selected and its window 1330 * has the focus. 1331 * 1332 * @see #ENABLED_STATE_SET 1333 * @see #FOCUSED_STATE_SET 1334 * @see #SELECTED_STATE_SET 1335 * @see #WINDOW_FOCUSED_STATE_SET 1336 */ 1337 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1338 /** 1339 * Indicates the view is pressed and its window has the focus. 1340 * 1341 * @see #PRESSED_STATE_SET 1342 * @see #WINDOW_FOCUSED_STATE_SET 1343 */ 1344 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1345 /** 1346 * Indicates the view is pressed and selected. 1347 * 1348 * @see #PRESSED_STATE_SET 1349 * @see #SELECTED_STATE_SET 1350 */ 1351 protected static final int[] PRESSED_SELECTED_STATE_SET; 1352 /** 1353 * Indicates the view is pressed, selected and its window has the focus. 1354 * 1355 * @see #PRESSED_STATE_SET 1356 * @see #SELECTED_STATE_SET 1357 * @see #WINDOW_FOCUSED_STATE_SET 1358 */ 1359 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1360 /** 1361 * Indicates the view is pressed and focused. 1362 * 1363 * @see #PRESSED_STATE_SET 1364 * @see #FOCUSED_STATE_SET 1365 */ 1366 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1367 /** 1368 * Indicates the view is pressed, focused and its window has the focus. 1369 * 1370 * @see #PRESSED_STATE_SET 1371 * @see #FOCUSED_STATE_SET 1372 * @see #WINDOW_FOCUSED_STATE_SET 1373 */ 1374 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1375 /** 1376 * Indicates the view is pressed, focused and selected. 1377 * 1378 * @see #PRESSED_STATE_SET 1379 * @see #SELECTED_STATE_SET 1380 * @see #FOCUSED_STATE_SET 1381 */ 1382 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1383 /** 1384 * Indicates the view is pressed, focused, selected and its window has the focus. 1385 * 1386 * @see #PRESSED_STATE_SET 1387 * @see #FOCUSED_STATE_SET 1388 * @see #SELECTED_STATE_SET 1389 * @see #WINDOW_FOCUSED_STATE_SET 1390 */ 1391 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1392 /** 1393 * Indicates the view is pressed and enabled. 1394 * 1395 * @see #PRESSED_STATE_SET 1396 * @see #ENABLED_STATE_SET 1397 */ 1398 protected static final int[] PRESSED_ENABLED_STATE_SET; 1399 /** 1400 * Indicates the view is pressed, enabled and its window has the focus. 1401 * 1402 * @see #PRESSED_STATE_SET 1403 * @see #ENABLED_STATE_SET 1404 * @see #WINDOW_FOCUSED_STATE_SET 1405 */ 1406 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1407 /** 1408 * Indicates the view is pressed, enabled and selected. 1409 * 1410 * @see #PRESSED_STATE_SET 1411 * @see #ENABLED_STATE_SET 1412 * @see #SELECTED_STATE_SET 1413 */ 1414 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1415 /** 1416 * Indicates the view is pressed, enabled, selected and its window has the 1417 * focus. 1418 * 1419 * @see #PRESSED_STATE_SET 1420 * @see #ENABLED_STATE_SET 1421 * @see #SELECTED_STATE_SET 1422 * @see #WINDOW_FOCUSED_STATE_SET 1423 */ 1424 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1425 /** 1426 * Indicates the view is pressed, enabled and focused. 1427 * 1428 * @see #PRESSED_STATE_SET 1429 * @see #ENABLED_STATE_SET 1430 * @see #FOCUSED_STATE_SET 1431 */ 1432 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1433 /** 1434 * Indicates the view is pressed, enabled, focused and its window has the 1435 * focus. 1436 * 1437 * @see #PRESSED_STATE_SET 1438 * @see #ENABLED_STATE_SET 1439 * @see #FOCUSED_STATE_SET 1440 * @see #WINDOW_FOCUSED_STATE_SET 1441 */ 1442 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1443 /** 1444 * Indicates the view is pressed, enabled, focused and selected. 1445 * 1446 * @see #PRESSED_STATE_SET 1447 * @see #ENABLED_STATE_SET 1448 * @see #SELECTED_STATE_SET 1449 * @see #FOCUSED_STATE_SET 1450 */ 1451 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1452 /** 1453 * Indicates the view is pressed, enabled, focused, selected and its window 1454 * has the focus. 1455 * 1456 * @see #PRESSED_STATE_SET 1457 * @see #ENABLED_STATE_SET 1458 * @see #SELECTED_STATE_SET 1459 * @see #FOCUSED_STATE_SET 1460 * @see #WINDOW_FOCUSED_STATE_SET 1461 */ 1462 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1463 1464 static { 1465 EMPTY_STATE_SET = StateSet.get(0); 1466 1467 WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED); 1468 1469 SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED); 1470 SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1471 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED); 1472 1473 FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED); 1474 FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1475 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED); 1476 FOCUSED_SELECTED_STATE_SET = StateSet.get( 1477 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED); 1478 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1479 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1480 | StateSet.VIEW_STATE_FOCUSED); 1481 1482 ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED); 1483 ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1484 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1485 ENABLED_SELECTED_STATE_SET = StateSet.get( 1486 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED); 1487 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1488 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1489 | StateSet.VIEW_STATE_ENABLED); 1490 ENABLED_FOCUSED_STATE_SET = StateSet.get( 1491 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1492 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1493 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1494 | StateSet.VIEW_STATE_ENABLED); 1495 ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1496 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1497 | StateSet.VIEW_STATE_ENABLED); 1498 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1499 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1500 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED); 1501 1502 PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED); 1503 PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1504 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1505 PRESSED_SELECTED_STATE_SET = StateSet.get( 1506 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED); 1507 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1508 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1509 | StateSet.VIEW_STATE_PRESSED); 1510 PRESSED_FOCUSED_STATE_SET = StateSet.get( 1511 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1512 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1513 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1514 | StateSet.VIEW_STATE_PRESSED); 1515 PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1516 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1517 | StateSet.VIEW_STATE_PRESSED); 1518 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1519 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1520 | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1521 PRESSED_ENABLED_STATE_SET = StateSet.get( 1522 StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1523 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1524 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED 1525 | StateSet.VIEW_STATE_PRESSED); 1526 PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get( 1527 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED 1528 | StateSet.VIEW_STATE_PRESSED); 1529 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1530 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1531 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1532 PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get( 1533 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED 1534 | StateSet.VIEW_STATE_PRESSED); 1535 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1536 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1537 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1538 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1539 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1540 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1541 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1542 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1543 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED 1544 | StateSet.VIEW_STATE_PRESSED); 1545 } 1546 1547 /** 1548 * Accessibility event types that are dispatched for text population. 1549 */ 1550 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1551 AccessibilityEvent.TYPE_VIEW_CLICKED 1552 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1553 | AccessibilityEvent.TYPE_VIEW_SELECTED 1554 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1555 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1556 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1557 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1558 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1559 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1560 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1561 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1562 1563 /** 1564 * Temporary Rect currently for use in setBackground(). This will probably 1565 * be extended in the future to hold our own class with more than just 1566 * a Rect. :) 1567 */ 1568 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1569 1570 /** 1571 * Map used to store views' tags. 1572 */ 1573 private SparseArray<Object> mKeyedTags; 1574 1575 /** 1576 * The next available accessibility id. 1577 */ 1578 private static int sNextAccessibilityViewId; 1579 1580 /** 1581 * The animation currently associated with this view. 1582 * @hide 1583 */ 1584 protected Animation mCurrentAnimation = null; 1585 1586 /** 1587 * Width as measured during measure pass. 1588 * {@hide} 1589 */ 1590 @ViewDebug.ExportedProperty(category = "measurement") 1591 int mMeasuredWidth; 1592 1593 /** 1594 * Height as measured during measure pass. 1595 * {@hide} 1596 */ 1597 @ViewDebug.ExportedProperty(category = "measurement") 1598 int mMeasuredHeight; 1599 1600 /** 1601 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1602 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1603 * its display list. This flag, used only when hw accelerated, allows us to clear the 1604 * flag while retaining this information until it's needed (at getDisplayList() time and 1605 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1606 * 1607 * {@hide} 1608 */ 1609 boolean mRecreateDisplayList = false; 1610 1611 /** 1612 * The view's identifier. 1613 * {@hide} 1614 * 1615 * @see #setId(int) 1616 * @see #getId() 1617 */ 1618 @IdRes 1619 @ViewDebug.ExportedProperty(resolveId = true) 1620 int mID = NO_ID; 1621 1622 /** 1623 * The stable ID of this view for accessibility purposes. 1624 */ 1625 int mAccessibilityViewId = NO_ID; 1626 1627 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1628 1629 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1630 1631 /** 1632 * The view's tag. 1633 * {@hide} 1634 * 1635 * @see #setTag(Object) 1636 * @see #getTag() 1637 */ 1638 protected Object mTag = null; 1639 1640 // for mPrivateFlags: 1641 /** {@hide} */ 1642 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1643 /** {@hide} */ 1644 static final int PFLAG_FOCUSED = 0x00000002; 1645 /** {@hide} */ 1646 static final int PFLAG_SELECTED = 0x00000004; 1647 /** {@hide} */ 1648 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1649 /** {@hide} */ 1650 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1651 /** {@hide} */ 1652 static final int PFLAG_DRAWN = 0x00000020; 1653 /** 1654 * When this flag is set, this view is running an animation on behalf of its 1655 * children and should therefore not cancel invalidate requests, even if they 1656 * lie outside of this view's bounds. 1657 * 1658 * {@hide} 1659 */ 1660 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1661 /** {@hide} */ 1662 static final int PFLAG_SKIP_DRAW = 0x00000080; 1663 /** {@hide} */ 1664 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1665 /** {@hide} */ 1666 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1667 /** {@hide} */ 1668 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1669 /** {@hide} */ 1670 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1671 /** {@hide} */ 1672 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1673 /** {@hide} */ 1674 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1675 1676 private static final int PFLAG_PRESSED = 0x00004000; 1677 1678 /** {@hide} */ 1679 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1680 /** 1681 * Flag used to indicate that this view should be drawn once more (and only once 1682 * more) after its animation has completed. 1683 * {@hide} 1684 */ 1685 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1686 1687 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1688 1689 /** 1690 * Indicates that the View returned true when onSetAlpha() was called and that 1691 * the alpha must be restored. 1692 * {@hide} 1693 */ 1694 static final int PFLAG_ALPHA_SET = 0x00040000; 1695 1696 /** 1697 * Set by {@link #setScrollContainer(boolean)}. 1698 */ 1699 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1700 1701 /** 1702 * Set by {@link #setScrollContainer(boolean)}. 1703 */ 1704 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1705 1706 /** 1707 * View flag indicating whether this view was invalidated (fully or partially.) 1708 * 1709 * @hide 1710 */ 1711 static final int PFLAG_DIRTY = 0x00200000; 1712 1713 /** 1714 * View flag indicating whether this view was invalidated by an opaque 1715 * invalidate request. 1716 * 1717 * @hide 1718 */ 1719 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1720 1721 /** 1722 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1723 * 1724 * @hide 1725 */ 1726 static final int PFLAG_DIRTY_MASK = 0x00600000; 1727 1728 /** 1729 * Indicates whether the background is opaque. 1730 * 1731 * @hide 1732 */ 1733 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1734 1735 /** 1736 * Indicates whether the scrollbars are opaque. 1737 * 1738 * @hide 1739 */ 1740 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1741 1742 /** 1743 * Indicates whether the view is opaque. 1744 * 1745 * @hide 1746 */ 1747 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1748 1749 /** 1750 * Indicates a prepressed state; 1751 * the short time between ACTION_DOWN and recognizing 1752 * a 'real' press. Prepressed is used to recognize quick taps 1753 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1754 * 1755 * @hide 1756 */ 1757 private static final int PFLAG_PREPRESSED = 0x02000000; 1758 1759 /** 1760 * Indicates whether the view is temporarily detached. 1761 * 1762 * @hide 1763 */ 1764 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1765 1766 /** 1767 * Indicates that we should awaken scroll bars once attached 1768 * 1769 * @hide 1770 */ 1771 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1772 1773 /** 1774 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1775 * @hide 1776 */ 1777 private static final int PFLAG_HOVERED = 0x10000000; 1778 1779 /** 1780 * no longer needed, should be reused 1781 */ 1782 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1783 1784 /** {@hide} */ 1785 static final int PFLAG_ACTIVATED = 0x40000000; 1786 1787 /** 1788 * Indicates that this view was specifically invalidated, not just dirtied because some 1789 * child view was invalidated. The flag is used to determine when we need to recreate 1790 * a view's display list (as opposed to just returning a reference to its existing 1791 * display list). 1792 * 1793 * @hide 1794 */ 1795 static final int PFLAG_INVALIDATED = 0x80000000; 1796 1797 /** 1798 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1799 * 1800 * |-------|-------|-------|-------| 1801 * 1 PFLAG2_DRAG_CAN_ACCEPT 1802 * 1 PFLAG2_DRAG_HOVERED 1803 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1804 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1805 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1806 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1807 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1808 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1809 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1810 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1811 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1812 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[6] 1813 * 111 PFLAG2_TEXT_DIRECTION_FLAGS[7] 1814 * 111 PFLAG2_TEXT_DIRECTION_MASK 1815 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1816 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1817 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1818 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1819 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1820 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1821 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1822 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1823 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1824 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1825 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1826 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1827 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1828 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1829 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1830 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1831 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1832 * 1 PFLAG2_VIEW_QUICK_REJECTED 1833 * 1 PFLAG2_PADDING_RESOLVED 1834 * 1 PFLAG2_DRAWABLE_RESOLVED 1835 * 1 PFLAG2_HAS_TRANSIENT_STATE 1836 * |-------|-------|-------|-------| 1837 */ 1838 1839 /** 1840 * Indicates that this view has reported that it can accept the current drag's content. 1841 * Cleared when the drag operation concludes. 1842 * @hide 1843 */ 1844 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1845 1846 /** 1847 * Indicates that this view is currently directly under the drag location in a 1848 * drag-and-drop operation involving content that it can accept. Cleared when 1849 * the drag exits the view, or when the drag operation concludes. 1850 * @hide 1851 */ 1852 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1853 1854 /** @hide */ 1855 @IntDef({ 1856 LAYOUT_DIRECTION_LTR, 1857 LAYOUT_DIRECTION_RTL, 1858 LAYOUT_DIRECTION_INHERIT, 1859 LAYOUT_DIRECTION_LOCALE 1860 }) 1861 @Retention(RetentionPolicy.SOURCE) 1862 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1863 public @interface LayoutDir {} 1864 1865 /** @hide */ 1866 @IntDef({ 1867 LAYOUT_DIRECTION_LTR, 1868 LAYOUT_DIRECTION_RTL 1869 }) 1870 @Retention(RetentionPolicy.SOURCE) 1871 public @interface ResolvedLayoutDir {} 1872 1873 /** 1874 * Horizontal layout direction of this view is from Left to Right. 1875 * Use with {@link #setLayoutDirection}. 1876 */ 1877 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1878 1879 /** 1880 * Horizontal layout direction of this view is from Right to Left. 1881 * Use with {@link #setLayoutDirection}. 1882 */ 1883 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1884 1885 /** 1886 * Horizontal layout direction of this view is inherited from its parent. 1887 * Use with {@link #setLayoutDirection}. 1888 */ 1889 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1890 1891 /** 1892 * Horizontal layout direction of this view is from deduced from the default language 1893 * script for the locale. Use with {@link #setLayoutDirection}. 1894 */ 1895 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1896 1897 /** 1898 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1899 * @hide 1900 */ 1901 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1902 1903 /** 1904 * Mask for use with private flags indicating bits used for horizontal layout direction. 1905 * @hide 1906 */ 1907 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1908 1909 /** 1910 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1911 * right-to-left direction. 1912 * @hide 1913 */ 1914 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1915 1916 /** 1917 * Indicates whether the view horizontal layout direction has been resolved. 1918 * @hide 1919 */ 1920 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1921 1922 /** 1923 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1924 * @hide 1925 */ 1926 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1927 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1928 1929 /* 1930 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1931 * flag value. 1932 * @hide 1933 */ 1934 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1935 LAYOUT_DIRECTION_LTR, 1936 LAYOUT_DIRECTION_RTL, 1937 LAYOUT_DIRECTION_INHERIT, 1938 LAYOUT_DIRECTION_LOCALE 1939 }; 1940 1941 /** 1942 * Default horizontal layout direction. 1943 */ 1944 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1945 1946 /** 1947 * Default horizontal layout direction. 1948 * @hide 1949 */ 1950 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1951 1952 /** 1953 * Text direction is inherited through {@link ViewGroup} 1954 */ 1955 public static final int TEXT_DIRECTION_INHERIT = 0; 1956 1957 /** 1958 * Text direction is using "first strong algorithm". The first strong directional character 1959 * determines the paragraph direction. If there is no strong directional character, the 1960 * paragraph direction is the view's resolved layout direction. 1961 */ 1962 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1963 1964 /** 1965 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1966 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1967 * If there are neither, the paragraph direction is the view's resolved layout direction. 1968 */ 1969 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1970 1971 /** 1972 * Text direction is forced to LTR. 1973 */ 1974 public static final int TEXT_DIRECTION_LTR = 3; 1975 1976 /** 1977 * Text direction is forced to RTL. 1978 */ 1979 public static final int TEXT_DIRECTION_RTL = 4; 1980 1981 /** 1982 * Text direction is coming from the system Locale. 1983 */ 1984 public static final int TEXT_DIRECTION_LOCALE = 5; 1985 1986 /** 1987 * Text direction is using "first strong algorithm". The first strong directional character 1988 * determines the paragraph direction. If there is no strong directional character, the 1989 * paragraph direction is LTR. 1990 */ 1991 public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6; 1992 1993 /** 1994 * Text direction is using "first strong algorithm". The first strong directional character 1995 * determines the paragraph direction. If there is no strong directional character, the 1996 * paragraph direction is RTL. 1997 */ 1998 public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7; 1999 2000 /** 2001 * Default text direction is inherited 2002 */ 2003 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2004 2005 /** 2006 * Default resolved text direction 2007 * @hide 2008 */ 2009 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2010 2011 /** 2012 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2013 * @hide 2014 */ 2015 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2016 2017 /** 2018 * Mask for use with private flags indicating bits used for text direction. 2019 * @hide 2020 */ 2021 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2022 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2023 2024 /** 2025 * Array of text direction flags for mapping attribute "textDirection" to correct 2026 * flag value. 2027 * @hide 2028 */ 2029 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2030 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2031 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2032 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2033 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2034 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2035 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2036 TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2037 TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2038 }; 2039 2040 /** 2041 * Indicates whether the view text direction has been resolved. 2042 * @hide 2043 */ 2044 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2045 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2046 2047 /** 2048 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2049 * @hide 2050 */ 2051 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2052 2053 /** 2054 * Mask for use with private flags indicating bits used for resolved text direction. 2055 * @hide 2056 */ 2057 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2058 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2059 2060 /** 2061 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2062 * @hide 2063 */ 2064 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2065 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2066 2067 /** @hide */ 2068 @IntDef({ 2069 TEXT_ALIGNMENT_INHERIT, 2070 TEXT_ALIGNMENT_GRAVITY, 2071 TEXT_ALIGNMENT_CENTER, 2072 TEXT_ALIGNMENT_TEXT_START, 2073 TEXT_ALIGNMENT_TEXT_END, 2074 TEXT_ALIGNMENT_VIEW_START, 2075 TEXT_ALIGNMENT_VIEW_END 2076 }) 2077 @Retention(RetentionPolicy.SOURCE) 2078 public @interface TextAlignment {} 2079 2080 /** 2081 * Default text alignment. The text alignment of this View is inherited from its parent. 2082 * Use with {@link #setTextAlignment(int)} 2083 */ 2084 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2085 2086 /** 2087 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2088 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2089 * 2090 * Use with {@link #setTextAlignment(int)} 2091 */ 2092 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2093 2094 /** 2095 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2096 * 2097 * Use with {@link #setTextAlignment(int)} 2098 */ 2099 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2100 2101 /** 2102 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2103 * 2104 * Use with {@link #setTextAlignment(int)} 2105 */ 2106 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2107 2108 /** 2109 * Center the paragraph, e.g. ALIGN_CENTER. 2110 * 2111 * Use with {@link #setTextAlignment(int)} 2112 */ 2113 public static final int TEXT_ALIGNMENT_CENTER = 4; 2114 2115 /** 2116 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2117 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2118 * 2119 * Use with {@link #setTextAlignment(int)} 2120 */ 2121 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2122 2123 /** 2124 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2125 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2126 * 2127 * Use with {@link #setTextAlignment(int)} 2128 */ 2129 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2130 2131 /** 2132 * Default text alignment is inherited 2133 */ 2134 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2135 2136 /** 2137 * Default resolved text alignment 2138 * @hide 2139 */ 2140 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2141 2142 /** 2143 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2144 * @hide 2145 */ 2146 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2147 2148 /** 2149 * Mask for use with private flags indicating bits used for text alignment. 2150 * @hide 2151 */ 2152 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2153 2154 /** 2155 * Array of text direction flags for mapping attribute "textAlignment" to correct 2156 * flag value. 2157 * @hide 2158 */ 2159 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2160 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2161 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2162 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2163 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2164 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2165 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2166 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2167 }; 2168 2169 /** 2170 * Indicates whether the view text alignment has been resolved. 2171 * @hide 2172 */ 2173 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2174 2175 /** 2176 * Bit shift to get the resolved text alignment. 2177 * @hide 2178 */ 2179 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2180 2181 /** 2182 * Mask for use with private flags indicating bits used for text alignment. 2183 * @hide 2184 */ 2185 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2186 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2187 2188 /** 2189 * Indicates whether if the view text alignment has been resolved to gravity 2190 */ 2191 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2192 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2193 2194 // Accessiblity constants for mPrivateFlags2 2195 2196 /** 2197 * Shift for the bits in {@link #mPrivateFlags2} related to the 2198 * "importantForAccessibility" attribute. 2199 */ 2200 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2201 2202 /** 2203 * Automatically determine whether a view is important for accessibility. 2204 */ 2205 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2206 2207 /** 2208 * The view is important for accessibility. 2209 */ 2210 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2211 2212 /** 2213 * The view is not important for accessibility. 2214 */ 2215 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2216 2217 /** 2218 * The view is not important for accessibility, nor are any of its 2219 * descendant views. 2220 */ 2221 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2222 2223 /** 2224 * The default whether the view is important for accessibility. 2225 */ 2226 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2227 2228 /** 2229 * Mask for obtainig the bits which specify how to determine 2230 * whether a view is important for accessibility. 2231 */ 2232 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2233 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2234 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2235 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2236 2237 /** 2238 * Shift for the bits in {@link #mPrivateFlags2} related to the 2239 * "accessibilityLiveRegion" attribute. 2240 */ 2241 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2242 2243 /** 2244 * Live region mode specifying that accessibility services should not 2245 * automatically announce changes to this view. This is the default live 2246 * region mode for most views. 2247 * <p> 2248 * Use with {@link #setAccessibilityLiveRegion(int)}. 2249 */ 2250 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2251 2252 /** 2253 * Live region mode specifying that accessibility services should announce 2254 * changes to this view. 2255 * <p> 2256 * Use with {@link #setAccessibilityLiveRegion(int)}. 2257 */ 2258 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2259 2260 /** 2261 * Live region mode specifying that accessibility services should interrupt 2262 * ongoing speech to immediately announce changes to this view. 2263 * <p> 2264 * Use with {@link #setAccessibilityLiveRegion(int)}. 2265 */ 2266 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2267 2268 /** 2269 * The default whether the view is important for accessibility. 2270 */ 2271 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2272 2273 /** 2274 * Mask for obtaining the bits which specify a view's accessibility live 2275 * region mode. 2276 */ 2277 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2278 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2279 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2280 2281 /** 2282 * Flag indicating whether a view has accessibility focus. 2283 */ 2284 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2285 2286 /** 2287 * Flag whether the accessibility state of the subtree rooted at this view changed. 2288 */ 2289 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2290 2291 /** 2292 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2293 * is used to check whether later changes to the view's transform should invalidate the 2294 * view to force the quickReject test to run again. 2295 */ 2296 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2297 2298 /** 2299 * Flag indicating that start/end padding has been resolved into left/right padding 2300 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2301 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2302 * during measurement. In some special cases this is required such as when an adapter-based 2303 * view measures prospective children without attaching them to a window. 2304 */ 2305 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2306 2307 /** 2308 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2309 */ 2310 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2311 2312 /** 2313 * Indicates that the view is tracking some sort of transient state 2314 * that the app should not need to be aware of, but that the framework 2315 * should take special care to preserve. 2316 */ 2317 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2318 2319 /** 2320 * Group of bits indicating that RTL properties resolution is done. 2321 */ 2322 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2323 PFLAG2_TEXT_DIRECTION_RESOLVED | 2324 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2325 PFLAG2_PADDING_RESOLVED | 2326 PFLAG2_DRAWABLE_RESOLVED; 2327 2328 // There are a couple of flags left in mPrivateFlags2 2329 2330 /* End of masks for mPrivateFlags2 */ 2331 2332 /** 2333 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2334 * 2335 * |-------|-------|-------|-------| 2336 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2337 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2338 * 1 PFLAG3_IS_LAID_OUT 2339 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2340 * 1 PFLAG3_CALLED_SUPER 2341 * 1 PFLAG3_APPLYING_INSETS 2342 * 1 PFLAG3_FITTING_SYSTEM_WINDOWS 2343 * 1 PFLAG3_NESTED_SCROLLING_ENABLED 2344 * 1 PFLAG3_ASSIST_BLOCKED 2345 * |-------|-------|-------|-------| 2346 */ 2347 2348 /** 2349 * Flag indicating that view has a transform animation set on it. This is used to track whether 2350 * an animation is cleared between successive frames, in order to tell the associated 2351 * DisplayList to clear its animation matrix. 2352 */ 2353 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2354 2355 /** 2356 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2357 * animation is cleared between successive frames, in order to tell the associated 2358 * DisplayList to restore its alpha value. 2359 */ 2360 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2361 2362 /** 2363 * Flag indicating that the view has been through at least one layout since it 2364 * was last attached to a window. 2365 */ 2366 static final int PFLAG3_IS_LAID_OUT = 0x4; 2367 2368 /** 2369 * Flag indicating that a call to measure() was skipped and should be done 2370 * instead when layout() is invoked. 2371 */ 2372 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2373 2374 /** 2375 * Flag indicating that an overridden method correctly called down to 2376 * the superclass implementation as required by the API spec. 2377 */ 2378 static final int PFLAG3_CALLED_SUPER = 0x10; 2379 2380 /** 2381 * Flag indicating that we're in the process of applying window insets. 2382 */ 2383 static final int PFLAG3_APPLYING_INSETS = 0x20; 2384 2385 /** 2386 * Flag indicating that we're in the process of fitting system windows using the old method. 2387 */ 2388 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2389 2390 /** 2391 * Flag indicating that nested scrolling is enabled for this view. 2392 * The view will optionally cooperate with views up its parent chain to allow for 2393 * integrated nested scrolling along the same axis. 2394 */ 2395 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2396 2397 /** 2398 * Flag indicating that the bottom scroll indicator should be displayed 2399 * when this view can scroll up. 2400 */ 2401 static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100; 2402 2403 /** 2404 * Flag indicating that the bottom scroll indicator should be displayed 2405 * when this view can scroll down. 2406 */ 2407 static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200; 2408 2409 /** 2410 * Flag indicating that the left scroll indicator should be displayed 2411 * when this view can scroll left. 2412 */ 2413 static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400; 2414 2415 /** 2416 * Flag indicating that the right scroll indicator should be displayed 2417 * when this view can scroll right. 2418 */ 2419 static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800; 2420 2421 /** 2422 * Flag indicating that the start scroll indicator should be displayed 2423 * when this view can scroll in the start direction. 2424 */ 2425 static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000; 2426 2427 /** 2428 * Flag indicating that the end scroll indicator should be displayed 2429 * when this view can scroll in the end direction. 2430 */ 2431 static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000; 2432 2433 /* End of masks for mPrivateFlags3 */ 2434 2435 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2436 2437 static final int SCROLL_INDICATORS_NONE = 0x0000; 2438 2439 /** 2440 * Mask for use with setFlags indicating bits used for indicating which 2441 * scroll indicators are enabled. 2442 */ 2443 static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP 2444 | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT 2445 | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START 2446 | PFLAG3_SCROLL_INDICATOR_END; 2447 2448 /** 2449 * Left-shift required to translate between public scroll indicator flags 2450 * and internal PFLAGS3 flags. When used as a right-shift, translates 2451 * PFLAGS3 flags to public flags. 2452 */ 2453 static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8; 2454 2455 /** @hide */ 2456 @Retention(RetentionPolicy.SOURCE) 2457 @IntDef(flag = true, 2458 value = { 2459 SCROLL_INDICATOR_TOP, 2460 SCROLL_INDICATOR_BOTTOM, 2461 SCROLL_INDICATOR_LEFT, 2462 SCROLL_INDICATOR_RIGHT, 2463 SCROLL_INDICATOR_START, 2464 SCROLL_INDICATOR_END, 2465 }) 2466 public @interface ScrollIndicators {} 2467 2468 /** 2469 * Scroll indicator direction for the top edge of the view. 2470 * 2471 * @see #setScrollIndicators(int) 2472 * @see #setScrollIndicators(int, int) 2473 * @see #getScrollIndicators() 2474 */ 2475 public static final int SCROLL_INDICATOR_TOP = 2476 PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2477 2478 /** 2479 * Scroll indicator direction for the bottom edge of the view. 2480 * 2481 * @see #setScrollIndicators(int) 2482 * @see #setScrollIndicators(int, int) 2483 * @see #getScrollIndicators() 2484 */ 2485 public static final int SCROLL_INDICATOR_BOTTOM = 2486 PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2487 2488 /** 2489 * Scroll indicator direction for the left edge of the view. 2490 * 2491 * @see #setScrollIndicators(int) 2492 * @see #setScrollIndicators(int, int) 2493 * @see #getScrollIndicators() 2494 */ 2495 public static final int SCROLL_INDICATOR_LEFT = 2496 PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2497 2498 /** 2499 * Scroll indicator direction for the right edge of the view. 2500 * 2501 * @see #setScrollIndicators(int) 2502 * @see #setScrollIndicators(int, int) 2503 * @see #getScrollIndicators() 2504 */ 2505 public static final int SCROLL_INDICATOR_RIGHT = 2506 PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2507 2508 /** 2509 * Scroll indicator direction for the starting edge of the view. 2510 * <p> 2511 * Resolved according to the view's layout direction, see 2512 * {@link #getLayoutDirection()} for more information. 2513 * 2514 * @see #setScrollIndicators(int) 2515 * @see #setScrollIndicators(int, int) 2516 * @see #getScrollIndicators() 2517 */ 2518 public static final int SCROLL_INDICATOR_START = 2519 PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2520 2521 /** 2522 * Scroll indicator direction for the ending edge of the view. 2523 * <p> 2524 * Resolved according to the view's layout direction, see 2525 * {@link #getLayoutDirection()} for more information. 2526 * 2527 * @see #setScrollIndicators(int) 2528 * @see #setScrollIndicators(int, int) 2529 * @see #getScrollIndicators() 2530 */ 2531 public static final int SCROLL_INDICATOR_END = 2532 PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2533 2534 /** 2535 * <p>Indicates that we are allowing {@link ViewStructure} to traverse 2536 * into this view.<p> 2537 */ 2538 static final int PFLAG3_ASSIST_BLOCKED = 0x100; 2539 2540 /** 2541 * Always allow a user to over-scroll this view, provided it is a 2542 * view that can scroll. 2543 * 2544 * @see #getOverScrollMode() 2545 * @see #setOverScrollMode(int) 2546 */ 2547 public static final int OVER_SCROLL_ALWAYS = 0; 2548 2549 /** 2550 * Allow a user to over-scroll this view only if the content is large 2551 * enough to meaningfully scroll, provided it is a view that can scroll. 2552 * 2553 * @see #getOverScrollMode() 2554 * @see #setOverScrollMode(int) 2555 */ 2556 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2557 2558 /** 2559 * Never allow a user to over-scroll this view. 2560 * 2561 * @see #getOverScrollMode() 2562 * @see #setOverScrollMode(int) 2563 */ 2564 public static final int OVER_SCROLL_NEVER = 2; 2565 2566 /** 2567 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2568 * requested the system UI (status bar) to be visible (the default). 2569 * 2570 * @see #setSystemUiVisibility(int) 2571 */ 2572 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2573 2574 /** 2575 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2576 * system UI to enter an unobtrusive "low profile" mode. 2577 * 2578 * <p>This is for use in games, book readers, video players, or any other 2579 * "immersive" application where the usual system chrome is deemed too distracting. 2580 * 2581 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2582 * 2583 * @see #setSystemUiVisibility(int) 2584 */ 2585 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2586 2587 /** 2588 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2589 * system navigation be temporarily hidden. 2590 * 2591 * <p>This is an even less obtrusive state than that called for by 2592 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2593 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2594 * those to disappear. This is useful (in conjunction with the 2595 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2596 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2597 * window flags) for displaying content using every last pixel on the display. 2598 * 2599 * <p>There is a limitation: because navigation controls are so important, the least user 2600 * interaction will cause them to reappear immediately. When this happens, both 2601 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2602 * so that both elements reappear at the same time. 2603 * 2604 * @see #setSystemUiVisibility(int) 2605 */ 2606 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2607 2608 /** 2609 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2610 * into the normal fullscreen mode so that its content can take over the screen 2611 * while still allowing the user to interact with the application. 2612 * 2613 * <p>This has the same visual effect as 2614 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2615 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2616 * meaning that non-critical screen decorations (such as the status bar) will be 2617 * hidden while the user is in the View's window, focusing the experience on 2618 * that content. Unlike the window flag, if you are using ActionBar in 2619 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2620 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2621 * hide the action bar. 2622 * 2623 * <p>This approach to going fullscreen is best used over the window flag when 2624 * it is a transient state -- that is, the application does this at certain 2625 * points in its user interaction where it wants to allow the user to focus 2626 * on content, but not as a continuous state. For situations where the application 2627 * would like to simply stay full screen the entire time (such as a game that 2628 * wants to take over the screen), the 2629 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2630 * is usually a better approach. The state set here will be removed by the system 2631 * in various situations (such as the user moving to another application) like 2632 * the other system UI states. 2633 * 2634 * <p>When using this flag, the application should provide some easy facility 2635 * for the user to go out of it. A common example would be in an e-book 2636 * reader, where tapping on the screen brings back whatever screen and UI 2637 * decorations that had been hidden while the user was immersed in reading 2638 * the book. 2639 * 2640 * @see #setSystemUiVisibility(int) 2641 */ 2642 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2643 2644 /** 2645 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2646 * flags, we would like a stable view of the content insets given to 2647 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2648 * will always represent the worst case that the application can expect 2649 * as a continuous state. In the stock Android UI this is the space for 2650 * the system bar, nav bar, and status bar, but not more transient elements 2651 * such as an input method. 2652 * 2653 * The stable layout your UI sees is based on the system UI modes you can 2654 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2655 * then you will get a stable layout for changes of the 2656 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2657 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2658 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2659 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2660 * with a stable layout. (Note that you should avoid using 2661 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2662 * 2663 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2664 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2665 * then a hidden status bar will be considered a "stable" state for purposes 2666 * here. This allows your UI to continually hide the status bar, while still 2667 * using the system UI flags to hide the action bar while still retaining 2668 * a stable layout. Note that changing the window fullscreen flag will never 2669 * provide a stable layout for a clean transition. 2670 * 2671 * <p>If you are using ActionBar in 2672 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2673 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2674 * insets it adds to those given to the application. 2675 */ 2676 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2677 2678 /** 2679 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2680 * to be laid out as if it has requested 2681 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2682 * allows it to avoid artifacts when switching in and out of that mode, at 2683 * the expense that some of its user interface may be covered by screen 2684 * decorations when they are shown. You can perform layout of your inner 2685 * UI elements to account for the navigation system UI through the 2686 * {@link #fitSystemWindows(Rect)} method. 2687 */ 2688 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2689 2690 /** 2691 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2692 * to be laid out as if it has requested 2693 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2694 * allows it to avoid artifacts when switching in and out of that mode, at 2695 * the expense that some of its user interface may be covered by screen 2696 * decorations when they are shown. You can perform layout of your inner 2697 * UI elements to account for non-fullscreen system UI through the 2698 * {@link #fitSystemWindows(Rect)} method. 2699 */ 2700 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2701 2702 /** 2703 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2704 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2705 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2706 * user interaction. 2707 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2708 * has an effect when used in combination with that flag.</p> 2709 */ 2710 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2711 2712 /** 2713 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2714 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2715 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2716 * experience while also hiding the system bars. If this flag is not set, 2717 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2718 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2719 * if the user swipes from the top of the screen. 2720 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2721 * system gestures, such as swiping from the top of the screen. These transient system bars 2722 * will overlay app’s content, may have some degree of transparency, and will automatically 2723 * hide after a short timeout. 2724 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2725 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2726 * with one or both of those flags.</p> 2727 */ 2728 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2729 2730 /** 2731 * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that 2732 * is compatible with light status bar backgrounds. 2733 * 2734 * <p>For this to take effect, the window must request 2735 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 2736 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not 2737 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS 2738 * FLAG_TRANSLUCENT_STATUS}. 2739 * 2740 * @see android.R.attr#windowLightStatusBar 2741 */ 2742 public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000; 2743 2744 /** 2745 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2746 */ 2747 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2748 2749 /** 2750 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2751 */ 2752 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2753 2754 /** 2755 * @hide 2756 * 2757 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2758 * out of the public fields to keep the undefined bits out of the developer's way. 2759 * 2760 * Flag to make the status bar not expandable. Unless you also 2761 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2762 */ 2763 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2764 2765 /** 2766 * @hide 2767 * 2768 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2769 * out of the public fields to keep the undefined bits out of the developer's way. 2770 * 2771 * Flag to hide notification icons and scrolling ticker text. 2772 */ 2773 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2774 2775 /** 2776 * @hide 2777 * 2778 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2779 * out of the public fields to keep the undefined bits out of the developer's way. 2780 * 2781 * Flag to disable incoming notification alerts. This will not block 2782 * icons, but it will block sound, vibrating and other visual or aural notifications. 2783 */ 2784 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2785 2786 /** 2787 * @hide 2788 * 2789 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2790 * out of the public fields to keep the undefined bits out of the developer's way. 2791 * 2792 * Flag to hide only the scrolling ticker. Note that 2793 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2794 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2795 */ 2796 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2797 2798 /** 2799 * @hide 2800 * 2801 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2802 * out of the public fields to keep the undefined bits out of the developer's way. 2803 * 2804 * Flag to hide the center system info area. 2805 */ 2806 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2807 2808 /** 2809 * @hide 2810 * 2811 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2812 * out of the public fields to keep the undefined bits out of the developer's way. 2813 * 2814 * Flag to hide only the home button. Don't use this 2815 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2816 */ 2817 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2818 2819 /** 2820 * @hide 2821 * 2822 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2823 * out of the public fields to keep the undefined bits out of the developer's way. 2824 * 2825 * Flag to hide only the back button. Don't use this 2826 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2827 */ 2828 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2829 2830 /** 2831 * @hide 2832 * 2833 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2834 * out of the public fields to keep the undefined bits out of the developer's way. 2835 * 2836 * Flag to hide only the clock. You might use this if your activity has 2837 * its own clock making the status bar's clock redundant. 2838 */ 2839 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2840 2841 /** 2842 * @hide 2843 * 2844 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2845 * out of the public fields to keep the undefined bits out of the developer's way. 2846 * 2847 * Flag to hide only the recent apps button. Don't use this 2848 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2849 */ 2850 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2851 2852 /** 2853 * @hide 2854 * 2855 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2856 * out of the public fields to keep the undefined bits out of the developer's way. 2857 * 2858 * Flag to disable the global search gesture. Don't use this 2859 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2860 */ 2861 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2862 2863 /** 2864 * @hide 2865 * 2866 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2867 * out of the public fields to keep the undefined bits out of the developer's way. 2868 * 2869 * Flag to specify that the status bar is displayed in transient mode. 2870 */ 2871 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2872 2873 /** 2874 * @hide 2875 * 2876 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2877 * out of the public fields to keep the undefined bits out of the developer's way. 2878 * 2879 * Flag to specify that the navigation bar is displayed in transient mode. 2880 */ 2881 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2882 2883 /** 2884 * @hide 2885 * 2886 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2887 * out of the public fields to keep the undefined bits out of the developer's way. 2888 * 2889 * Flag to specify that the hidden status bar would like to be shown. 2890 */ 2891 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2892 2893 /** 2894 * @hide 2895 * 2896 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2897 * out of the public fields to keep the undefined bits out of the developer's way. 2898 * 2899 * Flag to specify that the hidden navigation bar would like to be shown. 2900 */ 2901 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2902 2903 /** 2904 * @hide 2905 * 2906 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2907 * out of the public fields to keep the undefined bits out of the developer's way. 2908 * 2909 * Flag to specify that the status bar is displayed in translucent mode. 2910 */ 2911 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2912 2913 /** 2914 * @hide 2915 * 2916 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2917 * out of the public fields to keep the undefined bits out of the developer's way. 2918 * 2919 * Flag to specify that the navigation bar is displayed in translucent mode. 2920 */ 2921 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2922 2923 /** 2924 * @hide 2925 * 2926 * Whether Recents is visible or not. 2927 */ 2928 public static final int RECENT_APPS_VISIBLE = 0x00004000; 2929 2930 /** 2931 * @hide 2932 * 2933 * Makes system ui transparent. 2934 */ 2935 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2936 2937 /** 2938 * @hide 2939 */ 2940 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF; 2941 2942 /** 2943 * These are the system UI flags that can be cleared by events outside 2944 * of an application. Currently this is just the ability to tap on the 2945 * screen while hiding the navigation bar to have it return. 2946 * @hide 2947 */ 2948 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2949 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2950 | SYSTEM_UI_FLAG_FULLSCREEN; 2951 2952 /** 2953 * Flags that can impact the layout in relation to system UI. 2954 */ 2955 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2956 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2957 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2958 2959 /** @hide */ 2960 @IntDef(flag = true, 2961 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2962 @Retention(RetentionPolicy.SOURCE) 2963 public @interface FindViewFlags {} 2964 2965 /** 2966 * Find views that render the specified text. 2967 * 2968 * @see #findViewsWithText(ArrayList, CharSequence, int) 2969 */ 2970 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2971 2972 /** 2973 * Find find views that contain the specified content description. 2974 * 2975 * @see #findViewsWithText(ArrayList, CharSequence, int) 2976 */ 2977 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2978 2979 /** 2980 * Find views that contain {@link AccessibilityNodeProvider}. Such 2981 * a View is a root of virtual view hierarchy and may contain the searched 2982 * text. If this flag is set Views with providers are automatically 2983 * added and it is a responsibility of the client to call the APIs of 2984 * the provider to determine whether the virtual tree rooted at this View 2985 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2986 * representing the virtual views with this text. 2987 * 2988 * @see #findViewsWithText(ArrayList, CharSequence, int) 2989 * 2990 * @hide 2991 */ 2992 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2993 2994 /** 2995 * The undefined cursor position. 2996 * 2997 * @hide 2998 */ 2999 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 3000 3001 /** 3002 * Indicates that the screen has changed state and is now off. 3003 * 3004 * @see #onScreenStateChanged(int) 3005 */ 3006 public static final int SCREEN_STATE_OFF = 0x0; 3007 3008 /** 3009 * Indicates that the screen has changed state and is now on. 3010 * 3011 * @see #onScreenStateChanged(int) 3012 */ 3013 public static final int SCREEN_STATE_ON = 0x1; 3014 3015 /** 3016 * Indicates no axis of view scrolling. 3017 */ 3018 public static final int SCROLL_AXIS_NONE = 0; 3019 3020 /** 3021 * Indicates scrolling along the horizontal axis. 3022 */ 3023 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 3024 3025 /** 3026 * Indicates scrolling along the vertical axis. 3027 */ 3028 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 3029 3030 /** 3031 * Controls the over-scroll mode for this view. 3032 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 3033 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 3034 * and {@link #OVER_SCROLL_NEVER}. 3035 */ 3036 private int mOverScrollMode; 3037 3038 /** 3039 * The parent this view is attached to. 3040 * {@hide} 3041 * 3042 * @see #getParent() 3043 */ 3044 protected ViewParent mParent; 3045 3046 /** 3047 * {@hide} 3048 */ 3049 AttachInfo mAttachInfo; 3050 3051 /** 3052 * {@hide} 3053 */ 3054 @ViewDebug.ExportedProperty(flagMapping = { 3055 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 3056 name = "FORCE_LAYOUT"), 3057 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 3058 name = "LAYOUT_REQUIRED"), 3059 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 3060 name = "DRAWING_CACHE_INVALID", outputIf = false), 3061 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 3062 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 3063 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 3064 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 3065 }, formatToHexString = true) 3066 int mPrivateFlags; 3067 int mPrivateFlags2; 3068 int mPrivateFlags3; 3069 3070 /** 3071 * This view's request for the visibility of the status bar. 3072 * @hide 3073 */ 3074 @ViewDebug.ExportedProperty(flagMapping = { 3075 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 3076 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 3077 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 3078 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3079 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3080 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 3081 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 3082 equals = SYSTEM_UI_FLAG_VISIBLE, 3083 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 3084 }, formatToHexString = true) 3085 int mSystemUiVisibility; 3086 3087 /** 3088 * Reference count for transient state. 3089 * @see #setHasTransientState(boolean) 3090 */ 3091 int mTransientStateCount = 0; 3092 3093 /** 3094 * Count of how many windows this view has been attached to. 3095 */ 3096 int mWindowAttachCount; 3097 3098 /** 3099 * The layout parameters associated with this view and used by the parent 3100 * {@link android.view.ViewGroup} to determine how this view should be 3101 * laid out. 3102 * {@hide} 3103 */ 3104 protected ViewGroup.LayoutParams mLayoutParams; 3105 3106 /** 3107 * The view flags hold various views states. 3108 * {@hide} 3109 */ 3110 @ViewDebug.ExportedProperty(formatToHexString = true) 3111 int mViewFlags; 3112 3113 static class TransformationInfo { 3114 /** 3115 * The transform matrix for the View. This transform is calculated internally 3116 * based on the translation, rotation, and scale properties. 3117 * 3118 * Do *not* use this variable directly; instead call getMatrix(), which will 3119 * load the value from the View's RenderNode. 3120 */ 3121 private final Matrix mMatrix = new Matrix(); 3122 3123 /** 3124 * The inverse transform matrix for the View. This transform is calculated 3125 * internally based on the translation, rotation, and scale properties. 3126 * 3127 * Do *not* use this variable directly; instead call getInverseMatrix(), 3128 * which will load the value from the View's RenderNode. 3129 */ 3130 private Matrix mInverseMatrix; 3131 3132 /** 3133 * The opacity of the View. This is a value from 0 to 1, where 0 means 3134 * completely transparent and 1 means completely opaque. 3135 */ 3136 @ViewDebug.ExportedProperty 3137 float mAlpha = 1f; 3138 3139 /** 3140 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3141 * property only used by transitions, which is composited with the other alpha 3142 * values to calculate the final visual alpha value. 3143 */ 3144 float mTransitionAlpha = 1f; 3145 } 3146 3147 TransformationInfo mTransformationInfo; 3148 3149 /** 3150 * Current clip bounds. to which all drawing of this view are constrained. 3151 */ 3152 Rect mClipBounds = null; 3153 3154 private boolean mLastIsOpaque; 3155 3156 /** 3157 * The distance in pixels from the left edge of this view's parent 3158 * to the left edge of this view. 3159 * {@hide} 3160 */ 3161 @ViewDebug.ExportedProperty(category = "layout") 3162 protected int mLeft; 3163 /** 3164 * The distance in pixels from the left edge of this view's parent 3165 * to the right edge of this view. 3166 * {@hide} 3167 */ 3168 @ViewDebug.ExportedProperty(category = "layout") 3169 protected int mRight; 3170 /** 3171 * The distance in pixels from the top edge of this view's parent 3172 * to the top edge of this view. 3173 * {@hide} 3174 */ 3175 @ViewDebug.ExportedProperty(category = "layout") 3176 protected int mTop; 3177 /** 3178 * The distance in pixels from the top edge of this view's parent 3179 * to the bottom edge of this view. 3180 * {@hide} 3181 */ 3182 @ViewDebug.ExportedProperty(category = "layout") 3183 protected int mBottom; 3184 3185 /** 3186 * The offset, in pixels, by which the content of this view is scrolled 3187 * horizontally. 3188 * {@hide} 3189 */ 3190 @ViewDebug.ExportedProperty(category = "scrolling") 3191 protected int mScrollX; 3192 /** 3193 * The offset, in pixels, by which the content of this view is scrolled 3194 * vertically. 3195 * {@hide} 3196 */ 3197 @ViewDebug.ExportedProperty(category = "scrolling") 3198 protected int mScrollY; 3199 3200 /** 3201 * The left padding in pixels, that is the distance in pixels between the 3202 * left edge of this view and the left edge of its content. 3203 * {@hide} 3204 */ 3205 @ViewDebug.ExportedProperty(category = "padding") 3206 protected int mPaddingLeft = 0; 3207 /** 3208 * The right padding in pixels, that is the distance in pixels between the 3209 * right edge of this view and the right edge of its content. 3210 * {@hide} 3211 */ 3212 @ViewDebug.ExportedProperty(category = "padding") 3213 protected int mPaddingRight = 0; 3214 /** 3215 * The top padding in pixels, that is the distance in pixels between the 3216 * top edge of this view and the top edge of its content. 3217 * {@hide} 3218 */ 3219 @ViewDebug.ExportedProperty(category = "padding") 3220 protected int mPaddingTop; 3221 /** 3222 * The bottom padding in pixels, that is the distance in pixels between the 3223 * bottom edge of this view and the bottom edge of its content. 3224 * {@hide} 3225 */ 3226 @ViewDebug.ExportedProperty(category = "padding") 3227 protected int mPaddingBottom; 3228 3229 /** 3230 * The layout insets in pixels, that is the distance in pixels between the 3231 * visible edges of this view its bounds. 3232 */ 3233 private Insets mLayoutInsets; 3234 3235 /** 3236 * Briefly describes the view and is primarily used for accessibility support. 3237 */ 3238 private CharSequence mContentDescription; 3239 3240 /** 3241 * Specifies the id of a view for which this view serves as a label for 3242 * accessibility purposes. 3243 */ 3244 private int mLabelForId = View.NO_ID; 3245 3246 /** 3247 * Predicate for matching labeled view id with its label for 3248 * accessibility purposes. 3249 */ 3250 private MatchLabelForPredicate mMatchLabelForPredicate; 3251 3252 /** 3253 * Specifies a view before which this one is visited in accessibility traversal. 3254 */ 3255 private int mAccessibilityTraversalBeforeId = NO_ID; 3256 3257 /** 3258 * Specifies a view after which this one is visited in accessibility traversal. 3259 */ 3260 private int mAccessibilityTraversalAfterId = NO_ID; 3261 3262 /** 3263 * Predicate for matching a view by its id. 3264 */ 3265 private MatchIdPredicate mMatchIdPredicate; 3266 3267 /** 3268 * Cache the paddingRight set by the user to append to the scrollbar's size. 3269 * 3270 * @hide 3271 */ 3272 @ViewDebug.ExportedProperty(category = "padding") 3273 protected int mUserPaddingRight; 3274 3275 /** 3276 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3277 * 3278 * @hide 3279 */ 3280 @ViewDebug.ExportedProperty(category = "padding") 3281 protected int mUserPaddingBottom; 3282 3283 /** 3284 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3285 * 3286 * @hide 3287 */ 3288 @ViewDebug.ExportedProperty(category = "padding") 3289 protected int mUserPaddingLeft; 3290 3291 /** 3292 * Cache the paddingStart set by the user to append to the scrollbar's size. 3293 * 3294 */ 3295 @ViewDebug.ExportedProperty(category = "padding") 3296 int mUserPaddingStart; 3297 3298 /** 3299 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3300 * 3301 */ 3302 @ViewDebug.ExportedProperty(category = "padding") 3303 int mUserPaddingEnd; 3304 3305 /** 3306 * Cache initial left padding. 3307 * 3308 * @hide 3309 */ 3310 int mUserPaddingLeftInitial; 3311 3312 /** 3313 * Cache initial right padding. 3314 * 3315 * @hide 3316 */ 3317 int mUserPaddingRightInitial; 3318 3319 /** 3320 * Default undefined padding 3321 */ 3322 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3323 3324 /** 3325 * Cache if a left padding has been defined 3326 */ 3327 private boolean mLeftPaddingDefined = false; 3328 3329 /** 3330 * Cache if a right padding has been defined 3331 */ 3332 private boolean mRightPaddingDefined = false; 3333 3334 /** 3335 * @hide 3336 */ 3337 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3338 /** 3339 * @hide 3340 */ 3341 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3342 3343 private LongSparseLongArray mMeasureCache; 3344 3345 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3346 private Drawable mBackground; 3347 private TintInfo mBackgroundTint; 3348 3349 @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_") 3350 private ForegroundInfo mForegroundInfo; 3351 3352 private Drawable mScrollIndicatorDrawable; 3353 3354 /** 3355 * RenderNode used for backgrounds. 3356 * <p> 3357 * When non-null and valid, this is expected to contain an up-to-date copy 3358 * of the background drawable. It is cleared on temporary detach, and reset 3359 * on cleanup. 3360 */ 3361 private RenderNode mBackgroundRenderNode; 3362 3363 private int mBackgroundResource; 3364 private boolean mBackgroundSizeChanged; 3365 3366 private String mTransitionName; 3367 3368 static class TintInfo { 3369 ColorStateList mTintList; 3370 PorterDuff.Mode mTintMode; 3371 boolean mHasTintMode; 3372 boolean mHasTintList; 3373 } 3374 3375 private static class ForegroundInfo { 3376 private Drawable mDrawable; 3377 private TintInfo mTintInfo; 3378 private int mGravity = Gravity.FILL; 3379 private boolean mInsidePadding = true; 3380 private boolean mBoundsChanged = true; 3381 private final Rect mSelfBounds = new Rect(); 3382 private final Rect mOverlayBounds = new Rect(); 3383 } 3384 3385 static class ListenerInfo { 3386 /** 3387 * Listener used to dispatch focus change events. 3388 * This field should be made private, so it is hidden from the SDK. 3389 * {@hide} 3390 */ 3391 protected OnFocusChangeListener mOnFocusChangeListener; 3392 3393 /** 3394 * Listeners for layout change events. 3395 */ 3396 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3397 3398 protected OnScrollChangeListener mOnScrollChangeListener; 3399 3400 /** 3401 * Listeners for attach events. 3402 */ 3403 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3404 3405 /** 3406 * Listener used to dispatch click events. 3407 * This field should be made private, so it is hidden from the SDK. 3408 * {@hide} 3409 */ 3410 public OnClickListener mOnClickListener; 3411 3412 /** 3413 * Listener used to dispatch long click events. 3414 * This field should be made private, so it is hidden from the SDK. 3415 * {@hide} 3416 */ 3417 protected OnLongClickListener mOnLongClickListener; 3418 3419 /** 3420 * Listener used to dispatch stylus touch and button press events. This field should be made 3421 * private, so it is hidden from the SDK. 3422 * {@hide} 3423 */ 3424 protected OnStylusButtonPressListener mOnStylusButtonPressListener; 3425 3426 /** 3427 * Listener used to build the context menu. 3428 * This field should be made private, so it is hidden from the SDK. 3429 * {@hide} 3430 */ 3431 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3432 3433 private OnKeyListener mOnKeyListener; 3434 3435 private OnTouchListener mOnTouchListener; 3436 3437 private OnHoverListener mOnHoverListener; 3438 3439 private OnGenericMotionListener mOnGenericMotionListener; 3440 3441 private OnDragListener mOnDragListener; 3442 3443 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3444 3445 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3446 } 3447 3448 ListenerInfo mListenerInfo; 3449 3450 /** 3451 * The application environment this view lives in. 3452 * This field should be made private, so it is hidden from the SDK. 3453 * {@hide} 3454 */ 3455 @ViewDebug.ExportedProperty(deepExport = true) 3456 protected Context mContext; 3457 3458 private final Resources mResources; 3459 3460 private ScrollabilityCache mScrollCache; 3461 3462 private int[] mDrawableState = null; 3463 3464 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3465 3466 /** 3467 * Animator that automatically runs based on state changes. 3468 */ 3469 private StateListAnimator mStateListAnimator; 3470 3471 /** 3472 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3473 * the user may specify which view to go to next. 3474 */ 3475 private int mNextFocusLeftId = View.NO_ID; 3476 3477 /** 3478 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3479 * the user may specify which view to go to next. 3480 */ 3481 private int mNextFocusRightId = View.NO_ID; 3482 3483 /** 3484 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3485 * the user may specify which view to go to next. 3486 */ 3487 private int mNextFocusUpId = View.NO_ID; 3488 3489 /** 3490 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3491 * the user may specify which view to go to next. 3492 */ 3493 private int mNextFocusDownId = View.NO_ID; 3494 3495 /** 3496 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3497 * the user may specify which view to go to next. 3498 */ 3499 int mNextFocusForwardId = View.NO_ID; 3500 3501 private CheckForLongPress mPendingCheckForLongPress; 3502 private CheckForTap mPendingCheckForTap = null; 3503 private PerformClick mPerformClick; 3504 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3505 3506 private UnsetPressedState mUnsetPressedState; 3507 3508 /** 3509 * Whether the long press's action has been invoked. The tap's action is invoked on the 3510 * up event while a long press is invoked as soon as the long press duration is reached, so 3511 * a long press could be performed before the tap is checked, in which case the tap's action 3512 * should not be invoked. 3513 */ 3514 private boolean mHasPerformedLongPress; 3515 3516 /** 3517 * Whether the stylus button is currently pressed down. This is true when 3518 * the stylus is touching the screen and the button has been pressed, this 3519 * is false once the stylus has been lifted. 3520 */ 3521 private boolean mInStylusButtonPress = false; 3522 3523 /** 3524 * The minimum height of the view. We'll try our best to have the height 3525 * of this view to at least this amount. 3526 */ 3527 @ViewDebug.ExportedProperty(category = "measurement") 3528 private int mMinHeight; 3529 3530 /** 3531 * The minimum width of the view. We'll try our best to have the width 3532 * of this view to at least this amount. 3533 */ 3534 @ViewDebug.ExportedProperty(category = "measurement") 3535 private int mMinWidth; 3536 3537 /** 3538 * The delegate to handle touch events that are physically in this view 3539 * but should be handled by another view. 3540 */ 3541 private TouchDelegate mTouchDelegate = null; 3542 3543 /** 3544 * Solid color to use as a background when creating the drawing cache. Enables 3545 * the cache to use 16 bit bitmaps instead of 32 bit. 3546 */ 3547 private int mDrawingCacheBackgroundColor = 0; 3548 3549 /** 3550 * Special tree observer used when mAttachInfo is null. 3551 */ 3552 private ViewTreeObserver mFloatingTreeObserver; 3553 3554 /** 3555 * Cache the touch slop from the context that created the view. 3556 */ 3557 private int mTouchSlop; 3558 3559 /** 3560 * Object that handles automatic animation of view properties. 3561 */ 3562 private ViewPropertyAnimator mAnimator = null; 3563 3564 /** 3565 * Flag indicating that a drag can cross window boundaries. When 3566 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3567 * with this flag set, all visible applications will be able to participate 3568 * in the drag operation and receive the dragged content. 3569 * 3570 * @hide 3571 */ 3572 public static final int DRAG_FLAG_GLOBAL = 1; 3573 3574 /** 3575 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3576 */ 3577 private float mVerticalScrollFactor; 3578 3579 /** 3580 * Position of the vertical scroll bar. 3581 */ 3582 private int mVerticalScrollbarPosition; 3583 3584 /** 3585 * Position the scroll bar at the default position as determined by the system. 3586 */ 3587 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3588 3589 /** 3590 * Position the scroll bar along the left edge. 3591 */ 3592 public static final int SCROLLBAR_POSITION_LEFT = 1; 3593 3594 /** 3595 * Position the scroll bar along the right edge. 3596 */ 3597 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3598 3599 /** 3600 * Indicates that the view does not have a layer. 3601 * 3602 * @see #getLayerType() 3603 * @see #setLayerType(int, android.graphics.Paint) 3604 * @see #LAYER_TYPE_SOFTWARE 3605 * @see #LAYER_TYPE_HARDWARE 3606 */ 3607 public static final int LAYER_TYPE_NONE = 0; 3608 3609 /** 3610 * <p>Indicates that the view has a software layer. A software layer is backed 3611 * by a bitmap and causes the view to be rendered using Android's software 3612 * rendering pipeline, even if hardware acceleration is enabled.</p> 3613 * 3614 * <p>Software layers have various usages:</p> 3615 * <p>When the application is not using hardware acceleration, a software layer 3616 * is useful to apply a specific color filter and/or blending mode and/or 3617 * translucency to a view and all its children.</p> 3618 * <p>When the application is using hardware acceleration, a software layer 3619 * is useful to render drawing primitives not supported by the hardware 3620 * accelerated pipeline. It can also be used to cache a complex view tree 3621 * into a texture and reduce the complexity of drawing operations. For instance, 3622 * when animating a complex view tree with a translation, a software layer can 3623 * be used to render the view tree only once.</p> 3624 * <p>Software layers should be avoided when the affected view tree updates 3625 * often. Every update will require to re-render the software layer, which can 3626 * potentially be slow (particularly when hardware acceleration is turned on 3627 * since the layer will have to be uploaded into a hardware texture after every 3628 * update.)</p> 3629 * 3630 * @see #getLayerType() 3631 * @see #setLayerType(int, android.graphics.Paint) 3632 * @see #LAYER_TYPE_NONE 3633 * @see #LAYER_TYPE_HARDWARE 3634 */ 3635 public static final int LAYER_TYPE_SOFTWARE = 1; 3636 3637 /** 3638 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3639 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3640 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3641 * rendering pipeline, but only if hardware acceleration is turned on for the 3642 * view hierarchy. When hardware acceleration is turned off, hardware layers 3643 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3644 * 3645 * <p>A hardware layer is useful to apply a specific color filter and/or 3646 * blending mode and/or translucency to a view and all its children.</p> 3647 * <p>A hardware layer can be used to cache a complex view tree into a 3648 * texture and reduce the complexity of drawing operations. For instance, 3649 * when animating a complex view tree with a translation, a hardware layer can 3650 * be used to render the view tree only once.</p> 3651 * <p>A hardware layer can also be used to increase the rendering quality when 3652 * rotation transformations are applied on a view. It can also be used to 3653 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3654 * 3655 * @see #getLayerType() 3656 * @see #setLayerType(int, android.graphics.Paint) 3657 * @see #LAYER_TYPE_NONE 3658 * @see #LAYER_TYPE_SOFTWARE 3659 */ 3660 public static final int LAYER_TYPE_HARDWARE = 2; 3661 3662 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3663 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3664 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3665 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3666 }) 3667 int mLayerType = LAYER_TYPE_NONE; 3668 Paint mLayerPaint; 3669 3670 /** 3671 * Set to true when drawing cache is enabled and cannot be created. 3672 * 3673 * @hide 3674 */ 3675 public boolean mCachingFailed; 3676 private Bitmap mDrawingCache; 3677 private Bitmap mUnscaledDrawingCache; 3678 3679 /** 3680 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3681 * <p> 3682 * When non-null and valid, this is expected to contain an up-to-date copy 3683 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3684 * cleanup. 3685 */ 3686 final RenderNode mRenderNode; 3687 3688 /** 3689 * Set to true when the view is sending hover accessibility events because it 3690 * is the innermost hovered view. 3691 */ 3692 private boolean mSendingHoverAccessibilityEvents; 3693 3694 /** 3695 * Delegate for injecting accessibility functionality. 3696 */ 3697 AccessibilityDelegate mAccessibilityDelegate; 3698 3699 /** 3700 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3701 * and add/remove objects to/from the overlay directly through the Overlay methods. 3702 */ 3703 ViewOverlay mOverlay; 3704 3705 /** 3706 * The currently active parent view for receiving delegated nested scrolling events. 3707 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3708 * by {@link #stopNestedScroll()} at the same point where we clear 3709 * requestDisallowInterceptTouchEvent. 3710 */ 3711 private ViewParent mNestedScrollingParent; 3712 3713 /** 3714 * Consistency verifier for debugging purposes. 3715 * @hide 3716 */ 3717 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3718 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3719 new InputEventConsistencyVerifier(this, 0) : null; 3720 3721 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3722 3723 private int[] mTempNestedScrollConsumed; 3724 3725 /** 3726 * An overlay is going to draw this View instead of being drawn as part of this 3727 * View's parent. mGhostView is the View in the Overlay that must be invalidated 3728 * when this view is invalidated. 3729 */ 3730 GhostView mGhostView; 3731 3732 /** 3733 * Holds pairs of adjacent attribute data: attribute name followed by its value. 3734 * @hide 3735 */ 3736 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 3737 public String[] mAttributes; 3738 3739 /** 3740 * Maps a Resource id to its name. 3741 */ 3742 private static SparseArray<String> mAttributeMap; 3743 3744 /** 3745 * @hide 3746 */ 3747 String mStartActivityRequestWho; 3748 3749 /** 3750 * Simple constructor to use when creating a view from code. 3751 * 3752 * @param context The Context the view is running in, through which it can 3753 * access the current theme, resources, etc. 3754 */ 3755 public View(Context context) { 3756 mContext = context; 3757 mResources = context != null ? context.getResources() : null; 3758 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3759 // Set some flags defaults 3760 mPrivateFlags2 = 3761 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3762 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3763 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3764 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3765 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3766 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3767 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3768 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3769 mUserPaddingStart = UNDEFINED_PADDING; 3770 mUserPaddingEnd = UNDEFINED_PADDING; 3771 mRenderNode = RenderNode.create(getClass().getName(), this); 3772 3773 if (!sCompatibilityDone && context != null) { 3774 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3775 3776 // Older apps may need this compatibility hack for measurement. 3777 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3778 3779 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3780 // of whether a layout was requested on that View. 3781 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3782 3783 Canvas.sCompatibilityRestore = targetSdkVersion < MNC; 3784 3785 sCompatibilityDone = true; 3786 } 3787 } 3788 3789 /** 3790 * Constructor that is called when inflating a view from XML. This is called 3791 * when a view is being constructed from an XML file, supplying attributes 3792 * that were specified in the XML file. This version uses a default style of 3793 * 0, so the only attribute values applied are those in the Context's Theme 3794 * and the given AttributeSet. 3795 * 3796 * <p> 3797 * The method onFinishInflate() will be called after all children have been 3798 * added. 3799 * 3800 * @param context The Context the view is running in, through which it can 3801 * access the current theme, resources, etc. 3802 * @param attrs The attributes of the XML tag that is inflating the view. 3803 * @see #View(Context, AttributeSet, int) 3804 */ 3805 public View(Context context, @Nullable AttributeSet attrs) { 3806 this(context, attrs, 0); 3807 } 3808 3809 /** 3810 * Perform inflation from XML and apply a class-specific base style from a 3811 * theme attribute. This constructor of View allows subclasses to use their 3812 * own base style when they are inflating. For example, a Button class's 3813 * constructor would call this version of the super class constructor and 3814 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3815 * allows the theme's button style to modify all of the base view attributes 3816 * (in particular its background) as well as the Button class's attributes. 3817 * 3818 * @param context The Context the view is running in, through which it can 3819 * access the current theme, resources, etc. 3820 * @param attrs The attributes of the XML tag that is inflating the view. 3821 * @param defStyleAttr An attribute in the current theme that contains a 3822 * reference to a style resource that supplies default values for 3823 * the view. Can be 0 to not look for defaults. 3824 * @see #View(Context, AttributeSet) 3825 */ 3826 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 3827 this(context, attrs, defStyleAttr, 0); 3828 } 3829 3830 /** 3831 * Perform inflation from XML and apply a class-specific base style from a 3832 * theme attribute or style resource. This constructor of View allows 3833 * subclasses to use their own base style when they are inflating. 3834 * <p> 3835 * When determining the final value of a particular attribute, there are 3836 * four inputs that come into play: 3837 * <ol> 3838 * <li>Any attribute values in the given AttributeSet. 3839 * <li>The style resource specified in the AttributeSet (named "style"). 3840 * <li>The default style specified by <var>defStyleAttr</var>. 3841 * <li>The default style specified by <var>defStyleRes</var>. 3842 * <li>The base values in this theme. 3843 * </ol> 3844 * <p> 3845 * Each of these inputs is considered in-order, with the first listed taking 3846 * precedence over the following ones. In other words, if in the 3847 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3848 * , then the button's text will <em>always</em> be black, regardless of 3849 * what is specified in any of the styles. 3850 * 3851 * @param context The Context the view is running in, through which it can 3852 * access the current theme, resources, etc. 3853 * @param attrs The attributes of the XML tag that is inflating the view. 3854 * @param defStyleAttr An attribute in the current theme that contains a 3855 * reference to a style resource that supplies default values for 3856 * the view. Can be 0 to not look for defaults. 3857 * @param defStyleRes A resource identifier of a style resource that 3858 * supplies default values for the view, used only if 3859 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3860 * to not look for defaults. 3861 * @see #View(Context, AttributeSet, int) 3862 */ 3863 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3864 this(context); 3865 3866 final TypedArray a = context.obtainStyledAttributes( 3867 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3868 3869 if (mDebugViewAttributes) { 3870 saveAttributeData(attrs, a); 3871 } 3872 3873 Drawable background = null; 3874 3875 int leftPadding = -1; 3876 int topPadding = -1; 3877 int rightPadding = -1; 3878 int bottomPadding = -1; 3879 int startPadding = UNDEFINED_PADDING; 3880 int endPadding = UNDEFINED_PADDING; 3881 3882 int padding = -1; 3883 3884 int viewFlagValues = 0; 3885 int viewFlagMasks = 0; 3886 3887 boolean setScrollContainer = false; 3888 3889 int x = 0; 3890 int y = 0; 3891 3892 float tx = 0; 3893 float ty = 0; 3894 float tz = 0; 3895 float elevation = 0; 3896 float rotation = 0; 3897 float rotationX = 0; 3898 float rotationY = 0; 3899 float sx = 1f; 3900 float sy = 1f; 3901 boolean transformSet = false; 3902 3903 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3904 int overScrollMode = mOverScrollMode; 3905 boolean initializeScrollbars = false; 3906 boolean initializeScrollIndicators = false; 3907 3908 boolean startPaddingDefined = false; 3909 boolean endPaddingDefined = false; 3910 boolean leftPaddingDefined = false; 3911 boolean rightPaddingDefined = false; 3912 3913 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3914 3915 final int N = a.getIndexCount(); 3916 for (int i = 0; i < N; i++) { 3917 int attr = a.getIndex(i); 3918 switch (attr) { 3919 case com.android.internal.R.styleable.View_background: 3920 background = a.getDrawable(attr); 3921 break; 3922 case com.android.internal.R.styleable.View_padding: 3923 padding = a.getDimensionPixelSize(attr, -1); 3924 mUserPaddingLeftInitial = padding; 3925 mUserPaddingRightInitial = padding; 3926 leftPaddingDefined = true; 3927 rightPaddingDefined = true; 3928 break; 3929 case com.android.internal.R.styleable.View_paddingLeft: 3930 leftPadding = a.getDimensionPixelSize(attr, -1); 3931 mUserPaddingLeftInitial = leftPadding; 3932 leftPaddingDefined = true; 3933 break; 3934 case com.android.internal.R.styleable.View_paddingTop: 3935 topPadding = a.getDimensionPixelSize(attr, -1); 3936 break; 3937 case com.android.internal.R.styleable.View_paddingRight: 3938 rightPadding = a.getDimensionPixelSize(attr, -1); 3939 mUserPaddingRightInitial = rightPadding; 3940 rightPaddingDefined = true; 3941 break; 3942 case com.android.internal.R.styleable.View_paddingBottom: 3943 bottomPadding = a.getDimensionPixelSize(attr, -1); 3944 break; 3945 case com.android.internal.R.styleable.View_paddingStart: 3946 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3947 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3948 break; 3949 case com.android.internal.R.styleable.View_paddingEnd: 3950 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3951 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3952 break; 3953 case com.android.internal.R.styleable.View_scrollX: 3954 x = a.getDimensionPixelOffset(attr, 0); 3955 break; 3956 case com.android.internal.R.styleable.View_scrollY: 3957 y = a.getDimensionPixelOffset(attr, 0); 3958 break; 3959 case com.android.internal.R.styleable.View_alpha: 3960 setAlpha(a.getFloat(attr, 1f)); 3961 break; 3962 case com.android.internal.R.styleable.View_transformPivotX: 3963 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3964 break; 3965 case com.android.internal.R.styleable.View_transformPivotY: 3966 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3967 break; 3968 case com.android.internal.R.styleable.View_translationX: 3969 tx = a.getDimensionPixelOffset(attr, 0); 3970 transformSet = true; 3971 break; 3972 case com.android.internal.R.styleable.View_translationY: 3973 ty = a.getDimensionPixelOffset(attr, 0); 3974 transformSet = true; 3975 break; 3976 case com.android.internal.R.styleable.View_translationZ: 3977 tz = a.getDimensionPixelOffset(attr, 0); 3978 transformSet = true; 3979 break; 3980 case com.android.internal.R.styleable.View_elevation: 3981 elevation = a.getDimensionPixelOffset(attr, 0); 3982 transformSet = true; 3983 break; 3984 case com.android.internal.R.styleable.View_rotation: 3985 rotation = a.getFloat(attr, 0); 3986 transformSet = true; 3987 break; 3988 case com.android.internal.R.styleable.View_rotationX: 3989 rotationX = a.getFloat(attr, 0); 3990 transformSet = true; 3991 break; 3992 case com.android.internal.R.styleable.View_rotationY: 3993 rotationY = a.getFloat(attr, 0); 3994 transformSet = true; 3995 break; 3996 case com.android.internal.R.styleable.View_scaleX: 3997 sx = a.getFloat(attr, 1f); 3998 transformSet = true; 3999 break; 4000 case com.android.internal.R.styleable.View_scaleY: 4001 sy = a.getFloat(attr, 1f); 4002 transformSet = true; 4003 break; 4004 case com.android.internal.R.styleable.View_id: 4005 mID = a.getResourceId(attr, NO_ID); 4006 break; 4007 case com.android.internal.R.styleable.View_tag: 4008 mTag = a.getText(attr); 4009 break; 4010 case com.android.internal.R.styleable.View_fitsSystemWindows: 4011 if (a.getBoolean(attr, false)) { 4012 viewFlagValues |= FITS_SYSTEM_WINDOWS; 4013 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 4014 } 4015 break; 4016 case com.android.internal.R.styleable.View_focusable: 4017 if (a.getBoolean(attr, false)) { 4018 viewFlagValues |= FOCUSABLE; 4019 viewFlagMasks |= FOCUSABLE_MASK; 4020 } 4021 break; 4022 case com.android.internal.R.styleable.View_focusableInTouchMode: 4023 if (a.getBoolean(attr, false)) { 4024 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 4025 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 4026 } 4027 break; 4028 case com.android.internal.R.styleable.View_clickable: 4029 if (a.getBoolean(attr, false)) { 4030 viewFlagValues |= CLICKABLE; 4031 viewFlagMasks |= CLICKABLE; 4032 } 4033 break; 4034 case com.android.internal.R.styleable.View_longClickable: 4035 if (a.getBoolean(attr, false)) { 4036 viewFlagValues |= LONG_CLICKABLE; 4037 viewFlagMasks |= LONG_CLICKABLE; 4038 } 4039 break; 4040 case com.android.internal.R.styleable.View_stylusButtonPressable: 4041 if (a.getBoolean(attr, false)) { 4042 viewFlagValues |= STYLUS_BUTTON_PRESSABLE; 4043 viewFlagMasks |= STYLUS_BUTTON_PRESSABLE; 4044 } 4045 break; 4046 case com.android.internal.R.styleable.View_saveEnabled: 4047 if (!a.getBoolean(attr, true)) { 4048 viewFlagValues |= SAVE_DISABLED; 4049 viewFlagMasks |= SAVE_DISABLED_MASK; 4050 } 4051 break; 4052 case com.android.internal.R.styleable.View_duplicateParentState: 4053 if (a.getBoolean(attr, false)) { 4054 viewFlagValues |= DUPLICATE_PARENT_STATE; 4055 viewFlagMasks |= DUPLICATE_PARENT_STATE; 4056 } 4057 break; 4058 case com.android.internal.R.styleable.View_visibility: 4059 final int visibility = a.getInt(attr, 0); 4060 if (visibility != 0) { 4061 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 4062 viewFlagMasks |= VISIBILITY_MASK; 4063 } 4064 break; 4065 case com.android.internal.R.styleable.View_layoutDirection: 4066 // Clear any layout direction flags (included resolved bits) already set 4067 mPrivateFlags2 &= 4068 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 4069 // Set the layout direction flags depending on the value of the attribute 4070 final int layoutDirection = a.getInt(attr, -1); 4071 final int value = (layoutDirection != -1) ? 4072 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 4073 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 4074 break; 4075 case com.android.internal.R.styleable.View_drawingCacheQuality: 4076 final int cacheQuality = a.getInt(attr, 0); 4077 if (cacheQuality != 0) { 4078 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 4079 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 4080 } 4081 break; 4082 case com.android.internal.R.styleable.View_contentDescription: 4083 setContentDescription(a.getString(attr)); 4084 break; 4085 case com.android.internal.R.styleable.View_accessibilityTraversalBefore: 4086 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID)); 4087 break; 4088 case com.android.internal.R.styleable.View_accessibilityTraversalAfter: 4089 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID)); 4090 break; 4091 case com.android.internal.R.styleable.View_labelFor: 4092 setLabelFor(a.getResourceId(attr, NO_ID)); 4093 break; 4094 case com.android.internal.R.styleable.View_soundEffectsEnabled: 4095 if (!a.getBoolean(attr, true)) { 4096 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 4097 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 4098 } 4099 break; 4100 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 4101 if (!a.getBoolean(attr, true)) { 4102 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 4103 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 4104 } 4105 break; 4106 case R.styleable.View_scrollbars: 4107 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 4108 if (scrollbars != SCROLLBARS_NONE) { 4109 viewFlagValues |= scrollbars; 4110 viewFlagMasks |= SCROLLBARS_MASK; 4111 initializeScrollbars = true; 4112 } 4113 break; 4114 //noinspection deprecation 4115 case R.styleable.View_fadingEdge: 4116 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 4117 // Ignore the attribute starting with ICS 4118 break; 4119 } 4120 // With builds < ICS, fall through and apply fading edges 4121 case R.styleable.View_requiresFadingEdge: 4122 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 4123 if (fadingEdge != FADING_EDGE_NONE) { 4124 viewFlagValues |= fadingEdge; 4125 viewFlagMasks |= FADING_EDGE_MASK; 4126 initializeFadingEdgeInternal(a); 4127 } 4128 break; 4129 case R.styleable.View_scrollbarStyle: 4130 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 4131 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4132 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 4133 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 4134 } 4135 break; 4136 case R.styleable.View_isScrollContainer: 4137 setScrollContainer = true; 4138 if (a.getBoolean(attr, false)) { 4139 setScrollContainer(true); 4140 } 4141 break; 4142 case com.android.internal.R.styleable.View_keepScreenOn: 4143 if (a.getBoolean(attr, false)) { 4144 viewFlagValues |= KEEP_SCREEN_ON; 4145 viewFlagMasks |= KEEP_SCREEN_ON; 4146 } 4147 break; 4148 case R.styleable.View_filterTouchesWhenObscured: 4149 if (a.getBoolean(attr, false)) { 4150 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 4151 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 4152 } 4153 break; 4154 case R.styleable.View_nextFocusLeft: 4155 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 4156 break; 4157 case R.styleable.View_nextFocusRight: 4158 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 4159 break; 4160 case R.styleable.View_nextFocusUp: 4161 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 4162 break; 4163 case R.styleable.View_nextFocusDown: 4164 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 4165 break; 4166 case R.styleable.View_nextFocusForward: 4167 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 4168 break; 4169 case R.styleable.View_minWidth: 4170 mMinWidth = a.getDimensionPixelSize(attr, 0); 4171 break; 4172 case R.styleable.View_minHeight: 4173 mMinHeight = a.getDimensionPixelSize(attr, 0); 4174 break; 4175 case R.styleable.View_onClick: 4176 if (context.isRestricted()) { 4177 throw new IllegalStateException("The android:onClick attribute cannot " 4178 + "be used within a restricted context"); 4179 } 4180 4181 final String handlerName = a.getString(attr); 4182 if (handlerName != null) { 4183 setOnClickListener(new DeclaredOnClickListener(this, handlerName)); 4184 } 4185 break; 4186 case R.styleable.View_overScrollMode: 4187 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4188 break; 4189 case R.styleable.View_verticalScrollbarPosition: 4190 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4191 break; 4192 case R.styleable.View_layerType: 4193 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4194 break; 4195 case R.styleable.View_textDirection: 4196 // Clear any text direction flag already set 4197 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4198 // Set the text direction flags depending on the value of the attribute 4199 final int textDirection = a.getInt(attr, -1); 4200 if (textDirection != -1) { 4201 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4202 } 4203 break; 4204 case R.styleable.View_textAlignment: 4205 // Clear any text alignment flag already set 4206 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4207 // Set the text alignment flag depending on the value of the attribute 4208 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4209 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4210 break; 4211 case R.styleable.View_importantForAccessibility: 4212 setImportantForAccessibility(a.getInt(attr, 4213 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4214 break; 4215 case R.styleable.View_accessibilityLiveRegion: 4216 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4217 break; 4218 case R.styleable.View_transitionName: 4219 setTransitionName(a.getString(attr)); 4220 break; 4221 case R.styleable.View_nestedScrollingEnabled: 4222 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4223 break; 4224 case R.styleable.View_stateListAnimator: 4225 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4226 a.getResourceId(attr, 0))); 4227 break; 4228 case R.styleable.View_backgroundTint: 4229 // This will get applied later during setBackground(). 4230 if (mBackgroundTint == null) { 4231 mBackgroundTint = new TintInfo(); 4232 } 4233 mBackgroundTint.mTintList = a.getColorStateList( 4234 R.styleable.View_backgroundTint); 4235 mBackgroundTint.mHasTintList = true; 4236 break; 4237 case R.styleable.View_backgroundTintMode: 4238 // This will get applied later during setBackground(). 4239 if (mBackgroundTint == null) { 4240 mBackgroundTint = new TintInfo(); 4241 } 4242 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 4243 R.styleable.View_backgroundTintMode, -1), null); 4244 mBackgroundTint.mHasTintMode = true; 4245 break; 4246 case R.styleable.View_outlineProvider: 4247 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4248 PROVIDER_BACKGROUND)); 4249 break; 4250 case R.styleable.View_foreground: 4251 setForeground(a.getDrawable(attr)); 4252 break; 4253 case R.styleable.View_foregroundGravity: 4254 setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY)); 4255 break; 4256 case R.styleable.View_foregroundTintMode: 4257 setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null)); 4258 break; 4259 case R.styleable.View_foregroundTint: 4260 setForegroundTintList(a.getColorStateList(attr)); 4261 break; 4262 case R.styleable.View_foregroundInsidePadding: 4263 if (mForegroundInfo == null) { 4264 mForegroundInfo = new ForegroundInfo(); 4265 } 4266 mForegroundInfo.mInsidePadding = a.getBoolean(attr, 4267 mForegroundInfo.mInsidePadding); 4268 break; 4269 case R.styleable.View_scrollIndicators: 4270 final int scrollIndicators = 4271 (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT) 4272 & SCROLL_INDICATORS_PFLAG3_MASK; 4273 if (scrollIndicators != 0) { 4274 mPrivateFlags3 |= scrollIndicators; 4275 initializeScrollIndicators = true; 4276 } 4277 break; 4278 } 4279 } 4280 4281 setOverScrollMode(overScrollMode); 4282 4283 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4284 // the resolved layout direction). Those cached values will be used later during padding 4285 // resolution. 4286 mUserPaddingStart = startPadding; 4287 mUserPaddingEnd = endPadding; 4288 4289 if (background != null) { 4290 setBackground(background); 4291 } 4292 4293 // setBackground above will record that padding is currently provided by the background. 4294 // If we have padding specified via xml, record that here instead and use it. 4295 mLeftPaddingDefined = leftPaddingDefined; 4296 mRightPaddingDefined = rightPaddingDefined; 4297 4298 if (padding >= 0) { 4299 leftPadding = padding; 4300 topPadding = padding; 4301 rightPadding = padding; 4302 bottomPadding = padding; 4303 mUserPaddingLeftInitial = padding; 4304 mUserPaddingRightInitial = padding; 4305 } 4306 4307 if (isRtlCompatibilityMode()) { 4308 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4309 // left / right padding are used if defined (meaning here nothing to do). If they are not 4310 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4311 // start / end and resolve them as left / right (layout direction is not taken into account). 4312 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4313 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4314 // defined. 4315 if (!mLeftPaddingDefined && startPaddingDefined) { 4316 leftPadding = startPadding; 4317 } 4318 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4319 if (!mRightPaddingDefined && endPaddingDefined) { 4320 rightPadding = endPadding; 4321 } 4322 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4323 } else { 4324 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4325 // values defined. Otherwise, left /right values are used. 4326 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4327 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4328 // defined. 4329 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4330 4331 if (mLeftPaddingDefined && !hasRelativePadding) { 4332 mUserPaddingLeftInitial = leftPadding; 4333 } 4334 if (mRightPaddingDefined && !hasRelativePadding) { 4335 mUserPaddingRightInitial = rightPadding; 4336 } 4337 } 4338 4339 internalSetPadding( 4340 mUserPaddingLeftInitial, 4341 topPadding >= 0 ? topPadding : mPaddingTop, 4342 mUserPaddingRightInitial, 4343 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4344 4345 if (viewFlagMasks != 0) { 4346 setFlags(viewFlagValues, viewFlagMasks); 4347 } 4348 4349 if (initializeScrollbars) { 4350 initializeScrollbarsInternal(a); 4351 } 4352 4353 if (initializeScrollIndicators) { 4354 initializeScrollIndicatorsInternal(); 4355 } 4356 4357 a.recycle(); 4358 4359 // Needs to be called after mViewFlags is set 4360 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4361 recomputePadding(); 4362 } 4363 4364 if (x != 0 || y != 0) { 4365 scrollTo(x, y); 4366 } 4367 4368 if (transformSet) { 4369 setTranslationX(tx); 4370 setTranslationY(ty); 4371 setTranslationZ(tz); 4372 setElevation(elevation); 4373 setRotation(rotation); 4374 setRotationX(rotationX); 4375 setRotationY(rotationY); 4376 setScaleX(sx); 4377 setScaleY(sy); 4378 } 4379 4380 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4381 setScrollContainer(true); 4382 } 4383 4384 computeOpaqueFlags(); 4385 } 4386 4387 /** 4388 * An implementation of OnClickListener that attempts to lazily load a 4389 * named click handling method from a parent or ancestor context. 4390 */ 4391 private static class DeclaredOnClickListener implements OnClickListener { 4392 private final View mHostView; 4393 private final String mMethodName; 4394 4395 private Method mMethod; 4396 4397 public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) { 4398 mHostView = hostView; 4399 mMethodName = methodName; 4400 } 4401 4402 @Override 4403 public void onClick(@NonNull View v) { 4404 if (mMethod == null) { 4405 mMethod = resolveMethod(mHostView.getContext(), mMethodName); 4406 } 4407 4408 try { 4409 mMethod.invoke(mHostView.getContext(), v); 4410 } catch (IllegalAccessException e) { 4411 throw new IllegalStateException( 4412 "Could not execute non-public method for android:onClick", e); 4413 } catch (InvocationTargetException e) { 4414 throw new IllegalStateException( 4415 "Could not execute method for android:onClick", e); 4416 } 4417 } 4418 4419 @NonNull 4420 private Method resolveMethod(@Nullable Context context, @NonNull String name) { 4421 while (context != null) { 4422 try { 4423 if (!context.isRestricted()) { 4424 return context.getClass().getMethod(mMethodName, View.class); 4425 } 4426 } catch (NoSuchMethodException e) { 4427 // Failed to find method, keep searching up the hierarchy. 4428 } 4429 4430 if (context instanceof ContextWrapper) { 4431 context = ((ContextWrapper) context).getBaseContext(); 4432 } else { 4433 // Can't search up the hierarchy, null out and fail. 4434 context = null; 4435 } 4436 } 4437 4438 final int id = mHostView.getId(); 4439 final String idText = id == NO_ID ? "" : " with id '" 4440 + mHostView.getContext().getResources().getResourceEntryName(id) + "'"; 4441 throw new IllegalStateException("Could not find method " + mMethodName 4442 + "(View) in a parent or ancestor Context for android:onClick " 4443 + "attribute defined on view " + mHostView.getClass() + idText); 4444 } 4445 } 4446 4447 /** 4448 * Non-public constructor for use in testing 4449 */ 4450 View() { 4451 mResources = null; 4452 mRenderNode = RenderNode.create(getClass().getName(), this); 4453 } 4454 4455 private static SparseArray<String> getAttributeMap() { 4456 if (mAttributeMap == null) { 4457 mAttributeMap = new SparseArray<String>(); 4458 } 4459 return mAttributeMap; 4460 } 4461 4462 private void saveAttributeData(AttributeSet attrs, TypedArray a) { 4463 int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2; 4464 mAttributes = new String[length]; 4465 4466 int i = 0; 4467 if (attrs != null) { 4468 for (i = 0; i < attrs.getAttributeCount(); i += 2) { 4469 mAttributes[i] = attrs.getAttributeName(i); 4470 mAttributes[i + 1] = attrs.getAttributeValue(i); 4471 } 4472 4473 } 4474 4475 SparseArray<String> attributeMap = getAttributeMap(); 4476 for (int j = 0; j < a.length(); ++j) { 4477 if (a.hasValue(j)) { 4478 try { 4479 int resourceId = a.getResourceId(j, 0); 4480 if (resourceId == 0) { 4481 continue; 4482 } 4483 4484 String resourceName = attributeMap.get(resourceId); 4485 if (resourceName == null) { 4486 resourceName = a.getResources().getResourceName(resourceId); 4487 attributeMap.put(resourceId, resourceName); 4488 } 4489 4490 mAttributes[i] = resourceName; 4491 mAttributes[i + 1] = a.getText(j).toString(); 4492 i += 2; 4493 } catch (Resources.NotFoundException e) { 4494 // if we can't get the resource name, we just ignore it 4495 } 4496 } 4497 } 4498 } 4499 4500 public String toString() { 4501 StringBuilder out = new StringBuilder(128); 4502 out.append(getClass().getName()); 4503 out.append('{'); 4504 out.append(Integer.toHexString(System.identityHashCode(this))); 4505 out.append(' '); 4506 switch (mViewFlags&VISIBILITY_MASK) { 4507 case VISIBLE: out.append('V'); break; 4508 case INVISIBLE: out.append('I'); break; 4509 case GONE: out.append('G'); break; 4510 default: out.append('.'); break; 4511 } 4512 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4513 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4514 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4515 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4516 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4517 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4518 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4519 out.append((mViewFlags & STYLUS_BUTTON_PRESSABLE) != 0 ? 'S' : '.'); 4520 out.append(' '); 4521 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4522 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4523 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4524 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4525 out.append('p'); 4526 } else { 4527 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4528 } 4529 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4530 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4531 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4532 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4533 out.append(' '); 4534 out.append(mLeft); 4535 out.append(','); 4536 out.append(mTop); 4537 out.append('-'); 4538 out.append(mRight); 4539 out.append(','); 4540 out.append(mBottom); 4541 final int id = getId(); 4542 if (id != NO_ID) { 4543 out.append(" #"); 4544 out.append(Integer.toHexString(id)); 4545 final Resources r = mResources; 4546 if (Resources.resourceHasPackage(id) && r != null) { 4547 try { 4548 String pkgname; 4549 switch (id&0xff000000) { 4550 case 0x7f000000: 4551 pkgname="app"; 4552 break; 4553 case 0x01000000: 4554 pkgname="android"; 4555 break; 4556 default: 4557 pkgname = r.getResourcePackageName(id); 4558 break; 4559 } 4560 String typename = r.getResourceTypeName(id); 4561 String entryname = r.getResourceEntryName(id); 4562 out.append(" "); 4563 out.append(pkgname); 4564 out.append(":"); 4565 out.append(typename); 4566 out.append("/"); 4567 out.append(entryname); 4568 } catch (Resources.NotFoundException e) { 4569 } 4570 } 4571 } 4572 out.append("}"); 4573 return out.toString(); 4574 } 4575 4576 /** 4577 * <p> 4578 * Initializes the fading edges from a given set of styled attributes. This 4579 * method should be called by subclasses that need fading edges and when an 4580 * instance of these subclasses is created programmatically rather than 4581 * being inflated from XML. This method is automatically called when the XML 4582 * is inflated. 4583 * </p> 4584 * 4585 * @param a the styled attributes set to initialize the fading edges from 4586 * 4587 * @removed 4588 */ 4589 protected void initializeFadingEdge(TypedArray a) { 4590 // This method probably shouldn't have been included in the SDK to begin with. 4591 // It relies on 'a' having been initialized using an attribute filter array that is 4592 // not publicly available to the SDK. The old method has been renamed 4593 // to initializeFadingEdgeInternal and hidden for framework use only; 4594 // this one initializes using defaults to make it safe to call for apps. 4595 4596 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4597 4598 initializeFadingEdgeInternal(arr); 4599 4600 arr.recycle(); 4601 } 4602 4603 /** 4604 * <p> 4605 * Initializes the fading edges from a given set of styled attributes. This 4606 * method should be called by subclasses that need fading edges and when an 4607 * instance of these subclasses is created programmatically rather than 4608 * being inflated from XML. This method is automatically called when the XML 4609 * is inflated. 4610 * </p> 4611 * 4612 * @param a the styled attributes set to initialize the fading edges from 4613 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4614 */ 4615 protected void initializeFadingEdgeInternal(TypedArray a) { 4616 initScrollCache(); 4617 4618 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4619 R.styleable.View_fadingEdgeLength, 4620 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4621 } 4622 4623 /** 4624 * Returns the size of the vertical faded edges used to indicate that more 4625 * content in this view is visible. 4626 * 4627 * @return The size in pixels of the vertical faded edge or 0 if vertical 4628 * faded edges are not enabled for this view. 4629 * @attr ref android.R.styleable#View_fadingEdgeLength 4630 */ 4631 public int getVerticalFadingEdgeLength() { 4632 if (isVerticalFadingEdgeEnabled()) { 4633 ScrollabilityCache cache = mScrollCache; 4634 if (cache != null) { 4635 return cache.fadingEdgeLength; 4636 } 4637 } 4638 return 0; 4639 } 4640 4641 /** 4642 * Set the size of the faded edge used to indicate that more content in this 4643 * view is available. Will not change whether the fading edge is enabled; use 4644 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4645 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4646 * for the vertical or horizontal fading edges. 4647 * 4648 * @param length The size in pixels of the faded edge used to indicate that more 4649 * content in this view is visible. 4650 */ 4651 public void setFadingEdgeLength(int length) { 4652 initScrollCache(); 4653 mScrollCache.fadingEdgeLength = length; 4654 } 4655 4656 /** 4657 * Returns the size of the horizontal faded edges used to indicate that more 4658 * content in this view is visible. 4659 * 4660 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4661 * faded edges are not enabled for this view. 4662 * @attr ref android.R.styleable#View_fadingEdgeLength 4663 */ 4664 public int getHorizontalFadingEdgeLength() { 4665 if (isHorizontalFadingEdgeEnabled()) { 4666 ScrollabilityCache cache = mScrollCache; 4667 if (cache != null) { 4668 return cache.fadingEdgeLength; 4669 } 4670 } 4671 return 0; 4672 } 4673 4674 /** 4675 * Returns the width of the vertical scrollbar. 4676 * 4677 * @return The width in pixels of the vertical scrollbar or 0 if there 4678 * is no vertical scrollbar. 4679 */ 4680 public int getVerticalScrollbarWidth() { 4681 ScrollabilityCache cache = mScrollCache; 4682 if (cache != null) { 4683 ScrollBarDrawable scrollBar = cache.scrollBar; 4684 if (scrollBar != null) { 4685 int size = scrollBar.getSize(true); 4686 if (size <= 0) { 4687 size = cache.scrollBarSize; 4688 } 4689 return size; 4690 } 4691 return 0; 4692 } 4693 return 0; 4694 } 4695 4696 /** 4697 * Returns the height of the horizontal scrollbar. 4698 * 4699 * @return The height in pixels of the horizontal scrollbar or 0 if 4700 * there is no horizontal scrollbar. 4701 */ 4702 protected int getHorizontalScrollbarHeight() { 4703 ScrollabilityCache cache = mScrollCache; 4704 if (cache != null) { 4705 ScrollBarDrawable scrollBar = cache.scrollBar; 4706 if (scrollBar != null) { 4707 int size = scrollBar.getSize(false); 4708 if (size <= 0) { 4709 size = cache.scrollBarSize; 4710 } 4711 return size; 4712 } 4713 return 0; 4714 } 4715 return 0; 4716 } 4717 4718 /** 4719 * <p> 4720 * Initializes the scrollbars from a given set of styled attributes. This 4721 * method should be called by subclasses that need scrollbars and when an 4722 * instance of these subclasses is created programmatically rather than 4723 * being inflated from XML. This method is automatically called when the XML 4724 * is inflated. 4725 * </p> 4726 * 4727 * @param a the styled attributes set to initialize the scrollbars from 4728 * 4729 * @removed 4730 */ 4731 protected void initializeScrollbars(TypedArray a) { 4732 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 4733 // using the View filter array which is not available to the SDK. As such, internal 4734 // framework usage now uses initializeScrollbarsInternal and we grab a default 4735 // TypedArray with the right filter instead here. 4736 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4737 4738 initializeScrollbarsInternal(arr); 4739 4740 // We ignored the method parameter. Recycle the one we actually did use. 4741 arr.recycle(); 4742 } 4743 4744 /** 4745 * <p> 4746 * Initializes the scrollbars from a given set of styled attributes. This 4747 * method should be called by subclasses that need scrollbars and when an 4748 * instance of these subclasses is created programmatically rather than 4749 * being inflated from XML. This method is automatically called when the XML 4750 * is inflated. 4751 * </p> 4752 * 4753 * @param a the styled attributes set to initialize the scrollbars from 4754 * @hide 4755 */ 4756 protected void initializeScrollbarsInternal(TypedArray a) { 4757 initScrollCache(); 4758 4759 final ScrollabilityCache scrollabilityCache = mScrollCache; 4760 4761 if (scrollabilityCache.scrollBar == null) { 4762 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4763 scrollabilityCache.scrollBar.setCallback(this); 4764 scrollabilityCache.scrollBar.setState(getDrawableState()); 4765 } 4766 4767 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4768 4769 if (!fadeScrollbars) { 4770 scrollabilityCache.state = ScrollabilityCache.ON; 4771 } 4772 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4773 4774 4775 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4776 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4777 .getScrollBarFadeDuration()); 4778 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4779 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4780 ViewConfiguration.getScrollDefaultDelay()); 4781 4782 4783 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4784 com.android.internal.R.styleable.View_scrollbarSize, 4785 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4786 4787 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4788 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4789 4790 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4791 if (thumb != null) { 4792 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4793 } 4794 4795 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4796 false); 4797 if (alwaysDraw) { 4798 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4799 } 4800 4801 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4802 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4803 4804 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4805 if (thumb != null) { 4806 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4807 } 4808 4809 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4810 false); 4811 if (alwaysDraw) { 4812 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4813 } 4814 4815 // Apply layout direction to the new Drawables if needed 4816 final int layoutDirection = getLayoutDirection(); 4817 if (track != null) { 4818 track.setLayoutDirection(layoutDirection); 4819 } 4820 if (thumb != null) { 4821 thumb.setLayoutDirection(layoutDirection); 4822 } 4823 4824 // Re-apply user/background padding so that scrollbar(s) get added 4825 resolvePadding(); 4826 } 4827 4828 private void initializeScrollIndicatorsInternal() { 4829 // Some day maybe we'll break this into top/left/start/etc. and let the 4830 // client control it. Until then, you can have any scroll indicator you 4831 // want as long as it's a 1dp foreground-colored rectangle. 4832 if (mScrollIndicatorDrawable == null) { 4833 mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material); 4834 } 4835 } 4836 4837 /** 4838 * <p> 4839 * Initalizes the scrollability cache if necessary. 4840 * </p> 4841 */ 4842 private void initScrollCache() { 4843 if (mScrollCache == null) { 4844 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4845 } 4846 } 4847 4848 private ScrollabilityCache getScrollCache() { 4849 initScrollCache(); 4850 return mScrollCache; 4851 } 4852 4853 /** 4854 * Set the position of the vertical scroll bar. Should be one of 4855 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4856 * {@link #SCROLLBAR_POSITION_RIGHT}. 4857 * 4858 * @param position Where the vertical scroll bar should be positioned. 4859 */ 4860 public void setVerticalScrollbarPosition(int position) { 4861 if (mVerticalScrollbarPosition != position) { 4862 mVerticalScrollbarPosition = position; 4863 computeOpaqueFlags(); 4864 resolvePadding(); 4865 } 4866 } 4867 4868 /** 4869 * @return The position where the vertical scroll bar will show, if applicable. 4870 * @see #setVerticalScrollbarPosition(int) 4871 */ 4872 public int getVerticalScrollbarPosition() { 4873 return mVerticalScrollbarPosition; 4874 } 4875 4876 /** 4877 * Sets the state of all scroll indicators. 4878 * <p> 4879 * See {@link #setScrollIndicators(int, int)} for usage information. 4880 * 4881 * @param indicators a bitmask of indicators that should be enabled, or 4882 * {@code 0} to disable all indicators 4883 * @see #setScrollIndicators(int, int) 4884 * @see #getScrollIndicators() 4885 * @attr ref android.R.styleable#View_scrollIndicators 4886 */ 4887 public void setScrollIndicators(@ScrollIndicators int indicators) { 4888 setScrollIndicators(indicators, 4889 SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT); 4890 } 4891 4892 /** 4893 * Sets the state of the scroll indicators specified by the mask. To change 4894 * all scroll indicators at once, see {@link #setScrollIndicators(int)}. 4895 * <p> 4896 * When a scroll indicator is enabled, it will be displayed if the view 4897 * can scroll in the direction of the indicator. 4898 * <p> 4899 * Multiple indicator types may be enabled or disabled by passing the 4900 * logical OR of the desired types. If multiple types are specified, they 4901 * will all be set to the same enabled state. 4902 * <p> 4903 * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators 4904 * 4905 * @param indicators the indicator direction, or the logical OR of multiple 4906 * indicator directions. One or more of: 4907 * <ul> 4908 * <li>{@link #SCROLL_INDICATOR_TOP}</li> 4909 * <li>{@link #SCROLL_INDICATOR_BOTTOM}</li> 4910 * <li>{@link #SCROLL_INDICATOR_LEFT}</li> 4911 * <li>{@link #SCROLL_INDICATOR_RIGHT}</li> 4912 * <li>{@link #SCROLL_INDICATOR_START}</li> 4913 * <li>{@link #SCROLL_INDICATOR_END}</li> 4914 * </ul> 4915 * @see #setScrollIndicators(int) 4916 * @see #getScrollIndicators() 4917 * @attr ref android.R.styleable#View_scrollIndicators 4918 */ 4919 public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) { 4920 // Shift and sanitize mask. 4921 mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 4922 mask &= SCROLL_INDICATORS_PFLAG3_MASK; 4923 4924 // Shift and mask indicators. 4925 indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 4926 indicators &= mask; 4927 4928 // Merge with non-masked flags. 4929 final int updatedFlags = indicators | (mPrivateFlags3 & ~mask); 4930 4931 if (mPrivateFlags3 != updatedFlags) { 4932 mPrivateFlags3 = updatedFlags; 4933 4934 if (indicators != 0) { 4935 initializeScrollIndicatorsInternal(); 4936 } 4937 invalidate(); 4938 } 4939 } 4940 4941 /** 4942 * Returns a bitmask representing the enabled scroll indicators. 4943 * <p> 4944 * For example, if the top and left scroll indicators are enabled and all 4945 * other indicators are disabled, the return value will be 4946 * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}. 4947 * <p> 4948 * To check whether the bottom scroll indicator is enabled, use the value 4949 * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}. 4950 * 4951 * @return a bitmask representing the enabled scroll indicators 4952 */ 4953 @ScrollIndicators 4954 public int getScrollIndicators() { 4955 return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) 4956 >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 4957 } 4958 4959 ListenerInfo getListenerInfo() { 4960 if (mListenerInfo != null) { 4961 return mListenerInfo; 4962 } 4963 mListenerInfo = new ListenerInfo(); 4964 return mListenerInfo; 4965 } 4966 4967 /** 4968 * Register a callback to be invoked when the scroll X or Y positions of 4969 * this view change. 4970 * <p> 4971 * <b>Note:</b> Some views handle scrolling independently from View and may 4972 * have their own separate listeners for scroll-type events. For example, 4973 * {@link android.widget.ListView ListView} allows clients to register an 4974 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 4975 * to listen for changes in list scroll position. 4976 * 4977 * @param l The listener to notify when the scroll X or Y position changes. 4978 * @see android.view.View#getScrollX() 4979 * @see android.view.View#getScrollY() 4980 */ 4981 public void setOnScrollChangeListener(OnScrollChangeListener l) { 4982 getListenerInfo().mOnScrollChangeListener = l; 4983 } 4984 4985 /** 4986 * Register a callback to be invoked when focus of this view changed. 4987 * 4988 * @param l The callback that will run. 4989 */ 4990 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4991 getListenerInfo().mOnFocusChangeListener = l; 4992 } 4993 4994 /** 4995 * Add a listener that will be called when the bounds of the view change due to 4996 * layout processing. 4997 * 4998 * @param listener The listener that will be called when layout bounds change. 4999 */ 5000 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 5001 ListenerInfo li = getListenerInfo(); 5002 if (li.mOnLayoutChangeListeners == null) { 5003 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 5004 } 5005 if (!li.mOnLayoutChangeListeners.contains(listener)) { 5006 li.mOnLayoutChangeListeners.add(listener); 5007 } 5008 } 5009 5010 /** 5011 * Remove a listener for layout changes. 5012 * 5013 * @param listener The listener for layout bounds change. 5014 */ 5015 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 5016 ListenerInfo li = mListenerInfo; 5017 if (li == null || li.mOnLayoutChangeListeners == null) { 5018 return; 5019 } 5020 li.mOnLayoutChangeListeners.remove(listener); 5021 } 5022 5023 /** 5024 * Add a listener for attach state changes. 5025 * 5026 * This listener will be called whenever this view is attached or detached 5027 * from a window. Remove the listener using 5028 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 5029 * 5030 * @param listener Listener to attach 5031 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 5032 */ 5033 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5034 ListenerInfo li = getListenerInfo(); 5035 if (li.mOnAttachStateChangeListeners == null) { 5036 li.mOnAttachStateChangeListeners 5037 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 5038 } 5039 li.mOnAttachStateChangeListeners.add(listener); 5040 } 5041 5042 /** 5043 * Remove a listener for attach state changes. The listener will receive no further 5044 * notification of window attach/detach events. 5045 * 5046 * @param listener Listener to remove 5047 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 5048 */ 5049 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5050 ListenerInfo li = mListenerInfo; 5051 if (li == null || li.mOnAttachStateChangeListeners == null) { 5052 return; 5053 } 5054 li.mOnAttachStateChangeListeners.remove(listener); 5055 } 5056 5057 /** 5058 * Returns the focus-change callback registered for this view. 5059 * 5060 * @return The callback, or null if one is not registered. 5061 */ 5062 public OnFocusChangeListener getOnFocusChangeListener() { 5063 ListenerInfo li = mListenerInfo; 5064 return li != null ? li.mOnFocusChangeListener : null; 5065 } 5066 5067 /** 5068 * Register a callback to be invoked when this view is clicked. If this view is not 5069 * clickable, it becomes clickable. 5070 * 5071 * @param l The callback that will run 5072 * 5073 * @see #setClickable(boolean) 5074 */ 5075 public void setOnClickListener(@Nullable OnClickListener l) { 5076 if (!isClickable()) { 5077 setClickable(true); 5078 } 5079 getListenerInfo().mOnClickListener = l; 5080 } 5081 5082 /** 5083 * Return whether this view has an attached OnClickListener. Returns 5084 * true if there is a listener, false if there is none. 5085 */ 5086 public boolean hasOnClickListeners() { 5087 ListenerInfo li = mListenerInfo; 5088 return (li != null && li.mOnClickListener != null); 5089 } 5090 5091 /** 5092 * Register a callback to be invoked when this view is clicked and held. If this view is not 5093 * long clickable, it becomes long clickable. 5094 * 5095 * @param l The callback that will run 5096 * 5097 * @see #setLongClickable(boolean) 5098 */ 5099 public void setOnLongClickListener(@Nullable OnLongClickListener l) { 5100 if (!isLongClickable()) { 5101 setLongClickable(true); 5102 } 5103 getListenerInfo().mOnLongClickListener = l; 5104 } 5105 5106 /** 5107 * Register a callback to be invoked when this view is touched with a stylus and the button is 5108 * pressed. 5109 * 5110 * @param l The callback that will run 5111 * @see #setStylusButtonPressable(boolean) 5112 */ 5113 public void setOnStylusButtonPressListener(@Nullable OnStylusButtonPressListener l) { 5114 if (!isStylusButtonPressable()) { 5115 setStylusButtonPressable(true); 5116 } 5117 getListenerInfo().mOnStylusButtonPressListener = l; 5118 } 5119 5120 /** 5121 * Register a callback to be invoked when the context menu for this view is 5122 * being built. If this view is not long clickable, it becomes long clickable. 5123 * 5124 * @param l The callback that will run 5125 * 5126 */ 5127 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 5128 if (!isLongClickable()) { 5129 setLongClickable(true); 5130 } 5131 getListenerInfo().mOnCreateContextMenuListener = l; 5132 } 5133 5134 /** 5135 * Call this view's OnClickListener, if it is defined. Performs all normal 5136 * actions associated with clicking: reporting accessibility event, playing 5137 * a sound, etc. 5138 * 5139 * @return True there was an assigned OnClickListener that was called, false 5140 * otherwise is returned. 5141 */ 5142 public boolean performClick() { 5143 final boolean result; 5144 final ListenerInfo li = mListenerInfo; 5145 if (li != null && li.mOnClickListener != null) { 5146 playSoundEffect(SoundEffectConstants.CLICK); 5147 li.mOnClickListener.onClick(this); 5148 result = true; 5149 } else { 5150 result = false; 5151 } 5152 5153 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 5154 return result; 5155 } 5156 5157 /** 5158 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 5159 * this only calls the listener, and does not do any associated clicking 5160 * actions like reporting an accessibility event. 5161 * 5162 * @return True there was an assigned OnClickListener that was called, false 5163 * otherwise is returned. 5164 */ 5165 public boolean callOnClick() { 5166 ListenerInfo li = mListenerInfo; 5167 if (li != null && li.mOnClickListener != null) { 5168 li.mOnClickListener.onClick(this); 5169 return true; 5170 } 5171 return false; 5172 } 5173 5174 /** 5175 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 5176 * OnLongClickListener did not consume the event. 5177 * 5178 * @return True if one of the above receivers consumed the event, false otherwise. 5179 */ 5180 public boolean performLongClick() { 5181 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 5182 5183 boolean handled = false; 5184 ListenerInfo li = mListenerInfo; 5185 if (li != null && li.mOnLongClickListener != null) { 5186 handled = li.mOnLongClickListener.onLongClick(View.this); 5187 } 5188 if (!handled) { 5189 handled = showContextMenu(); 5190 } 5191 if (handled) { 5192 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 5193 } 5194 return handled; 5195 } 5196 5197 /** 5198 * Call this view's OnStylusButtonPressListener, if it is defined. 5199 * 5200 * @return True if there was an assigned OnStylusButtonPressListener that consumed the event, 5201 * false otherwise. 5202 */ 5203 public boolean performStylusButtonPress() { 5204 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_STYLUS_BUTTON_PRESSED); 5205 5206 boolean handled = false; 5207 ListenerInfo li = mListenerInfo; 5208 if (li != null && li.mOnStylusButtonPressListener != null) { 5209 handled = li.mOnStylusButtonPressListener.onStylusButtonPress(View.this); 5210 } 5211 if (handled) { 5212 performHapticFeedback(HapticFeedbackConstants.STYLUS_BUTTON_PRESS); 5213 } 5214 return handled; 5215 } 5216 5217 /** 5218 * Checks for a stylus button press and calls the listener. 5219 * 5220 * @param event The event. 5221 * @return True if the event was consumed. 5222 */ 5223 private boolean performStylusActionOnButtonPress(MotionEvent event) { 5224 if (isStylusButtonPressable() && !mInStylusButtonPress 5225 && !mHasPerformedLongPress && event.isStylusButtonPressed()) { 5226 if (performStylusButtonPress()) { 5227 mInStylusButtonPress = true; 5228 setPressed(true, event.getX(), event.getY()); 5229 removeTapCallback(); 5230 removeLongPressCallback(); 5231 return true; 5232 } 5233 } 5234 return false; 5235 } 5236 5237 /** 5238 * Performs button-related actions during a touch down event. 5239 * 5240 * @param event The event. 5241 * @return True if the down was consumed. 5242 * 5243 * @hide 5244 */ 5245 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 5246 if (event.getToolType(0) == MotionEvent.TOOL_TYPE_MOUSE && 5247 (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 5248 showContextMenu(event.getX(), event.getY(), event.getMetaState()); 5249 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 5250 return true; 5251 } 5252 return false; 5253 } 5254 5255 /** 5256 * Bring up the context menu for this view. 5257 * 5258 * @return Whether a context menu was displayed. 5259 */ 5260 public boolean showContextMenu() { 5261 return getParent().showContextMenuForChild(this); 5262 } 5263 5264 /** 5265 * Bring up the context menu for this view, referring to the item under the specified point. 5266 * 5267 * @param x The referenced x coordinate. 5268 * @param y The referenced y coordinate. 5269 * @param metaState The keyboard modifiers that were pressed. 5270 * @return Whether a context menu was displayed. 5271 * 5272 * @hide 5273 */ 5274 public boolean showContextMenu(float x, float y, int metaState) { 5275 return showContextMenu(); 5276 } 5277 5278 /** 5279 * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}. 5280 * 5281 * @param callback Callback that will control the lifecycle of the action mode 5282 * @return The new action mode if it is started, null otherwise 5283 * 5284 * @see ActionMode 5285 * @see #startActionMode(android.view.ActionMode.Callback, int) 5286 */ 5287 public ActionMode startActionMode(ActionMode.Callback callback) { 5288 return startActionMode(callback, ActionMode.TYPE_PRIMARY); 5289 } 5290 5291 /** 5292 * Start an action mode with the given type. 5293 * 5294 * @param callback Callback that will control the lifecycle of the action mode 5295 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}. 5296 * @return The new action mode if it is started, null otherwise 5297 * 5298 * @see ActionMode 5299 */ 5300 public ActionMode startActionMode(ActionMode.Callback callback, int type) { 5301 ViewParent parent = getParent(); 5302 if (parent == null) return null; 5303 try { 5304 return parent.startActionModeForChild(this, callback, type); 5305 } catch (AbstractMethodError ame) { 5306 // Older implementations of custom views might not implement this. 5307 return parent.startActionModeForChild(this, callback); 5308 } 5309 } 5310 5311 /** 5312 * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's 5313 * Context, creating a unique View identifier to retrieve the result. 5314 * 5315 * @param intent The Intent to be started. 5316 * @param requestCode The request code to use. 5317 * @hide 5318 */ 5319 public void startActivityForResult(Intent intent, int requestCode) { 5320 mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this); 5321 getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null); 5322 } 5323 5324 /** 5325 * If this View corresponds to the calling who, dispatches the activity result. 5326 * @param who The identifier for the targeted View to receive the result. 5327 * @param requestCode The integer request code originally supplied to 5328 * startActivityForResult(), allowing you to identify who this 5329 * result came from. 5330 * @param resultCode The integer result code returned by the child activity 5331 * through its setResult(). 5332 * @param data An Intent, which can return result data to the caller 5333 * (various data can be attached to Intent "extras"). 5334 * @return {@code true} if the activity result was dispatched. 5335 * @hide 5336 */ 5337 public boolean dispatchActivityResult( 5338 String who, int requestCode, int resultCode, Intent data) { 5339 if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) { 5340 onActivityResult(requestCode, resultCode, data); 5341 mStartActivityRequestWho = null; 5342 return true; 5343 } 5344 return false; 5345 } 5346 5347 /** 5348 * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}. 5349 * 5350 * @param requestCode The integer request code originally supplied to 5351 * startActivityForResult(), allowing you to identify who this 5352 * result came from. 5353 * @param resultCode The integer result code returned by the child activity 5354 * through its setResult(). 5355 * @param data An Intent, which can return result data to the caller 5356 * (various data can be attached to Intent "extras"). 5357 * @hide 5358 */ 5359 public void onActivityResult(int requestCode, int resultCode, Intent data) { 5360 // Do nothing. 5361 } 5362 5363 /** 5364 * Register a callback to be invoked when a hardware key is pressed in this view. 5365 * Key presses in software input methods will generally not trigger the methods of 5366 * this listener. 5367 * @param l the key listener to attach to this view 5368 */ 5369 public void setOnKeyListener(OnKeyListener l) { 5370 getListenerInfo().mOnKeyListener = l; 5371 } 5372 5373 /** 5374 * Register a callback to be invoked when a touch event is sent to this view. 5375 * @param l the touch listener to attach to this view 5376 */ 5377 public void setOnTouchListener(OnTouchListener l) { 5378 getListenerInfo().mOnTouchListener = l; 5379 } 5380 5381 /** 5382 * Register a callback to be invoked when a generic motion event is sent to this view. 5383 * @param l the generic motion listener to attach to this view 5384 */ 5385 public void setOnGenericMotionListener(OnGenericMotionListener l) { 5386 getListenerInfo().mOnGenericMotionListener = l; 5387 } 5388 5389 /** 5390 * Register a callback to be invoked when a hover event is sent to this view. 5391 * @param l the hover listener to attach to this view 5392 */ 5393 public void setOnHoverListener(OnHoverListener l) { 5394 getListenerInfo().mOnHoverListener = l; 5395 } 5396 5397 /** 5398 * Register a drag event listener callback object for this View. The parameter is 5399 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 5400 * View, the system calls the 5401 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 5402 * @param l An implementation of {@link android.view.View.OnDragListener}. 5403 */ 5404 public void setOnDragListener(OnDragListener l) { 5405 getListenerInfo().mOnDragListener = l; 5406 } 5407 5408 /** 5409 * Give this view focus. This will cause 5410 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 5411 * 5412 * Note: this does not check whether this {@link View} should get focus, it just 5413 * gives it focus no matter what. It should only be called internally by framework 5414 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 5415 * 5416 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 5417 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 5418 * focus moved when requestFocus() is called. It may not always 5419 * apply, in which case use the default View.FOCUS_DOWN. 5420 * @param previouslyFocusedRect The rectangle of the view that had focus 5421 * prior in this View's coordinate system. 5422 */ 5423 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 5424 if (DBG) { 5425 System.out.println(this + " requestFocus()"); 5426 } 5427 5428 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 5429 mPrivateFlags |= PFLAG_FOCUSED; 5430 5431 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 5432 5433 if (mParent != null) { 5434 mParent.requestChildFocus(this, this); 5435 } 5436 5437 if (mAttachInfo != null) { 5438 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 5439 } 5440 5441 onFocusChanged(true, direction, previouslyFocusedRect); 5442 refreshDrawableState(); 5443 } 5444 } 5445 5446 /** 5447 * Populates <code>outRect</code> with the hotspot bounds. By default, 5448 * the hotspot bounds are identical to the screen bounds. 5449 * 5450 * @param outRect rect to populate with hotspot bounds 5451 * @hide Only for internal use by views and widgets. 5452 */ 5453 public void getHotspotBounds(Rect outRect) { 5454 final Drawable background = getBackground(); 5455 if (background != null) { 5456 background.getHotspotBounds(outRect); 5457 } else { 5458 getBoundsOnScreen(outRect); 5459 } 5460 } 5461 5462 /** 5463 * Request that a rectangle of this view be visible on the screen, 5464 * scrolling if necessary just enough. 5465 * 5466 * <p>A View should call this if it maintains some notion of which part 5467 * of its content is interesting. For example, a text editing view 5468 * should call this when its cursor moves. 5469 * 5470 * @param rectangle The rectangle. 5471 * @return Whether any parent scrolled. 5472 */ 5473 public boolean requestRectangleOnScreen(Rect rectangle) { 5474 return requestRectangleOnScreen(rectangle, false); 5475 } 5476 5477 /** 5478 * Request that a rectangle of this view be visible on the screen, 5479 * scrolling if necessary just enough. 5480 * 5481 * <p>A View should call this if it maintains some notion of which part 5482 * of its content is interesting. For example, a text editing view 5483 * should call this when its cursor moves. 5484 * 5485 * <p>When <code>immediate</code> is set to true, scrolling will not be 5486 * animated. 5487 * 5488 * @param rectangle The rectangle. 5489 * @param immediate True to forbid animated scrolling, false otherwise 5490 * @return Whether any parent scrolled. 5491 */ 5492 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 5493 if (mParent == null) { 5494 return false; 5495 } 5496 5497 View child = this; 5498 5499 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 5500 position.set(rectangle); 5501 5502 ViewParent parent = mParent; 5503 boolean scrolled = false; 5504 while (parent != null) { 5505 rectangle.set((int) position.left, (int) position.top, 5506 (int) position.right, (int) position.bottom); 5507 5508 scrolled |= parent.requestChildRectangleOnScreen(child, 5509 rectangle, immediate); 5510 5511 if (!child.hasIdentityMatrix()) { 5512 child.getMatrix().mapRect(position); 5513 } 5514 5515 position.offset(child.mLeft, child.mTop); 5516 5517 if (!(parent instanceof View)) { 5518 break; 5519 } 5520 5521 View parentView = (View) parent; 5522 5523 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 5524 5525 child = parentView; 5526 parent = child.getParent(); 5527 } 5528 5529 return scrolled; 5530 } 5531 5532 /** 5533 * Called when this view wants to give up focus. If focus is cleared 5534 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 5535 * <p> 5536 * <strong>Note:</strong> When a View clears focus the framework is trying 5537 * to give focus to the first focusable View from the top. Hence, if this 5538 * View is the first from the top that can take focus, then all callbacks 5539 * related to clearing focus will be invoked after which the framework will 5540 * give focus to this view. 5541 * </p> 5542 */ 5543 public void clearFocus() { 5544 if (DBG) { 5545 System.out.println(this + " clearFocus()"); 5546 } 5547 5548 clearFocusInternal(null, true, true); 5549 } 5550 5551 /** 5552 * Clears focus from the view, optionally propagating the change up through 5553 * the parent hierarchy and requesting that the root view place new focus. 5554 * 5555 * @param propagate whether to propagate the change up through the parent 5556 * hierarchy 5557 * @param refocus when propagate is true, specifies whether to request the 5558 * root view place new focus 5559 */ 5560 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 5561 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 5562 mPrivateFlags &= ~PFLAG_FOCUSED; 5563 5564 if (propagate && mParent != null) { 5565 mParent.clearChildFocus(this); 5566 } 5567 5568 onFocusChanged(false, 0, null); 5569 refreshDrawableState(); 5570 5571 if (propagate && (!refocus || !rootViewRequestFocus())) { 5572 notifyGlobalFocusCleared(this); 5573 } 5574 } 5575 } 5576 5577 void notifyGlobalFocusCleared(View oldFocus) { 5578 if (oldFocus != null && mAttachInfo != null) { 5579 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 5580 } 5581 } 5582 5583 boolean rootViewRequestFocus() { 5584 final View root = getRootView(); 5585 return root != null && root.requestFocus(); 5586 } 5587 5588 /** 5589 * Called internally by the view system when a new view is getting focus. 5590 * This is what clears the old focus. 5591 * <p> 5592 * <b>NOTE:</b> The parent view's focused child must be updated manually 5593 * after calling this method. Otherwise, the view hierarchy may be left in 5594 * an inconstent state. 5595 */ 5596 void unFocus(View focused) { 5597 if (DBG) { 5598 System.out.println(this + " unFocus()"); 5599 } 5600 5601 clearFocusInternal(focused, false, false); 5602 } 5603 5604 /** 5605 * Returns true if this view has focus itself, or is the ancestor of the 5606 * view that has focus. 5607 * 5608 * @return True if this view has or contains focus, false otherwise. 5609 */ 5610 @ViewDebug.ExportedProperty(category = "focus") 5611 public boolean hasFocus() { 5612 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5613 } 5614 5615 /** 5616 * Returns true if this view is focusable or if it contains a reachable View 5617 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 5618 * is a View whose parents do not block descendants focus. 5619 * 5620 * Only {@link #VISIBLE} views are considered focusable. 5621 * 5622 * @return True if the view is focusable or if the view contains a focusable 5623 * View, false otherwise. 5624 * 5625 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 5626 * @see ViewGroup#getTouchscreenBlocksFocus() 5627 */ 5628 public boolean hasFocusable() { 5629 if (!isFocusableInTouchMode()) { 5630 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 5631 final ViewGroup g = (ViewGroup) p; 5632 if (g.shouldBlockFocusForTouchscreen()) { 5633 return false; 5634 } 5635 } 5636 } 5637 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 5638 } 5639 5640 /** 5641 * Called by the view system when the focus state of this view changes. 5642 * When the focus change event is caused by directional navigation, direction 5643 * and previouslyFocusedRect provide insight into where the focus is coming from. 5644 * When overriding, be sure to call up through to the super class so that 5645 * the standard focus handling will occur. 5646 * 5647 * @param gainFocus True if the View has focus; false otherwise. 5648 * @param direction The direction focus has moved when requestFocus() 5649 * is called to give this view focus. Values are 5650 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5651 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5652 * It may not always apply, in which case use the default. 5653 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5654 * system, of the previously focused view. If applicable, this will be 5655 * passed in as finer grained information about where the focus is coming 5656 * from (in addition to direction). Will be <code>null</code> otherwise. 5657 */ 5658 @CallSuper 5659 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5660 @Nullable Rect previouslyFocusedRect) { 5661 if (gainFocus) { 5662 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5663 } else { 5664 notifyViewAccessibilityStateChangedIfNeeded( 5665 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5666 } 5667 5668 InputMethodManager imm = InputMethodManager.peekInstance(); 5669 if (!gainFocus) { 5670 if (isPressed()) { 5671 setPressed(false); 5672 } 5673 if (imm != null && mAttachInfo != null 5674 && mAttachInfo.mHasWindowFocus) { 5675 imm.focusOut(this); 5676 } 5677 onFocusLost(); 5678 } else if (imm != null && mAttachInfo != null 5679 && mAttachInfo.mHasWindowFocus) { 5680 imm.focusIn(this); 5681 } 5682 5683 invalidate(true); 5684 ListenerInfo li = mListenerInfo; 5685 if (li != null && li.mOnFocusChangeListener != null) { 5686 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5687 } 5688 5689 if (mAttachInfo != null) { 5690 mAttachInfo.mKeyDispatchState.reset(this); 5691 } 5692 } 5693 5694 /** 5695 * Sends an accessibility event of the given type. If accessibility is 5696 * not enabled this method has no effect. The default implementation calls 5697 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5698 * to populate information about the event source (this View), then calls 5699 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5700 * populate the text content of the event source including its descendants, 5701 * and last calls 5702 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5703 * on its parent to request sending of the event to interested parties. 5704 * <p> 5705 * If an {@link AccessibilityDelegate} has been specified via calling 5706 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5707 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5708 * responsible for handling this call. 5709 * </p> 5710 * 5711 * @param eventType The type of the event to send, as defined by several types from 5712 * {@link android.view.accessibility.AccessibilityEvent}, such as 5713 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5714 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5715 * 5716 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5717 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5718 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5719 * @see AccessibilityDelegate 5720 */ 5721 public void sendAccessibilityEvent(int eventType) { 5722 if (mAccessibilityDelegate != null) { 5723 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5724 } else { 5725 sendAccessibilityEventInternal(eventType); 5726 } 5727 } 5728 5729 /** 5730 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5731 * {@link AccessibilityEvent} to make an announcement which is related to some 5732 * sort of a context change for which none of the events representing UI transitions 5733 * is a good fit. For example, announcing a new page in a book. If accessibility 5734 * is not enabled this method does nothing. 5735 * 5736 * @param text The announcement text. 5737 */ 5738 public void announceForAccessibility(CharSequence text) { 5739 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5740 AccessibilityEvent event = AccessibilityEvent.obtain( 5741 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5742 onInitializeAccessibilityEvent(event); 5743 event.getText().add(text); 5744 event.setContentDescription(null); 5745 mParent.requestSendAccessibilityEvent(this, event); 5746 } 5747 } 5748 5749 /** 5750 * @see #sendAccessibilityEvent(int) 5751 * 5752 * Note: Called from the default {@link AccessibilityDelegate}. 5753 * 5754 * @hide 5755 */ 5756 public void sendAccessibilityEventInternal(int eventType) { 5757 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5758 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5759 } 5760 } 5761 5762 /** 5763 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5764 * takes as an argument an empty {@link AccessibilityEvent} and does not 5765 * perform a check whether accessibility is enabled. 5766 * <p> 5767 * If an {@link AccessibilityDelegate} has been specified via calling 5768 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5769 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5770 * is responsible for handling this call. 5771 * </p> 5772 * 5773 * @param event The event to send. 5774 * 5775 * @see #sendAccessibilityEvent(int) 5776 */ 5777 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5778 if (mAccessibilityDelegate != null) { 5779 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5780 } else { 5781 sendAccessibilityEventUncheckedInternal(event); 5782 } 5783 } 5784 5785 /** 5786 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5787 * 5788 * Note: Called from the default {@link AccessibilityDelegate}. 5789 * 5790 * @hide 5791 */ 5792 public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5793 if (!isShown()) { 5794 return; 5795 } 5796 onInitializeAccessibilityEvent(event); 5797 // Only a subset of accessibility events populates text content. 5798 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5799 dispatchPopulateAccessibilityEvent(event); 5800 } 5801 // In the beginning we called #isShown(), so we know that getParent() is not null. 5802 getParent().requestSendAccessibilityEvent(this, event); 5803 } 5804 5805 /** 5806 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5807 * to its children for adding their text content to the event. Note that the 5808 * event text is populated in a separate dispatch path since we add to the 5809 * event not only the text of the source but also the text of all its descendants. 5810 * A typical implementation will call 5811 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5812 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5813 * on each child. Override this method if custom population of the event text 5814 * content is required. 5815 * <p> 5816 * If an {@link AccessibilityDelegate} has been specified via calling 5817 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5818 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5819 * is responsible for handling this call. 5820 * </p> 5821 * <p> 5822 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5823 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5824 * </p> 5825 * 5826 * @param event The event. 5827 * 5828 * @return True if the event population was completed. 5829 */ 5830 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5831 if (mAccessibilityDelegate != null) { 5832 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5833 } else { 5834 return dispatchPopulateAccessibilityEventInternal(event); 5835 } 5836 } 5837 5838 /** 5839 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5840 * 5841 * Note: Called from the default {@link AccessibilityDelegate}. 5842 * 5843 * @hide 5844 */ 5845 public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5846 onPopulateAccessibilityEvent(event); 5847 return false; 5848 } 5849 5850 /** 5851 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5852 * giving a chance to this View to populate the accessibility event with its 5853 * text content. While this method is free to modify event 5854 * attributes other than text content, doing so should normally be performed in 5855 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5856 * <p> 5857 * Example: Adding formatted date string to an accessibility event in addition 5858 * to the text added by the super implementation: 5859 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5860 * super.onPopulateAccessibilityEvent(event); 5861 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5862 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5863 * mCurrentDate.getTimeInMillis(), flags); 5864 * event.getText().add(selectedDateUtterance); 5865 * }</pre> 5866 * <p> 5867 * If an {@link AccessibilityDelegate} has been specified via calling 5868 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5869 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5870 * is responsible for handling this call. 5871 * </p> 5872 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5873 * information to the event, in case the default implementation has basic information to add. 5874 * </p> 5875 * 5876 * @param event The accessibility event which to populate. 5877 * 5878 * @see #sendAccessibilityEvent(int) 5879 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5880 */ 5881 @CallSuper 5882 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5883 if (mAccessibilityDelegate != null) { 5884 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5885 } else { 5886 onPopulateAccessibilityEventInternal(event); 5887 } 5888 } 5889 5890 /** 5891 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5892 * 5893 * Note: Called from the default {@link AccessibilityDelegate}. 5894 * 5895 * @hide 5896 */ 5897 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5898 } 5899 5900 /** 5901 * Initializes an {@link AccessibilityEvent} with information about 5902 * this View which is the event source. In other words, the source of 5903 * an accessibility event is the view whose state change triggered firing 5904 * the event. 5905 * <p> 5906 * Example: Setting the password property of an event in addition 5907 * to properties set by the super implementation: 5908 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5909 * super.onInitializeAccessibilityEvent(event); 5910 * event.setPassword(true); 5911 * }</pre> 5912 * <p> 5913 * If an {@link AccessibilityDelegate} has been specified via calling 5914 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5915 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5916 * is responsible for handling this call. 5917 * </p> 5918 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5919 * information to the event, in case the default implementation has basic information to add. 5920 * </p> 5921 * @param event The event to initialize. 5922 * 5923 * @see #sendAccessibilityEvent(int) 5924 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5925 */ 5926 @CallSuper 5927 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5928 if (mAccessibilityDelegate != null) { 5929 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5930 } else { 5931 onInitializeAccessibilityEventInternal(event); 5932 } 5933 } 5934 5935 /** 5936 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5937 * 5938 * Note: Called from the default {@link AccessibilityDelegate}. 5939 * 5940 * @hide 5941 */ 5942 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5943 event.setSource(this); 5944 event.setClassName(getAccessibilityClassName()); 5945 event.setPackageName(getContext().getPackageName()); 5946 event.setEnabled(isEnabled()); 5947 event.setContentDescription(mContentDescription); 5948 5949 switch (event.getEventType()) { 5950 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5951 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5952 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5953 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5954 event.setItemCount(focusablesTempList.size()); 5955 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5956 if (mAttachInfo != null) { 5957 focusablesTempList.clear(); 5958 } 5959 } break; 5960 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5961 CharSequence text = getIterableTextForAccessibility(); 5962 if (text != null && text.length() > 0) { 5963 event.setFromIndex(getAccessibilitySelectionStart()); 5964 event.setToIndex(getAccessibilitySelectionEnd()); 5965 event.setItemCount(text.length()); 5966 } 5967 } break; 5968 } 5969 } 5970 5971 /** 5972 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5973 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5974 * This method is responsible for obtaining an accessibility node info from a 5975 * pool of reusable instances and calling 5976 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5977 * initialize the former. 5978 * <p> 5979 * Note: The client is responsible for recycling the obtained instance by calling 5980 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5981 * </p> 5982 * 5983 * @return A populated {@link AccessibilityNodeInfo}. 5984 * 5985 * @see AccessibilityNodeInfo 5986 */ 5987 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5988 if (mAccessibilityDelegate != null) { 5989 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5990 } else { 5991 return createAccessibilityNodeInfoInternal(); 5992 } 5993 } 5994 5995 /** 5996 * @see #createAccessibilityNodeInfo() 5997 * 5998 * @hide 5999 */ 6000 public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 6001 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6002 if (provider != null) { 6003 return provider.createAccessibilityNodeInfo(View.NO_ID); 6004 } else { 6005 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 6006 onInitializeAccessibilityNodeInfo(info); 6007 return info; 6008 } 6009 } 6010 6011 /** 6012 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 6013 * The base implementation sets: 6014 * <ul> 6015 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 6016 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 6017 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 6018 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 6019 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 6020 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 6021 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 6022 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 6023 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 6024 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 6025 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 6026 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 6027 * <li>{@link AccessibilityNodeInfo#setStylusButtonPressable(boolean)}</li> 6028 * </ul> 6029 * <p> 6030 * Subclasses should override this method, call the super implementation, 6031 * and set additional attributes. 6032 * </p> 6033 * <p> 6034 * If an {@link AccessibilityDelegate} has been specified via calling 6035 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6036 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 6037 * is responsible for handling this call. 6038 * </p> 6039 * 6040 * @param info The instance to initialize. 6041 */ 6042 @CallSuper 6043 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 6044 if (mAccessibilityDelegate != null) { 6045 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 6046 } else { 6047 onInitializeAccessibilityNodeInfoInternal(info); 6048 } 6049 } 6050 6051 /** 6052 * Gets the location of this view in screen coordinates. 6053 * 6054 * @param outRect The output location 6055 * @hide 6056 */ 6057 public void getBoundsOnScreen(Rect outRect) { 6058 getBoundsOnScreen(outRect, false); 6059 } 6060 6061 /** 6062 * Gets the location of this view in screen coordinates. 6063 * 6064 * @param outRect The output location 6065 * @param clipToParent Whether to clip child bounds to the parent ones. 6066 * @hide 6067 */ 6068 public void getBoundsOnScreen(Rect outRect, boolean clipToParent) { 6069 if (mAttachInfo == null) { 6070 return; 6071 } 6072 6073 RectF position = mAttachInfo.mTmpTransformRect; 6074 position.set(0, 0, mRight - mLeft, mBottom - mTop); 6075 6076 if (!hasIdentityMatrix()) { 6077 getMatrix().mapRect(position); 6078 } 6079 6080 position.offset(mLeft, mTop); 6081 6082 ViewParent parent = mParent; 6083 while (parent instanceof View) { 6084 View parentView = (View) parent; 6085 6086 position.offset(-parentView.mScrollX, -parentView.mScrollY); 6087 6088 if (clipToParent) { 6089 position.left = Math.max(position.left, 0); 6090 position.top = Math.max(position.top, 0); 6091 position.right = Math.min(position.right, parentView.getWidth()); 6092 position.bottom = Math.min(position.bottom, parentView.getHeight()); 6093 } 6094 6095 if (!parentView.hasIdentityMatrix()) { 6096 parentView.getMatrix().mapRect(position); 6097 } 6098 6099 position.offset(parentView.mLeft, parentView.mTop); 6100 6101 parent = parentView.mParent; 6102 } 6103 6104 if (parent instanceof ViewRootImpl) { 6105 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 6106 position.offset(0, -viewRootImpl.mCurScrollY); 6107 } 6108 6109 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 6110 6111 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 6112 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 6113 } 6114 6115 /** 6116 * Return the class name of this object to be used for accessibility purposes. 6117 * Subclasses should only override this if they are implementing something that 6118 * should be seen as a completely new class of view when used by accessibility, 6119 * unrelated to the class it is deriving from. This is used to fill in 6120 * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}. 6121 */ 6122 public CharSequence getAccessibilityClassName() { 6123 return View.class.getName(); 6124 } 6125 6126 /** 6127 * Called when assist structure is being retrieved from a view as part of 6128 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}. 6129 * @param structure Fill in with structured view data. The default implementation 6130 * fills in all data that can be inferred from the view itself. 6131 */ 6132 public void onProvideStructure(ViewStructure structure) { 6133 final int id = mID; 6134 if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0 6135 && (id&0x0000ffff) != 0) { 6136 String pkg, type, entry; 6137 try { 6138 final Resources res = getResources(); 6139 entry = res.getResourceEntryName(id); 6140 type = res.getResourceTypeName(id); 6141 pkg = res.getResourcePackageName(id); 6142 } catch (Resources.NotFoundException e) { 6143 entry = type = pkg = null; 6144 } 6145 structure.setId(id, pkg, type, entry); 6146 } else { 6147 structure.setId(id, null, null, null); 6148 } 6149 structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop); 6150 structure.setVisibility(getVisibility()); 6151 structure.setEnabled(isEnabled()); 6152 if (isClickable()) { 6153 structure.setClickable(true); 6154 } 6155 if (isFocusable()) { 6156 structure.setFocusable(true); 6157 } 6158 if (isFocused()) { 6159 structure.setFocused(true); 6160 } 6161 if (isAccessibilityFocused()) { 6162 structure.setAccessibilityFocused(true); 6163 } 6164 if (isSelected()) { 6165 structure.setSelected(true); 6166 } 6167 if (isActivated()) { 6168 structure.setActivated(true); 6169 } 6170 if (isLongClickable()) { 6171 structure.setLongClickable(true); 6172 } 6173 if (this instanceof Checkable) { 6174 structure.setCheckable(true); 6175 if (((Checkable)this).isChecked()) { 6176 structure.setChecked(true); 6177 } 6178 } 6179 if (isStylusButtonPressable()) { 6180 structure.setStylusButtonPressable(true); 6181 } 6182 structure.setClassName(getAccessibilityClassName().toString()); 6183 structure.setContentDescription(getContentDescription()); 6184 } 6185 6186 /** @hide */ 6187 public void onProvideAssistStructure(ViewStructure structure) { 6188 onProvideStructure(structure); 6189 } 6190 6191 /** 6192 * Called when assist structure is being retrieved from a view as part of 6193 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to 6194 * generate additional virtual structure under this view. The defaullt implementation 6195 * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the 6196 * view's virtual accessibility nodes, if any. You can override this for a more 6197 * optimal implementation providing this data. 6198 */ 6199 public void onProvideVirtualStructure(ViewStructure structure) { 6200 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6201 if (provider != null) { 6202 AccessibilityNodeInfo info = createAccessibilityNodeInfo(); 6203 Log.i("View", "Provider of " + this + ": children=" + info.getChildCount()); 6204 structure.setChildCount(1); 6205 ViewStructure root = structure.newChild(0); 6206 populateVirtualStructure(root, provider, info); 6207 info.recycle(); 6208 } 6209 } 6210 6211 /** @hide */ 6212 public void onProvideVirtualAssistStructure(ViewStructure structure) { 6213 onProvideVirtualStructure(structure); 6214 } 6215 6216 private void populateVirtualStructure(ViewStructure structure, 6217 AccessibilityNodeProvider provider, AccessibilityNodeInfo info) { 6218 structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()), 6219 null, null, null); 6220 Rect rect = structure.getTempRect(); 6221 info.getBoundsInParent(rect); 6222 structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height()); 6223 structure.setVisibility(VISIBLE); 6224 structure.setEnabled(info.isEnabled()); 6225 if (info.isClickable()) { 6226 structure.setClickable(true); 6227 } 6228 if (info.isFocusable()) { 6229 structure.setFocusable(true); 6230 } 6231 if (info.isFocused()) { 6232 structure.setFocused(true); 6233 } 6234 if (info.isAccessibilityFocused()) { 6235 structure.setAccessibilityFocused(true); 6236 } 6237 if (info.isSelected()) { 6238 structure.setSelected(true); 6239 } 6240 if (info.isLongClickable()) { 6241 structure.setLongClickable(true); 6242 } 6243 if (info.isCheckable()) { 6244 structure.setCheckable(true); 6245 if (info.isChecked()) { 6246 structure.setChecked(true); 6247 } 6248 } 6249 if (info.isStylusButtonPressable()) { 6250 structure.setStylusButtonPressable(true); 6251 } 6252 CharSequence cname = info.getClassName(); 6253 structure.setClassName(cname != null ? cname.toString() : null); 6254 structure.setContentDescription(info.getContentDescription()); 6255 Log.i("View", "vassist " + cname + " @ " + rect.toShortString() 6256 + " text=" + info.getText() + " cd=" + info.getContentDescription()); 6257 if (info.getText() != null || info.getError() != null) { 6258 structure.setText(info.getText(), info.getTextSelectionStart(), 6259 info.getTextSelectionEnd()); 6260 } 6261 final int NCHILDREN = info.getChildCount(); 6262 if (NCHILDREN > 0) { 6263 structure.setChildCount(NCHILDREN); 6264 for (int i=0; i<NCHILDREN; i++) { 6265 AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo( 6266 AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i))); 6267 ViewStructure child = structure.newChild(i); 6268 populateVirtualStructure(child, provider, cinfo); 6269 cinfo.recycle(); 6270 } 6271 } 6272 } 6273 6274 /** 6275 * Dispatch creation of {@link ViewStructure} down the hierarchy. The default 6276 * implementation calls {@link #onProvideStructure} and 6277 * {@link #onProvideVirtualStructure}. 6278 */ 6279 public void dispatchProvideStructure(ViewStructure structure) { 6280 if (!isAssistBlocked()) { 6281 onProvideAssistStructure(structure); 6282 onProvideVirtualAssistStructure(structure); 6283 } else { 6284 structure.setClassName(getAccessibilityClassName().toString()); 6285 structure.setAssistBlocked(true); 6286 } 6287 } 6288 6289 /** 6290 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 6291 * 6292 * Note: Called from the default {@link AccessibilityDelegate}. 6293 * 6294 * @hide 6295 */ 6296 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 6297 Rect bounds = mAttachInfo.mTmpInvalRect; 6298 6299 getDrawingRect(bounds); 6300 info.setBoundsInParent(bounds); 6301 6302 getBoundsOnScreen(bounds, true); 6303 info.setBoundsInScreen(bounds); 6304 6305 ViewParent parent = getParentForAccessibility(); 6306 if (parent instanceof View) { 6307 info.setParent((View) parent); 6308 } 6309 6310 if (mID != View.NO_ID) { 6311 View rootView = getRootView(); 6312 if (rootView == null) { 6313 rootView = this; 6314 } 6315 6316 View label = rootView.findLabelForView(this, mID); 6317 if (label != null) { 6318 info.setLabeledBy(label); 6319 } 6320 6321 if ((mAttachInfo.mAccessibilityFetchFlags 6322 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 6323 && Resources.resourceHasPackage(mID)) { 6324 try { 6325 String viewId = getResources().getResourceName(mID); 6326 info.setViewIdResourceName(viewId); 6327 } catch (Resources.NotFoundException nfe) { 6328 /* ignore */ 6329 } 6330 } 6331 } 6332 6333 if (mLabelForId != View.NO_ID) { 6334 View rootView = getRootView(); 6335 if (rootView == null) { 6336 rootView = this; 6337 } 6338 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 6339 if (labeled != null) { 6340 info.setLabelFor(labeled); 6341 } 6342 } 6343 6344 if (mAccessibilityTraversalBeforeId != View.NO_ID) { 6345 View rootView = getRootView(); 6346 if (rootView == null) { 6347 rootView = this; 6348 } 6349 View next = rootView.findViewInsideOutShouldExist(this, 6350 mAccessibilityTraversalBeforeId); 6351 if (next != null) { 6352 info.setTraversalBefore(next); 6353 } 6354 } 6355 6356 if (mAccessibilityTraversalAfterId != View.NO_ID) { 6357 View rootView = getRootView(); 6358 if (rootView == null) { 6359 rootView = this; 6360 } 6361 View next = rootView.findViewInsideOutShouldExist(this, 6362 mAccessibilityTraversalAfterId); 6363 if (next != null) { 6364 info.setTraversalAfter(next); 6365 } 6366 } 6367 6368 info.setVisibleToUser(isVisibleToUser()); 6369 6370 info.setPackageName(mContext.getPackageName()); 6371 info.setClassName(getAccessibilityClassName()); 6372 info.setContentDescription(getContentDescription()); 6373 6374 info.setEnabled(isEnabled()); 6375 info.setClickable(isClickable()); 6376 info.setFocusable(isFocusable()); 6377 info.setFocused(isFocused()); 6378 info.setAccessibilityFocused(isAccessibilityFocused()); 6379 info.setSelected(isSelected()); 6380 info.setLongClickable(isLongClickable()); 6381 info.setStylusButtonPressable(isStylusButtonPressable()); 6382 info.setLiveRegion(getAccessibilityLiveRegion()); 6383 6384 // TODO: These make sense only if we are in an AdapterView but all 6385 // views can be selected. Maybe from accessibility perspective 6386 // we should report as selectable view in an AdapterView. 6387 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 6388 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 6389 6390 if (isFocusable()) { 6391 if (isFocused()) { 6392 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 6393 } else { 6394 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 6395 } 6396 } 6397 6398 if (!isAccessibilityFocused()) { 6399 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 6400 } else { 6401 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 6402 } 6403 6404 if (isClickable() && isEnabled()) { 6405 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 6406 } 6407 6408 if (isLongClickable() && isEnabled()) { 6409 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 6410 } 6411 6412 if (isStylusButtonPressable() && isEnabled()) { 6413 info.addAction(AccessibilityAction.ACTION_STYLUS_BUTTON_PRESS); 6414 } 6415 6416 CharSequence text = getIterableTextForAccessibility(); 6417 if (text != null && text.length() > 0) { 6418 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 6419 6420 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 6421 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 6422 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 6423 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 6424 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 6425 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 6426 } 6427 6428 info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN); 6429 } 6430 6431 private View findLabelForView(View view, int labeledId) { 6432 if (mMatchLabelForPredicate == null) { 6433 mMatchLabelForPredicate = new MatchLabelForPredicate(); 6434 } 6435 mMatchLabelForPredicate.mLabeledId = labeledId; 6436 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 6437 } 6438 6439 /** 6440 * Computes whether this view is visible to the user. Such a view is 6441 * attached, visible, all its predecessors are visible, it is not clipped 6442 * entirely by its predecessors, and has an alpha greater than zero. 6443 * 6444 * @return Whether the view is visible on the screen. 6445 * 6446 * @hide 6447 */ 6448 protected boolean isVisibleToUser() { 6449 return isVisibleToUser(null); 6450 } 6451 6452 /** 6453 * Computes whether the given portion of this view is visible to the user. 6454 * Such a view is attached, visible, all its predecessors are visible, 6455 * has an alpha greater than zero, and the specified portion is not 6456 * clipped entirely by its predecessors. 6457 * 6458 * @param boundInView the portion of the view to test; coordinates should be relative; may be 6459 * <code>null</code>, and the entire view will be tested in this case. 6460 * When <code>true</code> is returned by the function, the actual visible 6461 * region will be stored in this parameter; that is, if boundInView is fully 6462 * contained within the view, no modification will be made, otherwise regions 6463 * outside of the visible area of the view will be clipped. 6464 * 6465 * @return Whether the specified portion of the view is visible on the screen. 6466 * 6467 * @hide 6468 */ 6469 protected boolean isVisibleToUser(Rect boundInView) { 6470 if (mAttachInfo != null) { 6471 // Attached to invisible window means this view is not visible. 6472 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 6473 return false; 6474 } 6475 // An invisible predecessor or one with alpha zero means 6476 // that this view is not visible to the user. 6477 Object current = this; 6478 while (current instanceof View) { 6479 View view = (View) current; 6480 // We have attach info so this view is attached and there is no 6481 // need to check whether we reach to ViewRootImpl on the way up. 6482 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 6483 view.getVisibility() != VISIBLE) { 6484 return false; 6485 } 6486 current = view.mParent; 6487 } 6488 // Check if the view is entirely covered by its predecessors. 6489 Rect visibleRect = mAttachInfo.mTmpInvalRect; 6490 Point offset = mAttachInfo.mPoint; 6491 if (!getGlobalVisibleRect(visibleRect, offset)) { 6492 return false; 6493 } 6494 // Check if the visible portion intersects the rectangle of interest. 6495 if (boundInView != null) { 6496 visibleRect.offset(-offset.x, -offset.y); 6497 return boundInView.intersect(visibleRect); 6498 } 6499 return true; 6500 } 6501 return false; 6502 } 6503 6504 /** 6505 * Returns the delegate for implementing accessibility support via 6506 * composition. For more details see {@link AccessibilityDelegate}. 6507 * 6508 * @return The delegate, or null if none set. 6509 * 6510 * @hide 6511 */ 6512 public AccessibilityDelegate getAccessibilityDelegate() { 6513 return mAccessibilityDelegate; 6514 } 6515 6516 /** 6517 * Sets a delegate for implementing accessibility support via composition as 6518 * opposed to inheritance. The delegate's primary use is for implementing 6519 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 6520 * 6521 * @param delegate The delegate instance. 6522 * 6523 * @see AccessibilityDelegate 6524 */ 6525 public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) { 6526 mAccessibilityDelegate = delegate; 6527 } 6528 6529 /** 6530 * Gets the provider for managing a virtual view hierarchy rooted at this View 6531 * and reported to {@link android.accessibilityservice.AccessibilityService}s 6532 * that explore the window content. 6533 * <p> 6534 * If this method returns an instance, this instance is responsible for managing 6535 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 6536 * View including the one representing the View itself. Similarly the returned 6537 * instance is responsible for performing accessibility actions on any virtual 6538 * view or the root view itself. 6539 * </p> 6540 * <p> 6541 * If an {@link AccessibilityDelegate} has been specified via calling 6542 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6543 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 6544 * is responsible for handling this call. 6545 * </p> 6546 * 6547 * @return The provider. 6548 * 6549 * @see AccessibilityNodeProvider 6550 */ 6551 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 6552 if (mAccessibilityDelegate != null) { 6553 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 6554 } else { 6555 return null; 6556 } 6557 } 6558 6559 /** 6560 * Gets the unique identifier of this view on the screen for accessibility purposes. 6561 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 6562 * 6563 * @return The view accessibility id. 6564 * 6565 * @hide 6566 */ 6567 public int getAccessibilityViewId() { 6568 if (mAccessibilityViewId == NO_ID) { 6569 mAccessibilityViewId = sNextAccessibilityViewId++; 6570 } 6571 return mAccessibilityViewId; 6572 } 6573 6574 /** 6575 * Gets the unique identifier of the window in which this View reseides. 6576 * 6577 * @return The window accessibility id. 6578 * 6579 * @hide 6580 */ 6581 public int getAccessibilityWindowId() { 6582 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 6583 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 6584 } 6585 6586 /** 6587 * Gets the {@link View} description. It briefly describes the view and is 6588 * primarily used for accessibility support. Set this property to enable 6589 * better accessibility support for your application. This is especially 6590 * true for views that do not have textual representation (For example, 6591 * ImageButton). 6592 * 6593 * @return The content description. 6594 * 6595 * @attr ref android.R.styleable#View_contentDescription 6596 */ 6597 @ViewDebug.ExportedProperty(category = "accessibility") 6598 public CharSequence getContentDescription() { 6599 return mContentDescription; 6600 } 6601 6602 /** 6603 * Sets the {@link View} description. It briefly describes the view and is 6604 * primarily used for accessibility support. Set this property to enable 6605 * better accessibility support for your application. This is especially 6606 * true for views that do not have textual representation (For example, 6607 * ImageButton). 6608 * 6609 * @param contentDescription The content description. 6610 * 6611 * @attr ref android.R.styleable#View_contentDescription 6612 */ 6613 @RemotableViewMethod 6614 public void setContentDescription(CharSequence contentDescription) { 6615 if (mContentDescription == null) { 6616 if (contentDescription == null) { 6617 return; 6618 } 6619 } else if (mContentDescription.equals(contentDescription)) { 6620 return; 6621 } 6622 mContentDescription = contentDescription; 6623 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 6624 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 6625 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 6626 notifySubtreeAccessibilityStateChangedIfNeeded(); 6627 } else { 6628 notifyViewAccessibilityStateChangedIfNeeded( 6629 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 6630 } 6631 } 6632 6633 /** 6634 * Sets the id of a view before which this one is visited in accessibility traversal. 6635 * A screen-reader must visit the content of this view before the content of the one 6636 * it precedes. For example, if view B is set to be before view A, then a screen-reader 6637 * will traverse the entire content of B before traversing the entire content of A, 6638 * regardles of what traversal strategy it is using. 6639 * <p> 6640 * Views that do not have specified before/after relationships are traversed in order 6641 * determined by the screen-reader. 6642 * </p> 6643 * <p> 6644 * Setting that this view is before a view that is not important for accessibility 6645 * or if this view is not important for accessibility will have no effect as the 6646 * screen-reader is not aware of unimportant views. 6647 * </p> 6648 * 6649 * @param beforeId The id of a view this one precedes in accessibility traversal. 6650 * 6651 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 6652 * 6653 * @see #setImportantForAccessibility(int) 6654 */ 6655 @RemotableViewMethod 6656 public void setAccessibilityTraversalBefore(int beforeId) { 6657 if (mAccessibilityTraversalBeforeId == beforeId) { 6658 return; 6659 } 6660 mAccessibilityTraversalBeforeId = beforeId; 6661 notifyViewAccessibilityStateChangedIfNeeded( 6662 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6663 } 6664 6665 /** 6666 * Gets the id of a view before which this one is visited in accessibility traversal. 6667 * 6668 * @return The id of a view this one precedes in accessibility traversal if 6669 * specified, otherwise {@link #NO_ID}. 6670 * 6671 * @see #setAccessibilityTraversalBefore(int) 6672 */ 6673 public int getAccessibilityTraversalBefore() { 6674 return mAccessibilityTraversalBeforeId; 6675 } 6676 6677 /** 6678 * Sets the id of a view after which this one is visited in accessibility traversal. 6679 * A screen-reader must visit the content of the other view before the content of this 6680 * one. For example, if view B is set to be after view A, then a screen-reader 6681 * will traverse the entire content of A before traversing the entire content of B, 6682 * regardles of what traversal strategy it is using. 6683 * <p> 6684 * Views that do not have specified before/after relationships are traversed in order 6685 * determined by the screen-reader. 6686 * </p> 6687 * <p> 6688 * Setting that this view is after a view that is not important for accessibility 6689 * or if this view is not important for accessibility will have no effect as the 6690 * screen-reader is not aware of unimportant views. 6691 * </p> 6692 * 6693 * @param afterId The id of a view this one succedees in accessibility traversal. 6694 * 6695 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 6696 * 6697 * @see #setImportantForAccessibility(int) 6698 */ 6699 @RemotableViewMethod 6700 public void setAccessibilityTraversalAfter(int afterId) { 6701 if (mAccessibilityTraversalAfterId == afterId) { 6702 return; 6703 } 6704 mAccessibilityTraversalAfterId = afterId; 6705 notifyViewAccessibilityStateChangedIfNeeded( 6706 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6707 } 6708 6709 /** 6710 * Gets the id of a view after which this one is visited in accessibility traversal. 6711 * 6712 * @return The id of a view this one succeedes in accessibility traversal if 6713 * specified, otherwise {@link #NO_ID}. 6714 * 6715 * @see #setAccessibilityTraversalAfter(int) 6716 */ 6717 public int getAccessibilityTraversalAfter() { 6718 return mAccessibilityTraversalAfterId; 6719 } 6720 6721 /** 6722 * Gets the id of a view for which this view serves as a label for 6723 * accessibility purposes. 6724 * 6725 * @return The labeled view id. 6726 */ 6727 @ViewDebug.ExportedProperty(category = "accessibility") 6728 public int getLabelFor() { 6729 return mLabelForId; 6730 } 6731 6732 /** 6733 * Sets the id of a view for which this view serves as a label for 6734 * accessibility purposes. 6735 * 6736 * @param id The labeled view id. 6737 */ 6738 @RemotableViewMethod 6739 public void setLabelFor(@IdRes int id) { 6740 if (mLabelForId == id) { 6741 return; 6742 } 6743 mLabelForId = id; 6744 if (mLabelForId != View.NO_ID 6745 && mID == View.NO_ID) { 6746 mID = generateViewId(); 6747 } 6748 notifyViewAccessibilityStateChangedIfNeeded( 6749 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6750 } 6751 6752 /** 6753 * Invoked whenever this view loses focus, either by losing window focus or by losing 6754 * focus within its window. This method can be used to clear any state tied to the 6755 * focus. For instance, if a button is held pressed with the trackball and the window 6756 * loses focus, this method can be used to cancel the press. 6757 * 6758 * Subclasses of View overriding this method should always call super.onFocusLost(). 6759 * 6760 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 6761 * @see #onWindowFocusChanged(boolean) 6762 * 6763 * @hide pending API council approval 6764 */ 6765 @CallSuper 6766 protected void onFocusLost() { 6767 resetPressedState(); 6768 } 6769 6770 private void resetPressedState() { 6771 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6772 return; 6773 } 6774 6775 if (isPressed()) { 6776 setPressed(false); 6777 6778 if (!mHasPerformedLongPress) { 6779 removeLongPressCallback(); 6780 } 6781 } 6782 } 6783 6784 /** 6785 * Returns true if this view has focus 6786 * 6787 * @return True if this view has focus, false otherwise. 6788 */ 6789 @ViewDebug.ExportedProperty(category = "focus") 6790 public boolean isFocused() { 6791 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6792 } 6793 6794 /** 6795 * Find the view in the hierarchy rooted at this view that currently has 6796 * focus. 6797 * 6798 * @return The view that currently has focus, or null if no focused view can 6799 * be found. 6800 */ 6801 public View findFocus() { 6802 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 6803 } 6804 6805 /** 6806 * Indicates whether this view is one of the set of scrollable containers in 6807 * its window. 6808 * 6809 * @return whether this view is one of the set of scrollable containers in 6810 * its window 6811 * 6812 * @attr ref android.R.styleable#View_isScrollContainer 6813 */ 6814 public boolean isScrollContainer() { 6815 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 6816 } 6817 6818 /** 6819 * Change whether this view is one of the set of scrollable containers in 6820 * its window. This will be used to determine whether the window can 6821 * resize or must pan when a soft input area is open -- scrollable 6822 * containers allow the window to use resize mode since the container 6823 * will appropriately shrink. 6824 * 6825 * @attr ref android.R.styleable#View_isScrollContainer 6826 */ 6827 public void setScrollContainer(boolean isScrollContainer) { 6828 if (isScrollContainer) { 6829 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 6830 mAttachInfo.mScrollContainers.add(this); 6831 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 6832 } 6833 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 6834 } else { 6835 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 6836 mAttachInfo.mScrollContainers.remove(this); 6837 } 6838 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 6839 } 6840 } 6841 6842 /** 6843 * Returns the quality of the drawing cache. 6844 * 6845 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6846 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6847 * 6848 * @see #setDrawingCacheQuality(int) 6849 * @see #setDrawingCacheEnabled(boolean) 6850 * @see #isDrawingCacheEnabled() 6851 * 6852 * @attr ref android.R.styleable#View_drawingCacheQuality 6853 */ 6854 @DrawingCacheQuality 6855 public int getDrawingCacheQuality() { 6856 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 6857 } 6858 6859 /** 6860 * Set the drawing cache quality of this view. This value is used only when the 6861 * drawing cache is enabled 6862 * 6863 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6864 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6865 * 6866 * @see #getDrawingCacheQuality() 6867 * @see #setDrawingCacheEnabled(boolean) 6868 * @see #isDrawingCacheEnabled() 6869 * 6870 * @attr ref android.R.styleable#View_drawingCacheQuality 6871 */ 6872 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 6873 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 6874 } 6875 6876 /** 6877 * Returns whether the screen should remain on, corresponding to the current 6878 * value of {@link #KEEP_SCREEN_ON}. 6879 * 6880 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 6881 * 6882 * @see #setKeepScreenOn(boolean) 6883 * 6884 * @attr ref android.R.styleable#View_keepScreenOn 6885 */ 6886 public boolean getKeepScreenOn() { 6887 return (mViewFlags & KEEP_SCREEN_ON) != 0; 6888 } 6889 6890 /** 6891 * Controls whether the screen should remain on, modifying the 6892 * value of {@link #KEEP_SCREEN_ON}. 6893 * 6894 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 6895 * 6896 * @see #getKeepScreenOn() 6897 * 6898 * @attr ref android.R.styleable#View_keepScreenOn 6899 */ 6900 public void setKeepScreenOn(boolean keepScreenOn) { 6901 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 6902 } 6903 6904 /** 6905 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6906 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6907 * 6908 * @attr ref android.R.styleable#View_nextFocusLeft 6909 */ 6910 public int getNextFocusLeftId() { 6911 return mNextFocusLeftId; 6912 } 6913 6914 /** 6915 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6916 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 6917 * decide automatically. 6918 * 6919 * @attr ref android.R.styleable#View_nextFocusLeft 6920 */ 6921 public void setNextFocusLeftId(int nextFocusLeftId) { 6922 mNextFocusLeftId = nextFocusLeftId; 6923 } 6924 6925 /** 6926 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6927 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6928 * 6929 * @attr ref android.R.styleable#View_nextFocusRight 6930 */ 6931 public int getNextFocusRightId() { 6932 return mNextFocusRightId; 6933 } 6934 6935 /** 6936 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6937 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 6938 * decide automatically. 6939 * 6940 * @attr ref android.R.styleable#View_nextFocusRight 6941 */ 6942 public void setNextFocusRightId(int nextFocusRightId) { 6943 mNextFocusRightId = nextFocusRightId; 6944 } 6945 6946 /** 6947 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6948 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6949 * 6950 * @attr ref android.R.styleable#View_nextFocusUp 6951 */ 6952 public int getNextFocusUpId() { 6953 return mNextFocusUpId; 6954 } 6955 6956 /** 6957 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6958 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 6959 * decide automatically. 6960 * 6961 * @attr ref android.R.styleable#View_nextFocusUp 6962 */ 6963 public void setNextFocusUpId(int nextFocusUpId) { 6964 mNextFocusUpId = nextFocusUpId; 6965 } 6966 6967 /** 6968 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6969 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6970 * 6971 * @attr ref android.R.styleable#View_nextFocusDown 6972 */ 6973 public int getNextFocusDownId() { 6974 return mNextFocusDownId; 6975 } 6976 6977 /** 6978 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6979 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 6980 * decide automatically. 6981 * 6982 * @attr ref android.R.styleable#View_nextFocusDown 6983 */ 6984 public void setNextFocusDownId(int nextFocusDownId) { 6985 mNextFocusDownId = nextFocusDownId; 6986 } 6987 6988 /** 6989 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6990 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6991 * 6992 * @attr ref android.R.styleable#View_nextFocusForward 6993 */ 6994 public int getNextFocusForwardId() { 6995 return mNextFocusForwardId; 6996 } 6997 6998 /** 6999 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7000 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 7001 * decide automatically. 7002 * 7003 * @attr ref android.R.styleable#View_nextFocusForward 7004 */ 7005 public void setNextFocusForwardId(int nextFocusForwardId) { 7006 mNextFocusForwardId = nextFocusForwardId; 7007 } 7008 7009 /** 7010 * Returns the visibility of this view and all of its ancestors 7011 * 7012 * @return True if this view and all of its ancestors are {@link #VISIBLE} 7013 */ 7014 public boolean isShown() { 7015 View current = this; 7016 //noinspection ConstantConditions 7017 do { 7018 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7019 return false; 7020 } 7021 ViewParent parent = current.mParent; 7022 if (parent == null) { 7023 return false; // We are not attached to the view root 7024 } 7025 if (!(parent instanceof View)) { 7026 return true; 7027 } 7028 current = (View) parent; 7029 } while (current != null); 7030 7031 return false; 7032 } 7033 7034 /** 7035 * Called by the view hierarchy when the content insets for a window have 7036 * changed, to allow it to adjust its content to fit within those windows. 7037 * The content insets tell you the space that the status bar, input method, 7038 * and other system windows infringe on the application's window. 7039 * 7040 * <p>You do not normally need to deal with this function, since the default 7041 * window decoration given to applications takes care of applying it to the 7042 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 7043 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 7044 * and your content can be placed under those system elements. You can then 7045 * use this method within your view hierarchy if you have parts of your UI 7046 * which you would like to ensure are not being covered. 7047 * 7048 * <p>The default implementation of this method simply applies the content 7049 * insets to the view's padding, consuming that content (modifying the 7050 * insets to be 0), and returning true. This behavior is off by default, but can 7051 * be enabled through {@link #setFitsSystemWindows(boolean)}. 7052 * 7053 * <p>This function's traversal down the hierarchy is depth-first. The same content 7054 * insets object is propagated down the hierarchy, so any changes made to it will 7055 * be seen by all following views (including potentially ones above in 7056 * the hierarchy since this is a depth-first traversal). The first view 7057 * that returns true will abort the entire traversal. 7058 * 7059 * <p>The default implementation works well for a situation where it is 7060 * used with a container that covers the entire window, allowing it to 7061 * apply the appropriate insets to its content on all edges. If you need 7062 * a more complicated layout (such as two different views fitting system 7063 * windows, one on the top of the window, and one on the bottom), 7064 * you can override the method and handle the insets however you would like. 7065 * Note that the insets provided by the framework are always relative to the 7066 * far edges of the window, not accounting for the location of the called view 7067 * within that window. (In fact when this method is called you do not yet know 7068 * where the layout will place the view, as it is done before layout happens.) 7069 * 7070 * <p>Note: unlike many View methods, there is no dispatch phase to this 7071 * call. If you are overriding it in a ViewGroup and want to allow the 7072 * call to continue to your children, you must be sure to call the super 7073 * implementation. 7074 * 7075 * <p>Here is a sample layout that makes use of fitting system windows 7076 * to have controls for a video view placed inside of the window decorations 7077 * that it hides and shows. This can be used with code like the second 7078 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 7079 * 7080 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 7081 * 7082 * @param insets Current content insets of the window. Prior to 7083 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 7084 * the insets or else you and Android will be unhappy. 7085 * 7086 * @return {@code true} if this view applied the insets and it should not 7087 * continue propagating further down the hierarchy, {@code false} otherwise. 7088 * @see #getFitsSystemWindows() 7089 * @see #setFitsSystemWindows(boolean) 7090 * @see #setSystemUiVisibility(int) 7091 * 7092 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 7093 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 7094 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 7095 * to implement handling their own insets. 7096 */ 7097 protected boolean fitSystemWindows(Rect insets) { 7098 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 7099 if (insets == null) { 7100 // Null insets by definition have already been consumed. 7101 // This call cannot apply insets since there are none to apply, 7102 // so return false. 7103 return false; 7104 } 7105 // If we're not in the process of dispatching the newer apply insets call, 7106 // that means we're not in the compatibility path. Dispatch into the newer 7107 // apply insets path and take things from there. 7108 try { 7109 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 7110 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 7111 } finally { 7112 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 7113 } 7114 } else { 7115 // We're being called from the newer apply insets path. 7116 // Perform the standard fallback behavior. 7117 return fitSystemWindowsInt(insets); 7118 } 7119 } 7120 7121 private boolean fitSystemWindowsInt(Rect insets) { 7122 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 7123 mUserPaddingStart = UNDEFINED_PADDING; 7124 mUserPaddingEnd = UNDEFINED_PADDING; 7125 Rect localInsets = sThreadLocal.get(); 7126 if (localInsets == null) { 7127 localInsets = new Rect(); 7128 sThreadLocal.set(localInsets); 7129 } 7130 boolean res = computeFitSystemWindows(insets, localInsets); 7131 mUserPaddingLeftInitial = localInsets.left; 7132 mUserPaddingRightInitial = localInsets.right; 7133 internalSetPadding(localInsets.left, localInsets.top, 7134 localInsets.right, localInsets.bottom); 7135 return res; 7136 } 7137 return false; 7138 } 7139 7140 /** 7141 * Called when the view should apply {@link WindowInsets} according to its internal policy. 7142 * 7143 * <p>This method should be overridden by views that wish to apply a policy different from or 7144 * in addition to the default behavior. Clients that wish to force a view subtree 7145 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 7146 * 7147 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 7148 * it will be called during dispatch instead of this method. The listener may optionally 7149 * call this method from its own implementation if it wishes to apply the view's default 7150 * insets policy in addition to its own.</p> 7151 * 7152 * <p>Implementations of this method should either return the insets parameter unchanged 7153 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 7154 * that this view applied itself. This allows new inset types added in future platform 7155 * versions to pass through existing implementations unchanged without being erroneously 7156 * consumed.</p> 7157 * 7158 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 7159 * property is set then the view will consume the system window insets and apply them 7160 * as padding for the view.</p> 7161 * 7162 * @param insets Insets to apply 7163 * @return The supplied insets with any applied insets consumed 7164 */ 7165 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 7166 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 7167 // We weren't called from within a direct call to fitSystemWindows, 7168 // call into it as a fallback in case we're in a class that overrides it 7169 // and has logic to perform. 7170 if (fitSystemWindows(insets.getSystemWindowInsets())) { 7171 return insets.consumeSystemWindowInsets(); 7172 } 7173 } else { 7174 // We were called from within a direct call to fitSystemWindows. 7175 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 7176 return insets.consumeSystemWindowInsets(); 7177 } 7178 } 7179 return insets; 7180 } 7181 7182 /** 7183 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 7184 * window insets to this view. The listener's 7185 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 7186 * method will be called instead of the view's 7187 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 7188 * 7189 * @param listener Listener to set 7190 * 7191 * @see #onApplyWindowInsets(WindowInsets) 7192 */ 7193 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 7194 getListenerInfo().mOnApplyWindowInsetsListener = listener; 7195 } 7196 7197 /** 7198 * Request to apply the given window insets to this view or another view in its subtree. 7199 * 7200 * <p>This method should be called by clients wishing to apply insets corresponding to areas 7201 * obscured by window decorations or overlays. This can include the status and navigation bars, 7202 * action bars, input methods and more. New inset categories may be added in the future. 7203 * The method returns the insets provided minus any that were applied by this view or its 7204 * children.</p> 7205 * 7206 * <p>Clients wishing to provide custom behavior should override the 7207 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 7208 * {@link OnApplyWindowInsetsListener} via the 7209 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 7210 * method.</p> 7211 * 7212 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 7213 * </p> 7214 * 7215 * @param insets Insets to apply 7216 * @return The provided insets minus the insets that were consumed 7217 */ 7218 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 7219 try { 7220 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 7221 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 7222 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 7223 } else { 7224 return onApplyWindowInsets(insets); 7225 } 7226 } finally { 7227 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 7228 } 7229 } 7230 7231 /** 7232 * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are 7233 * only available if the view is attached. 7234 * 7235 * @return WindowInsets from the top of the view hierarchy or null if View is detached 7236 */ 7237 public WindowInsets getRootWindowInsets() { 7238 if (mAttachInfo != null) { 7239 return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */); 7240 } 7241 return null; 7242 } 7243 7244 /** 7245 * @hide Compute the insets that should be consumed by this view and the ones 7246 * that should propagate to those under it. 7247 */ 7248 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 7249 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7250 || mAttachInfo == null 7251 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 7252 && !mAttachInfo.mOverscanRequested)) { 7253 outLocalInsets.set(inoutInsets); 7254 inoutInsets.set(0, 0, 0, 0); 7255 return true; 7256 } else { 7257 // The application wants to take care of fitting system window for 7258 // the content... however we still need to take care of any overscan here. 7259 final Rect overscan = mAttachInfo.mOverscanInsets; 7260 outLocalInsets.set(overscan); 7261 inoutInsets.left -= overscan.left; 7262 inoutInsets.top -= overscan.top; 7263 inoutInsets.right -= overscan.right; 7264 inoutInsets.bottom -= overscan.bottom; 7265 return false; 7266 } 7267 } 7268 7269 /** 7270 * Compute insets that should be consumed by this view and the ones that should propagate 7271 * to those under it. 7272 * 7273 * @param in Insets currently being processed by this View, likely received as a parameter 7274 * to {@link #onApplyWindowInsets(WindowInsets)}. 7275 * @param outLocalInsets A Rect that will receive the insets that should be consumed 7276 * by this view 7277 * @return Insets that should be passed along to views under this one 7278 */ 7279 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 7280 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7281 || mAttachInfo == null 7282 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 7283 outLocalInsets.set(in.getSystemWindowInsets()); 7284 return in.consumeSystemWindowInsets(); 7285 } else { 7286 outLocalInsets.set(0, 0, 0, 0); 7287 return in; 7288 } 7289 } 7290 7291 /** 7292 * Sets whether or not this view should account for system screen decorations 7293 * such as the status bar and inset its content; that is, controlling whether 7294 * the default implementation of {@link #fitSystemWindows(Rect)} will be 7295 * executed. See that method for more details. 7296 * 7297 * <p>Note that if you are providing your own implementation of 7298 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 7299 * flag to true -- your implementation will be overriding the default 7300 * implementation that checks this flag. 7301 * 7302 * @param fitSystemWindows If true, then the default implementation of 7303 * {@link #fitSystemWindows(Rect)} will be executed. 7304 * 7305 * @attr ref android.R.styleable#View_fitsSystemWindows 7306 * @see #getFitsSystemWindows() 7307 * @see #fitSystemWindows(Rect) 7308 * @see #setSystemUiVisibility(int) 7309 */ 7310 public void setFitsSystemWindows(boolean fitSystemWindows) { 7311 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 7312 } 7313 7314 /** 7315 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 7316 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 7317 * will be executed. 7318 * 7319 * @return {@code true} if the default implementation of 7320 * {@link #fitSystemWindows(Rect)} will be executed. 7321 * 7322 * @attr ref android.R.styleable#View_fitsSystemWindows 7323 * @see #setFitsSystemWindows(boolean) 7324 * @see #fitSystemWindows(Rect) 7325 * @see #setSystemUiVisibility(int) 7326 */ 7327 @ViewDebug.ExportedProperty 7328 public boolean getFitsSystemWindows() { 7329 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 7330 } 7331 7332 /** @hide */ 7333 public boolean fitsSystemWindows() { 7334 return getFitsSystemWindows(); 7335 } 7336 7337 /** 7338 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 7339 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 7340 */ 7341 public void requestFitSystemWindows() { 7342 if (mParent != null) { 7343 mParent.requestFitSystemWindows(); 7344 } 7345 } 7346 7347 /** 7348 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 7349 */ 7350 public void requestApplyInsets() { 7351 requestFitSystemWindows(); 7352 } 7353 7354 /** 7355 * For use by PhoneWindow to make its own system window fitting optional. 7356 * @hide 7357 */ 7358 public void makeOptionalFitsSystemWindows() { 7359 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 7360 } 7361 7362 /** 7363 * Returns the visibility status for this view. 7364 * 7365 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 7366 * @attr ref android.R.styleable#View_visibility 7367 */ 7368 @ViewDebug.ExportedProperty(mapping = { 7369 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 7370 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 7371 @ViewDebug.IntToString(from = GONE, to = "GONE") 7372 }) 7373 @Visibility 7374 public int getVisibility() { 7375 return mViewFlags & VISIBILITY_MASK; 7376 } 7377 7378 /** 7379 * Set the enabled state of this view. 7380 * 7381 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 7382 * @attr ref android.R.styleable#View_visibility 7383 */ 7384 @RemotableViewMethod 7385 public void setVisibility(@Visibility int visibility) { 7386 setFlags(visibility, VISIBILITY_MASK); 7387 } 7388 7389 /** 7390 * Returns the enabled status for this view. The interpretation of the 7391 * enabled state varies by subclass. 7392 * 7393 * @return True if this view is enabled, false otherwise. 7394 */ 7395 @ViewDebug.ExportedProperty 7396 public boolean isEnabled() { 7397 return (mViewFlags & ENABLED_MASK) == ENABLED; 7398 } 7399 7400 /** 7401 * Set the enabled state of this view. The interpretation of the enabled 7402 * state varies by subclass. 7403 * 7404 * @param enabled True if this view is enabled, false otherwise. 7405 */ 7406 @RemotableViewMethod 7407 public void setEnabled(boolean enabled) { 7408 if (enabled == isEnabled()) return; 7409 7410 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 7411 7412 /* 7413 * The View most likely has to change its appearance, so refresh 7414 * the drawable state. 7415 */ 7416 refreshDrawableState(); 7417 7418 // Invalidate too, since the default behavior for views is to be 7419 // be drawn at 50% alpha rather than to change the drawable. 7420 invalidate(true); 7421 7422 if (!enabled) { 7423 cancelPendingInputEvents(); 7424 } 7425 } 7426 7427 /** 7428 * Set whether this view can receive the focus. 7429 * 7430 * Setting this to false will also ensure that this view is not focusable 7431 * in touch mode. 7432 * 7433 * @param focusable If true, this view can receive the focus. 7434 * 7435 * @see #setFocusableInTouchMode(boolean) 7436 * @attr ref android.R.styleable#View_focusable 7437 */ 7438 public void setFocusable(boolean focusable) { 7439 if (!focusable) { 7440 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 7441 } 7442 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 7443 } 7444 7445 /** 7446 * Set whether this view can receive focus while in touch mode. 7447 * 7448 * Setting this to true will also ensure that this view is focusable. 7449 * 7450 * @param focusableInTouchMode If true, this view can receive the focus while 7451 * in touch mode. 7452 * 7453 * @see #setFocusable(boolean) 7454 * @attr ref android.R.styleable#View_focusableInTouchMode 7455 */ 7456 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 7457 // Focusable in touch mode should always be set before the focusable flag 7458 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 7459 // which, in touch mode, will not successfully request focus on this view 7460 // because the focusable in touch mode flag is not set 7461 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 7462 if (focusableInTouchMode) { 7463 setFlags(FOCUSABLE, FOCUSABLE_MASK); 7464 } 7465 } 7466 7467 /** 7468 * Set whether this view should have sound effects enabled for events such as 7469 * clicking and touching. 7470 * 7471 * <p>You may wish to disable sound effects for a view if you already play sounds, 7472 * for instance, a dial key that plays dtmf tones. 7473 * 7474 * @param soundEffectsEnabled whether sound effects are enabled for this view. 7475 * @see #isSoundEffectsEnabled() 7476 * @see #playSoundEffect(int) 7477 * @attr ref android.R.styleable#View_soundEffectsEnabled 7478 */ 7479 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 7480 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 7481 } 7482 7483 /** 7484 * @return whether this view should have sound effects enabled for events such as 7485 * clicking and touching. 7486 * 7487 * @see #setSoundEffectsEnabled(boolean) 7488 * @see #playSoundEffect(int) 7489 * @attr ref android.R.styleable#View_soundEffectsEnabled 7490 */ 7491 @ViewDebug.ExportedProperty 7492 public boolean isSoundEffectsEnabled() { 7493 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 7494 } 7495 7496 /** 7497 * Set whether this view should have haptic feedback for events such as 7498 * long presses. 7499 * 7500 * <p>You may wish to disable haptic feedback if your view already controls 7501 * its own haptic feedback. 7502 * 7503 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 7504 * @see #isHapticFeedbackEnabled() 7505 * @see #performHapticFeedback(int) 7506 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 7507 */ 7508 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 7509 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 7510 } 7511 7512 /** 7513 * @return whether this view should have haptic feedback enabled for events 7514 * long presses. 7515 * 7516 * @see #setHapticFeedbackEnabled(boolean) 7517 * @see #performHapticFeedback(int) 7518 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 7519 */ 7520 @ViewDebug.ExportedProperty 7521 public boolean isHapticFeedbackEnabled() { 7522 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 7523 } 7524 7525 /** 7526 * Returns the layout direction for this view. 7527 * 7528 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 7529 * {@link #LAYOUT_DIRECTION_RTL}, 7530 * {@link #LAYOUT_DIRECTION_INHERIT} or 7531 * {@link #LAYOUT_DIRECTION_LOCALE}. 7532 * 7533 * @attr ref android.R.styleable#View_layoutDirection 7534 * 7535 * @hide 7536 */ 7537 @ViewDebug.ExportedProperty(category = "layout", mapping = { 7538 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 7539 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 7540 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 7541 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 7542 }) 7543 @LayoutDir 7544 public int getRawLayoutDirection() { 7545 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 7546 } 7547 7548 /** 7549 * Set the layout direction for this view. This will propagate a reset of layout direction 7550 * resolution to the view's children and resolve layout direction for this view. 7551 * 7552 * @param layoutDirection the layout direction to set. Should be one of: 7553 * 7554 * {@link #LAYOUT_DIRECTION_LTR}, 7555 * {@link #LAYOUT_DIRECTION_RTL}, 7556 * {@link #LAYOUT_DIRECTION_INHERIT}, 7557 * {@link #LAYOUT_DIRECTION_LOCALE}. 7558 * 7559 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 7560 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 7561 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 7562 * 7563 * @attr ref android.R.styleable#View_layoutDirection 7564 */ 7565 @RemotableViewMethod 7566 public void setLayoutDirection(@LayoutDir int layoutDirection) { 7567 if (getRawLayoutDirection() != layoutDirection) { 7568 // Reset the current layout direction and the resolved one 7569 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 7570 resetRtlProperties(); 7571 // Set the new layout direction (filtered) 7572 mPrivateFlags2 |= 7573 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 7574 // We need to resolve all RTL properties as they all depend on layout direction 7575 resolveRtlPropertiesIfNeeded(); 7576 requestLayout(); 7577 invalidate(true); 7578 } 7579 } 7580 7581 /** 7582 * Returns the resolved layout direction for this view. 7583 * 7584 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 7585 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 7586 * 7587 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 7588 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 7589 * 7590 * @attr ref android.R.styleable#View_layoutDirection 7591 */ 7592 @ViewDebug.ExportedProperty(category = "layout", mapping = { 7593 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 7594 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 7595 }) 7596 @ResolvedLayoutDir 7597 public int getLayoutDirection() { 7598 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 7599 if (targetSdkVersion < JELLY_BEAN_MR1) { 7600 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 7601 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 7602 } 7603 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 7604 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 7605 } 7606 7607 /** 7608 * Indicates whether or not this view's layout is right-to-left. This is resolved from 7609 * layout attribute and/or the inherited value from the parent 7610 * 7611 * @return true if the layout is right-to-left. 7612 * 7613 * @hide 7614 */ 7615 @ViewDebug.ExportedProperty(category = "layout") 7616 public boolean isLayoutRtl() { 7617 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 7618 } 7619 7620 /** 7621 * Indicates whether the view is currently tracking transient state that the 7622 * app should not need to concern itself with saving and restoring, but that 7623 * the framework should take special note to preserve when possible. 7624 * 7625 * <p>A view with transient state cannot be trivially rebound from an external 7626 * data source, such as an adapter binding item views in a list. This may be 7627 * because the view is performing an animation, tracking user selection 7628 * of content, or similar.</p> 7629 * 7630 * @return true if the view has transient state 7631 */ 7632 @ViewDebug.ExportedProperty(category = "layout") 7633 public boolean hasTransientState() { 7634 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 7635 } 7636 7637 /** 7638 * Set whether this view is currently tracking transient state that the 7639 * framework should attempt to preserve when possible. This flag is reference counted, 7640 * so every call to setHasTransientState(true) should be paired with a later call 7641 * to setHasTransientState(false). 7642 * 7643 * <p>A view with transient state cannot be trivially rebound from an external 7644 * data source, such as an adapter binding item views in a list. This may be 7645 * because the view is performing an animation, tracking user selection 7646 * of content, or similar.</p> 7647 * 7648 * @param hasTransientState true if this view has transient state 7649 */ 7650 public void setHasTransientState(boolean hasTransientState) { 7651 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 7652 mTransientStateCount - 1; 7653 if (mTransientStateCount < 0) { 7654 mTransientStateCount = 0; 7655 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 7656 "unmatched pair of setHasTransientState calls"); 7657 } else if ((hasTransientState && mTransientStateCount == 1) || 7658 (!hasTransientState && mTransientStateCount == 0)) { 7659 // update flag if we've just incremented up from 0 or decremented down to 0 7660 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 7661 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 7662 if (mParent != null) { 7663 try { 7664 mParent.childHasTransientStateChanged(this, hasTransientState); 7665 } catch (AbstractMethodError e) { 7666 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7667 " does not fully implement ViewParent", e); 7668 } 7669 } 7670 } 7671 } 7672 7673 /** 7674 * Returns true if this view is currently attached to a window. 7675 */ 7676 public boolean isAttachedToWindow() { 7677 return mAttachInfo != null; 7678 } 7679 7680 /** 7681 * Returns true if this view has been through at least one layout since it 7682 * was last attached to or detached from a window. 7683 */ 7684 public boolean isLaidOut() { 7685 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 7686 } 7687 7688 /** 7689 * If this view doesn't do any drawing on its own, set this flag to 7690 * allow further optimizations. By default, this flag is not set on 7691 * View, but could be set on some View subclasses such as ViewGroup. 7692 * 7693 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 7694 * you should clear this flag. 7695 * 7696 * @param willNotDraw whether or not this View draw on its own 7697 */ 7698 public void setWillNotDraw(boolean willNotDraw) { 7699 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 7700 } 7701 7702 /** 7703 * Returns whether or not this View draws on its own. 7704 * 7705 * @return true if this view has nothing to draw, false otherwise 7706 */ 7707 @ViewDebug.ExportedProperty(category = "drawing") 7708 public boolean willNotDraw() { 7709 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 7710 } 7711 7712 /** 7713 * When a View's drawing cache is enabled, drawing is redirected to an 7714 * offscreen bitmap. Some views, like an ImageView, must be able to 7715 * bypass this mechanism if they already draw a single bitmap, to avoid 7716 * unnecessary usage of the memory. 7717 * 7718 * @param willNotCacheDrawing true if this view does not cache its 7719 * drawing, false otherwise 7720 */ 7721 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 7722 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 7723 } 7724 7725 /** 7726 * Returns whether or not this View can cache its drawing or not. 7727 * 7728 * @return true if this view does not cache its drawing, false otherwise 7729 */ 7730 @ViewDebug.ExportedProperty(category = "drawing") 7731 public boolean willNotCacheDrawing() { 7732 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 7733 } 7734 7735 /** 7736 * Indicates whether this view reacts to click events or not. 7737 * 7738 * @return true if the view is clickable, false otherwise 7739 * 7740 * @see #setClickable(boolean) 7741 * @attr ref android.R.styleable#View_clickable 7742 */ 7743 @ViewDebug.ExportedProperty 7744 public boolean isClickable() { 7745 return (mViewFlags & CLICKABLE) == CLICKABLE; 7746 } 7747 7748 /** 7749 * Enables or disables click events for this view. When a view 7750 * is clickable it will change its state to "pressed" on every click. 7751 * Subclasses should set the view clickable to visually react to 7752 * user's clicks. 7753 * 7754 * @param clickable true to make the view clickable, false otherwise 7755 * 7756 * @see #isClickable() 7757 * @attr ref android.R.styleable#View_clickable 7758 */ 7759 public void setClickable(boolean clickable) { 7760 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 7761 } 7762 7763 /** 7764 * Indicates whether this view reacts to long click events or not. 7765 * 7766 * @return true if the view is long clickable, false otherwise 7767 * 7768 * @see #setLongClickable(boolean) 7769 * @attr ref android.R.styleable#View_longClickable 7770 */ 7771 public boolean isLongClickable() { 7772 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 7773 } 7774 7775 /** 7776 * Enables or disables long click events for this view. When a view is long 7777 * clickable it reacts to the user holding down the button for a longer 7778 * duration than a tap. This event can either launch the listener or a 7779 * context menu. 7780 * 7781 * @param longClickable true to make the view long clickable, false otherwise 7782 * @see #isLongClickable() 7783 * @attr ref android.R.styleable#View_longClickable 7784 */ 7785 public void setLongClickable(boolean longClickable) { 7786 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 7787 } 7788 7789 /** 7790 * Indicates whether this view reacts to stylus button press events or not. 7791 * 7792 * @return true if the view is stylus button pressable, false otherwise 7793 * @see #setStylusButtonPressable(boolean) 7794 * @attr ref android.R.styleable#View_stylusButtonPressable 7795 */ 7796 public boolean isStylusButtonPressable() { 7797 return (mViewFlags & STYLUS_BUTTON_PRESSABLE) == STYLUS_BUTTON_PRESSABLE; 7798 } 7799 7800 /** 7801 * Enables or disables stylus button press events for this view. When a view is stylus button 7802 * pressable it reacts to the user touching the screen with a stylus and pressing the first 7803 * stylus button. This event can launch the listener. 7804 * 7805 * @param stylusButtonPressable true to make the view react to a stylus button press, false 7806 * otherwise 7807 * @see #isStylusButtonPressable() 7808 * @attr ref android.R.styleable#View_stylusButtonPressable 7809 */ 7810 public void setStylusButtonPressable(boolean stylusButtonPressable) { 7811 setFlags(stylusButtonPressable ? STYLUS_BUTTON_PRESSABLE : 0, STYLUS_BUTTON_PRESSABLE); 7812 } 7813 7814 /** 7815 * Sets the pressed state for this view and provides a touch coordinate for 7816 * animation hinting. 7817 * 7818 * @param pressed Pass true to set the View's internal state to "pressed", 7819 * or false to reverts the View's internal state from a 7820 * previously set "pressed" state. 7821 * @param x The x coordinate of the touch that caused the press 7822 * @param y The y coordinate of the touch that caused the press 7823 */ 7824 private void setPressed(boolean pressed, float x, float y) { 7825 if (pressed) { 7826 drawableHotspotChanged(x, y); 7827 } 7828 7829 setPressed(pressed); 7830 } 7831 7832 /** 7833 * Sets the pressed state for this view. 7834 * 7835 * @see #isClickable() 7836 * @see #setClickable(boolean) 7837 * 7838 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 7839 * the View's internal state from a previously set "pressed" state. 7840 */ 7841 public void setPressed(boolean pressed) { 7842 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 7843 7844 if (pressed) { 7845 mPrivateFlags |= PFLAG_PRESSED; 7846 } else { 7847 mPrivateFlags &= ~PFLAG_PRESSED; 7848 } 7849 7850 if (needsRefresh) { 7851 refreshDrawableState(); 7852 } 7853 dispatchSetPressed(pressed); 7854 } 7855 7856 /** 7857 * Dispatch setPressed to all of this View's children. 7858 * 7859 * @see #setPressed(boolean) 7860 * 7861 * @param pressed The new pressed state 7862 */ 7863 protected void dispatchSetPressed(boolean pressed) { 7864 } 7865 7866 /** 7867 * Indicates whether the view is currently in pressed state. Unless 7868 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 7869 * the pressed state. 7870 * 7871 * @see #setPressed(boolean) 7872 * @see #isClickable() 7873 * @see #setClickable(boolean) 7874 * 7875 * @return true if the view is currently pressed, false otherwise 7876 */ 7877 @ViewDebug.ExportedProperty 7878 public boolean isPressed() { 7879 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 7880 } 7881 7882 /** 7883 * @hide 7884 * Indicates whether this view will participate in data collection through 7885 * {@link ViewStructure}. If true, it will not provide any data 7886 * for itself or its children. If false, the normal data collection will be allowed. 7887 * 7888 * @return Returns false if assist data collection is not blocked, else true. 7889 * 7890 * @see #setAssistBlocked(boolean) 7891 * @attr ref android.R.styleable#View_assistBlocked 7892 */ 7893 public boolean isAssistBlocked() { 7894 return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0; 7895 } 7896 7897 /** 7898 * @hide 7899 * Controls whether assist data collection from this view and its children is enabled 7900 * (that is, whether {@link #onProvideStructure} and 7901 * {@link #onProvideVirtualStructure} will be called). The default value is false, 7902 * allowing normal assist collection. Setting this to false will disable assist collection. 7903 * 7904 * @param enabled Set to true to <em>disable</em> assist data collection, or false 7905 * (the default) to allow it. 7906 * 7907 * @see #isAssistBlocked() 7908 * @see #onProvideStructure 7909 * @see #onProvideVirtualStructure 7910 * @attr ref android.R.styleable#View_assistBlocked 7911 */ 7912 public void setAssistBlocked(boolean enabled) { 7913 if (enabled) { 7914 mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED; 7915 } else { 7916 mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED; 7917 } 7918 } 7919 7920 /** 7921 * Indicates whether this view will save its state (that is, 7922 * whether its {@link #onSaveInstanceState} method will be called). 7923 * 7924 * @return Returns true if the view state saving is enabled, else false. 7925 * 7926 * @see #setSaveEnabled(boolean) 7927 * @attr ref android.R.styleable#View_saveEnabled 7928 */ 7929 public boolean isSaveEnabled() { 7930 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 7931 } 7932 7933 /** 7934 * Controls whether the saving of this view's state is 7935 * enabled (that is, whether its {@link #onSaveInstanceState} method 7936 * will be called). Note that even if freezing is enabled, the 7937 * view still must have an id assigned to it (via {@link #setId(int)}) 7938 * for its state to be saved. This flag can only disable the 7939 * saving of this view; any child views may still have their state saved. 7940 * 7941 * @param enabled Set to false to <em>disable</em> state saving, or true 7942 * (the default) to allow it. 7943 * 7944 * @see #isSaveEnabled() 7945 * @see #setId(int) 7946 * @see #onSaveInstanceState() 7947 * @attr ref android.R.styleable#View_saveEnabled 7948 */ 7949 public void setSaveEnabled(boolean enabled) { 7950 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 7951 } 7952 7953 /** 7954 * Gets whether the framework should discard touches when the view's 7955 * window is obscured by another visible window. 7956 * Refer to the {@link View} security documentation for more details. 7957 * 7958 * @return True if touch filtering is enabled. 7959 * 7960 * @see #setFilterTouchesWhenObscured(boolean) 7961 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 7962 */ 7963 @ViewDebug.ExportedProperty 7964 public boolean getFilterTouchesWhenObscured() { 7965 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 7966 } 7967 7968 /** 7969 * Sets whether the framework should discard touches when the view's 7970 * window is obscured by another visible window. 7971 * Refer to the {@link View} security documentation for more details. 7972 * 7973 * @param enabled True if touch filtering should be enabled. 7974 * 7975 * @see #getFilterTouchesWhenObscured 7976 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 7977 */ 7978 public void setFilterTouchesWhenObscured(boolean enabled) { 7979 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 7980 FILTER_TOUCHES_WHEN_OBSCURED); 7981 } 7982 7983 /** 7984 * Indicates whether the entire hierarchy under this view will save its 7985 * state when a state saving traversal occurs from its parent. The default 7986 * is true; if false, these views will not be saved unless 7987 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 7988 * 7989 * @return Returns true if the view state saving from parent is enabled, else false. 7990 * 7991 * @see #setSaveFromParentEnabled(boolean) 7992 */ 7993 public boolean isSaveFromParentEnabled() { 7994 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 7995 } 7996 7997 /** 7998 * Controls whether the entire hierarchy under this view will save its 7999 * state when a state saving traversal occurs from its parent. The default 8000 * is true; if false, these views will not be saved unless 8001 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8002 * 8003 * @param enabled Set to false to <em>disable</em> state saving, or true 8004 * (the default) to allow it. 8005 * 8006 * @see #isSaveFromParentEnabled() 8007 * @see #setId(int) 8008 * @see #onSaveInstanceState() 8009 */ 8010 public void setSaveFromParentEnabled(boolean enabled) { 8011 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 8012 } 8013 8014 8015 /** 8016 * Returns whether this View is able to take focus. 8017 * 8018 * @return True if this view can take focus, or false otherwise. 8019 * @attr ref android.R.styleable#View_focusable 8020 */ 8021 @ViewDebug.ExportedProperty(category = "focus") 8022 public final boolean isFocusable() { 8023 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 8024 } 8025 8026 /** 8027 * When a view is focusable, it may not want to take focus when in touch mode. 8028 * For example, a button would like focus when the user is navigating via a D-pad 8029 * so that the user can click on it, but once the user starts touching the screen, 8030 * the button shouldn't take focus 8031 * @return Whether the view is focusable in touch mode. 8032 * @attr ref android.R.styleable#View_focusableInTouchMode 8033 */ 8034 @ViewDebug.ExportedProperty 8035 public final boolean isFocusableInTouchMode() { 8036 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 8037 } 8038 8039 /** 8040 * Find the nearest view in the specified direction that can take focus. 8041 * This does not actually give focus to that view. 8042 * 8043 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8044 * 8045 * @return The nearest focusable in the specified direction, or null if none 8046 * can be found. 8047 */ 8048 public View focusSearch(@FocusRealDirection int direction) { 8049 if (mParent != null) { 8050 return mParent.focusSearch(this, direction); 8051 } else { 8052 return null; 8053 } 8054 } 8055 8056 /** 8057 * This method is the last chance for the focused view and its ancestors to 8058 * respond to an arrow key. This is called when the focused view did not 8059 * consume the key internally, nor could the view system find a new view in 8060 * the requested direction to give focus to. 8061 * 8062 * @param focused The currently focused view. 8063 * @param direction The direction focus wants to move. One of FOCUS_UP, 8064 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 8065 * @return True if the this view consumed this unhandled move. 8066 */ 8067 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 8068 return false; 8069 } 8070 8071 /** 8072 * If a user manually specified the next view id for a particular direction, 8073 * use the root to look up the view. 8074 * @param root The root view of the hierarchy containing this view. 8075 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 8076 * or FOCUS_BACKWARD. 8077 * @return The user specified next view, or null if there is none. 8078 */ 8079 View findUserSetNextFocus(View root, @FocusDirection int direction) { 8080 switch (direction) { 8081 case FOCUS_LEFT: 8082 if (mNextFocusLeftId == View.NO_ID) return null; 8083 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 8084 case FOCUS_RIGHT: 8085 if (mNextFocusRightId == View.NO_ID) return null; 8086 return findViewInsideOutShouldExist(root, mNextFocusRightId); 8087 case FOCUS_UP: 8088 if (mNextFocusUpId == View.NO_ID) return null; 8089 return findViewInsideOutShouldExist(root, mNextFocusUpId); 8090 case FOCUS_DOWN: 8091 if (mNextFocusDownId == View.NO_ID) return null; 8092 return findViewInsideOutShouldExist(root, mNextFocusDownId); 8093 case FOCUS_FORWARD: 8094 if (mNextFocusForwardId == View.NO_ID) return null; 8095 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 8096 case FOCUS_BACKWARD: { 8097 if (mID == View.NO_ID) return null; 8098 final int id = mID; 8099 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 8100 @Override 8101 public boolean apply(View t) { 8102 return t.mNextFocusForwardId == id; 8103 } 8104 }); 8105 } 8106 } 8107 return null; 8108 } 8109 8110 private View findViewInsideOutShouldExist(View root, int id) { 8111 if (mMatchIdPredicate == null) { 8112 mMatchIdPredicate = new MatchIdPredicate(); 8113 } 8114 mMatchIdPredicate.mId = id; 8115 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 8116 if (result == null) { 8117 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 8118 } 8119 return result; 8120 } 8121 8122 /** 8123 * Find and return all focusable views that are descendants of this view, 8124 * possibly including this view if it is focusable itself. 8125 * 8126 * @param direction The direction of the focus 8127 * @return A list of focusable views 8128 */ 8129 public ArrayList<View> getFocusables(@FocusDirection int direction) { 8130 ArrayList<View> result = new ArrayList<View>(24); 8131 addFocusables(result, direction); 8132 return result; 8133 } 8134 8135 /** 8136 * Add any focusable views that are descendants of this view (possibly 8137 * including this view if it is focusable itself) to views. If we are in touch mode, 8138 * only add views that are also focusable in touch mode. 8139 * 8140 * @param views Focusable views found so far 8141 * @param direction The direction of the focus 8142 */ 8143 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 8144 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 8145 } 8146 8147 /** 8148 * Adds any focusable views that are descendants of this view (possibly 8149 * including this view if it is focusable itself) to views. This method 8150 * adds all focusable views regardless if we are in touch mode or 8151 * only views focusable in touch mode if we are in touch mode or 8152 * only views that can take accessibility focus if accessibility is enabled 8153 * depending on the focusable mode parameter. 8154 * 8155 * @param views Focusable views found so far or null if all we are interested is 8156 * the number of focusables. 8157 * @param direction The direction of the focus. 8158 * @param focusableMode The type of focusables to be added. 8159 * 8160 * @see #FOCUSABLES_ALL 8161 * @see #FOCUSABLES_TOUCH_MODE 8162 */ 8163 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 8164 @FocusableMode int focusableMode) { 8165 if (views == null) { 8166 return; 8167 } 8168 if (!isFocusable()) { 8169 return; 8170 } 8171 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 8172 && isInTouchMode() && !isFocusableInTouchMode()) { 8173 return; 8174 } 8175 views.add(this); 8176 } 8177 8178 /** 8179 * Finds the Views that contain given text. The containment is case insensitive. 8180 * The search is performed by either the text that the View renders or the content 8181 * description that describes the view for accessibility purposes and the view does 8182 * not render or both. Clients can specify how the search is to be performed via 8183 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 8184 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 8185 * 8186 * @param outViews The output list of matching Views. 8187 * @param searched The text to match against. 8188 * 8189 * @see #FIND_VIEWS_WITH_TEXT 8190 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 8191 * @see #setContentDescription(CharSequence) 8192 */ 8193 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 8194 @FindViewFlags int flags) { 8195 if (getAccessibilityNodeProvider() != null) { 8196 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 8197 outViews.add(this); 8198 } 8199 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 8200 && (searched != null && searched.length() > 0) 8201 && (mContentDescription != null && mContentDescription.length() > 0)) { 8202 String searchedLowerCase = searched.toString().toLowerCase(); 8203 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 8204 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 8205 outViews.add(this); 8206 } 8207 } 8208 } 8209 8210 /** 8211 * Find and return all touchable views that are descendants of this view, 8212 * possibly including this view if it is touchable itself. 8213 * 8214 * @return A list of touchable views 8215 */ 8216 public ArrayList<View> getTouchables() { 8217 ArrayList<View> result = new ArrayList<View>(); 8218 addTouchables(result); 8219 return result; 8220 } 8221 8222 /** 8223 * Add any touchable views that are descendants of this view (possibly 8224 * including this view if it is touchable itself) to views. 8225 * 8226 * @param views Touchable views found so far 8227 */ 8228 public void addTouchables(ArrayList<View> views) { 8229 final int viewFlags = mViewFlags; 8230 8231 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 8232 || (viewFlags & STYLUS_BUTTON_PRESSABLE) == STYLUS_BUTTON_PRESSABLE) 8233 && (viewFlags & ENABLED_MASK) == ENABLED) { 8234 views.add(this); 8235 } 8236 } 8237 8238 /** 8239 * Returns whether this View is accessibility focused. 8240 * 8241 * @return True if this View is accessibility focused. 8242 */ 8243 public boolean isAccessibilityFocused() { 8244 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 8245 } 8246 8247 /** 8248 * Call this to try to give accessibility focus to this view. 8249 * 8250 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 8251 * returns false or the view is no visible or the view already has accessibility 8252 * focus. 8253 * 8254 * See also {@link #focusSearch(int)}, which is what you call to say that you 8255 * have focus, and you want your parent to look for the next one. 8256 * 8257 * @return Whether this view actually took accessibility focus. 8258 * 8259 * @hide 8260 */ 8261 public boolean requestAccessibilityFocus() { 8262 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 8263 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 8264 return false; 8265 } 8266 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 8267 return false; 8268 } 8269 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 8270 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 8271 ViewRootImpl viewRootImpl = getViewRootImpl(); 8272 if (viewRootImpl != null) { 8273 viewRootImpl.setAccessibilityFocus(this, null); 8274 } 8275 invalidate(); 8276 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 8277 return true; 8278 } 8279 return false; 8280 } 8281 8282 /** 8283 * Call this to try to clear accessibility focus of this view. 8284 * 8285 * See also {@link #focusSearch(int)}, which is what you call to say that you 8286 * have focus, and you want your parent to look for the next one. 8287 * 8288 * @hide 8289 */ 8290 public void clearAccessibilityFocus() { 8291 clearAccessibilityFocusNoCallbacks(); 8292 // Clear the global reference of accessibility focus if this 8293 // view or any of its descendants had accessibility focus. 8294 ViewRootImpl viewRootImpl = getViewRootImpl(); 8295 if (viewRootImpl != null) { 8296 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 8297 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 8298 viewRootImpl.setAccessibilityFocus(null, null); 8299 } 8300 } 8301 } 8302 8303 private void sendAccessibilityHoverEvent(int eventType) { 8304 // Since we are not delivering to a client accessibility events from not 8305 // important views (unless the clinet request that) we need to fire the 8306 // event from the deepest view exposed to the client. As a consequence if 8307 // the user crosses a not exposed view the client will see enter and exit 8308 // of the exposed predecessor followed by and enter and exit of that same 8309 // predecessor when entering and exiting the not exposed descendant. This 8310 // is fine since the client has a clear idea which view is hovered at the 8311 // price of a couple more events being sent. This is a simple and 8312 // working solution. 8313 View source = this; 8314 while (true) { 8315 if (source.includeForAccessibility()) { 8316 source.sendAccessibilityEvent(eventType); 8317 return; 8318 } 8319 ViewParent parent = source.getParent(); 8320 if (parent instanceof View) { 8321 source = (View) parent; 8322 } else { 8323 return; 8324 } 8325 } 8326 } 8327 8328 /** 8329 * Clears accessibility focus without calling any callback methods 8330 * normally invoked in {@link #clearAccessibilityFocus()}. This method 8331 * is used for clearing accessibility focus when giving this focus to 8332 * another view. 8333 */ 8334 void clearAccessibilityFocusNoCallbacks() { 8335 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 8336 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 8337 invalidate(); 8338 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 8339 } 8340 } 8341 8342 /** 8343 * Call this to try to give focus to a specific view or to one of its 8344 * descendants. 8345 * 8346 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8347 * false), or if it is focusable and it is not focusable in touch mode 8348 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8349 * 8350 * See also {@link #focusSearch(int)}, which is what you call to say that you 8351 * have focus, and you want your parent to look for the next one. 8352 * 8353 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 8354 * {@link #FOCUS_DOWN} and <code>null</code>. 8355 * 8356 * @return Whether this view or one of its descendants actually took focus. 8357 */ 8358 public final boolean requestFocus() { 8359 return requestFocus(View.FOCUS_DOWN); 8360 } 8361 8362 /** 8363 * Call this to try to give focus to a specific view or to one of its 8364 * descendants and give it a hint about what direction focus is heading. 8365 * 8366 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8367 * false), or if it is focusable and it is not focusable in touch mode 8368 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8369 * 8370 * See also {@link #focusSearch(int)}, which is what you call to say that you 8371 * have focus, and you want your parent to look for the next one. 8372 * 8373 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 8374 * <code>null</code> set for the previously focused rectangle. 8375 * 8376 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8377 * @return Whether this view or one of its descendants actually took focus. 8378 */ 8379 public final boolean requestFocus(int direction) { 8380 return requestFocus(direction, null); 8381 } 8382 8383 /** 8384 * Call this to try to give focus to a specific view or to one of its descendants 8385 * and give it hints about the direction and a specific rectangle that the focus 8386 * is coming from. The rectangle can help give larger views a finer grained hint 8387 * about where focus is coming from, and therefore, where to show selection, or 8388 * forward focus change internally. 8389 * 8390 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8391 * false), or if it is focusable and it is not focusable in touch mode 8392 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8393 * 8394 * A View will not take focus if it is not visible. 8395 * 8396 * A View will not take focus if one of its parents has 8397 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 8398 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 8399 * 8400 * See also {@link #focusSearch(int)}, which is what you call to say that you 8401 * have focus, and you want your parent to look for the next one. 8402 * 8403 * You may wish to override this method if your custom {@link View} has an internal 8404 * {@link View} that it wishes to forward the request to. 8405 * 8406 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8407 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 8408 * to give a finer grained hint about where focus is coming from. May be null 8409 * if there is no hint. 8410 * @return Whether this view or one of its descendants actually took focus. 8411 */ 8412 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 8413 return requestFocusNoSearch(direction, previouslyFocusedRect); 8414 } 8415 8416 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 8417 // need to be focusable 8418 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 8419 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 8420 return false; 8421 } 8422 8423 // need to be focusable in touch mode if in touch mode 8424 if (isInTouchMode() && 8425 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 8426 return false; 8427 } 8428 8429 // need to not have any parents blocking us 8430 if (hasAncestorThatBlocksDescendantFocus()) { 8431 return false; 8432 } 8433 8434 handleFocusGainInternal(direction, previouslyFocusedRect); 8435 return true; 8436 } 8437 8438 /** 8439 * Call this to try to give focus to a specific view or to one of its descendants. This is a 8440 * special variant of {@link #requestFocus() } that will allow views that are not focusable in 8441 * touch mode to request focus when they are touched. 8442 * 8443 * @return Whether this view or one of its descendants actually took focus. 8444 * 8445 * @see #isInTouchMode() 8446 * 8447 */ 8448 public final boolean requestFocusFromTouch() { 8449 // Leave touch mode if we need to 8450 if (isInTouchMode()) { 8451 ViewRootImpl viewRoot = getViewRootImpl(); 8452 if (viewRoot != null) { 8453 viewRoot.ensureTouchMode(false); 8454 } 8455 } 8456 return requestFocus(View.FOCUS_DOWN); 8457 } 8458 8459 /** 8460 * @return Whether any ancestor of this view blocks descendant focus. 8461 */ 8462 private boolean hasAncestorThatBlocksDescendantFocus() { 8463 final boolean focusableInTouchMode = isFocusableInTouchMode(); 8464 ViewParent ancestor = mParent; 8465 while (ancestor instanceof ViewGroup) { 8466 final ViewGroup vgAncestor = (ViewGroup) ancestor; 8467 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 8468 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 8469 return true; 8470 } else { 8471 ancestor = vgAncestor.getParent(); 8472 } 8473 } 8474 return false; 8475 } 8476 8477 /** 8478 * Gets the mode for determining whether this View is important for accessibility 8479 * which is if it fires accessibility events and if it is reported to 8480 * accessibility services that query the screen. 8481 * 8482 * @return The mode for determining whether a View is important for accessibility. 8483 * 8484 * @attr ref android.R.styleable#View_importantForAccessibility 8485 * 8486 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 8487 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 8488 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 8489 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 8490 */ 8491 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 8492 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 8493 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 8494 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 8495 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 8496 to = "noHideDescendants") 8497 }) 8498 public int getImportantForAccessibility() { 8499 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 8500 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 8501 } 8502 8503 /** 8504 * Sets the live region mode for this view. This indicates to accessibility 8505 * services whether they should automatically notify the user about changes 8506 * to the view's content description or text, or to the content descriptions 8507 * or text of the view's children (where applicable). 8508 * <p> 8509 * For example, in a login screen with a TextView that displays an "incorrect 8510 * password" notification, that view should be marked as a live region with 8511 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 8512 * <p> 8513 * To disable change notifications for this view, use 8514 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 8515 * mode for most views. 8516 * <p> 8517 * To indicate that the user should be notified of changes, use 8518 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 8519 * <p> 8520 * If the view's changes should interrupt ongoing speech and notify the user 8521 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 8522 * 8523 * @param mode The live region mode for this view, one of: 8524 * <ul> 8525 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 8526 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 8527 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 8528 * </ul> 8529 * @attr ref android.R.styleable#View_accessibilityLiveRegion 8530 */ 8531 public void setAccessibilityLiveRegion(int mode) { 8532 if (mode != getAccessibilityLiveRegion()) { 8533 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 8534 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 8535 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 8536 notifyViewAccessibilityStateChangedIfNeeded( 8537 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8538 } 8539 } 8540 8541 /** 8542 * Gets the live region mode for this View. 8543 * 8544 * @return The live region mode for the view. 8545 * 8546 * @attr ref android.R.styleable#View_accessibilityLiveRegion 8547 * 8548 * @see #setAccessibilityLiveRegion(int) 8549 */ 8550 public int getAccessibilityLiveRegion() { 8551 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 8552 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 8553 } 8554 8555 /** 8556 * Sets how to determine whether this view is important for accessibility 8557 * which is if it fires accessibility events and if it is reported to 8558 * accessibility services that query the screen. 8559 * 8560 * @param mode How to determine whether this view is important for accessibility. 8561 * 8562 * @attr ref android.R.styleable#View_importantForAccessibility 8563 * 8564 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 8565 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 8566 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 8567 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 8568 */ 8569 public void setImportantForAccessibility(int mode) { 8570 final int oldMode = getImportantForAccessibility(); 8571 if (mode != oldMode) { 8572 // If we're moving between AUTO and another state, we might not need 8573 // to send a subtree changed notification. We'll store the computed 8574 // importance, since we'll need to check it later to make sure. 8575 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 8576 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 8577 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 8578 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 8579 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 8580 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 8581 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 8582 notifySubtreeAccessibilityStateChangedIfNeeded(); 8583 } else { 8584 notifyViewAccessibilityStateChangedIfNeeded( 8585 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8586 } 8587 } 8588 } 8589 8590 /** 8591 * Computes whether this view should be exposed for accessibility. In 8592 * general, views that are interactive or provide information are exposed 8593 * while views that serve only as containers are hidden. 8594 * <p> 8595 * If an ancestor of this view has importance 8596 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 8597 * returns <code>false</code>. 8598 * <p> 8599 * Otherwise, the value is computed according to the view's 8600 * {@link #getImportantForAccessibility()} value: 8601 * <ol> 8602 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 8603 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 8604 * </code> 8605 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 8606 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 8607 * view satisfies any of the following: 8608 * <ul> 8609 * <li>Is actionable, e.g. {@link #isClickable()}, 8610 * {@link #isLongClickable()}, or {@link #isFocusable()} 8611 * <li>Has an {@link AccessibilityDelegate} 8612 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 8613 * {@link OnKeyListener}, etc. 8614 * <li>Is an accessibility live region, e.g. 8615 * {@link #getAccessibilityLiveRegion()} is not 8616 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 8617 * </ul> 8618 * </ol> 8619 * 8620 * @return Whether the view is exposed for accessibility. 8621 * @see #setImportantForAccessibility(int) 8622 * @see #getImportantForAccessibility() 8623 */ 8624 public boolean isImportantForAccessibility() { 8625 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 8626 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 8627 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 8628 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 8629 return false; 8630 } 8631 8632 // Check parent mode to ensure we're not hidden. 8633 ViewParent parent = mParent; 8634 while (parent instanceof View) { 8635 if (((View) parent).getImportantForAccessibility() 8636 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 8637 return false; 8638 } 8639 parent = parent.getParent(); 8640 } 8641 8642 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 8643 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 8644 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 8645 } 8646 8647 /** 8648 * Gets the parent for accessibility purposes. Note that the parent for 8649 * accessibility is not necessary the immediate parent. It is the first 8650 * predecessor that is important for accessibility. 8651 * 8652 * @return The parent for accessibility purposes. 8653 */ 8654 public ViewParent getParentForAccessibility() { 8655 if (mParent instanceof View) { 8656 View parentView = (View) mParent; 8657 if (parentView.includeForAccessibility()) { 8658 return mParent; 8659 } else { 8660 return mParent.getParentForAccessibility(); 8661 } 8662 } 8663 return null; 8664 } 8665 8666 /** 8667 * Adds the children of a given View for accessibility. Since some Views are 8668 * not important for accessibility the children for accessibility are not 8669 * necessarily direct children of the view, rather they are the first level of 8670 * descendants important for accessibility. 8671 * 8672 * @param children The list of children for accessibility. 8673 */ 8674 public void addChildrenForAccessibility(ArrayList<View> children) { 8675 8676 } 8677 8678 /** 8679 * Whether to regard this view for accessibility. A view is regarded for 8680 * accessibility if it is important for accessibility or the querying 8681 * accessibility service has explicitly requested that view not 8682 * important for accessibility are regarded. 8683 * 8684 * @return Whether to regard the view for accessibility. 8685 * 8686 * @hide 8687 */ 8688 public boolean includeForAccessibility() { 8689 if (mAttachInfo != null) { 8690 return (mAttachInfo.mAccessibilityFetchFlags 8691 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 8692 || isImportantForAccessibility(); 8693 } 8694 return false; 8695 } 8696 8697 /** 8698 * Returns whether the View is considered actionable from 8699 * accessibility perspective. Such view are important for 8700 * accessibility. 8701 * 8702 * @return True if the view is actionable for accessibility. 8703 * 8704 * @hide 8705 */ 8706 public boolean isActionableForAccessibility() { 8707 return (isClickable() || isLongClickable() || isFocusable()); 8708 } 8709 8710 /** 8711 * Returns whether the View has registered callbacks which makes it 8712 * important for accessibility. 8713 * 8714 * @return True if the view is actionable for accessibility. 8715 */ 8716 private boolean hasListenersForAccessibility() { 8717 ListenerInfo info = getListenerInfo(); 8718 return mTouchDelegate != null || info.mOnKeyListener != null 8719 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 8720 || info.mOnHoverListener != null || info.mOnDragListener != null; 8721 } 8722 8723 /** 8724 * Notifies that the accessibility state of this view changed. The change 8725 * is local to this view and does not represent structural changes such 8726 * as children and parent. For example, the view became focusable. The 8727 * notification is at at most once every 8728 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 8729 * to avoid unnecessary load to the system. Also once a view has a pending 8730 * notification this method is a NOP until the notification has been sent. 8731 * 8732 * @hide 8733 */ 8734 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 8735 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 8736 return; 8737 } 8738 if (mSendViewStateChangedAccessibilityEvent == null) { 8739 mSendViewStateChangedAccessibilityEvent = 8740 new SendViewStateChangedAccessibilityEvent(); 8741 } 8742 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 8743 } 8744 8745 /** 8746 * Notifies that the accessibility state of this view changed. The change 8747 * is *not* local to this view and does represent structural changes such 8748 * as children and parent. For example, the view size changed. The 8749 * notification is at at most once every 8750 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 8751 * to avoid unnecessary load to the system. Also once a view has a pending 8752 * notification this method is a NOP until the notification has been sent. 8753 * 8754 * @hide 8755 */ 8756 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 8757 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 8758 return; 8759 } 8760 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 8761 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 8762 if (mParent != null) { 8763 try { 8764 mParent.notifySubtreeAccessibilityStateChanged( 8765 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 8766 } catch (AbstractMethodError e) { 8767 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 8768 " does not fully implement ViewParent", e); 8769 } 8770 } 8771 } 8772 } 8773 8774 /** 8775 * Reset the flag indicating the accessibility state of the subtree rooted 8776 * at this view changed. 8777 */ 8778 void resetSubtreeAccessibilityStateChanged() { 8779 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 8780 } 8781 8782 /** 8783 * Report an accessibility action to this view's parents for delegated processing. 8784 * 8785 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally 8786 * call this method to delegate an accessibility action to a supporting parent. If the parent 8787 * returns true from its 8788 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)} 8789 * method this method will return true to signify that the action was consumed.</p> 8790 * 8791 * <p>This method is useful for implementing nested scrolling child views. If 8792 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action 8793 * a custom view implementation may invoke this method to allow a parent to consume the 8794 * scroll first. If this method returns true the custom view should skip its own scrolling 8795 * behavior.</p> 8796 * 8797 * @param action Accessibility action to delegate 8798 * @param arguments Optional action arguments 8799 * @return true if the action was consumed by a parent 8800 */ 8801 public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) { 8802 for (ViewParent p = getParent(); p != null; p = p.getParent()) { 8803 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) { 8804 return true; 8805 } 8806 } 8807 return false; 8808 } 8809 8810 /** 8811 * Performs the specified accessibility action on the view. For 8812 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 8813 * <p> 8814 * If an {@link AccessibilityDelegate} has been specified via calling 8815 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 8816 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 8817 * is responsible for handling this call. 8818 * </p> 8819 * 8820 * <p>The default implementation will delegate 8821 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and 8822 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if 8823 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p> 8824 * 8825 * @param action The action to perform. 8826 * @param arguments Optional action arguments. 8827 * @return Whether the action was performed. 8828 */ 8829 public boolean performAccessibilityAction(int action, Bundle arguments) { 8830 if (mAccessibilityDelegate != null) { 8831 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 8832 } else { 8833 return performAccessibilityActionInternal(action, arguments); 8834 } 8835 } 8836 8837 /** 8838 * @see #performAccessibilityAction(int, Bundle) 8839 * 8840 * Note: Called from the default {@link AccessibilityDelegate}. 8841 * 8842 * @hide 8843 */ 8844 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 8845 if (isNestedScrollingEnabled() 8846 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD 8847 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD 8848 || action == R.id.accessibilityActionScrollUp 8849 || action == R.id.accessibilityActionScrollLeft 8850 || action == R.id.accessibilityActionScrollDown 8851 || action == R.id.accessibilityActionScrollRight)) { 8852 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) { 8853 return true; 8854 } 8855 } 8856 8857 switch (action) { 8858 case AccessibilityNodeInfo.ACTION_CLICK: { 8859 if (isClickable()) { 8860 performClick(); 8861 return true; 8862 } 8863 } break; 8864 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 8865 if (isLongClickable()) { 8866 performLongClick(); 8867 return true; 8868 } 8869 } break; 8870 case AccessibilityNodeInfo.ACTION_FOCUS: { 8871 if (!hasFocus()) { 8872 // Get out of touch mode since accessibility 8873 // wants to move focus around. 8874 getViewRootImpl().ensureTouchMode(false); 8875 return requestFocus(); 8876 } 8877 } break; 8878 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 8879 if (hasFocus()) { 8880 clearFocus(); 8881 return !isFocused(); 8882 } 8883 } break; 8884 case AccessibilityNodeInfo.ACTION_SELECT: { 8885 if (!isSelected()) { 8886 setSelected(true); 8887 return isSelected(); 8888 } 8889 } break; 8890 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 8891 if (isSelected()) { 8892 setSelected(false); 8893 return !isSelected(); 8894 } 8895 } break; 8896 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 8897 if (!isAccessibilityFocused()) { 8898 return requestAccessibilityFocus(); 8899 } 8900 } break; 8901 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 8902 if (isAccessibilityFocused()) { 8903 clearAccessibilityFocus(); 8904 return true; 8905 } 8906 } break; 8907 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 8908 if (arguments != null) { 8909 final int granularity = arguments.getInt( 8910 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8911 final boolean extendSelection = arguments.getBoolean( 8912 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8913 return traverseAtGranularity(granularity, true, extendSelection); 8914 } 8915 } break; 8916 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 8917 if (arguments != null) { 8918 final int granularity = arguments.getInt( 8919 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8920 final boolean extendSelection = arguments.getBoolean( 8921 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8922 return traverseAtGranularity(granularity, false, extendSelection); 8923 } 8924 } break; 8925 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 8926 CharSequence text = getIterableTextForAccessibility(); 8927 if (text == null) { 8928 return false; 8929 } 8930 final int start = (arguments != null) ? arguments.getInt( 8931 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 8932 final int end = (arguments != null) ? arguments.getInt( 8933 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 8934 // Only cursor position can be specified (selection length == 0) 8935 if ((getAccessibilitySelectionStart() != start 8936 || getAccessibilitySelectionEnd() != end) 8937 && (start == end)) { 8938 setAccessibilitySelection(start, end); 8939 notifyViewAccessibilityStateChangedIfNeeded( 8940 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8941 return true; 8942 } 8943 } break; 8944 case R.id.accessibilityActionShowOnScreen: { 8945 if (mAttachInfo != null) { 8946 final Rect r = mAttachInfo.mTmpInvalRect; 8947 getDrawingRect(r); 8948 return requestRectangleOnScreen(r, true); 8949 } 8950 } break; 8951 case R.id.accessibilityActionStylusButtonPress: { 8952 if (isStylusButtonPressable()) { 8953 performStylusButtonPress(); 8954 return true; 8955 } 8956 } break; 8957 } 8958 return false; 8959 } 8960 8961 private boolean traverseAtGranularity(int granularity, boolean forward, 8962 boolean extendSelection) { 8963 CharSequence text = getIterableTextForAccessibility(); 8964 if (text == null || text.length() == 0) { 8965 return false; 8966 } 8967 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 8968 if (iterator == null) { 8969 return false; 8970 } 8971 int current = getAccessibilitySelectionEnd(); 8972 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 8973 current = forward ? 0 : text.length(); 8974 } 8975 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 8976 if (range == null) { 8977 return false; 8978 } 8979 final int segmentStart = range[0]; 8980 final int segmentEnd = range[1]; 8981 int selectionStart; 8982 int selectionEnd; 8983 if (extendSelection && isAccessibilitySelectionExtendable()) { 8984 selectionStart = getAccessibilitySelectionStart(); 8985 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 8986 selectionStart = forward ? segmentStart : segmentEnd; 8987 } 8988 selectionEnd = forward ? segmentEnd : segmentStart; 8989 } else { 8990 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 8991 } 8992 setAccessibilitySelection(selectionStart, selectionEnd); 8993 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 8994 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 8995 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 8996 return true; 8997 } 8998 8999 /** 9000 * Gets the text reported for accessibility purposes. 9001 * 9002 * @return The accessibility text. 9003 * 9004 * @hide 9005 */ 9006 public CharSequence getIterableTextForAccessibility() { 9007 return getContentDescription(); 9008 } 9009 9010 /** 9011 * Gets whether accessibility selection can be extended. 9012 * 9013 * @return If selection is extensible. 9014 * 9015 * @hide 9016 */ 9017 public boolean isAccessibilitySelectionExtendable() { 9018 return false; 9019 } 9020 9021 /** 9022 * @hide 9023 */ 9024 public int getAccessibilitySelectionStart() { 9025 return mAccessibilityCursorPosition; 9026 } 9027 9028 /** 9029 * @hide 9030 */ 9031 public int getAccessibilitySelectionEnd() { 9032 return getAccessibilitySelectionStart(); 9033 } 9034 9035 /** 9036 * @hide 9037 */ 9038 public void setAccessibilitySelection(int start, int end) { 9039 if (start == end && end == mAccessibilityCursorPosition) { 9040 return; 9041 } 9042 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 9043 mAccessibilityCursorPosition = start; 9044 } else { 9045 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 9046 } 9047 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 9048 } 9049 9050 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 9051 int fromIndex, int toIndex) { 9052 if (mParent == null) { 9053 return; 9054 } 9055 AccessibilityEvent event = AccessibilityEvent.obtain( 9056 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 9057 onInitializeAccessibilityEvent(event); 9058 onPopulateAccessibilityEvent(event); 9059 event.setFromIndex(fromIndex); 9060 event.setToIndex(toIndex); 9061 event.setAction(action); 9062 event.setMovementGranularity(granularity); 9063 mParent.requestSendAccessibilityEvent(this, event); 9064 } 9065 9066 /** 9067 * @hide 9068 */ 9069 public TextSegmentIterator getIteratorForGranularity(int granularity) { 9070 switch (granularity) { 9071 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 9072 CharSequence text = getIterableTextForAccessibility(); 9073 if (text != null && text.length() > 0) { 9074 CharacterTextSegmentIterator iterator = 9075 CharacterTextSegmentIterator.getInstance( 9076 mContext.getResources().getConfiguration().locale); 9077 iterator.initialize(text.toString()); 9078 return iterator; 9079 } 9080 } break; 9081 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 9082 CharSequence text = getIterableTextForAccessibility(); 9083 if (text != null && text.length() > 0) { 9084 WordTextSegmentIterator iterator = 9085 WordTextSegmentIterator.getInstance( 9086 mContext.getResources().getConfiguration().locale); 9087 iterator.initialize(text.toString()); 9088 return iterator; 9089 } 9090 } break; 9091 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 9092 CharSequence text = getIterableTextForAccessibility(); 9093 if (text != null && text.length() > 0) { 9094 ParagraphTextSegmentIterator iterator = 9095 ParagraphTextSegmentIterator.getInstance(); 9096 iterator.initialize(text.toString()); 9097 return iterator; 9098 } 9099 } break; 9100 } 9101 return null; 9102 } 9103 9104 /** 9105 * @hide 9106 */ 9107 public void dispatchStartTemporaryDetach() { 9108 onStartTemporaryDetach(); 9109 } 9110 9111 /** 9112 * This is called when a container is going to temporarily detach a child, with 9113 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 9114 * It will either be followed by {@link #onFinishTemporaryDetach()} or 9115 * {@link #onDetachedFromWindow()} when the container is done. 9116 */ 9117 public void onStartTemporaryDetach() { 9118 removeUnsetPressCallback(); 9119 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 9120 } 9121 9122 /** 9123 * @hide 9124 */ 9125 public void dispatchFinishTemporaryDetach() { 9126 onFinishTemporaryDetach(); 9127 } 9128 9129 /** 9130 * Called after {@link #onStartTemporaryDetach} when the container is done 9131 * changing the view. 9132 */ 9133 public void onFinishTemporaryDetach() { 9134 } 9135 9136 /** 9137 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 9138 * for this view's window. Returns null if the view is not currently attached 9139 * to the window. Normally you will not need to use this directly, but 9140 * just use the standard high-level event callbacks like 9141 * {@link #onKeyDown(int, KeyEvent)}. 9142 */ 9143 public KeyEvent.DispatcherState getKeyDispatcherState() { 9144 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 9145 } 9146 9147 /** 9148 * Dispatch a key event before it is processed by any input method 9149 * associated with the view hierarchy. This can be used to intercept 9150 * key events in special situations before the IME consumes them; a 9151 * typical example would be handling the BACK key to update the application's 9152 * UI instead of allowing the IME to see it and close itself. 9153 * 9154 * @param event The key event to be dispatched. 9155 * @return True if the event was handled, false otherwise. 9156 */ 9157 public boolean dispatchKeyEventPreIme(KeyEvent event) { 9158 return onKeyPreIme(event.getKeyCode(), event); 9159 } 9160 9161 /** 9162 * Dispatch a key event to the next view on the focus path. This path runs 9163 * from the top of the view tree down to the currently focused view. If this 9164 * view has focus, it will dispatch to itself. Otherwise it will dispatch 9165 * the next node down the focus path. This method also fires any key 9166 * listeners. 9167 * 9168 * @param event The key event to be dispatched. 9169 * @return True if the event was handled, false otherwise. 9170 */ 9171 public boolean dispatchKeyEvent(KeyEvent event) { 9172 if (mInputEventConsistencyVerifier != null) { 9173 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 9174 } 9175 9176 // Give any attached key listener a first crack at the event. 9177 //noinspection SimplifiableIfStatement 9178 ListenerInfo li = mListenerInfo; 9179 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 9180 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 9181 return true; 9182 } 9183 9184 if (event.dispatch(this, mAttachInfo != null 9185 ? mAttachInfo.mKeyDispatchState : null, this)) { 9186 return true; 9187 } 9188 9189 if (mInputEventConsistencyVerifier != null) { 9190 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9191 } 9192 return false; 9193 } 9194 9195 /** 9196 * Dispatches a key shortcut event. 9197 * 9198 * @param event The key event to be dispatched. 9199 * @return True if the event was handled by the view, false otherwise. 9200 */ 9201 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 9202 return onKeyShortcut(event.getKeyCode(), event); 9203 } 9204 9205 /** 9206 * Pass the touch screen motion event down to the target view, or this 9207 * view if it is the target. 9208 * 9209 * @param event The motion event to be dispatched. 9210 * @return True if the event was handled by the view, false otherwise. 9211 */ 9212 public boolean dispatchTouchEvent(MotionEvent event) { 9213 // If the event should be handled by accessibility focus first. 9214 if (event.isTargetAccessibilityFocus()) { 9215 // We don't have focus or no virtual descendant has it, do not handle the event. 9216 if (!isAccessibilityFocusedViewOrHost()) { 9217 return false; 9218 } 9219 // We have focus and got the event, then use normal event dispatch. 9220 event.setTargetAccessibilityFocus(false); 9221 } 9222 9223 boolean result = false; 9224 9225 if (mInputEventConsistencyVerifier != null) { 9226 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 9227 } 9228 9229 final int actionMasked = event.getActionMasked(); 9230 if (actionMasked == MotionEvent.ACTION_DOWN) { 9231 // Defensive cleanup for new gesture 9232 stopNestedScroll(); 9233 } 9234 9235 if (onFilterTouchEventForSecurity(event)) { 9236 //noinspection SimplifiableIfStatement 9237 ListenerInfo li = mListenerInfo; 9238 if (li != null && li.mOnTouchListener != null 9239 && (mViewFlags & ENABLED_MASK) == ENABLED 9240 && li.mOnTouchListener.onTouch(this, event)) { 9241 result = true; 9242 } 9243 9244 if (!result && onTouchEvent(event)) { 9245 result = true; 9246 } 9247 } 9248 9249 if (!result && mInputEventConsistencyVerifier != null) { 9250 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9251 } 9252 9253 // Clean up after nested scrolls if this is the end of a gesture; 9254 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 9255 // of the gesture. 9256 if (actionMasked == MotionEvent.ACTION_UP || 9257 actionMasked == MotionEvent.ACTION_CANCEL || 9258 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 9259 stopNestedScroll(); 9260 } 9261 9262 return result; 9263 } 9264 9265 boolean isAccessibilityFocusedViewOrHost() { 9266 return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl() 9267 .getAccessibilityFocusedHost() == this); 9268 } 9269 9270 /** 9271 * Filter the touch event to apply security policies. 9272 * 9273 * @param event The motion event to be filtered. 9274 * @return True if the event should be dispatched, false if the event should be dropped. 9275 * 9276 * @see #getFilterTouchesWhenObscured 9277 */ 9278 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 9279 //noinspection RedundantIfStatement 9280 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 9281 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 9282 // Window is obscured, drop this touch. 9283 return false; 9284 } 9285 return true; 9286 } 9287 9288 /** 9289 * Pass a trackball motion event down to the focused view. 9290 * 9291 * @param event The motion event to be dispatched. 9292 * @return True if the event was handled by the view, false otherwise. 9293 */ 9294 public boolean dispatchTrackballEvent(MotionEvent event) { 9295 if (mInputEventConsistencyVerifier != null) { 9296 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 9297 } 9298 9299 return onTrackballEvent(event); 9300 } 9301 9302 /** 9303 * Dispatch a generic motion event. 9304 * <p> 9305 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 9306 * are delivered to the view under the pointer. All other generic motion events are 9307 * delivered to the focused view. Hover events are handled specially and are delivered 9308 * to {@link #onHoverEvent(MotionEvent)}. 9309 * </p> 9310 * 9311 * @param event The motion event to be dispatched. 9312 * @return True if the event was handled by the view, false otherwise. 9313 */ 9314 public boolean dispatchGenericMotionEvent(MotionEvent event) { 9315 if (mInputEventConsistencyVerifier != null) { 9316 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 9317 } 9318 9319 final int source = event.getSource(); 9320 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 9321 final int action = event.getAction(); 9322 if (action == MotionEvent.ACTION_HOVER_ENTER 9323 || action == MotionEvent.ACTION_HOVER_MOVE 9324 || action == MotionEvent.ACTION_HOVER_EXIT) { 9325 if (dispatchHoverEvent(event)) { 9326 return true; 9327 } 9328 } else if (dispatchGenericPointerEvent(event)) { 9329 return true; 9330 } 9331 } else if (dispatchGenericFocusedEvent(event)) { 9332 return true; 9333 } 9334 9335 if (dispatchGenericMotionEventInternal(event)) { 9336 return true; 9337 } 9338 9339 if (mInputEventConsistencyVerifier != null) { 9340 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9341 } 9342 return false; 9343 } 9344 9345 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 9346 //noinspection SimplifiableIfStatement 9347 ListenerInfo li = mListenerInfo; 9348 if (li != null && li.mOnGenericMotionListener != null 9349 && (mViewFlags & ENABLED_MASK) == ENABLED 9350 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 9351 return true; 9352 } 9353 9354 if (onGenericMotionEvent(event)) { 9355 return true; 9356 } 9357 9358 if (mInputEventConsistencyVerifier != null) { 9359 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9360 } 9361 return false; 9362 } 9363 9364 /** 9365 * Dispatch a hover event. 9366 * <p> 9367 * Do not call this method directly. 9368 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 9369 * </p> 9370 * 9371 * @param event The motion event to be dispatched. 9372 * @return True if the event was handled by the view, false otherwise. 9373 */ 9374 protected boolean dispatchHoverEvent(MotionEvent event) { 9375 ListenerInfo li = mListenerInfo; 9376 //noinspection SimplifiableIfStatement 9377 if (li != null && li.mOnHoverListener != null 9378 && (mViewFlags & ENABLED_MASK) == ENABLED 9379 && li.mOnHoverListener.onHover(this, event)) { 9380 return true; 9381 } 9382 9383 return onHoverEvent(event); 9384 } 9385 9386 /** 9387 * Returns true if the view has a child to which it has recently sent 9388 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 9389 * it does not have a hovered child, then it must be the innermost hovered view. 9390 * @hide 9391 */ 9392 protected boolean hasHoveredChild() { 9393 return false; 9394 } 9395 9396 /** 9397 * Dispatch a generic motion event to the view under the first pointer. 9398 * <p> 9399 * Do not call this method directly. 9400 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 9401 * </p> 9402 * 9403 * @param event The motion event to be dispatched. 9404 * @return True if the event was handled by the view, false otherwise. 9405 */ 9406 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 9407 return false; 9408 } 9409 9410 /** 9411 * Dispatch a generic motion event to the currently focused view. 9412 * <p> 9413 * Do not call this method directly. 9414 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 9415 * </p> 9416 * 9417 * @param event The motion event to be dispatched. 9418 * @return True if the event was handled by the view, false otherwise. 9419 */ 9420 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 9421 return false; 9422 } 9423 9424 /** 9425 * Dispatch a pointer event. 9426 * <p> 9427 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 9428 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 9429 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 9430 * and should not be expected to handle other pointing device features. 9431 * </p> 9432 * 9433 * @param event The motion event to be dispatched. 9434 * @return True if the event was handled by the view, false otherwise. 9435 * @hide 9436 */ 9437 public final boolean dispatchPointerEvent(MotionEvent event) { 9438 if (event.isTouchEvent()) { 9439 return dispatchTouchEvent(event); 9440 } else { 9441 return dispatchGenericMotionEvent(event); 9442 } 9443 } 9444 9445 /** 9446 * Called when the window containing this view gains or loses window focus. 9447 * ViewGroups should override to route to their children. 9448 * 9449 * @param hasFocus True if the window containing this view now has focus, 9450 * false otherwise. 9451 */ 9452 public void dispatchWindowFocusChanged(boolean hasFocus) { 9453 onWindowFocusChanged(hasFocus); 9454 } 9455 9456 /** 9457 * Called when the window containing this view gains or loses focus. Note 9458 * that this is separate from view focus: to receive key events, both 9459 * your view and its window must have focus. If a window is displayed 9460 * on top of yours that takes input focus, then your own window will lose 9461 * focus but the view focus will remain unchanged. 9462 * 9463 * @param hasWindowFocus True if the window containing this view now has 9464 * focus, false otherwise. 9465 */ 9466 public void onWindowFocusChanged(boolean hasWindowFocus) { 9467 InputMethodManager imm = InputMethodManager.peekInstance(); 9468 if (!hasWindowFocus) { 9469 if (isPressed()) { 9470 setPressed(false); 9471 } 9472 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 9473 imm.focusOut(this); 9474 } 9475 removeLongPressCallback(); 9476 removeTapCallback(); 9477 onFocusLost(); 9478 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 9479 imm.focusIn(this); 9480 } 9481 refreshDrawableState(); 9482 } 9483 9484 /** 9485 * Returns true if this view is in a window that currently has window focus. 9486 * Note that this is not the same as the view itself having focus. 9487 * 9488 * @return True if this view is in a window that currently has window focus. 9489 */ 9490 public boolean hasWindowFocus() { 9491 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 9492 } 9493 9494 /** 9495 * Dispatch a view visibility change down the view hierarchy. 9496 * ViewGroups should override to route to their children. 9497 * @param changedView The view whose visibility changed. Could be 'this' or 9498 * an ancestor view. 9499 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 9500 * {@link #INVISIBLE} or {@link #GONE}. 9501 */ 9502 protected void dispatchVisibilityChanged(@NonNull View changedView, 9503 @Visibility int visibility) { 9504 onVisibilityChanged(changedView, visibility); 9505 } 9506 9507 /** 9508 * Called when the visibility of the view or an ancestor of the view has 9509 * changed. 9510 * 9511 * @param changedView The view whose visibility changed. May be 9512 * {@code this} or an ancestor view. 9513 * @param visibility The new visibility, one of {@link #VISIBLE}, 9514 * {@link #INVISIBLE} or {@link #GONE}. 9515 */ 9516 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 9517 final boolean visible = visibility == VISIBLE && getVisibility() == VISIBLE; 9518 if (visible) { 9519 if (mAttachInfo != null) { 9520 initialAwakenScrollBars(); 9521 } else { 9522 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 9523 } 9524 } 9525 9526 final Drawable dr = mBackground; 9527 if (dr != null && visible != dr.isVisible()) { 9528 dr.setVisible(visible, false); 9529 } 9530 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 9531 if (fg != null && visible != fg.isVisible()) { 9532 fg.setVisible(visible, false); 9533 } 9534 } 9535 9536 /** 9537 * Dispatch a hint about whether this view is displayed. For instance, when 9538 * a View moves out of the screen, it might receives a display hint indicating 9539 * the view is not displayed. Applications should not <em>rely</em> on this hint 9540 * as there is no guarantee that they will receive one. 9541 * 9542 * @param hint A hint about whether or not this view is displayed: 9543 * {@link #VISIBLE} or {@link #INVISIBLE}. 9544 */ 9545 public void dispatchDisplayHint(@Visibility int hint) { 9546 onDisplayHint(hint); 9547 } 9548 9549 /** 9550 * Gives this view a hint about whether is displayed or not. For instance, when 9551 * a View moves out of the screen, it might receives a display hint indicating 9552 * the view is not displayed. Applications should not <em>rely</em> on this hint 9553 * as there is no guarantee that they will receive one. 9554 * 9555 * @param hint A hint about whether or not this view is displayed: 9556 * {@link #VISIBLE} or {@link #INVISIBLE}. 9557 */ 9558 protected void onDisplayHint(@Visibility int hint) { 9559 } 9560 9561 /** 9562 * Dispatch a window visibility change down the view hierarchy. 9563 * ViewGroups should override to route to their children. 9564 * 9565 * @param visibility The new visibility of the window. 9566 * 9567 * @see #onWindowVisibilityChanged(int) 9568 */ 9569 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 9570 onWindowVisibilityChanged(visibility); 9571 } 9572 9573 /** 9574 * Called when the window containing has change its visibility 9575 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 9576 * that this tells you whether or not your window is being made visible 9577 * to the window manager; this does <em>not</em> tell you whether or not 9578 * your window is obscured by other windows on the screen, even if it 9579 * is itself visible. 9580 * 9581 * @param visibility The new visibility of the window. 9582 */ 9583 protected void onWindowVisibilityChanged(@Visibility int visibility) { 9584 if (visibility == VISIBLE) { 9585 initialAwakenScrollBars(); 9586 } 9587 } 9588 9589 /** 9590 * Returns the current visibility of the window this view is attached to 9591 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 9592 * 9593 * @return Returns the current visibility of the view's window. 9594 */ 9595 @Visibility 9596 public int getWindowVisibility() { 9597 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 9598 } 9599 9600 /** 9601 * Retrieve the overall visible display size in which the window this view is 9602 * attached to has been positioned in. This takes into account screen 9603 * decorations above the window, for both cases where the window itself 9604 * is being position inside of them or the window is being placed under 9605 * then and covered insets are used for the window to position its content 9606 * inside. In effect, this tells you the available area where content can 9607 * be placed and remain visible to users. 9608 * 9609 * <p>This function requires an IPC back to the window manager to retrieve 9610 * the requested information, so should not be used in performance critical 9611 * code like drawing. 9612 * 9613 * @param outRect Filled in with the visible display frame. If the view 9614 * is not attached to a window, this is simply the raw display size. 9615 */ 9616 public void getWindowVisibleDisplayFrame(Rect outRect) { 9617 if (mAttachInfo != null) { 9618 try { 9619 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 9620 } catch (RemoteException e) { 9621 return; 9622 } 9623 // XXX This is really broken, and probably all needs to be done 9624 // in the window manager, and we need to know more about whether 9625 // we want the area behind or in front of the IME. 9626 final Rect insets = mAttachInfo.mVisibleInsets; 9627 outRect.left += insets.left; 9628 outRect.top += insets.top; 9629 outRect.right -= insets.right; 9630 outRect.bottom -= insets.bottom; 9631 return; 9632 } 9633 // The view is not attached to a display so we don't have a context. 9634 // Make a best guess about the display size. 9635 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 9636 d.getRectSize(outRect); 9637 } 9638 9639 /** 9640 * Dispatch a notification about a resource configuration change down 9641 * the view hierarchy. 9642 * ViewGroups should override to route to their children. 9643 * 9644 * @param newConfig The new resource configuration. 9645 * 9646 * @see #onConfigurationChanged(android.content.res.Configuration) 9647 */ 9648 public void dispatchConfigurationChanged(Configuration newConfig) { 9649 onConfigurationChanged(newConfig); 9650 } 9651 9652 /** 9653 * Called when the current configuration of the resources being used 9654 * by the application have changed. You can use this to decide when 9655 * to reload resources that can changed based on orientation and other 9656 * configuration characteristics. You only need to use this if you are 9657 * not relying on the normal {@link android.app.Activity} mechanism of 9658 * recreating the activity instance upon a configuration change. 9659 * 9660 * @param newConfig The new resource configuration. 9661 */ 9662 protected void onConfigurationChanged(Configuration newConfig) { 9663 } 9664 9665 /** 9666 * Private function to aggregate all per-view attributes in to the view 9667 * root. 9668 */ 9669 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 9670 performCollectViewAttributes(attachInfo, visibility); 9671 } 9672 9673 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 9674 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 9675 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 9676 attachInfo.mKeepScreenOn = true; 9677 } 9678 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 9679 ListenerInfo li = mListenerInfo; 9680 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 9681 attachInfo.mHasSystemUiListeners = true; 9682 } 9683 } 9684 } 9685 9686 void needGlobalAttributesUpdate(boolean force) { 9687 final AttachInfo ai = mAttachInfo; 9688 if (ai != null && !ai.mRecomputeGlobalAttributes) { 9689 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 9690 || ai.mHasSystemUiListeners) { 9691 ai.mRecomputeGlobalAttributes = true; 9692 } 9693 } 9694 } 9695 9696 /** 9697 * Returns whether the device is currently in touch mode. Touch mode is entered 9698 * once the user begins interacting with the device by touch, and affects various 9699 * things like whether focus is always visible to the user. 9700 * 9701 * @return Whether the device is in touch mode. 9702 */ 9703 @ViewDebug.ExportedProperty 9704 public boolean isInTouchMode() { 9705 if (mAttachInfo != null) { 9706 return mAttachInfo.mInTouchMode; 9707 } else { 9708 return ViewRootImpl.isInTouchMode(); 9709 } 9710 } 9711 9712 /** 9713 * Returns the context the view is running in, through which it can 9714 * access the current theme, resources, etc. 9715 * 9716 * @return The view's Context. 9717 */ 9718 @ViewDebug.CapturedViewProperty 9719 public final Context getContext() { 9720 return mContext; 9721 } 9722 9723 /** 9724 * Handle a key event before it is processed by any input method 9725 * associated with the view hierarchy. This can be used to intercept 9726 * key events in special situations before the IME consumes them; a 9727 * typical example would be handling the BACK key to update the application's 9728 * UI instead of allowing the IME to see it and close itself. 9729 * 9730 * @param keyCode The value in event.getKeyCode(). 9731 * @param event Description of the key event. 9732 * @return If you handled the event, return true. If you want to allow the 9733 * event to be handled by the next receiver, return false. 9734 */ 9735 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 9736 return false; 9737 } 9738 9739 /** 9740 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 9741 * KeyEvent.Callback.onKeyDown()}: perform press of the view 9742 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 9743 * is released, if the view is enabled and clickable. 9744 * 9745 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9746 * although some may elect to do so in some situations. Do not rely on this to 9747 * catch software key presses. 9748 * 9749 * @param keyCode A key code that represents the button pressed, from 9750 * {@link android.view.KeyEvent}. 9751 * @param event The KeyEvent object that defines the button action. 9752 */ 9753 public boolean onKeyDown(int keyCode, KeyEvent event) { 9754 boolean result = false; 9755 9756 if (KeyEvent.isConfirmKey(keyCode)) { 9757 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 9758 return true; 9759 } 9760 // Long clickable items don't necessarily have to be clickable 9761 if (((mViewFlags & CLICKABLE) == CLICKABLE || 9762 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 9763 (event.getRepeatCount() == 0)) { 9764 setPressed(true); 9765 checkForLongClick(0); 9766 return true; 9767 } 9768 } 9769 return result; 9770 } 9771 9772 /** 9773 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 9774 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 9775 * the event). 9776 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9777 * although some may elect to do so in some situations. Do not rely on this to 9778 * catch software key presses. 9779 */ 9780 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 9781 return false; 9782 } 9783 9784 /** 9785 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 9786 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 9787 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 9788 * {@link KeyEvent#KEYCODE_ENTER} is released. 9789 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9790 * although some may elect to do so in some situations. Do not rely on this to 9791 * catch software key presses. 9792 * 9793 * @param keyCode A key code that represents the button pressed, from 9794 * {@link android.view.KeyEvent}. 9795 * @param event The KeyEvent object that defines the button action. 9796 */ 9797 public boolean onKeyUp(int keyCode, KeyEvent event) { 9798 if (KeyEvent.isConfirmKey(keyCode)) { 9799 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 9800 return true; 9801 } 9802 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 9803 setPressed(false); 9804 9805 if (!mHasPerformedLongPress) { 9806 // This is a tap, so remove the longpress check 9807 removeLongPressCallback(); 9808 return performClick(); 9809 } 9810 } 9811 } 9812 return false; 9813 } 9814 9815 /** 9816 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 9817 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 9818 * the event). 9819 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9820 * although some may elect to do so in some situations. Do not rely on this to 9821 * catch software key presses. 9822 * 9823 * @param keyCode A key code that represents the button pressed, from 9824 * {@link android.view.KeyEvent}. 9825 * @param repeatCount The number of times the action was made. 9826 * @param event The KeyEvent object that defines the button action. 9827 */ 9828 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 9829 return false; 9830 } 9831 9832 /** 9833 * Called on the focused view when a key shortcut event is not handled. 9834 * Override this method to implement local key shortcuts for the View. 9835 * Key shortcuts can also be implemented by setting the 9836 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 9837 * 9838 * @param keyCode The value in event.getKeyCode(). 9839 * @param event Description of the key event. 9840 * @return If you handled the event, return true. If you want to allow the 9841 * event to be handled by the next receiver, return false. 9842 */ 9843 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 9844 return false; 9845 } 9846 9847 /** 9848 * Check whether the called view is a text editor, in which case it 9849 * would make sense to automatically display a soft input window for 9850 * it. Subclasses should override this if they implement 9851 * {@link #onCreateInputConnection(EditorInfo)} to return true if 9852 * a call on that method would return a non-null InputConnection, and 9853 * they are really a first-class editor that the user would normally 9854 * start typing on when the go into a window containing your view. 9855 * 9856 * <p>The default implementation always returns false. This does 9857 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 9858 * will not be called or the user can not otherwise perform edits on your 9859 * view; it is just a hint to the system that this is not the primary 9860 * purpose of this view. 9861 * 9862 * @return Returns true if this view is a text editor, else false. 9863 */ 9864 public boolean onCheckIsTextEditor() { 9865 return false; 9866 } 9867 9868 /** 9869 * Create a new InputConnection for an InputMethod to interact 9870 * with the view. The default implementation returns null, since it doesn't 9871 * support input methods. You can override this to implement such support. 9872 * This is only needed for views that take focus and text input. 9873 * 9874 * <p>When implementing this, you probably also want to implement 9875 * {@link #onCheckIsTextEditor()} to indicate you will return a 9876 * non-null InputConnection.</p> 9877 * 9878 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 9879 * object correctly and in its entirety, so that the connected IME can rely 9880 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 9881 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 9882 * must be filled in with the correct cursor position for IMEs to work correctly 9883 * with your application.</p> 9884 * 9885 * @param outAttrs Fill in with attribute information about the connection. 9886 */ 9887 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 9888 return null; 9889 } 9890 9891 /** 9892 * Called by the {@link android.view.inputmethod.InputMethodManager} 9893 * when a view who is not the current 9894 * input connection target is trying to make a call on the manager. The 9895 * default implementation returns false; you can override this to return 9896 * true for certain views if you are performing InputConnection proxying 9897 * to them. 9898 * @param view The View that is making the InputMethodManager call. 9899 * @return Return true to allow the call, false to reject. 9900 */ 9901 public boolean checkInputConnectionProxy(View view) { 9902 return false; 9903 } 9904 9905 /** 9906 * Show the context menu for this view. It is not safe to hold on to the 9907 * menu after returning from this method. 9908 * 9909 * You should normally not overload this method. Overload 9910 * {@link #onCreateContextMenu(ContextMenu)} or define an 9911 * {@link OnCreateContextMenuListener} to add items to the context menu. 9912 * 9913 * @param menu The context menu to populate 9914 */ 9915 public void createContextMenu(ContextMenu menu) { 9916 ContextMenuInfo menuInfo = getContextMenuInfo(); 9917 9918 // Sets the current menu info so all items added to menu will have 9919 // my extra info set. 9920 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 9921 9922 onCreateContextMenu(menu); 9923 ListenerInfo li = mListenerInfo; 9924 if (li != null && li.mOnCreateContextMenuListener != null) { 9925 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 9926 } 9927 9928 // Clear the extra information so subsequent items that aren't mine don't 9929 // have my extra info. 9930 ((MenuBuilder)menu).setCurrentMenuInfo(null); 9931 9932 if (mParent != null) { 9933 mParent.createContextMenu(menu); 9934 } 9935 } 9936 9937 /** 9938 * Views should implement this if they have extra information to associate 9939 * with the context menu. The return result is supplied as a parameter to 9940 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 9941 * callback. 9942 * 9943 * @return Extra information about the item for which the context menu 9944 * should be shown. This information will vary across different 9945 * subclasses of View. 9946 */ 9947 protected ContextMenuInfo getContextMenuInfo() { 9948 return null; 9949 } 9950 9951 /** 9952 * Views should implement this if the view itself is going to add items to 9953 * the context menu. 9954 * 9955 * @param menu the context menu to populate 9956 */ 9957 protected void onCreateContextMenu(ContextMenu menu) { 9958 } 9959 9960 /** 9961 * Implement this method to handle trackball motion events. The 9962 * <em>relative</em> movement of the trackball since the last event 9963 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 9964 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 9965 * that a movement of 1 corresponds to the user pressing one DPAD key (so 9966 * they will often be fractional values, representing the more fine-grained 9967 * movement information available from a trackball). 9968 * 9969 * @param event The motion event. 9970 * @return True if the event was handled, false otherwise. 9971 */ 9972 public boolean onTrackballEvent(MotionEvent event) { 9973 return false; 9974 } 9975 9976 /** 9977 * Implement this method to handle generic motion events. 9978 * <p> 9979 * Generic motion events describe joystick movements, mouse hovers, track pad 9980 * touches, scroll wheel movements and other input events. The 9981 * {@link MotionEvent#getSource() source} of the motion event specifies 9982 * the class of input that was received. Implementations of this method 9983 * must examine the bits in the source before processing the event. 9984 * The following code example shows how this is done. 9985 * </p><p> 9986 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 9987 * are delivered to the view under the pointer. All other generic motion events are 9988 * delivered to the focused view. 9989 * </p> 9990 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 9991 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 9992 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 9993 * // process the joystick movement... 9994 * return true; 9995 * } 9996 * } 9997 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 9998 * switch (event.getAction()) { 9999 * case MotionEvent.ACTION_HOVER_MOVE: 10000 * // process the mouse hover movement... 10001 * return true; 10002 * case MotionEvent.ACTION_SCROLL: 10003 * // process the scroll wheel movement... 10004 * return true; 10005 * } 10006 * } 10007 * return super.onGenericMotionEvent(event); 10008 * }</pre> 10009 * 10010 * @param event The generic motion event being processed. 10011 * @return True if the event was handled, false otherwise. 10012 */ 10013 public boolean onGenericMotionEvent(MotionEvent event) { 10014 return false; 10015 } 10016 10017 /** 10018 * Implement this method to handle hover events. 10019 * <p> 10020 * This method is called whenever a pointer is hovering into, over, or out of the 10021 * bounds of a view and the view is not currently being touched. 10022 * Hover events are represented as pointer events with action 10023 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 10024 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 10025 * </p> 10026 * <ul> 10027 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 10028 * when the pointer enters the bounds of the view.</li> 10029 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 10030 * when the pointer has already entered the bounds of the view and has moved.</li> 10031 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 10032 * when the pointer has exited the bounds of the view or when the pointer is 10033 * about to go down due to a button click, tap, or similar user action that 10034 * causes the view to be touched.</li> 10035 * </ul> 10036 * <p> 10037 * The view should implement this method to return true to indicate that it is 10038 * handling the hover event, such as by changing its drawable state. 10039 * </p><p> 10040 * The default implementation calls {@link #setHovered} to update the hovered state 10041 * of the view when a hover enter or hover exit event is received, if the view 10042 * is enabled and is clickable. The default implementation also sends hover 10043 * accessibility events. 10044 * </p> 10045 * 10046 * @param event The motion event that describes the hover. 10047 * @return True if the view handled the hover event. 10048 * 10049 * @see #isHovered 10050 * @see #setHovered 10051 * @see #onHoverChanged 10052 */ 10053 public boolean onHoverEvent(MotionEvent event) { 10054 // The root view may receive hover (or touch) events that are outside the bounds of 10055 // the window. This code ensures that we only send accessibility events for 10056 // hovers that are actually within the bounds of the root view. 10057 final int action = event.getActionMasked(); 10058 if (!mSendingHoverAccessibilityEvents) { 10059 if ((action == MotionEvent.ACTION_HOVER_ENTER 10060 || action == MotionEvent.ACTION_HOVER_MOVE) 10061 && !hasHoveredChild() 10062 && pointInView(event.getX(), event.getY())) { 10063 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 10064 mSendingHoverAccessibilityEvents = true; 10065 } 10066 } else { 10067 if (action == MotionEvent.ACTION_HOVER_EXIT 10068 || (action == MotionEvent.ACTION_MOVE 10069 && !pointInView(event.getX(), event.getY()))) { 10070 mSendingHoverAccessibilityEvents = false; 10071 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 10072 } 10073 } 10074 10075 if (isHoverable()) { 10076 switch (action) { 10077 case MotionEvent.ACTION_HOVER_ENTER: 10078 setHovered(true); 10079 break; 10080 case MotionEvent.ACTION_HOVER_EXIT: 10081 setHovered(false); 10082 break; 10083 } 10084 10085 // Dispatch the event to onGenericMotionEvent before returning true. 10086 // This is to provide compatibility with existing applications that 10087 // handled HOVER_MOVE events in onGenericMotionEvent and that would 10088 // break because of the new default handling for hoverable views 10089 // in onHoverEvent. 10090 // Note that onGenericMotionEvent will be called by default when 10091 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 10092 dispatchGenericMotionEventInternal(event); 10093 // The event was already handled by calling setHovered(), so always 10094 // return true. 10095 return true; 10096 } 10097 10098 return false; 10099 } 10100 10101 /** 10102 * Returns true if the view should handle {@link #onHoverEvent} 10103 * by calling {@link #setHovered} to change its hovered state. 10104 * 10105 * @return True if the view is hoverable. 10106 */ 10107 private boolean isHoverable() { 10108 final int viewFlags = mViewFlags; 10109 if ((viewFlags & ENABLED_MASK) == DISABLED) { 10110 return false; 10111 } 10112 10113 return (viewFlags & CLICKABLE) == CLICKABLE 10114 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 10115 || (viewFlags & STYLUS_BUTTON_PRESSABLE) == STYLUS_BUTTON_PRESSABLE; 10116 } 10117 10118 /** 10119 * Returns true if the view is currently hovered. 10120 * 10121 * @return True if the view is currently hovered. 10122 * 10123 * @see #setHovered 10124 * @see #onHoverChanged 10125 */ 10126 @ViewDebug.ExportedProperty 10127 public boolean isHovered() { 10128 return (mPrivateFlags & PFLAG_HOVERED) != 0; 10129 } 10130 10131 /** 10132 * Sets whether the view is currently hovered. 10133 * <p> 10134 * Calling this method also changes the drawable state of the view. This 10135 * enables the view to react to hover by using different drawable resources 10136 * to change its appearance. 10137 * </p><p> 10138 * The {@link #onHoverChanged} method is called when the hovered state changes. 10139 * </p> 10140 * 10141 * @param hovered True if the view is hovered. 10142 * 10143 * @see #isHovered 10144 * @see #onHoverChanged 10145 */ 10146 public void setHovered(boolean hovered) { 10147 if (hovered) { 10148 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 10149 mPrivateFlags |= PFLAG_HOVERED; 10150 refreshDrawableState(); 10151 onHoverChanged(true); 10152 } 10153 } else { 10154 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 10155 mPrivateFlags &= ~PFLAG_HOVERED; 10156 refreshDrawableState(); 10157 onHoverChanged(false); 10158 } 10159 } 10160 } 10161 10162 /** 10163 * Implement this method to handle hover state changes. 10164 * <p> 10165 * This method is called whenever the hover state changes as a result of a 10166 * call to {@link #setHovered}. 10167 * </p> 10168 * 10169 * @param hovered The current hover state, as returned by {@link #isHovered}. 10170 * 10171 * @see #isHovered 10172 * @see #setHovered 10173 */ 10174 public void onHoverChanged(boolean hovered) { 10175 } 10176 10177 /** 10178 * Implement this method to handle touch screen motion events. 10179 * <p> 10180 * If this method is used to detect click actions, it is recommended that 10181 * the actions be performed by implementing and calling 10182 * {@link #performClick()}. This will ensure consistent system behavior, 10183 * including: 10184 * <ul> 10185 * <li>obeying click sound preferences 10186 * <li>dispatching OnClickListener calls 10187 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 10188 * accessibility features are enabled 10189 * </ul> 10190 * 10191 * @param event The motion event. 10192 * @return True if the event was handled, false otherwise. 10193 */ 10194 public boolean onTouchEvent(MotionEvent event) { 10195 final float x = event.getX(); 10196 final float y = event.getY(); 10197 final int viewFlags = mViewFlags; 10198 final int action = event.getAction(); 10199 10200 if ((viewFlags & ENABLED_MASK) == DISABLED) { 10201 if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 10202 setPressed(false); 10203 } 10204 // A disabled view that is clickable still consumes the touch 10205 // events, it just doesn't respond to them. 10206 return (((viewFlags & CLICKABLE) == CLICKABLE 10207 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 10208 || (viewFlags & STYLUS_BUTTON_PRESSABLE) == STYLUS_BUTTON_PRESSABLE); 10209 } 10210 10211 if (mTouchDelegate != null) { 10212 if (mTouchDelegate.onTouchEvent(event)) { 10213 return true; 10214 } 10215 } 10216 10217 if (((viewFlags & CLICKABLE) == CLICKABLE || 10218 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) || 10219 (viewFlags & STYLUS_BUTTON_PRESSABLE) == STYLUS_BUTTON_PRESSABLE) { 10220 switch (action) { 10221 case MotionEvent.ACTION_UP: 10222 if (mInStylusButtonPress) { 10223 mInStylusButtonPress = false; 10224 mHasPerformedLongPress = false; 10225 } 10226 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 10227 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 10228 // take focus if we don't have it already and we should in 10229 // touch mode. 10230 boolean focusTaken = false; 10231 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 10232 focusTaken = requestFocus(); 10233 } 10234 10235 if (prepressed) { 10236 // The button is being released before we actually 10237 // showed it as pressed. Make it show the pressed 10238 // state now (before scheduling the click) to ensure 10239 // the user sees it. 10240 setPressed(true, x, y); 10241 } 10242 10243 if (!mHasPerformedLongPress) { 10244 // This is a tap, so remove the longpress check 10245 removeLongPressCallback(); 10246 10247 // Only perform take click actions if we were in the pressed state 10248 if (!focusTaken) { 10249 // Use a Runnable and post this rather than calling 10250 // performClick directly. This lets other visual state 10251 // of the view update before click actions start. 10252 if (mPerformClick == null) { 10253 mPerformClick = new PerformClick(); 10254 } 10255 if (!post(mPerformClick)) { 10256 performClick(); 10257 } 10258 } 10259 } 10260 10261 if (mUnsetPressedState == null) { 10262 mUnsetPressedState = new UnsetPressedState(); 10263 } 10264 10265 if (prepressed) { 10266 postDelayed(mUnsetPressedState, 10267 ViewConfiguration.getPressedStateDuration()); 10268 } else if (!post(mUnsetPressedState)) { 10269 // If the post failed, unpress right now 10270 mUnsetPressedState.run(); 10271 } 10272 10273 removeTapCallback(); 10274 } 10275 break; 10276 10277 case MotionEvent.ACTION_DOWN: 10278 mHasPerformedLongPress = false; 10279 mInStylusButtonPress = false; 10280 10281 if (performStylusActionOnButtonPress(event)) { 10282 break; 10283 } 10284 10285 if (performButtonActionOnTouchDown(event)) { 10286 break; 10287 } 10288 10289 // Walk up the hierarchy to determine if we're inside a scrolling container. 10290 boolean isInScrollingContainer = isInScrollingContainer(); 10291 10292 // For views inside a scrolling container, delay the pressed feedback for 10293 // a short period in case this is a scroll. 10294 if (isInScrollingContainer) { 10295 mPrivateFlags |= PFLAG_PREPRESSED; 10296 if (mPendingCheckForTap == null) { 10297 mPendingCheckForTap = new CheckForTap(); 10298 } 10299 mPendingCheckForTap.x = event.getX(); 10300 mPendingCheckForTap.y = event.getY(); 10301 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 10302 } else { 10303 // Not inside a scrolling container, so show the feedback right away 10304 setPressed(true, x, y); 10305 checkForLongClick(0); 10306 } 10307 break; 10308 10309 case MotionEvent.ACTION_CANCEL: 10310 setPressed(false); 10311 removeTapCallback(); 10312 removeLongPressCallback(); 10313 if (mInStylusButtonPress) { 10314 mInStylusButtonPress = false; 10315 mHasPerformedLongPress = false; 10316 } 10317 break; 10318 10319 case MotionEvent.ACTION_MOVE: 10320 drawableHotspotChanged(x, y); 10321 10322 // Be lenient about moving outside of buttons 10323 if (!pointInView(x, y, mTouchSlop)) { 10324 // Outside button 10325 removeTapCallback(); 10326 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 10327 // Remove any future long press/tap checks 10328 removeLongPressCallback(); 10329 10330 setPressed(false); 10331 } 10332 } else if (performStylusActionOnButtonPress(event)) { 10333 // Check for stylus button press if we're within the view. 10334 break; 10335 } 10336 break; 10337 } 10338 10339 return true; 10340 } 10341 10342 return false; 10343 } 10344 10345 /** 10346 * @hide 10347 */ 10348 public boolean isInScrollingContainer() { 10349 ViewParent p = getParent(); 10350 while (p != null && p instanceof ViewGroup) { 10351 if (((ViewGroup) p).shouldDelayChildPressedState()) { 10352 return true; 10353 } 10354 p = p.getParent(); 10355 } 10356 return false; 10357 } 10358 10359 /** 10360 * Remove the longpress detection timer. 10361 */ 10362 private void removeLongPressCallback() { 10363 if (mPendingCheckForLongPress != null) { 10364 removeCallbacks(mPendingCheckForLongPress); 10365 } 10366 } 10367 10368 /** 10369 * Remove the pending click action 10370 */ 10371 private void removePerformClickCallback() { 10372 if (mPerformClick != null) { 10373 removeCallbacks(mPerformClick); 10374 } 10375 } 10376 10377 /** 10378 * Remove the prepress detection timer. 10379 */ 10380 private void removeUnsetPressCallback() { 10381 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 10382 setPressed(false); 10383 removeCallbacks(mUnsetPressedState); 10384 } 10385 } 10386 10387 /** 10388 * Remove the tap detection timer. 10389 */ 10390 private void removeTapCallback() { 10391 if (mPendingCheckForTap != null) { 10392 mPrivateFlags &= ~PFLAG_PREPRESSED; 10393 removeCallbacks(mPendingCheckForTap); 10394 } 10395 } 10396 10397 /** 10398 * Cancels a pending long press. Your subclass can use this if you 10399 * want the context menu to come up if the user presses and holds 10400 * at the same place, but you don't want it to come up if they press 10401 * and then move around enough to cause scrolling. 10402 */ 10403 public void cancelLongPress() { 10404 removeLongPressCallback(); 10405 10406 /* 10407 * The prepressed state handled by the tap callback is a display 10408 * construct, but the tap callback will post a long press callback 10409 * less its own timeout. Remove it here. 10410 */ 10411 removeTapCallback(); 10412 } 10413 10414 /** 10415 * Remove the pending callback for sending a 10416 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 10417 */ 10418 private void removeSendViewScrolledAccessibilityEventCallback() { 10419 if (mSendViewScrolledAccessibilityEvent != null) { 10420 removeCallbacks(mSendViewScrolledAccessibilityEvent); 10421 mSendViewScrolledAccessibilityEvent.mIsPending = false; 10422 } 10423 } 10424 10425 /** 10426 * Sets the TouchDelegate for this View. 10427 */ 10428 public void setTouchDelegate(TouchDelegate delegate) { 10429 mTouchDelegate = delegate; 10430 } 10431 10432 /** 10433 * Gets the TouchDelegate for this View. 10434 */ 10435 public TouchDelegate getTouchDelegate() { 10436 return mTouchDelegate; 10437 } 10438 10439 /** 10440 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 10441 * 10442 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 10443 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 10444 * available. This method should only be called for touch events. 10445 * 10446 * <p class="note">This api is not intended for most applications. Buffered dispatch 10447 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 10448 * streams will not improve your input latency. Side effects include: increased latency, 10449 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 10450 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 10451 * you.</p> 10452 */ 10453 public final void requestUnbufferedDispatch(MotionEvent event) { 10454 final int action = event.getAction(); 10455 if (mAttachInfo == null 10456 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 10457 || !event.isTouchEvent()) { 10458 return; 10459 } 10460 mAttachInfo.mUnbufferedDispatchRequested = true; 10461 } 10462 10463 /** 10464 * Set flags controlling behavior of this view. 10465 * 10466 * @param flags Constant indicating the value which should be set 10467 * @param mask Constant indicating the bit range that should be changed 10468 */ 10469 void setFlags(int flags, int mask) { 10470 final boolean accessibilityEnabled = 10471 AccessibilityManager.getInstance(mContext).isEnabled(); 10472 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 10473 10474 int old = mViewFlags; 10475 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 10476 10477 int changed = mViewFlags ^ old; 10478 if (changed == 0) { 10479 return; 10480 } 10481 int privateFlags = mPrivateFlags; 10482 10483 /* Check if the FOCUSABLE bit has changed */ 10484 if (((changed & FOCUSABLE_MASK) != 0) && 10485 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 10486 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 10487 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 10488 /* Give up focus if we are no longer focusable */ 10489 clearFocus(); 10490 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 10491 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 10492 /* 10493 * Tell the view system that we are now available to take focus 10494 * if no one else already has it. 10495 */ 10496 if (mParent != null) mParent.focusableViewAvailable(this); 10497 } 10498 } 10499 10500 final int newVisibility = flags & VISIBILITY_MASK; 10501 if (newVisibility == VISIBLE) { 10502 if ((changed & VISIBILITY_MASK) != 0) { 10503 /* 10504 * If this view is becoming visible, invalidate it in case it changed while 10505 * it was not visible. Marking it drawn ensures that the invalidation will 10506 * go through. 10507 */ 10508 mPrivateFlags |= PFLAG_DRAWN; 10509 invalidate(true); 10510 10511 needGlobalAttributesUpdate(true); 10512 10513 // a view becoming visible is worth notifying the parent 10514 // about in case nothing has focus. even if this specific view 10515 // isn't focusable, it may contain something that is, so let 10516 // the root view try to give this focus if nothing else does. 10517 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 10518 mParent.focusableViewAvailable(this); 10519 } 10520 } 10521 } 10522 10523 /* Check if the GONE bit has changed */ 10524 if ((changed & GONE) != 0) { 10525 needGlobalAttributesUpdate(false); 10526 requestLayout(); 10527 10528 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 10529 if (hasFocus()) clearFocus(); 10530 clearAccessibilityFocus(); 10531 destroyDrawingCache(); 10532 if (mParent instanceof View) { 10533 // GONE views noop invalidation, so invalidate the parent 10534 ((View) mParent).invalidate(true); 10535 } 10536 // Mark the view drawn to ensure that it gets invalidated properly the next 10537 // time it is visible and gets invalidated 10538 mPrivateFlags |= PFLAG_DRAWN; 10539 } 10540 if (mAttachInfo != null) { 10541 mAttachInfo.mViewVisibilityChanged = true; 10542 } 10543 } 10544 10545 /* Check if the VISIBLE bit has changed */ 10546 if ((changed & INVISIBLE) != 0) { 10547 needGlobalAttributesUpdate(false); 10548 /* 10549 * If this view is becoming invisible, set the DRAWN flag so that 10550 * the next invalidate() will not be skipped. 10551 */ 10552 mPrivateFlags |= PFLAG_DRAWN; 10553 10554 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 10555 // root view becoming invisible shouldn't clear focus and accessibility focus 10556 if (getRootView() != this) { 10557 if (hasFocus()) clearFocus(); 10558 clearAccessibilityFocus(); 10559 } 10560 } 10561 if (mAttachInfo != null) { 10562 mAttachInfo.mViewVisibilityChanged = true; 10563 } 10564 } 10565 10566 if ((changed & VISIBILITY_MASK) != 0) { 10567 // If the view is invisible, cleanup its display list to free up resources 10568 if (newVisibility != VISIBLE && mAttachInfo != null) { 10569 cleanupDraw(); 10570 } 10571 10572 if (mParent instanceof ViewGroup) { 10573 ((ViewGroup) mParent).onChildVisibilityChanged(this, 10574 (changed & VISIBILITY_MASK), newVisibility); 10575 ((View) mParent).invalidate(true); 10576 } else if (mParent != null) { 10577 mParent.invalidateChild(this, null); 10578 } 10579 dispatchVisibilityChanged(this, newVisibility); 10580 10581 notifySubtreeAccessibilityStateChangedIfNeeded(); 10582 } 10583 10584 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 10585 destroyDrawingCache(); 10586 } 10587 10588 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 10589 destroyDrawingCache(); 10590 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10591 invalidateParentCaches(); 10592 } 10593 10594 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 10595 destroyDrawingCache(); 10596 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10597 } 10598 10599 if ((changed & DRAW_MASK) != 0) { 10600 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 10601 if (mBackground != null) { 10602 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 10603 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 10604 } else { 10605 mPrivateFlags |= PFLAG_SKIP_DRAW; 10606 } 10607 } else { 10608 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 10609 } 10610 requestLayout(); 10611 invalidate(true); 10612 } 10613 10614 if ((changed & KEEP_SCREEN_ON) != 0) { 10615 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 10616 mParent.recomputeViewAttributes(this); 10617 } 10618 } 10619 10620 if (accessibilityEnabled) { 10621 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 10622 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0 10623 || (changed & STYLUS_BUTTON_PRESSABLE) != 0) { 10624 if (oldIncludeForAccessibility != includeForAccessibility()) { 10625 notifySubtreeAccessibilityStateChangedIfNeeded(); 10626 } else { 10627 notifyViewAccessibilityStateChangedIfNeeded( 10628 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10629 } 10630 } else if ((changed & ENABLED_MASK) != 0) { 10631 notifyViewAccessibilityStateChangedIfNeeded( 10632 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10633 } 10634 } 10635 } 10636 10637 /** 10638 * Change the view's z order in the tree, so it's on top of other sibling 10639 * views. This ordering change may affect layout, if the parent container 10640 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 10641 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 10642 * method should be followed by calls to {@link #requestLayout()} and 10643 * {@link View#invalidate()} on the view's parent to force the parent to redraw 10644 * with the new child ordering. 10645 * 10646 * @see ViewGroup#bringChildToFront(View) 10647 */ 10648 public void bringToFront() { 10649 if (mParent != null) { 10650 mParent.bringChildToFront(this); 10651 } 10652 } 10653 10654 /** 10655 * This is called in response to an internal scroll in this view (i.e., the 10656 * view scrolled its own contents). This is typically as a result of 10657 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 10658 * called. 10659 * 10660 * @param l Current horizontal scroll origin. 10661 * @param t Current vertical scroll origin. 10662 * @param oldl Previous horizontal scroll origin. 10663 * @param oldt Previous vertical scroll origin. 10664 */ 10665 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 10666 notifySubtreeAccessibilityStateChangedIfNeeded(); 10667 10668 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 10669 postSendViewScrolledAccessibilityEventCallback(); 10670 } 10671 10672 mBackgroundSizeChanged = true; 10673 if (mForegroundInfo != null) { 10674 mForegroundInfo.mBoundsChanged = true; 10675 } 10676 10677 final AttachInfo ai = mAttachInfo; 10678 if (ai != null) { 10679 ai.mViewScrollChanged = true; 10680 } 10681 10682 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 10683 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 10684 } 10685 } 10686 10687 /** 10688 * Interface definition for a callback to be invoked when the scroll 10689 * X or Y positions of a view change. 10690 * <p> 10691 * <b>Note:</b> Some views handle scrolling independently from View and may 10692 * have their own separate listeners for scroll-type events. For example, 10693 * {@link android.widget.ListView ListView} allows clients to register an 10694 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 10695 * to listen for changes in list scroll position. 10696 * 10697 * @see #setOnScrollChangeListener(View.OnScrollChangeListener) 10698 */ 10699 public interface OnScrollChangeListener { 10700 /** 10701 * Called when the scroll position of a view changes. 10702 * 10703 * @param v The view whose scroll position has changed. 10704 * @param scrollX Current horizontal scroll origin. 10705 * @param scrollY Current vertical scroll origin. 10706 * @param oldScrollX Previous horizontal scroll origin. 10707 * @param oldScrollY Previous vertical scroll origin. 10708 */ 10709 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 10710 } 10711 10712 /** 10713 * Interface definition for a callback to be invoked when the layout bounds of a view 10714 * changes due to layout processing. 10715 */ 10716 public interface OnLayoutChangeListener { 10717 /** 10718 * Called when the layout bounds of a view changes due to layout processing. 10719 * 10720 * @param v The view whose bounds have changed. 10721 * @param left The new value of the view's left property. 10722 * @param top The new value of the view's top property. 10723 * @param right The new value of the view's right property. 10724 * @param bottom The new value of the view's bottom property. 10725 * @param oldLeft The previous value of the view's left property. 10726 * @param oldTop The previous value of the view's top property. 10727 * @param oldRight The previous value of the view's right property. 10728 * @param oldBottom The previous value of the view's bottom property. 10729 */ 10730 void onLayoutChange(View v, int left, int top, int right, int bottom, 10731 int oldLeft, int oldTop, int oldRight, int oldBottom); 10732 } 10733 10734 /** 10735 * This is called during layout when the size of this view has changed. If 10736 * you were just added to the view hierarchy, you're called with the old 10737 * values of 0. 10738 * 10739 * @param w Current width of this view. 10740 * @param h Current height of this view. 10741 * @param oldw Old width of this view. 10742 * @param oldh Old height of this view. 10743 */ 10744 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 10745 } 10746 10747 /** 10748 * Called by draw to draw the child views. This may be overridden 10749 * by derived classes to gain control just before its children are drawn 10750 * (but after its own view has been drawn). 10751 * @param canvas the canvas on which to draw the view 10752 */ 10753 protected void dispatchDraw(Canvas canvas) { 10754 10755 } 10756 10757 /** 10758 * Gets the parent of this view. Note that the parent is a 10759 * ViewParent and not necessarily a View. 10760 * 10761 * @return Parent of this view. 10762 */ 10763 public final ViewParent getParent() { 10764 return mParent; 10765 } 10766 10767 /** 10768 * Set the horizontal scrolled position of your view. This will cause a call to 10769 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10770 * invalidated. 10771 * @param value the x position to scroll to 10772 */ 10773 public void setScrollX(int value) { 10774 scrollTo(value, mScrollY); 10775 } 10776 10777 /** 10778 * Set the vertical scrolled position of your view. This will cause a call to 10779 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10780 * invalidated. 10781 * @param value the y position to scroll to 10782 */ 10783 public void setScrollY(int value) { 10784 scrollTo(mScrollX, value); 10785 } 10786 10787 /** 10788 * Return the scrolled left position of this view. This is the left edge of 10789 * the displayed part of your view. You do not need to draw any pixels 10790 * farther left, since those are outside of the frame of your view on 10791 * screen. 10792 * 10793 * @return The left edge of the displayed part of your view, in pixels. 10794 */ 10795 public final int getScrollX() { 10796 return mScrollX; 10797 } 10798 10799 /** 10800 * Return the scrolled top position of this view. This is the top edge of 10801 * the displayed part of your view. You do not need to draw any pixels above 10802 * it, since those are outside of the frame of your view on screen. 10803 * 10804 * @return The top edge of the displayed part of your view, in pixels. 10805 */ 10806 public final int getScrollY() { 10807 return mScrollY; 10808 } 10809 10810 /** 10811 * Return the width of the your view. 10812 * 10813 * @return The width of your view, in pixels. 10814 */ 10815 @ViewDebug.ExportedProperty(category = "layout") 10816 public final int getWidth() { 10817 return mRight - mLeft; 10818 } 10819 10820 /** 10821 * Return the height of your view. 10822 * 10823 * @return The height of your view, in pixels. 10824 */ 10825 @ViewDebug.ExportedProperty(category = "layout") 10826 public final int getHeight() { 10827 return mBottom - mTop; 10828 } 10829 10830 /** 10831 * Return the visible drawing bounds of your view. Fills in the output 10832 * rectangle with the values from getScrollX(), getScrollY(), 10833 * getWidth(), and getHeight(). These bounds do not account for any 10834 * transformation properties currently set on the view, such as 10835 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 10836 * 10837 * @param outRect The (scrolled) drawing bounds of the view. 10838 */ 10839 public void getDrawingRect(Rect outRect) { 10840 outRect.left = mScrollX; 10841 outRect.top = mScrollY; 10842 outRect.right = mScrollX + (mRight - mLeft); 10843 outRect.bottom = mScrollY + (mBottom - mTop); 10844 } 10845 10846 /** 10847 * Like {@link #getMeasuredWidthAndState()}, but only returns the 10848 * raw width component (that is the result is masked by 10849 * {@link #MEASURED_SIZE_MASK}). 10850 * 10851 * @return The raw measured width of this view. 10852 */ 10853 public final int getMeasuredWidth() { 10854 return mMeasuredWidth & MEASURED_SIZE_MASK; 10855 } 10856 10857 /** 10858 * Return the full width measurement information for this view as computed 10859 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 10860 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 10861 * This should be used during measurement and layout calculations only. Use 10862 * {@link #getWidth()} to see how wide a view is after layout. 10863 * 10864 * @return The measured width of this view as a bit mask. 10865 */ 10866 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 10867 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 10868 name = "MEASURED_STATE_TOO_SMALL"), 10869 }) 10870 public final int getMeasuredWidthAndState() { 10871 return mMeasuredWidth; 10872 } 10873 10874 /** 10875 * Like {@link #getMeasuredHeightAndState()}, but only returns the 10876 * raw width component (that is the result is masked by 10877 * {@link #MEASURED_SIZE_MASK}). 10878 * 10879 * @return The raw measured height of this view. 10880 */ 10881 public final int getMeasuredHeight() { 10882 return mMeasuredHeight & MEASURED_SIZE_MASK; 10883 } 10884 10885 /** 10886 * Return the full height measurement information for this view as computed 10887 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 10888 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 10889 * This should be used during measurement and layout calculations only. Use 10890 * {@link #getHeight()} to see how wide a view is after layout. 10891 * 10892 * @return The measured width of this view as a bit mask. 10893 */ 10894 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 10895 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 10896 name = "MEASURED_STATE_TOO_SMALL"), 10897 }) 10898 public final int getMeasuredHeightAndState() { 10899 return mMeasuredHeight; 10900 } 10901 10902 /** 10903 * Return only the state bits of {@link #getMeasuredWidthAndState()} 10904 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 10905 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 10906 * and the height component is at the shifted bits 10907 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 10908 */ 10909 public final int getMeasuredState() { 10910 return (mMeasuredWidth&MEASURED_STATE_MASK) 10911 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 10912 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 10913 } 10914 10915 /** 10916 * The transform matrix of this view, which is calculated based on the current 10917 * rotation, scale, and pivot properties. 10918 * 10919 * @see #getRotation() 10920 * @see #getScaleX() 10921 * @see #getScaleY() 10922 * @see #getPivotX() 10923 * @see #getPivotY() 10924 * @return The current transform matrix for the view 10925 */ 10926 public Matrix getMatrix() { 10927 ensureTransformationInfo(); 10928 final Matrix matrix = mTransformationInfo.mMatrix; 10929 mRenderNode.getMatrix(matrix); 10930 return matrix; 10931 } 10932 10933 /** 10934 * Returns true if the transform matrix is the identity matrix. 10935 * Recomputes the matrix if necessary. 10936 * 10937 * @return True if the transform matrix is the identity matrix, false otherwise. 10938 */ 10939 final boolean hasIdentityMatrix() { 10940 return mRenderNode.hasIdentityMatrix(); 10941 } 10942 10943 void ensureTransformationInfo() { 10944 if (mTransformationInfo == null) { 10945 mTransformationInfo = new TransformationInfo(); 10946 } 10947 } 10948 10949 /** 10950 * Utility method to retrieve the inverse of the current mMatrix property. 10951 * We cache the matrix to avoid recalculating it when transform properties 10952 * have not changed. 10953 * 10954 * @return The inverse of the current matrix of this view. 10955 * @hide 10956 */ 10957 public final Matrix getInverseMatrix() { 10958 ensureTransformationInfo(); 10959 if (mTransformationInfo.mInverseMatrix == null) { 10960 mTransformationInfo.mInverseMatrix = new Matrix(); 10961 } 10962 final Matrix matrix = mTransformationInfo.mInverseMatrix; 10963 mRenderNode.getInverseMatrix(matrix); 10964 return matrix; 10965 } 10966 10967 /** 10968 * Gets the distance along the Z axis from the camera to this view. 10969 * 10970 * @see #setCameraDistance(float) 10971 * 10972 * @return The distance along the Z axis. 10973 */ 10974 public float getCameraDistance() { 10975 final float dpi = mResources.getDisplayMetrics().densityDpi; 10976 return -(mRenderNode.getCameraDistance() * dpi); 10977 } 10978 10979 /** 10980 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 10981 * views are drawn) from the camera to this view. The camera's distance 10982 * affects 3D transformations, for instance rotations around the X and Y 10983 * axis. If the rotationX or rotationY properties are changed and this view is 10984 * large (more than half the size of the screen), it is recommended to always 10985 * use a camera distance that's greater than the height (X axis rotation) or 10986 * the width (Y axis rotation) of this view.</p> 10987 * 10988 * <p>The distance of the camera from the view plane can have an affect on the 10989 * perspective distortion of the view when it is rotated around the x or y axis. 10990 * For example, a large distance will result in a large viewing angle, and there 10991 * will not be much perspective distortion of the view as it rotates. A short 10992 * distance may cause much more perspective distortion upon rotation, and can 10993 * also result in some drawing artifacts if the rotated view ends up partially 10994 * behind the camera (which is why the recommendation is to use a distance at 10995 * least as far as the size of the view, if the view is to be rotated.)</p> 10996 * 10997 * <p>The distance is expressed in "depth pixels." The default distance depends 10998 * on the screen density. For instance, on a medium density display, the 10999 * default distance is 1280. On a high density display, the default distance 11000 * is 1920.</p> 11001 * 11002 * <p>If you want to specify a distance that leads to visually consistent 11003 * results across various densities, use the following formula:</p> 11004 * <pre> 11005 * float scale = context.getResources().getDisplayMetrics().density; 11006 * view.setCameraDistance(distance * scale); 11007 * </pre> 11008 * 11009 * <p>The density scale factor of a high density display is 1.5, 11010 * and 1920 = 1280 * 1.5.</p> 11011 * 11012 * @param distance The distance in "depth pixels", if negative the opposite 11013 * value is used 11014 * 11015 * @see #setRotationX(float) 11016 * @see #setRotationY(float) 11017 */ 11018 public void setCameraDistance(float distance) { 11019 final float dpi = mResources.getDisplayMetrics().densityDpi; 11020 11021 invalidateViewProperty(true, false); 11022 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 11023 invalidateViewProperty(false, false); 11024 11025 invalidateParentIfNeededAndWasQuickRejected(); 11026 } 11027 11028 /** 11029 * The degrees that the view is rotated around the pivot point. 11030 * 11031 * @see #setRotation(float) 11032 * @see #getPivotX() 11033 * @see #getPivotY() 11034 * 11035 * @return The degrees of rotation. 11036 */ 11037 @ViewDebug.ExportedProperty(category = "drawing") 11038 public float getRotation() { 11039 return mRenderNode.getRotation(); 11040 } 11041 11042 /** 11043 * Sets the degrees that the view is rotated around the pivot point. Increasing values 11044 * result in clockwise rotation. 11045 * 11046 * @param rotation The degrees of rotation. 11047 * 11048 * @see #getRotation() 11049 * @see #getPivotX() 11050 * @see #getPivotY() 11051 * @see #setRotationX(float) 11052 * @see #setRotationY(float) 11053 * 11054 * @attr ref android.R.styleable#View_rotation 11055 */ 11056 public void setRotation(float rotation) { 11057 if (rotation != getRotation()) { 11058 // Double-invalidation is necessary to capture view's old and new areas 11059 invalidateViewProperty(true, false); 11060 mRenderNode.setRotation(rotation); 11061 invalidateViewProperty(false, true); 11062 11063 invalidateParentIfNeededAndWasQuickRejected(); 11064 notifySubtreeAccessibilityStateChangedIfNeeded(); 11065 } 11066 } 11067 11068 /** 11069 * The degrees that the view is rotated around the vertical axis through the pivot point. 11070 * 11071 * @see #getPivotX() 11072 * @see #getPivotY() 11073 * @see #setRotationY(float) 11074 * 11075 * @return The degrees of Y rotation. 11076 */ 11077 @ViewDebug.ExportedProperty(category = "drawing") 11078 public float getRotationY() { 11079 return mRenderNode.getRotationY(); 11080 } 11081 11082 /** 11083 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 11084 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 11085 * down the y axis. 11086 * 11087 * When rotating large views, it is recommended to adjust the camera distance 11088 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 11089 * 11090 * @param rotationY The degrees of Y rotation. 11091 * 11092 * @see #getRotationY() 11093 * @see #getPivotX() 11094 * @see #getPivotY() 11095 * @see #setRotation(float) 11096 * @see #setRotationX(float) 11097 * @see #setCameraDistance(float) 11098 * 11099 * @attr ref android.R.styleable#View_rotationY 11100 */ 11101 public void setRotationY(float rotationY) { 11102 if (rotationY != getRotationY()) { 11103 invalidateViewProperty(true, false); 11104 mRenderNode.setRotationY(rotationY); 11105 invalidateViewProperty(false, true); 11106 11107 invalidateParentIfNeededAndWasQuickRejected(); 11108 notifySubtreeAccessibilityStateChangedIfNeeded(); 11109 } 11110 } 11111 11112 /** 11113 * The degrees that the view is rotated around the horizontal axis through the pivot point. 11114 * 11115 * @see #getPivotX() 11116 * @see #getPivotY() 11117 * @see #setRotationX(float) 11118 * 11119 * @return The degrees of X rotation. 11120 */ 11121 @ViewDebug.ExportedProperty(category = "drawing") 11122 public float getRotationX() { 11123 return mRenderNode.getRotationX(); 11124 } 11125 11126 /** 11127 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 11128 * Increasing values result in clockwise rotation from the viewpoint of looking down the 11129 * x axis. 11130 * 11131 * When rotating large views, it is recommended to adjust the camera distance 11132 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 11133 * 11134 * @param rotationX The degrees of X rotation. 11135 * 11136 * @see #getRotationX() 11137 * @see #getPivotX() 11138 * @see #getPivotY() 11139 * @see #setRotation(float) 11140 * @see #setRotationY(float) 11141 * @see #setCameraDistance(float) 11142 * 11143 * @attr ref android.R.styleable#View_rotationX 11144 */ 11145 public void setRotationX(float rotationX) { 11146 if (rotationX != getRotationX()) { 11147 invalidateViewProperty(true, false); 11148 mRenderNode.setRotationX(rotationX); 11149 invalidateViewProperty(false, true); 11150 11151 invalidateParentIfNeededAndWasQuickRejected(); 11152 notifySubtreeAccessibilityStateChangedIfNeeded(); 11153 } 11154 } 11155 11156 /** 11157 * The amount that the view is scaled in x around the pivot point, as a proportion of 11158 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 11159 * 11160 * <p>By default, this is 1.0f. 11161 * 11162 * @see #getPivotX() 11163 * @see #getPivotY() 11164 * @return The scaling factor. 11165 */ 11166 @ViewDebug.ExportedProperty(category = "drawing") 11167 public float getScaleX() { 11168 return mRenderNode.getScaleX(); 11169 } 11170 11171 /** 11172 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 11173 * the view's unscaled width. A value of 1 means that no scaling is applied. 11174 * 11175 * @param scaleX The scaling factor. 11176 * @see #getPivotX() 11177 * @see #getPivotY() 11178 * 11179 * @attr ref android.R.styleable#View_scaleX 11180 */ 11181 public void setScaleX(float scaleX) { 11182 if (scaleX != getScaleX()) { 11183 invalidateViewProperty(true, false); 11184 mRenderNode.setScaleX(scaleX); 11185 invalidateViewProperty(false, true); 11186 11187 invalidateParentIfNeededAndWasQuickRejected(); 11188 notifySubtreeAccessibilityStateChangedIfNeeded(); 11189 } 11190 } 11191 11192 /** 11193 * The amount that the view is scaled in y around the pivot point, as a proportion of 11194 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 11195 * 11196 * <p>By default, this is 1.0f. 11197 * 11198 * @see #getPivotX() 11199 * @see #getPivotY() 11200 * @return The scaling factor. 11201 */ 11202 @ViewDebug.ExportedProperty(category = "drawing") 11203 public float getScaleY() { 11204 return mRenderNode.getScaleY(); 11205 } 11206 11207 /** 11208 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 11209 * the view's unscaled width. A value of 1 means that no scaling is applied. 11210 * 11211 * @param scaleY The scaling factor. 11212 * @see #getPivotX() 11213 * @see #getPivotY() 11214 * 11215 * @attr ref android.R.styleable#View_scaleY 11216 */ 11217 public void setScaleY(float scaleY) { 11218 if (scaleY != getScaleY()) { 11219 invalidateViewProperty(true, false); 11220 mRenderNode.setScaleY(scaleY); 11221 invalidateViewProperty(false, true); 11222 11223 invalidateParentIfNeededAndWasQuickRejected(); 11224 notifySubtreeAccessibilityStateChangedIfNeeded(); 11225 } 11226 } 11227 11228 /** 11229 * The x location of the point around which the view is {@link #setRotation(float) rotated} 11230 * and {@link #setScaleX(float) scaled}. 11231 * 11232 * @see #getRotation() 11233 * @see #getScaleX() 11234 * @see #getScaleY() 11235 * @see #getPivotY() 11236 * @return The x location of the pivot point. 11237 * 11238 * @attr ref android.R.styleable#View_transformPivotX 11239 */ 11240 @ViewDebug.ExportedProperty(category = "drawing") 11241 public float getPivotX() { 11242 return mRenderNode.getPivotX(); 11243 } 11244 11245 /** 11246 * Sets the x location of the point around which the view is 11247 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 11248 * By default, the pivot point is centered on the object. 11249 * Setting this property disables this behavior and causes the view to use only the 11250 * explicitly set pivotX and pivotY values. 11251 * 11252 * @param pivotX The x location of the pivot point. 11253 * @see #getRotation() 11254 * @see #getScaleX() 11255 * @see #getScaleY() 11256 * @see #getPivotY() 11257 * 11258 * @attr ref android.R.styleable#View_transformPivotX 11259 */ 11260 public void setPivotX(float pivotX) { 11261 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 11262 invalidateViewProperty(true, false); 11263 mRenderNode.setPivotX(pivotX); 11264 invalidateViewProperty(false, true); 11265 11266 invalidateParentIfNeededAndWasQuickRejected(); 11267 } 11268 } 11269 11270 /** 11271 * The y location of the point around which the view is {@link #setRotation(float) rotated} 11272 * and {@link #setScaleY(float) scaled}. 11273 * 11274 * @see #getRotation() 11275 * @see #getScaleX() 11276 * @see #getScaleY() 11277 * @see #getPivotY() 11278 * @return The y location of the pivot point. 11279 * 11280 * @attr ref android.R.styleable#View_transformPivotY 11281 */ 11282 @ViewDebug.ExportedProperty(category = "drawing") 11283 public float getPivotY() { 11284 return mRenderNode.getPivotY(); 11285 } 11286 11287 /** 11288 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 11289 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 11290 * Setting this property disables this behavior and causes the view to use only the 11291 * explicitly set pivotX and pivotY values. 11292 * 11293 * @param pivotY The y location of the pivot point. 11294 * @see #getRotation() 11295 * @see #getScaleX() 11296 * @see #getScaleY() 11297 * @see #getPivotY() 11298 * 11299 * @attr ref android.R.styleable#View_transformPivotY 11300 */ 11301 public void setPivotY(float pivotY) { 11302 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 11303 invalidateViewProperty(true, false); 11304 mRenderNode.setPivotY(pivotY); 11305 invalidateViewProperty(false, true); 11306 11307 invalidateParentIfNeededAndWasQuickRejected(); 11308 } 11309 } 11310 11311 /** 11312 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 11313 * completely transparent and 1 means the view is completely opaque. 11314 * 11315 * <p>By default this is 1.0f. 11316 * @return The opacity of the view. 11317 */ 11318 @ViewDebug.ExportedProperty(category = "drawing") 11319 public float getAlpha() { 11320 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 11321 } 11322 11323 /** 11324 * Returns whether this View has content which overlaps. 11325 * 11326 * <p>This function, intended to be overridden by specific View types, is an optimization when 11327 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 11328 * an offscreen buffer and then composited into place, which can be expensive. If the view has 11329 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 11330 * directly. An example of overlapping rendering is a TextView with a background image, such as 11331 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 11332 * ImageView with only the foreground image. The default implementation returns true; subclasses 11333 * should override if they have cases which can be optimized.</p> 11334 * 11335 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 11336 * necessitates that a View return true if it uses the methods internally without passing the 11337 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 11338 * 11339 * @return true if the content in this view might overlap, false otherwise. 11340 */ 11341 @ViewDebug.ExportedProperty(category = "drawing") 11342 public boolean hasOverlappingRendering() { 11343 return true; 11344 } 11345 11346 /** 11347 * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is 11348 * completely transparent and 1 means the view is completely opaque. 11349 * 11350 * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1) 11351 * can have significant performance implications, especially for large views. It is best to use 11352 * the alpha property sparingly and transiently, as in the case of fading animations.</p> 11353 * 11354 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 11355 * strongly recommended for performance reasons to either override 11356 * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a 11357 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration 11358 * of the animation. On versions {@link android.os.Build.VERSION_CODES#MNC} and below, 11359 * the default path for rendering an unlayered View with alpha could add multiple milliseconds 11360 * of rendering cost, even for simple or small views. Starting with 11361 * {@link android.os.Build.VERSION_CODES#MNC}, {@link #LAYER_TYPE_HARDWARE} is automatically 11362 * applied to the view at the rendering level.</p> 11363 * 11364 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 11365 * responsible for applying the opacity itself.</p> 11366 * 11367 * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if 11368 * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is 11369 * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an 11370 * alpha value less than 1.0 will supersede the alpha of the layer paint.</p> 11371 * 11372 * <p>Starting with {@link android.os.Build.VERSION_CODES#MNC}, setting a translucent alpha 11373 * value will clip a View to its bounds, unless the View returns <code>false</code> from 11374 * {@link #hasOverlappingRendering}.</p> 11375 * 11376 * @param alpha The opacity of the view. 11377 * 11378 * @see #hasOverlappingRendering() 11379 * @see #setLayerType(int, android.graphics.Paint) 11380 * 11381 * @attr ref android.R.styleable#View_alpha 11382 */ 11383 public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) { 11384 ensureTransformationInfo(); 11385 if (mTransformationInfo.mAlpha != alpha) { 11386 mTransformationInfo.mAlpha = alpha; 11387 if (onSetAlpha((int) (alpha * 255))) { 11388 mPrivateFlags |= PFLAG_ALPHA_SET; 11389 // subclass is handling alpha - don't optimize rendering cache invalidation 11390 invalidateParentCaches(); 11391 invalidate(true); 11392 } else { 11393 mPrivateFlags &= ~PFLAG_ALPHA_SET; 11394 invalidateViewProperty(true, false); 11395 mRenderNode.setAlpha(getFinalAlpha()); 11396 notifyViewAccessibilityStateChangedIfNeeded( 11397 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11398 } 11399 } 11400 } 11401 11402 /** 11403 * Faster version of setAlpha() which performs the same steps except there are 11404 * no calls to invalidate(). The caller of this function should perform proper invalidation 11405 * on the parent and this object. The return value indicates whether the subclass handles 11406 * alpha (the return value for onSetAlpha()). 11407 * 11408 * @param alpha The new value for the alpha property 11409 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 11410 * the new value for the alpha property is different from the old value 11411 */ 11412 boolean setAlphaNoInvalidation(float alpha) { 11413 ensureTransformationInfo(); 11414 if (mTransformationInfo.mAlpha != alpha) { 11415 mTransformationInfo.mAlpha = alpha; 11416 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 11417 if (subclassHandlesAlpha) { 11418 mPrivateFlags |= PFLAG_ALPHA_SET; 11419 return true; 11420 } else { 11421 mPrivateFlags &= ~PFLAG_ALPHA_SET; 11422 mRenderNode.setAlpha(getFinalAlpha()); 11423 } 11424 } 11425 return false; 11426 } 11427 11428 /** 11429 * This property is hidden and intended only for use by the Fade transition, which 11430 * animates it to produce a visual translucency that does not side-effect (or get 11431 * affected by) the real alpha property. This value is composited with the other 11432 * alpha value (and the AlphaAnimation value, when that is present) to produce 11433 * a final visual translucency result, which is what is passed into the DisplayList. 11434 * 11435 * @hide 11436 */ 11437 public void setTransitionAlpha(float alpha) { 11438 ensureTransformationInfo(); 11439 if (mTransformationInfo.mTransitionAlpha != alpha) { 11440 mTransformationInfo.mTransitionAlpha = alpha; 11441 mPrivateFlags &= ~PFLAG_ALPHA_SET; 11442 invalidateViewProperty(true, false); 11443 mRenderNode.setAlpha(getFinalAlpha()); 11444 } 11445 } 11446 11447 /** 11448 * Calculates the visual alpha of this view, which is a combination of the actual 11449 * alpha value and the transitionAlpha value (if set). 11450 */ 11451 private float getFinalAlpha() { 11452 if (mTransformationInfo != null) { 11453 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 11454 } 11455 return 1; 11456 } 11457 11458 /** 11459 * This property is hidden and intended only for use by the Fade transition, which 11460 * animates it to produce a visual translucency that does not side-effect (or get 11461 * affected by) the real alpha property. This value is composited with the other 11462 * alpha value (and the AlphaAnimation value, when that is present) to produce 11463 * a final visual translucency result, which is what is passed into the DisplayList. 11464 * 11465 * @hide 11466 */ 11467 @ViewDebug.ExportedProperty(category = "drawing") 11468 public float getTransitionAlpha() { 11469 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 11470 } 11471 11472 /** 11473 * Top position of this view relative to its parent. 11474 * 11475 * @return The top of this view, in pixels. 11476 */ 11477 @ViewDebug.CapturedViewProperty 11478 public final int getTop() { 11479 return mTop; 11480 } 11481 11482 /** 11483 * Sets the top position of this view relative to its parent. This method is meant to be called 11484 * by the layout system and should not generally be called otherwise, because the property 11485 * may be changed at any time by the layout. 11486 * 11487 * @param top The top of this view, in pixels. 11488 */ 11489 public final void setTop(int top) { 11490 if (top != mTop) { 11491 final boolean matrixIsIdentity = hasIdentityMatrix(); 11492 if (matrixIsIdentity) { 11493 if (mAttachInfo != null) { 11494 int minTop; 11495 int yLoc; 11496 if (top < mTop) { 11497 minTop = top; 11498 yLoc = top - mTop; 11499 } else { 11500 minTop = mTop; 11501 yLoc = 0; 11502 } 11503 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 11504 } 11505 } else { 11506 // Double-invalidation is necessary to capture view's old and new areas 11507 invalidate(true); 11508 } 11509 11510 int width = mRight - mLeft; 11511 int oldHeight = mBottom - mTop; 11512 11513 mTop = top; 11514 mRenderNode.setTop(mTop); 11515 11516 sizeChange(width, mBottom - mTop, width, oldHeight); 11517 11518 if (!matrixIsIdentity) { 11519 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11520 invalidate(true); 11521 } 11522 mBackgroundSizeChanged = true; 11523 if (mForegroundInfo != null) { 11524 mForegroundInfo.mBoundsChanged = true; 11525 } 11526 invalidateParentIfNeeded(); 11527 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 11528 // View was rejected last time it was drawn by its parent; this may have changed 11529 invalidateParentIfNeeded(); 11530 } 11531 } 11532 } 11533 11534 /** 11535 * Bottom position of this view relative to its parent. 11536 * 11537 * @return The bottom of this view, in pixels. 11538 */ 11539 @ViewDebug.CapturedViewProperty 11540 public final int getBottom() { 11541 return mBottom; 11542 } 11543 11544 /** 11545 * True if this view has changed since the last time being drawn. 11546 * 11547 * @return The dirty state of this view. 11548 */ 11549 public boolean isDirty() { 11550 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 11551 } 11552 11553 /** 11554 * Sets the bottom position of this view relative to its parent. This method is meant to be 11555 * called by the layout system and should not generally be called otherwise, because the 11556 * property may be changed at any time by the layout. 11557 * 11558 * @param bottom The bottom of this view, in pixels. 11559 */ 11560 public final void setBottom(int bottom) { 11561 if (bottom != mBottom) { 11562 final boolean matrixIsIdentity = hasIdentityMatrix(); 11563 if (matrixIsIdentity) { 11564 if (mAttachInfo != null) { 11565 int maxBottom; 11566 if (bottom < mBottom) { 11567 maxBottom = mBottom; 11568 } else { 11569 maxBottom = bottom; 11570 } 11571 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 11572 } 11573 } else { 11574 // Double-invalidation is necessary to capture view's old and new areas 11575 invalidate(true); 11576 } 11577 11578 int width = mRight - mLeft; 11579 int oldHeight = mBottom - mTop; 11580 11581 mBottom = bottom; 11582 mRenderNode.setBottom(mBottom); 11583 11584 sizeChange(width, mBottom - mTop, width, oldHeight); 11585 11586 if (!matrixIsIdentity) { 11587 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11588 invalidate(true); 11589 } 11590 mBackgroundSizeChanged = true; 11591 if (mForegroundInfo != null) { 11592 mForegroundInfo.mBoundsChanged = true; 11593 } 11594 invalidateParentIfNeeded(); 11595 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 11596 // View was rejected last time it was drawn by its parent; this may have changed 11597 invalidateParentIfNeeded(); 11598 } 11599 } 11600 } 11601 11602 /** 11603 * Left position of this view relative to its parent. 11604 * 11605 * @return The left edge of this view, in pixels. 11606 */ 11607 @ViewDebug.CapturedViewProperty 11608 public final int getLeft() { 11609 return mLeft; 11610 } 11611 11612 /** 11613 * Sets the left position of this view relative to its parent. This method is meant to be called 11614 * by the layout system and should not generally be called otherwise, because the property 11615 * may be changed at any time by the layout. 11616 * 11617 * @param left The left of this view, in pixels. 11618 */ 11619 public final void setLeft(int left) { 11620 if (left != mLeft) { 11621 final boolean matrixIsIdentity = hasIdentityMatrix(); 11622 if (matrixIsIdentity) { 11623 if (mAttachInfo != null) { 11624 int minLeft; 11625 int xLoc; 11626 if (left < mLeft) { 11627 minLeft = left; 11628 xLoc = left - mLeft; 11629 } else { 11630 minLeft = mLeft; 11631 xLoc = 0; 11632 } 11633 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 11634 } 11635 } else { 11636 // Double-invalidation is necessary to capture view's old and new areas 11637 invalidate(true); 11638 } 11639 11640 int oldWidth = mRight - mLeft; 11641 int height = mBottom - mTop; 11642 11643 mLeft = left; 11644 mRenderNode.setLeft(left); 11645 11646 sizeChange(mRight - mLeft, height, oldWidth, height); 11647 11648 if (!matrixIsIdentity) { 11649 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11650 invalidate(true); 11651 } 11652 mBackgroundSizeChanged = true; 11653 if (mForegroundInfo != null) { 11654 mForegroundInfo.mBoundsChanged = true; 11655 } 11656 invalidateParentIfNeeded(); 11657 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 11658 // View was rejected last time it was drawn by its parent; this may have changed 11659 invalidateParentIfNeeded(); 11660 } 11661 } 11662 } 11663 11664 /** 11665 * Right position of this view relative to its parent. 11666 * 11667 * @return The right edge of this view, in pixels. 11668 */ 11669 @ViewDebug.CapturedViewProperty 11670 public final int getRight() { 11671 return mRight; 11672 } 11673 11674 /** 11675 * Sets the right position of this view relative to its parent. This method is meant to be called 11676 * by the layout system and should not generally be called otherwise, because the property 11677 * may be changed at any time by the layout. 11678 * 11679 * @param right The right of this view, in pixels. 11680 */ 11681 public final void setRight(int right) { 11682 if (right != mRight) { 11683 final boolean matrixIsIdentity = hasIdentityMatrix(); 11684 if (matrixIsIdentity) { 11685 if (mAttachInfo != null) { 11686 int maxRight; 11687 if (right < mRight) { 11688 maxRight = mRight; 11689 } else { 11690 maxRight = right; 11691 } 11692 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 11693 } 11694 } else { 11695 // Double-invalidation is necessary to capture view's old and new areas 11696 invalidate(true); 11697 } 11698 11699 int oldWidth = mRight - mLeft; 11700 int height = mBottom - mTop; 11701 11702 mRight = right; 11703 mRenderNode.setRight(mRight); 11704 11705 sizeChange(mRight - mLeft, height, oldWidth, height); 11706 11707 if (!matrixIsIdentity) { 11708 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11709 invalidate(true); 11710 } 11711 mBackgroundSizeChanged = true; 11712 if (mForegroundInfo != null) { 11713 mForegroundInfo.mBoundsChanged = true; 11714 } 11715 invalidateParentIfNeeded(); 11716 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 11717 // View was rejected last time it was drawn by its parent; this may have changed 11718 invalidateParentIfNeeded(); 11719 } 11720 } 11721 } 11722 11723 /** 11724 * The visual x position of this view, in pixels. This is equivalent to the 11725 * {@link #setTranslationX(float) translationX} property plus the current 11726 * {@link #getLeft() left} property. 11727 * 11728 * @return The visual x position of this view, in pixels. 11729 */ 11730 @ViewDebug.ExportedProperty(category = "drawing") 11731 public float getX() { 11732 return mLeft + getTranslationX(); 11733 } 11734 11735 /** 11736 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 11737 * {@link #setTranslationX(float) translationX} property to be the difference between 11738 * the x value passed in and the current {@link #getLeft() left} property. 11739 * 11740 * @param x The visual x position of this view, in pixels. 11741 */ 11742 public void setX(float x) { 11743 setTranslationX(x - mLeft); 11744 } 11745 11746 /** 11747 * The visual y position of this view, in pixels. This is equivalent to the 11748 * {@link #setTranslationY(float) translationY} property plus the current 11749 * {@link #getTop() top} property. 11750 * 11751 * @return The visual y position of this view, in pixels. 11752 */ 11753 @ViewDebug.ExportedProperty(category = "drawing") 11754 public float getY() { 11755 return mTop + getTranslationY(); 11756 } 11757 11758 /** 11759 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 11760 * {@link #setTranslationY(float) translationY} property to be the difference between 11761 * the y value passed in and the current {@link #getTop() top} property. 11762 * 11763 * @param y The visual y position of this view, in pixels. 11764 */ 11765 public void setY(float y) { 11766 setTranslationY(y - mTop); 11767 } 11768 11769 /** 11770 * The visual z position of this view, in pixels. This is equivalent to the 11771 * {@link #setTranslationZ(float) translationZ} property plus the current 11772 * {@link #getElevation() elevation} property. 11773 * 11774 * @return The visual z position of this view, in pixels. 11775 */ 11776 @ViewDebug.ExportedProperty(category = "drawing") 11777 public float getZ() { 11778 return getElevation() + getTranslationZ(); 11779 } 11780 11781 /** 11782 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 11783 * {@link #setTranslationZ(float) translationZ} property to be the difference between 11784 * the x value passed in and the current {@link #getElevation() elevation} property. 11785 * 11786 * @param z The visual z position of this view, in pixels. 11787 */ 11788 public void setZ(float z) { 11789 setTranslationZ(z - getElevation()); 11790 } 11791 11792 /** 11793 * The base elevation of this view relative to its parent, in pixels. 11794 * 11795 * @return The base depth position of the view, in pixels. 11796 */ 11797 @ViewDebug.ExportedProperty(category = "drawing") 11798 public float getElevation() { 11799 return mRenderNode.getElevation(); 11800 } 11801 11802 /** 11803 * Sets the base elevation of this view, in pixels. 11804 * 11805 * @attr ref android.R.styleable#View_elevation 11806 */ 11807 public void setElevation(float elevation) { 11808 if (elevation != getElevation()) { 11809 invalidateViewProperty(true, false); 11810 mRenderNode.setElevation(elevation); 11811 invalidateViewProperty(false, true); 11812 11813 invalidateParentIfNeededAndWasQuickRejected(); 11814 } 11815 } 11816 11817 /** 11818 * The horizontal location of this view relative to its {@link #getLeft() left} position. 11819 * This position is post-layout, in addition to wherever the object's 11820 * layout placed it. 11821 * 11822 * @return The horizontal position of this view relative to its left position, in pixels. 11823 */ 11824 @ViewDebug.ExportedProperty(category = "drawing") 11825 public float getTranslationX() { 11826 return mRenderNode.getTranslationX(); 11827 } 11828 11829 /** 11830 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 11831 * This effectively positions the object post-layout, in addition to wherever the object's 11832 * layout placed it. 11833 * 11834 * @param translationX The horizontal position of this view relative to its left position, 11835 * in pixels. 11836 * 11837 * @attr ref android.R.styleable#View_translationX 11838 */ 11839 public void setTranslationX(float translationX) { 11840 if (translationX != getTranslationX()) { 11841 invalidateViewProperty(true, false); 11842 mRenderNode.setTranslationX(translationX); 11843 invalidateViewProperty(false, true); 11844 11845 invalidateParentIfNeededAndWasQuickRejected(); 11846 notifySubtreeAccessibilityStateChangedIfNeeded(); 11847 } 11848 } 11849 11850 /** 11851 * The vertical location of this view relative to its {@link #getTop() top} position. 11852 * This position is post-layout, in addition to wherever the object's 11853 * layout placed it. 11854 * 11855 * @return The vertical position of this view relative to its top position, 11856 * in pixels. 11857 */ 11858 @ViewDebug.ExportedProperty(category = "drawing") 11859 public float getTranslationY() { 11860 return mRenderNode.getTranslationY(); 11861 } 11862 11863 /** 11864 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 11865 * This effectively positions the object post-layout, in addition to wherever the object's 11866 * layout placed it. 11867 * 11868 * @param translationY The vertical position of this view relative to its top position, 11869 * in pixels. 11870 * 11871 * @attr ref android.R.styleable#View_translationY 11872 */ 11873 public void setTranslationY(float translationY) { 11874 if (translationY != getTranslationY()) { 11875 invalidateViewProperty(true, false); 11876 mRenderNode.setTranslationY(translationY); 11877 invalidateViewProperty(false, true); 11878 11879 invalidateParentIfNeededAndWasQuickRejected(); 11880 notifySubtreeAccessibilityStateChangedIfNeeded(); 11881 } 11882 } 11883 11884 /** 11885 * The depth location of this view relative to its {@link #getElevation() elevation}. 11886 * 11887 * @return The depth of this view relative to its elevation. 11888 */ 11889 @ViewDebug.ExportedProperty(category = "drawing") 11890 public float getTranslationZ() { 11891 return mRenderNode.getTranslationZ(); 11892 } 11893 11894 /** 11895 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 11896 * 11897 * @attr ref android.R.styleable#View_translationZ 11898 */ 11899 public void setTranslationZ(float translationZ) { 11900 if (translationZ != getTranslationZ()) { 11901 invalidateViewProperty(true, false); 11902 mRenderNode.setTranslationZ(translationZ); 11903 invalidateViewProperty(false, true); 11904 11905 invalidateParentIfNeededAndWasQuickRejected(); 11906 } 11907 } 11908 11909 /** @hide */ 11910 public void setAnimationMatrix(Matrix matrix) { 11911 invalidateViewProperty(true, false); 11912 mRenderNode.setAnimationMatrix(matrix); 11913 invalidateViewProperty(false, true); 11914 11915 invalidateParentIfNeededAndWasQuickRejected(); 11916 } 11917 11918 /** 11919 * Returns the current StateListAnimator if exists. 11920 * 11921 * @return StateListAnimator or null if it does not exists 11922 * @see #setStateListAnimator(android.animation.StateListAnimator) 11923 */ 11924 public StateListAnimator getStateListAnimator() { 11925 return mStateListAnimator; 11926 } 11927 11928 /** 11929 * Attaches the provided StateListAnimator to this View. 11930 * <p> 11931 * Any previously attached StateListAnimator will be detached. 11932 * 11933 * @param stateListAnimator The StateListAnimator to update the view 11934 * @see {@link android.animation.StateListAnimator} 11935 */ 11936 public void setStateListAnimator(StateListAnimator stateListAnimator) { 11937 if (mStateListAnimator == stateListAnimator) { 11938 return; 11939 } 11940 if (mStateListAnimator != null) { 11941 mStateListAnimator.setTarget(null); 11942 } 11943 mStateListAnimator = stateListAnimator; 11944 if (stateListAnimator != null) { 11945 stateListAnimator.setTarget(this); 11946 if (isAttachedToWindow()) { 11947 stateListAnimator.setState(getDrawableState()); 11948 } 11949 } 11950 } 11951 11952 /** 11953 * Returns whether the Outline should be used to clip the contents of the View. 11954 * <p> 11955 * Note that this flag will only be respected if the View's Outline returns true from 11956 * {@link Outline#canClip()}. 11957 * 11958 * @see #setOutlineProvider(ViewOutlineProvider) 11959 * @see #setClipToOutline(boolean) 11960 */ 11961 public final boolean getClipToOutline() { 11962 return mRenderNode.getClipToOutline(); 11963 } 11964 11965 /** 11966 * Sets whether the View's Outline should be used to clip the contents of the View. 11967 * <p> 11968 * Only a single non-rectangular clip can be applied on a View at any time. 11969 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 11970 * circular reveal} animation take priority over Outline clipping, and 11971 * child Outline clipping takes priority over Outline clipping done by a 11972 * parent. 11973 * <p> 11974 * Note that this flag will only be respected if the View's Outline returns true from 11975 * {@link Outline#canClip()}. 11976 * 11977 * @see #setOutlineProvider(ViewOutlineProvider) 11978 * @see #getClipToOutline() 11979 */ 11980 public void setClipToOutline(boolean clipToOutline) { 11981 damageInParent(); 11982 if (getClipToOutline() != clipToOutline) { 11983 mRenderNode.setClipToOutline(clipToOutline); 11984 } 11985 } 11986 11987 // correspond to the enum values of View_outlineProvider 11988 private static final int PROVIDER_BACKGROUND = 0; 11989 private static final int PROVIDER_NONE = 1; 11990 private static final int PROVIDER_BOUNDS = 2; 11991 private static final int PROVIDER_PADDED_BOUNDS = 3; 11992 private void setOutlineProviderFromAttribute(int providerInt) { 11993 switch (providerInt) { 11994 case PROVIDER_BACKGROUND: 11995 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 11996 break; 11997 case PROVIDER_NONE: 11998 setOutlineProvider(null); 11999 break; 12000 case PROVIDER_BOUNDS: 12001 setOutlineProvider(ViewOutlineProvider.BOUNDS); 12002 break; 12003 case PROVIDER_PADDED_BOUNDS: 12004 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 12005 break; 12006 } 12007 } 12008 12009 /** 12010 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 12011 * the shape of the shadow it casts, and enables outline clipping. 12012 * <p> 12013 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 12014 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 12015 * outline provider with this method allows this behavior to be overridden. 12016 * <p> 12017 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 12018 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 12019 * <p> 12020 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 12021 * 12022 * @see #setClipToOutline(boolean) 12023 * @see #getClipToOutline() 12024 * @see #getOutlineProvider() 12025 */ 12026 public void setOutlineProvider(ViewOutlineProvider provider) { 12027 mOutlineProvider = provider; 12028 invalidateOutline(); 12029 } 12030 12031 /** 12032 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 12033 * that defines the shape of the shadow it casts, and enables outline clipping. 12034 * 12035 * @see #setOutlineProvider(ViewOutlineProvider) 12036 */ 12037 public ViewOutlineProvider getOutlineProvider() { 12038 return mOutlineProvider; 12039 } 12040 12041 /** 12042 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 12043 * 12044 * @see #setOutlineProvider(ViewOutlineProvider) 12045 */ 12046 public void invalidateOutline() { 12047 rebuildOutline(); 12048 12049 notifySubtreeAccessibilityStateChangedIfNeeded(); 12050 invalidateViewProperty(false, false); 12051 } 12052 12053 /** 12054 * Internal version of {@link #invalidateOutline()} which invalidates the 12055 * outline without invalidating the view itself. This is intended to be called from 12056 * within methods in the View class itself which are the result of the view being 12057 * invalidated already. For example, when we are drawing the background of a View, 12058 * we invalidate the outline in case it changed in the meantime, but we do not 12059 * need to invalidate the view because we're already drawing the background as part 12060 * of drawing the view in response to an earlier invalidation of the view. 12061 */ 12062 private void rebuildOutline() { 12063 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 12064 if (mAttachInfo == null) return; 12065 12066 if (mOutlineProvider == null) { 12067 // no provider, remove outline 12068 mRenderNode.setOutline(null); 12069 } else { 12070 final Outline outline = mAttachInfo.mTmpOutline; 12071 outline.setEmpty(); 12072 outline.setAlpha(1.0f); 12073 12074 mOutlineProvider.getOutline(this, outline); 12075 mRenderNode.setOutline(outline); 12076 } 12077 } 12078 12079 /** 12080 * HierarchyViewer only 12081 * 12082 * @hide 12083 */ 12084 @ViewDebug.ExportedProperty(category = "drawing") 12085 public boolean hasShadow() { 12086 return mRenderNode.hasShadow(); 12087 } 12088 12089 12090 /** @hide */ 12091 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 12092 mRenderNode.setRevealClip(shouldClip, x, y, radius); 12093 invalidateViewProperty(false, false); 12094 } 12095 12096 /** 12097 * Hit rectangle in parent's coordinates 12098 * 12099 * @param outRect The hit rectangle of the view. 12100 */ 12101 public void getHitRect(Rect outRect) { 12102 if (hasIdentityMatrix() || mAttachInfo == null) { 12103 outRect.set(mLeft, mTop, mRight, mBottom); 12104 } else { 12105 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 12106 tmpRect.set(0, 0, getWidth(), getHeight()); 12107 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 12108 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 12109 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 12110 } 12111 } 12112 12113 /** 12114 * Determines whether the given point, in local coordinates is inside the view. 12115 */ 12116 /*package*/ final boolean pointInView(float localX, float localY) { 12117 return localX >= 0 && localX < (mRight - mLeft) 12118 && localY >= 0 && localY < (mBottom - mTop); 12119 } 12120 12121 /** 12122 * Utility method to determine whether the given point, in local coordinates, 12123 * is inside the view, where the area of the view is expanded by the slop factor. 12124 * This method is called while processing touch-move events to determine if the event 12125 * is still within the view. 12126 * 12127 * @hide 12128 */ 12129 public boolean pointInView(float localX, float localY, float slop) { 12130 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 12131 localY < ((mBottom - mTop) + slop); 12132 } 12133 12134 /** 12135 * When a view has focus and the user navigates away from it, the next view is searched for 12136 * starting from the rectangle filled in by this method. 12137 * 12138 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 12139 * of the view. However, if your view maintains some idea of internal selection, 12140 * such as a cursor, or a selected row or column, you should override this method and 12141 * fill in a more specific rectangle. 12142 * 12143 * @param r The rectangle to fill in, in this view's coordinates. 12144 */ 12145 public void getFocusedRect(Rect r) { 12146 getDrawingRect(r); 12147 } 12148 12149 /** 12150 * If some part of this view is not clipped by any of its parents, then 12151 * return that area in r in global (root) coordinates. To convert r to local 12152 * coordinates (without taking possible View rotations into account), offset 12153 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 12154 * If the view is completely clipped or translated out, return false. 12155 * 12156 * @param r If true is returned, r holds the global coordinates of the 12157 * visible portion of this view. 12158 * @param globalOffset If true is returned, globalOffset holds the dx,dy 12159 * between this view and its root. globalOffet may be null. 12160 * @return true if r is non-empty (i.e. part of the view is visible at the 12161 * root level. 12162 */ 12163 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 12164 int width = mRight - mLeft; 12165 int height = mBottom - mTop; 12166 if (width > 0 && height > 0) { 12167 r.set(0, 0, width, height); 12168 if (globalOffset != null) { 12169 globalOffset.set(-mScrollX, -mScrollY); 12170 } 12171 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 12172 } 12173 return false; 12174 } 12175 12176 public final boolean getGlobalVisibleRect(Rect r) { 12177 return getGlobalVisibleRect(r, null); 12178 } 12179 12180 public final boolean getLocalVisibleRect(Rect r) { 12181 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 12182 if (getGlobalVisibleRect(r, offset)) { 12183 r.offset(-offset.x, -offset.y); // make r local 12184 return true; 12185 } 12186 return false; 12187 } 12188 12189 /** 12190 * Offset this view's vertical location by the specified number of pixels. 12191 * 12192 * @param offset the number of pixels to offset the view by 12193 */ 12194 public void offsetTopAndBottom(int offset) { 12195 if (offset != 0) { 12196 final boolean matrixIsIdentity = hasIdentityMatrix(); 12197 if (matrixIsIdentity) { 12198 if (isHardwareAccelerated()) { 12199 invalidateViewProperty(false, false); 12200 } else { 12201 final ViewParent p = mParent; 12202 if (p != null && mAttachInfo != null) { 12203 final Rect r = mAttachInfo.mTmpInvalRect; 12204 int minTop; 12205 int maxBottom; 12206 int yLoc; 12207 if (offset < 0) { 12208 minTop = mTop + offset; 12209 maxBottom = mBottom; 12210 yLoc = offset; 12211 } else { 12212 minTop = mTop; 12213 maxBottom = mBottom + offset; 12214 yLoc = 0; 12215 } 12216 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 12217 p.invalidateChild(this, r); 12218 } 12219 } 12220 } else { 12221 invalidateViewProperty(false, false); 12222 } 12223 12224 mTop += offset; 12225 mBottom += offset; 12226 mRenderNode.offsetTopAndBottom(offset); 12227 if (isHardwareAccelerated()) { 12228 invalidateViewProperty(false, false); 12229 } else { 12230 if (!matrixIsIdentity) { 12231 invalidateViewProperty(false, true); 12232 } 12233 invalidateParentIfNeeded(); 12234 } 12235 notifySubtreeAccessibilityStateChangedIfNeeded(); 12236 } 12237 } 12238 12239 /** 12240 * Offset this view's horizontal location by the specified amount of pixels. 12241 * 12242 * @param offset the number of pixels to offset the view by 12243 */ 12244 public void offsetLeftAndRight(int offset) { 12245 if (offset != 0) { 12246 final boolean matrixIsIdentity = hasIdentityMatrix(); 12247 if (matrixIsIdentity) { 12248 if (isHardwareAccelerated()) { 12249 invalidateViewProperty(false, false); 12250 } else { 12251 final ViewParent p = mParent; 12252 if (p != null && mAttachInfo != null) { 12253 final Rect r = mAttachInfo.mTmpInvalRect; 12254 int minLeft; 12255 int maxRight; 12256 if (offset < 0) { 12257 minLeft = mLeft + offset; 12258 maxRight = mRight; 12259 } else { 12260 minLeft = mLeft; 12261 maxRight = mRight + offset; 12262 } 12263 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 12264 p.invalidateChild(this, r); 12265 } 12266 } 12267 } else { 12268 invalidateViewProperty(false, false); 12269 } 12270 12271 mLeft += offset; 12272 mRight += offset; 12273 mRenderNode.offsetLeftAndRight(offset); 12274 if (isHardwareAccelerated()) { 12275 invalidateViewProperty(false, false); 12276 } else { 12277 if (!matrixIsIdentity) { 12278 invalidateViewProperty(false, true); 12279 } 12280 invalidateParentIfNeeded(); 12281 } 12282 notifySubtreeAccessibilityStateChangedIfNeeded(); 12283 } 12284 } 12285 12286 /** 12287 * Get the LayoutParams associated with this view. All views should have 12288 * layout parameters. These supply parameters to the <i>parent</i> of this 12289 * view specifying how it should be arranged. There are many subclasses of 12290 * ViewGroup.LayoutParams, and these correspond to the different subclasses 12291 * of ViewGroup that are responsible for arranging their children. 12292 * 12293 * This method may return null if this View is not attached to a parent 12294 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 12295 * was not invoked successfully. When a View is attached to a parent 12296 * ViewGroup, this method must not return null. 12297 * 12298 * @return The LayoutParams associated with this view, or null if no 12299 * parameters have been set yet 12300 */ 12301 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 12302 public ViewGroup.LayoutParams getLayoutParams() { 12303 return mLayoutParams; 12304 } 12305 12306 /** 12307 * Set the layout parameters associated with this view. These supply 12308 * parameters to the <i>parent</i> of this view specifying how it should be 12309 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 12310 * correspond to the different subclasses of ViewGroup that are responsible 12311 * for arranging their children. 12312 * 12313 * @param params The layout parameters for this view, cannot be null 12314 */ 12315 public void setLayoutParams(ViewGroup.LayoutParams params) { 12316 if (params == null) { 12317 throw new NullPointerException("Layout parameters cannot be null"); 12318 } 12319 mLayoutParams = params; 12320 resolveLayoutParams(); 12321 if (mParent instanceof ViewGroup) { 12322 ((ViewGroup) mParent).onSetLayoutParams(this, params); 12323 } 12324 requestLayout(); 12325 } 12326 12327 /** 12328 * Resolve the layout parameters depending on the resolved layout direction 12329 * 12330 * @hide 12331 */ 12332 public void resolveLayoutParams() { 12333 if (mLayoutParams != null) { 12334 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 12335 } 12336 } 12337 12338 /** 12339 * Set the scrolled position of your view. This will cause a call to 12340 * {@link #onScrollChanged(int, int, int, int)} and the view will be 12341 * invalidated. 12342 * @param x the x position to scroll to 12343 * @param y the y position to scroll to 12344 */ 12345 public void scrollTo(int x, int y) { 12346 if (mScrollX != x || mScrollY != y) { 12347 int oldX = mScrollX; 12348 int oldY = mScrollY; 12349 mScrollX = x; 12350 mScrollY = y; 12351 invalidateParentCaches(); 12352 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 12353 if (!awakenScrollBars()) { 12354 postInvalidateOnAnimation(); 12355 } 12356 } 12357 } 12358 12359 /** 12360 * Move the scrolled position of your view. This will cause a call to 12361 * {@link #onScrollChanged(int, int, int, int)} and the view will be 12362 * invalidated. 12363 * @param x the amount of pixels to scroll by horizontally 12364 * @param y the amount of pixels to scroll by vertically 12365 */ 12366 public void scrollBy(int x, int y) { 12367 scrollTo(mScrollX + x, mScrollY + y); 12368 } 12369 12370 /** 12371 * <p>Trigger the scrollbars to draw. When invoked this method starts an 12372 * animation to fade the scrollbars out after a default delay. If a subclass 12373 * provides animated scrolling, the start delay should equal the duration 12374 * of the scrolling animation.</p> 12375 * 12376 * <p>The animation starts only if at least one of the scrollbars is 12377 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 12378 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 12379 * this method returns true, and false otherwise. If the animation is 12380 * started, this method calls {@link #invalidate()}; in that case the 12381 * caller should not call {@link #invalidate()}.</p> 12382 * 12383 * <p>This method should be invoked every time a subclass directly updates 12384 * the scroll parameters.</p> 12385 * 12386 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 12387 * and {@link #scrollTo(int, int)}.</p> 12388 * 12389 * @return true if the animation is played, false otherwise 12390 * 12391 * @see #awakenScrollBars(int) 12392 * @see #scrollBy(int, int) 12393 * @see #scrollTo(int, int) 12394 * @see #isHorizontalScrollBarEnabled() 12395 * @see #isVerticalScrollBarEnabled() 12396 * @see #setHorizontalScrollBarEnabled(boolean) 12397 * @see #setVerticalScrollBarEnabled(boolean) 12398 */ 12399 protected boolean awakenScrollBars() { 12400 return mScrollCache != null && 12401 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 12402 } 12403 12404 /** 12405 * Trigger the scrollbars to draw. 12406 * This method differs from awakenScrollBars() only in its default duration. 12407 * initialAwakenScrollBars() will show the scroll bars for longer than 12408 * usual to give the user more of a chance to notice them. 12409 * 12410 * @return true if the animation is played, false otherwise. 12411 */ 12412 private boolean initialAwakenScrollBars() { 12413 return mScrollCache != null && 12414 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 12415 } 12416 12417 /** 12418 * <p> 12419 * Trigger the scrollbars to draw. When invoked this method starts an 12420 * animation to fade the scrollbars out after a fixed delay. If a subclass 12421 * provides animated scrolling, the start delay should equal the duration of 12422 * the scrolling animation. 12423 * </p> 12424 * 12425 * <p> 12426 * The animation starts only if at least one of the scrollbars is enabled, 12427 * as specified by {@link #isHorizontalScrollBarEnabled()} and 12428 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 12429 * this method returns true, and false otherwise. If the animation is 12430 * started, this method calls {@link #invalidate()}; in that case the caller 12431 * should not call {@link #invalidate()}. 12432 * </p> 12433 * 12434 * <p> 12435 * This method should be invoked every time a subclass directly updates the 12436 * scroll parameters. 12437 * </p> 12438 * 12439 * @param startDelay the delay, in milliseconds, after which the animation 12440 * should start; when the delay is 0, the animation starts 12441 * immediately 12442 * @return true if the animation is played, false otherwise 12443 * 12444 * @see #scrollBy(int, int) 12445 * @see #scrollTo(int, int) 12446 * @see #isHorizontalScrollBarEnabled() 12447 * @see #isVerticalScrollBarEnabled() 12448 * @see #setHorizontalScrollBarEnabled(boolean) 12449 * @see #setVerticalScrollBarEnabled(boolean) 12450 */ 12451 protected boolean awakenScrollBars(int startDelay) { 12452 return awakenScrollBars(startDelay, true); 12453 } 12454 12455 /** 12456 * <p> 12457 * Trigger the scrollbars to draw. When invoked this method starts an 12458 * animation to fade the scrollbars out after a fixed delay. If a subclass 12459 * provides animated scrolling, the start delay should equal the duration of 12460 * the scrolling animation. 12461 * </p> 12462 * 12463 * <p> 12464 * The animation starts only if at least one of the scrollbars is enabled, 12465 * as specified by {@link #isHorizontalScrollBarEnabled()} and 12466 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 12467 * this method returns true, and false otherwise. If the animation is 12468 * started, this method calls {@link #invalidate()} if the invalidate parameter 12469 * is set to true; in that case the caller 12470 * should not call {@link #invalidate()}. 12471 * </p> 12472 * 12473 * <p> 12474 * This method should be invoked every time a subclass directly updates the 12475 * scroll parameters. 12476 * </p> 12477 * 12478 * @param startDelay the delay, in milliseconds, after which the animation 12479 * should start; when the delay is 0, the animation starts 12480 * immediately 12481 * 12482 * @param invalidate Whether this method should call invalidate 12483 * 12484 * @return true if the animation is played, false otherwise 12485 * 12486 * @see #scrollBy(int, int) 12487 * @see #scrollTo(int, int) 12488 * @see #isHorizontalScrollBarEnabled() 12489 * @see #isVerticalScrollBarEnabled() 12490 * @see #setHorizontalScrollBarEnabled(boolean) 12491 * @see #setVerticalScrollBarEnabled(boolean) 12492 */ 12493 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 12494 final ScrollabilityCache scrollCache = mScrollCache; 12495 12496 if (scrollCache == null || !scrollCache.fadeScrollBars) { 12497 return false; 12498 } 12499 12500 if (scrollCache.scrollBar == null) { 12501 scrollCache.scrollBar = new ScrollBarDrawable(); 12502 scrollCache.scrollBar.setCallback(this); 12503 scrollCache.scrollBar.setState(getDrawableState()); 12504 } 12505 12506 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 12507 12508 if (invalidate) { 12509 // Invalidate to show the scrollbars 12510 postInvalidateOnAnimation(); 12511 } 12512 12513 if (scrollCache.state == ScrollabilityCache.OFF) { 12514 // FIXME: this is copied from WindowManagerService. 12515 // We should get this value from the system when it 12516 // is possible to do so. 12517 final int KEY_REPEAT_FIRST_DELAY = 750; 12518 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 12519 } 12520 12521 // Tell mScrollCache when we should start fading. This may 12522 // extend the fade start time if one was already scheduled 12523 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 12524 scrollCache.fadeStartTime = fadeStartTime; 12525 scrollCache.state = ScrollabilityCache.ON; 12526 12527 // Schedule our fader to run, unscheduling any old ones first 12528 if (mAttachInfo != null) { 12529 mAttachInfo.mHandler.removeCallbacks(scrollCache); 12530 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 12531 } 12532 12533 return true; 12534 } 12535 12536 return false; 12537 } 12538 12539 /** 12540 * Do not invalidate views which are not visible and which are not running an animation. They 12541 * will not get drawn and they should not set dirty flags as if they will be drawn 12542 */ 12543 private boolean skipInvalidate() { 12544 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 12545 (!(mParent instanceof ViewGroup) || 12546 !((ViewGroup) mParent).isViewTransitioning(this)); 12547 } 12548 12549 /** 12550 * Mark the area defined by dirty as needing to be drawn. If the view is 12551 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 12552 * point in the future. 12553 * <p> 12554 * This must be called from a UI thread. To call from a non-UI thread, call 12555 * {@link #postInvalidate()}. 12556 * <p> 12557 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 12558 * {@code dirty}. 12559 * 12560 * @param dirty the rectangle representing the bounds of the dirty region 12561 */ 12562 public void invalidate(Rect dirty) { 12563 final int scrollX = mScrollX; 12564 final int scrollY = mScrollY; 12565 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 12566 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 12567 } 12568 12569 /** 12570 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 12571 * coordinates of the dirty rect are relative to the view. If the view is 12572 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 12573 * point in the future. 12574 * <p> 12575 * This must be called from a UI thread. To call from a non-UI thread, call 12576 * {@link #postInvalidate()}. 12577 * 12578 * @param l the left position of the dirty region 12579 * @param t the top position of the dirty region 12580 * @param r the right position of the dirty region 12581 * @param b the bottom position of the dirty region 12582 */ 12583 public void invalidate(int l, int t, int r, int b) { 12584 final int scrollX = mScrollX; 12585 final int scrollY = mScrollY; 12586 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 12587 } 12588 12589 /** 12590 * Invalidate the whole view. If the view is visible, 12591 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 12592 * the future. 12593 * <p> 12594 * This must be called from a UI thread. To call from a non-UI thread, call 12595 * {@link #postInvalidate()}. 12596 */ 12597 public void invalidate() { 12598 invalidate(true); 12599 } 12600 12601 /** 12602 * This is where the invalidate() work actually happens. A full invalidate() 12603 * causes the drawing cache to be invalidated, but this function can be 12604 * called with invalidateCache set to false to skip that invalidation step 12605 * for cases that do not need it (for example, a component that remains at 12606 * the same dimensions with the same content). 12607 * 12608 * @param invalidateCache Whether the drawing cache for this view should be 12609 * invalidated as well. This is usually true for a full 12610 * invalidate, but may be set to false if the View's contents or 12611 * dimensions have not changed. 12612 */ 12613 void invalidate(boolean invalidateCache) { 12614 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 12615 } 12616 12617 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 12618 boolean fullInvalidate) { 12619 if (mGhostView != null) { 12620 mGhostView.invalidate(true); 12621 return; 12622 } 12623 12624 if (skipInvalidate()) { 12625 return; 12626 } 12627 12628 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 12629 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 12630 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 12631 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 12632 if (fullInvalidate) { 12633 mLastIsOpaque = isOpaque(); 12634 mPrivateFlags &= ~PFLAG_DRAWN; 12635 } 12636 12637 mPrivateFlags |= PFLAG_DIRTY; 12638 12639 if (invalidateCache) { 12640 mPrivateFlags |= PFLAG_INVALIDATED; 12641 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 12642 } 12643 12644 // Propagate the damage rectangle to the parent view. 12645 final AttachInfo ai = mAttachInfo; 12646 final ViewParent p = mParent; 12647 if (p != null && ai != null && l < r && t < b) { 12648 final Rect damage = ai.mTmpInvalRect; 12649 damage.set(l, t, r, b); 12650 p.invalidateChild(this, damage); 12651 } 12652 12653 // Damage the entire projection receiver, if necessary. 12654 if (mBackground != null && mBackground.isProjected()) { 12655 final View receiver = getProjectionReceiver(); 12656 if (receiver != null) { 12657 receiver.damageInParent(); 12658 } 12659 } 12660 12661 // Damage the entire IsolatedZVolume receiving this view's shadow. 12662 if (isHardwareAccelerated() && getZ() != 0) { 12663 damageShadowReceiver(); 12664 } 12665 } 12666 } 12667 12668 /** 12669 * @return this view's projection receiver, or {@code null} if none exists 12670 */ 12671 private View getProjectionReceiver() { 12672 ViewParent p = getParent(); 12673 while (p != null && p instanceof View) { 12674 final View v = (View) p; 12675 if (v.isProjectionReceiver()) { 12676 return v; 12677 } 12678 p = p.getParent(); 12679 } 12680 12681 return null; 12682 } 12683 12684 /** 12685 * @return whether the view is a projection receiver 12686 */ 12687 private boolean isProjectionReceiver() { 12688 return mBackground != null; 12689 } 12690 12691 /** 12692 * Damage area of the screen that can be covered by this View's shadow. 12693 * 12694 * This method will guarantee that any changes to shadows cast by a View 12695 * are damaged on the screen for future redraw. 12696 */ 12697 private void damageShadowReceiver() { 12698 final AttachInfo ai = mAttachInfo; 12699 if (ai != null) { 12700 ViewParent p = getParent(); 12701 if (p != null && p instanceof ViewGroup) { 12702 final ViewGroup vg = (ViewGroup) p; 12703 vg.damageInParent(); 12704 } 12705 } 12706 } 12707 12708 /** 12709 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 12710 * set any flags or handle all of the cases handled by the default invalidation methods. 12711 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 12712 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 12713 * walk up the hierarchy, transforming the dirty rect as necessary. 12714 * 12715 * The method also handles normal invalidation logic if display list properties are not 12716 * being used in this view. The invalidateParent and forceRedraw flags are used by that 12717 * backup approach, to handle these cases used in the various property-setting methods. 12718 * 12719 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 12720 * are not being used in this view 12721 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 12722 * list properties are not being used in this view 12723 */ 12724 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 12725 if (!isHardwareAccelerated() 12726 || !mRenderNode.isValid() 12727 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 12728 if (invalidateParent) { 12729 invalidateParentCaches(); 12730 } 12731 if (forceRedraw) { 12732 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12733 } 12734 invalidate(false); 12735 } else { 12736 damageInParent(); 12737 } 12738 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 12739 damageShadowReceiver(); 12740 } 12741 } 12742 12743 /** 12744 * Tells the parent view to damage this view's bounds. 12745 * 12746 * @hide 12747 */ 12748 protected void damageInParent() { 12749 final AttachInfo ai = mAttachInfo; 12750 final ViewParent p = mParent; 12751 if (p != null && ai != null) { 12752 final Rect r = ai.mTmpInvalRect; 12753 r.set(0, 0, mRight - mLeft, mBottom - mTop); 12754 if (mParent instanceof ViewGroup) { 12755 ((ViewGroup) mParent).damageChild(this, r); 12756 } else { 12757 mParent.invalidateChild(this, r); 12758 } 12759 } 12760 } 12761 12762 /** 12763 * Utility method to transform a given Rect by the current matrix of this view. 12764 */ 12765 void transformRect(final Rect rect) { 12766 if (!getMatrix().isIdentity()) { 12767 RectF boundingRect = mAttachInfo.mTmpTransformRect; 12768 boundingRect.set(rect); 12769 getMatrix().mapRect(boundingRect); 12770 rect.set((int) Math.floor(boundingRect.left), 12771 (int) Math.floor(boundingRect.top), 12772 (int) Math.ceil(boundingRect.right), 12773 (int) Math.ceil(boundingRect.bottom)); 12774 } 12775 } 12776 12777 /** 12778 * Used to indicate that the parent of this view should clear its caches. This functionality 12779 * is used to force the parent to rebuild its display list (when hardware-accelerated), 12780 * which is necessary when various parent-managed properties of the view change, such as 12781 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 12782 * clears the parent caches and does not causes an invalidate event. 12783 * 12784 * @hide 12785 */ 12786 protected void invalidateParentCaches() { 12787 if (mParent instanceof View) { 12788 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 12789 } 12790 } 12791 12792 /** 12793 * Used to indicate that the parent of this view should be invalidated. This functionality 12794 * is used to force the parent to rebuild its display list (when hardware-accelerated), 12795 * which is necessary when various parent-managed properties of the view change, such as 12796 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 12797 * an invalidation event to the parent. 12798 * 12799 * @hide 12800 */ 12801 protected void invalidateParentIfNeeded() { 12802 if (isHardwareAccelerated() && mParent instanceof View) { 12803 ((View) mParent).invalidate(true); 12804 } 12805 } 12806 12807 /** 12808 * @hide 12809 */ 12810 protected void invalidateParentIfNeededAndWasQuickRejected() { 12811 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 12812 // View was rejected last time it was drawn by its parent; this may have changed 12813 invalidateParentIfNeeded(); 12814 } 12815 } 12816 12817 /** 12818 * Indicates whether this View is opaque. An opaque View guarantees that it will 12819 * draw all the pixels overlapping its bounds using a fully opaque color. 12820 * 12821 * Subclasses of View should override this method whenever possible to indicate 12822 * whether an instance is opaque. Opaque Views are treated in a special way by 12823 * the View hierarchy, possibly allowing it to perform optimizations during 12824 * invalidate/draw passes. 12825 * 12826 * @return True if this View is guaranteed to be fully opaque, false otherwise. 12827 */ 12828 @ViewDebug.ExportedProperty(category = "drawing") 12829 public boolean isOpaque() { 12830 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 12831 getFinalAlpha() >= 1.0f; 12832 } 12833 12834 /** 12835 * @hide 12836 */ 12837 protected void computeOpaqueFlags() { 12838 // Opaque if: 12839 // - Has a background 12840 // - Background is opaque 12841 // - Doesn't have scrollbars or scrollbars overlay 12842 12843 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 12844 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 12845 } else { 12846 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 12847 } 12848 12849 final int flags = mViewFlags; 12850 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 12851 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 12852 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 12853 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 12854 } else { 12855 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 12856 } 12857 } 12858 12859 /** 12860 * @hide 12861 */ 12862 protected boolean hasOpaqueScrollbars() { 12863 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 12864 } 12865 12866 /** 12867 * @return A handler associated with the thread running the View. This 12868 * handler can be used to pump events in the UI events queue. 12869 */ 12870 public Handler getHandler() { 12871 final AttachInfo attachInfo = mAttachInfo; 12872 if (attachInfo != null) { 12873 return attachInfo.mHandler; 12874 } 12875 return null; 12876 } 12877 12878 /** 12879 * Gets the view root associated with the View. 12880 * @return The view root, or null if none. 12881 * @hide 12882 */ 12883 public ViewRootImpl getViewRootImpl() { 12884 if (mAttachInfo != null) { 12885 return mAttachInfo.mViewRootImpl; 12886 } 12887 return null; 12888 } 12889 12890 /** 12891 * @hide 12892 */ 12893 public HardwareRenderer getHardwareRenderer() { 12894 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 12895 } 12896 12897 /** 12898 * <p>Causes the Runnable to be added to the message queue. 12899 * The runnable will be run on the user interface thread.</p> 12900 * 12901 * @param action The Runnable that will be executed. 12902 * 12903 * @return Returns true if the Runnable was successfully placed in to the 12904 * message queue. Returns false on failure, usually because the 12905 * looper processing the message queue is exiting. 12906 * 12907 * @see #postDelayed 12908 * @see #removeCallbacks 12909 */ 12910 public boolean post(Runnable action) { 12911 final AttachInfo attachInfo = mAttachInfo; 12912 if (attachInfo != null) { 12913 return attachInfo.mHandler.post(action); 12914 } 12915 // Assume that post will succeed later 12916 ViewRootImpl.getRunQueue().post(action); 12917 return true; 12918 } 12919 12920 /** 12921 * <p>Causes the Runnable to be added to the message queue, to be run 12922 * after the specified amount of time elapses. 12923 * The runnable will be run on the user interface thread.</p> 12924 * 12925 * @param action The Runnable that will be executed. 12926 * @param delayMillis The delay (in milliseconds) until the Runnable 12927 * will be executed. 12928 * 12929 * @return true if the Runnable was successfully placed in to the 12930 * message queue. Returns false on failure, usually because the 12931 * looper processing the message queue is exiting. Note that a 12932 * result of true does not mean the Runnable will be processed -- 12933 * if the looper is quit before the delivery time of the message 12934 * occurs then the message will be dropped. 12935 * 12936 * @see #post 12937 * @see #removeCallbacks 12938 */ 12939 public boolean postDelayed(Runnable action, long delayMillis) { 12940 final AttachInfo attachInfo = mAttachInfo; 12941 if (attachInfo != null) { 12942 return attachInfo.mHandler.postDelayed(action, delayMillis); 12943 } 12944 // Assume that post will succeed later 12945 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 12946 return true; 12947 } 12948 12949 /** 12950 * <p>Causes the Runnable to execute on the next animation time step. 12951 * The runnable will be run on the user interface thread.</p> 12952 * 12953 * @param action The Runnable that will be executed. 12954 * 12955 * @see #postOnAnimationDelayed 12956 * @see #removeCallbacks 12957 */ 12958 public void postOnAnimation(Runnable action) { 12959 final AttachInfo attachInfo = mAttachInfo; 12960 if (attachInfo != null) { 12961 attachInfo.mViewRootImpl.mChoreographer.postCallback( 12962 Choreographer.CALLBACK_ANIMATION, action, null); 12963 } else { 12964 // Assume that post will succeed later 12965 ViewRootImpl.getRunQueue().post(action); 12966 } 12967 } 12968 12969 /** 12970 * <p>Causes the Runnable to execute on the next animation time step, 12971 * after the specified amount of time elapses. 12972 * The runnable will be run on the user interface thread.</p> 12973 * 12974 * @param action The Runnable that will be executed. 12975 * @param delayMillis The delay (in milliseconds) until the Runnable 12976 * will be executed. 12977 * 12978 * @see #postOnAnimation 12979 * @see #removeCallbacks 12980 */ 12981 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 12982 final AttachInfo attachInfo = mAttachInfo; 12983 if (attachInfo != null) { 12984 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 12985 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 12986 } else { 12987 // Assume that post will succeed later 12988 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 12989 } 12990 } 12991 12992 /** 12993 * <p>Removes the specified Runnable from the message queue.</p> 12994 * 12995 * @param action The Runnable to remove from the message handling queue 12996 * 12997 * @return true if this view could ask the Handler to remove the Runnable, 12998 * false otherwise. When the returned value is true, the Runnable 12999 * may or may not have been actually removed from the message queue 13000 * (for instance, if the Runnable was not in the queue already.) 13001 * 13002 * @see #post 13003 * @see #postDelayed 13004 * @see #postOnAnimation 13005 * @see #postOnAnimationDelayed 13006 */ 13007 public boolean removeCallbacks(Runnable action) { 13008 if (action != null) { 13009 final AttachInfo attachInfo = mAttachInfo; 13010 if (attachInfo != null) { 13011 attachInfo.mHandler.removeCallbacks(action); 13012 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 13013 Choreographer.CALLBACK_ANIMATION, action, null); 13014 } 13015 // Assume that post will succeed later 13016 ViewRootImpl.getRunQueue().removeCallbacks(action); 13017 } 13018 return true; 13019 } 13020 13021 /** 13022 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 13023 * Use this to invalidate the View from a non-UI thread.</p> 13024 * 13025 * <p>This method can be invoked from outside of the UI thread 13026 * only when this View is attached to a window.</p> 13027 * 13028 * @see #invalidate() 13029 * @see #postInvalidateDelayed(long) 13030 */ 13031 public void postInvalidate() { 13032 postInvalidateDelayed(0); 13033 } 13034 13035 /** 13036 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 13037 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 13038 * 13039 * <p>This method can be invoked from outside of the UI thread 13040 * only when this View is attached to a window.</p> 13041 * 13042 * @param left The left coordinate of the rectangle to invalidate. 13043 * @param top The top coordinate of the rectangle to invalidate. 13044 * @param right The right coordinate of the rectangle to invalidate. 13045 * @param bottom The bottom coordinate of the rectangle to invalidate. 13046 * 13047 * @see #invalidate(int, int, int, int) 13048 * @see #invalidate(Rect) 13049 * @see #postInvalidateDelayed(long, int, int, int, int) 13050 */ 13051 public void postInvalidate(int left, int top, int right, int bottom) { 13052 postInvalidateDelayed(0, left, top, right, bottom); 13053 } 13054 13055 /** 13056 * <p>Cause an invalidate to happen on a subsequent cycle through the event 13057 * loop. Waits for the specified amount of time.</p> 13058 * 13059 * <p>This method can be invoked from outside of the UI thread 13060 * only when this View is attached to a window.</p> 13061 * 13062 * @param delayMilliseconds the duration in milliseconds to delay the 13063 * invalidation by 13064 * 13065 * @see #invalidate() 13066 * @see #postInvalidate() 13067 */ 13068 public void postInvalidateDelayed(long delayMilliseconds) { 13069 // We try only with the AttachInfo because there's no point in invalidating 13070 // if we are not attached to our window 13071 final AttachInfo attachInfo = mAttachInfo; 13072 if (attachInfo != null) { 13073 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 13074 } 13075 } 13076 13077 /** 13078 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 13079 * through the event loop. Waits for the specified amount of time.</p> 13080 * 13081 * <p>This method can be invoked from outside of the UI thread 13082 * only when this View is attached to a window.</p> 13083 * 13084 * @param delayMilliseconds the duration in milliseconds to delay the 13085 * invalidation by 13086 * @param left The left coordinate of the rectangle to invalidate. 13087 * @param top The top coordinate of the rectangle to invalidate. 13088 * @param right The right coordinate of the rectangle to invalidate. 13089 * @param bottom The bottom coordinate of the rectangle to invalidate. 13090 * 13091 * @see #invalidate(int, int, int, int) 13092 * @see #invalidate(Rect) 13093 * @see #postInvalidate(int, int, int, int) 13094 */ 13095 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 13096 int right, int bottom) { 13097 13098 // We try only with the AttachInfo because there's no point in invalidating 13099 // if we are not attached to our window 13100 final AttachInfo attachInfo = mAttachInfo; 13101 if (attachInfo != null) { 13102 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 13103 info.target = this; 13104 info.left = left; 13105 info.top = top; 13106 info.right = right; 13107 info.bottom = bottom; 13108 13109 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 13110 } 13111 } 13112 13113 /** 13114 * <p>Cause an invalidate to happen on the next animation time step, typically the 13115 * next display frame.</p> 13116 * 13117 * <p>This method can be invoked from outside of the UI thread 13118 * only when this View is attached to a window.</p> 13119 * 13120 * @see #invalidate() 13121 */ 13122 public void postInvalidateOnAnimation() { 13123 // We try only with the AttachInfo because there's no point in invalidating 13124 // if we are not attached to our window 13125 final AttachInfo attachInfo = mAttachInfo; 13126 if (attachInfo != null) { 13127 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 13128 } 13129 } 13130 13131 /** 13132 * <p>Cause an invalidate of the specified area to happen on the next animation 13133 * time step, typically the next display frame.</p> 13134 * 13135 * <p>This method can be invoked from outside of the UI thread 13136 * only when this View is attached to a window.</p> 13137 * 13138 * @param left The left coordinate of the rectangle to invalidate. 13139 * @param top The top coordinate of the rectangle to invalidate. 13140 * @param right The right coordinate of the rectangle to invalidate. 13141 * @param bottom The bottom coordinate of the rectangle to invalidate. 13142 * 13143 * @see #invalidate(int, int, int, int) 13144 * @see #invalidate(Rect) 13145 */ 13146 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 13147 // We try only with the AttachInfo because there's no point in invalidating 13148 // if we are not attached to our window 13149 final AttachInfo attachInfo = mAttachInfo; 13150 if (attachInfo != null) { 13151 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 13152 info.target = this; 13153 info.left = left; 13154 info.top = top; 13155 info.right = right; 13156 info.bottom = bottom; 13157 13158 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 13159 } 13160 } 13161 13162 /** 13163 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 13164 * This event is sent at most once every 13165 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 13166 */ 13167 private void postSendViewScrolledAccessibilityEventCallback() { 13168 if (mSendViewScrolledAccessibilityEvent == null) { 13169 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 13170 } 13171 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 13172 mSendViewScrolledAccessibilityEvent.mIsPending = true; 13173 postDelayed(mSendViewScrolledAccessibilityEvent, 13174 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 13175 } 13176 } 13177 13178 /** 13179 * Called by a parent to request that a child update its values for mScrollX 13180 * and mScrollY if necessary. This will typically be done if the child is 13181 * animating a scroll using a {@link android.widget.Scroller Scroller} 13182 * object. 13183 */ 13184 public void computeScroll() { 13185 } 13186 13187 /** 13188 * <p>Indicate whether the horizontal edges are faded when the view is 13189 * scrolled horizontally.</p> 13190 * 13191 * @return true if the horizontal edges should are faded on scroll, false 13192 * otherwise 13193 * 13194 * @see #setHorizontalFadingEdgeEnabled(boolean) 13195 * 13196 * @attr ref android.R.styleable#View_requiresFadingEdge 13197 */ 13198 public boolean isHorizontalFadingEdgeEnabled() { 13199 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 13200 } 13201 13202 /** 13203 * <p>Define whether the horizontal edges should be faded when this view 13204 * is scrolled horizontally.</p> 13205 * 13206 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 13207 * be faded when the view is scrolled 13208 * horizontally 13209 * 13210 * @see #isHorizontalFadingEdgeEnabled() 13211 * 13212 * @attr ref android.R.styleable#View_requiresFadingEdge 13213 */ 13214 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 13215 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 13216 if (horizontalFadingEdgeEnabled) { 13217 initScrollCache(); 13218 } 13219 13220 mViewFlags ^= FADING_EDGE_HORIZONTAL; 13221 } 13222 } 13223 13224 /** 13225 * <p>Indicate whether the vertical edges are faded when the view is 13226 * scrolled horizontally.</p> 13227 * 13228 * @return true if the vertical edges should are faded on scroll, false 13229 * otherwise 13230 * 13231 * @see #setVerticalFadingEdgeEnabled(boolean) 13232 * 13233 * @attr ref android.R.styleable#View_requiresFadingEdge 13234 */ 13235 public boolean isVerticalFadingEdgeEnabled() { 13236 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 13237 } 13238 13239 /** 13240 * <p>Define whether the vertical edges should be faded when this view 13241 * is scrolled vertically.</p> 13242 * 13243 * @param verticalFadingEdgeEnabled true if the vertical edges should 13244 * be faded when the view is scrolled 13245 * vertically 13246 * 13247 * @see #isVerticalFadingEdgeEnabled() 13248 * 13249 * @attr ref android.R.styleable#View_requiresFadingEdge 13250 */ 13251 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 13252 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 13253 if (verticalFadingEdgeEnabled) { 13254 initScrollCache(); 13255 } 13256 13257 mViewFlags ^= FADING_EDGE_VERTICAL; 13258 } 13259 } 13260 13261 /** 13262 * Returns the strength, or intensity, of the top faded edge. The strength is 13263 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 13264 * returns 0.0 or 1.0 but no value in between. 13265 * 13266 * Subclasses should override this method to provide a smoother fade transition 13267 * when scrolling occurs. 13268 * 13269 * @return the intensity of the top fade as a float between 0.0f and 1.0f 13270 */ 13271 protected float getTopFadingEdgeStrength() { 13272 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 13273 } 13274 13275 /** 13276 * Returns the strength, or intensity, of the bottom faded edge. The strength is 13277 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 13278 * returns 0.0 or 1.0 but no value in between. 13279 * 13280 * Subclasses should override this method to provide a smoother fade transition 13281 * when scrolling occurs. 13282 * 13283 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 13284 */ 13285 protected float getBottomFadingEdgeStrength() { 13286 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 13287 computeVerticalScrollRange() ? 1.0f : 0.0f; 13288 } 13289 13290 /** 13291 * Returns the strength, or intensity, of the left faded edge. The strength is 13292 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 13293 * returns 0.0 or 1.0 but no value in between. 13294 * 13295 * Subclasses should override this method to provide a smoother fade transition 13296 * when scrolling occurs. 13297 * 13298 * @return the intensity of the left fade as a float between 0.0f and 1.0f 13299 */ 13300 protected float getLeftFadingEdgeStrength() { 13301 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 13302 } 13303 13304 /** 13305 * Returns the strength, or intensity, of the right faded edge. The strength is 13306 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 13307 * returns 0.0 or 1.0 but no value in between. 13308 * 13309 * Subclasses should override this method to provide a smoother fade transition 13310 * when scrolling occurs. 13311 * 13312 * @return the intensity of the right fade as a float between 0.0f and 1.0f 13313 */ 13314 protected float getRightFadingEdgeStrength() { 13315 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 13316 computeHorizontalScrollRange() ? 1.0f : 0.0f; 13317 } 13318 13319 /** 13320 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 13321 * scrollbar is not drawn by default.</p> 13322 * 13323 * @return true if the horizontal scrollbar should be painted, false 13324 * otherwise 13325 * 13326 * @see #setHorizontalScrollBarEnabled(boolean) 13327 */ 13328 public boolean isHorizontalScrollBarEnabled() { 13329 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 13330 } 13331 13332 /** 13333 * <p>Define whether the horizontal scrollbar should be drawn or not. The 13334 * scrollbar is not drawn by default.</p> 13335 * 13336 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 13337 * be painted 13338 * 13339 * @see #isHorizontalScrollBarEnabled() 13340 */ 13341 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 13342 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 13343 mViewFlags ^= SCROLLBARS_HORIZONTAL; 13344 computeOpaqueFlags(); 13345 resolvePadding(); 13346 } 13347 } 13348 13349 /** 13350 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 13351 * scrollbar is not drawn by default.</p> 13352 * 13353 * @return true if the vertical scrollbar should be painted, false 13354 * otherwise 13355 * 13356 * @see #setVerticalScrollBarEnabled(boolean) 13357 */ 13358 public boolean isVerticalScrollBarEnabled() { 13359 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 13360 } 13361 13362 /** 13363 * <p>Define whether the vertical scrollbar should be drawn or not. The 13364 * scrollbar is not drawn by default.</p> 13365 * 13366 * @param verticalScrollBarEnabled true if the vertical scrollbar should 13367 * be painted 13368 * 13369 * @see #isVerticalScrollBarEnabled() 13370 */ 13371 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 13372 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 13373 mViewFlags ^= SCROLLBARS_VERTICAL; 13374 computeOpaqueFlags(); 13375 resolvePadding(); 13376 } 13377 } 13378 13379 /** 13380 * @hide 13381 */ 13382 protected void recomputePadding() { 13383 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 13384 } 13385 13386 /** 13387 * Define whether scrollbars will fade when the view is not scrolling. 13388 * 13389 * @param fadeScrollbars whether to enable fading 13390 * 13391 * @attr ref android.R.styleable#View_fadeScrollbars 13392 */ 13393 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 13394 initScrollCache(); 13395 final ScrollabilityCache scrollabilityCache = mScrollCache; 13396 scrollabilityCache.fadeScrollBars = fadeScrollbars; 13397 if (fadeScrollbars) { 13398 scrollabilityCache.state = ScrollabilityCache.OFF; 13399 } else { 13400 scrollabilityCache.state = ScrollabilityCache.ON; 13401 } 13402 } 13403 13404 /** 13405 * 13406 * Returns true if scrollbars will fade when this view is not scrolling 13407 * 13408 * @return true if scrollbar fading is enabled 13409 * 13410 * @attr ref android.R.styleable#View_fadeScrollbars 13411 */ 13412 public boolean isScrollbarFadingEnabled() { 13413 return mScrollCache != null && mScrollCache.fadeScrollBars; 13414 } 13415 13416 /** 13417 * 13418 * Returns the delay before scrollbars fade. 13419 * 13420 * @return the delay before scrollbars fade 13421 * 13422 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 13423 */ 13424 public int getScrollBarDefaultDelayBeforeFade() { 13425 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 13426 mScrollCache.scrollBarDefaultDelayBeforeFade; 13427 } 13428 13429 /** 13430 * Define the delay before scrollbars fade. 13431 * 13432 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 13433 * 13434 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 13435 */ 13436 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 13437 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 13438 } 13439 13440 /** 13441 * 13442 * Returns the scrollbar fade duration. 13443 * 13444 * @return the scrollbar fade duration 13445 * 13446 * @attr ref android.R.styleable#View_scrollbarFadeDuration 13447 */ 13448 public int getScrollBarFadeDuration() { 13449 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 13450 mScrollCache.scrollBarFadeDuration; 13451 } 13452 13453 /** 13454 * Define the scrollbar fade duration. 13455 * 13456 * @param scrollBarFadeDuration - the scrollbar fade duration 13457 * 13458 * @attr ref android.R.styleable#View_scrollbarFadeDuration 13459 */ 13460 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 13461 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 13462 } 13463 13464 /** 13465 * 13466 * Returns the scrollbar size. 13467 * 13468 * @return the scrollbar size 13469 * 13470 * @attr ref android.R.styleable#View_scrollbarSize 13471 */ 13472 public int getScrollBarSize() { 13473 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 13474 mScrollCache.scrollBarSize; 13475 } 13476 13477 /** 13478 * Define the scrollbar size. 13479 * 13480 * @param scrollBarSize - the scrollbar size 13481 * 13482 * @attr ref android.R.styleable#View_scrollbarSize 13483 */ 13484 public void setScrollBarSize(int scrollBarSize) { 13485 getScrollCache().scrollBarSize = scrollBarSize; 13486 } 13487 13488 /** 13489 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 13490 * inset. When inset, they add to the padding of the view. And the scrollbars 13491 * can be drawn inside the padding area or on the edge of the view. For example, 13492 * if a view has a background drawable and you want to draw the scrollbars 13493 * inside the padding specified by the drawable, you can use 13494 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 13495 * appear at the edge of the view, ignoring the padding, then you can use 13496 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 13497 * @param style the style of the scrollbars. Should be one of 13498 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 13499 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 13500 * @see #SCROLLBARS_INSIDE_OVERLAY 13501 * @see #SCROLLBARS_INSIDE_INSET 13502 * @see #SCROLLBARS_OUTSIDE_OVERLAY 13503 * @see #SCROLLBARS_OUTSIDE_INSET 13504 * 13505 * @attr ref android.R.styleable#View_scrollbarStyle 13506 */ 13507 public void setScrollBarStyle(@ScrollBarStyle int style) { 13508 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 13509 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 13510 computeOpaqueFlags(); 13511 resolvePadding(); 13512 } 13513 } 13514 13515 /** 13516 * <p>Returns the current scrollbar style.</p> 13517 * @return the current scrollbar style 13518 * @see #SCROLLBARS_INSIDE_OVERLAY 13519 * @see #SCROLLBARS_INSIDE_INSET 13520 * @see #SCROLLBARS_OUTSIDE_OVERLAY 13521 * @see #SCROLLBARS_OUTSIDE_INSET 13522 * 13523 * @attr ref android.R.styleable#View_scrollbarStyle 13524 */ 13525 @ViewDebug.ExportedProperty(mapping = { 13526 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 13527 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 13528 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 13529 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 13530 }) 13531 @ScrollBarStyle 13532 public int getScrollBarStyle() { 13533 return mViewFlags & SCROLLBARS_STYLE_MASK; 13534 } 13535 13536 /** 13537 * <p>Compute the horizontal range that the horizontal scrollbar 13538 * represents.</p> 13539 * 13540 * <p>The range is expressed in arbitrary units that must be the same as the 13541 * units used by {@link #computeHorizontalScrollExtent()} and 13542 * {@link #computeHorizontalScrollOffset()}.</p> 13543 * 13544 * <p>The default range is the drawing width of this view.</p> 13545 * 13546 * @return the total horizontal range represented by the horizontal 13547 * scrollbar 13548 * 13549 * @see #computeHorizontalScrollExtent() 13550 * @see #computeHorizontalScrollOffset() 13551 * @see android.widget.ScrollBarDrawable 13552 */ 13553 protected int computeHorizontalScrollRange() { 13554 return getWidth(); 13555 } 13556 13557 /** 13558 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 13559 * within the horizontal range. This value is used to compute the position 13560 * of the thumb within the scrollbar's track.</p> 13561 * 13562 * <p>The range is expressed in arbitrary units that must be the same as the 13563 * units used by {@link #computeHorizontalScrollRange()} and 13564 * {@link #computeHorizontalScrollExtent()}.</p> 13565 * 13566 * <p>The default offset is the scroll offset of this view.</p> 13567 * 13568 * @return the horizontal offset of the scrollbar's thumb 13569 * 13570 * @see #computeHorizontalScrollRange() 13571 * @see #computeHorizontalScrollExtent() 13572 * @see android.widget.ScrollBarDrawable 13573 */ 13574 protected int computeHorizontalScrollOffset() { 13575 return mScrollX; 13576 } 13577 13578 /** 13579 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 13580 * within the horizontal range. This value is used to compute the length 13581 * of the thumb within the scrollbar's track.</p> 13582 * 13583 * <p>The range is expressed in arbitrary units that must be the same as the 13584 * units used by {@link #computeHorizontalScrollRange()} and 13585 * {@link #computeHorizontalScrollOffset()}.</p> 13586 * 13587 * <p>The default extent is the drawing width of this view.</p> 13588 * 13589 * @return the horizontal extent of the scrollbar's thumb 13590 * 13591 * @see #computeHorizontalScrollRange() 13592 * @see #computeHorizontalScrollOffset() 13593 * @see android.widget.ScrollBarDrawable 13594 */ 13595 protected int computeHorizontalScrollExtent() { 13596 return getWidth(); 13597 } 13598 13599 /** 13600 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 13601 * 13602 * <p>The range is expressed in arbitrary units that must be the same as the 13603 * units used by {@link #computeVerticalScrollExtent()} and 13604 * {@link #computeVerticalScrollOffset()}.</p> 13605 * 13606 * @return the total vertical range represented by the vertical scrollbar 13607 * 13608 * <p>The default range is the drawing height of this view.</p> 13609 * 13610 * @see #computeVerticalScrollExtent() 13611 * @see #computeVerticalScrollOffset() 13612 * @see android.widget.ScrollBarDrawable 13613 */ 13614 protected int computeVerticalScrollRange() { 13615 return getHeight(); 13616 } 13617 13618 /** 13619 * <p>Compute the vertical offset of the vertical scrollbar's thumb 13620 * within the horizontal range. This value is used to compute the position 13621 * of the thumb within the scrollbar's track.</p> 13622 * 13623 * <p>The range is expressed in arbitrary units that must be the same as the 13624 * units used by {@link #computeVerticalScrollRange()} and 13625 * {@link #computeVerticalScrollExtent()}.</p> 13626 * 13627 * <p>The default offset is the scroll offset of this view.</p> 13628 * 13629 * @return the vertical offset of the scrollbar's thumb 13630 * 13631 * @see #computeVerticalScrollRange() 13632 * @see #computeVerticalScrollExtent() 13633 * @see android.widget.ScrollBarDrawable 13634 */ 13635 protected int computeVerticalScrollOffset() { 13636 return mScrollY; 13637 } 13638 13639 /** 13640 * <p>Compute the vertical extent of the vertical scrollbar's thumb 13641 * within the vertical range. This value is used to compute the length 13642 * of the thumb within the scrollbar's track.</p> 13643 * 13644 * <p>The range is expressed in arbitrary units that must be the same as the 13645 * units used by {@link #computeVerticalScrollRange()} and 13646 * {@link #computeVerticalScrollOffset()}.</p> 13647 * 13648 * <p>The default extent is the drawing height of this view.</p> 13649 * 13650 * @return the vertical extent of the scrollbar's thumb 13651 * 13652 * @see #computeVerticalScrollRange() 13653 * @see #computeVerticalScrollOffset() 13654 * @see android.widget.ScrollBarDrawable 13655 */ 13656 protected int computeVerticalScrollExtent() { 13657 return getHeight(); 13658 } 13659 13660 /** 13661 * Check if this view can be scrolled horizontally in a certain direction. 13662 * 13663 * @param direction Negative to check scrolling left, positive to check scrolling right. 13664 * @return true if this view can be scrolled in the specified direction, false otherwise. 13665 */ 13666 public boolean canScrollHorizontally(int direction) { 13667 final int offset = computeHorizontalScrollOffset(); 13668 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 13669 if (range == 0) return false; 13670 if (direction < 0) { 13671 return offset > 0; 13672 } else { 13673 return offset < range - 1; 13674 } 13675 } 13676 13677 /** 13678 * Check if this view can be scrolled vertically in a certain direction. 13679 * 13680 * @param direction Negative to check scrolling up, positive to check scrolling down. 13681 * @return true if this view can be scrolled in the specified direction, false otherwise. 13682 */ 13683 public boolean canScrollVertically(int direction) { 13684 final int offset = computeVerticalScrollOffset(); 13685 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 13686 if (range == 0) return false; 13687 if (direction < 0) { 13688 return offset > 0; 13689 } else { 13690 return offset < range - 1; 13691 } 13692 } 13693 13694 void getScrollIndicatorBounds(@NonNull Rect out) { 13695 out.left = mScrollX; 13696 out.right = mScrollX + mRight - mLeft; 13697 out.top = mScrollY; 13698 out.bottom = mScrollY + mBottom - mTop; 13699 } 13700 13701 private void onDrawScrollIndicators(Canvas c) { 13702 if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) { 13703 // No scroll indicators enabled. 13704 return; 13705 } 13706 13707 final Drawable dr = mScrollIndicatorDrawable; 13708 if (dr == null) { 13709 // Scroll indicators aren't supported here. 13710 return; 13711 } 13712 13713 final int h = dr.getIntrinsicHeight(); 13714 final int w = dr.getIntrinsicWidth(); 13715 final Rect rect = mAttachInfo.mTmpInvalRect; 13716 getScrollIndicatorBounds(rect); 13717 13718 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) { 13719 final boolean canScrollUp = canScrollVertically(-1); 13720 if (canScrollUp) { 13721 dr.setBounds(rect.left, rect.top, rect.right, rect.top + h); 13722 dr.draw(c); 13723 } 13724 } 13725 13726 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) { 13727 final boolean canScrollDown = canScrollVertically(1); 13728 if (canScrollDown) { 13729 dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom); 13730 dr.draw(c); 13731 } 13732 } 13733 13734 final int leftRtl; 13735 final int rightRtl; 13736 if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 13737 leftRtl = PFLAG3_SCROLL_INDICATOR_END; 13738 rightRtl = PFLAG3_SCROLL_INDICATOR_START; 13739 } else { 13740 leftRtl = PFLAG3_SCROLL_INDICATOR_START; 13741 rightRtl = PFLAG3_SCROLL_INDICATOR_END; 13742 } 13743 13744 final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl; 13745 if ((mPrivateFlags3 & leftMask) != 0) { 13746 final boolean canScrollLeft = canScrollHorizontally(-1); 13747 if (canScrollLeft) { 13748 dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom); 13749 dr.draw(c); 13750 } 13751 } 13752 13753 final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl; 13754 if ((mPrivateFlags3 & rightMask) != 0) { 13755 final boolean canScrollRight = canScrollHorizontally(1); 13756 if (canScrollRight) { 13757 dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom); 13758 dr.draw(c); 13759 } 13760 } 13761 } 13762 13763 /** 13764 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 13765 * scrollbars are painted only if they have been awakened first.</p> 13766 * 13767 * @param canvas the canvas on which to draw the scrollbars 13768 * 13769 * @see #awakenScrollBars(int) 13770 */ 13771 protected final void onDrawScrollBars(Canvas canvas) { 13772 // scrollbars are drawn only when the animation is running 13773 final ScrollabilityCache cache = mScrollCache; 13774 if (cache != null) { 13775 13776 int state = cache.state; 13777 13778 if (state == ScrollabilityCache.OFF) { 13779 return; 13780 } 13781 13782 boolean invalidate = false; 13783 13784 if (state == ScrollabilityCache.FADING) { 13785 // We're fading -- get our fade interpolation 13786 if (cache.interpolatorValues == null) { 13787 cache.interpolatorValues = new float[1]; 13788 } 13789 13790 float[] values = cache.interpolatorValues; 13791 13792 // Stops the animation if we're done 13793 if (cache.scrollBarInterpolator.timeToValues(values) == 13794 Interpolator.Result.FREEZE_END) { 13795 cache.state = ScrollabilityCache.OFF; 13796 } else { 13797 cache.scrollBar.mutate().setAlpha(Math.round(values[0])); 13798 } 13799 13800 // This will make the scroll bars inval themselves after 13801 // drawing. We only want this when we're fading so that 13802 // we prevent excessive redraws 13803 invalidate = true; 13804 } else { 13805 // We're just on -- but we may have been fading before so 13806 // reset alpha 13807 cache.scrollBar.mutate().setAlpha(255); 13808 } 13809 13810 13811 final int viewFlags = mViewFlags; 13812 13813 final boolean drawHorizontalScrollBar = 13814 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 13815 final boolean drawVerticalScrollBar = 13816 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 13817 && !isVerticalScrollBarHidden(); 13818 13819 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 13820 final int width = mRight - mLeft; 13821 final int height = mBottom - mTop; 13822 13823 final ScrollBarDrawable scrollBar = cache.scrollBar; 13824 13825 final int scrollX = mScrollX; 13826 final int scrollY = mScrollY; 13827 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 13828 13829 int left; 13830 int top; 13831 int right; 13832 int bottom; 13833 13834 if (drawHorizontalScrollBar) { 13835 int size = scrollBar.getSize(false); 13836 if (size <= 0) { 13837 size = cache.scrollBarSize; 13838 } 13839 13840 scrollBar.setParameters(computeHorizontalScrollRange(), 13841 computeHorizontalScrollOffset(), 13842 computeHorizontalScrollExtent(), false); 13843 final int verticalScrollBarGap = drawVerticalScrollBar ? 13844 getVerticalScrollbarWidth() : 0; 13845 top = scrollY + height - size - (mUserPaddingBottom & inside); 13846 left = scrollX + (mPaddingLeft & inside); 13847 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 13848 bottom = top + size; 13849 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 13850 if (invalidate) { 13851 invalidate(left, top, right, bottom); 13852 } 13853 } 13854 13855 if (drawVerticalScrollBar) { 13856 int size = scrollBar.getSize(true); 13857 if (size <= 0) { 13858 size = cache.scrollBarSize; 13859 } 13860 13861 scrollBar.setParameters(computeVerticalScrollRange(), 13862 computeVerticalScrollOffset(), 13863 computeVerticalScrollExtent(), true); 13864 int verticalScrollbarPosition = mVerticalScrollbarPosition; 13865 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 13866 verticalScrollbarPosition = isLayoutRtl() ? 13867 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 13868 } 13869 switch (verticalScrollbarPosition) { 13870 default: 13871 case SCROLLBAR_POSITION_RIGHT: 13872 left = scrollX + width - size - (mUserPaddingRight & inside); 13873 break; 13874 case SCROLLBAR_POSITION_LEFT: 13875 left = scrollX + (mUserPaddingLeft & inside); 13876 break; 13877 } 13878 top = scrollY + (mPaddingTop & inside); 13879 right = left + size; 13880 bottom = scrollY + height - (mUserPaddingBottom & inside); 13881 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 13882 if (invalidate) { 13883 invalidate(left, top, right, bottom); 13884 } 13885 } 13886 } 13887 } 13888 } 13889 13890 /** 13891 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 13892 * FastScroller is visible. 13893 * @return whether to temporarily hide the vertical scrollbar 13894 * @hide 13895 */ 13896 protected boolean isVerticalScrollBarHidden() { 13897 return false; 13898 } 13899 13900 /** 13901 * <p>Draw the horizontal scrollbar if 13902 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 13903 * 13904 * @param canvas the canvas on which to draw the scrollbar 13905 * @param scrollBar the scrollbar's drawable 13906 * 13907 * @see #isHorizontalScrollBarEnabled() 13908 * @see #computeHorizontalScrollRange() 13909 * @see #computeHorizontalScrollExtent() 13910 * @see #computeHorizontalScrollOffset() 13911 * @see android.widget.ScrollBarDrawable 13912 * @hide 13913 */ 13914 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 13915 int l, int t, int r, int b) { 13916 scrollBar.setBounds(l, t, r, b); 13917 scrollBar.draw(canvas); 13918 } 13919 13920 /** 13921 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 13922 * returns true.</p> 13923 * 13924 * @param canvas the canvas on which to draw the scrollbar 13925 * @param scrollBar the scrollbar's drawable 13926 * 13927 * @see #isVerticalScrollBarEnabled() 13928 * @see #computeVerticalScrollRange() 13929 * @see #computeVerticalScrollExtent() 13930 * @see #computeVerticalScrollOffset() 13931 * @see android.widget.ScrollBarDrawable 13932 * @hide 13933 */ 13934 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 13935 int l, int t, int r, int b) { 13936 scrollBar.setBounds(l, t, r, b); 13937 scrollBar.draw(canvas); 13938 } 13939 13940 /** 13941 * Implement this to do your drawing. 13942 * 13943 * @param canvas the canvas on which the background will be drawn 13944 */ 13945 protected void onDraw(Canvas canvas) { 13946 } 13947 13948 /* 13949 * Caller is responsible for calling requestLayout if necessary. 13950 * (This allows addViewInLayout to not request a new layout.) 13951 */ 13952 void assignParent(ViewParent parent) { 13953 if (mParent == null) { 13954 mParent = parent; 13955 } else if (parent == null) { 13956 mParent = null; 13957 } else { 13958 throw new RuntimeException("view " + this + " being added, but" 13959 + " it already has a parent"); 13960 } 13961 } 13962 13963 /** 13964 * This is called when the view is attached to a window. At this point it 13965 * has a Surface and will start drawing. Note that this function is 13966 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 13967 * however it may be called any time before the first onDraw -- including 13968 * before or after {@link #onMeasure(int, int)}. 13969 * 13970 * @see #onDetachedFromWindow() 13971 */ 13972 @CallSuper 13973 protected void onAttachedToWindow() { 13974 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 13975 mParent.requestTransparentRegion(this); 13976 } 13977 13978 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 13979 initialAwakenScrollBars(); 13980 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 13981 } 13982 13983 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 13984 13985 jumpDrawablesToCurrentState(); 13986 13987 resetSubtreeAccessibilityStateChanged(); 13988 13989 // rebuild, since Outline not maintained while View is detached 13990 rebuildOutline(); 13991 13992 if (isFocused()) { 13993 InputMethodManager imm = InputMethodManager.peekInstance(); 13994 if (imm != null) { 13995 imm.focusIn(this); 13996 } 13997 } 13998 } 13999 14000 /** 14001 * Resolve all RTL related properties. 14002 * 14003 * @return true if resolution of RTL properties has been done 14004 * 14005 * @hide 14006 */ 14007 public boolean resolveRtlPropertiesIfNeeded() { 14008 if (!needRtlPropertiesResolution()) return false; 14009 14010 // Order is important here: LayoutDirection MUST be resolved first 14011 if (!isLayoutDirectionResolved()) { 14012 resolveLayoutDirection(); 14013 resolveLayoutParams(); 14014 } 14015 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 14016 if (!isTextDirectionResolved()) { 14017 resolveTextDirection(); 14018 } 14019 if (!isTextAlignmentResolved()) { 14020 resolveTextAlignment(); 14021 } 14022 // Should resolve Drawables before Padding because we need the layout direction of the 14023 // Drawable to correctly resolve Padding. 14024 if (!areDrawablesResolved()) { 14025 resolveDrawables(); 14026 } 14027 if (!isPaddingResolved()) { 14028 resolvePadding(); 14029 } 14030 onRtlPropertiesChanged(getLayoutDirection()); 14031 return true; 14032 } 14033 14034 /** 14035 * Reset resolution of all RTL related properties. 14036 * 14037 * @hide 14038 */ 14039 public void resetRtlProperties() { 14040 resetResolvedLayoutDirection(); 14041 resetResolvedTextDirection(); 14042 resetResolvedTextAlignment(); 14043 resetResolvedPadding(); 14044 resetResolvedDrawables(); 14045 } 14046 14047 /** 14048 * @see #onScreenStateChanged(int) 14049 */ 14050 void dispatchScreenStateChanged(int screenState) { 14051 onScreenStateChanged(screenState); 14052 } 14053 14054 /** 14055 * This method is called whenever the state of the screen this view is 14056 * attached to changes. A state change will usually occurs when the screen 14057 * turns on or off (whether it happens automatically or the user does it 14058 * manually.) 14059 * 14060 * @param screenState The new state of the screen. Can be either 14061 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 14062 */ 14063 public void onScreenStateChanged(int screenState) { 14064 } 14065 14066 /** 14067 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 14068 */ 14069 private boolean hasRtlSupport() { 14070 return mContext.getApplicationInfo().hasRtlSupport(); 14071 } 14072 14073 /** 14074 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 14075 * RTL not supported) 14076 */ 14077 private boolean isRtlCompatibilityMode() { 14078 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 14079 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 14080 } 14081 14082 /** 14083 * @return true if RTL properties need resolution. 14084 * 14085 */ 14086 private boolean needRtlPropertiesResolution() { 14087 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 14088 } 14089 14090 /** 14091 * Called when any RTL property (layout direction or text direction or text alignment) has 14092 * been changed. 14093 * 14094 * Subclasses need to override this method to take care of cached information that depends on the 14095 * resolved layout direction, or to inform child views that inherit their layout direction. 14096 * 14097 * The default implementation does nothing. 14098 * 14099 * @param layoutDirection the direction of the layout 14100 * 14101 * @see #LAYOUT_DIRECTION_LTR 14102 * @see #LAYOUT_DIRECTION_RTL 14103 */ 14104 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 14105 } 14106 14107 /** 14108 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 14109 * that the parent directionality can and will be resolved before its children. 14110 * 14111 * @return true if resolution has been done, false otherwise. 14112 * 14113 * @hide 14114 */ 14115 public boolean resolveLayoutDirection() { 14116 // Clear any previous layout direction resolution 14117 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 14118 14119 if (hasRtlSupport()) { 14120 // Set resolved depending on layout direction 14121 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 14122 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 14123 case LAYOUT_DIRECTION_INHERIT: 14124 // We cannot resolve yet. LTR is by default and let the resolution happen again 14125 // later to get the correct resolved value 14126 if (!canResolveLayoutDirection()) return false; 14127 14128 // Parent has not yet resolved, LTR is still the default 14129 try { 14130 if (!mParent.isLayoutDirectionResolved()) return false; 14131 14132 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 14133 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 14134 } 14135 } catch (AbstractMethodError e) { 14136 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 14137 " does not fully implement ViewParent", e); 14138 } 14139 break; 14140 case LAYOUT_DIRECTION_RTL: 14141 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 14142 break; 14143 case LAYOUT_DIRECTION_LOCALE: 14144 if((LAYOUT_DIRECTION_RTL == 14145 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 14146 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 14147 } 14148 break; 14149 default: 14150 // Nothing to do, LTR by default 14151 } 14152 } 14153 14154 // Set to resolved 14155 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 14156 return true; 14157 } 14158 14159 /** 14160 * Check if layout direction resolution can be done. 14161 * 14162 * @return true if layout direction resolution can be done otherwise return false. 14163 */ 14164 public boolean canResolveLayoutDirection() { 14165 switch (getRawLayoutDirection()) { 14166 case LAYOUT_DIRECTION_INHERIT: 14167 if (mParent != null) { 14168 try { 14169 return mParent.canResolveLayoutDirection(); 14170 } catch (AbstractMethodError e) { 14171 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 14172 " does not fully implement ViewParent", e); 14173 } 14174 } 14175 return false; 14176 14177 default: 14178 return true; 14179 } 14180 } 14181 14182 /** 14183 * Reset the resolved layout direction. Layout direction will be resolved during a call to 14184 * {@link #onMeasure(int, int)}. 14185 * 14186 * @hide 14187 */ 14188 public void resetResolvedLayoutDirection() { 14189 // Reset the current resolved bits 14190 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 14191 } 14192 14193 /** 14194 * @return true if the layout direction is inherited. 14195 * 14196 * @hide 14197 */ 14198 public boolean isLayoutDirectionInherited() { 14199 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 14200 } 14201 14202 /** 14203 * @return true if layout direction has been resolved. 14204 */ 14205 public boolean isLayoutDirectionResolved() { 14206 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 14207 } 14208 14209 /** 14210 * Return if padding has been resolved 14211 * 14212 * @hide 14213 */ 14214 boolean isPaddingResolved() { 14215 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 14216 } 14217 14218 /** 14219 * Resolves padding depending on layout direction, if applicable, and 14220 * recomputes internal padding values to adjust for scroll bars. 14221 * 14222 * @hide 14223 */ 14224 public void resolvePadding() { 14225 final int resolvedLayoutDirection = getLayoutDirection(); 14226 14227 if (!isRtlCompatibilityMode()) { 14228 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 14229 // If start / end padding are defined, they will be resolved (hence overriding) to 14230 // left / right or right / left depending on the resolved layout direction. 14231 // If start / end padding are not defined, use the left / right ones. 14232 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 14233 Rect padding = sThreadLocal.get(); 14234 if (padding == null) { 14235 padding = new Rect(); 14236 sThreadLocal.set(padding); 14237 } 14238 mBackground.getPadding(padding); 14239 if (!mLeftPaddingDefined) { 14240 mUserPaddingLeftInitial = padding.left; 14241 } 14242 if (!mRightPaddingDefined) { 14243 mUserPaddingRightInitial = padding.right; 14244 } 14245 } 14246 switch (resolvedLayoutDirection) { 14247 case LAYOUT_DIRECTION_RTL: 14248 if (mUserPaddingStart != UNDEFINED_PADDING) { 14249 mUserPaddingRight = mUserPaddingStart; 14250 } else { 14251 mUserPaddingRight = mUserPaddingRightInitial; 14252 } 14253 if (mUserPaddingEnd != UNDEFINED_PADDING) { 14254 mUserPaddingLeft = mUserPaddingEnd; 14255 } else { 14256 mUserPaddingLeft = mUserPaddingLeftInitial; 14257 } 14258 break; 14259 case LAYOUT_DIRECTION_LTR: 14260 default: 14261 if (mUserPaddingStart != UNDEFINED_PADDING) { 14262 mUserPaddingLeft = mUserPaddingStart; 14263 } else { 14264 mUserPaddingLeft = mUserPaddingLeftInitial; 14265 } 14266 if (mUserPaddingEnd != UNDEFINED_PADDING) { 14267 mUserPaddingRight = mUserPaddingEnd; 14268 } else { 14269 mUserPaddingRight = mUserPaddingRightInitial; 14270 } 14271 } 14272 14273 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 14274 } 14275 14276 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 14277 onRtlPropertiesChanged(resolvedLayoutDirection); 14278 14279 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 14280 } 14281 14282 /** 14283 * Reset the resolved layout direction. 14284 * 14285 * @hide 14286 */ 14287 public void resetResolvedPadding() { 14288 resetResolvedPaddingInternal(); 14289 } 14290 14291 /** 14292 * Used when we only want to reset *this* view's padding and not trigger overrides 14293 * in ViewGroup that reset children too. 14294 */ 14295 void resetResolvedPaddingInternal() { 14296 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 14297 } 14298 14299 /** 14300 * This is called when the view is detached from a window. At this point it 14301 * no longer has a surface for drawing. 14302 * 14303 * @see #onAttachedToWindow() 14304 */ 14305 @CallSuper 14306 protected void onDetachedFromWindow() { 14307 } 14308 14309 /** 14310 * This is a framework-internal mirror of onDetachedFromWindow() that's called 14311 * after onDetachedFromWindow(). 14312 * 14313 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 14314 * The super method should be called at the end of the overridden method to ensure 14315 * subclasses are destroyed first 14316 * 14317 * @hide 14318 */ 14319 @CallSuper 14320 protected void onDetachedFromWindowInternal() { 14321 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 14322 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 14323 14324 removeUnsetPressCallback(); 14325 removeLongPressCallback(); 14326 removePerformClickCallback(); 14327 removeSendViewScrolledAccessibilityEventCallback(); 14328 stopNestedScroll(); 14329 14330 // Anything that started animating right before detach should already 14331 // be in its final state when re-attached. 14332 jumpDrawablesToCurrentState(); 14333 14334 destroyDrawingCache(); 14335 14336 cleanupDraw(); 14337 mCurrentAnimation = null; 14338 } 14339 14340 private void cleanupDraw() { 14341 resetDisplayList(); 14342 if (mAttachInfo != null) { 14343 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 14344 } 14345 } 14346 14347 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 14348 } 14349 14350 /** 14351 * @return The number of times this view has been attached to a window 14352 */ 14353 protected int getWindowAttachCount() { 14354 return mWindowAttachCount; 14355 } 14356 14357 /** 14358 * Retrieve a unique token identifying the window this view is attached to. 14359 * @return Return the window's token for use in 14360 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 14361 */ 14362 public IBinder getWindowToken() { 14363 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 14364 } 14365 14366 /** 14367 * Retrieve the {@link WindowId} for the window this view is 14368 * currently attached to. 14369 */ 14370 public WindowId getWindowId() { 14371 if (mAttachInfo == null) { 14372 return null; 14373 } 14374 if (mAttachInfo.mWindowId == null) { 14375 try { 14376 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 14377 mAttachInfo.mWindowToken); 14378 mAttachInfo.mWindowId = new WindowId( 14379 mAttachInfo.mIWindowId); 14380 } catch (RemoteException e) { 14381 } 14382 } 14383 return mAttachInfo.mWindowId; 14384 } 14385 14386 /** 14387 * Retrieve a unique token identifying the top-level "real" window of 14388 * the window that this view is attached to. That is, this is like 14389 * {@link #getWindowToken}, except if the window this view in is a panel 14390 * window (attached to another containing window), then the token of 14391 * the containing window is returned instead. 14392 * 14393 * @return Returns the associated window token, either 14394 * {@link #getWindowToken()} or the containing window's token. 14395 */ 14396 public IBinder getApplicationWindowToken() { 14397 AttachInfo ai = mAttachInfo; 14398 if (ai != null) { 14399 IBinder appWindowToken = ai.mPanelParentWindowToken; 14400 if (appWindowToken == null) { 14401 appWindowToken = ai.mWindowToken; 14402 } 14403 return appWindowToken; 14404 } 14405 return null; 14406 } 14407 14408 /** 14409 * Gets the logical display to which the view's window has been attached. 14410 * 14411 * @return The logical display, or null if the view is not currently attached to a window. 14412 */ 14413 public Display getDisplay() { 14414 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 14415 } 14416 14417 /** 14418 * Retrieve private session object this view hierarchy is using to 14419 * communicate with the window manager. 14420 * @return the session object to communicate with the window manager 14421 */ 14422 /*package*/ IWindowSession getWindowSession() { 14423 return mAttachInfo != null ? mAttachInfo.mSession : null; 14424 } 14425 14426 /** 14427 * @param info the {@link android.view.View.AttachInfo} to associated with 14428 * this view 14429 */ 14430 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 14431 //System.out.println("Attached! " + this); 14432 mAttachInfo = info; 14433 if (mOverlay != null) { 14434 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 14435 } 14436 mWindowAttachCount++; 14437 // We will need to evaluate the drawable state at least once. 14438 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 14439 if (mFloatingTreeObserver != null) { 14440 info.mTreeObserver.merge(mFloatingTreeObserver); 14441 mFloatingTreeObserver = null; 14442 } 14443 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 14444 mAttachInfo.mScrollContainers.add(this); 14445 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 14446 } 14447 performCollectViewAttributes(mAttachInfo, visibility); 14448 onAttachedToWindow(); 14449 14450 ListenerInfo li = mListenerInfo; 14451 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 14452 li != null ? li.mOnAttachStateChangeListeners : null; 14453 if (listeners != null && listeners.size() > 0) { 14454 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 14455 // perform the dispatching. The iterator is a safe guard against listeners that 14456 // could mutate the list by calling the various add/remove methods. This prevents 14457 // the array from being modified while we iterate it. 14458 for (OnAttachStateChangeListener listener : listeners) { 14459 listener.onViewAttachedToWindow(this); 14460 } 14461 } 14462 14463 int vis = info.mWindowVisibility; 14464 if (vis != GONE) { 14465 onWindowVisibilityChanged(vis); 14466 } 14467 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 14468 // If nobody has evaluated the drawable state yet, then do it now. 14469 refreshDrawableState(); 14470 } 14471 needGlobalAttributesUpdate(false); 14472 } 14473 14474 void dispatchDetachedFromWindow() { 14475 AttachInfo info = mAttachInfo; 14476 if (info != null) { 14477 int vis = info.mWindowVisibility; 14478 if (vis != GONE) { 14479 onWindowVisibilityChanged(GONE); 14480 } 14481 } 14482 14483 onDetachedFromWindow(); 14484 onDetachedFromWindowInternal(); 14485 14486 ListenerInfo li = mListenerInfo; 14487 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 14488 li != null ? li.mOnAttachStateChangeListeners : null; 14489 if (listeners != null && listeners.size() > 0) { 14490 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 14491 // perform the dispatching. The iterator is a safe guard against listeners that 14492 // could mutate the list by calling the various add/remove methods. This prevents 14493 // the array from being modified while we iterate it. 14494 for (OnAttachStateChangeListener listener : listeners) { 14495 listener.onViewDetachedFromWindow(this); 14496 } 14497 } 14498 14499 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 14500 mAttachInfo.mScrollContainers.remove(this); 14501 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 14502 } 14503 14504 mAttachInfo = null; 14505 if (mOverlay != null) { 14506 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 14507 } 14508 } 14509 14510 /** 14511 * Cancel any deferred high-level input events that were previously posted to the event queue. 14512 * 14513 * <p>Many views post high-level events such as click handlers to the event queue 14514 * to run deferred in order to preserve a desired user experience - clearing visible 14515 * pressed states before executing, etc. This method will abort any events of this nature 14516 * that are currently in flight.</p> 14517 * 14518 * <p>Custom views that generate their own high-level deferred input events should override 14519 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 14520 * 14521 * <p>This will also cancel pending input events for any child views.</p> 14522 * 14523 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 14524 * This will not impact newer events posted after this call that may occur as a result of 14525 * lower-level input events still waiting in the queue. If you are trying to prevent 14526 * double-submitted events for the duration of some sort of asynchronous transaction 14527 * you should also take other steps to protect against unexpected double inputs e.g. calling 14528 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 14529 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 14530 */ 14531 public final void cancelPendingInputEvents() { 14532 dispatchCancelPendingInputEvents(); 14533 } 14534 14535 /** 14536 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 14537 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 14538 */ 14539 void dispatchCancelPendingInputEvents() { 14540 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 14541 onCancelPendingInputEvents(); 14542 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 14543 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 14544 " did not call through to super.onCancelPendingInputEvents()"); 14545 } 14546 } 14547 14548 /** 14549 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 14550 * a parent view. 14551 * 14552 * <p>This method is responsible for removing any pending high-level input events that were 14553 * posted to the event queue to run later. Custom view classes that post their own deferred 14554 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 14555 * {@link android.os.Handler} should override this method, call 14556 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 14557 * </p> 14558 */ 14559 public void onCancelPendingInputEvents() { 14560 removePerformClickCallback(); 14561 cancelLongPress(); 14562 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 14563 } 14564 14565 /** 14566 * Store this view hierarchy's frozen state into the given container. 14567 * 14568 * @param container The SparseArray in which to save the view's state. 14569 * 14570 * @see #restoreHierarchyState(android.util.SparseArray) 14571 * @see #dispatchSaveInstanceState(android.util.SparseArray) 14572 * @see #onSaveInstanceState() 14573 */ 14574 public void saveHierarchyState(SparseArray<Parcelable> container) { 14575 dispatchSaveInstanceState(container); 14576 } 14577 14578 /** 14579 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 14580 * this view and its children. May be overridden to modify how freezing happens to a 14581 * view's children; for example, some views may want to not store state for their children. 14582 * 14583 * @param container The SparseArray in which to save the view's state. 14584 * 14585 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 14586 * @see #saveHierarchyState(android.util.SparseArray) 14587 * @see #onSaveInstanceState() 14588 */ 14589 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 14590 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 14591 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 14592 Parcelable state = onSaveInstanceState(); 14593 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 14594 throw new IllegalStateException( 14595 "Derived class did not call super.onSaveInstanceState()"); 14596 } 14597 if (state != null) { 14598 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 14599 // + ": " + state); 14600 container.put(mID, state); 14601 } 14602 } 14603 } 14604 14605 /** 14606 * Hook allowing a view to generate a representation of its internal state 14607 * that can later be used to create a new instance with that same state. 14608 * This state should only contain information that is not persistent or can 14609 * not be reconstructed later. For example, you will never store your 14610 * current position on screen because that will be computed again when a 14611 * new instance of the view is placed in its view hierarchy. 14612 * <p> 14613 * Some examples of things you may store here: the current cursor position 14614 * in a text view (but usually not the text itself since that is stored in a 14615 * content provider or other persistent storage), the currently selected 14616 * item in a list view. 14617 * 14618 * @return Returns a Parcelable object containing the view's current dynamic 14619 * state, or null if there is nothing interesting to save. The 14620 * default implementation returns null. 14621 * @see #onRestoreInstanceState(android.os.Parcelable) 14622 * @see #saveHierarchyState(android.util.SparseArray) 14623 * @see #dispatchSaveInstanceState(android.util.SparseArray) 14624 * @see #setSaveEnabled(boolean) 14625 */ 14626 @CallSuper 14627 protected Parcelable onSaveInstanceState() { 14628 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 14629 if (mStartActivityRequestWho != null) { 14630 BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE); 14631 state.mStartActivityRequestWhoSaved = mStartActivityRequestWho; 14632 return state; 14633 } 14634 return BaseSavedState.EMPTY_STATE; 14635 } 14636 14637 /** 14638 * Restore this view hierarchy's frozen state from the given container. 14639 * 14640 * @param container The SparseArray which holds previously frozen states. 14641 * 14642 * @see #saveHierarchyState(android.util.SparseArray) 14643 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 14644 * @see #onRestoreInstanceState(android.os.Parcelable) 14645 */ 14646 public void restoreHierarchyState(SparseArray<Parcelable> container) { 14647 dispatchRestoreInstanceState(container); 14648 } 14649 14650 /** 14651 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 14652 * state for this view and its children. May be overridden to modify how restoring 14653 * happens to a view's children; for example, some views may want to not store state 14654 * for their children. 14655 * 14656 * @param container The SparseArray which holds previously saved state. 14657 * 14658 * @see #dispatchSaveInstanceState(android.util.SparseArray) 14659 * @see #restoreHierarchyState(android.util.SparseArray) 14660 * @see #onRestoreInstanceState(android.os.Parcelable) 14661 */ 14662 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 14663 if (mID != NO_ID) { 14664 Parcelable state = container.get(mID); 14665 if (state != null) { 14666 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 14667 // + ": " + state); 14668 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 14669 onRestoreInstanceState(state); 14670 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 14671 throw new IllegalStateException( 14672 "Derived class did not call super.onRestoreInstanceState()"); 14673 } 14674 } 14675 } 14676 } 14677 14678 /** 14679 * Hook allowing a view to re-apply a representation of its internal state that had previously 14680 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 14681 * null state. 14682 * 14683 * @param state The frozen state that had previously been returned by 14684 * {@link #onSaveInstanceState}. 14685 * 14686 * @see #onSaveInstanceState() 14687 * @see #restoreHierarchyState(android.util.SparseArray) 14688 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 14689 */ 14690 @CallSuper 14691 protected void onRestoreInstanceState(Parcelable state) { 14692 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 14693 if (state != null && !(state instanceof AbsSavedState)) { 14694 throw new IllegalArgumentException("Wrong state class, expecting View State but " 14695 + "received " + state.getClass().toString() + " instead. This usually happens " 14696 + "when two views of different type have the same id in the same hierarchy. " 14697 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 14698 + "other views do not use the same id."); 14699 } 14700 if (state != null && state instanceof BaseSavedState) { 14701 mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved; 14702 } 14703 } 14704 14705 /** 14706 * <p>Return the time at which the drawing of the view hierarchy started.</p> 14707 * 14708 * @return the drawing start time in milliseconds 14709 */ 14710 public long getDrawingTime() { 14711 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 14712 } 14713 14714 /** 14715 * <p>Enables or disables the duplication of the parent's state into this view. When 14716 * duplication is enabled, this view gets its drawable state from its parent rather 14717 * than from its own internal properties.</p> 14718 * 14719 * <p>Note: in the current implementation, setting this property to true after the 14720 * view was added to a ViewGroup might have no effect at all. This property should 14721 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 14722 * 14723 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 14724 * property is enabled, an exception will be thrown.</p> 14725 * 14726 * <p>Note: if the child view uses and updates additional states which are unknown to the 14727 * parent, these states should not be affected by this method.</p> 14728 * 14729 * @param enabled True to enable duplication of the parent's drawable state, false 14730 * to disable it. 14731 * 14732 * @see #getDrawableState() 14733 * @see #isDuplicateParentStateEnabled() 14734 */ 14735 public void setDuplicateParentStateEnabled(boolean enabled) { 14736 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 14737 } 14738 14739 /** 14740 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 14741 * 14742 * @return True if this view's drawable state is duplicated from the parent, 14743 * false otherwise 14744 * 14745 * @see #getDrawableState() 14746 * @see #setDuplicateParentStateEnabled(boolean) 14747 */ 14748 public boolean isDuplicateParentStateEnabled() { 14749 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 14750 } 14751 14752 /** 14753 * <p>Specifies the type of layer backing this view. The layer can be 14754 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 14755 * {@link #LAYER_TYPE_HARDWARE}.</p> 14756 * 14757 * <p>A layer is associated with an optional {@link android.graphics.Paint} 14758 * instance that controls how the layer is composed on screen. The following 14759 * properties of the paint are taken into account when composing the layer:</p> 14760 * <ul> 14761 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 14762 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 14763 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 14764 * </ul> 14765 * 14766 * <p>If this view has an alpha value set to < 1.0 by calling 14767 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded 14768 * by this view's alpha value.</p> 14769 * 14770 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 14771 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 14772 * for more information on when and how to use layers.</p> 14773 * 14774 * @param layerType The type of layer to use with this view, must be one of 14775 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 14776 * {@link #LAYER_TYPE_HARDWARE} 14777 * @param paint The paint used to compose the layer. This argument is optional 14778 * and can be null. It is ignored when the layer type is 14779 * {@link #LAYER_TYPE_NONE} 14780 * 14781 * @see #getLayerType() 14782 * @see #LAYER_TYPE_NONE 14783 * @see #LAYER_TYPE_SOFTWARE 14784 * @see #LAYER_TYPE_HARDWARE 14785 * @see #setAlpha(float) 14786 * 14787 * @attr ref android.R.styleable#View_layerType 14788 */ 14789 public void setLayerType(int layerType, Paint paint) { 14790 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 14791 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 14792 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 14793 } 14794 14795 boolean typeChanged = mRenderNode.setLayerType(layerType); 14796 14797 if (!typeChanged) { 14798 setLayerPaint(paint); 14799 return; 14800 } 14801 14802 // Destroy any previous software drawing cache if needed 14803 if (mLayerType == LAYER_TYPE_SOFTWARE) { 14804 destroyDrawingCache(); 14805 } 14806 14807 mLayerType = layerType; 14808 final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE); 14809 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 14810 mRenderNode.setLayerPaint(mLayerPaint); 14811 14812 // draw() behaves differently if we are on a layer, so we need to 14813 // invalidate() here 14814 invalidateParentCaches(); 14815 invalidate(true); 14816 } 14817 14818 /** 14819 * Updates the {@link Paint} object used with the current layer (used only if the current 14820 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 14821 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 14822 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 14823 * ensure that the view gets redrawn immediately. 14824 * 14825 * <p>A layer is associated with an optional {@link android.graphics.Paint} 14826 * instance that controls how the layer is composed on screen. The following 14827 * properties of the paint are taken into account when composing the layer:</p> 14828 * <ul> 14829 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 14830 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 14831 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 14832 * </ul> 14833 * 14834 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 14835 * alpha value of the layer's paint is superseded by this view's alpha value.</p> 14836 * 14837 * @param paint The paint used to compose the layer. This argument is optional 14838 * and can be null. It is ignored when the layer type is 14839 * {@link #LAYER_TYPE_NONE} 14840 * 14841 * @see #setLayerType(int, android.graphics.Paint) 14842 */ 14843 public void setLayerPaint(Paint paint) { 14844 int layerType = getLayerType(); 14845 if (layerType != LAYER_TYPE_NONE) { 14846 mLayerPaint = paint == null ? new Paint() : paint; 14847 if (layerType == LAYER_TYPE_HARDWARE) { 14848 if (mRenderNode.setLayerPaint(mLayerPaint)) { 14849 invalidateViewProperty(false, false); 14850 } 14851 } else { 14852 invalidate(); 14853 } 14854 } 14855 } 14856 14857 /** 14858 * Indicates what type of layer is currently associated with this view. By default 14859 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 14860 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 14861 * for more information on the different types of layers. 14862 * 14863 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 14864 * {@link #LAYER_TYPE_HARDWARE} 14865 * 14866 * @see #setLayerType(int, android.graphics.Paint) 14867 * @see #buildLayer() 14868 * @see #LAYER_TYPE_NONE 14869 * @see #LAYER_TYPE_SOFTWARE 14870 * @see #LAYER_TYPE_HARDWARE 14871 */ 14872 public int getLayerType() { 14873 return mLayerType; 14874 } 14875 14876 /** 14877 * Forces this view's layer to be created and this view to be rendered 14878 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 14879 * invoking this method will have no effect. 14880 * 14881 * This method can for instance be used to render a view into its layer before 14882 * starting an animation. If this view is complex, rendering into the layer 14883 * before starting the animation will avoid skipping frames. 14884 * 14885 * @throws IllegalStateException If this view is not attached to a window 14886 * 14887 * @see #setLayerType(int, android.graphics.Paint) 14888 */ 14889 public void buildLayer() { 14890 if (mLayerType == LAYER_TYPE_NONE) return; 14891 14892 final AttachInfo attachInfo = mAttachInfo; 14893 if (attachInfo == null) { 14894 throw new IllegalStateException("This view must be attached to a window first"); 14895 } 14896 14897 if (getWidth() == 0 || getHeight() == 0) { 14898 return; 14899 } 14900 14901 switch (mLayerType) { 14902 case LAYER_TYPE_HARDWARE: 14903 updateDisplayListIfDirty(); 14904 if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) { 14905 attachInfo.mHardwareRenderer.buildLayer(mRenderNode); 14906 } 14907 break; 14908 case LAYER_TYPE_SOFTWARE: 14909 buildDrawingCache(true); 14910 break; 14911 } 14912 } 14913 14914 /** 14915 * If this View draws with a HardwareLayer, returns it. 14916 * Otherwise returns null 14917 * 14918 * TODO: Only TextureView uses this, can we eliminate it? 14919 */ 14920 HardwareLayer getHardwareLayer() { 14921 return null; 14922 } 14923 14924 /** 14925 * Destroys all hardware rendering resources. This method is invoked 14926 * when the system needs to reclaim resources. Upon execution of this 14927 * method, you should free any OpenGL resources created by the view. 14928 * 14929 * Note: you <strong>must</strong> call 14930 * <code>super.destroyHardwareResources()</code> when overriding 14931 * this method. 14932 * 14933 * @hide 14934 */ 14935 @CallSuper 14936 protected void destroyHardwareResources() { 14937 // Although the Layer will be destroyed by RenderNode, we want to release 14938 // the staging display list, which is also a signal to RenderNode that it's 14939 // safe to free its copy of the display list as it knows that we will 14940 // push an updated DisplayList if we try to draw again 14941 resetDisplayList(); 14942 } 14943 14944 /** 14945 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 14946 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 14947 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 14948 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 14949 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 14950 * null.</p> 14951 * 14952 * <p>Enabling the drawing cache is similar to 14953 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 14954 * acceleration is turned off. When hardware acceleration is turned on, enabling the 14955 * drawing cache has no effect on rendering because the system uses a different mechanism 14956 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 14957 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 14958 * for information on how to enable software and hardware layers.</p> 14959 * 14960 * <p>This API can be used to manually generate 14961 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 14962 * {@link #getDrawingCache()}.</p> 14963 * 14964 * @param enabled true to enable the drawing cache, false otherwise 14965 * 14966 * @see #isDrawingCacheEnabled() 14967 * @see #getDrawingCache() 14968 * @see #buildDrawingCache() 14969 * @see #setLayerType(int, android.graphics.Paint) 14970 */ 14971 public void setDrawingCacheEnabled(boolean enabled) { 14972 mCachingFailed = false; 14973 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 14974 } 14975 14976 /** 14977 * <p>Indicates whether the drawing cache is enabled for this view.</p> 14978 * 14979 * @return true if the drawing cache is enabled 14980 * 14981 * @see #setDrawingCacheEnabled(boolean) 14982 * @see #getDrawingCache() 14983 */ 14984 @ViewDebug.ExportedProperty(category = "drawing") 14985 public boolean isDrawingCacheEnabled() { 14986 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 14987 } 14988 14989 /** 14990 * Debugging utility which recursively outputs the dirty state of a view and its 14991 * descendants. 14992 * 14993 * @hide 14994 */ 14995 @SuppressWarnings({"UnusedDeclaration"}) 14996 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 14997 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 14998 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 14999 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 15000 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 15001 if (clear) { 15002 mPrivateFlags &= clearMask; 15003 } 15004 if (this instanceof ViewGroup) { 15005 ViewGroup parent = (ViewGroup) this; 15006 final int count = parent.getChildCount(); 15007 for (int i = 0; i < count; i++) { 15008 final View child = parent.getChildAt(i); 15009 child.outputDirtyFlags(indent + " ", clear, clearMask); 15010 } 15011 } 15012 } 15013 15014 /** 15015 * This method is used by ViewGroup to cause its children to restore or recreate their 15016 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 15017 * to recreate its own display list, which would happen if it went through the normal 15018 * draw/dispatchDraw mechanisms. 15019 * 15020 * @hide 15021 */ 15022 protected void dispatchGetDisplayList() {} 15023 15024 /** 15025 * A view that is not attached or hardware accelerated cannot create a display list. 15026 * This method checks these conditions and returns the appropriate result. 15027 * 15028 * @return true if view has the ability to create a display list, false otherwise. 15029 * 15030 * @hide 15031 */ 15032 public boolean canHaveDisplayList() { 15033 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 15034 } 15035 15036 /** 15037 * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported) 15038 * @hide 15039 */ 15040 @NonNull 15041 public RenderNode updateDisplayListIfDirty() { 15042 final RenderNode renderNode = mRenderNode; 15043 if (!canHaveDisplayList()) { 15044 // can't populate RenderNode, don't try 15045 return renderNode; 15046 } 15047 15048 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 15049 || !renderNode.isValid() 15050 || (mRecreateDisplayList)) { 15051 // Don't need to recreate the display list, just need to tell our 15052 // children to restore/recreate theirs 15053 if (renderNode.isValid() 15054 && !mRecreateDisplayList) { 15055 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 15056 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15057 dispatchGetDisplayList(); 15058 15059 return renderNode; // no work needed 15060 } 15061 15062 // If we got here, we're recreating it. Mark it as such to ensure that 15063 // we copy in child display lists into ours in drawChild() 15064 mRecreateDisplayList = true; 15065 15066 int width = mRight - mLeft; 15067 int height = mBottom - mTop; 15068 int layerType = getLayerType(); 15069 15070 final DisplayListCanvas canvas = renderNode.start(width, height); 15071 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 15072 15073 try { 15074 final HardwareLayer layer = getHardwareLayer(); 15075 if (layer != null && layer.isValid()) { 15076 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 15077 } else if (layerType == LAYER_TYPE_SOFTWARE) { 15078 buildDrawingCache(true); 15079 Bitmap cache = getDrawingCache(true); 15080 if (cache != null) { 15081 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 15082 } 15083 } else { 15084 computeScroll(); 15085 15086 canvas.translate(-mScrollX, -mScrollY); 15087 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 15088 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15089 15090 // Fast path for layouts with no backgrounds 15091 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 15092 dispatchDraw(canvas); 15093 if (mOverlay != null && !mOverlay.isEmpty()) { 15094 mOverlay.getOverlayView().draw(canvas); 15095 } 15096 } else { 15097 draw(canvas); 15098 } 15099 } 15100 } finally { 15101 renderNode.end(canvas); 15102 setDisplayListProperties(renderNode); 15103 } 15104 } else { 15105 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 15106 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15107 } 15108 return renderNode; 15109 } 15110 15111 private void resetDisplayList() { 15112 if (mRenderNode.isValid()) { 15113 mRenderNode.destroyDisplayListData(); 15114 } 15115 15116 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 15117 mBackgroundRenderNode.destroyDisplayListData(); 15118 } 15119 } 15120 15121 /** 15122 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 15123 * 15124 * @return A non-scaled bitmap representing this view or null if cache is disabled. 15125 * 15126 * @see #getDrawingCache(boolean) 15127 */ 15128 public Bitmap getDrawingCache() { 15129 return getDrawingCache(false); 15130 } 15131 15132 /** 15133 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 15134 * is null when caching is disabled. If caching is enabled and the cache is not ready, 15135 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 15136 * draw from the cache when the cache is enabled. To benefit from the cache, you must 15137 * request the drawing cache by calling this method and draw it on screen if the 15138 * returned bitmap is not null.</p> 15139 * 15140 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 15141 * this method will create a bitmap of the same size as this view. Because this bitmap 15142 * will be drawn scaled by the parent ViewGroup, the result on screen might show 15143 * scaling artifacts. To avoid such artifacts, you should call this method by setting 15144 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 15145 * size than the view. This implies that your application must be able to handle this 15146 * size.</p> 15147 * 15148 * @param autoScale Indicates whether the generated bitmap should be scaled based on 15149 * the current density of the screen when the application is in compatibility 15150 * mode. 15151 * 15152 * @return A bitmap representing this view or null if cache is disabled. 15153 * 15154 * @see #setDrawingCacheEnabled(boolean) 15155 * @see #isDrawingCacheEnabled() 15156 * @see #buildDrawingCache(boolean) 15157 * @see #destroyDrawingCache() 15158 */ 15159 public Bitmap getDrawingCache(boolean autoScale) { 15160 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 15161 return null; 15162 } 15163 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 15164 buildDrawingCache(autoScale); 15165 } 15166 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 15167 } 15168 15169 /** 15170 * <p>Frees the resources used by the drawing cache. If you call 15171 * {@link #buildDrawingCache()} manually without calling 15172 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 15173 * should cleanup the cache with this method afterwards.</p> 15174 * 15175 * @see #setDrawingCacheEnabled(boolean) 15176 * @see #buildDrawingCache() 15177 * @see #getDrawingCache() 15178 */ 15179 public void destroyDrawingCache() { 15180 if (mDrawingCache != null) { 15181 mDrawingCache.recycle(); 15182 mDrawingCache = null; 15183 } 15184 if (mUnscaledDrawingCache != null) { 15185 mUnscaledDrawingCache.recycle(); 15186 mUnscaledDrawingCache = null; 15187 } 15188 } 15189 15190 /** 15191 * Setting a solid background color for the drawing cache's bitmaps will improve 15192 * performance and memory usage. Note, though that this should only be used if this 15193 * view will always be drawn on top of a solid color. 15194 * 15195 * @param color The background color to use for the drawing cache's bitmap 15196 * 15197 * @see #setDrawingCacheEnabled(boolean) 15198 * @see #buildDrawingCache() 15199 * @see #getDrawingCache() 15200 */ 15201 public void setDrawingCacheBackgroundColor(@ColorInt int color) { 15202 if (color != mDrawingCacheBackgroundColor) { 15203 mDrawingCacheBackgroundColor = color; 15204 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 15205 } 15206 } 15207 15208 /** 15209 * @see #setDrawingCacheBackgroundColor(int) 15210 * 15211 * @return The background color to used for the drawing cache's bitmap 15212 */ 15213 @ColorInt 15214 public int getDrawingCacheBackgroundColor() { 15215 return mDrawingCacheBackgroundColor; 15216 } 15217 15218 /** 15219 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 15220 * 15221 * @see #buildDrawingCache(boolean) 15222 */ 15223 public void buildDrawingCache() { 15224 buildDrawingCache(false); 15225 } 15226 15227 /** 15228 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 15229 * 15230 * <p>If you call {@link #buildDrawingCache()} manually without calling 15231 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 15232 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 15233 * 15234 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 15235 * this method will create a bitmap of the same size as this view. Because this bitmap 15236 * will be drawn scaled by the parent ViewGroup, the result on screen might show 15237 * scaling artifacts. To avoid such artifacts, you should call this method by setting 15238 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 15239 * size than the view. This implies that your application must be able to handle this 15240 * size.</p> 15241 * 15242 * <p>You should avoid calling this method when hardware acceleration is enabled. If 15243 * you do not need the drawing cache bitmap, calling this method will increase memory 15244 * usage and cause the view to be rendered in software once, thus negatively impacting 15245 * performance.</p> 15246 * 15247 * @see #getDrawingCache() 15248 * @see #destroyDrawingCache() 15249 */ 15250 public void buildDrawingCache(boolean autoScale) { 15251 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 15252 mDrawingCache == null : mUnscaledDrawingCache == null)) { 15253 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 15254 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 15255 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 15256 } 15257 try { 15258 buildDrawingCacheImpl(autoScale); 15259 } finally { 15260 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 15261 } 15262 } 15263 } 15264 15265 /** 15266 * private, internal implementation of buildDrawingCache, used to enable tracing 15267 */ 15268 private void buildDrawingCacheImpl(boolean autoScale) { 15269 mCachingFailed = false; 15270 15271 int width = mRight - mLeft; 15272 int height = mBottom - mTop; 15273 15274 final AttachInfo attachInfo = mAttachInfo; 15275 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 15276 15277 if (autoScale && scalingRequired) { 15278 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 15279 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 15280 } 15281 15282 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 15283 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 15284 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 15285 15286 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 15287 final long drawingCacheSize = 15288 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 15289 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 15290 if (width > 0 && height > 0) { 15291 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 15292 + projectedBitmapSize + " bytes, only " 15293 + drawingCacheSize + " available"); 15294 } 15295 destroyDrawingCache(); 15296 mCachingFailed = true; 15297 return; 15298 } 15299 15300 boolean clear = true; 15301 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 15302 15303 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 15304 Bitmap.Config quality; 15305 if (!opaque) { 15306 // Never pick ARGB_4444 because it looks awful 15307 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 15308 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 15309 case DRAWING_CACHE_QUALITY_AUTO: 15310 case DRAWING_CACHE_QUALITY_LOW: 15311 case DRAWING_CACHE_QUALITY_HIGH: 15312 default: 15313 quality = Bitmap.Config.ARGB_8888; 15314 break; 15315 } 15316 } else { 15317 // Optimization for translucent windows 15318 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 15319 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 15320 } 15321 15322 // Try to cleanup memory 15323 if (bitmap != null) bitmap.recycle(); 15324 15325 try { 15326 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 15327 width, height, quality); 15328 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 15329 if (autoScale) { 15330 mDrawingCache = bitmap; 15331 } else { 15332 mUnscaledDrawingCache = bitmap; 15333 } 15334 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 15335 } catch (OutOfMemoryError e) { 15336 // If there is not enough memory to create the bitmap cache, just 15337 // ignore the issue as bitmap caches are not required to draw the 15338 // view hierarchy 15339 if (autoScale) { 15340 mDrawingCache = null; 15341 } else { 15342 mUnscaledDrawingCache = null; 15343 } 15344 mCachingFailed = true; 15345 return; 15346 } 15347 15348 clear = drawingCacheBackgroundColor != 0; 15349 } 15350 15351 Canvas canvas; 15352 if (attachInfo != null) { 15353 canvas = attachInfo.mCanvas; 15354 if (canvas == null) { 15355 canvas = new Canvas(); 15356 } 15357 canvas.setBitmap(bitmap); 15358 // Temporarily clobber the cached Canvas in case one of our children 15359 // is also using a drawing cache. Without this, the children would 15360 // steal the canvas by attaching their own bitmap to it and bad, bad 15361 // thing would happen (invisible views, corrupted drawings, etc.) 15362 attachInfo.mCanvas = null; 15363 } else { 15364 // This case should hopefully never or seldom happen 15365 canvas = new Canvas(bitmap); 15366 } 15367 15368 if (clear) { 15369 bitmap.eraseColor(drawingCacheBackgroundColor); 15370 } 15371 15372 computeScroll(); 15373 final int restoreCount = canvas.save(); 15374 15375 if (autoScale && scalingRequired) { 15376 final float scale = attachInfo.mApplicationScale; 15377 canvas.scale(scale, scale); 15378 } 15379 15380 canvas.translate(-mScrollX, -mScrollY); 15381 15382 mPrivateFlags |= PFLAG_DRAWN; 15383 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 15384 mLayerType != LAYER_TYPE_NONE) { 15385 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 15386 } 15387 15388 // Fast path for layouts with no backgrounds 15389 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 15390 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15391 dispatchDraw(canvas); 15392 if (mOverlay != null && !mOverlay.isEmpty()) { 15393 mOverlay.getOverlayView().draw(canvas); 15394 } 15395 } else { 15396 draw(canvas); 15397 } 15398 15399 canvas.restoreToCount(restoreCount); 15400 canvas.setBitmap(null); 15401 15402 if (attachInfo != null) { 15403 // Restore the cached Canvas for our siblings 15404 attachInfo.mCanvas = canvas; 15405 } 15406 } 15407 15408 /** 15409 * Create a snapshot of the view into a bitmap. We should probably make 15410 * some form of this public, but should think about the API. 15411 */ 15412 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 15413 int width = mRight - mLeft; 15414 int height = mBottom - mTop; 15415 15416 final AttachInfo attachInfo = mAttachInfo; 15417 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 15418 width = (int) ((width * scale) + 0.5f); 15419 height = (int) ((height * scale) + 0.5f); 15420 15421 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 15422 width > 0 ? width : 1, height > 0 ? height : 1, quality); 15423 if (bitmap == null) { 15424 throw new OutOfMemoryError(); 15425 } 15426 15427 Resources resources = getResources(); 15428 if (resources != null) { 15429 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 15430 } 15431 15432 Canvas canvas; 15433 if (attachInfo != null) { 15434 canvas = attachInfo.mCanvas; 15435 if (canvas == null) { 15436 canvas = new Canvas(); 15437 } 15438 canvas.setBitmap(bitmap); 15439 // Temporarily clobber the cached Canvas in case one of our children 15440 // is also using a drawing cache. Without this, the children would 15441 // steal the canvas by attaching their own bitmap to it and bad, bad 15442 // things would happen (invisible views, corrupted drawings, etc.) 15443 attachInfo.mCanvas = null; 15444 } else { 15445 // This case should hopefully never or seldom happen 15446 canvas = new Canvas(bitmap); 15447 } 15448 15449 if ((backgroundColor & 0xff000000) != 0) { 15450 bitmap.eraseColor(backgroundColor); 15451 } 15452 15453 computeScroll(); 15454 final int restoreCount = canvas.save(); 15455 canvas.scale(scale, scale); 15456 canvas.translate(-mScrollX, -mScrollY); 15457 15458 // Temporarily remove the dirty mask 15459 int flags = mPrivateFlags; 15460 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15461 15462 // Fast path for layouts with no backgrounds 15463 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 15464 dispatchDraw(canvas); 15465 if (mOverlay != null && !mOverlay.isEmpty()) { 15466 mOverlay.getOverlayView().draw(canvas); 15467 } 15468 } else { 15469 draw(canvas); 15470 } 15471 15472 mPrivateFlags = flags; 15473 15474 canvas.restoreToCount(restoreCount); 15475 canvas.setBitmap(null); 15476 15477 if (attachInfo != null) { 15478 // Restore the cached Canvas for our siblings 15479 attachInfo.mCanvas = canvas; 15480 } 15481 15482 return bitmap; 15483 } 15484 15485 /** 15486 * Indicates whether this View is currently in edit mode. A View is usually 15487 * in edit mode when displayed within a developer tool. For instance, if 15488 * this View is being drawn by a visual user interface builder, this method 15489 * should return true. 15490 * 15491 * Subclasses should check the return value of this method to provide 15492 * different behaviors if their normal behavior might interfere with the 15493 * host environment. For instance: the class spawns a thread in its 15494 * constructor, the drawing code relies on device-specific features, etc. 15495 * 15496 * This method is usually checked in the drawing code of custom widgets. 15497 * 15498 * @return True if this View is in edit mode, false otherwise. 15499 */ 15500 public boolean isInEditMode() { 15501 return false; 15502 } 15503 15504 /** 15505 * If the View draws content inside its padding and enables fading edges, 15506 * it needs to support padding offsets. Padding offsets are added to the 15507 * fading edges to extend the length of the fade so that it covers pixels 15508 * drawn inside the padding. 15509 * 15510 * Subclasses of this class should override this method if they need 15511 * to draw content inside the padding. 15512 * 15513 * @return True if padding offset must be applied, false otherwise. 15514 * 15515 * @see #getLeftPaddingOffset() 15516 * @see #getRightPaddingOffset() 15517 * @see #getTopPaddingOffset() 15518 * @see #getBottomPaddingOffset() 15519 * 15520 * @since CURRENT 15521 */ 15522 protected boolean isPaddingOffsetRequired() { 15523 return false; 15524 } 15525 15526 /** 15527 * Amount by which to extend the left fading region. Called only when 15528 * {@link #isPaddingOffsetRequired()} returns true. 15529 * 15530 * @return The left padding offset in pixels. 15531 * 15532 * @see #isPaddingOffsetRequired() 15533 * 15534 * @since CURRENT 15535 */ 15536 protected int getLeftPaddingOffset() { 15537 return 0; 15538 } 15539 15540 /** 15541 * Amount by which to extend the right fading region. Called only when 15542 * {@link #isPaddingOffsetRequired()} returns true. 15543 * 15544 * @return The right padding offset in pixels. 15545 * 15546 * @see #isPaddingOffsetRequired() 15547 * 15548 * @since CURRENT 15549 */ 15550 protected int getRightPaddingOffset() { 15551 return 0; 15552 } 15553 15554 /** 15555 * Amount by which to extend the top fading region. Called only when 15556 * {@link #isPaddingOffsetRequired()} returns true. 15557 * 15558 * @return The top padding offset in pixels. 15559 * 15560 * @see #isPaddingOffsetRequired() 15561 * 15562 * @since CURRENT 15563 */ 15564 protected int getTopPaddingOffset() { 15565 return 0; 15566 } 15567 15568 /** 15569 * Amount by which to extend the bottom fading region. Called only when 15570 * {@link #isPaddingOffsetRequired()} returns true. 15571 * 15572 * @return The bottom padding offset in pixels. 15573 * 15574 * @see #isPaddingOffsetRequired() 15575 * 15576 * @since CURRENT 15577 */ 15578 protected int getBottomPaddingOffset() { 15579 return 0; 15580 } 15581 15582 /** 15583 * @hide 15584 * @param offsetRequired 15585 */ 15586 protected int getFadeTop(boolean offsetRequired) { 15587 int top = mPaddingTop; 15588 if (offsetRequired) top += getTopPaddingOffset(); 15589 return top; 15590 } 15591 15592 /** 15593 * @hide 15594 * @param offsetRequired 15595 */ 15596 protected int getFadeHeight(boolean offsetRequired) { 15597 int padding = mPaddingTop; 15598 if (offsetRequired) padding += getTopPaddingOffset(); 15599 return mBottom - mTop - mPaddingBottom - padding; 15600 } 15601 15602 /** 15603 * <p>Indicates whether this view is attached to a hardware accelerated 15604 * window or not.</p> 15605 * 15606 * <p>Even if this method returns true, it does not mean that every call 15607 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 15608 * accelerated {@link android.graphics.Canvas}. For instance, if this view 15609 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 15610 * window is hardware accelerated, 15611 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 15612 * return false, and this method will return true.</p> 15613 * 15614 * @return True if the view is attached to a window and the window is 15615 * hardware accelerated; false in any other case. 15616 */ 15617 @ViewDebug.ExportedProperty(category = "drawing") 15618 public boolean isHardwareAccelerated() { 15619 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 15620 } 15621 15622 /** 15623 * Sets a rectangular area on this view to which the view will be clipped 15624 * when it is drawn. Setting the value to null will remove the clip bounds 15625 * and the view will draw normally, using its full bounds. 15626 * 15627 * @param clipBounds The rectangular area, in the local coordinates of 15628 * this view, to which future drawing operations will be clipped. 15629 */ 15630 public void setClipBounds(Rect clipBounds) { 15631 if (clipBounds == mClipBounds 15632 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 15633 return; 15634 } 15635 if (clipBounds != null) { 15636 if (mClipBounds == null) { 15637 mClipBounds = new Rect(clipBounds); 15638 } else { 15639 mClipBounds.set(clipBounds); 15640 } 15641 } else { 15642 mClipBounds = null; 15643 } 15644 mRenderNode.setClipBounds(mClipBounds); 15645 invalidateViewProperty(false, false); 15646 } 15647 15648 /** 15649 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 15650 * 15651 * @return A copy of the current clip bounds if clip bounds are set, 15652 * otherwise null. 15653 */ 15654 public Rect getClipBounds() { 15655 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 15656 } 15657 15658 15659 /** 15660 * Populates an output rectangle with the clip bounds of the view, 15661 * returning {@code true} if successful or {@code false} if the view's 15662 * clip bounds are {@code null}. 15663 * 15664 * @param outRect rectangle in which to place the clip bounds of the view 15665 * @return {@code true} if successful or {@code false} if the view's 15666 * clip bounds are {@code null} 15667 */ 15668 public boolean getClipBounds(Rect outRect) { 15669 if (mClipBounds != null) { 15670 outRect.set(mClipBounds); 15671 return true; 15672 } 15673 return false; 15674 } 15675 15676 /** 15677 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 15678 * case of an active Animation being run on the view. 15679 */ 15680 private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime, 15681 Animation a, boolean scalingRequired) { 15682 Transformation invalidationTransform; 15683 final int flags = parent.mGroupFlags; 15684 final boolean initialized = a.isInitialized(); 15685 if (!initialized) { 15686 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 15687 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 15688 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 15689 onAnimationStart(); 15690 } 15691 15692 final Transformation t = parent.getChildTransformation(); 15693 boolean more = a.getTransformation(drawingTime, t, 1f); 15694 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 15695 if (parent.mInvalidationTransformation == null) { 15696 parent.mInvalidationTransformation = new Transformation(); 15697 } 15698 invalidationTransform = parent.mInvalidationTransformation; 15699 a.getTransformation(drawingTime, invalidationTransform, 1f); 15700 } else { 15701 invalidationTransform = t; 15702 } 15703 15704 if (more) { 15705 if (!a.willChangeBounds()) { 15706 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 15707 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 15708 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 15709 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 15710 // The child need to draw an animation, potentially offscreen, so 15711 // make sure we do not cancel invalidate requests 15712 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 15713 parent.invalidate(mLeft, mTop, mRight, mBottom); 15714 } 15715 } else { 15716 if (parent.mInvalidateRegion == null) { 15717 parent.mInvalidateRegion = new RectF(); 15718 } 15719 final RectF region = parent.mInvalidateRegion; 15720 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 15721 invalidationTransform); 15722 15723 // The child need to draw an animation, potentially offscreen, so 15724 // make sure we do not cancel invalidate requests 15725 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 15726 15727 final int left = mLeft + (int) region.left; 15728 final int top = mTop + (int) region.top; 15729 parent.invalidate(left, top, left + (int) (region.width() + .5f), 15730 top + (int) (region.height() + .5f)); 15731 } 15732 } 15733 return more; 15734 } 15735 15736 /** 15737 * This method is called by getDisplayList() when a display list is recorded for a View. 15738 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 15739 */ 15740 void setDisplayListProperties(RenderNode renderNode) { 15741 if (renderNode != null) { 15742 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 15743 renderNode.setClipToBounds(mParent instanceof ViewGroup 15744 && ((ViewGroup) mParent).getClipChildren()); 15745 15746 float alpha = 1; 15747 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 15748 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 15749 ViewGroup parentVG = (ViewGroup) mParent; 15750 final Transformation t = parentVG.getChildTransformation(); 15751 if (parentVG.getChildStaticTransformation(this, t)) { 15752 final int transformType = t.getTransformationType(); 15753 if (transformType != Transformation.TYPE_IDENTITY) { 15754 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 15755 alpha = t.getAlpha(); 15756 } 15757 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 15758 renderNode.setStaticMatrix(t.getMatrix()); 15759 } 15760 } 15761 } 15762 } 15763 if (mTransformationInfo != null) { 15764 alpha *= getFinalAlpha(); 15765 if (alpha < 1) { 15766 final int multipliedAlpha = (int) (255 * alpha); 15767 if (onSetAlpha(multipliedAlpha)) { 15768 alpha = 1; 15769 } 15770 } 15771 renderNode.setAlpha(alpha); 15772 } else if (alpha < 1) { 15773 renderNode.setAlpha(alpha); 15774 } 15775 } 15776 } 15777 15778 /** 15779 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 15780 * 15781 * This is where the View specializes rendering behavior based on layer type, 15782 * and hardware acceleration. 15783 */ 15784 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 15785 final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated(); 15786 /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList. 15787 * 15788 * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't 15789 * HW accelerated, it can't handle drawing RenderNodes. 15790 */ 15791 boolean drawingWithRenderNode = mAttachInfo != null 15792 && mAttachInfo.mHardwareAccelerated 15793 && hardwareAcceleratedCanvas; 15794 15795 boolean more = false; 15796 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 15797 final int parentFlags = parent.mGroupFlags; 15798 15799 if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) { 15800 parent.getChildTransformation().clear(); 15801 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15802 } 15803 15804 Transformation transformToApply = null; 15805 boolean concatMatrix = false; 15806 final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired; 15807 final Animation a = getAnimation(); 15808 if (a != null) { 15809 more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired); 15810 concatMatrix = a.willChangeTransformationMatrix(); 15811 if (concatMatrix) { 15812 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 15813 } 15814 transformToApply = parent.getChildTransformation(); 15815 } else { 15816 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 15817 // No longer animating: clear out old animation matrix 15818 mRenderNode.setAnimationMatrix(null); 15819 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 15820 } 15821 if (!drawingWithRenderNode 15822 && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 15823 final Transformation t = parent.getChildTransformation(); 15824 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 15825 if (hasTransform) { 15826 final int transformType = t.getTransformationType(); 15827 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 15828 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 15829 } 15830 } 15831 } 15832 15833 concatMatrix |= !childHasIdentityMatrix; 15834 15835 // Sets the flag as early as possible to allow draw() implementations 15836 // to call invalidate() successfully when doing animations 15837 mPrivateFlags |= PFLAG_DRAWN; 15838 15839 if (!concatMatrix && 15840 (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 15841 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 15842 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 15843 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 15844 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 15845 return more; 15846 } 15847 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 15848 15849 if (hardwareAcceleratedCanvas) { 15850 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 15851 // retain the flag's value temporarily in the mRecreateDisplayList flag 15852 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0; 15853 mPrivateFlags &= ~PFLAG_INVALIDATED; 15854 } 15855 15856 RenderNode renderNode = null; 15857 Bitmap cache = null; 15858 int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local 15859 if (layerType == LAYER_TYPE_SOFTWARE 15860 || (!drawingWithRenderNode && layerType != LAYER_TYPE_NONE)) { 15861 // If not drawing with RenderNode, treat HW layers as SW 15862 layerType = LAYER_TYPE_SOFTWARE; 15863 buildDrawingCache(true); 15864 cache = getDrawingCache(true); 15865 } 15866 15867 if (drawingWithRenderNode) { 15868 // Delay getting the display list until animation-driven alpha values are 15869 // set up and possibly passed on to the view 15870 renderNode = updateDisplayListIfDirty(); 15871 if (!renderNode.isValid()) { 15872 // Uncommon, but possible. If a view is removed from the hierarchy during the call 15873 // to getDisplayList(), the display list will be marked invalid and we should not 15874 // try to use it again. 15875 renderNode = null; 15876 drawingWithRenderNode = false; 15877 } 15878 } 15879 15880 int sx = 0; 15881 int sy = 0; 15882 if (!drawingWithRenderNode) { 15883 computeScroll(); 15884 sx = mScrollX; 15885 sy = mScrollY; 15886 } 15887 15888 final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode; 15889 final boolean offsetForScroll = cache == null && !drawingWithRenderNode; 15890 15891 int restoreTo = -1; 15892 if (!drawingWithRenderNode || transformToApply != null) { 15893 restoreTo = canvas.save(); 15894 } 15895 if (offsetForScroll) { 15896 canvas.translate(mLeft - sx, mTop - sy); 15897 } else { 15898 if (!drawingWithRenderNode) { 15899 canvas.translate(mLeft, mTop); 15900 } 15901 if (scalingRequired) { 15902 if (drawingWithRenderNode) { 15903 // TODO: Might not need this if we put everything inside the DL 15904 restoreTo = canvas.save(); 15905 } 15906 // mAttachInfo cannot be null, otherwise scalingRequired == false 15907 final float scale = 1.0f / mAttachInfo.mApplicationScale; 15908 canvas.scale(scale, scale); 15909 } 15910 } 15911 15912 float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha()); 15913 if (transformToApply != null 15914 || alpha < 1 15915 || !hasIdentityMatrix() 15916 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 15917 if (transformToApply != null || !childHasIdentityMatrix) { 15918 int transX = 0; 15919 int transY = 0; 15920 15921 if (offsetForScroll) { 15922 transX = -sx; 15923 transY = -sy; 15924 } 15925 15926 if (transformToApply != null) { 15927 if (concatMatrix) { 15928 if (drawingWithRenderNode) { 15929 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 15930 } else { 15931 // Undo the scroll translation, apply the transformation matrix, 15932 // then redo the scroll translate to get the correct result. 15933 canvas.translate(-transX, -transY); 15934 canvas.concat(transformToApply.getMatrix()); 15935 canvas.translate(transX, transY); 15936 } 15937 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15938 } 15939 15940 float transformAlpha = transformToApply.getAlpha(); 15941 if (transformAlpha < 1) { 15942 alpha *= transformAlpha; 15943 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15944 } 15945 } 15946 15947 if (!childHasIdentityMatrix && !drawingWithRenderNode) { 15948 canvas.translate(-transX, -transY); 15949 canvas.concat(getMatrix()); 15950 canvas.translate(transX, transY); 15951 } 15952 } 15953 15954 // Deal with alpha if it is or used to be <1 15955 if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 15956 if (alpha < 1) { 15957 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 15958 } else { 15959 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 15960 } 15961 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15962 if (!drawingWithDrawingCache) { 15963 final int multipliedAlpha = (int) (255 * alpha); 15964 if (!onSetAlpha(multipliedAlpha)) { 15965 if (drawingWithRenderNode) { 15966 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 15967 } else if (layerType == LAYER_TYPE_NONE) { 15968 canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(), 15969 multipliedAlpha); 15970 } 15971 } else { 15972 // Alpha is handled by the child directly, clobber the layer's alpha 15973 mPrivateFlags |= PFLAG_ALPHA_SET; 15974 } 15975 } 15976 } 15977 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 15978 onSetAlpha(255); 15979 mPrivateFlags &= ~PFLAG_ALPHA_SET; 15980 } 15981 15982 if (!drawingWithRenderNode) { 15983 // apply clips directly, since RenderNode won't do it for this draw 15984 if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) { 15985 if (offsetForScroll) { 15986 canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight()); 15987 } else { 15988 if (!scalingRequired || cache == null) { 15989 canvas.clipRect(0, 0, getWidth(), getHeight()); 15990 } else { 15991 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 15992 } 15993 } 15994 } 15995 15996 if (mClipBounds != null) { 15997 // clip bounds ignore scroll 15998 canvas.clipRect(mClipBounds); 15999 } 16000 } 16001 16002 if (!drawingWithDrawingCache) { 16003 if (drawingWithRenderNode) { 16004 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16005 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 16006 } else { 16007 // Fast path for layouts with no backgrounds 16008 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16009 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16010 dispatchDraw(canvas); 16011 } else { 16012 draw(canvas); 16013 } 16014 } 16015 } else if (cache != null) { 16016 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16017 Paint cachePaint; 16018 int restoreAlpha = 0; 16019 16020 if (layerType == LAYER_TYPE_NONE) { 16021 cachePaint = parent.mCachePaint; 16022 if (cachePaint == null) { 16023 cachePaint = new Paint(); 16024 cachePaint.setDither(false); 16025 parent.mCachePaint = cachePaint; 16026 } 16027 } else { 16028 cachePaint = mLayerPaint; 16029 restoreAlpha = mLayerPaint.getAlpha(); 16030 } 16031 cachePaint.setAlpha((int) (alpha * 255)); 16032 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 16033 cachePaint.setAlpha(restoreAlpha); 16034 } 16035 16036 if (restoreTo >= 0) { 16037 canvas.restoreToCount(restoreTo); 16038 } 16039 16040 if (a != null && !more) { 16041 if (!hardwareAcceleratedCanvas && !a.getFillAfter()) { 16042 onSetAlpha(255); 16043 } 16044 parent.finishAnimatingView(this, a); 16045 } 16046 16047 if (more && hardwareAcceleratedCanvas) { 16048 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 16049 // alpha animations should cause the child to recreate its display list 16050 invalidate(true); 16051 } 16052 } 16053 16054 mRecreateDisplayList = false; 16055 16056 return more; 16057 } 16058 16059 /** 16060 * Manually render this view (and all of its children) to the given Canvas. 16061 * The view must have already done a full layout before this function is 16062 * called. When implementing a view, implement 16063 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 16064 * If you do need to override this method, call the superclass version. 16065 * 16066 * @param canvas The Canvas to which the View is rendered. 16067 */ 16068 @CallSuper 16069 public void draw(Canvas canvas) { 16070 final int privateFlags = mPrivateFlags; 16071 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 16072 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 16073 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 16074 16075 /* 16076 * Draw traversal performs several drawing steps which must be executed 16077 * in the appropriate order: 16078 * 16079 * 1. Draw the background 16080 * 2. If necessary, save the canvas' layers to prepare for fading 16081 * 3. Draw view's content 16082 * 4. Draw children 16083 * 5. If necessary, draw the fading edges and restore layers 16084 * 6. Draw decorations (scrollbars for instance) 16085 */ 16086 16087 // Step 1, draw the background, if needed 16088 int saveCount; 16089 16090 if (!dirtyOpaque) { 16091 drawBackground(canvas); 16092 } 16093 16094 // skip step 2 & 5 if possible (common case) 16095 final int viewFlags = mViewFlags; 16096 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 16097 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 16098 if (!verticalEdges && !horizontalEdges) { 16099 // Step 3, draw the content 16100 if (!dirtyOpaque) onDraw(canvas); 16101 16102 // Step 4, draw the children 16103 dispatchDraw(canvas); 16104 16105 // Overlay is part of the content and draws beneath Foreground 16106 if (mOverlay != null && !mOverlay.isEmpty()) { 16107 mOverlay.getOverlayView().dispatchDraw(canvas); 16108 } 16109 16110 // Step 6, draw decorations (foreground, scrollbars) 16111 onDrawForeground(canvas); 16112 16113 // we're done... 16114 return; 16115 } 16116 16117 /* 16118 * Here we do the full fledged routine... 16119 * (this is an uncommon case where speed matters less, 16120 * this is why we repeat some of the tests that have been 16121 * done above) 16122 */ 16123 16124 boolean drawTop = false; 16125 boolean drawBottom = false; 16126 boolean drawLeft = false; 16127 boolean drawRight = false; 16128 16129 float topFadeStrength = 0.0f; 16130 float bottomFadeStrength = 0.0f; 16131 float leftFadeStrength = 0.0f; 16132 float rightFadeStrength = 0.0f; 16133 16134 // Step 2, save the canvas' layers 16135 int paddingLeft = mPaddingLeft; 16136 16137 final boolean offsetRequired = isPaddingOffsetRequired(); 16138 if (offsetRequired) { 16139 paddingLeft += getLeftPaddingOffset(); 16140 } 16141 16142 int left = mScrollX + paddingLeft; 16143 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 16144 int top = mScrollY + getFadeTop(offsetRequired); 16145 int bottom = top + getFadeHeight(offsetRequired); 16146 16147 if (offsetRequired) { 16148 right += getRightPaddingOffset(); 16149 bottom += getBottomPaddingOffset(); 16150 } 16151 16152 final ScrollabilityCache scrollabilityCache = mScrollCache; 16153 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 16154 int length = (int) fadeHeight; 16155 16156 // clip the fade length if top and bottom fades overlap 16157 // overlapping fades produce odd-looking artifacts 16158 if (verticalEdges && (top + length > bottom - length)) { 16159 length = (bottom - top) / 2; 16160 } 16161 16162 // also clip horizontal fades if necessary 16163 if (horizontalEdges && (left + length > right - length)) { 16164 length = (right - left) / 2; 16165 } 16166 16167 if (verticalEdges) { 16168 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 16169 drawTop = topFadeStrength * fadeHeight > 1.0f; 16170 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 16171 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 16172 } 16173 16174 if (horizontalEdges) { 16175 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 16176 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 16177 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 16178 drawRight = rightFadeStrength * fadeHeight > 1.0f; 16179 } 16180 16181 saveCount = canvas.getSaveCount(); 16182 16183 int solidColor = getSolidColor(); 16184 if (solidColor == 0) { 16185 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 16186 16187 if (drawTop) { 16188 canvas.saveLayer(left, top, right, top + length, null, flags); 16189 } 16190 16191 if (drawBottom) { 16192 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 16193 } 16194 16195 if (drawLeft) { 16196 canvas.saveLayer(left, top, left + length, bottom, null, flags); 16197 } 16198 16199 if (drawRight) { 16200 canvas.saveLayer(right - length, top, right, bottom, null, flags); 16201 } 16202 } else { 16203 scrollabilityCache.setFadeColor(solidColor); 16204 } 16205 16206 // Step 3, draw the content 16207 if (!dirtyOpaque) onDraw(canvas); 16208 16209 // Step 4, draw the children 16210 dispatchDraw(canvas); 16211 16212 // Step 5, draw the fade effect and restore layers 16213 final Paint p = scrollabilityCache.paint; 16214 final Matrix matrix = scrollabilityCache.matrix; 16215 final Shader fade = scrollabilityCache.shader; 16216 16217 if (drawTop) { 16218 matrix.setScale(1, fadeHeight * topFadeStrength); 16219 matrix.postTranslate(left, top); 16220 fade.setLocalMatrix(matrix); 16221 p.setShader(fade); 16222 canvas.drawRect(left, top, right, top + length, p); 16223 } 16224 16225 if (drawBottom) { 16226 matrix.setScale(1, fadeHeight * bottomFadeStrength); 16227 matrix.postRotate(180); 16228 matrix.postTranslate(left, bottom); 16229 fade.setLocalMatrix(matrix); 16230 p.setShader(fade); 16231 canvas.drawRect(left, bottom - length, right, bottom, p); 16232 } 16233 16234 if (drawLeft) { 16235 matrix.setScale(1, fadeHeight * leftFadeStrength); 16236 matrix.postRotate(-90); 16237 matrix.postTranslate(left, top); 16238 fade.setLocalMatrix(matrix); 16239 p.setShader(fade); 16240 canvas.drawRect(left, top, left + length, bottom, p); 16241 } 16242 16243 if (drawRight) { 16244 matrix.setScale(1, fadeHeight * rightFadeStrength); 16245 matrix.postRotate(90); 16246 matrix.postTranslate(right, top); 16247 fade.setLocalMatrix(matrix); 16248 p.setShader(fade); 16249 canvas.drawRect(right - length, top, right, bottom, p); 16250 } 16251 16252 canvas.restoreToCount(saveCount); 16253 16254 // Overlay is part of the content and draws beneath Foreground 16255 if (mOverlay != null && !mOverlay.isEmpty()) { 16256 mOverlay.getOverlayView().dispatchDraw(canvas); 16257 } 16258 16259 // Step 6, draw decorations (foreground, scrollbars) 16260 onDrawForeground(canvas); 16261 } 16262 16263 /** 16264 * Draws the background onto the specified canvas. 16265 * 16266 * @param canvas Canvas on which to draw the background 16267 */ 16268 private void drawBackground(Canvas canvas) { 16269 final Drawable background = mBackground; 16270 if (background == null) { 16271 return; 16272 } 16273 16274 setBackgroundBounds(); 16275 16276 // Attempt to use a display list if requested. 16277 if (canvas.isHardwareAccelerated() && mAttachInfo != null 16278 && mAttachInfo.mHardwareRenderer != null) { 16279 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 16280 16281 final RenderNode renderNode = mBackgroundRenderNode; 16282 if (renderNode != null && renderNode.isValid()) { 16283 setBackgroundRenderNodeProperties(renderNode); 16284 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 16285 return; 16286 } 16287 } 16288 16289 final int scrollX = mScrollX; 16290 final int scrollY = mScrollY; 16291 if ((scrollX | scrollY) == 0) { 16292 background.draw(canvas); 16293 } else { 16294 canvas.translate(scrollX, scrollY); 16295 background.draw(canvas); 16296 canvas.translate(-scrollX, -scrollY); 16297 } 16298 } 16299 16300 /** 16301 * Sets the correct background bounds and rebuilds the outline, if needed. 16302 * <p/> 16303 * This is called by LayoutLib. 16304 */ 16305 void setBackgroundBounds() { 16306 if (mBackgroundSizeChanged && mBackground != null) { 16307 mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 16308 mBackgroundSizeChanged = false; 16309 rebuildOutline(); 16310 } 16311 } 16312 16313 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 16314 renderNode.setTranslationX(mScrollX); 16315 renderNode.setTranslationY(mScrollY); 16316 } 16317 16318 /** 16319 * Creates a new display list or updates the existing display list for the 16320 * specified Drawable. 16321 * 16322 * @param drawable Drawable for which to create a display list 16323 * @param renderNode Existing RenderNode, or {@code null} 16324 * @return A valid display list for the specified drawable 16325 */ 16326 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 16327 if (renderNode == null) { 16328 renderNode = RenderNode.create(drawable.getClass().getName(), this); 16329 } 16330 16331 final Rect bounds = drawable.getBounds(); 16332 final int width = bounds.width(); 16333 final int height = bounds.height(); 16334 final DisplayListCanvas canvas = renderNode.start(width, height); 16335 16336 // Reverse left/top translation done by drawable canvas, which will 16337 // instead be applied by rendernode's LTRB bounds below. This way, the 16338 // drawable's bounds match with its rendernode bounds and its content 16339 // will lie within those bounds in the rendernode tree. 16340 canvas.translate(-bounds.left, -bounds.top); 16341 16342 try { 16343 drawable.draw(canvas); 16344 } finally { 16345 renderNode.end(canvas); 16346 } 16347 16348 // Set up drawable properties that are view-independent. 16349 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 16350 renderNode.setProjectBackwards(drawable.isProjected()); 16351 renderNode.setProjectionReceiver(true); 16352 renderNode.setClipToBounds(false); 16353 return renderNode; 16354 } 16355 16356 /** 16357 * Returns the overlay for this view, creating it if it does not yet exist. 16358 * Adding drawables to the overlay will cause them to be displayed whenever 16359 * the view itself is redrawn. Objects in the overlay should be actively 16360 * managed: remove them when they should not be displayed anymore. The 16361 * overlay will always have the same size as its host view. 16362 * 16363 * <p>Note: Overlays do not currently work correctly with {@link 16364 * SurfaceView} or {@link TextureView}; contents in overlays for these 16365 * types of views may not display correctly.</p> 16366 * 16367 * @return The ViewOverlay object for this view. 16368 * @see ViewOverlay 16369 */ 16370 public ViewOverlay getOverlay() { 16371 if (mOverlay == null) { 16372 mOverlay = new ViewOverlay(mContext, this); 16373 } 16374 return mOverlay; 16375 } 16376 16377 /** 16378 * Override this if your view is known to always be drawn on top of a solid color background, 16379 * and needs to draw fading edges. Returning a non-zero color enables the view system to 16380 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 16381 * should be set to 0xFF. 16382 * 16383 * @see #setVerticalFadingEdgeEnabled(boolean) 16384 * @see #setHorizontalFadingEdgeEnabled(boolean) 16385 * 16386 * @return The known solid color background for this view, or 0 if the color may vary 16387 */ 16388 @ViewDebug.ExportedProperty(category = "drawing") 16389 @ColorInt 16390 public int getSolidColor() { 16391 return 0; 16392 } 16393 16394 /** 16395 * Build a human readable string representation of the specified view flags. 16396 * 16397 * @param flags the view flags to convert to a string 16398 * @return a String representing the supplied flags 16399 */ 16400 private static String printFlags(int flags) { 16401 String output = ""; 16402 int numFlags = 0; 16403 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 16404 output += "TAKES_FOCUS"; 16405 numFlags++; 16406 } 16407 16408 switch (flags & VISIBILITY_MASK) { 16409 case INVISIBLE: 16410 if (numFlags > 0) { 16411 output += " "; 16412 } 16413 output += "INVISIBLE"; 16414 // USELESS HERE numFlags++; 16415 break; 16416 case GONE: 16417 if (numFlags > 0) { 16418 output += " "; 16419 } 16420 output += "GONE"; 16421 // USELESS HERE numFlags++; 16422 break; 16423 default: 16424 break; 16425 } 16426 return output; 16427 } 16428 16429 /** 16430 * Build a human readable string representation of the specified private 16431 * view flags. 16432 * 16433 * @param privateFlags the private view flags to convert to a string 16434 * @return a String representing the supplied flags 16435 */ 16436 private static String printPrivateFlags(int privateFlags) { 16437 String output = ""; 16438 int numFlags = 0; 16439 16440 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 16441 output += "WANTS_FOCUS"; 16442 numFlags++; 16443 } 16444 16445 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 16446 if (numFlags > 0) { 16447 output += " "; 16448 } 16449 output += "FOCUSED"; 16450 numFlags++; 16451 } 16452 16453 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 16454 if (numFlags > 0) { 16455 output += " "; 16456 } 16457 output += "SELECTED"; 16458 numFlags++; 16459 } 16460 16461 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 16462 if (numFlags > 0) { 16463 output += " "; 16464 } 16465 output += "IS_ROOT_NAMESPACE"; 16466 numFlags++; 16467 } 16468 16469 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 16470 if (numFlags > 0) { 16471 output += " "; 16472 } 16473 output += "HAS_BOUNDS"; 16474 numFlags++; 16475 } 16476 16477 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 16478 if (numFlags > 0) { 16479 output += " "; 16480 } 16481 output += "DRAWN"; 16482 // USELESS HERE numFlags++; 16483 } 16484 return output; 16485 } 16486 16487 /** 16488 * <p>Indicates whether or not this view's layout will be requested during 16489 * the next hierarchy layout pass.</p> 16490 * 16491 * @return true if the layout will be forced during next layout pass 16492 */ 16493 public boolean isLayoutRequested() { 16494 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 16495 } 16496 16497 /** 16498 * Return true if o is a ViewGroup that is laying out using optical bounds. 16499 * @hide 16500 */ 16501 public static boolean isLayoutModeOptical(Object o) { 16502 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 16503 } 16504 16505 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 16506 Insets parentInsets = mParent instanceof View ? 16507 ((View) mParent).getOpticalInsets() : Insets.NONE; 16508 Insets childInsets = getOpticalInsets(); 16509 return setFrame( 16510 left + parentInsets.left - childInsets.left, 16511 top + parentInsets.top - childInsets.top, 16512 right + parentInsets.left + childInsets.right, 16513 bottom + parentInsets.top + childInsets.bottom); 16514 } 16515 16516 /** 16517 * Assign a size and position to a view and all of its 16518 * descendants 16519 * 16520 * <p>This is the second phase of the layout mechanism. 16521 * (The first is measuring). In this phase, each parent calls 16522 * layout on all of its children to position them. 16523 * This is typically done using the child measurements 16524 * that were stored in the measure pass().</p> 16525 * 16526 * <p>Derived classes should not override this method. 16527 * Derived classes with children should override 16528 * onLayout. In that method, they should 16529 * call layout on each of their children.</p> 16530 * 16531 * @param l Left position, relative to parent 16532 * @param t Top position, relative to parent 16533 * @param r Right position, relative to parent 16534 * @param b Bottom position, relative to parent 16535 */ 16536 @SuppressWarnings({"unchecked"}) 16537 public void layout(int l, int t, int r, int b) { 16538 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 16539 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 16540 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16541 } 16542 16543 int oldL = mLeft; 16544 int oldT = mTop; 16545 int oldB = mBottom; 16546 int oldR = mRight; 16547 16548 boolean changed = isLayoutModeOptical(mParent) ? 16549 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 16550 16551 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 16552 onLayout(changed, l, t, r, b); 16553 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 16554 16555 ListenerInfo li = mListenerInfo; 16556 if (li != null && li.mOnLayoutChangeListeners != null) { 16557 ArrayList<OnLayoutChangeListener> listenersCopy = 16558 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 16559 int numListeners = listenersCopy.size(); 16560 for (int i = 0; i < numListeners; ++i) { 16561 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 16562 } 16563 } 16564 } 16565 16566 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 16567 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 16568 } 16569 16570 /** 16571 * Called from layout when this view should 16572 * assign a size and position to each of its children. 16573 * 16574 * Derived classes with children should override 16575 * this method and call layout on each of 16576 * their children. 16577 * @param changed This is a new size or position for this view 16578 * @param left Left position, relative to parent 16579 * @param top Top position, relative to parent 16580 * @param right Right position, relative to parent 16581 * @param bottom Bottom position, relative to parent 16582 */ 16583 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 16584 } 16585 16586 /** 16587 * Assign a size and position to this view. 16588 * 16589 * This is called from layout. 16590 * 16591 * @param left Left position, relative to parent 16592 * @param top Top position, relative to parent 16593 * @param right Right position, relative to parent 16594 * @param bottom Bottom position, relative to parent 16595 * @return true if the new size and position are different than the 16596 * previous ones 16597 * {@hide} 16598 */ 16599 protected boolean setFrame(int left, int top, int right, int bottom) { 16600 boolean changed = false; 16601 16602 if (DBG) { 16603 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 16604 + right + "," + bottom + ")"); 16605 } 16606 16607 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 16608 changed = true; 16609 16610 // Remember our drawn bit 16611 int drawn = mPrivateFlags & PFLAG_DRAWN; 16612 16613 int oldWidth = mRight - mLeft; 16614 int oldHeight = mBottom - mTop; 16615 int newWidth = right - left; 16616 int newHeight = bottom - top; 16617 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 16618 16619 // Invalidate our old position 16620 invalidate(sizeChanged); 16621 16622 mLeft = left; 16623 mTop = top; 16624 mRight = right; 16625 mBottom = bottom; 16626 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 16627 16628 mPrivateFlags |= PFLAG_HAS_BOUNDS; 16629 16630 16631 if (sizeChanged) { 16632 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 16633 } 16634 16635 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 16636 // If we are visible, force the DRAWN bit to on so that 16637 // this invalidate will go through (at least to our parent). 16638 // This is because someone may have invalidated this view 16639 // before this call to setFrame came in, thereby clearing 16640 // the DRAWN bit. 16641 mPrivateFlags |= PFLAG_DRAWN; 16642 invalidate(sizeChanged); 16643 // parent display list may need to be recreated based on a change in the bounds 16644 // of any child 16645 invalidateParentCaches(); 16646 } 16647 16648 // Reset drawn bit to original value (invalidate turns it off) 16649 mPrivateFlags |= drawn; 16650 16651 mBackgroundSizeChanged = true; 16652 if (mForegroundInfo != null) { 16653 mForegroundInfo.mBoundsChanged = true; 16654 } 16655 16656 notifySubtreeAccessibilityStateChangedIfNeeded(); 16657 } 16658 return changed; 16659 } 16660 16661 /** 16662 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 16663 * @hide 16664 */ 16665 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 16666 setFrame(left, top, right, bottom); 16667 } 16668 16669 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 16670 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 16671 if (mOverlay != null) { 16672 mOverlay.getOverlayView().setRight(newWidth); 16673 mOverlay.getOverlayView().setBottom(newHeight); 16674 } 16675 rebuildOutline(); 16676 } 16677 16678 /** 16679 * Finalize inflating a view from XML. This is called as the last phase 16680 * of inflation, after all child views have been added. 16681 * 16682 * <p>Even if the subclass overrides onFinishInflate, they should always be 16683 * sure to call the super method, so that we get called. 16684 */ 16685 @CallSuper 16686 protected void onFinishInflate() { 16687 } 16688 16689 /** 16690 * Returns the resources associated with this view. 16691 * 16692 * @return Resources object. 16693 */ 16694 public Resources getResources() { 16695 return mResources; 16696 } 16697 16698 /** 16699 * Invalidates the specified Drawable. 16700 * 16701 * @param drawable the drawable to invalidate 16702 */ 16703 @Override 16704 public void invalidateDrawable(@NonNull Drawable drawable) { 16705 if (verifyDrawable(drawable)) { 16706 final Rect dirty = drawable.getDirtyBounds(); 16707 final int scrollX = mScrollX; 16708 final int scrollY = mScrollY; 16709 16710 invalidate(dirty.left + scrollX, dirty.top + scrollY, 16711 dirty.right + scrollX, dirty.bottom + scrollY); 16712 rebuildOutline(); 16713 } 16714 } 16715 16716 /** 16717 * Schedules an action on a drawable to occur at a specified time. 16718 * 16719 * @param who the recipient of the action 16720 * @param what the action to run on the drawable 16721 * @param when the time at which the action must occur. Uses the 16722 * {@link SystemClock#uptimeMillis} timebase. 16723 */ 16724 @Override 16725 public void scheduleDrawable(Drawable who, Runnable what, long when) { 16726 if (verifyDrawable(who) && what != null) { 16727 final long delay = when - SystemClock.uptimeMillis(); 16728 if (mAttachInfo != null) { 16729 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 16730 Choreographer.CALLBACK_ANIMATION, what, who, 16731 Choreographer.subtractFrameDelay(delay)); 16732 } else { 16733 ViewRootImpl.getRunQueue().postDelayed(what, delay); 16734 } 16735 } 16736 } 16737 16738 /** 16739 * Cancels a scheduled action on a drawable. 16740 * 16741 * @param who the recipient of the action 16742 * @param what the action to cancel 16743 */ 16744 @Override 16745 public void unscheduleDrawable(Drawable who, Runnable what) { 16746 if (verifyDrawable(who) && what != null) { 16747 if (mAttachInfo != null) { 16748 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 16749 Choreographer.CALLBACK_ANIMATION, what, who); 16750 } 16751 ViewRootImpl.getRunQueue().removeCallbacks(what); 16752 } 16753 } 16754 16755 /** 16756 * Unschedule any events associated with the given Drawable. This can be 16757 * used when selecting a new Drawable into a view, so that the previous 16758 * one is completely unscheduled. 16759 * 16760 * @param who The Drawable to unschedule. 16761 * 16762 * @see #drawableStateChanged 16763 */ 16764 public void unscheduleDrawable(Drawable who) { 16765 if (mAttachInfo != null && who != null) { 16766 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 16767 Choreographer.CALLBACK_ANIMATION, null, who); 16768 } 16769 } 16770 16771 /** 16772 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 16773 * that the View directionality can and will be resolved before its Drawables. 16774 * 16775 * Will call {@link View#onResolveDrawables} when resolution is done. 16776 * 16777 * @hide 16778 */ 16779 protected void resolveDrawables() { 16780 // Drawables resolution may need to happen before resolving the layout direction (which is 16781 // done only during the measure() call). 16782 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 16783 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 16784 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 16785 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 16786 // direction to be resolved as its resolved value will be the same as its raw value. 16787 if (!isLayoutDirectionResolved() && 16788 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 16789 return; 16790 } 16791 16792 final int layoutDirection = isLayoutDirectionResolved() ? 16793 getLayoutDirection() : getRawLayoutDirection(); 16794 16795 if (mBackground != null) { 16796 mBackground.setLayoutDirection(layoutDirection); 16797 } 16798 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 16799 mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection); 16800 } 16801 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 16802 onResolveDrawables(layoutDirection); 16803 } 16804 16805 boolean areDrawablesResolved() { 16806 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 16807 } 16808 16809 /** 16810 * Called when layout direction has been resolved. 16811 * 16812 * The default implementation does nothing. 16813 * 16814 * @param layoutDirection The resolved layout direction. 16815 * 16816 * @see #LAYOUT_DIRECTION_LTR 16817 * @see #LAYOUT_DIRECTION_RTL 16818 * 16819 * @hide 16820 */ 16821 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 16822 } 16823 16824 /** 16825 * @hide 16826 */ 16827 protected void resetResolvedDrawables() { 16828 resetResolvedDrawablesInternal(); 16829 } 16830 16831 void resetResolvedDrawablesInternal() { 16832 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 16833 } 16834 16835 /** 16836 * If your view subclass is displaying its own Drawable objects, it should 16837 * override this function and return true for any Drawable it is 16838 * displaying. This allows animations for those drawables to be 16839 * scheduled. 16840 * 16841 * <p>Be sure to call through to the super class when overriding this 16842 * function. 16843 * 16844 * @param who The Drawable to verify. Return true if it is one you are 16845 * displaying, else return the result of calling through to the 16846 * super class. 16847 * 16848 * @return boolean If true than the Drawable is being displayed in the 16849 * view; else false and it is not allowed to animate. 16850 * 16851 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 16852 * @see #drawableStateChanged() 16853 */ 16854 @CallSuper 16855 protected boolean verifyDrawable(Drawable who) { 16856 return who == mBackground || (mScrollCache != null && mScrollCache.scrollBar == who) 16857 || (mForegroundInfo != null && mForegroundInfo.mDrawable == who); 16858 } 16859 16860 /** 16861 * This function is called whenever the state of the view changes in such 16862 * a way that it impacts the state of drawables being shown. 16863 * <p> 16864 * If the View has a StateListAnimator, it will also be called to run necessary state 16865 * change animations. 16866 * <p> 16867 * Be sure to call through to the superclass when overriding this function. 16868 * 16869 * @see Drawable#setState(int[]) 16870 */ 16871 @CallSuper 16872 protected void drawableStateChanged() { 16873 final int[] state = getDrawableState(); 16874 16875 final Drawable bg = mBackground; 16876 if (bg != null && bg.isStateful()) { 16877 bg.setState(state); 16878 } 16879 16880 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 16881 if (fg != null && fg.isStateful()) { 16882 fg.setState(state); 16883 } 16884 16885 if (mScrollCache != null) { 16886 final Drawable scrollBar = mScrollCache.scrollBar; 16887 if (scrollBar != null && scrollBar.isStateful()) { 16888 scrollBar.setState(state); 16889 } 16890 } 16891 16892 if (mStateListAnimator != null) { 16893 mStateListAnimator.setState(state); 16894 } 16895 } 16896 16897 /** 16898 * This function is called whenever the view hotspot changes and needs to 16899 * be propagated to drawables or child views managed by the view. 16900 * <p> 16901 * Dispatching to child views is handled by 16902 * {@link #dispatchDrawableHotspotChanged(float, float)}. 16903 * <p> 16904 * Be sure to call through to the superclass when overriding this function. 16905 * 16906 * @param x hotspot x coordinate 16907 * @param y hotspot y coordinate 16908 */ 16909 @CallSuper 16910 public void drawableHotspotChanged(float x, float y) { 16911 if (mBackground != null) { 16912 mBackground.setHotspot(x, y); 16913 } 16914 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 16915 mForegroundInfo.mDrawable.setHotspot(x, y); 16916 } 16917 16918 dispatchDrawableHotspotChanged(x, y); 16919 } 16920 16921 /** 16922 * Dispatches drawableHotspotChanged to all of this View's children. 16923 * 16924 * @param x hotspot x coordinate 16925 * @param y hotspot y coordinate 16926 * @see #drawableHotspotChanged(float, float) 16927 */ 16928 public void dispatchDrawableHotspotChanged(float x, float y) { 16929 } 16930 16931 /** 16932 * Call this to force a view to update its drawable state. This will cause 16933 * drawableStateChanged to be called on this view. Views that are interested 16934 * in the new state should call getDrawableState. 16935 * 16936 * @see #drawableStateChanged 16937 * @see #getDrawableState 16938 */ 16939 public void refreshDrawableState() { 16940 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 16941 drawableStateChanged(); 16942 16943 ViewParent parent = mParent; 16944 if (parent != null) { 16945 parent.childDrawableStateChanged(this); 16946 } 16947 } 16948 16949 /** 16950 * Return an array of resource IDs of the drawable states representing the 16951 * current state of the view. 16952 * 16953 * @return The current drawable state 16954 * 16955 * @see Drawable#setState(int[]) 16956 * @see #drawableStateChanged() 16957 * @see #onCreateDrawableState(int) 16958 */ 16959 public final int[] getDrawableState() { 16960 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 16961 return mDrawableState; 16962 } else { 16963 mDrawableState = onCreateDrawableState(0); 16964 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 16965 return mDrawableState; 16966 } 16967 } 16968 16969 /** 16970 * Generate the new {@link android.graphics.drawable.Drawable} state for 16971 * this view. This is called by the view 16972 * system when the cached Drawable state is determined to be invalid. To 16973 * retrieve the current state, you should use {@link #getDrawableState}. 16974 * 16975 * @param extraSpace if non-zero, this is the number of extra entries you 16976 * would like in the returned array in which you can place your own 16977 * states. 16978 * 16979 * @return Returns an array holding the current {@link Drawable} state of 16980 * the view. 16981 * 16982 * @see #mergeDrawableStates(int[], int[]) 16983 */ 16984 protected int[] onCreateDrawableState(int extraSpace) { 16985 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 16986 mParent instanceof View) { 16987 return ((View) mParent).onCreateDrawableState(extraSpace); 16988 } 16989 16990 int[] drawableState; 16991 16992 int privateFlags = mPrivateFlags; 16993 16994 int viewStateIndex = 0; 16995 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED; 16996 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED; 16997 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED; 16998 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED; 16999 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED; 17000 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED; 17001 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 17002 HardwareRenderer.isAvailable()) { 17003 // This is set if HW acceleration is requested, even if the current 17004 // process doesn't allow it. This is just to allow app preview 17005 // windows to better match their app. 17006 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED; 17007 } 17008 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED; 17009 17010 final int privateFlags2 = mPrivateFlags2; 17011 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) { 17012 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT; 17013 } 17014 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) { 17015 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED; 17016 } 17017 17018 drawableState = StateSet.get(viewStateIndex); 17019 17020 //noinspection ConstantIfStatement 17021 if (false) { 17022 Log.i("View", "drawableStateIndex=" + viewStateIndex); 17023 Log.i("View", toString() 17024 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 17025 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 17026 + " fo=" + hasFocus() 17027 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 17028 + " wf=" + hasWindowFocus() 17029 + ": " + Arrays.toString(drawableState)); 17030 } 17031 17032 if (extraSpace == 0) { 17033 return drawableState; 17034 } 17035 17036 final int[] fullState; 17037 if (drawableState != null) { 17038 fullState = new int[drawableState.length + extraSpace]; 17039 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 17040 } else { 17041 fullState = new int[extraSpace]; 17042 } 17043 17044 return fullState; 17045 } 17046 17047 /** 17048 * Merge your own state values in <var>additionalState</var> into the base 17049 * state values <var>baseState</var> that were returned by 17050 * {@link #onCreateDrawableState(int)}. 17051 * 17052 * @param baseState The base state values returned by 17053 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 17054 * own additional state values. 17055 * 17056 * @param additionalState The additional state values you would like 17057 * added to <var>baseState</var>; this array is not modified. 17058 * 17059 * @return As a convenience, the <var>baseState</var> array you originally 17060 * passed into the function is returned. 17061 * 17062 * @see #onCreateDrawableState(int) 17063 */ 17064 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 17065 final int N = baseState.length; 17066 int i = N - 1; 17067 while (i >= 0 && baseState[i] == 0) { 17068 i--; 17069 } 17070 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 17071 return baseState; 17072 } 17073 17074 /** 17075 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 17076 * on all Drawable objects associated with this view. 17077 * <p> 17078 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 17079 * attached to this view. 17080 */ 17081 public void jumpDrawablesToCurrentState() { 17082 if (mBackground != null) { 17083 mBackground.jumpToCurrentState(); 17084 } 17085 if (mStateListAnimator != null) { 17086 mStateListAnimator.jumpToCurrentState(); 17087 } 17088 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17089 mForegroundInfo.mDrawable.jumpToCurrentState(); 17090 } 17091 } 17092 17093 /** 17094 * Sets the background color for this view. 17095 * @param color the color of the background 17096 */ 17097 @RemotableViewMethod 17098 public void setBackgroundColor(@ColorInt int color) { 17099 if (mBackground instanceof ColorDrawable) { 17100 ((ColorDrawable) mBackground.mutate()).setColor(color); 17101 computeOpaqueFlags(); 17102 mBackgroundResource = 0; 17103 } else { 17104 setBackground(new ColorDrawable(color)); 17105 } 17106 } 17107 17108 /** 17109 * If the view has a ColorDrawable background, returns the color of that 17110 * drawable. 17111 * 17112 * @return The color of the ColorDrawable background, if set, otherwise 0. 17113 */ 17114 @ColorInt 17115 public int getBackgroundColor() { 17116 if (mBackground instanceof ColorDrawable) { 17117 return ((ColorDrawable) mBackground).getColor(); 17118 } 17119 return 0; 17120 } 17121 17122 /** 17123 * Set the background to a given resource. The resource should refer to 17124 * a Drawable object or 0 to remove the background. 17125 * @param resid The identifier of the resource. 17126 * 17127 * @attr ref android.R.styleable#View_background 17128 */ 17129 @RemotableViewMethod 17130 public void setBackgroundResource(@DrawableRes int resid) { 17131 if (resid != 0 && resid == mBackgroundResource) { 17132 return; 17133 } 17134 17135 Drawable d = null; 17136 if (resid != 0) { 17137 d = mContext.getDrawable(resid); 17138 } 17139 setBackground(d); 17140 17141 mBackgroundResource = resid; 17142 } 17143 17144 /** 17145 * Set the background to a given Drawable, or remove the background. If the 17146 * background has padding, this View's padding is set to the background's 17147 * padding. However, when a background is removed, this View's padding isn't 17148 * touched. If setting the padding is desired, please use 17149 * {@link #setPadding(int, int, int, int)}. 17150 * 17151 * @param background The Drawable to use as the background, or null to remove the 17152 * background 17153 */ 17154 public void setBackground(Drawable background) { 17155 //noinspection deprecation 17156 setBackgroundDrawable(background); 17157 } 17158 17159 /** 17160 * @deprecated use {@link #setBackground(Drawable)} instead 17161 */ 17162 @Deprecated 17163 public void setBackgroundDrawable(Drawable background) { 17164 computeOpaqueFlags(); 17165 17166 if (background == mBackground) { 17167 return; 17168 } 17169 17170 boolean requestLayout = false; 17171 17172 mBackgroundResource = 0; 17173 17174 /* 17175 * Regardless of whether we're setting a new background or not, we want 17176 * to clear the previous drawable. 17177 */ 17178 if (mBackground != null) { 17179 mBackground.setCallback(null); 17180 unscheduleDrawable(mBackground); 17181 } 17182 17183 if (background != null) { 17184 Rect padding = sThreadLocal.get(); 17185 if (padding == null) { 17186 padding = new Rect(); 17187 sThreadLocal.set(padding); 17188 } 17189 resetResolvedDrawablesInternal(); 17190 background.setLayoutDirection(getLayoutDirection()); 17191 if (background.getPadding(padding)) { 17192 resetResolvedPaddingInternal(); 17193 switch (background.getLayoutDirection()) { 17194 case LAYOUT_DIRECTION_RTL: 17195 mUserPaddingLeftInitial = padding.right; 17196 mUserPaddingRightInitial = padding.left; 17197 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 17198 break; 17199 case LAYOUT_DIRECTION_LTR: 17200 default: 17201 mUserPaddingLeftInitial = padding.left; 17202 mUserPaddingRightInitial = padding.right; 17203 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 17204 } 17205 mLeftPaddingDefined = false; 17206 mRightPaddingDefined = false; 17207 } 17208 17209 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 17210 // if it has a different minimum size, we should layout again 17211 if (mBackground == null 17212 || mBackground.getMinimumHeight() != background.getMinimumHeight() 17213 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 17214 requestLayout = true; 17215 } 17216 17217 background.setCallback(this); 17218 if (background.isStateful()) { 17219 background.setState(getDrawableState()); 17220 } 17221 background.setVisible(getVisibility() == VISIBLE, false); 17222 mBackground = background; 17223 17224 applyBackgroundTint(); 17225 17226 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 17227 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 17228 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 17229 requestLayout = true; 17230 } 17231 } else { 17232 /* Remove the background */ 17233 mBackground = null; 17234 17235 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 17236 /* 17237 * This view ONLY drew the background before and we're removing 17238 * the background, so now it won't draw anything 17239 * (hence we SKIP_DRAW) 17240 */ 17241 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 17242 mPrivateFlags |= PFLAG_SKIP_DRAW; 17243 } 17244 17245 /* 17246 * When the background is set, we try to apply its padding to this 17247 * View. When the background is removed, we don't touch this View's 17248 * padding. This is noted in the Javadocs. Hence, we don't need to 17249 * requestLayout(), the invalidate() below is sufficient. 17250 */ 17251 17252 // The old background's minimum size could have affected this 17253 // View's layout, so let's requestLayout 17254 requestLayout = true; 17255 } 17256 17257 computeOpaqueFlags(); 17258 17259 if (requestLayout) { 17260 requestLayout(); 17261 } 17262 17263 mBackgroundSizeChanged = true; 17264 invalidate(true); 17265 } 17266 17267 /** 17268 * Gets the background drawable 17269 * 17270 * @return The drawable used as the background for this view, if any. 17271 * 17272 * @see #setBackground(Drawable) 17273 * 17274 * @attr ref android.R.styleable#View_background 17275 */ 17276 public Drawable getBackground() { 17277 return mBackground; 17278 } 17279 17280 /** 17281 * Applies a tint to the background drawable. Does not modify the current tint 17282 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 17283 * <p> 17284 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 17285 * mutate the drawable and apply the specified tint and tint mode using 17286 * {@link Drawable#setTintList(ColorStateList)}. 17287 * 17288 * @param tint the tint to apply, may be {@code null} to clear tint 17289 * 17290 * @attr ref android.R.styleable#View_backgroundTint 17291 * @see #getBackgroundTintList() 17292 * @see Drawable#setTintList(ColorStateList) 17293 */ 17294 public void setBackgroundTintList(@Nullable ColorStateList tint) { 17295 if (mBackgroundTint == null) { 17296 mBackgroundTint = new TintInfo(); 17297 } 17298 mBackgroundTint.mTintList = tint; 17299 mBackgroundTint.mHasTintList = true; 17300 17301 applyBackgroundTint(); 17302 } 17303 17304 /** 17305 * Return the tint applied to the background drawable, if specified. 17306 * 17307 * @return the tint applied to the background drawable 17308 * @attr ref android.R.styleable#View_backgroundTint 17309 * @see #setBackgroundTintList(ColorStateList) 17310 */ 17311 @Nullable 17312 public ColorStateList getBackgroundTintList() { 17313 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 17314 } 17315 17316 /** 17317 * Specifies the blending mode used to apply the tint specified by 17318 * {@link #setBackgroundTintList(ColorStateList)}} to the background 17319 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 17320 * 17321 * @param tintMode the blending mode used to apply the tint, may be 17322 * {@code null} to clear tint 17323 * @attr ref android.R.styleable#View_backgroundTintMode 17324 * @see #getBackgroundTintMode() 17325 * @see Drawable#setTintMode(PorterDuff.Mode) 17326 */ 17327 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 17328 if (mBackgroundTint == null) { 17329 mBackgroundTint = new TintInfo(); 17330 } 17331 mBackgroundTint.mTintMode = tintMode; 17332 mBackgroundTint.mHasTintMode = true; 17333 17334 applyBackgroundTint(); 17335 } 17336 17337 /** 17338 * Return the blending mode used to apply the tint to the background 17339 * drawable, if specified. 17340 * 17341 * @return the blending mode used to apply the tint to the background 17342 * drawable 17343 * @attr ref android.R.styleable#View_backgroundTintMode 17344 * @see #setBackgroundTintMode(PorterDuff.Mode) 17345 */ 17346 @Nullable 17347 public PorterDuff.Mode getBackgroundTintMode() { 17348 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 17349 } 17350 17351 private void applyBackgroundTint() { 17352 if (mBackground != null && mBackgroundTint != null) { 17353 final TintInfo tintInfo = mBackgroundTint; 17354 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 17355 mBackground = mBackground.mutate(); 17356 17357 if (tintInfo.mHasTintList) { 17358 mBackground.setTintList(tintInfo.mTintList); 17359 } 17360 17361 if (tintInfo.mHasTintMode) { 17362 mBackground.setTintMode(tintInfo.mTintMode); 17363 } 17364 17365 // The drawable (or one of its children) may not have been 17366 // stateful before applying the tint, so let's try again. 17367 if (mBackground.isStateful()) { 17368 mBackground.setState(getDrawableState()); 17369 } 17370 } 17371 } 17372 } 17373 17374 /** 17375 * Returns the drawable used as the foreground of this View. The 17376 * foreground drawable, if non-null, is always drawn on top of the view's content. 17377 * 17378 * @return a Drawable or null if no foreground was set 17379 * 17380 * @see #onDrawForeground(Canvas) 17381 */ 17382 public Drawable getForeground() { 17383 return mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 17384 } 17385 17386 /** 17387 * Supply a Drawable that is to be rendered on top of all of the content in the view. 17388 * 17389 * @param foreground the Drawable to be drawn on top of the children 17390 * 17391 * @attr ref android.R.styleable#View_foreground 17392 */ 17393 public void setForeground(Drawable foreground) { 17394 if (mForegroundInfo == null) { 17395 if (foreground == null) { 17396 // Nothing to do. 17397 return; 17398 } 17399 mForegroundInfo = new ForegroundInfo(); 17400 } 17401 17402 if (foreground == mForegroundInfo.mDrawable) { 17403 // Nothing to do 17404 return; 17405 } 17406 17407 if (mForegroundInfo.mDrawable != null) { 17408 mForegroundInfo.mDrawable.setCallback(null); 17409 unscheduleDrawable(mForegroundInfo.mDrawable); 17410 } 17411 17412 mForegroundInfo.mDrawable = foreground; 17413 mForegroundInfo.mBoundsChanged = true; 17414 if (foreground != null) { 17415 setWillNotDraw(false); 17416 foreground.setCallback(this); 17417 foreground.setLayoutDirection(getLayoutDirection()); 17418 if (foreground.isStateful()) { 17419 foreground.setState(getDrawableState()); 17420 } 17421 applyForegroundTint(); 17422 } 17423 requestLayout(); 17424 invalidate(); 17425 } 17426 17427 /** 17428 * Magic bit used to support features of framework-internal window decor implementation details. 17429 * This used to live exclusively in FrameLayout. 17430 * 17431 * @return true if the foreground should draw inside the padding region or false 17432 * if it should draw inset by the view's padding 17433 * @hide internal use only; only used by FrameLayout and internal screen layouts. 17434 */ 17435 public boolean isForegroundInsidePadding() { 17436 return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true; 17437 } 17438 17439 /** 17440 * Describes how the foreground is positioned. 17441 * 17442 * @return foreground gravity. 17443 * 17444 * @see #setForegroundGravity(int) 17445 * 17446 * @attr ref android.R.styleable#View_foregroundGravity 17447 */ 17448 public int getForegroundGravity() { 17449 return mForegroundInfo != null ? mForegroundInfo.mGravity 17450 : Gravity.START | Gravity.TOP; 17451 } 17452 17453 /** 17454 * Describes how the foreground is positioned. Defaults to START and TOP. 17455 * 17456 * @param gravity see {@link android.view.Gravity} 17457 * 17458 * @see #getForegroundGravity() 17459 * 17460 * @attr ref android.R.styleable#View_foregroundGravity 17461 */ 17462 public void setForegroundGravity(int gravity) { 17463 if (mForegroundInfo == null) { 17464 mForegroundInfo = new ForegroundInfo(); 17465 } 17466 17467 if (mForegroundInfo.mGravity != gravity) { 17468 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 17469 gravity |= Gravity.START; 17470 } 17471 17472 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 17473 gravity |= Gravity.TOP; 17474 } 17475 17476 mForegroundInfo.mGravity = gravity; 17477 requestLayout(); 17478 } 17479 } 17480 17481 /** 17482 * Applies a tint to the foreground drawable. Does not modify the current tint 17483 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 17484 * <p> 17485 * Subsequent calls to {@link #setForeground(Drawable)} will automatically 17486 * mutate the drawable and apply the specified tint and tint mode using 17487 * {@link Drawable#setTintList(ColorStateList)}. 17488 * 17489 * @param tint the tint to apply, may be {@code null} to clear tint 17490 * 17491 * @attr ref android.R.styleable#View_foregroundTint 17492 * @see #getForegroundTintList() 17493 * @see Drawable#setTintList(ColorStateList) 17494 */ 17495 public void setForegroundTintList(@Nullable ColorStateList tint) { 17496 if (mForegroundInfo == null) { 17497 mForegroundInfo = new ForegroundInfo(); 17498 } 17499 if (mForegroundInfo.mTintInfo == null) { 17500 mForegroundInfo.mTintInfo = new TintInfo(); 17501 } 17502 mForegroundInfo.mTintInfo.mTintList = tint; 17503 mForegroundInfo.mTintInfo.mHasTintList = true; 17504 17505 applyForegroundTint(); 17506 } 17507 17508 /** 17509 * Return the tint applied to the foreground drawable, if specified. 17510 * 17511 * @return the tint applied to the foreground drawable 17512 * @attr ref android.R.styleable#View_foregroundTint 17513 * @see #setForegroundTintList(ColorStateList) 17514 */ 17515 @Nullable 17516 public ColorStateList getForegroundTintList() { 17517 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 17518 ? mForegroundInfo.mTintInfo.mTintList : null; 17519 } 17520 17521 /** 17522 * Specifies the blending mode used to apply the tint specified by 17523 * {@link #setForegroundTintList(ColorStateList)}} to the background 17524 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 17525 * 17526 * @param tintMode the blending mode used to apply the tint, may be 17527 * {@code null} to clear tint 17528 * @attr ref android.R.styleable#View_foregroundTintMode 17529 * @see #getForegroundTintMode() 17530 * @see Drawable#setTintMode(PorterDuff.Mode) 17531 */ 17532 public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) { 17533 if (mBackgroundTint == null) { 17534 mBackgroundTint = new TintInfo(); 17535 } 17536 mBackgroundTint.mTintMode = tintMode; 17537 mBackgroundTint.mHasTintMode = true; 17538 17539 applyBackgroundTint(); 17540 } 17541 17542 /** 17543 * Return the blending mode used to apply the tint to the foreground 17544 * drawable, if specified. 17545 * 17546 * @return the blending mode used to apply the tint to the foreground 17547 * drawable 17548 * @attr ref android.R.styleable#View_foregroundTintMode 17549 * @see #setBackgroundTintMode(PorterDuff.Mode) 17550 */ 17551 @Nullable 17552 public PorterDuff.Mode getForegroundTintMode() { 17553 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 17554 ? mForegroundInfo.mTintInfo.mTintMode : null; 17555 } 17556 17557 private void applyForegroundTint() { 17558 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 17559 && mForegroundInfo.mTintInfo != null) { 17560 final TintInfo tintInfo = mForegroundInfo.mTintInfo; 17561 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 17562 mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate(); 17563 17564 if (tintInfo.mHasTintList) { 17565 mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList); 17566 } 17567 17568 if (tintInfo.mHasTintMode) { 17569 mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode); 17570 } 17571 17572 // The drawable (or one of its children) may not have been 17573 // stateful before applying the tint, so let's try again. 17574 if (mForegroundInfo.mDrawable.isStateful()) { 17575 mForegroundInfo.mDrawable.setState(getDrawableState()); 17576 } 17577 } 17578 } 17579 } 17580 17581 /** 17582 * Draw any foreground content for this view. 17583 * 17584 * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground} 17585 * drawable or other view-specific decorations. The foreground is drawn on top of the 17586 * primary view content.</p> 17587 * 17588 * @param canvas canvas to draw into 17589 */ 17590 public void onDrawForeground(Canvas canvas) { 17591 onDrawScrollIndicators(canvas); 17592 onDrawScrollBars(canvas); 17593 17594 final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 17595 if (foreground != null) { 17596 if (mForegroundInfo.mBoundsChanged) { 17597 mForegroundInfo.mBoundsChanged = false; 17598 final Rect selfBounds = mForegroundInfo.mSelfBounds; 17599 final Rect overlayBounds = mForegroundInfo.mOverlayBounds; 17600 17601 if (mForegroundInfo.mInsidePadding) { 17602 selfBounds.set(0, 0, getWidth(), getHeight()); 17603 } else { 17604 selfBounds.set(getPaddingLeft(), getPaddingTop(), 17605 getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()); 17606 } 17607 17608 final int ld = getLayoutDirection(); 17609 Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(), 17610 foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld); 17611 foreground.setBounds(overlayBounds); 17612 } 17613 17614 foreground.draw(canvas); 17615 } 17616 } 17617 17618 /** 17619 * Sets the padding. The view may add on the space required to display 17620 * the scrollbars, depending on the style and visibility of the scrollbars. 17621 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 17622 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 17623 * from the values set in this call. 17624 * 17625 * @attr ref android.R.styleable#View_padding 17626 * @attr ref android.R.styleable#View_paddingBottom 17627 * @attr ref android.R.styleable#View_paddingLeft 17628 * @attr ref android.R.styleable#View_paddingRight 17629 * @attr ref android.R.styleable#View_paddingTop 17630 * @param left the left padding in pixels 17631 * @param top the top padding in pixels 17632 * @param right the right padding in pixels 17633 * @param bottom the bottom padding in pixels 17634 */ 17635 public void setPadding(int left, int top, int right, int bottom) { 17636 resetResolvedPaddingInternal(); 17637 17638 mUserPaddingStart = UNDEFINED_PADDING; 17639 mUserPaddingEnd = UNDEFINED_PADDING; 17640 17641 mUserPaddingLeftInitial = left; 17642 mUserPaddingRightInitial = right; 17643 17644 mLeftPaddingDefined = true; 17645 mRightPaddingDefined = true; 17646 17647 internalSetPadding(left, top, right, bottom); 17648 } 17649 17650 /** 17651 * @hide 17652 */ 17653 protected void internalSetPadding(int left, int top, int right, int bottom) { 17654 mUserPaddingLeft = left; 17655 mUserPaddingRight = right; 17656 mUserPaddingBottom = bottom; 17657 17658 final int viewFlags = mViewFlags; 17659 boolean changed = false; 17660 17661 // Common case is there are no scroll bars. 17662 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 17663 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 17664 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 17665 ? 0 : getVerticalScrollbarWidth(); 17666 switch (mVerticalScrollbarPosition) { 17667 case SCROLLBAR_POSITION_DEFAULT: 17668 if (isLayoutRtl()) { 17669 left += offset; 17670 } else { 17671 right += offset; 17672 } 17673 break; 17674 case SCROLLBAR_POSITION_RIGHT: 17675 right += offset; 17676 break; 17677 case SCROLLBAR_POSITION_LEFT: 17678 left += offset; 17679 break; 17680 } 17681 } 17682 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 17683 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 17684 ? 0 : getHorizontalScrollbarHeight(); 17685 } 17686 } 17687 17688 if (mPaddingLeft != left) { 17689 changed = true; 17690 mPaddingLeft = left; 17691 } 17692 if (mPaddingTop != top) { 17693 changed = true; 17694 mPaddingTop = top; 17695 } 17696 if (mPaddingRight != right) { 17697 changed = true; 17698 mPaddingRight = right; 17699 } 17700 if (mPaddingBottom != bottom) { 17701 changed = true; 17702 mPaddingBottom = bottom; 17703 } 17704 17705 if (changed) { 17706 requestLayout(); 17707 invalidateOutline(); 17708 } 17709 } 17710 17711 /** 17712 * Sets the relative padding. The view may add on the space required to display 17713 * the scrollbars, depending on the style and visibility of the scrollbars. 17714 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 17715 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 17716 * from the values set in this call. 17717 * 17718 * @attr ref android.R.styleable#View_padding 17719 * @attr ref android.R.styleable#View_paddingBottom 17720 * @attr ref android.R.styleable#View_paddingStart 17721 * @attr ref android.R.styleable#View_paddingEnd 17722 * @attr ref android.R.styleable#View_paddingTop 17723 * @param start the start padding in pixels 17724 * @param top the top padding in pixels 17725 * @param end the end padding in pixels 17726 * @param bottom the bottom padding in pixels 17727 */ 17728 public void setPaddingRelative(int start, int top, int end, int bottom) { 17729 resetResolvedPaddingInternal(); 17730 17731 mUserPaddingStart = start; 17732 mUserPaddingEnd = end; 17733 mLeftPaddingDefined = true; 17734 mRightPaddingDefined = true; 17735 17736 switch(getLayoutDirection()) { 17737 case LAYOUT_DIRECTION_RTL: 17738 mUserPaddingLeftInitial = end; 17739 mUserPaddingRightInitial = start; 17740 internalSetPadding(end, top, start, bottom); 17741 break; 17742 case LAYOUT_DIRECTION_LTR: 17743 default: 17744 mUserPaddingLeftInitial = start; 17745 mUserPaddingRightInitial = end; 17746 internalSetPadding(start, top, end, bottom); 17747 } 17748 } 17749 17750 /** 17751 * Returns the top padding of this view. 17752 * 17753 * @return the top padding in pixels 17754 */ 17755 public int getPaddingTop() { 17756 return mPaddingTop; 17757 } 17758 17759 /** 17760 * Returns the bottom padding of this view. If there are inset and enabled 17761 * scrollbars, this value may include the space required to display the 17762 * scrollbars as well. 17763 * 17764 * @return the bottom padding in pixels 17765 */ 17766 public int getPaddingBottom() { 17767 return mPaddingBottom; 17768 } 17769 17770 /** 17771 * Returns the left padding of this view. If there are inset and enabled 17772 * scrollbars, this value may include the space required to display the 17773 * scrollbars as well. 17774 * 17775 * @return the left padding in pixels 17776 */ 17777 public int getPaddingLeft() { 17778 if (!isPaddingResolved()) { 17779 resolvePadding(); 17780 } 17781 return mPaddingLeft; 17782 } 17783 17784 /** 17785 * Returns the start padding of this view depending on its resolved layout direction. 17786 * If there are inset and enabled scrollbars, this value may include the space 17787 * required to display the scrollbars as well. 17788 * 17789 * @return the start padding in pixels 17790 */ 17791 public int getPaddingStart() { 17792 if (!isPaddingResolved()) { 17793 resolvePadding(); 17794 } 17795 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 17796 mPaddingRight : mPaddingLeft; 17797 } 17798 17799 /** 17800 * Returns the right padding of this view. If there are inset and enabled 17801 * scrollbars, this value may include the space required to display the 17802 * scrollbars as well. 17803 * 17804 * @return the right padding in pixels 17805 */ 17806 public int getPaddingRight() { 17807 if (!isPaddingResolved()) { 17808 resolvePadding(); 17809 } 17810 return mPaddingRight; 17811 } 17812 17813 /** 17814 * Returns the end padding of this view depending on its resolved layout direction. 17815 * If there are inset and enabled scrollbars, this value may include the space 17816 * required to display the scrollbars as well. 17817 * 17818 * @return the end padding in pixels 17819 */ 17820 public int getPaddingEnd() { 17821 if (!isPaddingResolved()) { 17822 resolvePadding(); 17823 } 17824 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 17825 mPaddingLeft : mPaddingRight; 17826 } 17827 17828 /** 17829 * Return if the padding has been set through relative values 17830 * {@link #setPaddingRelative(int, int, int, int)} or through 17831 * @attr ref android.R.styleable#View_paddingStart or 17832 * @attr ref android.R.styleable#View_paddingEnd 17833 * 17834 * @return true if the padding is relative or false if it is not. 17835 */ 17836 public boolean isPaddingRelative() { 17837 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 17838 } 17839 17840 Insets computeOpticalInsets() { 17841 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 17842 } 17843 17844 /** 17845 * @hide 17846 */ 17847 public void resetPaddingToInitialValues() { 17848 if (isRtlCompatibilityMode()) { 17849 mPaddingLeft = mUserPaddingLeftInitial; 17850 mPaddingRight = mUserPaddingRightInitial; 17851 return; 17852 } 17853 if (isLayoutRtl()) { 17854 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 17855 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 17856 } else { 17857 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 17858 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 17859 } 17860 } 17861 17862 /** 17863 * @hide 17864 */ 17865 public Insets getOpticalInsets() { 17866 if (mLayoutInsets == null) { 17867 mLayoutInsets = computeOpticalInsets(); 17868 } 17869 return mLayoutInsets; 17870 } 17871 17872 /** 17873 * Set this view's optical insets. 17874 * 17875 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 17876 * property. Views that compute their own optical insets should call it as part of measurement. 17877 * This method does not request layout. If you are setting optical insets outside of 17878 * measure/layout itself you will want to call requestLayout() yourself. 17879 * </p> 17880 * @hide 17881 */ 17882 public void setOpticalInsets(Insets insets) { 17883 mLayoutInsets = insets; 17884 } 17885 17886 /** 17887 * Changes the selection state of this view. A view can be selected or not. 17888 * Note that selection is not the same as focus. Views are typically 17889 * selected in the context of an AdapterView like ListView or GridView; 17890 * the selected view is the view that is highlighted. 17891 * 17892 * @param selected true if the view must be selected, false otherwise 17893 */ 17894 public void setSelected(boolean selected) { 17895 //noinspection DoubleNegation 17896 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 17897 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 17898 if (!selected) resetPressedState(); 17899 invalidate(true); 17900 refreshDrawableState(); 17901 dispatchSetSelected(selected); 17902 if (selected) { 17903 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 17904 } else { 17905 notifyViewAccessibilityStateChangedIfNeeded( 17906 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 17907 } 17908 } 17909 } 17910 17911 /** 17912 * Dispatch setSelected to all of this View's children. 17913 * 17914 * @see #setSelected(boolean) 17915 * 17916 * @param selected The new selected state 17917 */ 17918 protected void dispatchSetSelected(boolean selected) { 17919 } 17920 17921 /** 17922 * Indicates the selection state of this view. 17923 * 17924 * @return true if the view is selected, false otherwise 17925 */ 17926 @ViewDebug.ExportedProperty 17927 public boolean isSelected() { 17928 return (mPrivateFlags & PFLAG_SELECTED) != 0; 17929 } 17930 17931 /** 17932 * Changes the activated state of this view. A view can be activated or not. 17933 * Note that activation is not the same as selection. Selection is 17934 * a transient property, representing the view (hierarchy) the user is 17935 * currently interacting with. Activation is a longer-term state that the 17936 * user can move views in and out of. For example, in a list view with 17937 * single or multiple selection enabled, the views in the current selection 17938 * set are activated. (Um, yeah, we are deeply sorry about the terminology 17939 * here.) The activated state is propagated down to children of the view it 17940 * is set on. 17941 * 17942 * @param activated true if the view must be activated, false otherwise 17943 */ 17944 public void setActivated(boolean activated) { 17945 //noinspection DoubleNegation 17946 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 17947 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 17948 invalidate(true); 17949 refreshDrawableState(); 17950 dispatchSetActivated(activated); 17951 } 17952 } 17953 17954 /** 17955 * Dispatch setActivated to all of this View's children. 17956 * 17957 * @see #setActivated(boolean) 17958 * 17959 * @param activated The new activated state 17960 */ 17961 protected void dispatchSetActivated(boolean activated) { 17962 } 17963 17964 /** 17965 * Indicates the activation state of this view. 17966 * 17967 * @return true if the view is activated, false otherwise 17968 */ 17969 @ViewDebug.ExportedProperty 17970 public boolean isActivated() { 17971 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 17972 } 17973 17974 /** 17975 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 17976 * observer can be used to get notifications when global events, like 17977 * layout, happen. 17978 * 17979 * The returned ViewTreeObserver observer is not guaranteed to remain 17980 * valid for the lifetime of this View. If the caller of this method keeps 17981 * a long-lived reference to ViewTreeObserver, it should always check for 17982 * the return value of {@link ViewTreeObserver#isAlive()}. 17983 * 17984 * @return The ViewTreeObserver for this view's hierarchy. 17985 */ 17986 public ViewTreeObserver getViewTreeObserver() { 17987 if (mAttachInfo != null) { 17988 return mAttachInfo.mTreeObserver; 17989 } 17990 if (mFloatingTreeObserver == null) { 17991 mFloatingTreeObserver = new ViewTreeObserver(); 17992 } 17993 return mFloatingTreeObserver; 17994 } 17995 17996 /** 17997 * <p>Finds the topmost view in the current view hierarchy.</p> 17998 * 17999 * @return the topmost view containing this view 18000 */ 18001 public View getRootView() { 18002 if (mAttachInfo != null) { 18003 final View v = mAttachInfo.mRootView; 18004 if (v != null) { 18005 return v; 18006 } 18007 } 18008 18009 View parent = this; 18010 18011 while (parent.mParent != null && parent.mParent instanceof View) { 18012 parent = (View) parent.mParent; 18013 } 18014 18015 return parent; 18016 } 18017 18018 /** 18019 * Transforms a motion event from view-local coordinates to on-screen 18020 * coordinates. 18021 * 18022 * @param ev the view-local motion event 18023 * @return false if the transformation could not be applied 18024 * @hide 18025 */ 18026 public boolean toGlobalMotionEvent(MotionEvent ev) { 18027 final AttachInfo info = mAttachInfo; 18028 if (info == null) { 18029 return false; 18030 } 18031 18032 final Matrix m = info.mTmpMatrix; 18033 m.set(Matrix.IDENTITY_MATRIX); 18034 transformMatrixToGlobal(m); 18035 ev.transform(m); 18036 return true; 18037 } 18038 18039 /** 18040 * Transforms a motion event from on-screen coordinates to view-local 18041 * coordinates. 18042 * 18043 * @param ev the on-screen motion event 18044 * @return false if the transformation could not be applied 18045 * @hide 18046 */ 18047 public boolean toLocalMotionEvent(MotionEvent ev) { 18048 final AttachInfo info = mAttachInfo; 18049 if (info == null) { 18050 return false; 18051 } 18052 18053 final Matrix m = info.mTmpMatrix; 18054 m.set(Matrix.IDENTITY_MATRIX); 18055 transformMatrixToLocal(m); 18056 ev.transform(m); 18057 return true; 18058 } 18059 18060 /** 18061 * Modifies the input matrix such that it maps view-local coordinates to 18062 * on-screen coordinates. 18063 * 18064 * @param m input matrix to modify 18065 * @hide 18066 */ 18067 public void transformMatrixToGlobal(Matrix m) { 18068 final ViewParent parent = mParent; 18069 if (parent instanceof View) { 18070 final View vp = (View) parent; 18071 vp.transformMatrixToGlobal(m); 18072 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 18073 } else if (parent instanceof ViewRootImpl) { 18074 final ViewRootImpl vr = (ViewRootImpl) parent; 18075 vr.transformMatrixToGlobal(m); 18076 m.preTranslate(0, -vr.mCurScrollY); 18077 } 18078 18079 m.preTranslate(mLeft, mTop); 18080 18081 if (!hasIdentityMatrix()) { 18082 m.preConcat(getMatrix()); 18083 } 18084 } 18085 18086 /** 18087 * Modifies the input matrix such that it maps on-screen coordinates to 18088 * view-local coordinates. 18089 * 18090 * @param m input matrix to modify 18091 * @hide 18092 */ 18093 public void transformMatrixToLocal(Matrix m) { 18094 final ViewParent parent = mParent; 18095 if (parent instanceof View) { 18096 final View vp = (View) parent; 18097 vp.transformMatrixToLocal(m); 18098 m.postTranslate(vp.mScrollX, vp.mScrollY); 18099 } else if (parent instanceof ViewRootImpl) { 18100 final ViewRootImpl vr = (ViewRootImpl) parent; 18101 vr.transformMatrixToLocal(m); 18102 m.postTranslate(0, vr.mCurScrollY); 18103 } 18104 18105 m.postTranslate(-mLeft, -mTop); 18106 18107 if (!hasIdentityMatrix()) { 18108 m.postConcat(getInverseMatrix()); 18109 } 18110 } 18111 18112 /** 18113 * @hide 18114 */ 18115 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 18116 @ViewDebug.IntToString(from = 0, to = "x"), 18117 @ViewDebug.IntToString(from = 1, to = "y") 18118 }) 18119 public int[] getLocationOnScreen() { 18120 int[] location = new int[2]; 18121 getLocationOnScreen(location); 18122 return location; 18123 } 18124 18125 /** 18126 * <p>Computes the coordinates of this view on the screen. The argument 18127 * must be an array of two integers. After the method returns, the array 18128 * contains the x and y location in that order.</p> 18129 * 18130 * @param location an array of two integers in which to hold the coordinates 18131 */ 18132 public void getLocationOnScreen(@Size(2) int[] location) { 18133 getLocationInWindow(location); 18134 18135 final AttachInfo info = mAttachInfo; 18136 if (info != null) { 18137 location[0] += info.mWindowLeft; 18138 location[1] += info.mWindowTop; 18139 } 18140 } 18141 18142 /** 18143 * <p>Computes the coordinates of this view in its window. The argument 18144 * must be an array of two integers. After the method returns, the array 18145 * contains the x and y location in that order.</p> 18146 * 18147 * @param location an array of two integers in which to hold the coordinates 18148 */ 18149 public void getLocationInWindow(@Size(2) int[] location) { 18150 if (location == null || location.length < 2) { 18151 throw new IllegalArgumentException("location must be an array of two integers"); 18152 } 18153 18154 if (mAttachInfo == null) { 18155 // When the view is not attached to a window, this method does not make sense 18156 location[0] = location[1] = 0; 18157 return; 18158 } 18159 18160 float[] position = mAttachInfo.mTmpTransformLocation; 18161 position[0] = position[1] = 0.0f; 18162 18163 if (!hasIdentityMatrix()) { 18164 getMatrix().mapPoints(position); 18165 } 18166 18167 position[0] += mLeft; 18168 position[1] += mTop; 18169 18170 ViewParent viewParent = mParent; 18171 while (viewParent instanceof View) { 18172 final View view = (View) viewParent; 18173 18174 position[0] -= view.mScrollX; 18175 position[1] -= view.mScrollY; 18176 18177 if (!view.hasIdentityMatrix()) { 18178 view.getMatrix().mapPoints(position); 18179 } 18180 18181 position[0] += view.mLeft; 18182 position[1] += view.mTop; 18183 18184 viewParent = view.mParent; 18185 } 18186 18187 if (viewParent instanceof ViewRootImpl) { 18188 // *cough* 18189 final ViewRootImpl vr = (ViewRootImpl) viewParent; 18190 position[1] -= vr.mCurScrollY; 18191 } 18192 18193 location[0] = (int) (position[0] + 0.5f); 18194 location[1] = (int) (position[1] + 0.5f); 18195 } 18196 18197 /** 18198 * {@hide} 18199 * @param id the id of the view to be found 18200 * @return the view of the specified id, null if cannot be found 18201 */ 18202 protected View findViewTraversal(@IdRes int id) { 18203 if (id == mID) { 18204 return this; 18205 } 18206 return null; 18207 } 18208 18209 /** 18210 * {@hide} 18211 * @param tag the tag of the view to be found 18212 * @return the view of specified tag, null if cannot be found 18213 */ 18214 protected View findViewWithTagTraversal(Object tag) { 18215 if (tag != null && tag.equals(mTag)) { 18216 return this; 18217 } 18218 return null; 18219 } 18220 18221 /** 18222 * {@hide} 18223 * @param predicate The predicate to evaluate. 18224 * @param childToSkip If not null, ignores this child during the recursive traversal. 18225 * @return The first view that matches the predicate or null. 18226 */ 18227 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 18228 if (predicate.apply(this)) { 18229 return this; 18230 } 18231 return null; 18232 } 18233 18234 /** 18235 * Look for a child view with the given id. If this view has the given 18236 * id, return this view. 18237 * 18238 * @param id The id to search for. 18239 * @return The view that has the given id in the hierarchy or null 18240 */ 18241 @Nullable 18242 public final View findViewById(@IdRes int id) { 18243 if (id < 0) { 18244 return null; 18245 } 18246 return findViewTraversal(id); 18247 } 18248 18249 /** 18250 * Finds a view by its unuque and stable accessibility id. 18251 * 18252 * @param accessibilityId The searched accessibility id. 18253 * @return The found view. 18254 */ 18255 final View findViewByAccessibilityId(int accessibilityId) { 18256 if (accessibilityId < 0) { 18257 return null; 18258 } 18259 return findViewByAccessibilityIdTraversal(accessibilityId); 18260 } 18261 18262 /** 18263 * Performs the traversal to find a view by its unuque and stable accessibility id. 18264 * 18265 * <strong>Note:</strong>This method does not stop at the root namespace 18266 * boundary since the user can touch the screen at an arbitrary location 18267 * potentially crossing the root namespace bounday which will send an 18268 * accessibility event to accessibility services and they should be able 18269 * to obtain the event source. Also accessibility ids are guaranteed to be 18270 * unique in the window. 18271 * 18272 * @param accessibilityId The accessibility id. 18273 * @return The found view. 18274 * 18275 * @hide 18276 */ 18277 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 18278 if (getAccessibilityViewId() == accessibilityId) { 18279 return this; 18280 } 18281 return null; 18282 } 18283 18284 /** 18285 * Look for a child view with the given tag. If this view has the given 18286 * tag, return this view. 18287 * 18288 * @param tag The tag to search for, using "tag.equals(getTag())". 18289 * @return The View that has the given tag in the hierarchy or null 18290 */ 18291 public final View findViewWithTag(Object tag) { 18292 if (tag == null) { 18293 return null; 18294 } 18295 return findViewWithTagTraversal(tag); 18296 } 18297 18298 /** 18299 * {@hide} 18300 * Look for a child view that matches the specified predicate. 18301 * If this view matches the predicate, return this view. 18302 * 18303 * @param predicate The predicate to evaluate. 18304 * @return The first view that matches the predicate or null. 18305 */ 18306 public final View findViewByPredicate(Predicate<View> predicate) { 18307 return findViewByPredicateTraversal(predicate, null); 18308 } 18309 18310 /** 18311 * {@hide} 18312 * Look for a child view that matches the specified predicate, 18313 * starting with the specified view and its descendents and then 18314 * recusively searching the ancestors and siblings of that view 18315 * until this view is reached. 18316 * 18317 * This method is useful in cases where the predicate does not match 18318 * a single unique view (perhaps multiple views use the same id) 18319 * and we are trying to find the view that is "closest" in scope to the 18320 * starting view. 18321 * 18322 * @param start The view to start from. 18323 * @param predicate The predicate to evaluate. 18324 * @return The first view that matches the predicate or null. 18325 */ 18326 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 18327 View childToSkip = null; 18328 for (;;) { 18329 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 18330 if (view != null || start == this) { 18331 return view; 18332 } 18333 18334 ViewParent parent = start.getParent(); 18335 if (parent == null || !(parent instanceof View)) { 18336 return null; 18337 } 18338 18339 childToSkip = start; 18340 start = (View) parent; 18341 } 18342 } 18343 18344 /** 18345 * Sets the identifier for this view. The identifier does not have to be 18346 * unique in this view's hierarchy. The identifier should be a positive 18347 * number. 18348 * 18349 * @see #NO_ID 18350 * @see #getId() 18351 * @see #findViewById(int) 18352 * 18353 * @param id a number used to identify the view 18354 * 18355 * @attr ref android.R.styleable#View_id 18356 */ 18357 public void setId(@IdRes int id) { 18358 mID = id; 18359 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 18360 mID = generateViewId(); 18361 } 18362 } 18363 18364 /** 18365 * {@hide} 18366 * 18367 * @param isRoot true if the view belongs to the root namespace, false 18368 * otherwise 18369 */ 18370 public void setIsRootNamespace(boolean isRoot) { 18371 if (isRoot) { 18372 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 18373 } else { 18374 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 18375 } 18376 } 18377 18378 /** 18379 * {@hide} 18380 * 18381 * @return true if the view belongs to the root namespace, false otherwise 18382 */ 18383 public boolean isRootNamespace() { 18384 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 18385 } 18386 18387 /** 18388 * Returns this view's identifier. 18389 * 18390 * @return a positive integer used to identify the view or {@link #NO_ID} 18391 * if the view has no ID 18392 * 18393 * @see #setId(int) 18394 * @see #findViewById(int) 18395 * @attr ref android.R.styleable#View_id 18396 */ 18397 @IdRes 18398 @ViewDebug.CapturedViewProperty 18399 public int getId() { 18400 return mID; 18401 } 18402 18403 /** 18404 * Returns this view's tag. 18405 * 18406 * @return the Object stored in this view as a tag, or {@code null} if not 18407 * set 18408 * 18409 * @see #setTag(Object) 18410 * @see #getTag(int) 18411 */ 18412 @ViewDebug.ExportedProperty 18413 public Object getTag() { 18414 return mTag; 18415 } 18416 18417 /** 18418 * Sets the tag associated with this view. A tag can be used to mark 18419 * a view in its hierarchy and does not have to be unique within the 18420 * hierarchy. Tags can also be used to store data within a view without 18421 * resorting to another data structure. 18422 * 18423 * @param tag an Object to tag the view with 18424 * 18425 * @see #getTag() 18426 * @see #setTag(int, Object) 18427 */ 18428 public void setTag(final Object tag) { 18429 mTag = tag; 18430 } 18431 18432 /** 18433 * Returns the tag associated with this view and the specified key. 18434 * 18435 * @param key The key identifying the tag 18436 * 18437 * @return the Object stored in this view as a tag, or {@code null} if not 18438 * set 18439 * 18440 * @see #setTag(int, Object) 18441 * @see #getTag() 18442 */ 18443 public Object getTag(int key) { 18444 if (mKeyedTags != null) return mKeyedTags.get(key); 18445 return null; 18446 } 18447 18448 /** 18449 * Sets a tag associated with this view and a key. A tag can be used 18450 * to mark a view in its hierarchy and does not have to be unique within 18451 * the hierarchy. Tags can also be used to store data within a view 18452 * without resorting to another data structure. 18453 * 18454 * The specified key should be an id declared in the resources of the 18455 * application to ensure it is unique (see the <a 18456 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 18457 * Keys identified as belonging to 18458 * the Android framework or not associated with any package will cause 18459 * an {@link IllegalArgumentException} to be thrown. 18460 * 18461 * @param key The key identifying the tag 18462 * @param tag An Object to tag the view with 18463 * 18464 * @throws IllegalArgumentException If they specified key is not valid 18465 * 18466 * @see #setTag(Object) 18467 * @see #getTag(int) 18468 */ 18469 public void setTag(int key, final Object tag) { 18470 // If the package id is 0x00 or 0x01, it's either an undefined package 18471 // or a framework id 18472 if ((key >>> 24) < 2) { 18473 throw new IllegalArgumentException("The key must be an application-specific " 18474 + "resource id."); 18475 } 18476 18477 setKeyedTag(key, tag); 18478 } 18479 18480 /** 18481 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 18482 * framework id. 18483 * 18484 * @hide 18485 */ 18486 public void setTagInternal(int key, Object tag) { 18487 if ((key >>> 24) != 0x1) { 18488 throw new IllegalArgumentException("The key must be a framework-specific " 18489 + "resource id."); 18490 } 18491 18492 setKeyedTag(key, tag); 18493 } 18494 18495 private void setKeyedTag(int key, Object tag) { 18496 if (mKeyedTags == null) { 18497 mKeyedTags = new SparseArray<Object>(2); 18498 } 18499 18500 mKeyedTags.put(key, tag); 18501 } 18502 18503 /** 18504 * Prints information about this view in the log output, with the tag 18505 * {@link #VIEW_LOG_TAG}. 18506 * 18507 * @hide 18508 */ 18509 public void debug() { 18510 debug(0); 18511 } 18512 18513 /** 18514 * Prints information about this view in the log output, with the tag 18515 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 18516 * indentation defined by the <code>depth</code>. 18517 * 18518 * @param depth the indentation level 18519 * 18520 * @hide 18521 */ 18522 protected void debug(int depth) { 18523 String output = debugIndent(depth - 1); 18524 18525 output += "+ " + this; 18526 int id = getId(); 18527 if (id != -1) { 18528 output += " (id=" + id + ")"; 18529 } 18530 Object tag = getTag(); 18531 if (tag != null) { 18532 output += " (tag=" + tag + ")"; 18533 } 18534 Log.d(VIEW_LOG_TAG, output); 18535 18536 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 18537 output = debugIndent(depth) + " FOCUSED"; 18538 Log.d(VIEW_LOG_TAG, output); 18539 } 18540 18541 output = debugIndent(depth); 18542 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 18543 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 18544 + "} "; 18545 Log.d(VIEW_LOG_TAG, output); 18546 18547 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 18548 || mPaddingBottom != 0) { 18549 output = debugIndent(depth); 18550 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 18551 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 18552 Log.d(VIEW_LOG_TAG, output); 18553 } 18554 18555 output = debugIndent(depth); 18556 output += "mMeasureWidth=" + mMeasuredWidth + 18557 " mMeasureHeight=" + mMeasuredHeight; 18558 Log.d(VIEW_LOG_TAG, output); 18559 18560 output = debugIndent(depth); 18561 if (mLayoutParams == null) { 18562 output += "BAD! no layout params"; 18563 } else { 18564 output = mLayoutParams.debug(output); 18565 } 18566 Log.d(VIEW_LOG_TAG, output); 18567 18568 output = debugIndent(depth); 18569 output += "flags={"; 18570 output += View.printFlags(mViewFlags); 18571 output += "}"; 18572 Log.d(VIEW_LOG_TAG, output); 18573 18574 output = debugIndent(depth); 18575 output += "privateFlags={"; 18576 output += View.printPrivateFlags(mPrivateFlags); 18577 output += "}"; 18578 Log.d(VIEW_LOG_TAG, output); 18579 } 18580 18581 /** 18582 * Creates a string of whitespaces used for indentation. 18583 * 18584 * @param depth the indentation level 18585 * @return a String containing (depth * 2 + 3) * 2 white spaces 18586 * 18587 * @hide 18588 */ 18589 protected static String debugIndent(int depth) { 18590 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 18591 for (int i = 0; i < (depth * 2) + 3; i++) { 18592 spaces.append(' ').append(' '); 18593 } 18594 return spaces.toString(); 18595 } 18596 18597 /** 18598 * <p>Return the offset of the widget's text baseline from the widget's top 18599 * boundary. If this widget does not support baseline alignment, this 18600 * method returns -1. </p> 18601 * 18602 * @return the offset of the baseline within the widget's bounds or -1 18603 * if baseline alignment is not supported 18604 */ 18605 @ViewDebug.ExportedProperty(category = "layout") 18606 public int getBaseline() { 18607 return -1; 18608 } 18609 18610 /** 18611 * Returns whether the view hierarchy is currently undergoing a layout pass. This 18612 * information is useful to avoid situations such as calling {@link #requestLayout()} during 18613 * a layout pass. 18614 * 18615 * @return whether the view hierarchy is currently undergoing a layout pass 18616 */ 18617 public boolean isInLayout() { 18618 ViewRootImpl viewRoot = getViewRootImpl(); 18619 return (viewRoot != null && viewRoot.isInLayout()); 18620 } 18621 18622 /** 18623 * Call this when something has changed which has invalidated the 18624 * layout of this view. This will schedule a layout pass of the view 18625 * tree. This should not be called while the view hierarchy is currently in a layout 18626 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 18627 * end of the current layout pass (and then layout will run again) or after the current 18628 * frame is drawn and the next layout occurs. 18629 * 18630 * <p>Subclasses which override this method should call the superclass method to 18631 * handle possible request-during-layout errors correctly.</p> 18632 */ 18633 @CallSuper 18634 public void requestLayout() { 18635 if (mMeasureCache != null) mMeasureCache.clear(); 18636 18637 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 18638 // Only trigger request-during-layout logic if this is the view requesting it, 18639 // not the views in its parent hierarchy 18640 ViewRootImpl viewRoot = getViewRootImpl(); 18641 if (viewRoot != null && viewRoot.isInLayout()) { 18642 if (!viewRoot.requestLayoutDuringLayout(this)) { 18643 return; 18644 } 18645 } 18646 mAttachInfo.mViewRequestingLayout = this; 18647 } 18648 18649 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 18650 mPrivateFlags |= PFLAG_INVALIDATED; 18651 18652 if (mParent != null && !mParent.isLayoutRequested()) { 18653 mParent.requestLayout(); 18654 } 18655 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 18656 mAttachInfo.mViewRequestingLayout = null; 18657 } 18658 } 18659 18660 /** 18661 * Forces this view to be laid out during the next layout pass. 18662 * This method does not call requestLayout() or forceLayout() 18663 * on the parent. 18664 */ 18665 public void forceLayout() { 18666 if (mMeasureCache != null) mMeasureCache.clear(); 18667 18668 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 18669 mPrivateFlags |= PFLAG_INVALIDATED; 18670 } 18671 18672 /** 18673 * <p> 18674 * This is called to find out how big a view should be. The parent 18675 * supplies constraint information in the width and height parameters. 18676 * </p> 18677 * 18678 * <p> 18679 * The actual measurement work of a view is performed in 18680 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 18681 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 18682 * </p> 18683 * 18684 * 18685 * @param widthMeasureSpec Horizontal space requirements as imposed by the 18686 * parent 18687 * @param heightMeasureSpec Vertical space requirements as imposed by the 18688 * parent 18689 * 18690 * @see #onMeasure(int, int) 18691 */ 18692 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 18693 boolean optical = isLayoutModeOptical(this); 18694 if (optical != isLayoutModeOptical(mParent)) { 18695 Insets insets = getOpticalInsets(); 18696 int oWidth = insets.left + insets.right; 18697 int oHeight = insets.top + insets.bottom; 18698 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 18699 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 18700 } 18701 18702 // Suppress sign extension for the low bytes 18703 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 18704 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 18705 18706 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 18707 final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY && 18708 MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 18709 final boolean matchingSize = isExactly && 18710 getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) && 18711 getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 18712 if (forceLayout || !matchingSize && 18713 (widthMeasureSpec != mOldWidthMeasureSpec || 18714 heightMeasureSpec != mOldHeightMeasureSpec)) { 18715 18716 // first clears the measured dimension flag 18717 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 18718 18719 resolveRtlPropertiesIfNeeded(); 18720 18721 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 18722 if (cacheIndex < 0 || sIgnoreMeasureCache) { 18723 // measure ourselves, this should set the measured dimension flag back 18724 onMeasure(widthMeasureSpec, heightMeasureSpec); 18725 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 18726 } else { 18727 long value = mMeasureCache.valueAt(cacheIndex); 18728 // Casting a long to int drops the high 32 bits, no mask needed 18729 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 18730 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 18731 } 18732 18733 // flag not set, setMeasuredDimension() was not invoked, we raise 18734 // an exception to warn the developer 18735 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 18736 throw new IllegalStateException("View with id " + getId() + ": " 18737 + getClass().getName() + "#onMeasure() did not set the" 18738 + " measured dimension by calling" 18739 + " setMeasuredDimension()"); 18740 } 18741 18742 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 18743 } 18744 18745 mOldWidthMeasureSpec = widthMeasureSpec; 18746 mOldHeightMeasureSpec = heightMeasureSpec; 18747 18748 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 18749 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 18750 } 18751 18752 /** 18753 * <p> 18754 * Measure the view and its content to determine the measured width and the 18755 * measured height. This method is invoked by {@link #measure(int, int)} and 18756 * should be overridden by subclasses to provide accurate and efficient 18757 * measurement of their contents. 18758 * </p> 18759 * 18760 * <p> 18761 * <strong>CONTRACT:</strong> When overriding this method, you 18762 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 18763 * measured width and height of this view. Failure to do so will trigger an 18764 * <code>IllegalStateException</code>, thrown by 18765 * {@link #measure(int, int)}. Calling the superclass' 18766 * {@link #onMeasure(int, int)} is a valid use. 18767 * </p> 18768 * 18769 * <p> 18770 * The base class implementation of measure defaults to the background size, 18771 * unless a larger size is allowed by the MeasureSpec. Subclasses should 18772 * override {@link #onMeasure(int, int)} to provide better measurements of 18773 * their content. 18774 * </p> 18775 * 18776 * <p> 18777 * If this method is overridden, it is the subclass's responsibility to make 18778 * sure the measured height and width are at least the view's minimum height 18779 * and width ({@link #getSuggestedMinimumHeight()} and 18780 * {@link #getSuggestedMinimumWidth()}). 18781 * </p> 18782 * 18783 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 18784 * The requirements are encoded with 18785 * {@link android.view.View.MeasureSpec}. 18786 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 18787 * The requirements are encoded with 18788 * {@link android.view.View.MeasureSpec}. 18789 * 18790 * @see #getMeasuredWidth() 18791 * @see #getMeasuredHeight() 18792 * @see #setMeasuredDimension(int, int) 18793 * @see #getSuggestedMinimumHeight() 18794 * @see #getSuggestedMinimumWidth() 18795 * @see android.view.View.MeasureSpec#getMode(int) 18796 * @see android.view.View.MeasureSpec#getSize(int) 18797 */ 18798 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 18799 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 18800 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 18801 } 18802 18803 /** 18804 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 18805 * measured width and measured height. Failing to do so will trigger an 18806 * exception at measurement time.</p> 18807 * 18808 * @param measuredWidth The measured width of this view. May be a complex 18809 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 18810 * {@link #MEASURED_STATE_TOO_SMALL}. 18811 * @param measuredHeight The measured height of this view. May be a complex 18812 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 18813 * {@link #MEASURED_STATE_TOO_SMALL}. 18814 */ 18815 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 18816 boolean optical = isLayoutModeOptical(this); 18817 if (optical != isLayoutModeOptical(mParent)) { 18818 Insets insets = getOpticalInsets(); 18819 int opticalWidth = insets.left + insets.right; 18820 int opticalHeight = insets.top + insets.bottom; 18821 18822 measuredWidth += optical ? opticalWidth : -opticalWidth; 18823 measuredHeight += optical ? opticalHeight : -opticalHeight; 18824 } 18825 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 18826 } 18827 18828 /** 18829 * Sets the measured dimension without extra processing for things like optical bounds. 18830 * Useful for reapplying consistent values that have already been cooked with adjustments 18831 * for optical bounds, etc. such as those from the measurement cache. 18832 * 18833 * @param measuredWidth The measured width of this view. May be a complex 18834 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 18835 * {@link #MEASURED_STATE_TOO_SMALL}. 18836 * @param measuredHeight The measured height of this view. May be a complex 18837 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 18838 * {@link #MEASURED_STATE_TOO_SMALL}. 18839 */ 18840 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 18841 mMeasuredWidth = measuredWidth; 18842 mMeasuredHeight = measuredHeight; 18843 18844 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 18845 } 18846 18847 /** 18848 * Merge two states as returned by {@link #getMeasuredState()}. 18849 * @param curState The current state as returned from a view or the result 18850 * of combining multiple views. 18851 * @param newState The new view state to combine. 18852 * @return Returns a new integer reflecting the combination of the two 18853 * states. 18854 */ 18855 public static int combineMeasuredStates(int curState, int newState) { 18856 return curState | newState; 18857 } 18858 18859 /** 18860 * Version of {@link #resolveSizeAndState(int, int, int)} 18861 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 18862 */ 18863 public static int resolveSize(int size, int measureSpec) { 18864 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 18865 } 18866 18867 /** 18868 * Utility to reconcile a desired size and state, with constraints imposed 18869 * by a MeasureSpec. Will take the desired size, unless a different size 18870 * is imposed by the constraints. The returned value is a compound integer, 18871 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 18872 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the 18873 * resulting size is smaller than the size the view wants to be. 18874 * 18875 * @param size How big the view wants to be. 18876 * @param measureSpec Constraints imposed by the parent. 18877 * @param childMeasuredState Size information bit mask for the view's 18878 * children. 18879 * @return Size information bit mask as defined by 18880 * {@link #MEASURED_SIZE_MASK} and 18881 * {@link #MEASURED_STATE_TOO_SMALL}. 18882 */ 18883 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 18884 final int specMode = MeasureSpec.getMode(measureSpec); 18885 final int specSize = MeasureSpec.getSize(measureSpec); 18886 final int result; 18887 switch (specMode) { 18888 case MeasureSpec.AT_MOST: 18889 if (specSize < size) { 18890 result = specSize | MEASURED_STATE_TOO_SMALL; 18891 } else { 18892 result = size; 18893 } 18894 break; 18895 case MeasureSpec.EXACTLY: 18896 result = specSize; 18897 break; 18898 case MeasureSpec.UNSPECIFIED: 18899 default: 18900 result = size; 18901 } 18902 return result | (childMeasuredState & MEASURED_STATE_MASK); 18903 } 18904 18905 /** 18906 * Utility to return a default size. Uses the supplied size if the 18907 * MeasureSpec imposed no constraints. Will get larger if allowed 18908 * by the MeasureSpec. 18909 * 18910 * @param size Default size for this view 18911 * @param measureSpec Constraints imposed by the parent 18912 * @return The size this view should be. 18913 */ 18914 public static int getDefaultSize(int size, int measureSpec) { 18915 int result = size; 18916 int specMode = MeasureSpec.getMode(measureSpec); 18917 int specSize = MeasureSpec.getSize(measureSpec); 18918 18919 switch (specMode) { 18920 case MeasureSpec.UNSPECIFIED: 18921 result = size; 18922 break; 18923 case MeasureSpec.AT_MOST: 18924 case MeasureSpec.EXACTLY: 18925 result = specSize; 18926 break; 18927 } 18928 return result; 18929 } 18930 18931 /** 18932 * Returns the suggested minimum height that the view should use. This 18933 * returns the maximum of the view's minimum height 18934 * and the background's minimum height 18935 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 18936 * <p> 18937 * When being used in {@link #onMeasure(int, int)}, the caller should still 18938 * ensure the returned height is within the requirements of the parent. 18939 * 18940 * @return The suggested minimum height of the view. 18941 */ 18942 protected int getSuggestedMinimumHeight() { 18943 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 18944 18945 } 18946 18947 /** 18948 * Returns the suggested minimum width that the view should use. This 18949 * returns the maximum of the view's minimum width) 18950 * and the background's minimum width 18951 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 18952 * <p> 18953 * When being used in {@link #onMeasure(int, int)}, the caller should still 18954 * ensure the returned width is within the requirements of the parent. 18955 * 18956 * @return The suggested minimum width of the view. 18957 */ 18958 protected int getSuggestedMinimumWidth() { 18959 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 18960 } 18961 18962 /** 18963 * Returns the minimum height of the view. 18964 * 18965 * @return the minimum height the view will try to be. 18966 * 18967 * @see #setMinimumHeight(int) 18968 * 18969 * @attr ref android.R.styleable#View_minHeight 18970 */ 18971 public int getMinimumHeight() { 18972 return mMinHeight; 18973 } 18974 18975 /** 18976 * Sets the minimum height of the view. It is not guaranteed the view will 18977 * be able to achieve this minimum height (for example, if its parent layout 18978 * constrains it with less available height). 18979 * 18980 * @param minHeight The minimum height the view will try to be. 18981 * 18982 * @see #getMinimumHeight() 18983 * 18984 * @attr ref android.R.styleable#View_minHeight 18985 */ 18986 public void setMinimumHeight(int minHeight) { 18987 mMinHeight = minHeight; 18988 requestLayout(); 18989 } 18990 18991 /** 18992 * Returns the minimum width of the view. 18993 * 18994 * @return the minimum width the view will try to be. 18995 * 18996 * @see #setMinimumWidth(int) 18997 * 18998 * @attr ref android.R.styleable#View_minWidth 18999 */ 19000 public int getMinimumWidth() { 19001 return mMinWidth; 19002 } 19003 19004 /** 19005 * Sets the minimum width of the view. It is not guaranteed the view will 19006 * be able to achieve this minimum width (for example, if its parent layout 19007 * constrains it with less available width). 19008 * 19009 * @param minWidth The minimum width the view will try to be. 19010 * 19011 * @see #getMinimumWidth() 19012 * 19013 * @attr ref android.R.styleable#View_minWidth 19014 */ 19015 public void setMinimumWidth(int minWidth) { 19016 mMinWidth = minWidth; 19017 requestLayout(); 19018 19019 } 19020 19021 /** 19022 * Get the animation currently associated with this view. 19023 * 19024 * @return The animation that is currently playing or 19025 * scheduled to play for this view. 19026 */ 19027 public Animation getAnimation() { 19028 return mCurrentAnimation; 19029 } 19030 19031 /** 19032 * Start the specified animation now. 19033 * 19034 * @param animation the animation to start now 19035 */ 19036 public void startAnimation(Animation animation) { 19037 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 19038 setAnimation(animation); 19039 invalidateParentCaches(); 19040 invalidate(true); 19041 } 19042 19043 /** 19044 * Cancels any animations for this view. 19045 */ 19046 public void clearAnimation() { 19047 if (mCurrentAnimation != null) { 19048 mCurrentAnimation.detach(); 19049 } 19050 mCurrentAnimation = null; 19051 invalidateParentIfNeeded(); 19052 } 19053 19054 /** 19055 * Sets the next animation to play for this view. 19056 * If you want the animation to play immediately, use 19057 * {@link #startAnimation(android.view.animation.Animation)} instead. 19058 * This method provides allows fine-grained 19059 * control over the start time and invalidation, but you 19060 * must make sure that 1) the animation has a start time set, and 19061 * 2) the view's parent (which controls animations on its children) 19062 * will be invalidated when the animation is supposed to 19063 * start. 19064 * 19065 * @param animation The next animation, or null. 19066 */ 19067 public void setAnimation(Animation animation) { 19068 mCurrentAnimation = animation; 19069 19070 if (animation != null) { 19071 // If the screen is off assume the animation start time is now instead of 19072 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 19073 // would cause the animation to start when the screen turns back on 19074 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 19075 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 19076 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 19077 } 19078 animation.reset(); 19079 } 19080 } 19081 19082 /** 19083 * Invoked by a parent ViewGroup to notify the start of the animation 19084 * currently associated with this view. If you override this method, 19085 * always call super.onAnimationStart(); 19086 * 19087 * @see #setAnimation(android.view.animation.Animation) 19088 * @see #getAnimation() 19089 */ 19090 @CallSuper 19091 protected void onAnimationStart() { 19092 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 19093 } 19094 19095 /** 19096 * Invoked by a parent ViewGroup to notify the end of the animation 19097 * currently associated with this view. If you override this method, 19098 * always call super.onAnimationEnd(); 19099 * 19100 * @see #setAnimation(android.view.animation.Animation) 19101 * @see #getAnimation() 19102 */ 19103 @CallSuper 19104 protected void onAnimationEnd() { 19105 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 19106 } 19107 19108 /** 19109 * Invoked if there is a Transform that involves alpha. Subclass that can 19110 * draw themselves with the specified alpha should return true, and then 19111 * respect that alpha when their onDraw() is called. If this returns false 19112 * then the view may be redirected to draw into an offscreen buffer to 19113 * fulfill the request, which will look fine, but may be slower than if the 19114 * subclass handles it internally. The default implementation returns false. 19115 * 19116 * @param alpha The alpha (0..255) to apply to the view's drawing 19117 * @return true if the view can draw with the specified alpha. 19118 */ 19119 protected boolean onSetAlpha(int alpha) { 19120 return false; 19121 } 19122 19123 /** 19124 * This is used by the RootView to perform an optimization when 19125 * the view hierarchy contains one or several SurfaceView. 19126 * SurfaceView is always considered transparent, but its children are not, 19127 * therefore all View objects remove themselves from the global transparent 19128 * region (passed as a parameter to this function). 19129 * 19130 * @param region The transparent region for this ViewAncestor (window). 19131 * 19132 * @return Returns true if the effective visibility of the view at this 19133 * point is opaque, regardless of the transparent region; returns false 19134 * if it is possible for underlying windows to be seen behind the view. 19135 * 19136 * {@hide} 19137 */ 19138 public boolean gatherTransparentRegion(Region region) { 19139 final AttachInfo attachInfo = mAttachInfo; 19140 if (region != null && attachInfo != null) { 19141 final int pflags = mPrivateFlags; 19142 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 19143 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 19144 // remove it from the transparent region. 19145 final int[] location = attachInfo.mTransparentLocation; 19146 getLocationInWindow(location); 19147 region.op(location[0], location[1], location[0] + mRight - mLeft, 19148 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 19149 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null && 19150 mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 19151 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 19152 // exists, so we remove the background drawable's non-transparent 19153 // parts from this transparent region. 19154 applyDrawableToTransparentRegion(mBackground, region); 19155 } 19156 final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 19157 if (foreground != null) { 19158 applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region); 19159 } 19160 } 19161 return true; 19162 } 19163 19164 /** 19165 * Play a sound effect for this view. 19166 * 19167 * <p>The framework will play sound effects for some built in actions, such as 19168 * clicking, but you may wish to play these effects in your widget, 19169 * for instance, for internal navigation. 19170 * 19171 * <p>The sound effect will only be played if sound effects are enabled by the user, and 19172 * {@link #isSoundEffectsEnabled()} is true. 19173 * 19174 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 19175 */ 19176 public void playSoundEffect(int soundConstant) { 19177 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 19178 return; 19179 } 19180 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 19181 } 19182 19183 /** 19184 * BZZZTT!!1! 19185 * 19186 * <p>Provide haptic feedback to the user for this view. 19187 * 19188 * <p>The framework will provide haptic feedback for some built in actions, 19189 * such as long presses, but you may wish to provide feedback for your 19190 * own widget. 19191 * 19192 * <p>The feedback will only be performed if 19193 * {@link #isHapticFeedbackEnabled()} is true. 19194 * 19195 * @param feedbackConstant One of the constants defined in 19196 * {@link HapticFeedbackConstants} 19197 */ 19198 public boolean performHapticFeedback(int feedbackConstant) { 19199 return performHapticFeedback(feedbackConstant, 0); 19200 } 19201 19202 /** 19203 * BZZZTT!!1! 19204 * 19205 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 19206 * 19207 * @param feedbackConstant One of the constants defined in 19208 * {@link HapticFeedbackConstants} 19209 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 19210 */ 19211 public boolean performHapticFeedback(int feedbackConstant, int flags) { 19212 if (mAttachInfo == null) { 19213 return false; 19214 } 19215 //noinspection SimplifiableIfStatement 19216 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 19217 && !isHapticFeedbackEnabled()) { 19218 return false; 19219 } 19220 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 19221 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 19222 } 19223 19224 /** 19225 * Request that the visibility of the status bar or other screen/window 19226 * decorations be changed. 19227 * 19228 * <p>This method is used to put the over device UI into temporary modes 19229 * where the user's attention is focused more on the application content, 19230 * by dimming or hiding surrounding system affordances. This is typically 19231 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 19232 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 19233 * to be placed behind the action bar (and with these flags other system 19234 * affordances) so that smooth transitions between hiding and showing them 19235 * can be done. 19236 * 19237 * <p>Two representative examples of the use of system UI visibility is 19238 * implementing a content browsing application (like a magazine reader) 19239 * and a video playing application. 19240 * 19241 * <p>The first code shows a typical implementation of a View in a content 19242 * browsing application. In this implementation, the application goes 19243 * into a content-oriented mode by hiding the status bar and action bar, 19244 * and putting the navigation elements into lights out mode. The user can 19245 * then interact with content while in this mode. Such an application should 19246 * provide an easy way for the user to toggle out of the mode (such as to 19247 * check information in the status bar or access notifications). In the 19248 * implementation here, this is done simply by tapping on the content. 19249 * 19250 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 19251 * content} 19252 * 19253 * <p>This second code sample shows a typical implementation of a View 19254 * in a video playing application. In this situation, while the video is 19255 * playing the application would like to go into a complete full-screen mode, 19256 * to use as much of the display as possible for the video. When in this state 19257 * the user can not interact with the application; the system intercepts 19258 * touching on the screen to pop the UI out of full screen mode. See 19259 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 19260 * 19261 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 19262 * content} 19263 * 19264 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19265 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 19266 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 19267 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 19268 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 19269 */ 19270 public void setSystemUiVisibility(int visibility) { 19271 if (visibility != mSystemUiVisibility) { 19272 mSystemUiVisibility = visibility; 19273 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 19274 mParent.recomputeViewAttributes(this); 19275 } 19276 } 19277 } 19278 19279 /** 19280 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 19281 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19282 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 19283 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 19284 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 19285 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 19286 */ 19287 public int getSystemUiVisibility() { 19288 return mSystemUiVisibility; 19289 } 19290 19291 /** 19292 * Returns the current system UI visibility that is currently set for 19293 * the entire window. This is the combination of the 19294 * {@link #setSystemUiVisibility(int)} values supplied by all of the 19295 * views in the window. 19296 */ 19297 public int getWindowSystemUiVisibility() { 19298 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 19299 } 19300 19301 /** 19302 * Override to find out when the window's requested system UI visibility 19303 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 19304 * This is different from the callbacks received through 19305 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 19306 * in that this is only telling you about the local request of the window, 19307 * not the actual values applied by the system. 19308 */ 19309 public void onWindowSystemUiVisibilityChanged(int visible) { 19310 } 19311 19312 /** 19313 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 19314 * the view hierarchy. 19315 */ 19316 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 19317 onWindowSystemUiVisibilityChanged(visible); 19318 } 19319 19320 /** 19321 * Set a listener to receive callbacks when the visibility of the system bar changes. 19322 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 19323 */ 19324 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 19325 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 19326 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 19327 mParent.recomputeViewAttributes(this); 19328 } 19329 } 19330 19331 /** 19332 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 19333 * the view hierarchy. 19334 */ 19335 public void dispatchSystemUiVisibilityChanged(int visibility) { 19336 ListenerInfo li = mListenerInfo; 19337 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 19338 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 19339 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 19340 } 19341 } 19342 19343 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 19344 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 19345 if (val != mSystemUiVisibility) { 19346 setSystemUiVisibility(val); 19347 return true; 19348 } 19349 return false; 19350 } 19351 19352 /** @hide */ 19353 public void setDisabledSystemUiVisibility(int flags) { 19354 if (mAttachInfo != null) { 19355 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 19356 mAttachInfo.mDisabledSystemUiVisibility = flags; 19357 if (mParent != null) { 19358 mParent.recomputeViewAttributes(this); 19359 } 19360 } 19361 } 19362 } 19363 19364 /** 19365 * Creates an image that the system displays during the drag and drop 19366 * operation. This is called a "drag shadow". The default implementation 19367 * for a DragShadowBuilder based on a View returns an image that has exactly the same 19368 * appearance as the given View. The default also positions the center of the drag shadow 19369 * directly under the touch point. If no View is provided (the constructor with no parameters 19370 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 19371 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the 19372 * default is an invisible drag shadow. 19373 * <p> 19374 * You are not required to use the View you provide to the constructor as the basis of the 19375 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 19376 * anything you want as the drag shadow. 19377 * </p> 19378 * <p> 19379 * You pass a DragShadowBuilder object to the system when you start the drag. The system 19380 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 19381 * size and position of the drag shadow. It uses this data to construct a 19382 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 19383 * so that your application can draw the shadow image in the Canvas. 19384 * </p> 19385 * 19386 * <div class="special reference"> 19387 * <h3>Developer Guides</h3> 19388 * <p>For a guide to implementing drag and drop features, read the 19389 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 19390 * </div> 19391 */ 19392 public static class DragShadowBuilder { 19393 private final WeakReference<View> mView; 19394 19395 /** 19396 * Constructs a shadow image builder based on a View. By default, the resulting drag 19397 * shadow will have the same appearance and dimensions as the View, with the touch point 19398 * over the center of the View. 19399 * @param view A View. Any View in scope can be used. 19400 */ 19401 public DragShadowBuilder(View view) { 19402 mView = new WeakReference<View>(view); 19403 } 19404 19405 /** 19406 * Construct a shadow builder object with no associated View. This 19407 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 19408 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 19409 * to supply the drag shadow's dimensions and appearance without 19410 * reference to any View object. If they are not overridden, then the result is an 19411 * invisible drag shadow. 19412 */ 19413 public DragShadowBuilder() { 19414 mView = new WeakReference<View>(null); 19415 } 19416 19417 /** 19418 * Returns the View object that had been passed to the 19419 * {@link #View.DragShadowBuilder(View)} 19420 * constructor. If that View parameter was {@code null} or if the 19421 * {@link #View.DragShadowBuilder()} 19422 * constructor was used to instantiate the builder object, this method will return 19423 * null. 19424 * 19425 * @return The View object associate with this builder object. 19426 */ 19427 @SuppressWarnings({"JavadocReference"}) 19428 final public View getView() { 19429 return mView.get(); 19430 } 19431 19432 /** 19433 * Provides the metrics for the shadow image. These include the dimensions of 19434 * the shadow image, and the point within that shadow that should 19435 * be centered under the touch location while dragging. 19436 * <p> 19437 * The default implementation sets the dimensions of the shadow to be the 19438 * same as the dimensions of the View itself and centers the shadow under 19439 * the touch point. 19440 * </p> 19441 * 19442 * @param shadowSize A {@link android.graphics.Point} containing the width and height 19443 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 19444 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 19445 * image. 19446 * 19447 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 19448 * shadow image that should be underneath the touch point during the drag and drop 19449 * operation. Your application must set {@link android.graphics.Point#x} to the 19450 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 19451 */ 19452 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 19453 final View view = mView.get(); 19454 if (view != null) { 19455 shadowSize.set(view.getWidth(), view.getHeight()); 19456 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 19457 } else { 19458 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 19459 } 19460 } 19461 19462 /** 19463 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 19464 * based on the dimensions it received from the 19465 * {@link #onProvideShadowMetrics(Point, Point)} callback. 19466 * 19467 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 19468 */ 19469 public void onDrawShadow(Canvas canvas) { 19470 final View view = mView.get(); 19471 if (view != null) { 19472 view.draw(canvas); 19473 } else { 19474 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 19475 } 19476 } 19477 } 19478 19479 /** 19480 * Starts a drag and drop operation. When your application calls this method, it passes a 19481 * {@link android.view.View.DragShadowBuilder} object to the system. The 19482 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 19483 * to get metrics for the drag shadow, and then calls the object's 19484 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 19485 * <p> 19486 * Once the system has the drag shadow, it begins the drag and drop operation by sending 19487 * drag events to all the View objects in your application that are currently visible. It does 19488 * this either by calling the View object's drag listener (an implementation of 19489 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 19490 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 19491 * Both are passed a {@link android.view.DragEvent} object that has a 19492 * {@link android.view.DragEvent#getAction()} value of 19493 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 19494 * </p> 19495 * <p> 19496 * Your application can invoke startDrag() on any attached View object. The View object does not 19497 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 19498 * be related to the View the user selected for dragging. 19499 * </p> 19500 * @param data A {@link android.content.ClipData} object pointing to the data to be 19501 * transferred by the drag and drop operation. 19502 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 19503 * drag shadow. 19504 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 19505 * drop operation. This Object is put into every DragEvent object sent by the system during the 19506 * current drag. 19507 * <p> 19508 * myLocalState is a lightweight mechanism for the sending information from the dragged View 19509 * to the target Views. For example, it can contain flags that differentiate between a 19510 * a copy operation and a move operation. 19511 * </p> 19512 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 19513 * so the parameter should be set to 0. 19514 * @return {@code true} if the method completes successfully, or 19515 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 19516 * do a drag, and so no drag operation is in progress. 19517 */ 19518 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 19519 Object myLocalState, int flags) { 19520 if (ViewDebug.DEBUG_DRAG) { 19521 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 19522 } 19523 boolean okay = false; 19524 19525 Point shadowSize = new Point(); 19526 Point shadowTouchPoint = new Point(); 19527 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 19528 19529 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 19530 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 19531 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 19532 } 19533 19534 if (ViewDebug.DEBUG_DRAG) { 19535 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 19536 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 19537 } 19538 Surface surface = new Surface(); 19539 try { 19540 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 19541 flags, shadowSize.x, shadowSize.y, surface); 19542 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 19543 + " surface=" + surface); 19544 if (token != null) { 19545 Canvas canvas = surface.lockCanvas(null); 19546 try { 19547 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 19548 shadowBuilder.onDrawShadow(canvas); 19549 } finally { 19550 surface.unlockCanvasAndPost(canvas); 19551 } 19552 19553 final ViewRootImpl root = getViewRootImpl(); 19554 19555 // Cache the local state object for delivery with DragEvents 19556 root.setLocalDragState(myLocalState); 19557 19558 // repurpose 'shadowSize' for the last touch point 19559 root.getLastTouchPoint(shadowSize); 19560 19561 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 19562 shadowSize.x, shadowSize.y, 19563 shadowTouchPoint.x, shadowTouchPoint.y, data); 19564 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 19565 19566 // Off and running! Release our local surface instance; the drag 19567 // shadow surface is now managed by the system process. 19568 surface.release(); 19569 } 19570 } catch (Exception e) { 19571 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 19572 surface.destroy(); 19573 } 19574 19575 return okay; 19576 } 19577 19578 /** 19579 * Handles drag events sent by the system following a call to 19580 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 19581 *<p> 19582 * When the system calls this method, it passes a 19583 * {@link android.view.DragEvent} object. A call to 19584 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 19585 * in DragEvent. The method uses these to determine what is happening in the drag and drop 19586 * operation. 19587 * @param event The {@link android.view.DragEvent} sent by the system. 19588 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 19589 * in DragEvent, indicating the type of drag event represented by this object. 19590 * @return {@code true} if the method was successful, otherwise {@code false}. 19591 * <p> 19592 * The method should return {@code true} in response to an action type of 19593 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 19594 * operation. 19595 * </p> 19596 * <p> 19597 * The method should also return {@code true} in response to an action type of 19598 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 19599 * {@code false} if it didn't. 19600 * </p> 19601 */ 19602 public boolean onDragEvent(DragEvent event) { 19603 return false; 19604 } 19605 19606 /** 19607 * Detects if this View is enabled and has a drag event listener. 19608 * If both are true, then it calls the drag event listener with the 19609 * {@link android.view.DragEvent} it received. If the drag event listener returns 19610 * {@code true}, then dispatchDragEvent() returns {@code true}. 19611 * <p> 19612 * For all other cases, the method calls the 19613 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 19614 * method and returns its result. 19615 * </p> 19616 * <p> 19617 * This ensures that a drag event is always consumed, even if the View does not have a drag 19618 * event listener. However, if the View has a listener and the listener returns true, then 19619 * onDragEvent() is not called. 19620 * </p> 19621 */ 19622 public boolean dispatchDragEvent(DragEvent event) { 19623 ListenerInfo li = mListenerInfo; 19624 //noinspection SimplifiableIfStatement 19625 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 19626 && li.mOnDragListener.onDrag(this, event)) { 19627 return true; 19628 } 19629 return onDragEvent(event); 19630 } 19631 19632 boolean canAcceptDrag() { 19633 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 19634 } 19635 19636 /** 19637 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 19638 * it is ever exposed at all. 19639 * @hide 19640 */ 19641 public void onCloseSystemDialogs(String reason) { 19642 } 19643 19644 /** 19645 * Given a Drawable whose bounds have been set to draw into this view, 19646 * update a Region being computed for 19647 * {@link #gatherTransparentRegion(android.graphics.Region)} so 19648 * that any non-transparent parts of the Drawable are removed from the 19649 * given transparent region. 19650 * 19651 * @param dr The Drawable whose transparency is to be applied to the region. 19652 * @param region A Region holding the current transparency information, 19653 * where any parts of the region that are set are considered to be 19654 * transparent. On return, this region will be modified to have the 19655 * transparency information reduced by the corresponding parts of the 19656 * Drawable that are not transparent. 19657 * {@hide} 19658 */ 19659 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 19660 if (DBG) { 19661 Log.i("View", "Getting transparent region for: " + this); 19662 } 19663 final Region r = dr.getTransparentRegion(); 19664 final Rect db = dr.getBounds(); 19665 final AttachInfo attachInfo = mAttachInfo; 19666 if (r != null && attachInfo != null) { 19667 final int w = getRight()-getLeft(); 19668 final int h = getBottom()-getTop(); 19669 if (db.left > 0) { 19670 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 19671 r.op(0, 0, db.left, h, Region.Op.UNION); 19672 } 19673 if (db.right < w) { 19674 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 19675 r.op(db.right, 0, w, h, Region.Op.UNION); 19676 } 19677 if (db.top > 0) { 19678 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 19679 r.op(0, 0, w, db.top, Region.Op.UNION); 19680 } 19681 if (db.bottom < h) { 19682 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 19683 r.op(0, db.bottom, w, h, Region.Op.UNION); 19684 } 19685 final int[] location = attachInfo.mTransparentLocation; 19686 getLocationInWindow(location); 19687 r.translate(location[0], location[1]); 19688 region.op(r, Region.Op.INTERSECT); 19689 } else { 19690 region.op(db, Region.Op.DIFFERENCE); 19691 } 19692 } 19693 19694 private void checkForLongClick(int delayOffset) { 19695 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 19696 mHasPerformedLongPress = false; 19697 19698 if (mPendingCheckForLongPress == null) { 19699 mPendingCheckForLongPress = new CheckForLongPress(); 19700 } 19701 mPendingCheckForLongPress.rememberWindowAttachCount(); 19702 postDelayed(mPendingCheckForLongPress, 19703 ViewConfiguration.getLongPressTimeout() - delayOffset); 19704 } 19705 } 19706 19707 /** 19708 * Inflate a view from an XML resource. This convenience method wraps the {@link 19709 * LayoutInflater} class, which provides a full range of options for view inflation. 19710 * 19711 * @param context The Context object for your activity or application. 19712 * @param resource The resource ID to inflate 19713 * @param root A view group that will be the parent. Used to properly inflate the 19714 * layout_* parameters. 19715 * @see LayoutInflater 19716 */ 19717 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { 19718 LayoutInflater factory = LayoutInflater.from(context); 19719 return factory.inflate(resource, root); 19720 } 19721 19722 /** 19723 * Scroll the view with standard behavior for scrolling beyond the normal 19724 * content boundaries. Views that call this method should override 19725 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 19726 * results of an over-scroll operation. 19727 * 19728 * Views can use this method to handle any touch or fling-based scrolling. 19729 * 19730 * @param deltaX Change in X in pixels 19731 * @param deltaY Change in Y in pixels 19732 * @param scrollX Current X scroll value in pixels before applying deltaX 19733 * @param scrollY Current Y scroll value in pixels before applying deltaY 19734 * @param scrollRangeX Maximum content scroll range along the X axis 19735 * @param scrollRangeY Maximum content scroll range along the Y axis 19736 * @param maxOverScrollX Number of pixels to overscroll by in either direction 19737 * along the X axis. 19738 * @param maxOverScrollY Number of pixels to overscroll by in either direction 19739 * along the Y axis. 19740 * @param isTouchEvent true if this scroll operation is the result of a touch event. 19741 * @return true if scrolling was clamped to an over-scroll boundary along either 19742 * axis, false otherwise. 19743 */ 19744 @SuppressWarnings({"UnusedParameters"}) 19745 protected boolean overScrollBy(int deltaX, int deltaY, 19746 int scrollX, int scrollY, 19747 int scrollRangeX, int scrollRangeY, 19748 int maxOverScrollX, int maxOverScrollY, 19749 boolean isTouchEvent) { 19750 final int overScrollMode = mOverScrollMode; 19751 final boolean canScrollHorizontal = 19752 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 19753 final boolean canScrollVertical = 19754 computeVerticalScrollRange() > computeVerticalScrollExtent(); 19755 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 19756 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 19757 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 19758 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 19759 19760 int newScrollX = scrollX + deltaX; 19761 if (!overScrollHorizontal) { 19762 maxOverScrollX = 0; 19763 } 19764 19765 int newScrollY = scrollY + deltaY; 19766 if (!overScrollVertical) { 19767 maxOverScrollY = 0; 19768 } 19769 19770 // Clamp values if at the limits and record 19771 final int left = -maxOverScrollX; 19772 final int right = maxOverScrollX + scrollRangeX; 19773 final int top = -maxOverScrollY; 19774 final int bottom = maxOverScrollY + scrollRangeY; 19775 19776 boolean clampedX = false; 19777 if (newScrollX > right) { 19778 newScrollX = right; 19779 clampedX = true; 19780 } else if (newScrollX < left) { 19781 newScrollX = left; 19782 clampedX = true; 19783 } 19784 19785 boolean clampedY = false; 19786 if (newScrollY > bottom) { 19787 newScrollY = bottom; 19788 clampedY = true; 19789 } else if (newScrollY < top) { 19790 newScrollY = top; 19791 clampedY = true; 19792 } 19793 19794 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 19795 19796 return clampedX || clampedY; 19797 } 19798 19799 /** 19800 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 19801 * respond to the results of an over-scroll operation. 19802 * 19803 * @param scrollX New X scroll value in pixels 19804 * @param scrollY New Y scroll value in pixels 19805 * @param clampedX True if scrollX was clamped to an over-scroll boundary 19806 * @param clampedY True if scrollY was clamped to an over-scroll boundary 19807 */ 19808 protected void onOverScrolled(int scrollX, int scrollY, 19809 boolean clampedX, boolean clampedY) { 19810 // Intentionally empty. 19811 } 19812 19813 /** 19814 * Returns the over-scroll mode for this view. The result will be 19815 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 19816 * (allow over-scrolling only if the view content is larger than the container), 19817 * or {@link #OVER_SCROLL_NEVER}. 19818 * 19819 * @return This view's over-scroll mode. 19820 */ 19821 public int getOverScrollMode() { 19822 return mOverScrollMode; 19823 } 19824 19825 /** 19826 * Set the over-scroll mode for this view. Valid over-scroll modes are 19827 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 19828 * (allow over-scrolling only if the view content is larger than the container), 19829 * or {@link #OVER_SCROLL_NEVER}. 19830 * 19831 * Setting the over-scroll mode of a view will have an effect only if the 19832 * view is capable of scrolling. 19833 * 19834 * @param overScrollMode The new over-scroll mode for this view. 19835 */ 19836 public void setOverScrollMode(int overScrollMode) { 19837 if (overScrollMode != OVER_SCROLL_ALWAYS && 19838 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 19839 overScrollMode != OVER_SCROLL_NEVER) { 19840 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 19841 } 19842 mOverScrollMode = overScrollMode; 19843 } 19844 19845 /** 19846 * Enable or disable nested scrolling for this view. 19847 * 19848 * <p>If this property is set to true the view will be permitted to initiate nested 19849 * scrolling operations with a compatible parent view in the current hierarchy. If this 19850 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 19851 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 19852 * the nested scroll.</p> 19853 * 19854 * @param enabled true to enable nested scrolling, false to disable 19855 * 19856 * @see #isNestedScrollingEnabled() 19857 */ 19858 public void setNestedScrollingEnabled(boolean enabled) { 19859 if (enabled) { 19860 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 19861 } else { 19862 stopNestedScroll(); 19863 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 19864 } 19865 } 19866 19867 /** 19868 * Returns true if nested scrolling is enabled for this view. 19869 * 19870 * <p>If nested scrolling is enabled and this View class implementation supports it, 19871 * this view will act as a nested scrolling child view when applicable, forwarding data 19872 * about the scroll operation in progress to a compatible and cooperating nested scrolling 19873 * parent.</p> 19874 * 19875 * @return true if nested scrolling is enabled 19876 * 19877 * @see #setNestedScrollingEnabled(boolean) 19878 */ 19879 public boolean isNestedScrollingEnabled() { 19880 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 19881 PFLAG3_NESTED_SCROLLING_ENABLED; 19882 } 19883 19884 /** 19885 * Begin a nestable scroll operation along the given axes. 19886 * 19887 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 19888 * 19889 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 19890 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 19891 * In the case of touch scrolling the nested scroll will be terminated automatically in 19892 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 19893 * In the event of programmatic scrolling the caller must explicitly call 19894 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 19895 * 19896 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 19897 * If it returns false the caller may ignore the rest of this contract until the next scroll. 19898 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 19899 * 19900 * <p>At each incremental step of the scroll the caller should invoke 19901 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 19902 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 19903 * parent at least partially consumed the scroll and the caller should adjust the amount it 19904 * scrolls by.</p> 19905 * 19906 * <p>After applying the remainder of the scroll delta the caller should invoke 19907 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 19908 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 19909 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 19910 * </p> 19911 * 19912 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 19913 * {@link #SCROLL_AXIS_VERTICAL}. 19914 * @return true if a cooperative parent was found and nested scrolling has been enabled for 19915 * the current gesture. 19916 * 19917 * @see #stopNestedScroll() 19918 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 19919 * @see #dispatchNestedScroll(int, int, int, int, int[]) 19920 */ 19921 public boolean startNestedScroll(int axes) { 19922 if (hasNestedScrollingParent()) { 19923 // Already in progress 19924 return true; 19925 } 19926 if (isNestedScrollingEnabled()) { 19927 ViewParent p = getParent(); 19928 View child = this; 19929 while (p != null) { 19930 try { 19931 if (p.onStartNestedScroll(child, this, axes)) { 19932 mNestedScrollingParent = p; 19933 p.onNestedScrollAccepted(child, this, axes); 19934 return true; 19935 } 19936 } catch (AbstractMethodError e) { 19937 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 19938 "method onStartNestedScroll", e); 19939 // Allow the search upward to continue 19940 } 19941 if (p instanceof View) { 19942 child = (View) p; 19943 } 19944 p = p.getParent(); 19945 } 19946 } 19947 return false; 19948 } 19949 19950 /** 19951 * Stop a nested scroll in progress. 19952 * 19953 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 19954 * 19955 * @see #startNestedScroll(int) 19956 */ 19957 public void stopNestedScroll() { 19958 if (mNestedScrollingParent != null) { 19959 mNestedScrollingParent.onStopNestedScroll(this); 19960 mNestedScrollingParent = null; 19961 } 19962 } 19963 19964 /** 19965 * Returns true if this view has a nested scrolling parent. 19966 * 19967 * <p>The presence of a nested scrolling parent indicates that this view has initiated 19968 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 19969 * 19970 * @return whether this view has a nested scrolling parent 19971 */ 19972 public boolean hasNestedScrollingParent() { 19973 return mNestedScrollingParent != null; 19974 } 19975 19976 /** 19977 * Dispatch one step of a nested scroll in progress. 19978 * 19979 * <p>Implementations of views that support nested scrolling should call this to report 19980 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 19981 * is not currently in progress or nested scrolling is not 19982 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 19983 * 19984 * <p>Compatible View implementations should also call 19985 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 19986 * consuming a component of the scroll event themselves.</p> 19987 * 19988 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 19989 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 19990 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 19991 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 19992 * @param offsetInWindow Optional. If not null, on return this will contain the offset 19993 * in local view coordinates of this view from before this operation 19994 * to after it completes. View implementations may use this to adjust 19995 * expected input coordinate tracking. 19996 * @return true if the event was dispatched, false if it could not be dispatched. 19997 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 19998 */ 19999 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 20000 int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) { 20001 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 20002 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 20003 int startX = 0; 20004 int startY = 0; 20005 if (offsetInWindow != null) { 20006 getLocationInWindow(offsetInWindow); 20007 startX = offsetInWindow[0]; 20008 startY = offsetInWindow[1]; 20009 } 20010 20011 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 20012 dxUnconsumed, dyUnconsumed); 20013 20014 if (offsetInWindow != null) { 20015 getLocationInWindow(offsetInWindow); 20016 offsetInWindow[0] -= startX; 20017 offsetInWindow[1] -= startY; 20018 } 20019 return true; 20020 } else if (offsetInWindow != null) { 20021 // No motion, no dispatch. Keep offsetInWindow up to date. 20022 offsetInWindow[0] = 0; 20023 offsetInWindow[1] = 0; 20024 } 20025 } 20026 return false; 20027 } 20028 20029 /** 20030 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 20031 * 20032 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 20033 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 20034 * scrolling operation to consume some or all of the scroll operation before the child view 20035 * consumes it.</p> 20036 * 20037 * @param dx Horizontal scroll distance in pixels 20038 * @param dy Vertical scroll distance in pixels 20039 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 20040 * and consumed[1] the consumed dy. 20041 * @param offsetInWindow Optional. If not null, on return this will contain the offset 20042 * in local view coordinates of this view from before this operation 20043 * to after it completes. View implementations may use this to adjust 20044 * expected input coordinate tracking. 20045 * @return true if the parent consumed some or all of the scroll delta 20046 * @see #dispatchNestedScroll(int, int, int, int, int[]) 20047 */ 20048 public boolean dispatchNestedPreScroll(int dx, int dy, 20049 @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) { 20050 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 20051 if (dx != 0 || dy != 0) { 20052 int startX = 0; 20053 int startY = 0; 20054 if (offsetInWindow != null) { 20055 getLocationInWindow(offsetInWindow); 20056 startX = offsetInWindow[0]; 20057 startY = offsetInWindow[1]; 20058 } 20059 20060 if (consumed == null) { 20061 if (mTempNestedScrollConsumed == null) { 20062 mTempNestedScrollConsumed = new int[2]; 20063 } 20064 consumed = mTempNestedScrollConsumed; 20065 } 20066 consumed[0] = 0; 20067 consumed[1] = 0; 20068 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 20069 20070 if (offsetInWindow != null) { 20071 getLocationInWindow(offsetInWindow); 20072 offsetInWindow[0] -= startX; 20073 offsetInWindow[1] -= startY; 20074 } 20075 return consumed[0] != 0 || consumed[1] != 0; 20076 } else if (offsetInWindow != null) { 20077 offsetInWindow[0] = 0; 20078 offsetInWindow[1] = 0; 20079 } 20080 } 20081 return false; 20082 } 20083 20084 /** 20085 * Dispatch a fling to a nested scrolling parent. 20086 * 20087 * <p>This method should be used to indicate that a nested scrolling child has detected 20088 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 20089 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 20090 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 20091 * along a scrollable axis.</p> 20092 * 20093 * <p>If a nested scrolling child view would normally fling but it is at the edge of 20094 * its own content, it can use this method to delegate the fling to its nested scrolling 20095 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 20096 * 20097 * @param velocityX Horizontal fling velocity in pixels per second 20098 * @param velocityY Vertical fling velocity in pixels per second 20099 * @param consumed true if the child consumed the fling, false otherwise 20100 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 20101 */ 20102 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 20103 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 20104 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 20105 } 20106 return false; 20107 } 20108 20109 /** 20110 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 20111 * 20112 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 20113 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 20114 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 20115 * before the child view consumes it. If this method returns <code>true</code>, a nested 20116 * parent view consumed the fling and this view should not scroll as a result.</p> 20117 * 20118 * <p>For a better user experience, only one view in a nested scrolling chain should consume 20119 * the fling at a time. If a parent view consumed the fling this method will return false. 20120 * Custom view implementations should account for this in two ways:</p> 20121 * 20122 * <ul> 20123 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 20124 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 20125 * position regardless.</li> 20126 * <li>If a nested parent does consume the fling, this view should not scroll at all, 20127 * even to settle back to a valid idle position.</li> 20128 * </ul> 20129 * 20130 * <p>Views should also not offer fling velocities to nested parent views along an axis 20131 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 20132 * should not offer a horizontal fling velocity to its parents since scrolling along that 20133 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 20134 * 20135 * @param velocityX Horizontal fling velocity in pixels per second 20136 * @param velocityY Vertical fling velocity in pixels per second 20137 * @return true if a nested scrolling parent consumed the fling 20138 */ 20139 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 20140 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 20141 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 20142 } 20143 return false; 20144 } 20145 20146 /** 20147 * Gets a scale factor that determines the distance the view should scroll 20148 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 20149 * @return The vertical scroll scale factor. 20150 * @hide 20151 */ 20152 protected float getVerticalScrollFactor() { 20153 if (mVerticalScrollFactor == 0) { 20154 TypedValue outValue = new TypedValue(); 20155 if (!mContext.getTheme().resolveAttribute( 20156 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 20157 throw new IllegalStateException( 20158 "Expected theme to define listPreferredItemHeight."); 20159 } 20160 mVerticalScrollFactor = outValue.getDimension( 20161 mContext.getResources().getDisplayMetrics()); 20162 } 20163 return mVerticalScrollFactor; 20164 } 20165 20166 /** 20167 * Gets a scale factor that determines the distance the view should scroll 20168 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 20169 * @return The horizontal scroll scale factor. 20170 * @hide 20171 */ 20172 protected float getHorizontalScrollFactor() { 20173 // TODO: Should use something else. 20174 return getVerticalScrollFactor(); 20175 } 20176 20177 /** 20178 * Return the value specifying the text direction or policy that was set with 20179 * {@link #setTextDirection(int)}. 20180 * 20181 * @return the defined text direction. It can be one of: 20182 * 20183 * {@link #TEXT_DIRECTION_INHERIT}, 20184 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 20185 * {@link #TEXT_DIRECTION_ANY_RTL}, 20186 * {@link #TEXT_DIRECTION_LTR}, 20187 * {@link #TEXT_DIRECTION_RTL}, 20188 * {@link #TEXT_DIRECTION_LOCALE}, 20189 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 20190 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 20191 * 20192 * @attr ref android.R.styleable#View_textDirection 20193 * 20194 * @hide 20195 */ 20196 @ViewDebug.ExportedProperty(category = "text", mapping = { 20197 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 20198 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 20199 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 20200 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 20201 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 20202 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 20203 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 20204 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 20205 }) 20206 public int getRawTextDirection() { 20207 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 20208 } 20209 20210 /** 20211 * Set the text direction. 20212 * 20213 * @param textDirection the direction to set. Should be one of: 20214 * 20215 * {@link #TEXT_DIRECTION_INHERIT}, 20216 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 20217 * {@link #TEXT_DIRECTION_ANY_RTL}, 20218 * {@link #TEXT_DIRECTION_LTR}, 20219 * {@link #TEXT_DIRECTION_RTL}, 20220 * {@link #TEXT_DIRECTION_LOCALE} 20221 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 20222 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}, 20223 * 20224 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 20225 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 20226 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 20227 * 20228 * @attr ref android.R.styleable#View_textDirection 20229 */ 20230 public void setTextDirection(int textDirection) { 20231 if (getRawTextDirection() != textDirection) { 20232 // Reset the current text direction and the resolved one 20233 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 20234 resetResolvedTextDirection(); 20235 // Set the new text direction 20236 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 20237 // Do resolution 20238 resolveTextDirection(); 20239 // Notify change 20240 onRtlPropertiesChanged(getLayoutDirection()); 20241 // Refresh 20242 requestLayout(); 20243 invalidate(true); 20244 } 20245 } 20246 20247 /** 20248 * Return the resolved text direction. 20249 * 20250 * @return the resolved text direction. Returns one of: 20251 * 20252 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 20253 * {@link #TEXT_DIRECTION_ANY_RTL}, 20254 * {@link #TEXT_DIRECTION_LTR}, 20255 * {@link #TEXT_DIRECTION_RTL}, 20256 * {@link #TEXT_DIRECTION_LOCALE}, 20257 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 20258 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 20259 * 20260 * @attr ref android.R.styleable#View_textDirection 20261 */ 20262 @ViewDebug.ExportedProperty(category = "text", mapping = { 20263 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 20264 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 20265 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 20266 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 20267 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 20268 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 20269 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 20270 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 20271 }) 20272 public int getTextDirection() { 20273 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 20274 } 20275 20276 /** 20277 * Resolve the text direction. 20278 * 20279 * @return true if resolution has been done, false otherwise. 20280 * 20281 * @hide 20282 */ 20283 public boolean resolveTextDirection() { 20284 // Reset any previous text direction resolution 20285 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 20286 20287 if (hasRtlSupport()) { 20288 // Set resolved text direction flag depending on text direction flag 20289 final int textDirection = getRawTextDirection(); 20290 switch(textDirection) { 20291 case TEXT_DIRECTION_INHERIT: 20292 if (!canResolveTextDirection()) { 20293 // We cannot do the resolution if there is no parent, so use the default one 20294 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 20295 // Resolution will need to happen again later 20296 return false; 20297 } 20298 20299 // Parent has not yet resolved, so we still return the default 20300 try { 20301 if (!mParent.isTextDirectionResolved()) { 20302 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 20303 // Resolution will need to happen again later 20304 return false; 20305 } 20306 } catch (AbstractMethodError e) { 20307 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 20308 " does not fully implement ViewParent", e); 20309 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 20310 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 20311 return true; 20312 } 20313 20314 // Set current resolved direction to the same value as the parent's one 20315 int parentResolvedDirection; 20316 try { 20317 parentResolvedDirection = mParent.getTextDirection(); 20318 } catch (AbstractMethodError e) { 20319 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 20320 " does not fully implement ViewParent", e); 20321 parentResolvedDirection = TEXT_DIRECTION_LTR; 20322 } 20323 switch (parentResolvedDirection) { 20324 case TEXT_DIRECTION_FIRST_STRONG: 20325 case TEXT_DIRECTION_ANY_RTL: 20326 case TEXT_DIRECTION_LTR: 20327 case TEXT_DIRECTION_RTL: 20328 case TEXT_DIRECTION_LOCALE: 20329 case TEXT_DIRECTION_FIRST_STRONG_LTR: 20330 case TEXT_DIRECTION_FIRST_STRONG_RTL: 20331 mPrivateFlags2 |= 20332 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 20333 break; 20334 default: 20335 // Default resolved direction is "first strong" heuristic 20336 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 20337 } 20338 break; 20339 case TEXT_DIRECTION_FIRST_STRONG: 20340 case TEXT_DIRECTION_ANY_RTL: 20341 case TEXT_DIRECTION_LTR: 20342 case TEXT_DIRECTION_RTL: 20343 case TEXT_DIRECTION_LOCALE: 20344 case TEXT_DIRECTION_FIRST_STRONG_LTR: 20345 case TEXT_DIRECTION_FIRST_STRONG_RTL: 20346 // Resolved direction is the same as text direction 20347 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 20348 break; 20349 default: 20350 // Default resolved direction is "first strong" heuristic 20351 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 20352 } 20353 } else { 20354 // Default resolved direction is "first strong" heuristic 20355 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 20356 } 20357 20358 // Set to resolved 20359 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 20360 return true; 20361 } 20362 20363 /** 20364 * Check if text direction resolution can be done. 20365 * 20366 * @return true if text direction resolution can be done otherwise return false. 20367 */ 20368 public boolean canResolveTextDirection() { 20369 switch (getRawTextDirection()) { 20370 case TEXT_DIRECTION_INHERIT: 20371 if (mParent != null) { 20372 try { 20373 return mParent.canResolveTextDirection(); 20374 } catch (AbstractMethodError e) { 20375 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 20376 " does not fully implement ViewParent", e); 20377 } 20378 } 20379 return false; 20380 20381 default: 20382 return true; 20383 } 20384 } 20385 20386 /** 20387 * Reset resolved text direction. Text direction will be resolved during a call to 20388 * {@link #onMeasure(int, int)}. 20389 * 20390 * @hide 20391 */ 20392 public void resetResolvedTextDirection() { 20393 // Reset any previous text direction resolution 20394 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 20395 // Set to default value 20396 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 20397 } 20398 20399 /** 20400 * @return true if text direction is inherited. 20401 * 20402 * @hide 20403 */ 20404 public boolean isTextDirectionInherited() { 20405 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 20406 } 20407 20408 /** 20409 * @return true if text direction is resolved. 20410 */ 20411 public boolean isTextDirectionResolved() { 20412 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 20413 } 20414 20415 /** 20416 * Return the value specifying the text alignment or policy that was set with 20417 * {@link #setTextAlignment(int)}. 20418 * 20419 * @return the defined text alignment. It can be one of: 20420 * 20421 * {@link #TEXT_ALIGNMENT_INHERIT}, 20422 * {@link #TEXT_ALIGNMENT_GRAVITY}, 20423 * {@link #TEXT_ALIGNMENT_CENTER}, 20424 * {@link #TEXT_ALIGNMENT_TEXT_START}, 20425 * {@link #TEXT_ALIGNMENT_TEXT_END}, 20426 * {@link #TEXT_ALIGNMENT_VIEW_START}, 20427 * {@link #TEXT_ALIGNMENT_VIEW_END} 20428 * 20429 * @attr ref android.R.styleable#View_textAlignment 20430 * 20431 * @hide 20432 */ 20433 @ViewDebug.ExportedProperty(category = "text", mapping = { 20434 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 20435 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 20436 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 20437 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 20438 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 20439 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 20440 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 20441 }) 20442 @TextAlignment 20443 public int getRawTextAlignment() { 20444 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 20445 } 20446 20447 /** 20448 * Set the text alignment. 20449 * 20450 * @param textAlignment The text alignment to set. Should be one of 20451 * 20452 * {@link #TEXT_ALIGNMENT_INHERIT}, 20453 * {@link #TEXT_ALIGNMENT_GRAVITY}, 20454 * {@link #TEXT_ALIGNMENT_CENTER}, 20455 * {@link #TEXT_ALIGNMENT_TEXT_START}, 20456 * {@link #TEXT_ALIGNMENT_TEXT_END}, 20457 * {@link #TEXT_ALIGNMENT_VIEW_START}, 20458 * {@link #TEXT_ALIGNMENT_VIEW_END} 20459 * 20460 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 20461 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 20462 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 20463 * 20464 * @attr ref android.R.styleable#View_textAlignment 20465 */ 20466 public void setTextAlignment(@TextAlignment int textAlignment) { 20467 if (textAlignment != getRawTextAlignment()) { 20468 // Reset the current and resolved text alignment 20469 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 20470 resetResolvedTextAlignment(); 20471 // Set the new text alignment 20472 mPrivateFlags2 |= 20473 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 20474 // Do resolution 20475 resolveTextAlignment(); 20476 // Notify change 20477 onRtlPropertiesChanged(getLayoutDirection()); 20478 // Refresh 20479 requestLayout(); 20480 invalidate(true); 20481 } 20482 } 20483 20484 /** 20485 * Return the resolved text alignment. 20486 * 20487 * @return the resolved text alignment. Returns one of: 20488 * 20489 * {@link #TEXT_ALIGNMENT_GRAVITY}, 20490 * {@link #TEXT_ALIGNMENT_CENTER}, 20491 * {@link #TEXT_ALIGNMENT_TEXT_START}, 20492 * {@link #TEXT_ALIGNMENT_TEXT_END}, 20493 * {@link #TEXT_ALIGNMENT_VIEW_START}, 20494 * {@link #TEXT_ALIGNMENT_VIEW_END} 20495 * 20496 * @attr ref android.R.styleable#View_textAlignment 20497 */ 20498 @ViewDebug.ExportedProperty(category = "text", mapping = { 20499 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 20500 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 20501 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 20502 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 20503 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 20504 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 20505 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 20506 }) 20507 @TextAlignment 20508 public int getTextAlignment() { 20509 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 20510 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 20511 } 20512 20513 /** 20514 * Resolve the text alignment. 20515 * 20516 * @return true if resolution has been done, false otherwise. 20517 * 20518 * @hide 20519 */ 20520 public boolean resolveTextAlignment() { 20521 // Reset any previous text alignment resolution 20522 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 20523 20524 if (hasRtlSupport()) { 20525 // Set resolved text alignment flag depending on text alignment flag 20526 final int textAlignment = getRawTextAlignment(); 20527 switch (textAlignment) { 20528 case TEXT_ALIGNMENT_INHERIT: 20529 // Check if we can resolve the text alignment 20530 if (!canResolveTextAlignment()) { 20531 // We cannot do the resolution if there is no parent so use the default 20532 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 20533 // Resolution will need to happen again later 20534 return false; 20535 } 20536 20537 // Parent has not yet resolved, so we still return the default 20538 try { 20539 if (!mParent.isTextAlignmentResolved()) { 20540 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 20541 // Resolution will need to happen again later 20542 return false; 20543 } 20544 } catch (AbstractMethodError e) { 20545 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 20546 " does not fully implement ViewParent", e); 20547 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 20548 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 20549 return true; 20550 } 20551 20552 int parentResolvedTextAlignment; 20553 try { 20554 parentResolvedTextAlignment = mParent.getTextAlignment(); 20555 } catch (AbstractMethodError e) { 20556 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 20557 " does not fully implement ViewParent", e); 20558 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 20559 } 20560 switch (parentResolvedTextAlignment) { 20561 case TEXT_ALIGNMENT_GRAVITY: 20562 case TEXT_ALIGNMENT_TEXT_START: 20563 case TEXT_ALIGNMENT_TEXT_END: 20564 case TEXT_ALIGNMENT_CENTER: 20565 case TEXT_ALIGNMENT_VIEW_START: 20566 case TEXT_ALIGNMENT_VIEW_END: 20567 // Resolved text alignment is the same as the parent resolved 20568 // text alignment 20569 mPrivateFlags2 |= 20570 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 20571 break; 20572 default: 20573 // Use default resolved text alignment 20574 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 20575 } 20576 break; 20577 case TEXT_ALIGNMENT_GRAVITY: 20578 case TEXT_ALIGNMENT_TEXT_START: 20579 case TEXT_ALIGNMENT_TEXT_END: 20580 case TEXT_ALIGNMENT_CENTER: 20581 case TEXT_ALIGNMENT_VIEW_START: 20582 case TEXT_ALIGNMENT_VIEW_END: 20583 // Resolved text alignment is the same as text alignment 20584 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 20585 break; 20586 default: 20587 // Use default resolved text alignment 20588 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 20589 } 20590 } else { 20591 // Use default resolved text alignment 20592 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 20593 } 20594 20595 // Set the resolved 20596 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 20597 return true; 20598 } 20599 20600 /** 20601 * Check if text alignment resolution can be done. 20602 * 20603 * @return true if text alignment resolution can be done otherwise return false. 20604 */ 20605 public boolean canResolveTextAlignment() { 20606 switch (getRawTextAlignment()) { 20607 case TEXT_DIRECTION_INHERIT: 20608 if (mParent != null) { 20609 try { 20610 return mParent.canResolveTextAlignment(); 20611 } catch (AbstractMethodError e) { 20612 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 20613 " does not fully implement ViewParent", e); 20614 } 20615 } 20616 return false; 20617 20618 default: 20619 return true; 20620 } 20621 } 20622 20623 /** 20624 * Reset resolved text alignment. Text alignment will be resolved during a call to 20625 * {@link #onMeasure(int, int)}. 20626 * 20627 * @hide 20628 */ 20629 public void resetResolvedTextAlignment() { 20630 // Reset any previous text alignment resolution 20631 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 20632 // Set to default 20633 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 20634 } 20635 20636 /** 20637 * @return true if text alignment is inherited. 20638 * 20639 * @hide 20640 */ 20641 public boolean isTextAlignmentInherited() { 20642 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 20643 } 20644 20645 /** 20646 * @return true if text alignment is resolved. 20647 */ 20648 public boolean isTextAlignmentResolved() { 20649 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 20650 } 20651 20652 /** 20653 * Generate a value suitable for use in {@link #setId(int)}. 20654 * This value will not collide with ID values generated at build time by aapt for R.id. 20655 * 20656 * @return a generated ID value 20657 */ 20658 public static int generateViewId() { 20659 for (;;) { 20660 final int result = sNextGeneratedId.get(); 20661 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 20662 int newValue = result + 1; 20663 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 20664 if (sNextGeneratedId.compareAndSet(result, newValue)) { 20665 return result; 20666 } 20667 } 20668 } 20669 20670 /** 20671 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 20672 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 20673 * a normal View or a ViewGroup with 20674 * {@link android.view.ViewGroup#isTransitionGroup()} true. 20675 * @hide 20676 */ 20677 public void captureTransitioningViews(List<View> transitioningViews) { 20678 if (getVisibility() == View.VISIBLE) { 20679 transitioningViews.add(this); 20680 } 20681 } 20682 20683 /** 20684 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 20685 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 20686 * @hide 20687 */ 20688 public void findNamedViews(Map<String, View> namedElements) { 20689 if (getVisibility() == VISIBLE || mGhostView != null) { 20690 String transitionName = getTransitionName(); 20691 if (transitionName != null) { 20692 namedElements.put(transitionName, this); 20693 } 20694 } 20695 } 20696 20697 // 20698 // Properties 20699 // 20700 /** 20701 * A Property wrapper around the <code>alpha</code> functionality handled by the 20702 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 20703 */ 20704 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 20705 @Override 20706 public void setValue(View object, float value) { 20707 object.setAlpha(value); 20708 } 20709 20710 @Override 20711 public Float get(View object) { 20712 return object.getAlpha(); 20713 } 20714 }; 20715 20716 /** 20717 * A Property wrapper around the <code>translationX</code> functionality handled by the 20718 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 20719 */ 20720 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 20721 @Override 20722 public void setValue(View object, float value) { 20723 object.setTranslationX(value); 20724 } 20725 20726 @Override 20727 public Float get(View object) { 20728 return object.getTranslationX(); 20729 } 20730 }; 20731 20732 /** 20733 * A Property wrapper around the <code>translationY</code> functionality handled by the 20734 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 20735 */ 20736 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 20737 @Override 20738 public void setValue(View object, float value) { 20739 object.setTranslationY(value); 20740 } 20741 20742 @Override 20743 public Float get(View object) { 20744 return object.getTranslationY(); 20745 } 20746 }; 20747 20748 /** 20749 * A Property wrapper around the <code>translationZ</code> functionality handled by the 20750 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 20751 */ 20752 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 20753 @Override 20754 public void setValue(View object, float value) { 20755 object.setTranslationZ(value); 20756 } 20757 20758 @Override 20759 public Float get(View object) { 20760 return object.getTranslationZ(); 20761 } 20762 }; 20763 20764 /** 20765 * A Property wrapper around the <code>x</code> functionality handled by the 20766 * {@link View#setX(float)} and {@link View#getX()} methods. 20767 */ 20768 public static final Property<View, Float> X = new FloatProperty<View>("x") { 20769 @Override 20770 public void setValue(View object, float value) { 20771 object.setX(value); 20772 } 20773 20774 @Override 20775 public Float get(View object) { 20776 return object.getX(); 20777 } 20778 }; 20779 20780 /** 20781 * A Property wrapper around the <code>y</code> functionality handled by the 20782 * {@link View#setY(float)} and {@link View#getY()} methods. 20783 */ 20784 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 20785 @Override 20786 public void setValue(View object, float value) { 20787 object.setY(value); 20788 } 20789 20790 @Override 20791 public Float get(View object) { 20792 return object.getY(); 20793 } 20794 }; 20795 20796 /** 20797 * A Property wrapper around the <code>z</code> functionality handled by the 20798 * {@link View#setZ(float)} and {@link View#getZ()} methods. 20799 */ 20800 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 20801 @Override 20802 public void setValue(View object, float value) { 20803 object.setZ(value); 20804 } 20805 20806 @Override 20807 public Float get(View object) { 20808 return object.getZ(); 20809 } 20810 }; 20811 20812 /** 20813 * A Property wrapper around the <code>rotation</code> functionality handled by the 20814 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 20815 */ 20816 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 20817 @Override 20818 public void setValue(View object, float value) { 20819 object.setRotation(value); 20820 } 20821 20822 @Override 20823 public Float get(View object) { 20824 return object.getRotation(); 20825 } 20826 }; 20827 20828 /** 20829 * A Property wrapper around the <code>rotationX</code> functionality handled by the 20830 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 20831 */ 20832 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 20833 @Override 20834 public void setValue(View object, float value) { 20835 object.setRotationX(value); 20836 } 20837 20838 @Override 20839 public Float get(View object) { 20840 return object.getRotationX(); 20841 } 20842 }; 20843 20844 /** 20845 * A Property wrapper around the <code>rotationY</code> functionality handled by the 20846 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 20847 */ 20848 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 20849 @Override 20850 public void setValue(View object, float value) { 20851 object.setRotationY(value); 20852 } 20853 20854 @Override 20855 public Float get(View object) { 20856 return object.getRotationY(); 20857 } 20858 }; 20859 20860 /** 20861 * A Property wrapper around the <code>scaleX</code> functionality handled by the 20862 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 20863 */ 20864 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 20865 @Override 20866 public void setValue(View object, float value) { 20867 object.setScaleX(value); 20868 } 20869 20870 @Override 20871 public Float get(View object) { 20872 return object.getScaleX(); 20873 } 20874 }; 20875 20876 /** 20877 * A Property wrapper around the <code>scaleY</code> functionality handled by the 20878 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 20879 */ 20880 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 20881 @Override 20882 public void setValue(View object, float value) { 20883 object.setScaleY(value); 20884 } 20885 20886 @Override 20887 public Float get(View object) { 20888 return object.getScaleY(); 20889 } 20890 }; 20891 20892 /** 20893 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 20894 * Each MeasureSpec represents a requirement for either the width or the height. 20895 * A MeasureSpec is comprised of a size and a mode. There are three possible 20896 * modes: 20897 * <dl> 20898 * <dt>UNSPECIFIED</dt> 20899 * <dd> 20900 * The parent has not imposed any constraint on the child. It can be whatever size 20901 * it wants. 20902 * </dd> 20903 * 20904 * <dt>EXACTLY</dt> 20905 * <dd> 20906 * The parent has determined an exact size for the child. The child is going to be 20907 * given those bounds regardless of how big it wants to be. 20908 * </dd> 20909 * 20910 * <dt>AT_MOST</dt> 20911 * <dd> 20912 * The child can be as large as it wants up to the specified size. 20913 * </dd> 20914 * </dl> 20915 * 20916 * MeasureSpecs are implemented as ints to reduce object allocation. This class 20917 * is provided to pack and unpack the <size, mode> tuple into the int. 20918 */ 20919 public static class MeasureSpec { 20920 private static final int MODE_SHIFT = 30; 20921 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 20922 20923 /** 20924 * Measure specification mode: The parent has not imposed any constraint 20925 * on the child. It can be whatever size it wants. 20926 */ 20927 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 20928 20929 /** 20930 * Measure specification mode: The parent has determined an exact size 20931 * for the child. The child is going to be given those bounds regardless 20932 * of how big it wants to be. 20933 */ 20934 public static final int EXACTLY = 1 << MODE_SHIFT; 20935 20936 /** 20937 * Measure specification mode: The child can be as large as it wants up 20938 * to the specified size. 20939 */ 20940 public static final int AT_MOST = 2 << MODE_SHIFT; 20941 20942 /** 20943 * Creates a measure specification based on the supplied size and mode. 20944 * 20945 * The mode must always be one of the following: 20946 * <ul> 20947 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 20948 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 20949 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 20950 * </ul> 20951 * 20952 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 20953 * implementation was such that the order of arguments did not matter 20954 * and overflow in either value could impact the resulting MeasureSpec. 20955 * {@link android.widget.RelativeLayout} was affected by this bug. 20956 * Apps targeting API levels greater than 17 will get the fixed, more strict 20957 * behavior.</p> 20958 * 20959 * @param size the size of the measure specification 20960 * @param mode the mode of the measure specification 20961 * @return the measure specification based on size and mode 20962 */ 20963 public static int makeMeasureSpec(int size, int mode) { 20964 if (sUseBrokenMakeMeasureSpec) { 20965 return size + mode; 20966 } else { 20967 return (size & ~MODE_MASK) | (mode & MODE_MASK); 20968 } 20969 } 20970 20971 /** 20972 * Extracts the mode from the supplied measure specification. 20973 * 20974 * @param measureSpec the measure specification to extract the mode from 20975 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 20976 * {@link android.view.View.MeasureSpec#AT_MOST} or 20977 * {@link android.view.View.MeasureSpec#EXACTLY} 20978 */ 20979 public static int getMode(int measureSpec) { 20980 return (measureSpec & MODE_MASK); 20981 } 20982 20983 /** 20984 * Extracts the size from the supplied measure specification. 20985 * 20986 * @param measureSpec the measure specification to extract the size from 20987 * @return the size in pixels defined in the supplied measure specification 20988 */ 20989 public static int getSize(int measureSpec) { 20990 return (measureSpec & ~MODE_MASK); 20991 } 20992 20993 static int adjust(int measureSpec, int delta) { 20994 final int mode = getMode(measureSpec); 20995 int size = getSize(measureSpec); 20996 if (mode == UNSPECIFIED) { 20997 // No need to adjust size for UNSPECIFIED mode. 20998 return makeMeasureSpec(size, UNSPECIFIED); 20999 } 21000 size += delta; 21001 if (size < 0) { 21002 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 21003 ") spec: " + toString(measureSpec) + " delta: " + delta); 21004 size = 0; 21005 } 21006 return makeMeasureSpec(size, mode); 21007 } 21008 21009 /** 21010 * Returns a String representation of the specified measure 21011 * specification. 21012 * 21013 * @param measureSpec the measure specification to convert to a String 21014 * @return a String with the following format: "MeasureSpec: MODE SIZE" 21015 */ 21016 public static String toString(int measureSpec) { 21017 int mode = getMode(measureSpec); 21018 int size = getSize(measureSpec); 21019 21020 StringBuilder sb = new StringBuilder("MeasureSpec: "); 21021 21022 if (mode == UNSPECIFIED) 21023 sb.append("UNSPECIFIED "); 21024 else if (mode == EXACTLY) 21025 sb.append("EXACTLY "); 21026 else if (mode == AT_MOST) 21027 sb.append("AT_MOST "); 21028 else 21029 sb.append(mode).append(" "); 21030 21031 sb.append(size); 21032 return sb.toString(); 21033 } 21034 } 21035 21036 private final class CheckForLongPress implements Runnable { 21037 private int mOriginalWindowAttachCount; 21038 21039 @Override 21040 public void run() { 21041 if (isPressed() && (mParent != null) 21042 && mOriginalWindowAttachCount == mWindowAttachCount) { 21043 if (performLongClick()) { 21044 mHasPerformedLongPress = true; 21045 } 21046 } 21047 } 21048 21049 public void rememberWindowAttachCount() { 21050 mOriginalWindowAttachCount = mWindowAttachCount; 21051 } 21052 } 21053 21054 private final class CheckForTap implements Runnable { 21055 public float x; 21056 public float y; 21057 21058 @Override 21059 public void run() { 21060 mPrivateFlags &= ~PFLAG_PREPRESSED; 21061 setPressed(true, x, y); 21062 checkForLongClick(ViewConfiguration.getTapTimeout()); 21063 } 21064 } 21065 21066 private final class PerformClick implements Runnable { 21067 @Override 21068 public void run() { 21069 performClick(); 21070 } 21071 } 21072 21073 /** @hide */ 21074 public void hackTurnOffWindowResizeAnim(boolean off) { 21075 mAttachInfo.mTurnOffWindowResizeAnim = off; 21076 } 21077 21078 /** 21079 * This method returns a ViewPropertyAnimator object, which can be used to animate 21080 * specific properties on this View. 21081 * 21082 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 21083 */ 21084 public ViewPropertyAnimator animate() { 21085 if (mAnimator == null) { 21086 mAnimator = new ViewPropertyAnimator(this); 21087 } 21088 return mAnimator; 21089 } 21090 21091 /** 21092 * Sets the name of the View to be used to identify Views in Transitions. 21093 * Names should be unique in the View hierarchy. 21094 * 21095 * @param transitionName The name of the View to uniquely identify it for Transitions. 21096 */ 21097 public final void setTransitionName(String transitionName) { 21098 mTransitionName = transitionName; 21099 } 21100 21101 /** 21102 * Returns the name of the View to be used to identify Views in Transitions. 21103 * Names should be unique in the View hierarchy. 21104 * 21105 * <p>This returns null if the View has not been given a name.</p> 21106 * 21107 * @return The name used of the View to be used to identify Views in Transitions or null 21108 * if no name has been given. 21109 */ 21110 @ViewDebug.ExportedProperty 21111 public String getTransitionName() { 21112 return mTransitionName; 21113 } 21114 21115 /** 21116 * Interface definition for a callback to be invoked when a hardware key event is 21117 * dispatched to this view. The callback will be invoked before the key event is 21118 * given to the view. This is only useful for hardware keyboards; a software input 21119 * method has no obligation to trigger this listener. 21120 */ 21121 public interface OnKeyListener { 21122 /** 21123 * Called when a hardware key is dispatched to a view. This allows listeners to 21124 * get a chance to respond before the target view. 21125 * <p>Key presses in software keyboards will generally NOT trigger this method, 21126 * although some may elect to do so in some situations. Do not assume a 21127 * software input method has to be key-based; even if it is, it may use key presses 21128 * in a different way than you expect, so there is no way to reliably catch soft 21129 * input key presses. 21130 * 21131 * @param v The view the key has been dispatched to. 21132 * @param keyCode The code for the physical key that was pressed 21133 * @param event The KeyEvent object containing full information about 21134 * the event. 21135 * @return True if the listener has consumed the event, false otherwise. 21136 */ 21137 boolean onKey(View v, int keyCode, KeyEvent event); 21138 } 21139 21140 /** 21141 * Interface definition for a callback to be invoked when a touch event is 21142 * dispatched to this view. The callback will be invoked before the touch 21143 * event is given to the view. 21144 */ 21145 public interface OnTouchListener { 21146 /** 21147 * Called when a touch event is dispatched to a view. This allows listeners to 21148 * get a chance to respond before the target view. 21149 * 21150 * @param v The view the touch event has been dispatched to. 21151 * @param event The MotionEvent object containing full information about 21152 * the event. 21153 * @return True if the listener has consumed the event, false otherwise. 21154 */ 21155 boolean onTouch(View v, MotionEvent event); 21156 } 21157 21158 /** 21159 * Interface definition for a callback to be invoked when a hover event is 21160 * dispatched to this view. The callback will be invoked before the hover 21161 * event is given to the view. 21162 */ 21163 public interface OnHoverListener { 21164 /** 21165 * Called when a hover event is dispatched to a view. This allows listeners to 21166 * get a chance to respond before the target view. 21167 * 21168 * @param v The view the hover event has been dispatched to. 21169 * @param event The MotionEvent object containing full information about 21170 * the event. 21171 * @return True if the listener has consumed the event, false otherwise. 21172 */ 21173 boolean onHover(View v, MotionEvent event); 21174 } 21175 21176 /** 21177 * Interface definition for a callback to be invoked when a generic motion event is 21178 * dispatched to this view. The callback will be invoked before the generic motion 21179 * event is given to the view. 21180 */ 21181 public interface OnGenericMotionListener { 21182 /** 21183 * Called when a generic motion event is dispatched to a view. This allows listeners to 21184 * get a chance to respond before the target view. 21185 * 21186 * @param v The view the generic motion event has been dispatched to. 21187 * @param event The MotionEvent object containing full information about 21188 * the event. 21189 * @return True if the listener has consumed the event, false otherwise. 21190 */ 21191 boolean onGenericMotion(View v, MotionEvent event); 21192 } 21193 21194 /** 21195 * Interface definition for a callback to be invoked when a view has been clicked and held. 21196 */ 21197 public interface OnLongClickListener { 21198 /** 21199 * Called when a view has been clicked and held. 21200 * 21201 * @param v The view that was clicked and held. 21202 * 21203 * @return true if the callback consumed the long click, false otherwise. 21204 */ 21205 boolean onLongClick(View v); 21206 } 21207 21208 /** 21209 * Interface definition for a callback to be invoked when a drag is being dispatched 21210 * to this view. The callback will be invoked before the hosting view's own 21211 * onDrag(event) method. If the listener wants to fall back to the hosting view's 21212 * onDrag(event) behavior, it should return 'false' from this callback. 21213 * 21214 * <div class="special reference"> 21215 * <h3>Developer Guides</h3> 21216 * <p>For a guide to implementing drag and drop features, read the 21217 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 21218 * </div> 21219 */ 21220 public interface OnDragListener { 21221 /** 21222 * Called when a drag event is dispatched to a view. This allows listeners 21223 * to get a chance to override base View behavior. 21224 * 21225 * @param v The View that received the drag event. 21226 * @param event The {@link android.view.DragEvent} object for the drag event. 21227 * @return {@code true} if the drag event was handled successfully, or {@code false} 21228 * if the drag event was not handled. Note that {@code false} will trigger the View 21229 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 21230 */ 21231 boolean onDrag(View v, DragEvent event); 21232 } 21233 21234 /** 21235 * Interface definition for a callback to be invoked when the focus state of 21236 * a view changed. 21237 */ 21238 public interface OnFocusChangeListener { 21239 /** 21240 * Called when the focus state of a view has changed. 21241 * 21242 * @param v The view whose state has changed. 21243 * @param hasFocus The new focus state of v. 21244 */ 21245 void onFocusChange(View v, boolean hasFocus); 21246 } 21247 21248 /** 21249 * Interface definition for a callback to be invoked when a view is clicked. 21250 */ 21251 public interface OnClickListener { 21252 /** 21253 * Called when a view has been clicked. 21254 * 21255 * @param v The view that was clicked. 21256 */ 21257 void onClick(View v); 21258 } 21259 21260 /** 21261 * Interface definition for a callback to be invoked when a view is touched with a stylus while 21262 * the stylus button is pressed. 21263 */ 21264 public interface OnStylusButtonPressListener { 21265 /** 21266 * Called when a view is touched with a stylus while the stylus button is pressed. 21267 * 21268 * @param v The view that was touched. 21269 * @return true if the callback consumed the stylus button press, false otherwise. 21270 */ 21271 boolean onStylusButtonPress(View v); 21272 } 21273 21274 /** 21275 * Interface definition for a callback to be invoked when the context menu 21276 * for this view is being built. 21277 */ 21278 public interface OnCreateContextMenuListener { 21279 /** 21280 * Called when the context menu for this view is being built. It is not 21281 * safe to hold onto the menu after this method returns. 21282 * 21283 * @param menu The context menu that is being built 21284 * @param v The view for which the context menu is being built 21285 * @param menuInfo Extra information about the item for which the 21286 * context menu should be shown. This information will vary 21287 * depending on the class of v. 21288 */ 21289 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 21290 } 21291 21292 /** 21293 * Interface definition for a callback to be invoked when the status bar changes 21294 * visibility. This reports <strong>global</strong> changes to the system UI 21295 * state, not what the application is requesting. 21296 * 21297 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 21298 */ 21299 public interface OnSystemUiVisibilityChangeListener { 21300 /** 21301 * Called when the status bar changes visibility because of a call to 21302 * {@link View#setSystemUiVisibility(int)}. 21303 * 21304 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 21305 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 21306 * This tells you the <strong>global</strong> state of these UI visibility 21307 * flags, not what your app is currently applying. 21308 */ 21309 public void onSystemUiVisibilityChange(int visibility); 21310 } 21311 21312 /** 21313 * Interface definition for a callback to be invoked when this view is attached 21314 * or detached from its window. 21315 */ 21316 public interface OnAttachStateChangeListener { 21317 /** 21318 * Called when the view is attached to a window. 21319 * @param v The view that was attached 21320 */ 21321 public void onViewAttachedToWindow(View v); 21322 /** 21323 * Called when the view is detached from a window. 21324 * @param v The view that was detached 21325 */ 21326 public void onViewDetachedFromWindow(View v); 21327 } 21328 21329 /** 21330 * Listener for applying window insets on a view in a custom way. 21331 * 21332 * <p>Apps may choose to implement this interface if they want to apply custom policy 21333 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 21334 * is set, its 21335 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 21336 * method will be called instead of the View's own 21337 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 21338 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 21339 * the View's normal behavior as part of its own.</p> 21340 */ 21341 public interface OnApplyWindowInsetsListener { 21342 /** 21343 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 21344 * on a View, this listener method will be called instead of the view's own 21345 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 21346 * 21347 * @param v The view applying window insets 21348 * @param insets The insets to apply 21349 * @return The insets supplied, minus any insets that were consumed 21350 */ 21351 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 21352 } 21353 21354 private final class UnsetPressedState implements Runnable { 21355 @Override 21356 public void run() { 21357 setPressed(false); 21358 } 21359 } 21360 21361 /** 21362 * Base class for derived classes that want to save and restore their own 21363 * state in {@link android.view.View#onSaveInstanceState()}. 21364 */ 21365 public static class BaseSavedState extends AbsSavedState { 21366 String mStartActivityRequestWhoSaved; 21367 21368 /** 21369 * Constructor used when reading from a parcel. Reads the state of the superclass. 21370 * 21371 * @param source 21372 */ 21373 public BaseSavedState(Parcel source) { 21374 super(source); 21375 mStartActivityRequestWhoSaved = source.readString(); 21376 } 21377 21378 /** 21379 * Constructor called by derived classes when creating their SavedState objects 21380 * 21381 * @param superState The state of the superclass of this view 21382 */ 21383 public BaseSavedState(Parcelable superState) { 21384 super(superState); 21385 } 21386 21387 @Override 21388 public void writeToParcel(Parcel out, int flags) { 21389 super.writeToParcel(out, flags); 21390 out.writeString(mStartActivityRequestWhoSaved); 21391 } 21392 21393 public static final Parcelable.Creator<BaseSavedState> CREATOR = 21394 new Parcelable.Creator<BaseSavedState>() { 21395 public BaseSavedState createFromParcel(Parcel in) { 21396 return new BaseSavedState(in); 21397 } 21398 21399 public BaseSavedState[] newArray(int size) { 21400 return new BaseSavedState[size]; 21401 } 21402 }; 21403 } 21404 21405 /** 21406 * A set of information given to a view when it is attached to its parent 21407 * window. 21408 */ 21409 final static class AttachInfo { 21410 interface Callbacks { 21411 void playSoundEffect(int effectId); 21412 boolean performHapticFeedback(int effectId, boolean always); 21413 } 21414 21415 /** 21416 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 21417 * to a Handler. This class contains the target (View) to invalidate and 21418 * the coordinates of the dirty rectangle. 21419 * 21420 * For performance purposes, this class also implements a pool of up to 21421 * POOL_LIMIT objects that get reused. This reduces memory allocations 21422 * whenever possible. 21423 */ 21424 static class InvalidateInfo { 21425 private static final int POOL_LIMIT = 10; 21426 21427 private static final SynchronizedPool<InvalidateInfo> sPool = 21428 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 21429 21430 View target; 21431 21432 int left; 21433 int top; 21434 int right; 21435 int bottom; 21436 21437 public static InvalidateInfo obtain() { 21438 InvalidateInfo instance = sPool.acquire(); 21439 return (instance != null) ? instance : new InvalidateInfo(); 21440 } 21441 21442 public void recycle() { 21443 target = null; 21444 sPool.release(this); 21445 } 21446 } 21447 21448 final IWindowSession mSession; 21449 21450 final IWindow mWindow; 21451 21452 final IBinder mWindowToken; 21453 21454 final Display mDisplay; 21455 21456 final Callbacks mRootCallbacks; 21457 21458 IWindowId mIWindowId; 21459 WindowId mWindowId; 21460 21461 /** 21462 * The top view of the hierarchy. 21463 */ 21464 View mRootView; 21465 21466 IBinder mPanelParentWindowToken; 21467 21468 boolean mHardwareAccelerated; 21469 boolean mHardwareAccelerationRequested; 21470 HardwareRenderer mHardwareRenderer; 21471 List<RenderNode> mPendingAnimatingRenderNodes; 21472 21473 /** 21474 * The state of the display to which the window is attached, as reported 21475 * by {@link Display#getState()}. Note that the display state constants 21476 * declared by {@link Display} do not exactly line up with the screen state 21477 * constants declared by {@link View} (there are more display states than 21478 * screen states). 21479 */ 21480 int mDisplayState = Display.STATE_UNKNOWN; 21481 21482 /** 21483 * Scale factor used by the compatibility mode 21484 */ 21485 float mApplicationScale; 21486 21487 /** 21488 * Indicates whether the application is in compatibility mode 21489 */ 21490 boolean mScalingRequired; 21491 21492 /** 21493 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 21494 */ 21495 boolean mTurnOffWindowResizeAnim; 21496 21497 /** 21498 * Left position of this view's window 21499 */ 21500 int mWindowLeft; 21501 21502 /** 21503 * Top position of this view's window 21504 */ 21505 int mWindowTop; 21506 21507 /** 21508 * Indicates whether views need to use 32-bit drawing caches 21509 */ 21510 boolean mUse32BitDrawingCache; 21511 21512 /** 21513 * For windows that are full-screen but using insets to layout inside 21514 * of the screen areas, these are the current insets to appear inside 21515 * the overscan area of the display. 21516 */ 21517 final Rect mOverscanInsets = new Rect(); 21518 21519 /** 21520 * For windows that are full-screen but using insets to layout inside 21521 * of the screen decorations, these are the current insets for the 21522 * content of the window. 21523 */ 21524 final Rect mContentInsets = new Rect(); 21525 21526 /** 21527 * For windows that are full-screen but using insets to layout inside 21528 * of the screen decorations, these are the current insets for the 21529 * actual visible parts of the window. 21530 */ 21531 final Rect mVisibleInsets = new Rect(); 21532 21533 /** 21534 * For windows that are full-screen but using insets to layout inside 21535 * of the screen decorations, these are the current insets for the 21536 * stable system windows. 21537 */ 21538 final Rect mStableInsets = new Rect(); 21539 21540 /** 21541 * The internal insets given by this window. This value is 21542 * supplied by the client (through 21543 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 21544 * be given to the window manager when changed to be used in laying 21545 * out windows behind it. 21546 */ 21547 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 21548 = new ViewTreeObserver.InternalInsetsInfo(); 21549 21550 /** 21551 * Set to true when mGivenInternalInsets is non-empty. 21552 */ 21553 boolean mHasNonEmptyGivenInternalInsets; 21554 21555 /** 21556 * All views in the window's hierarchy that serve as scroll containers, 21557 * used to determine if the window can be resized or must be panned 21558 * to adjust for a soft input area. 21559 */ 21560 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 21561 21562 final KeyEvent.DispatcherState mKeyDispatchState 21563 = new KeyEvent.DispatcherState(); 21564 21565 /** 21566 * Indicates whether the view's window currently has the focus. 21567 */ 21568 boolean mHasWindowFocus; 21569 21570 /** 21571 * The current visibility of the window. 21572 */ 21573 int mWindowVisibility; 21574 21575 /** 21576 * Indicates the time at which drawing started to occur. 21577 */ 21578 long mDrawingTime; 21579 21580 /** 21581 * Indicates whether or not ignoring the DIRTY_MASK flags. 21582 */ 21583 boolean mIgnoreDirtyState; 21584 21585 /** 21586 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 21587 * to avoid clearing that flag prematurely. 21588 */ 21589 boolean mSetIgnoreDirtyState = false; 21590 21591 /** 21592 * Indicates whether the view's window is currently in touch mode. 21593 */ 21594 boolean mInTouchMode; 21595 21596 /** 21597 * Indicates whether the view has requested unbuffered input dispatching for the current 21598 * event stream. 21599 */ 21600 boolean mUnbufferedDispatchRequested; 21601 21602 /** 21603 * Indicates that ViewAncestor should trigger a global layout change 21604 * the next time it performs a traversal 21605 */ 21606 boolean mRecomputeGlobalAttributes; 21607 21608 /** 21609 * Always report new attributes at next traversal. 21610 */ 21611 boolean mForceReportNewAttributes; 21612 21613 /** 21614 * Set during a traveral if any views want to keep the screen on. 21615 */ 21616 boolean mKeepScreenOn; 21617 21618 /** 21619 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 21620 */ 21621 int mSystemUiVisibility; 21622 21623 /** 21624 * Hack to force certain system UI visibility flags to be cleared. 21625 */ 21626 int mDisabledSystemUiVisibility; 21627 21628 /** 21629 * Last global system UI visibility reported by the window manager. 21630 */ 21631 int mGlobalSystemUiVisibility; 21632 21633 /** 21634 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 21635 * attached. 21636 */ 21637 boolean mHasSystemUiListeners; 21638 21639 /** 21640 * Set if the window has requested to extend into the overscan region 21641 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 21642 */ 21643 boolean mOverscanRequested; 21644 21645 /** 21646 * Set if the visibility of any views has changed. 21647 */ 21648 boolean mViewVisibilityChanged; 21649 21650 /** 21651 * Set to true if a view has been scrolled. 21652 */ 21653 boolean mViewScrollChanged; 21654 21655 /** 21656 * Set to true if high contrast mode enabled 21657 */ 21658 boolean mHighContrastText; 21659 21660 /** 21661 * Global to the view hierarchy used as a temporary for dealing with 21662 * x/y points in the transparent region computations. 21663 */ 21664 final int[] mTransparentLocation = new int[2]; 21665 21666 /** 21667 * Global to the view hierarchy used as a temporary for dealing with 21668 * x/y points in the ViewGroup.invalidateChild implementation. 21669 */ 21670 final int[] mInvalidateChildLocation = new int[2]; 21671 21672 /** 21673 * Global to the view hierarchy used as a temporary for dealng with 21674 * computing absolute on-screen location. 21675 */ 21676 final int[] mTmpLocation = new int[2]; 21677 21678 /** 21679 * Global to the view hierarchy used as a temporary for dealing with 21680 * x/y location when view is transformed. 21681 */ 21682 final float[] mTmpTransformLocation = new float[2]; 21683 21684 /** 21685 * The view tree observer used to dispatch global events like 21686 * layout, pre-draw, touch mode change, etc. 21687 */ 21688 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 21689 21690 /** 21691 * A Canvas used by the view hierarchy to perform bitmap caching. 21692 */ 21693 Canvas mCanvas; 21694 21695 /** 21696 * The view root impl. 21697 */ 21698 final ViewRootImpl mViewRootImpl; 21699 21700 /** 21701 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 21702 * handler can be used to pump events in the UI events queue. 21703 */ 21704 final Handler mHandler; 21705 21706 /** 21707 * Temporary for use in computing invalidate rectangles while 21708 * calling up the hierarchy. 21709 */ 21710 final Rect mTmpInvalRect = new Rect(); 21711 21712 /** 21713 * Temporary for use in computing hit areas with transformed views 21714 */ 21715 final RectF mTmpTransformRect = new RectF(); 21716 21717 /** 21718 * Temporary for use in computing hit areas with transformed views 21719 */ 21720 final RectF mTmpTransformRect1 = new RectF(); 21721 21722 /** 21723 * Temporary list of rectanges. 21724 */ 21725 final List<RectF> mTmpRectList = new ArrayList<>(); 21726 21727 /** 21728 * Temporary for use in transforming invalidation rect 21729 */ 21730 final Matrix mTmpMatrix = new Matrix(); 21731 21732 /** 21733 * Temporary for use in transforming invalidation rect 21734 */ 21735 final Transformation mTmpTransformation = new Transformation(); 21736 21737 /** 21738 * Temporary for use in querying outlines from OutlineProviders 21739 */ 21740 final Outline mTmpOutline = new Outline(); 21741 21742 /** 21743 * Temporary list for use in collecting focusable descendents of a view. 21744 */ 21745 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 21746 21747 /** 21748 * The id of the window for accessibility purposes. 21749 */ 21750 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 21751 21752 /** 21753 * Flags related to accessibility processing. 21754 * 21755 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 21756 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 21757 */ 21758 int mAccessibilityFetchFlags; 21759 21760 /** 21761 * The drawable for highlighting accessibility focus. 21762 */ 21763 Drawable mAccessibilityFocusDrawable; 21764 21765 /** 21766 * Show where the margins, bounds and layout bounds are for each view. 21767 */ 21768 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 21769 21770 /** 21771 * Point used to compute visible regions. 21772 */ 21773 final Point mPoint = new Point(); 21774 21775 /** 21776 * Used to track which View originated a requestLayout() call, used when 21777 * requestLayout() is called during layout. 21778 */ 21779 View mViewRequestingLayout; 21780 21781 /** 21782 * Creates a new set of attachment information with the specified 21783 * events handler and thread. 21784 * 21785 * @param handler the events handler the view must use 21786 */ 21787 AttachInfo(IWindowSession session, IWindow window, Display display, 21788 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 21789 mSession = session; 21790 mWindow = window; 21791 mWindowToken = window.asBinder(); 21792 mDisplay = display; 21793 mViewRootImpl = viewRootImpl; 21794 mHandler = handler; 21795 mRootCallbacks = effectPlayer; 21796 } 21797 } 21798 21799 /** 21800 * <p>ScrollabilityCache holds various fields used by a View when scrolling 21801 * is supported. This avoids keeping too many unused fields in most 21802 * instances of View.</p> 21803 */ 21804 private static class ScrollabilityCache implements Runnable { 21805 21806 /** 21807 * Scrollbars are not visible 21808 */ 21809 public static final int OFF = 0; 21810 21811 /** 21812 * Scrollbars are visible 21813 */ 21814 public static final int ON = 1; 21815 21816 /** 21817 * Scrollbars are fading away 21818 */ 21819 public static final int FADING = 2; 21820 21821 public boolean fadeScrollBars; 21822 21823 public int fadingEdgeLength; 21824 public int scrollBarDefaultDelayBeforeFade; 21825 public int scrollBarFadeDuration; 21826 21827 public int scrollBarSize; 21828 public ScrollBarDrawable scrollBar; 21829 public float[] interpolatorValues; 21830 public View host; 21831 21832 public final Paint paint; 21833 public final Matrix matrix; 21834 public Shader shader; 21835 21836 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 21837 21838 private static final float[] OPAQUE = { 255 }; 21839 private static final float[] TRANSPARENT = { 0.0f }; 21840 21841 /** 21842 * When fading should start. This time moves into the future every time 21843 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 21844 */ 21845 public long fadeStartTime; 21846 21847 21848 /** 21849 * The current state of the scrollbars: ON, OFF, or FADING 21850 */ 21851 public int state = OFF; 21852 21853 private int mLastColor; 21854 21855 public ScrollabilityCache(ViewConfiguration configuration, View host) { 21856 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 21857 scrollBarSize = configuration.getScaledScrollBarSize(); 21858 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 21859 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 21860 21861 paint = new Paint(); 21862 matrix = new Matrix(); 21863 // use use a height of 1, and then wack the matrix each time we 21864 // actually use it. 21865 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 21866 paint.setShader(shader); 21867 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 21868 21869 this.host = host; 21870 } 21871 21872 public void setFadeColor(int color) { 21873 if (color != mLastColor) { 21874 mLastColor = color; 21875 21876 if (color != 0) { 21877 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 21878 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 21879 paint.setShader(shader); 21880 // Restore the default transfer mode (src_over) 21881 paint.setXfermode(null); 21882 } else { 21883 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 21884 paint.setShader(shader); 21885 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 21886 } 21887 } 21888 } 21889 21890 public void run() { 21891 long now = AnimationUtils.currentAnimationTimeMillis(); 21892 if (now >= fadeStartTime) { 21893 21894 // the animation fades the scrollbars out by changing 21895 // the opacity (alpha) from fully opaque to fully 21896 // transparent 21897 int nextFrame = (int) now; 21898 int framesCount = 0; 21899 21900 Interpolator interpolator = scrollBarInterpolator; 21901 21902 // Start opaque 21903 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 21904 21905 // End transparent 21906 nextFrame += scrollBarFadeDuration; 21907 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 21908 21909 state = FADING; 21910 21911 // Kick off the fade animation 21912 host.invalidate(true); 21913 } 21914 } 21915 } 21916 21917 /** 21918 * Resuable callback for sending 21919 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 21920 */ 21921 private class SendViewScrolledAccessibilityEvent implements Runnable { 21922 public volatile boolean mIsPending; 21923 21924 public void run() { 21925 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 21926 mIsPending = false; 21927 } 21928 } 21929 21930 /** 21931 * <p> 21932 * This class represents a delegate that can be registered in a {@link View} 21933 * to enhance accessibility support via composition rather via inheritance. 21934 * It is specifically targeted to widget developers that extend basic View 21935 * classes i.e. classes in package android.view, that would like their 21936 * applications to be backwards compatible. 21937 * </p> 21938 * <div class="special reference"> 21939 * <h3>Developer Guides</h3> 21940 * <p>For more information about making applications accessible, read the 21941 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 21942 * developer guide.</p> 21943 * </div> 21944 * <p> 21945 * A scenario in which a developer would like to use an accessibility delegate 21946 * is overriding a method introduced in a later API version then the minimal API 21947 * version supported by the application. For example, the method 21948 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 21949 * in API version 4 when the accessibility APIs were first introduced. If a 21950 * developer would like his application to run on API version 4 devices (assuming 21951 * all other APIs used by the application are version 4 or lower) and take advantage 21952 * of this method, instead of overriding the method which would break the application's 21953 * backwards compatibility, he can override the corresponding method in this 21954 * delegate and register the delegate in the target View if the API version of 21955 * the system is high enough i.e. the API version is same or higher to the API 21956 * version that introduced 21957 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 21958 * </p> 21959 * <p> 21960 * Here is an example implementation: 21961 * </p> 21962 * <code><pre><p> 21963 * if (Build.VERSION.SDK_INT >= 14) { 21964 * // If the API version is equal of higher than the version in 21965 * // which onInitializeAccessibilityNodeInfo was introduced we 21966 * // register a delegate with a customized implementation. 21967 * View view = findViewById(R.id.view_id); 21968 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 21969 * public void onInitializeAccessibilityNodeInfo(View host, 21970 * AccessibilityNodeInfo info) { 21971 * // Let the default implementation populate the info. 21972 * super.onInitializeAccessibilityNodeInfo(host, info); 21973 * // Set some other information. 21974 * info.setEnabled(host.isEnabled()); 21975 * } 21976 * }); 21977 * } 21978 * </code></pre></p> 21979 * <p> 21980 * This delegate contains methods that correspond to the accessibility methods 21981 * in View. If a delegate has been specified the implementation in View hands 21982 * off handling to the corresponding method in this delegate. The default 21983 * implementation the delegate methods behaves exactly as the corresponding 21984 * method in View for the case of no accessibility delegate been set. Hence, 21985 * to customize the behavior of a View method, clients can override only the 21986 * corresponding delegate method without altering the behavior of the rest 21987 * accessibility related methods of the host view. 21988 * </p> 21989 */ 21990 public static class AccessibilityDelegate { 21991 21992 /** 21993 * Sends an accessibility event of the given type. If accessibility is not 21994 * enabled this method has no effect. 21995 * <p> 21996 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 21997 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 21998 * been set. 21999 * </p> 22000 * 22001 * @param host The View hosting the delegate. 22002 * @param eventType The type of the event to send. 22003 * 22004 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 22005 */ 22006 public void sendAccessibilityEvent(View host, int eventType) { 22007 host.sendAccessibilityEventInternal(eventType); 22008 } 22009 22010 /** 22011 * Performs the specified accessibility action on the view. For 22012 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 22013 * <p> 22014 * The default implementation behaves as 22015 * {@link View#performAccessibilityAction(int, Bundle) 22016 * View#performAccessibilityAction(int, Bundle)} for the case of 22017 * no accessibility delegate been set. 22018 * </p> 22019 * 22020 * @param action The action to perform. 22021 * @return Whether the action was performed. 22022 * 22023 * @see View#performAccessibilityAction(int, Bundle) 22024 * View#performAccessibilityAction(int, Bundle) 22025 */ 22026 public boolean performAccessibilityAction(View host, int action, Bundle args) { 22027 return host.performAccessibilityActionInternal(action, args); 22028 } 22029 22030 /** 22031 * Sends an accessibility event. This method behaves exactly as 22032 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 22033 * empty {@link AccessibilityEvent} and does not perform a check whether 22034 * accessibility is enabled. 22035 * <p> 22036 * The default implementation behaves as 22037 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 22038 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 22039 * the case of no accessibility delegate been set. 22040 * </p> 22041 * 22042 * @param host The View hosting the delegate. 22043 * @param event The event to send. 22044 * 22045 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 22046 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 22047 */ 22048 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 22049 host.sendAccessibilityEventUncheckedInternal(event); 22050 } 22051 22052 /** 22053 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 22054 * to its children for adding their text content to the event. 22055 * <p> 22056 * The default implementation behaves as 22057 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 22058 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 22059 * the case of no accessibility delegate been set. 22060 * </p> 22061 * 22062 * @param host The View hosting the delegate. 22063 * @param event The event. 22064 * @return True if the event population was completed. 22065 * 22066 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 22067 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 22068 */ 22069 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 22070 return host.dispatchPopulateAccessibilityEventInternal(event); 22071 } 22072 22073 /** 22074 * Gives a chance to the host View to populate the accessibility event with its 22075 * text content. 22076 * <p> 22077 * The default implementation behaves as 22078 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 22079 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 22080 * the case of no accessibility delegate been set. 22081 * </p> 22082 * 22083 * @param host The View hosting the delegate. 22084 * @param event The accessibility event which to populate. 22085 * 22086 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 22087 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 22088 */ 22089 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 22090 host.onPopulateAccessibilityEventInternal(event); 22091 } 22092 22093 /** 22094 * Initializes an {@link AccessibilityEvent} with information about the 22095 * the host View which is the event source. 22096 * <p> 22097 * The default implementation behaves as 22098 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 22099 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 22100 * the case of no accessibility delegate been set. 22101 * </p> 22102 * 22103 * @param host The View hosting the delegate. 22104 * @param event The event to initialize. 22105 * 22106 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 22107 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 22108 */ 22109 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 22110 host.onInitializeAccessibilityEventInternal(event); 22111 } 22112 22113 /** 22114 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 22115 * <p> 22116 * The default implementation behaves as 22117 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 22118 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 22119 * the case of no accessibility delegate been set. 22120 * </p> 22121 * 22122 * @param host The View hosting the delegate. 22123 * @param info The instance to initialize. 22124 * 22125 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 22126 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 22127 */ 22128 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 22129 host.onInitializeAccessibilityNodeInfoInternal(info); 22130 } 22131 22132 /** 22133 * Called when a child of the host View has requested sending an 22134 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 22135 * to augment the event. 22136 * <p> 22137 * The default implementation behaves as 22138 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 22139 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 22140 * the case of no accessibility delegate been set. 22141 * </p> 22142 * 22143 * @param host The View hosting the delegate. 22144 * @param child The child which requests sending the event. 22145 * @param event The event to be sent. 22146 * @return True if the event should be sent 22147 * 22148 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 22149 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 22150 */ 22151 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 22152 AccessibilityEvent event) { 22153 return host.onRequestSendAccessibilityEventInternal(child, event); 22154 } 22155 22156 /** 22157 * Gets the provider for managing a virtual view hierarchy rooted at this View 22158 * and reported to {@link android.accessibilityservice.AccessibilityService}s 22159 * that explore the window content. 22160 * <p> 22161 * The default implementation behaves as 22162 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 22163 * the case of no accessibility delegate been set. 22164 * </p> 22165 * 22166 * @return The provider. 22167 * 22168 * @see AccessibilityNodeProvider 22169 */ 22170 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 22171 return null; 22172 } 22173 22174 /** 22175 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 22176 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 22177 * This method is responsible for obtaining an accessibility node info from a 22178 * pool of reusable instances and calling 22179 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 22180 * view to initialize the former. 22181 * <p> 22182 * <strong>Note:</strong> The client is responsible for recycling the obtained 22183 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 22184 * creation. 22185 * </p> 22186 * <p> 22187 * The default implementation behaves as 22188 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 22189 * the case of no accessibility delegate been set. 22190 * </p> 22191 * @return A populated {@link AccessibilityNodeInfo}. 22192 * 22193 * @see AccessibilityNodeInfo 22194 * 22195 * @hide 22196 */ 22197 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 22198 return host.createAccessibilityNodeInfoInternal(); 22199 } 22200 } 22201 22202 private class MatchIdPredicate implements Predicate<View> { 22203 public int mId; 22204 22205 @Override 22206 public boolean apply(View view) { 22207 return (view.mID == mId); 22208 } 22209 } 22210 22211 private class MatchLabelForPredicate implements Predicate<View> { 22212 private int mLabeledId; 22213 22214 @Override 22215 public boolean apply(View view) { 22216 return (view.mLabelForId == mLabeledId); 22217 } 22218 } 22219 22220 private class SendViewStateChangedAccessibilityEvent implements Runnable { 22221 private int mChangeTypes = 0; 22222 private boolean mPosted; 22223 private boolean mPostedWithDelay; 22224 private long mLastEventTimeMillis; 22225 22226 @Override 22227 public void run() { 22228 mPosted = false; 22229 mPostedWithDelay = false; 22230 mLastEventTimeMillis = SystemClock.uptimeMillis(); 22231 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 22232 final AccessibilityEvent event = AccessibilityEvent.obtain(); 22233 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 22234 event.setContentChangeTypes(mChangeTypes); 22235 sendAccessibilityEventUnchecked(event); 22236 } 22237 mChangeTypes = 0; 22238 } 22239 22240 public void runOrPost(int changeType) { 22241 mChangeTypes |= changeType; 22242 22243 // If this is a live region or the child of a live region, collect 22244 // all events from this frame and send them on the next frame. 22245 if (inLiveRegion()) { 22246 // If we're already posted with a delay, remove that. 22247 if (mPostedWithDelay) { 22248 removeCallbacks(this); 22249 mPostedWithDelay = false; 22250 } 22251 // Only post if we're not already posted. 22252 if (!mPosted) { 22253 post(this); 22254 mPosted = true; 22255 } 22256 return; 22257 } 22258 22259 if (mPosted) { 22260 return; 22261 } 22262 22263 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 22264 final long minEventIntevalMillis = 22265 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 22266 if (timeSinceLastMillis >= minEventIntevalMillis) { 22267 removeCallbacks(this); 22268 run(); 22269 } else { 22270 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 22271 mPostedWithDelay = true; 22272 } 22273 } 22274 } 22275 22276 private boolean inLiveRegion() { 22277 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 22278 return true; 22279 } 22280 22281 ViewParent parent = getParent(); 22282 while (parent instanceof View) { 22283 if (((View) parent).getAccessibilityLiveRegion() 22284 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 22285 return true; 22286 } 22287 parent = parent.getParent(); 22288 } 22289 22290 return false; 22291 } 22292 22293 /** 22294 * Dump all private flags in readable format, useful for documentation and 22295 * sanity checking. 22296 */ 22297 private static void dumpFlags() { 22298 final HashMap<String, String> found = Maps.newHashMap(); 22299 try { 22300 for (Field field : View.class.getDeclaredFields()) { 22301 final int modifiers = field.getModifiers(); 22302 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 22303 if (field.getType().equals(int.class)) { 22304 final int value = field.getInt(null); 22305 dumpFlag(found, field.getName(), value); 22306 } else if (field.getType().equals(int[].class)) { 22307 final int[] values = (int[]) field.get(null); 22308 for (int i = 0; i < values.length; i++) { 22309 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 22310 } 22311 } 22312 } 22313 } 22314 } catch (IllegalAccessException e) { 22315 throw new RuntimeException(e); 22316 } 22317 22318 final ArrayList<String> keys = Lists.newArrayList(); 22319 keys.addAll(found.keySet()); 22320 Collections.sort(keys); 22321 for (String key : keys) { 22322 Log.d(VIEW_LOG_TAG, found.get(key)); 22323 } 22324 } 22325 22326 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 22327 // Sort flags by prefix, then by bits, always keeping unique keys 22328 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 22329 final int prefix = name.indexOf('_'); 22330 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 22331 final String output = bits + " " + name; 22332 found.put(key, output); 22333 } 22334 22335 /** {@hide} */ 22336 public void encode(@NonNull ViewHierarchyEncoder stream) { 22337 stream.beginObject(this); 22338 encodeProperties(stream); 22339 stream.endObject(); 22340 } 22341 22342 /** {@hide} */ 22343 @CallSuper 22344 protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) { 22345 Object resolveId = ViewDebug.resolveId(getContext(), mID); 22346 if (resolveId instanceof String) { 22347 stream.addProperty("id", (String) resolveId); 22348 } else { 22349 stream.addProperty("id", mID); 22350 } 22351 22352 stream.addProperty("misc:transformation.alpha", 22353 mTransformationInfo != null ? mTransformationInfo.mAlpha : 0); 22354 stream.addProperty("misc:transitionName", getTransitionName()); 22355 22356 // layout 22357 stream.addProperty("layout:left", mLeft); 22358 stream.addProperty("layout:right", mRight); 22359 stream.addProperty("layout:top", mTop); 22360 stream.addProperty("layout:bottom", mBottom); 22361 stream.addProperty("layout:width", getWidth()); 22362 stream.addProperty("layout:height", getHeight()); 22363 stream.addProperty("layout:layoutDirection", getLayoutDirection()); 22364 stream.addProperty("layout:layoutRtl", isLayoutRtl()); 22365 stream.addProperty("layout:hasTransientState", hasTransientState()); 22366 stream.addProperty("layout:baseline", getBaseline()); 22367 22368 // layout params 22369 ViewGroup.LayoutParams layoutParams = getLayoutParams(); 22370 if (layoutParams != null) { 22371 stream.addPropertyKey("layoutParams"); 22372 layoutParams.encode(stream); 22373 } 22374 22375 // scrolling 22376 stream.addProperty("scrolling:scrollX", mScrollX); 22377 stream.addProperty("scrolling:scrollY", mScrollY); 22378 22379 // padding 22380 stream.addProperty("padding:paddingLeft", mPaddingLeft); 22381 stream.addProperty("padding:paddingRight", mPaddingRight); 22382 stream.addProperty("padding:paddingTop", mPaddingTop); 22383 stream.addProperty("padding:paddingBottom", mPaddingBottom); 22384 stream.addProperty("padding:userPaddingRight", mUserPaddingRight); 22385 stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft); 22386 stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom); 22387 stream.addProperty("padding:userPaddingStart", mUserPaddingStart); 22388 stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd); 22389 22390 // measurement 22391 stream.addProperty("measurement:minHeight", mMinHeight); 22392 stream.addProperty("measurement:minWidth", mMinWidth); 22393 stream.addProperty("measurement:measuredWidth", mMeasuredWidth); 22394 stream.addProperty("measurement:measuredHeight", mMeasuredHeight); 22395 22396 // drawing 22397 stream.addProperty("drawing:elevation", getElevation()); 22398 stream.addProperty("drawing:translationX", getTranslationX()); 22399 stream.addProperty("drawing:translationY", getTranslationY()); 22400 stream.addProperty("drawing:translationZ", getTranslationZ()); 22401 stream.addProperty("drawing:rotation", getRotation()); 22402 stream.addProperty("drawing:rotationX", getRotationX()); 22403 stream.addProperty("drawing:rotationY", getRotationY()); 22404 stream.addProperty("drawing:scaleX", getScaleX()); 22405 stream.addProperty("drawing:scaleY", getScaleY()); 22406 stream.addProperty("drawing:pivotX", getPivotX()); 22407 stream.addProperty("drawing:pivotY", getPivotY()); 22408 stream.addProperty("drawing:opaque", isOpaque()); 22409 stream.addProperty("drawing:alpha", getAlpha()); 22410 stream.addProperty("drawing:transitionAlpha", getTransitionAlpha()); 22411 stream.addProperty("drawing:shadow", hasShadow()); 22412 stream.addProperty("drawing:solidColor", getSolidColor()); 22413 stream.addProperty("drawing:layerType", mLayerType); 22414 stream.addProperty("drawing:willNotDraw", willNotDraw()); 22415 stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated()); 22416 stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing()); 22417 stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled()); 22418 stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering()); 22419 22420 // focus 22421 stream.addProperty("focus:hasFocus", hasFocus()); 22422 stream.addProperty("focus:isFocused", isFocused()); 22423 stream.addProperty("focus:isFocusable", isFocusable()); 22424 stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode()); 22425 22426 stream.addProperty("misc:clickable", isClickable()); 22427 stream.addProperty("misc:pressed", isPressed()); 22428 stream.addProperty("misc:selected", isSelected()); 22429 stream.addProperty("misc:touchMode", isInTouchMode()); 22430 stream.addProperty("misc:hovered", isHovered()); 22431 stream.addProperty("misc:activated", isActivated()); 22432 22433 stream.addProperty("misc:visibility", getVisibility()); 22434 stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows()); 22435 stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured()); 22436 22437 stream.addProperty("misc:enabled", isEnabled()); 22438 stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled()); 22439 stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled()); 22440 22441 // theme attributes 22442 Resources.Theme theme = getContext().getTheme(); 22443 if (theme != null) { 22444 stream.addPropertyKey("theme"); 22445 theme.encode(stream); 22446 } 22447 22448 // view attribute information 22449 int n = mAttributes != null ? mAttributes.length : 0; 22450 stream.addProperty("meta:__attrCount__", n/2); 22451 for (int i = 0; i < n; i += 2) { 22452 stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]); 22453 } 22454 22455 stream.addProperty("misc:scrollBarStyle", getScrollBarStyle()); 22456 22457 // text 22458 stream.addProperty("text:textDirection", getTextDirection()); 22459 stream.addProperty("text:textAlignment", getTextAlignment()); 22460 22461 // accessibility 22462 CharSequence contentDescription = getContentDescription(); 22463 stream.addProperty("accessibility:contentDescription", 22464 contentDescription == null ? "" : contentDescription.toString()); 22465 stream.addProperty("accessibility:labelFor", getLabelFor()); 22466 stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility()); 22467 } 22468} 22469