View.java revision 9d744c731295e6ba9b0031f3fb63b0df13e591d8
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.RevealAnimator; 21import android.animation.StateListAnimator; 22import android.animation.ValueAnimator; 23import android.annotation.IntDef; 24import android.annotation.NonNull; 25import android.annotation.Nullable; 26import android.content.ClipData; 27import android.content.Context; 28import android.content.res.Configuration; 29import android.content.res.Resources; 30import android.content.res.TypedArray; 31import android.graphics.Bitmap; 32import android.graphics.Canvas; 33import android.graphics.Insets; 34import android.graphics.Interpolator; 35import android.graphics.LinearGradient; 36import android.graphics.Matrix; 37import android.graphics.Outline; 38import android.graphics.Paint; 39import android.graphics.PixelFormat; 40import android.graphics.Point; 41import android.graphics.PorterDuff; 42import android.graphics.PorterDuffXfermode; 43import android.graphics.Rect; 44import android.graphics.RectF; 45import android.graphics.Region; 46import android.graphics.Shader; 47import android.graphics.drawable.ColorDrawable; 48import android.graphics.drawable.Drawable; 49import android.hardware.display.DisplayManagerGlobal; 50import android.os.Bundle; 51import android.os.Handler; 52import android.os.IBinder; 53import android.os.Parcel; 54import android.os.Parcelable; 55import android.os.RemoteException; 56import android.os.SystemClock; 57import android.os.SystemProperties; 58import android.text.TextUtils; 59import android.util.AttributeSet; 60import android.util.FloatProperty; 61import android.util.LayoutDirection; 62import android.util.Log; 63import android.util.LongSparseLongArray; 64import android.util.Pools.SynchronizedPool; 65import android.util.Property; 66import android.util.SparseArray; 67import android.util.SuperNotCalledException; 68import android.util.TypedValue; 69import android.view.ContextMenu.ContextMenuInfo; 70import android.view.AccessibilityIterators.TextSegmentIterator; 71import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 72import android.view.AccessibilityIterators.WordTextSegmentIterator; 73import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 74import android.view.accessibility.AccessibilityEvent; 75import android.view.accessibility.AccessibilityEventSource; 76import android.view.accessibility.AccessibilityManager; 77import android.view.accessibility.AccessibilityNodeInfo; 78import android.view.accessibility.AccessibilityNodeProvider; 79import android.view.animation.Animation; 80import android.view.animation.AnimationUtils; 81import android.view.animation.Transformation; 82import android.view.inputmethod.EditorInfo; 83import android.view.inputmethod.InputConnection; 84import android.view.inputmethod.InputMethodManager; 85import android.widget.ScrollBarDrawable; 86 87import static android.os.Build.VERSION_CODES.*; 88import static java.lang.Math.max; 89 90import com.android.internal.R; 91import com.android.internal.util.Predicate; 92import com.android.internal.view.menu.MenuBuilder; 93import com.google.android.collect.Lists; 94import com.google.android.collect.Maps; 95 96import java.lang.annotation.Retention; 97import java.lang.annotation.RetentionPolicy; 98import java.lang.ref.WeakReference; 99import java.lang.reflect.Field; 100import java.lang.reflect.InvocationTargetException; 101import java.lang.reflect.Method; 102import java.lang.reflect.Modifier; 103import java.util.ArrayList; 104import java.util.Arrays; 105import java.util.Collections; 106import java.util.HashMap; 107import java.util.List; 108import java.util.Locale; 109import java.util.Map; 110import java.util.concurrent.CopyOnWriteArrayList; 111import java.util.concurrent.atomic.AtomicInteger; 112 113/** 114 * <p> 115 * This class represents the basic building block for user interface components. A View 116 * occupies a rectangular area on the screen and is responsible for drawing and 117 * event handling. View is the base class for <em>widgets</em>, which are 118 * used to create interactive UI components (buttons, text fields, etc.). The 119 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 120 * are invisible containers that hold other Views (or other ViewGroups) and define 121 * their layout properties. 122 * </p> 123 * 124 * <div class="special reference"> 125 * <h3>Developer Guides</h3> 126 * <p>For information about using this class to develop your application's user interface, 127 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 128 * </div> 129 * 130 * <a name="Using"></a> 131 * <h3>Using Views</h3> 132 * <p> 133 * All of the views in a window are arranged in a single tree. You can add views 134 * either from code or by specifying a tree of views in one or more XML layout 135 * files. There are many specialized subclasses of views that act as controls or 136 * are capable of displaying text, images, or other content. 137 * </p> 138 * <p> 139 * Once you have created a tree of views, there are typically a few types of 140 * common operations you may wish to perform: 141 * <ul> 142 * <li><strong>Set properties:</strong> for example setting the text of a 143 * {@link android.widget.TextView}. The available properties and the methods 144 * that set them will vary among the different subclasses of views. Note that 145 * properties that are known at build time can be set in the XML layout 146 * files.</li> 147 * <li><strong>Set focus:</strong> The framework will handled moving focus in 148 * response to user input. To force focus to a specific view, call 149 * {@link #requestFocus}.</li> 150 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 151 * that will be notified when something interesting happens to the view. For 152 * example, all views will let you set a listener to be notified when the view 153 * gains or loses focus. You can register such a listener using 154 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 155 * Other view subclasses offer more specialized listeners. For example, a Button 156 * exposes a listener to notify clients when the button is clicked.</li> 157 * <li><strong>Set visibility:</strong> You can hide or show views using 158 * {@link #setVisibility(int)}.</li> 159 * </ul> 160 * </p> 161 * <p><em> 162 * Note: The Android framework is responsible for measuring, laying out and 163 * drawing views. You should not call methods that perform these actions on 164 * views yourself unless you are actually implementing a 165 * {@link android.view.ViewGroup}. 166 * </em></p> 167 * 168 * <a name="Lifecycle"></a> 169 * <h3>Implementing a Custom View</h3> 170 * 171 * <p> 172 * To implement a custom view, you will usually begin by providing overrides for 173 * some of the standard methods that the framework calls on all views. You do 174 * not need to override all of these methods. In fact, you can start by just 175 * overriding {@link #onDraw(android.graphics.Canvas)}. 176 * <table border="2" width="85%" align="center" cellpadding="5"> 177 * <thead> 178 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 179 * </thead> 180 * 181 * <tbody> 182 * <tr> 183 * <td rowspan="2">Creation</td> 184 * <td>Constructors</td> 185 * <td>There is a form of the constructor that are called when the view 186 * is created from code and a form that is called when the view is 187 * inflated from a layout file. The second form should parse and apply 188 * any attributes defined in the layout file. 189 * </td> 190 * </tr> 191 * <tr> 192 * <td><code>{@link #onFinishInflate()}</code></td> 193 * <td>Called after a view and all of its children has been inflated 194 * from XML.</td> 195 * </tr> 196 * 197 * <tr> 198 * <td rowspan="3">Layout</td> 199 * <td><code>{@link #onMeasure(int, int)}</code></td> 200 * <td>Called to determine the size requirements for this view and all 201 * of its children. 202 * </td> 203 * </tr> 204 * <tr> 205 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 206 * <td>Called when this view should assign a size and position to all 207 * of its children. 208 * </td> 209 * </tr> 210 * <tr> 211 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 212 * <td>Called when the size of this view has changed. 213 * </td> 214 * </tr> 215 * 216 * <tr> 217 * <td>Drawing</td> 218 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 219 * <td>Called when the view should render its content. 220 * </td> 221 * </tr> 222 * 223 * <tr> 224 * <td rowspan="4">Event processing</td> 225 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 226 * <td>Called when a new hardware key event occurs. 227 * </td> 228 * </tr> 229 * <tr> 230 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 231 * <td>Called when a hardware key up event occurs. 232 * </td> 233 * </tr> 234 * <tr> 235 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 236 * <td>Called when a trackball motion event occurs. 237 * </td> 238 * </tr> 239 * <tr> 240 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 241 * <td>Called when a touch screen motion event occurs. 242 * </td> 243 * </tr> 244 * 245 * <tr> 246 * <td rowspan="2">Focus</td> 247 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 248 * <td>Called when the view gains or loses focus. 249 * </td> 250 * </tr> 251 * 252 * <tr> 253 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 254 * <td>Called when the window containing the view gains or loses focus. 255 * </td> 256 * </tr> 257 * 258 * <tr> 259 * <td rowspan="3">Attaching</td> 260 * <td><code>{@link #onAttachedToWindow()}</code></td> 261 * <td>Called when the view is attached to a window. 262 * </td> 263 * </tr> 264 * 265 * <tr> 266 * <td><code>{@link #onDetachedFromWindow}</code></td> 267 * <td>Called when the view is detached from its window. 268 * </td> 269 * </tr> 270 * 271 * <tr> 272 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 273 * <td>Called when the visibility of the window containing the view 274 * has changed. 275 * </td> 276 * </tr> 277 * </tbody> 278 * 279 * </table> 280 * </p> 281 * 282 * <a name="IDs"></a> 283 * <h3>IDs</h3> 284 * Views may have an integer id associated with them. These ids are typically 285 * assigned in the layout XML files, and are used to find specific views within 286 * the view tree. A common pattern is to: 287 * <ul> 288 * <li>Define a Button in the layout file and assign it a unique ID. 289 * <pre> 290 * <Button 291 * android:id="@+id/my_button" 292 * android:layout_width="wrap_content" 293 * android:layout_height="wrap_content" 294 * android:text="@string/my_button_text"/> 295 * </pre></li> 296 * <li>From the onCreate method of an Activity, find the Button 297 * <pre class="prettyprint"> 298 * Button myButton = (Button) findViewById(R.id.my_button); 299 * </pre></li> 300 * </ul> 301 * <p> 302 * View IDs need not be unique throughout the tree, but it is good practice to 303 * ensure that they are at least unique within the part of the tree you are 304 * searching. 305 * </p> 306 * 307 * <a name="Position"></a> 308 * <h3>Position</h3> 309 * <p> 310 * The geometry of a view is that of a rectangle. A view has a location, 311 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 312 * two dimensions, expressed as a width and a height. The unit for location 313 * and dimensions is the pixel. 314 * </p> 315 * 316 * <p> 317 * It is possible to retrieve the location of a view by invoking the methods 318 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 319 * coordinate of the rectangle representing the view. The latter returns the 320 * top, or Y, coordinate of the rectangle representing the view. These methods 321 * both return the location of the view relative to its parent. For instance, 322 * when getLeft() returns 20, that means the view is located 20 pixels to the 323 * right of the left edge of its direct parent. 324 * </p> 325 * 326 * <p> 327 * In addition, several convenience methods are offered to avoid unnecessary 328 * computations, namely {@link #getRight()} and {@link #getBottom()}. 329 * These methods return the coordinates of the right and bottom edges of the 330 * rectangle representing the view. For instance, calling {@link #getRight()} 331 * is similar to the following computation: <code>getLeft() + getWidth()</code> 332 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 333 * </p> 334 * 335 * <a name="SizePaddingMargins"></a> 336 * <h3>Size, padding and margins</h3> 337 * <p> 338 * The size of a view is expressed with a width and a height. A view actually 339 * possess two pairs of width and height values. 340 * </p> 341 * 342 * <p> 343 * The first pair is known as <em>measured width</em> and 344 * <em>measured height</em>. These dimensions define how big a view wants to be 345 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 346 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 347 * and {@link #getMeasuredHeight()}. 348 * </p> 349 * 350 * <p> 351 * The second pair is simply known as <em>width</em> and <em>height</em>, or 352 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 353 * dimensions define the actual size of the view on screen, at drawing time and 354 * after layout. These values may, but do not have to, be different from the 355 * measured width and height. The width and height can be obtained by calling 356 * {@link #getWidth()} and {@link #getHeight()}. 357 * </p> 358 * 359 * <p> 360 * To measure its dimensions, a view takes into account its padding. The padding 361 * is expressed in pixels for the left, top, right and bottom parts of the view. 362 * Padding can be used to offset the content of the view by a specific amount of 363 * pixels. For instance, a left padding of 2 will push the view's content by 364 * 2 pixels to the right of the left edge. Padding can be set using the 365 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 366 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 367 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 368 * {@link #getPaddingEnd()}. 369 * </p> 370 * 371 * <p> 372 * Even though a view can define a padding, it does not provide any support for 373 * margins. However, view groups provide such a support. Refer to 374 * {@link android.view.ViewGroup} and 375 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 376 * </p> 377 * 378 * <a name="Layout"></a> 379 * <h3>Layout</h3> 380 * <p> 381 * Layout is a two pass process: a measure pass and a layout pass. The measuring 382 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 383 * of the view tree. Each view pushes dimension specifications down the tree 384 * during the recursion. At the end of the measure pass, every view has stored 385 * its measurements. The second pass happens in 386 * {@link #layout(int,int,int,int)} and is also top-down. During 387 * this pass each parent is responsible for positioning all of its children 388 * using the sizes computed in the measure pass. 389 * </p> 390 * 391 * <p> 392 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 393 * {@link #getMeasuredHeight()} values must be set, along with those for all of 394 * that view's descendants. A view's measured width and measured height values 395 * must respect the constraints imposed by the view's parents. This guarantees 396 * that at the end of the measure pass, all parents accept all of their 397 * children's measurements. A parent view may call measure() more than once on 398 * its children. For example, the parent may measure each child once with 399 * unspecified dimensions to find out how big they want to be, then call 400 * measure() on them again with actual numbers if the sum of all the children's 401 * unconstrained sizes is too big or too small. 402 * </p> 403 * 404 * <p> 405 * The measure pass uses two classes to communicate dimensions. The 406 * {@link MeasureSpec} class is used by views to tell their parents how they 407 * want to be measured and positioned. The base LayoutParams class just 408 * describes how big the view wants to be for both width and height. For each 409 * dimension, it can specify one of: 410 * <ul> 411 * <li> an exact number 412 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 413 * (minus padding) 414 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 415 * enclose its content (plus padding). 416 * </ul> 417 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 418 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 419 * an X and Y value. 420 * </p> 421 * 422 * <p> 423 * MeasureSpecs are used to push requirements down the tree from parent to 424 * child. A MeasureSpec can be in one of three modes: 425 * <ul> 426 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 427 * of a child view. For example, a LinearLayout may call measure() on its child 428 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 429 * tall the child view wants to be given a width of 240 pixels. 430 * <li>EXACTLY: This is used by the parent to impose an exact size on the 431 * child. The child must use this size, and guarantee that all of its 432 * descendants will fit within this size. 433 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 434 * child. The child must gurantee that it and all of its descendants will fit 435 * within this size. 436 * </ul> 437 * </p> 438 * 439 * <p> 440 * To intiate a layout, call {@link #requestLayout}. This method is typically 441 * called by a view on itself when it believes that is can no longer fit within 442 * its current bounds. 443 * </p> 444 * 445 * <a name="Drawing"></a> 446 * <h3>Drawing</h3> 447 * <p> 448 * Drawing is handled by walking the tree and rendering each view that 449 * intersects the invalid region. Because the tree is traversed in-order, 450 * this means that parents will draw before (i.e., behind) their children, with 451 * siblings drawn in the order they appear in the tree. 452 * If you set a background drawable for a View, then the View will draw it for you 453 * before calling back to its <code>onDraw()</code> method. 454 * </p> 455 * 456 * <p> 457 * Note that the framework will not draw views that are not in the invalid region. 458 * </p> 459 * 460 * <p> 461 * To force a view to draw, call {@link #invalidate()}. 462 * </p> 463 * 464 * <a name="EventHandlingThreading"></a> 465 * <h3>Event Handling and Threading</h3> 466 * <p> 467 * The basic cycle of a view is as follows: 468 * <ol> 469 * <li>An event comes in and is dispatched to the appropriate view. The view 470 * handles the event and notifies any listeners.</li> 471 * <li>If in the course of processing the event, the view's bounds may need 472 * to be changed, the view will call {@link #requestLayout()}.</li> 473 * <li>Similarly, if in the course of processing the event the view's appearance 474 * may need to be changed, the view will call {@link #invalidate()}.</li> 475 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 476 * the framework will take care of measuring, laying out, and drawing the tree 477 * as appropriate.</li> 478 * </ol> 479 * </p> 480 * 481 * <p><em>Note: The entire view tree is single threaded. You must always be on 482 * the UI thread when calling any method on any view.</em> 483 * If you are doing work on other threads and want to update the state of a view 484 * from that thread, you should use a {@link Handler}. 485 * </p> 486 * 487 * <a name="FocusHandling"></a> 488 * <h3>Focus Handling</h3> 489 * <p> 490 * The framework will handle routine focus movement in response to user input. 491 * This includes changing the focus as views are removed or hidden, or as new 492 * views become available. Views indicate their willingness to take focus 493 * through the {@link #isFocusable} method. To change whether a view can take 494 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 495 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 496 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 497 * </p> 498 * <p> 499 * Focus movement is based on an algorithm which finds the nearest neighbor in a 500 * given direction. In rare cases, the default algorithm may not match the 501 * intended behavior of the developer. In these situations, you can provide 502 * explicit overrides by using these XML attributes in the layout file: 503 * <pre> 504 * nextFocusDown 505 * nextFocusLeft 506 * nextFocusRight 507 * nextFocusUp 508 * </pre> 509 * </p> 510 * 511 * 512 * <p> 513 * To get a particular view to take focus, call {@link #requestFocus()}. 514 * </p> 515 * 516 * <a name="TouchMode"></a> 517 * <h3>Touch Mode</h3> 518 * <p> 519 * When a user is navigating a user interface via directional keys such as a D-pad, it is 520 * necessary to give focus to actionable items such as buttons so the user can see 521 * what will take input. If the device has touch capabilities, however, and the user 522 * begins interacting with the interface by touching it, it is no longer necessary to 523 * always highlight, or give focus to, a particular view. This motivates a mode 524 * for interaction named 'touch mode'. 525 * </p> 526 * <p> 527 * For a touch capable device, once the user touches the screen, the device 528 * will enter touch mode. From this point onward, only views for which 529 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 530 * Other views that are touchable, like buttons, will not take focus when touched; they will 531 * only fire the on click listeners. 532 * </p> 533 * <p> 534 * Any time a user hits a directional key, such as a D-pad direction, the view device will 535 * exit touch mode, and find a view to take focus, so that the user may resume interacting 536 * with the user interface without touching the screen again. 537 * </p> 538 * <p> 539 * The touch mode state is maintained across {@link android.app.Activity}s. Call 540 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 541 * </p> 542 * 543 * <a name="Scrolling"></a> 544 * <h3>Scrolling</h3> 545 * <p> 546 * The framework provides basic support for views that wish to internally 547 * scroll their content. This includes keeping track of the X and Y scroll 548 * offset as well as mechanisms for drawing scrollbars. See 549 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 550 * {@link #awakenScrollBars()} for more details. 551 * </p> 552 * 553 * <a name="Tags"></a> 554 * <h3>Tags</h3> 555 * <p> 556 * Unlike IDs, tags are not used to identify views. Tags are essentially an 557 * extra piece of information that can be associated with a view. They are most 558 * often used as a convenience to store data related to views in the views 559 * themselves rather than by putting them in a separate structure. 560 * </p> 561 * 562 * <a name="Properties"></a> 563 * <h3>Properties</h3> 564 * <p> 565 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 566 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 567 * available both in the {@link Property} form as well as in similarly-named setter/getter 568 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 569 * be used to set persistent state associated with these rendering-related properties on the view. 570 * The properties and methods can also be used in conjunction with 571 * {@link android.animation.Animator Animator}-based animations, described more in the 572 * <a href="#Animation">Animation</a> section. 573 * </p> 574 * 575 * <a name="Animation"></a> 576 * <h3>Animation</h3> 577 * <p> 578 * Starting with Android 3.0, the preferred way of animating views is to use the 579 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 580 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 581 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 582 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 583 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 584 * makes animating these View properties particularly easy and efficient. 585 * </p> 586 * <p> 587 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 588 * You can attach an {@link Animation} object to a view using 589 * {@link #setAnimation(Animation)} or 590 * {@link #startAnimation(Animation)}. The animation can alter the scale, 591 * rotation, translation and alpha of a view over time. If the animation is 592 * attached to a view that has children, the animation will affect the entire 593 * subtree rooted by that node. When an animation is started, the framework will 594 * take care of redrawing the appropriate views until the animation completes. 595 * </p> 596 * 597 * <a name="Security"></a> 598 * <h3>Security</h3> 599 * <p> 600 * Sometimes it is essential that an application be able to verify that an action 601 * is being performed with the full knowledge and consent of the user, such as 602 * granting a permission request, making a purchase or clicking on an advertisement. 603 * Unfortunately, a malicious application could try to spoof the user into 604 * performing these actions, unaware, by concealing the intended purpose of the view. 605 * As a remedy, the framework offers a touch filtering mechanism that can be used to 606 * improve the security of views that provide access to sensitive functionality. 607 * </p><p> 608 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 609 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 610 * will discard touches that are received whenever the view's window is obscured by 611 * another visible window. As a result, the view will not receive touches whenever a 612 * toast, dialog or other window appears above the view's window. 613 * </p><p> 614 * For more fine-grained control over security, consider overriding the 615 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 616 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 617 * </p> 618 * 619 * @attr ref android.R.styleable#View_alpha 620 * @attr ref android.R.styleable#View_background 621 * @attr ref android.R.styleable#View_clickable 622 * @attr ref android.R.styleable#View_contentDescription 623 * @attr ref android.R.styleable#View_drawingCacheQuality 624 * @attr ref android.R.styleable#View_duplicateParentState 625 * @attr ref android.R.styleable#View_id 626 * @attr ref android.R.styleable#View_requiresFadingEdge 627 * @attr ref android.R.styleable#View_fadeScrollbars 628 * @attr ref android.R.styleable#View_fadingEdgeLength 629 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 630 * @attr ref android.R.styleable#View_fitsSystemWindows 631 * @attr ref android.R.styleable#View_isScrollContainer 632 * @attr ref android.R.styleable#View_focusable 633 * @attr ref android.R.styleable#View_focusableInTouchMode 634 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 635 * @attr ref android.R.styleable#View_keepScreenOn 636 * @attr ref android.R.styleable#View_layerType 637 * @attr ref android.R.styleable#View_layoutDirection 638 * @attr ref android.R.styleable#View_longClickable 639 * @attr ref android.R.styleable#View_minHeight 640 * @attr ref android.R.styleable#View_minWidth 641 * @attr ref android.R.styleable#View_nextFocusDown 642 * @attr ref android.R.styleable#View_nextFocusLeft 643 * @attr ref android.R.styleable#View_nextFocusRight 644 * @attr ref android.R.styleable#View_nextFocusUp 645 * @attr ref android.R.styleable#View_onClick 646 * @attr ref android.R.styleable#View_padding 647 * @attr ref android.R.styleable#View_paddingBottom 648 * @attr ref android.R.styleable#View_paddingLeft 649 * @attr ref android.R.styleable#View_paddingRight 650 * @attr ref android.R.styleable#View_paddingTop 651 * @attr ref android.R.styleable#View_paddingStart 652 * @attr ref android.R.styleable#View_paddingEnd 653 * @attr ref android.R.styleable#View_saveEnabled 654 * @attr ref android.R.styleable#View_rotation 655 * @attr ref android.R.styleable#View_rotationX 656 * @attr ref android.R.styleable#View_rotationY 657 * @attr ref android.R.styleable#View_scaleX 658 * @attr ref android.R.styleable#View_scaleY 659 * @attr ref android.R.styleable#View_scrollX 660 * @attr ref android.R.styleable#View_scrollY 661 * @attr ref android.R.styleable#View_scrollbarSize 662 * @attr ref android.R.styleable#View_scrollbarStyle 663 * @attr ref android.R.styleable#View_scrollbars 664 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 665 * @attr ref android.R.styleable#View_scrollbarFadeDuration 666 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 667 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 668 * @attr ref android.R.styleable#View_scrollbarThumbVertical 669 * @attr ref android.R.styleable#View_scrollbarTrackVertical 670 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 671 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 672 * @attr ref android.R.styleable#View_stateListAnimator 673 * @attr ref android.R.styleable#View_viewName 674 * @attr ref android.R.styleable#View_soundEffectsEnabled 675 * @attr ref android.R.styleable#View_tag 676 * @attr ref android.R.styleable#View_textAlignment 677 * @attr ref android.R.styleable#View_textDirection 678 * @attr ref android.R.styleable#View_transformPivotX 679 * @attr ref android.R.styleable#View_transformPivotY 680 * @attr ref android.R.styleable#View_translationX 681 * @attr ref android.R.styleable#View_translationY 682 * @attr ref android.R.styleable#View_translationZ 683 * @attr ref android.R.styleable#View_visibility 684 * 685 * @see android.view.ViewGroup 686 */ 687public class View implements Drawable.Callback, KeyEvent.Callback, 688 AccessibilityEventSource { 689 private static final boolean DBG = false; 690 691 /** 692 * The logging tag used by this class with android.util.Log. 693 */ 694 protected static final String VIEW_LOG_TAG = "View"; 695 696 /** 697 * When set to true, apps will draw debugging information about their layouts. 698 * 699 * @hide 700 */ 701 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 702 703 /** 704 * Used to mark a View that has no ID. 705 */ 706 public static final int NO_ID = -1; 707 708 /** 709 * Signals that compatibility booleans have been initialized according to 710 * target SDK versions. 711 */ 712 private static boolean sCompatibilityDone = false; 713 714 /** 715 * Use the old (broken) way of building MeasureSpecs. 716 */ 717 private static boolean sUseBrokenMakeMeasureSpec = false; 718 719 /** 720 * Ignore any optimizations using the measure cache. 721 */ 722 private static boolean sIgnoreMeasureCache = false; 723 724 /** 725 * Ignore the clipBounds of this view for the children. 726 */ 727 static boolean sIgnoreClipBoundsForChildren = false; 728 729 /** 730 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 731 * calling setFlags. 732 */ 733 private static final int NOT_FOCUSABLE = 0x00000000; 734 735 /** 736 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 737 * setFlags. 738 */ 739 private static final int FOCUSABLE = 0x00000001; 740 741 /** 742 * Mask for use with setFlags indicating bits used for focus. 743 */ 744 private static final int FOCUSABLE_MASK = 0x00000001; 745 746 /** 747 * This view will adjust its padding to fit sytem windows (e.g. status bar) 748 */ 749 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 750 751 /** @hide */ 752 @IntDef({VISIBLE, INVISIBLE, GONE}) 753 @Retention(RetentionPolicy.SOURCE) 754 public @interface Visibility {} 755 756 /** 757 * This view is visible. 758 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 759 * android:visibility}. 760 */ 761 public static final int VISIBLE = 0x00000000; 762 763 /** 764 * This view is invisible, but it still takes up space for layout purposes. 765 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 766 * android:visibility}. 767 */ 768 public static final int INVISIBLE = 0x00000004; 769 770 /** 771 * This view is invisible, and it doesn't take any space for layout 772 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 773 * android:visibility}. 774 */ 775 public static final int GONE = 0x00000008; 776 777 /** 778 * Mask for use with setFlags indicating bits used for visibility. 779 * {@hide} 780 */ 781 static final int VISIBILITY_MASK = 0x0000000C; 782 783 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 784 785 /** 786 * This view is enabled. Interpretation varies by subclass. 787 * Use with ENABLED_MASK when calling setFlags. 788 * {@hide} 789 */ 790 static final int ENABLED = 0x00000000; 791 792 /** 793 * This view is disabled. Interpretation varies by subclass. 794 * Use with ENABLED_MASK when calling setFlags. 795 * {@hide} 796 */ 797 static final int DISABLED = 0x00000020; 798 799 /** 800 * Mask for use with setFlags indicating bits used for indicating whether 801 * this view is enabled 802 * {@hide} 803 */ 804 static final int ENABLED_MASK = 0x00000020; 805 806 /** 807 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 808 * called and further optimizations will be performed. It is okay to have 809 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 810 * {@hide} 811 */ 812 static final int WILL_NOT_DRAW = 0x00000080; 813 814 /** 815 * Mask for use with setFlags indicating bits used for indicating whether 816 * this view is will draw 817 * {@hide} 818 */ 819 static final int DRAW_MASK = 0x00000080; 820 821 /** 822 * <p>This view doesn't show scrollbars.</p> 823 * {@hide} 824 */ 825 static final int SCROLLBARS_NONE = 0x00000000; 826 827 /** 828 * <p>This view shows horizontal scrollbars.</p> 829 * {@hide} 830 */ 831 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 832 833 /** 834 * <p>This view shows vertical scrollbars.</p> 835 * {@hide} 836 */ 837 static final int SCROLLBARS_VERTICAL = 0x00000200; 838 839 /** 840 * <p>Mask for use with setFlags indicating bits used for indicating which 841 * scrollbars are enabled.</p> 842 * {@hide} 843 */ 844 static final int SCROLLBARS_MASK = 0x00000300; 845 846 /** 847 * Indicates that the view should filter touches when its window is obscured. 848 * Refer to the class comments for more information about this security feature. 849 * {@hide} 850 */ 851 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 852 853 /** 854 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 855 * that they are optional and should be skipped if the window has 856 * requested system UI flags that ignore those insets for layout. 857 */ 858 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 859 860 /** 861 * <p>This view doesn't show fading edges.</p> 862 * {@hide} 863 */ 864 static final int FADING_EDGE_NONE = 0x00000000; 865 866 /** 867 * <p>This view shows horizontal fading edges.</p> 868 * {@hide} 869 */ 870 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 871 872 /** 873 * <p>This view shows vertical fading edges.</p> 874 * {@hide} 875 */ 876 static final int FADING_EDGE_VERTICAL = 0x00002000; 877 878 /** 879 * <p>Mask for use with setFlags indicating bits used for indicating which 880 * fading edges are enabled.</p> 881 * {@hide} 882 */ 883 static final int FADING_EDGE_MASK = 0x00003000; 884 885 /** 886 * <p>Indicates this view can be clicked. When clickable, a View reacts 887 * to clicks by notifying the OnClickListener.<p> 888 * {@hide} 889 */ 890 static final int CLICKABLE = 0x00004000; 891 892 /** 893 * <p>Indicates this view is caching its drawing into a bitmap.</p> 894 * {@hide} 895 */ 896 static final int DRAWING_CACHE_ENABLED = 0x00008000; 897 898 /** 899 * <p>Indicates that no icicle should be saved for this view.<p> 900 * {@hide} 901 */ 902 static final int SAVE_DISABLED = 0x000010000; 903 904 /** 905 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 906 * property.</p> 907 * {@hide} 908 */ 909 static final int SAVE_DISABLED_MASK = 0x000010000; 910 911 /** 912 * <p>Indicates that no drawing cache should ever be created for this view.<p> 913 * {@hide} 914 */ 915 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 916 917 /** 918 * <p>Indicates this view can take / keep focus when int touch mode.</p> 919 * {@hide} 920 */ 921 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 922 923 /** @hide */ 924 @Retention(RetentionPolicy.SOURCE) 925 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 926 public @interface DrawingCacheQuality {} 927 928 /** 929 * <p>Enables low quality mode for the drawing cache.</p> 930 */ 931 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 932 933 /** 934 * <p>Enables high quality mode for the drawing cache.</p> 935 */ 936 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 937 938 /** 939 * <p>Enables automatic quality mode for the drawing cache.</p> 940 */ 941 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 942 943 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 944 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 945 }; 946 947 /** 948 * <p>Mask for use with setFlags indicating bits used for the cache 949 * quality property.</p> 950 * {@hide} 951 */ 952 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 953 954 /** 955 * <p> 956 * Indicates this view can be long clicked. When long clickable, a View 957 * reacts to long clicks by notifying the OnLongClickListener or showing a 958 * context menu. 959 * </p> 960 * {@hide} 961 */ 962 static final int LONG_CLICKABLE = 0x00200000; 963 964 /** 965 * <p>Indicates that this view gets its drawable states from its direct parent 966 * and ignores its original internal states.</p> 967 * 968 * @hide 969 */ 970 static final int DUPLICATE_PARENT_STATE = 0x00400000; 971 972 /** @hide */ 973 @IntDef({ 974 SCROLLBARS_INSIDE_OVERLAY, 975 SCROLLBARS_INSIDE_INSET, 976 SCROLLBARS_OUTSIDE_OVERLAY, 977 SCROLLBARS_OUTSIDE_INSET 978 }) 979 @Retention(RetentionPolicy.SOURCE) 980 public @interface ScrollBarStyle {} 981 982 /** 983 * The scrollbar style to display the scrollbars inside the content area, 984 * without increasing the padding. The scrollbars will be overlaid with 985 * translucency on the view's content. 986 */ 987 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 988 989 /** 990 * The scrollbar style to display the scrollbars inside the padded area, 991 * increasing the padding of the view. The scrollbars will not overlap the 992 * content area of the view. 993 */ 994 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 995 996 /** 997 * The scrollbar style to display the scrollbars at the edge of the view, 998 * without increasing the padding. The scrollbars will be overlaid with 999 * translucency. 1000 */ 1001 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1002 1003 /** 1004 * The scrollbar style to display the scrollbars at the edge of the view, 1005 * increasing the padding of the view. The scrollbars will only overlap the 1006 * background, if any. 1007 */ 1008 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1009 1010 /** 1011 * Mask to check if the scrollbar style is overlay or inset. 1012 * {@hide} 1013 */ 1014 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1015 1016 /** 1017 * Mask to check if the scrollbar style is inside or outside. 1018 * {@hide} 1019 */ 1020 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1021 1022 /** 1023 * Mask for scrollbar style. 1024 * {@hide} 1025 */ 1026 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1027 1028 /** 1029 * View flag indicating that the screen should remain on while the 1030 * window containing this view is visible to the user. This effectively 1031 * takes care of automatically setting the WindowManager's 1032 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1033 */ 1034 public static final int KEEP_SCREEN_ON = 0x04000000; 1035 1036 /** 1037 * View flag indicating whether this view should have sound effects enabled 1038 * for events such as clicking and touching. 1039 */ 1040 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1041 1042 /** 1043 * View flag indicating whether this view should have haptic feedback 1044 * enabled for events such as long presses. 1045 */ 1046 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1047 1048 /** 1049 * <p>Indicates that the view hierarchy should stop saving state when 1050 * it reaches this view. If state saving is initiated immediately at 1051 * the view, it will be allowed. 1052 * {@hide} 1053 */ 1054 static final int PARENT_SAVE_DISABLED = 0x20000000; 1055 1056 /** 1057 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1058 * {@hide} 1059 */ 1060 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1061 1062 /** @hide */ 1063 @IntDef(flag = true, 1064 value = { 1065 FOCUSABLES_ALL, 1066 FOCUSABLES_TOUCH_MODE 1067 }) 1068 @Retention(RetentionPolicy.SOURCE) 1069 public @interface FocusableMode {} 1070 1071 /** 1072 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1073 * should add all focusable Views regardless if they are focusable in touch mode. 1074 */ 1075 public static final int FOCUSABLES_ALL = 0x00000000; 1076 1077 /** 1078 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1079 * should add only Views focusable in touch mode. 1080 */ 1081 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1082 1083 /** @hide */ 1084 @IntDef({ 1085 FOCUS_BACKWARD, 1086 FOCUS_FORWARD, 1087 FOCUS_LEFT, 1088 FOCUS_UP, 1089 FOCUS_RIGHT, 1090 FOCUS_DOWN 1091 }) 1092 @Retention(RetentionPolicy.SOURCE) 1093 public @interface FocusDirection {} 1094 1095 /** @hide */ 1096 @IntDef({ 1097 FOCUS_LEFT, 1098 FOCUS_UP, 1099 FOCUS_RIGHT, 1100 FOCUS_DOWN 1101 }) 1102 @Retention(RetentionPolicy.SOURCE) 1103 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1104 1105 /** 1106 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1107 * item. 1108 */ 1109 public static final int FOCUS_BACKWARD = 0x00000001; 1110 1111 /** 1112 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1113 * item. 1114 */ 1115 public static final int FOCUS_FORWARD = 0x00000002; 1116 1117 /** 1118 * Use with {@link #focusSearch(int)}. Move focus to the left. 1119 */ 1120 public static final int FOCUS_LEFT = 0x00000011; 1121 1122 /** 1123 * Use with {@link #focusSearch(int)}. Move focus up. 1124 */ 1125 public static final int FOCUS_UP = 0x00000021; 1126 1127 /** 1128 * Use with {@link #focusSearch(int)}. Move focus to the right. 1129 */ 1130 public static final int FOCUS_RIGHT = 0x00000042; 1131 1132 /** 1133 * Use with {@link #focusSearch(int)}. Move focus down. 1134 */ 1135 public static final int FOCUS_DOWN = 0x00000082; 1136 1137 /** 1138 * Bits of {@link #getMeasuredWidthAndState()} and 1139 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1140 */ 1141 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1142 1143 /** 1144 * Bits of {@link #getMeasuredWidthAndState()} and 1145 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1146 */ 1147 public static final int MEASURED_STATE_MASK = 0xff000000; 1148 1149 /** 1150 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1151 * for functions that combine both width and height into a single int, 1152 * such as {@link #getMeasuredState()} and the childState argument of 1153 * {@link #resolveSizeAndState(int, int, int)}. 1154 */ 1155 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1156 1157 /** 1158 * Bit of {@link #getMeasuredWidthAndState()} and 1159 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1160 * is smaller that the space the view would like to have. 1161 */ 1162 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1163 1164 /** 1165 * Base View state sets 1166 */ 1167 // Singles 1168 /** 1169 * Indicates the view has no states set. States are used with 1170 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1171 * view depending on its state. 1172 * 1173 * @see android.graphics.drawable.Drawable 1174 * @see #getDrawableState() 1175 */ 1176 protected static final int[] EMPTY_STATE_SET; 1177 /** 1178 * Indicates the view is enabled. States are used with 1179 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1180 * view depending on its state. 1181 * 1182 * @see android.graphics.drawable.Drawable 1183 * @see #getDrawableState() 1184 */ 1185 protected static final int[] ENABLED_STATE_SET; 1186 /** 1187 * Indicates the view is focused. States are used with 1188 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1189 * view depending on its state. 1190 * 1191 * @see android.graphics.drawable.Drawable 1192 * @see #getDrawableState() 1193 */ 1194 protected static final int[] FOCUSED_STATE_SET; 1195 /** 1196 * Indicates the view is selected. States are used with 1197 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1198 * view depending on its state. 1199 * 1200 * @see android.graphics.drawable.Drawable 1201 * @see #getDrawableState() 1202 */ 1203 protected static final int[] SELECTED_STATE_SET; 1204 /** 1205 * Indicates the view is pressed. States are used with 1206 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1207 * view depending on its state. 1208 * 1209 * @see android.graphics.drawable.Drawable 1210 * @see #getDrawableState() 1211 */ 1212 protected static final int[] PRESSED_STATE_SET; 1213 /** 1214 * Indicates the view's window has focus. States are used with 1215 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1216 * view depending on its state. 1217 * 1218 * @see android.graphics.drawable.Drawable 1219 * @see #getDrawableState() 1220 */ 1221 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1222 // Doubles 1223 /** 1224 * Indicates the view is enabled and has the focus. 1225 * 1226 * @see #ENABLED_STATE_SET 1227 * @see #FOCUSED_STATE_SET 1228 */ 1229 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1230 /** 1231 * Indicates the view is enabled and selected. 1232 * 1233 * @see #ENABLED_STATE_SET 1234 * @see #SELECTED_STATE_SET 1235 */ 1236 protected static final int[] ENABLED_SELECTED_STATE_SET; 1237 /** 1238 * Indicates the view is enabled and that its window has focus. 1239 * 1240 * @see #ENABLED_STATE_SET 1241 * @see #WINDOW_FOCUSED_STATE_SET 1242 */ 1243 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1244 /** 1245 * Indicates the view is focused and selected. 1246 * 1247 * @see #FOCUSED_STATE_SET 1248 * @see #SELECTED_STATE_SET 1249 */ 1250 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1251 /** 1252 * Indicates the view has the focus and that its window has the focus. 1253 * 1254 * @see #FOCUSED_STATE_SET 1255 * @see #WINDOW_FOCUSED_STATE_SET 1256 */ 1257 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1258 /** 1259 * Indicates the view is selected and that its window has the focus. 1260 * 1261 * @see #SELECTED_STATE_SET 1262 * @see #WINDOW_FOCUSED_STATE_SET 1263 */ 1264 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1265 // Triples 1266 /** 1267 * Indicates the view is enabled, focused and selected. 1268 * 1269 * @see #ENABLED_STATE_SET 1270 * @see #FOCUSED_STATE_SET 1271 * @see #SELECTED_STATE_SET 1272 */ 1273 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1274 /** 1275 * Indicates the view is enabled, focused and its window has the focus. 1276 * 1277 * @see #ENABLED_STATE_SET 1278 * @see #FOCUSED_STATE_SET 1279 * @see #WINDOW_FOCUSED_STATE_SET 1280 */ 1281 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1282 /** 1283 * Indicates the view is enabled, selected and its window has the focus. 1284 * 1285 * @see #ENABLED_STATE_SET 1286 * @see #SELECTED_STATE_SET 1287 * @see #WINDOW_FOCUSED_STATE_SET 1288 */ 1289 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1290 /** 1291 * Indicates the view is focused, selected and its window has the focus. 1292 * 1293 * @see #FOCUSED_STATE_SET 1294 * @see #SELECTED_STATE_SET 1295 * @see #WINDOW_FOCUSED_STATE_SET 1296 */ 1297 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1298 /** 1299 * Indicates the view is enabled, focused, selected and its window 1300 * has the focus. 1301 * 1302 * @see #ENABLED_STATE_SET 1303 * @see #FOCUSED_STATE_SET 1304 * @see #SELECTED_STATE_SET 1305 * @see #WINDOW_FOCUSED_STATE_SET 1306 */ 1307 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1308 /** 1309 * Indicates the view is pressed and its window has the focus. 1310 * 1311 * @see #PRESSED_STATE_SET 1312 * @see #WINDOW_FOCUSED_STATE_SET 1313 */ 1314 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1315 /** 1316 * Indicates the view is pressed and selected. 1317 * 1318 * @see #PRESSED_STATE_SET 1319 * @see #SELECTED_STATE_SET 1320 */ 1321 protected static final int[] PRESSED_SELECTED_STATE_SET; 1322 /** 1323 * Indicates the view is pressed, selected and its window has the focus. 1324 * 1325 * @see #PRESSED_STATE_SET 1326 * @see #SELECTED_STATE_SET 1327 * @see #WINDOW_FOCUSED_STATE_SET 1328 */ 1329 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1330 /** 1331 * Indicates the view is pressed and focused. 1332 * 1333 * @see #PRESSED_STATE_SET 1334 * @see #FOCUSED_STATE_SET 1335 */ 1336 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1337 /** 1338 * Indicates the view is pressed, focused and its window has the focus. 1339 * 1340 * @see #PRESSED_STATE_SET 1341 * @see #FOCUSED_STATE_SET 1342 * @see #WINDOW_FOCUSED_STATE_SET 1343 */ 1344 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1345 /** 1346 * Indicates the view is pressed, focused and selected. 1347 * 1348 * @see #PRESSED_STATE_SET 1349 * @see #SELECTED_STATE_SET 1350 * @see #FOCUSED_STATE_SET 1351 */ 1352 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1353 /** 1354 * Indicates the view is pressed, focused, selected and its window has the focus. 1355 * 1356 * @see #PRESSED_STATE_SET 1357 * @see #FOCUSED_STATE_SET 1358 * @see #SELECTED_STATE_SET 1359 * @see #WINDOW_FOCUSED_STATE_SET 1360 */ 1361 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1362 /** 1363 * Indicates the view is pressed and enabled. 1364 * 1365 * @see #PRESSED_STATE_SET 1366 * @see #ENABLED_STATE_SET 1367 */ 1368 protected static final int[] PRESSED_ENABLED_STATE_SET; 1369 /** 1370 * Indicates the view is pressed, enabled and its window has the focus. 1371 * 1372 * @see #PRESSED_STATE_SET 1373 * @see #ENABLED_STATE_SET 1374 * @see #WINDOW_FOCUSED_STATE_SET 1375 */ 1376 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1377 /** 1378 * Indicates the view is pressed, enabled and selected. 1379 * 1380 * @see #PRESSED_STATE_SET 1381 * @see #ENABLED_STATE_SET 1382 * @see #SELECTED_STATE_SET 1383 */ 1384 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1385 /** 1386 * Indicates the view is pressed, enabled, selected and its window has the 1387 * focus. 1388 * 1389 * @see #PRESSED_STATE_SET 1390 * @see #ENABLED_STATE_SET 1391 * @see #SELECTED_STATE_SET 1392 * @see #WINDOW_FOCUSED_STATE_SET 1393 */ 1394 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1395 /** 1396 * Indicates the view is pressed, enabled and focused. 1397 * 1398 * @see #PRESSED_STATE_SET 1399 * @see #ENABLED_STATE_SET 1400 * @see #FOCUSED_STATE_SET 1401 */ 1402 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1403 /** 1404 * Indicates the view is pressed, enabled, focused and its window has the 1405 * focus. 1406 * 1407 * @see #PRESSED_STATE_SET 1408 * @see #ENABLED_STATE_SET 1409 * @see #FOCUSED_STATE_SET 1410 * @see #WINDOW_FOCUSED_STATE_SET 1411 */ 1412 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1413 /** 1414 * Indicates the view is pressed, enabled, focused and selected. 1415 * 1416 * @see #PRESSED_STATE_SET 1417 * @see #ENABLED_STATE_SET 1418 * @see #SELECTED_STATE_SET 1419 * @see #FOCUSED_STATE_SET 1420 */ 1421 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1422 /** 1423 * Indicates the view is pressed, enabled, focused, selected and its window 1424 * has the focus. 1425 * 1426 * @see #PRESSED_STATE_SET 1427 * @see #ENABLED_STATE_SET 1428 * @see #SELECTED_STATE_SET 1429 * @see #FOCUSED_STATE_SET 1430 * @see #WINDOW_FOCUSED_STATE_SET 1431 */ 1432 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1433 1434 /** 1435 * The order here is very important to {@link #getDrawableState()} 1436 */ 1437 private static final int[][] VIEW_STATE_SETS; 1438 1439 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1440 static final int VIEW_STATE_SELECTED = 1 << 1; 1441 static final int VIEW_STATE_FOCUSED = 1 << 2; 1442 static final int VIEW_STATE_ENABLED = 1 << 3; 1443 static final int VIEW_STATE_PRESSED = 1 << 4; 1444 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1445 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1446 static final int VIEW_STATE_HOVERED = 1 << 7; 1447 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1448 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1449 1450 static final int[] VIEW_STATE_IDS = new int[] { 1451 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1452 R.attr.state_selected, VIEW_STATE_SELECTED, 1453 R.attr.state_focused, VIEW_STATE_FOCUSED, 1454 R.attr.state_enabled, VIEW_STATE_ENABLED, 1455 R.attr.state_pressed, VIEW_STATE_PRESSED, 1456 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1457 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1458 R.attr.state_hovered, VIEW_STATE_HOVERED, 1459 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1460 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1461 }; 1462 1463 static { 1464 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1465 throw new IllegalStateException( 1466 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1467 } 1468 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1469 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1470 int viewState = R.styleable.ViewDrawableStates[i]; 1471 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1472 if (VIEW_STATE_IDS[j] == viewState) { 1473 orderedIds[i * 2] = viewState; 1474 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1475 } 1476 } 1477 } 1478 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1479 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1480 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1481 int numBits = Integer.bitCount(i); 1482 int[] set = new int[numBits]; 1483 int pos = 0; 1484 for (int j = 0; j < orderedIds.length; j += 2) { 1485 if ((i & orderedIds[j+1]) != 0) { 1486 set[pos++] = orderedIds[j]; 1487 } 1488 } 1489 VIEW_STATE_SETS[i] = set; 1490 } 1491 1492 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1493 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1494 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1495 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1496 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1497 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1498 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1499 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1500 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1501 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1502 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1503 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1504 | VIEW_STATE_FOCUSED]; 1505 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1506 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1507 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1508 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1509 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1510 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1511 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1512 | VIEW_STATE_ENABLED]; 1513 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1514 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1515 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1516 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1517 | VIEW_STATE_ENABLED]; 1518 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1519 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1520 | VIEW_STATE_ENABLED]; 1521 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1522 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1523 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1524 1525 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1526 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1527 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1528 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1529 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1530 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1531 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1532 | VIEW_STATE_PRESSED]; 1533 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1534 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1535 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1536 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1537 | VIEW_STATE_PRESSED]; 1538 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1539 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1540 | VIEW_STATE_PRESSED]; 1541 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1542 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1543 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1544 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1545 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1546 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1547 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1548 | VIEW_STATE_PRESSED]; 1549 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1550 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1551 | VIEW_STATE_PRESSED]; 1552 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1553 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1554 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1555 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1556 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1557 | VIEW_STATE_PRESSED]; 1558 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1559 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1560 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1561 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1562 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1563 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1564 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1565 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1566 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1567 | VIEW_STATE_PRESSED]; 1568 } 1569 1570 /** 1571 * Accessibility event types that are dispatched for text population. 1572 */ 1573 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1574 AccessibilityEvent.TYPE_VIEW_CLICKED 1575 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1576 | AccessibilityEvent.TYPE_VIEW_SELECTED 1577 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1578 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1579 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1580 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1581 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1582 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1583 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1584 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1585 1586 /** 1587 * Temporary Rect currently for use in setBackground(). This will probably 1588 * be extended in the future to hold our own class with more than just 1589 * a Rect. :) 1590 */ 1591 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1592 1593 /** 1594 * Map used to store views' tags. 1595 */ 1596 private SparseArray<Object> mKeyedTags; 1597 1598 /** 1599 * The next available accessibility id. 1600 */ 1601 private static int sNextAccessibilityViewId; 1602 1603 /** 1604 * The animation currently associated with this view. 1605 * @hide 1606 */ 1607 protected Animation mCurrentAnimation = null; 1608 1609 /** 1610 * Width as measured during measure pass. 1611 * {@hide} 1612 */ 1613 @ViewDebug.ExportedProperty(category = "measurement") 1614 int mMeasuredWidth; 1615 1616 /** 1617 * Height as measured during measure pass. 1618 * {@hide} 1619 */ 1620 @ViewDebug.ExportedProperty(category = "measurement") 1621 int mMeasuredHeight; 1622 1623 /** 1624 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1625 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1626 * its display list. This flag, used only when hw accelerated, allows us to clear the 1627 * flag while retaining this information until it's needed (at getDisplayList() time and 1628 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1629 * 1630 * {@hide} 1631 */ 1632 boolean mRecreateDisplayList = false; 1633 1634 /** 1635 * The view's identifier. 1636 * {@hide} 1637 * 1638 * @see #setId(int) 1639 * @see #getId() 1640 */ 1641 @ViewDebug.ExportedProperty(resolveId = true) 1642 int mID = NO_ID; 1643 1644 /** 1645 * The stable ID of this view for accessibility purposes. 1646 */ 1647 int mAccessibilityViewId = NO_ID; 1648 1649 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1650 1651 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1652 1653 /** 1654 * The view's tag. 1655 * {@hide} 1656 * 1657 * @see #setTag(Object) 1658 * @see #getTag() 1659 */ 1660 protected Object mTag = null; 1661 1662 // for mPrivateFlags: 1663 /** {@hide} */ 1664 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1665 /** {@hide} */ 1666 static final int PFLAG_FOCUSED = 0x00000002; 1667 /** {@hide} */ 1668 static final int PFLAG_SELECTED = 0x00000004; 1669 /** {@hide} */ 1670 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1671 /** {@hide} */ 1672 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1673 /** {@hide} */ 1674 static final int PFLAG_DRAWN = 0x00000020; 1675 /** 1676 * When this flag is set, this view is running an animation on behalf of its 1677 * children and should therefore not cancel invalidate requests, even if they 1678 * lie outside of this view's bounds. 1679 * 1680 * {@hide} 1681 */ 1682 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1683 /** {@hide} */ 1684 static final int PFLAG_SKIP_DRAW = 0x00000080; 1685 /** {@hide} */ 1686 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1687 /** {@hide} */ 1688 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1689 /** {@hide} */ 1690 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1691 /** {@hide} */ 1692 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1693 /** {@hide} */ 1694 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1695 /** {@hide} */ 1696 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1697 1698 private static final int PFLAG_PRESSED = 0x00004000; 1699 1700 /** {@hide} */ 1701 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1702 /** 1703 * Flag used to indicate that this view should be drawn once more (and only once 1704 * more) after its animation has completed. 1705 * {@hide} 1706 */ 1707 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1708 1709 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1710 1711 /** 1712 * Indicates that the View returned true when onSetAlpha() was called and that 1713 * the alpha must be restored. 1714 * {@hide} 1715 */ 1716 static final int PFLAG_ALPHA_SET = 0x00040000; 1717 1718 /** 1719 * Set by {@link #setScrollContainer(boolean)}. 1720 */ 1721 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1722 1723 /** 1724 * Set by {@link #setScrollContainer(boolean)}. 1725 */ 1726 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1727 1728 /** 1729 * View flag indicating whether this view was invalidated (fully or partially.) 1730 * 1731 * @hide 1732 */ 1733 static final int PFLAG_DIRTY = 0x00200000; 1734 1735 /** 1736 * View flag indicating whether this view was invalidated by an opaque 1737 * invalidate request. 1738 * 1739 * @hide 1740 */ 1741 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1742 1743 /** 1744 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1745 * 1746 * @hide 1747 */ 1748 static final int PFLAG_DIRTY_MASK = 0x00600000; 1749 1750 /** 1751 * Indicates whether the background is opaque. 1752 * 1753 * @hide 1754 */ 1755 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1756 1757 /** 1758 * Indicates whether the scrollbars are opaque. 1759 * 1760 * @hide 1761 */ 1762 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1763 1764 /** 1765 * Indicates whether the view is opaque. 1766 * 1767 * @hide 1768 */ 1769 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1770 1771 /** 1772 * Indicates a prepressed state; 1773 * the short time between ACTION_DOWN and recognizing 1774 * a 'real' press. Prepressed is used to recognize quick taps 1775 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1776 * 1777 * @hide 1778 */ 1779 private static final int PFLAG_PREPRESSED = 0x02000000; 1780 1781 /** 1782 * Indicates whether the view is temporarily detached. 1783 * 1784 * @hide 1785 */ 1786 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1787 1788 /** 1789 * Indicates that we should awaken scroll bars once attached 1790 * 1791 * @hide 1792 */ 1793 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1794 1795 /** 1796 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1797 * @hide 1798 */ 1799 private static final int PFLAG_HOVERED = 0x10000000; 1800 1801 /** 1802 * no longer needed, should be reused 1803 */ 1804 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1805 1806 /** {@hide} */ 1807 static final int PFLAG_ACTIVATED = 0x40000000; 1808 1809 /** 1810 * Indicates that this view was specifically invalidated, not just dirtied because some 1811 * child view was invalidated. The flag is used to determine when we need to recreate 1812 * a view's display list (as opposed to just returning a reference to its existing 1813 * display list). 1814 * 1815 * @hide 1816 */ 1817 static final int PFLAG_INVALIDATED = 0x80000000; 1818 1819 /** 1820 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1821 * 1822 * |-------|-------|-------|-------| 1823 * 1 PFLAG2_DRAG_CAN_ACCEPT 1824 * 1 PFLAG2_DRAG_HOVERED 1825 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1826 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1827 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1828 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1829 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1830 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1831 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1832 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1833 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1834 * 111 PFLAG2_TEXT_DIRECTION_MASK 1835 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1836 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1837 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1838 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1839 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1840 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1841 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1842 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1843 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1844 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1845 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1846 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1847 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1848 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1849 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1850 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1851 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1852 * 1 PFLAG2_VIEW_QUICK_REJECTED 1853 * 1 PFLAG2_PADDING_RESOLVED 1854 * 1 PFLAG2_DRAWABLE_RESOLVED 1855 * 1 PFLAG2_HAS_TRANSIENT_STATE 1856 * |-------|-------|-------|-------| 1857 */ 1858 1859 /** 1860 * Indicates that this view has reported that it can accept the current drag's content. 1861 * Cleared when the drag operation concludes. 1862 * @hide 1863 */ 1864 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1865 1866 /** 1867 * Indicates that this view is currently directly under the drag location in a 1868 * drag-and-drop operation involving content that it can accept. Cleared when 1869 * the drag exits the view, or when the drag operation concludes. 1870 * @hide 1871 */ 1872 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1873 1874 /** @hide */ 1875 @IntDef({ 1876 LAYOUT_DIRECTION_LTR, 1877 LAYOUT_DIRECTION_RTL, 1878 LAYOUT_DIRECTION_INHERIT, 1879 LAYOUT_DIRECTION_LOCALE 1880 }) 1881 @Retention(RetentionPolicy.SOURCE) 1882 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1883 public @interface LayoutDir {} 1884 1885 /** @hide */ 1886 @IntDef({ 1887 LAYOUT_DIRECTION_LTR, 1888 LAYOUT_DIRECTION_RTL 1889 }) 1890 @Retention(RetentionPolicy.SOURCE) 1891 public @interface ResolvedLayoutDir {} 1892 1893 /** 1894 * Horizontal layout direction of this view is from Left to Right. 1895 * Use with {@link #setLayoutDirection}. 1896 */ 1897 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1898 1899 /** 1900 * Horizontal layout direction of this view is from Right to Left. 1901 * Use with {@link #setLayoutDirection}. 1902 */ 1903 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1904 1905 /** 1906 * Horizontal layout direction of this view is inherited from its parent. 1907 * Use with {@link #setLayoutDirection}. 1908 */ 1909 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1910 1911 /** 1912 * Horizontal layout direction of this view is from deduced from the default language 1913 * script for the locale. Use with {@link #setLayoutDirection}. 1914 */ 1915 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1916 1917 /** 1918 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1919 * @hide 1920 */ 1921 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1922 1923 /** 1924 * Mask for use with private flags indicating bits used for horizontal layout direction. 1925 * @hide 1926 */ 1927 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1928 1929 /** 1930 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1931 * right-to-left direction. 1932 * @hide 1933 */ 1934 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1935 1936 /** 1937 * Indicates whether the view horizontal layout direction has been resolved. 1938 * @hide 1939 */ 1940 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1941 1942 /** 1943 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1944 * @hide 1945 */ 1946 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1947 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1948 1949 /* 1950 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1951 * flag value. 1952 * @hide 1953 */ 1954 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1955 LAYOUT_DIRECTION_LTR, 1956 LAYOUT_DIRECTION_RTL, 1957 LAYOUT_DIRECTION_INHERIT, 1958 LAYOUT_DIRECTION_LOCALE 1959 }; 1960 1961 /** 1962 * Default horizontal layout direction. 1963 */ 1964 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1965 1966 /** 1967 * Default horizontal layout direction. 1968 * @hide 1969 */ 1970 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1971 1972 /** 1973 * Text direction is inherited thru {@link ViewGroup} 1974 */ 1975 public static final int TEXT_DIRECTION_INHERIT = 0; 1976 1977 /** 1978 * Text direction is using "first strong algorithm". The first strong directional character 1979 * determines the paragraph direction. If there is no strong directional character, the 1980 * paragraph direction is the view's resolved layout direction. 1981 */ 1982 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1983 1984 /** 1985 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1986 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1987 * If there are neither, the paragraph direction is the view's resolved layout direction. 1988 */ 1989 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1990 1991 /** 1992 * Text direction is forced to LTR. 1993 */ 1994 public static final int TEXT_DIRECTION_LTR = 3; 1995 1996 /** 1997 * Text direction is forced to RTL. 1998 */ 1999 public static final int TEXT_DIRECTION_RTL = 4; 2000 2001 /** 2002 * Text direction is coming from the system Locale. 2003 */ 2004 public static final int TEXT_DIRECTION_LOCALE = 5; 2005 2006 /** 2007 * Default text direction is inherited 2008 */ 2009 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2010 2011 /** 2012 * Default resolved text direction 2013 * @hide 2014 */ 2015 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2016 2017 /** 2018 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2019 * @hide 2020 */ 2021 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2022 2023 /** 2024 * Mask for use with private flags indicating bits used for text direction. 2025 * @hide 2026 */ 2027 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2028 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2029 2030 /** 2031 * Array of text direction flags for mapping attribute "textDirection" to correct 2032 * flag value. 2033 * @hide 2034 */ 2035 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2036 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2037 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2038 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2039 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2040 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2041 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2042 }; 2043 2044 /** 2045 * Indicates whether the view text direction has been resolved. 2046 * @hide 2047 */ 2048 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2049 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2050 2051 /** 2052 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2053 * @hide 2054 */ 2055 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2056 2057 /** 2058 * Mask for use with private flags indicating bits used for resolved text direction. 2059 * @hide 2060 */ 2061 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2062 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2063 2064 /** 2065 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2066 * @hide 2067 */ 2068 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2069 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2070 2071 /** @hide */ 2072 @IntDef({ 2073 TEXT_ALIGNMENT_INHERIT, 2074 TEXT_ALIGNMENT_GRAVITY, 2075 TEXT_ALIGNMENT_CENTER, 2076 TEXT_ALIGNMENT_TEXT_START, 2077 TEXT_ALIGNMENT_TEXT_END, 2078 TEXT_ALIGNMENT_VIEW_START, 2079 TEXT_ALIGNMENT_VIEW_END 2080 }) 2081 @Retention(RetentionPolicy.SOURCE) 2082 public @interface TextAlignment {} 2083 2084 /** 2085 * Default text alignment. The text alignment of this View is inherited from its parent. 2086 * Use with {@link #setTextAlignment(int)} 2087 */ 2088 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2089 2090 /** 2091 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2092 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2093 * 2094 * Use with {@link #setTextAlignment(int)} 2095 */ 2096 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2097 2098 /** 2099 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2100 * 2101 * Use with {@link #setTextAlignment(int)} 2102 */ 2103 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2104 2105 /** 2106 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2107 * 2108 * Use with {@link #setTextAlignment(int)} 2109 */ 2110 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2111 2112 /** 2113 * Center the paragraph, e.g. ALIGN_CENTER. 2114 * 2115 * Use with {@link #setTextAlignment(int)} 2116 */ 2117 public static final int TEXT_ALIGNMENT_CENTER = 4; 2118 2119 /** 2120 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2121 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2122 * 2123 * Use with {@link #setTextAlignment(int)} 2124 */ 2125 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2126 2127 /** 2128 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2129 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2130 * 2131 * Use with {@link #setTextAlignment(int)} 2132 */ 2133 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2134 2135 /** 2136 * Default text alignment is inherited 2137 */ 2138 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2139 2140 /** 2141 * Default resolved text alignment 2142 * @hide 2143 */ 2144 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2145 2146 /** 2147 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2148 * @hide 2149 */ 2150 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2151 2152 /** 2153 * Mask for use with private flags indicating bits used for text alignment. 2154 * @hide 2155 */ 2156 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2157 2158 /** 2159 * Array of text direction flags for mapping attribute "textAlignment" to correct 2160 * flag value. 2161 * @hide 2162 */ 2163 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2164 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2165 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2166 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2167 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2168 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2169 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2170 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2171 }; 2172 2173 /** 2174 * Indicates whether the view text alignment has been resolved. 2175 * @hide 2176 */ 2177 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2178 2179 /** 2180 * Bit shift to get the resolved text alignment. 2181 * @hide 2182 */ 2183 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2184 2185 /** 2186 * Mask for use with private flags indicating bits used for text alignment. 2187 * @hide 2188 */ 2189 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2190 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2191 2192 /** 2193 * Indicates whether if the view text alignment has been resolved to gravity 2194 */ 2195 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2196 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2197 2198 // Accessiblity constants for mPrivateFlags2 2199 2200 /** 2201 * Shift for the bits in {@link #mPrivateFlags2} related to the 2202 * "importantForAccessibility" attribute. 2203 */ 2204 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2205 2206 /** 2207 * Automatically determine whether a view is important for accessibility. 2208 */ 2209 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2210 2211 /** 2212 * The view is important for accessibility. 2213 */ 2214 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2215 2216 /** 2217 * The view is not important for accessibility. 2218 */ 2219 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2220 2221 /** 2222 * The view is not important for accessibility, nor are any of its 2223 * descendant views. 2224 */ 2225 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2226 2227 /** 2228 * The default whether the view is important for accessibility. 2229 */ 2230 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2231 2232 /** 2233 * Mask for obtainig the bits which specify how to determine 2234 * whether a view is important for accessibility. 2235 */ 2236 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2237 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2238 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2239 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2240 2241 /** 2242 * Shift for the bits in {@link #mPrivateFlags2} related to the 2243 * "accessibilityLiveRegion" attribute. 2244 */ 2245 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2246 2247 /** 2248 * Live region mode specifying that accessibility services should not 2249 * automatically announce changes to this view. This is the default live 2250 * region mode for most views. 2251 * <p> 2252 * Use with {@link #setAccessibilityLiveRegion(int)}. 2253 */ 2254 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2255 2256 /** 2257 * Live region mode specifying that accessibility services should announce 2258 * changes to this view. 2259 * <p> 2260 * Use with {@link #setAccessibilityLiveRegion(int)}. 2261 */ 2262 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2263 2264 /** 2265 * Live region mode specifying that accessibility services should interrupt 2266 * ongoing speech to immediately announce changes to this view. 2267 * <p> 2268 * Use with {@link #setAccessibilityLiveRegion(int)}. 2269 */ 2270 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2271 2272 /** 2273 * The default whether the view is important for accessibility. 2274 */ 2275 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2276 2277 /** 2278 * Mask for obtaining the bits which specify a view's accessibility live 2279 * region mode. 2280 */ 2281 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2282 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2283 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2284 2285 /** 2286 * Flag indicating whether a view has accessibility focus. 2287 */ 2288 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2289 2290 /** 2291 * Flag whether the accessibility state of the subtree rooted at this view changed. 2292 */ 2293 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2294 2295 /** 2296 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2297 * is used to check whether later changes to the view's transform should invalidate the 2298 * view to force the quickReject test to run again. 2299 */ 2300 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2301 2302 /** 2303 * Flag indicating that start/end padding has been resolved into left/right padding 2304 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2305 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2306 * during measurement. In some special cases this is required such as when an adapter-based 2307 * view measures prospective children without attaching them to a window. 2308 */ 2309 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2310 2311 /** 2312 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2313 */ 2314 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2315 2316 /** 2317 * Indicates that the view is tracking some sort of transient state 2318 * that the app should not need to be aware of, but that the framework 2319 * should take special care to preserve. 2320 */ 2321 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2322 2323 /** 2324 * Group of bits indicating that RTL properties resolution is done. 2325 */ 2326 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2327 PFLAG2_TEXT_DIRECTION_RESOLVED | 2328 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2329 PFLAG2_PADDING_RESOLVED | 2330 PFLAG2_DRAWABLE_RESOLVED; 2331 2332 // There are a couple of flags left in mPrivateFlags2 2333 2334 /* End of masks for mPrivateFlags2 */ 2335 2336 /** 2337 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2338 * 2339 * |-------|-------|-------|-------| 2340 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2341 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2342 * 1 PFLAG3_IS_LAID_OUT 2343 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2344 * 1 PFLAG3_CALLED_SUPER 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 a view's outline has been specifically defined. 2382 */ 2383 static final int PFLAG3_OUTLINE_DEFINED = 0x20; 2384 2385 /** 2386 * Flag indicating that we're in the process of applying window insets. 2387 */ 2388 static final int PFLAG3_APPLYING_INSETS = 0x40; 2389 2390 /** 2391 * Flag indicating that we're in the process of fitting system windows using the old method. 2392 */ 2393 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x80; 2394 2395 /** 2396 * Flag indicating that nested scrolling is enabled for this view. 2397 * The view will optionally cooperate with views up its parent chain to allow for 2398 * integrated nested scrolling along the same axis. 2399 */ 2400 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x200; 2401 2402 /* End of masks for mPrivateFlags3 */ 2403 2404 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2405 2406 /** 2407 * Always allow a user to over-scroll this view, provided it is a 2408 * view that can scroll. 2409 * 2410 * @see #getOverScrollMode() 2411 * @see #setOverScrollMode(int) 2412 */ 2413 public static final int OVER_SCROLL_ALWAYS = 0; 2414 2415 /** 2416 * Allow a user to over-scroll this view only if the content is large 2417 * enough to meaningfully scroll, provided it is a view that can scroll. 2418 * 2419 * @see #getOverScrollMode() 2420 * @see #setOverScrollMode(int) 2421 */ 2422 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2423 2424 /** 2425 * Never allow a user to over-scroll this view. 2426 * 2427 * @see #getOverScrollMode() 2428 * @see #setOverScrollMode(int) 2429 */ 2430 public static final int OVER_SCROLL_NEVER = 2; 2431 2432 /** 2433 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2434 * requested the system UI (status bar) to be visible (the default). 2435 * 2436 * @see #setSystemUiVisibility(int) 2437 */ 2438 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2439 2440 /** 2441 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2442 * system UI to enter an unobtrusive "low profile" mode. 2443 * 2444 * <p>This is for use in games, book readers, video players, or any other 2445 * "immersive" application where the usual system chrome is deemed too distracting. 2446 * 2447 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2448 * 2449 * @see #setSystemUiVisibility(int) 2450 */ 2451 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2452 2453 /** 2454 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2455 * system navigation be temporarily hidden. 2456 * 2457 * <p>This is an even less obtrusive state than that called for by 2458 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2459 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2460 * those to disappear. This is useful (in conjunction with the 2461 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2462 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2463 * window flags) for displaying content using every last pixel on the display. 2464 * 2465 * <p>There is a limitation: because navigation controls are so important, the least user 2466 * interaction will cause them to reappear immediately. When this happens, both 2467 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2468 * so that both elements reappear at the same time. 2469 * 2470 * @see #setSystemUiVisibility(int) 2471 */ 2472 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2473 2474 /** 2475 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2476 * into the normal fullscreen mode so that its content can take over the screen 2477 * while still allowing the user to interact with the application. 2478 * 2479 * <p>This has the same visual effect as 2480 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2481 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2482 * meaning that non-critical screen decorations (such as the status bar) will be 2483 * hidden while the user is in the View's window, focusing the experience on 2484 * that content. Unlike the window flag, if you are using ActionBar in 2485 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2486 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2487 * hide the action bar. 2488 * 2489 * <p>This approach to going fullscreen is best used over the window flag when 2490 * it is a transient state -- that is, the application does this at certain 2491 * points in its user interaction where it wants to allow the user to focus 2492 * on content, but not as a continuous state. For situations where the application 2493 * would like to simply stay full screen the entire time (such as a game that 2494 * wants to take over the screen), the 2495 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2496 * is usually a better approach. The state set here will be removed by the system 2497 * in various situations (such as the user moving to another application) like 2498 * the other system UI states. 2499 * 2500 * <p>When using this flag, the application should provide some easy facility 2501 * for the user to go out of it. A common example would be in an e-book 2502 * reader, where tapping on the screen brings back whatever screen and UI 2503 * decorations that had been hidden while the user was immersed in reading 2504 * the book. 2505 * 2506 * @see #setSystemUiVisibility(int) 2507 */ 2508 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2509 2510 /** 2511 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2512 * flags, we would like a stable view of the content insets given to 2513 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2514 * will always represent the worst case that the application can expect 2515 * as a continuous state. In the stock Android UI this is the space for 2516 * the system bar, nav bar, and status bar, but not more transient elements 2517 * such as an input method. 2518 * 2519 * The stable layout your UI sees is based on the system UI modes you can 2520 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2521 * then you will get a stable layout for changes of the 2522 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2523 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2524 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2525 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2526 * with a stable layout. (Note that you should avoid using 2527 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2528 * 2529 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2530 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2531 * then a hidden status bar will be considered a "stable" state for purposes 2532 * here. This allows your UI to continually hide the status bar, while still 2533 * using the system UI flags to hide the action bar while still retaining 2534 * a stable layout. Note that changing the window fullscreen flag will never 2535 * provide a stable layout for a clean transition. 2536 * 2537 * <p>If you are using ActionBar in 2538 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2539 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2540 * insets it adds to those given to the application. 2541 */ 2542 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2543 2544 /** 2545 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2546 * to be layed out as if it has requested 2547 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2548 * allows it to avoid artifacts when switching in and out of that mode, at 2549 * the expense that some of its user interface may be covered by screen 2550 * decorations when they are shown. You can perform layout of your inner 2551 * UI elements to account for the navigation system UI through the 2552 * {@link #fitSystemWindows(Rect)} method. 2553 */ 2554 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2555 2556 /** 2557 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2558 * to be layed out as if it has requested 2559 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2560 * allows it to avoid artifacts when switching in and out of that mode, at 2561 * the expense that some of its user interface may be covered by screen 2562 * decorations when they are shown. You can perform layout of your inner 2563 * UI elements to account for non-fullscreen system UI through the 2564 * {@link #fitSystemWindows(Rect)} method. 2565 */ 2566 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2567 2568 /** 2569 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2570 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2571 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2572 * user interaction. 2573 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2574 * has an effect when used in combination with that flag.</p> 2575 */ 2576 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2577 2578 /** 2579 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2580 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2581 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2582 * experience while also hiding the system bars. If this flag is not set, 2583 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2584 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2585 * if the user swipes from the top of the screen. 2586 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2587 * system gestures, such as swiping from the top of the screen. These transient system bars 2588 * will overlay app’s content, may have some degree of transparency, and will automatically 2589 * hide after a short timeout. 2590 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2591 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2592 * with one or both of those flags.</p> 2593 */ 2594 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2595 2596 /** 2597 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2598 */ 2599 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2600 2601 /** 2602 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2603 */ 2604 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2605 2606 /** 2607 * @hide 2608 * 2609 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2610 * out of the public fields to keep the undefined bits out of the developer's way. 2611 * 2612 * Flag to make the status bar not expandable. Unless you also 2613 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2614 */ 2615 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2616 2617 /** 2618 * @hide 2619 * 2620 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2621 * out of the public fields to keep the undefined bits out of the developer's way. 2622 * 2623 * Flag to hide notification icons and scrolling ticker text. 2624 */ 2625 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2626 2627 /** 2628 * @hide 2629 * 2630 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2631 * out of the public fields to keep the undefined bits out of the developer's way. 2632 * 2633 * Flag to disable incoming notification alerts. This will not block 2634 * icons, but it will block sound, vibrating and other visual or aural notifications. 2635 */ 2636 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2637 2638 /** 2639 * @hide 2640 * 2641 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2642 * out of the public fields to keep the undefined bits out of the developer's way. 2643 * 2644 * Flag to hide only the scrolling ticker. Note that 2645 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2646 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2647 */ 2648 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2649 2650 /** 2651 * @hide 2652 * 2653 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2654 * out of the public fields to keep the undefined bits out of the developer's way. 2655 * 2656 * Flag to hide the center system info area. 2657 */ 2658 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2659 2660 /** 2661 * @hide 2662 * 2663 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2664 * out of the public fields to keep the undefined bits out of the developer's way. 2665 * 2666 * Flag to hide only the home button. Don't use this 2667 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2668 */ 2669 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2670 2671 /** 2672 * @hide 2673 * 2674 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2675 * out of the public fields to keep the undefined bits out of the developer's way. 2676 * 2677 * Flag to hide only the back button. Don't use this 2678 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2679 */ 2680 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2681 2682 /** 2683 * @hide 2684 * 2685 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2686 * out of the public fields to keep the undefined bits out of the developer's way. 2687 * 2688 * Flag to hide only the clock. You might use this if your activity has 2689 * its own clock making the status bar's clock redundant. 2690 */ 2691 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2692 2693 /** 2694 * @hide 2695 * 2696 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2697 * out of the public fields to keep the undefined bits out of the developer's way. 2698 * 2699 * Flag to hide only the recent apps button. Don't use this 2700 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2701 */ 2702 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2703 2704 /** 2705 * @hide 2706 * 2707 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2708 * out of the public fields to keep the undefined bits out of the developer's way. 2709 * 2710 * Flag to disable the global search gesture. Don't use this 2711 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2712 */ 2713 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2714 2715 /** 2716 * @hide 2717 * 2718 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2719 * out of the public fields to keep the undefined bits out of the developer's way. 2720 * 2721 * Flag to specify that the status bar is displayed in transient mode. 2722 */ 2723 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2724 2725 /** 2726 * @hide 2727 * 2728 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2729 * out of the public fields to keep the undefined bits out of the developer's way. 2730 * 2731 * Flag to specify that the navigation bar is displayed in transient mode. 2732 */ 2733 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2734 2735 /** 2736 * @hide 2737 * 2738 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2739 * out of the public fields to keep the undefined bits out of the developer's way. 2740 * 2741 * Flag to specify that the hidden status bar would like to be shown. 2742 */ 2743 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2744 2745 /** 2746 * @hide 2747 * 2748 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2749 * out of the public fields to keep the undefined bits out of the developer's way. 2750 * 2751 * Flag to specify that the hidden navigation bar would like to be shown. 2752 */ 2753 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2754 2755 /** 2756 * @hide 2757 * 2758 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2759 * out of the public fields to keep the undefined bits out of the developer's way. 2760 * 2761 * Flag to specify that the status bar is displayed in translucent mode. 2762 */ 2763 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 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 specify that the navigation bar is displayed in translucent mode. 2772 */ 2773 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2774 2775 /** 2776 * @hide 2777 * 2778 * Makes system ui transparent. 2779 */ 2780 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2781 2782 /** 2783 * @hide 2784 */ 2785 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00007FFF; 2786 2787 /** 2788 * These are the system UI flags that can be cleared by events outside 2789 * of an application. Currently this is just the ability to tap on the 2790 * screen while hiding the navigation bar to have it return. 2791 * @hide 2792 */ 2793 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2794 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2795 | SYSTEM_UI_FLAG_FULLSCREEN; 2796 2797 /** 2798 * Flags that can impact the layout in relation to system UI. 2799 */ 2800 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2801 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2802 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2803 2804 /** @hide */ 2805 @IntDef(flag = true, 2806 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2807 @Retention(RetentionPolicy.SOURCE) 2808 public @interface FindViewFlags {} 2809 2810 /** 2811 * Find views that render the specified text. 2812 * 2813 * @see #findViewsWithText(ArrayList, CharSequence, int) 2814 */ 2815 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2816 2817 /** 2818 * Find find views that contain the specified content description. 2819 * 2820 * @see #findViewsWithText(ArrayList, CharSequence, int) 2821 */ 2822 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2823 2824 /** 2825 * Find views that contain {@link AccessibilityNodeProvider}. Such 2826 * a View is a root of virtual view hierarchy and may contain the searched 2827 * text. If this flag is set Views with providers are automatically 2828 * added and it is a responsibility of the client to call the APIs of 2829 * the provider to determine whether the virtual tree rooted at this View 2830 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2831 * representing the virtual views with this text. 2832 * 2833 * @see #findViewsWithText(ArrayList, CharSequence, int) 2834 * 2835 * @hide 2836 */ 2837 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2838 2839 /** 2840 * The undefined cursor position. 2841 * 2842 * @hide 2843 */ 2844 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2845 2846 /** 2847 * Indicates that the screen has changed state and is now off. 2848 * 2849 * @see #onScreenStateChanged(int) 2850 */ 2851 public static final int SCREEN_STATE_OFF = 0x0; 2852 2853 /** 2854 * Indicates that the screen has changed state and is now on. 2855 * 2856 * @see #onScreenStateChanged(int) 2857 */ 2858 public static final int SCREEN_STATE_ON = 0x1; 2859 2860 /** 2861 * Indicates no axis of view scrolling. 2862 */ 2863 public static final int SCROLL_AXIS_NONE = 0; 2864 2865 /** 2866 * Indicates scrolling along the horizontal axis. 2867 */ 2868 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 2869 2870 /** 2871 * Indicates scrolling along the vertical axis. 2872 */ 2873 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 2874 2875 /** 2876 * Controls the over-scroll mode for this view. 2877 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2878 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2879 * and {@link #OVER_SCROLL_NEVER}. 2880 */ 2881 private int mOverScrollMode; 2882 2883 /** 2884 * The parent this view is attached to. 2885 * {@hide} 2886 * 2887 * @see #getParent() 2888 */ 2889 protected ViewParent mParent; 2890 2891 /** 2892 * {@hide} 2893 */ 2894 AttachInfo mAttachInfo; 2895 2896 /** 2897 * {@hide} 2898 */ 2899 @ViewDebug.ExportedProperty(flagMapping = { 2900 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2901 name = "FORCE_LAYOUT"), 2902 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2903 name = "LAYOUT_REQUIRED"), 2904 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2905 name = "DRAWING_CACHE_INVALID", outputIf = false), 2906 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2907 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2908 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2909 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2910 }) 2911 int mPrivateFlags; 2912 int mPrivateFlags2; 2913 int mPrivateFlags3; 2914 2915 /** 2916 * This view's request for the visibility of the status bar. 2917 * @hide 2918 */ 2919 @ViewDebug.ExportedProperty(flagMapping = { 2920 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2921 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2922 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2923 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2924 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2925 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2926 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2927 equals = SYSTEM_UI_FLAG_VISIBLE, 2928 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2929 }) 2930 int mSystemUiVisibility; 2931 2932 /** 2933 * Reference count for transient state. 2934 * @see #setHasTransientState(boolean) 2935 */ 2936 int mTransientStateCount = 0; 2937 2938 /** 2939 * Count of how many windows this view has been attached to. 2940 */ 2941 int mWindowAttachCount; 2942 2943 /** 2944 * The layout parameters associated with this view and used by the parent 2945 * {@link android.view.ViewGroup} to determine how this view should be 2946 * laid out. 2947 * {@hide} 2948 */ 2949 protected ViewGroup.LayoutParams mLayoutParams; 2950 2951 /** 2952 * The view flags hold various views states. 2953 * {@hide} 2954 */ 2955 @ViewDebug.ExportedProperty 2956 int mViewFlags; 2957 2958 static class TransformationInfo { 2959 /** 2960 * The transform matrix for the View. This transform is calculated internally 2961 * based on the translation, rotation, and scale properties. 2962 * 2963 * Do *not* use this variable directly; instead call getMatrix(), which will 2964 * load the value from the View's RenderNode. 2965 */ 2966 private final Matrix mMatrix = new Matrix(); 2967 2968 /** 2969 * The inverse transform matrix for the View. This transform is calculated 2970 * internally based on the translation, rotation, and scale properties. 2971 * 2972 * Do *not* use this variable directly; instead call getInverseMatrix(), 2973 * which will load the value from the View's RenderNode. 2974 */ 2975 private Matrix mInverseMatrix; 2976 2977 /** 2978 * The opacity of the View. This is a value from 0 to 1, where 0 means 2979 * completely transparent and 1 means completely opaque. 2980 */ 2981 @ViewDebug.ExportedProperty 2982 float mAlpha = 1f; 2983 2984 /** 2985 * The opacity of the view as manipulated by the Fade transition. This is a hidden 2986 * property only used by transitions, which is composited with the other alpha 2987 * values to calculate the final visual alpha value. 2988 */ 2989 float mTransitionAlpha = 1f; 2990 } 2991 2992 TransformationInfo mTransformationInfo; 2993 2994 /** 2995 * Current clip bounds. to which all drawing of this view are constrained. 2996 */ 2997 Rect mClipBounds = null; 2998 2999 private boolean mLastIsOpaque; 3000 3001 /** 3002 * The distance in pixels from the left edge of this view's parent 3003 * to the left edge of this view. 3004 * {@hide} 3005 */ 3006 @ViewDebug.ExportedProperty(category = "layout") 3007 protected int mLeft; 3008 /** 3009 * The distance in pixels from the left edge of this view's parent 3010 * to the right edge of this view. 3011 * {@hide} 3012 */ 3013 @ViewDebug.ExportedProperty(category = "layout") 3014 protected int mRight; 3015 /** 3016 * The distance in pixels from the top edge of this view's parent 3017 * to the top edge of this view. 3018 * {@hide} 3019 */ 3020 @ViewDebug.ExportedProperty(category = "layout") 3021 protected int mTop; 3022 /** 3023 * The distance in pixels from the top edge of this view's parent 3024 * to the bottom edge of this view. 3025 * {@hide} 3026 */ 3027 @ViewDebug.ExportedProperty(category = "layout") 3028 protected int mBottom; 3029 3030 /** 3031 * The offset, in pixels, by which the content of this view is scrolled 3032 * horizontally. 3033 * {@hide} 3034 */ 3035 @ViewDebug.ExportedProperty(category = "scrolling") 3036 protected int mScrollX; 3037 /** 3038 * The offset, in pixels, by which the content of this view is scrolled 3039 * vertically. 3040 * {@hide} 3041 */ 3042 @ViewDebug.ExportedProperty(category = "scrolling") 3043 protected int mScrollY; 3044 3045 /** 3046 * The left padding in pixels, that is the distance in pixels between the 3047 * left edge of this view and the left edge of its content. 3048 * {@hide} 3049 */ 3050 @ViewDebug.ExportedProperty(category = "padding") 3051 protected int mPaddingLeft = 0; 3052 /** 3053 * The right padding in pixels, that is the distance in pixels between the 3054 * right edge of this view and the right edge of its content. 3055 * {@hide} 3056 */ 3057 @ViewDebug.ExportedProperty(category = "padding") 3058 protected int mPaddingRight = 0; 3059 /** 3060 * The top padding in pixels, that is the distance in pixels between the 3061 * top edge of this view and the top edge of its content. 3062 * {@hide} 3063 */ 3064 @ViewDebug.ExportedProperty(category = "padding") 3065 protected int mPaddingTop; 3066 /** 3067 * The bottom padding in pixels, that is the distance in pixels between the 3068 * bottom edge of this view and the bottom edge of its content. 3069 * {@hide} 3070 */ 3071 @ViewDebug.ExportedProperty(category = "padding") 3072 protected int mPaddingBottom; 3073 3074 /** 3075 * The layout insets in pixels, that is the distance in pixels between the 3076 * visible edges of this view its bounds. 3077 */ 3078 private Insets mLayoutInsets; 3079 3080 /** 3081 * Briefly describes the view and is primarily used for accessibility support. 3082 */ 3083 private CharSequence mContentDescription; 3084 3085 /** 3086 * Specifies the id of a view for which this view serves as a label for 3087 * accessibility purposes. 3088 */ 3089 private int mLabelForId = View.NO_ID; 3090 3091 /** 3092 * Predicate for matching labeled view id with its label for 3093 * accessibility purposes. 3094 */ 3095 private MatchLabelForPredicate mMatchLabelForPredicate; 3096 3097 /** 3098 * Predicate for matching a view by its id. 3099 */ 3100 private MatchIdPredicate mMatchIdPredicate; 3101 3102 /** 3103 * Cache the paddingRight set by the user to append to the scrollbar's size. 3104 * 3105 * @hide 3106 */ 3107 @ViewDebug.ExportedProperty(category = "padding") 3108 protected int mUserPaddingRight; 3109 3110 /** 3111 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3112 * 3113 * @hide 3114 */ 3115 @ViewDebug.ExportedProperty(category = "padding") 3116 protected int mUserPaddingBottom; 3117 3118 /** 3119 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3120 * 3121 * @hide 3122 */ 3123 @ViewDebug.ExportedProperty(category = "padding") 3124 protected int mUserPaddingLeft; 3125 3126 /** 3127 * Cache the paddingStart set by the user to append to the scrollbar's size. 3128 * 3129 */ 3130 @ViewDebug.ExportedProperty(category = "padding") 3131 int mUserPaddingStart; 3132 3133 /** 3134 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3135 * 3136 */ 3137 @ViewDebug.ExportedProperty(category = "padding") 3138 int mUserPaddingEnd; 3139 3140 /** 3141 * Cache initial left padding. 3142 * 3143 * @hide 3144 */ 3145 int mUserPaddingLeftInitial; 3146 3147 /** 3148 * Cache initial right padding. 3149 * 3150 * @hide 3151 */ 3152 int mUserPaddingRightInitial; 3153 3154 /** 3155 * Default undefined padding 3156 */ 3157 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3158 3159 /** 3160 * Cache if a left padding has been defined 3161 */ 3162 private boolean mLeftPaddingDefined = false; 3163 3164 /** 3165 * Cache if a right padding has been defined 3166 */ 3167 private boolean mRightPaddingDefined = false; 3168 3169 /** 3170 * @hide 3171 */ 3172 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3173 /** 3174 * @hide 3175 */ 3176 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3177 3178 private LongSparseLongArray mMeasureCache; 3179 3180 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3181 private Drawable mBackground; 3182 3183 /** 3184 * Display list used for backgrounds. 3185 * <p> 3186 * When non-null and valid, this is expected to contain an up-to-date copy 3187 * of the background drawable. It is cleared on temporary detach and reset 3188 * on cleanup. 3189 */ 3190 private RenderNode mBackgroundDisplayList; 3191 3192 private int mBackgroundResource; 3193 private boolean mBackgroundSizeChanged; 3194 3195 private String mViewName; 3196 3197 static class ListenerInfo { 3198 /** 3199 * Listener used to dispatch focus change events. 3200 * This field should be made private, so it is hidden from the SDK. 3201 * {@hide} 3202 */ 3203 protected OnFocusChangeListener mOnFocusChangeListener; 3204 3205 /** 3206 * Listeners for layout change events. 3207 */ 3208 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3209 3210 /** 3211 * Listeners for attach events. 3212 */ 3213 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3214 3215 /** 3216 * Listener used to dispatch click events. 3217 * This field should be made private, so it is hidden from the SDK. 3218 * {@hide} 3219 */ 3220 public OnClickListener mOnClickListener; 3221 3222 /** 3223 * Listener used to dispatch long click events. 3224 * This field should be made private, so it is hidden from the SDK. 3225 * {@hide} 3226 */ 3227 protected OnLongClickListener mOnLongClickListener; 3228 3229 /** 3230 * Listener used to build the context menu. 3231 * This field should be made private, so it is hidden from the SDK. 3232 * {@hide} 3233 */ 3234 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3235 3236 private OnKeyListener mOnKeyListener; 3237 3238 private OnTouchListener mOnTouchListener; 3239 3240 private OnHoverListener mOnHoverListener; 3241 3242 private OnGenericMotionListener mOnGenericMotionListener; 3243 3244 private OnDragListener mOnDragListener; 3245 3246 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3247 3248 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3249 } 3250 3251 ListenerInfo mListenerInfo; 3252 3253 /** 3254 * The application environment this view lives in. 3255 * This field should be made private, so it is hidden from the SDK. 3256 * {@hide} 3257 */ 3258 protected Context mContext; 3259 3260 private final Resources mResources; 3261 3262 private ScrollabilityCache mScrollCache; 3263 3264 private int[] mDrawableState = null; 3265 3266 /** 3267 * Stores the outline of the view, passed down to the DisplayList level for 3268 * defining shadow shape. 3269 */ 3270 private Outline mOutline; 3271 3272 /** 3273 * Animator that automatically runs based on state changes. 3274 */ 3275 private StateListAnimator mStateListAnimator; 3276 3277 /** 3278 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3279 * the user may specify which view to go to next. 3280 */ 3281 private int mNextFocusLeftId = View.NO_ID; 3282 3283 /** 3284 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3285 * the user may specify which view to go to next. 3286 */ 3287 private int mNextFocusRightId = View.NO_ID; 3288 3289 /** 3290 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3291 * the user may specify which view to go to next. 3292 */ 3293 private int mNextFocusUpId = View.NO_ID; 3294 3295 /** 3296 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3297 * the user may specify which view to go to next. 3298 */ 3299 private int mNextFocusDownId = View.NO_ID; 3300 3301 /** 3302 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3303 * the user may specify which view to go to next. 3304 */ 3305 int mNextFocusForwardId = View.NO_ID; 3306 3307 private CheckForLongPress mPendingCheckForLongPress; 3308 private CheckForTap mPendingCheckForTap = null; 3309 private PerformClick mPerformClick; 3310 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3311 3312 private UnsetPressedState mUnsetPressedState; 3313 3314 /** 3315 * Whether the long press's action has been invoked. The tap's action is invoked on the 3316 * up event while a long press is invoked as soon as the long press duration is reached, so 3317 * a long press could be performed before the tap is checked, in which case the tap's action 3318 * should not be invoked. 3319 */ 3320 private boolean mHasPerformedLongPress; 3321 3322 /** 3323 * The minimum height of the view. We'll try our best to have the height 3324 * of this view to at least this amount. 3325 */ 3326 @ViewDebug.ExportedProperty(category = "measurement") 3327 private int mMinHeight; 3328 3329 /** 3330 * The minimum width of the view. We'll try our best to have the width 3331 * of this view to at least this amount. 3332 */ 3333 @ViewDebug.ExportedProperty(category = "measurement") 3334 private int mMinWidth; 3335 3336 /** 3337 * The delegate to handle touch events that are physically in this view 3338 * but should be handled by another view. 3339 */ 3340 private TouchDelegate mTouchDelegate = null; 3341 3342 /** 3343 * Solid color to use as a background when creating the drawing cache. Enables 3344 * the cache to use 16 bit bitmaps instead of 32 bit. 3345 */ 3346 private int mDrawingCacheBackgroundColor = 0; 3347 3348 /** 3349 * Special tree observer used when mAttachInfo is null. 3350 */ 3351 private ViewTreeObserver mFloatingTreeObserver; 3352 3353 /** 3354 * Cache the touch slop from the context that created the view. 3355 */ 3356 private int mTouchSlop; 3357 3358 /** 3359 * Object that handles automatic animation of view properties. 3360 */ 3361 private ViewPropertyAnimator mAnimator = null; 3362 3363 /** 3364 * Flag indicating that a drag can cross window boundaries. When 3365 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3366 * with this flag set, all visible applications will be able to participate 3367 * in the drag operation and receive the dragged content. 3368 * 3369 * @hide 3370 */ 3371 public static final int DRAG_FLAG_GLOBAL = 1; 3372 3373 /** 3374 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3375 */ 3376 private float mVerticalScrollFactor; 3377 3378 /** 3379 * Position of the vertical scroll bar. 3380 */ 3381 private int mVerticalScrollbarPosition; 3382 3383 /** 3384 * Position the scroll bar at the default position as determined by the system. 3385 */ 3386 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3387 3388 /** 3389 * Position the scroll bar along the left edge. 3390 */ 3391 public static final int SCROLLBAR_POSITION_LEFT = 1; 3392 3393 /** 3394 * Position the scroll bar along the right edge. 3395 */ 3396 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3397 3398 /** 3399 * Indicates that the view does not have a layer. 3400 * 3401 * @see #getLayerType() 3402 * @see #setLayerType(int, android.graphics.Paint) 3403 * @see #LAYER_TYPE_SOFTWARE 3404 * @see #LAYER_TYPE_HARDWARE 3405 */ 3406 public static final int LAYER_TYPE_NONE = 0; 3407 3408 /** 3409 * <p>Indicates that the view has a software layer. A software layer is backed 3410 * by a bitmap and causes the view to be rendered using Android's software 3411 * rendering pipeline, even if hardware acceleration is enabled.</p> 3412 * 3413 * <p>Software layers have various usages:</p> 3414 * <p>When the application is not using hardware acceleration, a software layer 3415 * is useful to apply a specific color filter and/or blending mode and/or 3416 * translucency to a view and all its children.</p> 3417 * <p>When the application is using hardware acceleration, a software layer 3418 * is useful to render drawing primitives not supported by the hardware 3419 * accelerated pipeline. It can also be used to cache a complex view tree 3420 * into a texture and reduce the complexity of drawing operations. For instance, 3421 * when animating a complex view tree with a translation, a software layer can 3422 * be used to render the view tree only once.</p> 3423 * <p>Software layers should be avoided when the affected view tree updates 3424 * often. Every update will require to re-render the software layer, which can 3425 * potentially be slow (particularly when hardware acceleration is turned on 3426 * since the layer will have to be uploaded into a hardware texture after every 3427 * update.)</p> 3428 * 3429 * @see #getLayerType() 3430 * @see #setLayerType(int, android.graphics.Paint) 3431 * @see #LAYER_TYPE_NONE 3432 * @see #LAYER_TYPE_HARDWARE 3433 */ 3434 public static final int LAYER_TYPE_SOFTWARE = 1; 3435 3436 /** 3437 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3438 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3439 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3440 * rendering pipeline, but only if hardware acceleration is turned on for the 3441 * view hierarchy. When hardware acceleration is turned off, hardware layers 3442 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3443 * 3444 * <p>A hardware layer is useful to apply a specific color filter and/or 3445 * blending mode and/or translucency to a view and all its children.</p> 3446 * <p>A hardware layer can be used to cache a complex view tree into a 3447 * texture and reduce the complexity of drawing operations. For instance, 3448 * when animating a complex view tree with a translation, a hardware layer can 3449 * be used to render the view tree only once.</p> 3450 * <p>A hardware layer can also be used to increase the rendering quality when 3451 * rotation transformations are applied on a view. It can also be used to 3452 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3453 * 3454 * @see #getLayerType() 3455 * @see #setLayerType(int, android.graphics.Paint) 3456 * @see #LAYER_TYPE_NONE 3457 * @see #LAYER_TYPE_SOFTWARE 3458 */ 3459 public static final int LAYER_TYPE_HARDWARE = 2; 3460 3461 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3462 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3463 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3464 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3465 }) 3466 int mLayerType = LAYER_TYPE_NONE; 3467 Paint mLayerPaint; 3468 Rect mLocalDirtyRect; 3469 private HardwareLayer mHardwareLayer; 3470 3471 /** 3472 * Set to true when drawing cache is enabled and cannot be created. 3473 * 3474 * @hide 3475 */ 3476 public boolean mCachingFailed; 3477 private Bitmap mDrawingCache; 3478 private Bitmap mUnscaledDrawingCache; 3479 3480 /** 3481 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3482 * <p> 3483 * When non-null and valid, this is expected to contain an up-to-date copy 3484 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3485 * cleanup. 3486 */ 3487 final RenderNode mRenderNode; 3488 3489 /** 3490 * Set to true when the view is sending hover accessibility events because it 3491 * is the innermost hovered view. 3492 */ 3493 private boolean mSendingHoverAccessibilityEvents; 3494 3495 /** 3496 * Delegate for injecting accessibility functionality. 3497 */ 3498 AccessibilityDelegate mAccessibilityDelegate; 3499 3500 /** 3501 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3502 * and add/remove objects to/from the overlay directly through the Overlay methods. 3503 */ 3504 ViewOverlay mOverlay; 3505 3506 /** 3507 * The currently active parent view for receiving delegated nested scrolling events. 3508 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3509 * by {@link #stopNestedScroll()} at the same point where we clear 3510 * requestDisallowInterceptTouchEvent. 3511 */ 3512 private ViewParent mNestedScrollingParent; 3513 3514 /** 3515 * Consistency verifier for debugging purposes. 3516 * @hide 3517 */ 3518 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3519 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3520 new InputEventConsistencyVerifier(this, 0) : null; 3521 3522 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3523 3524 private int[] mTempNestedScrollConsumed; 3525 3526 /** 3527 * Simple constructor to use when creating a view from code. 3528 * 3529 * @param context The Context the view is running in, through which it can 3530 * access the current theme, resources, etc. 3531 */ 3532 public View(Context context) { 3533 mContext = context; 3534 mResources = context != null ? context.getResources() : null; 3535 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3536 // Set some flags defaults 3537 mPrivateFlags2 = 3538 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3539 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3540 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3541 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3542 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3543 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3544 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3545 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3546 mUserPaddingStart = UNDEFINED_PADDING; 3547 mUserPaddingEnd = UNDEFINED_PADDING; 3548 mRenderNode = RenderNode.create(getClass().getName()); 3549 3550 if (!sCompatibilityDone && context != null) { 3551 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3552 3553 // Older apps may need this compatibility hack for measurement. 3554 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3555 3556 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3557 // of whether a layout was requested on that View. 3558 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3559 3560 // Older apps may need this to ignore the clip bounds 3561 sIgnoreClipBoundsForChildren = targetSdkVersion < L; 3562 3563 sCompatibilityDone = true; 3564 } 3565 } 3566 3567 /** 3568 * Constructor that is called when inflating a view from XML. This is called 3569 * when a view is being constructed from an XML file, supplying attributes 3570 * that were specified in the XML file. This version uses a default style of 3571 * 0, so the only attribute values applied are those in the Context's Theme 3572 * and the given AttributeSet. 3573 * 3574 * <p> 3575 * The method onFinishInflate() will be called after all children have been 3576 * added. 3577 * 3578 * @param context The Context the view is running in, through which it can 3579 * access the current theme, resources, etc. 3580 * @param attrs The attributes of the XML tag that is inflating the view. 3581 * @see #View(Context, AttributeSet, int) 3582 */ 3583 public View(Context context, AttributeSet attrs) { 3584 this(context, attrs, 0); 3585 } 3586 3587 /** 3588 * Perform inflation from XML and apply a class-specific base style from a 3589 * theme attribute. This constructor of View allows subclasses to use their 3590 * own base style when they are inflating. For example, a Button class's 3591 * constructor would call this version of the super class constructor and 3592 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3593 * allows the theme's button style to modify all of the base view attributes 3594 * (in particular its background) as well as the Button class's attributes. 3595 * 3596 * @param context The Context the view is running in, through which it can 3597 * access the current theme, resources, etc. 3598 * @param attrs The attributes of the XML tag that is inflating the view. 3599 * @param defStyleAttr An attribute in the current theme that contains a 3600 * reference to a style resource that supplies default values for 3601 * the view. Can be 0 to not look for defaults. 3602 * @see #View(Context, AttributeSet) 3603 */ 3604 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3605 this(context, attrs, defStyleAttr, 0); 3606 } 3607 3608 /** 3609 * Perform inflation from XML and apply a class-specific base style from a 3610 * theme attribute or style resource. This constructor of View allows 3611 * subclasses to use their own base style when they are inflating. 3612 * <p> 3613 * When determining the final value of a particular attribute, there are 3614 * four inputs that come into play: 3615 * <ol> 3616 * <li>Any attribute values in the given AttributeSet. 3617 * <li>The style resource specified in the AttributeSet (named "style"). 3618 * <li>The default style specified by <var>defStyleAttr</var>. 3619 * <li>The default style specified by <var>defStyleRes</var>. 3620 * <li>The base values in this theme. 3621 * </ol> 3622 * <p> 3623 * Each of these inputs is considered in-order, with the first listed taking 3624 * precedence over the following ones. In other words, if in the 3625 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3626 * , then the button's text will <em>always</em> be black, regardless of 3627 * what is specified in any of the styles. 3628 * 3629 * @param context The Context the view is running in, through which it can 3630 * access the current theme, resources, etc. 3631 * @param attrs The attributes of the XML tag that is inflating the view. 3632 * @param defStyleAttr An attribute in the current theme that contains a 3633 * reference to a style resource that supplies default values for 3634 * the view. Can be 0 to not look for defaults. 3635 * @param defStyleRes A resource identifier of a style resource that 3636 * supplies default values for the view, used only if 3637 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3638 * to not look for defaults. 3639 * @see #View(Context, AttributeSet, int) 3640 */ 3641 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3642 this(context); 3643 3644 final TypedArray a = context.obtainStyledAttributes( 3645 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3646 3647 Drawable background = null; 3648 3649 int leftPadding = -1; 3650 int topPadding = -1; 3651 int rightPadding = -1; 3652 int bottomPadding = -1; 3653 int startPadding = UNDEFINED_PADDING; 3654 int endPadding = UNDEFINED_PADDING; 3655 3656 int padding = -1; 3657 3658 int viewFlagValues = 0; 3659 int viewFlagMasks = 0; 3660 3661 boolean setScrollContainer = false; 3662 3663 int x = 0; 3664 int y = 0; 3665 3666 float tx = 0; 3667 float ty = 0; 3668 float tz = 0; 3669 float elevation = 0; 3670 float rotation = 0; 3671 float rotationX = 0; 3672 float rotationY = 0; 3673 float sx = 1f; 3674 float sy = 1f; 3675 boolean transformSet = false; 3676 3677 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3678 int overScrollMode = mOverScrollMode; 3679 boolean initializeScrollbars = false; 3680 3681 boolean startPaddingDefined = false; 3682 boolean endPaddingDefined = false; 3683 boolean leftPaddingDefined = false; 3684 boolean rightPaddingDefined = false; 3685 3686 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3687 3688 final int N = a.getIndexCount(); 3689 for (int i = 0; i < N; i++) { 3690 int attr = a.getIndex(i); 3691 switch (attr) { 3692 case com.android.internal.R.styleable.View_background: 3693 background = a.getDrawable(attr); 3694 break; 3695 case com.android.internal.R.styleable.View_padding: 3696 padding = a.getDimensionPixelSize(attr, -1); 3697 mUserPaddingLeftInitial = padding; 3698 mUserPaddingRightInitial = padding; 3699 leftPaddingDefined = true; 3700 rightPaddingDefined = true; 3701 break; 3702 case com.android.internal.R.styleable.View_paddingLeft: 3703 leftPadding = a.getDimensionPixelSize(attr, -1); 3704 mUserPaddingLeftInitial = leftPadding; 3705 leftPaddingDefined = true; 3706 break; 3707 case com.android.internal.R.styleable.View_paddingTop: 3708 topPadding = a.getDimensionPixelSize(attr, -1); 3709 break; 3710 case com.android.internal.R.styleable.View_paddingRight: 3711 rightPadding = a.getDimensionPixelSize(attr, -1); 3712 mUserPaddingRightInitial = rightPadding; 3713 rightPaddingDefined = true; 3714 break; 3715 case com.android.internal.R.styleable.View_paddingBottom: 3716 bottomPadding = a.getDimensionPixelSize(attr, -1); 3717 break; 3718 case com.android.internal.R.styleable.View_paddingStart: 3719 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3720 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3721 break; 3722 case com.android.internal.R.styleable.View_paddingEnd: 3723 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3724 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3725 break; 3726 case com.android.internal.R.styleable.View_scrollX: 3727 x = a.getDimensionPixelOffset(attr, 0); 3728 break; 3729 case com.android.internal.R.styleable.View_scrollY: 3730 y = a.getDimensionPixelOffset(attr, 0); 3731 break; 3732 case com.android.internal.R.styleable.View_alpha: 3733 setAlpha(a.getFloat(attr, 1f)); 3734 break; 3735 case com.android.internal.R.styleable.View_transformPivotX: 3736 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3737 break; 3738 case com.android.internal.R.styleable.View_transformPivotY: 3739 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3740 break; 3741 case com.android.internal.R.styleable.View_translationX: 3742 tx = a.getDimensionPixelOffset(attr, 0); 3743 transformSet = true; 3744 break; 3745 case com.android.internal.R.styleable.View_translationY: 3746 ty = a.getDimensionPixelOffset(attr, 0); 3747 transformSet = true; 3748 break; 3749 case com.android.internal.R.styleable.View_translationZ: 3750 tz = a.getDimensionPixelOffset(attr, 0); 3751 transformSet = true; 3752 break; 3753 case com.android.internal.R.styleable.View_elevation: 3754 elevation = a.getDimensionPixelOffset(attr, 0); 3755 transformSet = true; 3756 break; 3757 case com.android.internal.R.styleable.View_rotation: 3758 rotation = a.getFloat(attr, 0); 3759 transformSet = true; 3760 break; 3761 case com.android.internal.R.styleable.View_rotationX: 3762 rotationX = a.getFloat(attr, 0); 3763 transformSet = true; 3764 break; 3765 case com.android.internal.R.styleable.View_rotationY: 3766 rotationY = a.getFloat(attr, 0); 3767 transformSet = true; 3768 break; 3769 case com.android.internal.R.styleable.View_scaleX: 3770 sx = a.getFloat(attr, 1f); 3771 transformSet = true; 3772 break; 3773 case com.android.internal.R.styleable.View_scaleY: 3774 sy = a.getFloat(attr, 1f); 3775 transformSet = true; 3776 break; 3777 case com.android.internal.R.styleable.View_id: 3778 mID = a.getResourceId(attr, NO_ID); 3779 break; 3780 case com.android.internal.R.styleable.View_tag: 3781 mTag = a.getText(attr); 3782 break; 3783 case com.android.internal.R.styleable.View_fitsSystemWindows: 3784 if (a.getBoolean(attr, false)) { 3785 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3786 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3787 } 3788 break; 3789 case com.android.internal.R.styleable.View_focusable: 3790 if (a.getBoolean(attr, false)) { 3791 viewFlagValues |= FOCUSABLE; 3792 viewFlagMasks |= FOCUSABLE_MASK; 3793 } 3794 break; 3795 case com.android.internal.R.styleable.View_focusableInTouchMode: 3796 if (a.getBoolean(attr, false)) { 3797 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3798 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3799 } 3800 break; 3801 case com.android.internal.R.styleable.View_clickable: 3802 if (a.getBoolean(attr, false)) { 3803 viewFlagValues |= CLICKABLE; 3804 viewFlagMasks |= CLICKABLE; 3805 } 3806 break; 3807 case com.android.internal.R.styleable.View_longClickable: 3808 if (a.getBoolean(attr, false)) { 3809 viewFlagValues |= LONG_CLICKABLE; 3810 viewFlagMasks |= LONG_CLICKABLE; 3811 } 3812 break; 3813 case com.android.internal.R.styleable.View_saveEnabled: 3814 if (!a.getBoolean(attr, true)) { 3815 viewFlagValues |= SAVE_DISABLED; 3816 viewFlagMasks |= SAVE_DISABLED_MASK; 3817 } 3818 break; 3819 case com.android.internal.R.styleable.View_duplicateParentState: 3820 if (a.getBoolean(attr, false)) { 3821 viewFlagValues |= DUPLICATE_PARENT_STATE; 3822 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3823 } 3824 break; 3825 case com.android.internal.R.styleable.View_visibility: 3826 final int visibility = a.getInt(attr, 0); 3827 if (visibility != 0) { 3828 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3829 viewFlagMasks |= VISIBILITY_MASK; 3830 } 3831 break; 3832 case com.android.internal.R.styleable.View_layoutDirection: 3833 // Clear any layout direction flags (included resolved bits) already set 3834 mPrivateFlags2 &= 3835 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3836 // Set the layout direction flags depending on the value of the attribute 3837 final int layoutDirection = a.getInt(attr, -1); 3838 final int value = (layoutDirection != -1) ? 3839 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3840 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3841 break; 3842 case com.android.internal.R.styleable.View_drawingCacheQuality: 3843 final int cacheQuality = a.getInt(attr, 0); 3844 if (cacheQuality != 0) { 3845 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3846 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3847 } 3848 break; 3849 case com.android.internal.R.styleable.View_contentDescription: 3850 setContentDescription(a.getString(attr)); 3851 break; 3852 case com.android.internal.R.styleable.View_labelFor: 3853 setLabelFor(a.getResourceId(attr, NO_ID)); 3854 break; 3855 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3856 if (!a.getBoolean(attr, true)) { 3857 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3858 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3859 } 3860 break; 3861 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3862 if (!a.getBoolean(attr, true)) { 3863 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3864 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3865 } 3866 break; 3867 case R.styleable.View_scrollbars: 3868 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3869 if (scrollbars != SCROLLBARS_NONE) { 3870 viewFlagValues |= scrollbars; 3871 viewFlagMasks |= SCROLLBARS_MASK; 3872 initializeScrollbars = true; 3873 } 3874 break; 3875 //noinspection deprecation 3876 case R.styleable.View_fadingEdge: 3877 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3878 // Ignore the attribute starting with ICS 3879 break; 3880 } 3881 // With builds < ICS, fall through and apply fading edges 3882 case R.styleable.View_requiresFadingEdge: 3883 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3884 if (fadingEdge != FADING_EDGE_NONE) { 3885 viewFlagValues |= fadingEdge; 3886 viewFlagMasks |= FADING_EDGE_MASK; 3887 initializeFadingEdge(a); 3888 } 3889 break; 3890 case R.styleable.View_scrollbarStyle: 3891 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3892 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3893 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3894 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3895 } 3896 break; 3897 case R.styleable.View_isScrollContainer: 3898 setScrollContainer = true; 3899 if (a.getBoolean(attr, false)) { 3900 setScrollContainer(true); 3901 } 3902 break; 3903 case com.android.internal.R.styleable.View_keepScreenOn: 3904 if (a.getBoolean(attr, false)) { 3905 viewFlagValues |= KEEP_SCREEN_ON; 3906 viewFlagMasks |= KEEP_SCREEN_ON; 3907 } 3908 break; 3909 case R.styleable.View_filterTouchesWhenObscured: 3910 if (a.getBoolean(attr, false)) { 3911 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3912 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3913 } 3914 break; 3915 case R.styleable.View_nextFocusLeft: 3916 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3917 break; 3918 case R.styleable.View_nextFocusRight: 3919 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3920 break; 3921 case R.styleable.View_nextFocusUp: 3922 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3923 break; 3924 case R.styleable.View_nextFocusDown: 3925 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3926 break; 3927 case R.styleable.View_nextFocusForward: 3928 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3929 break; 3930 case R.styleable.View_minWidth: 3931 mMinWidth = a.getDimensionPixelSize(attr, 0); 3932 break; 3933 case R.styleable.View_minHeight: 3934 mMinHeight = a.getDimensionPixelSize(attr, 0); 3935 break; 3936 case R.styleable.View_onClick: 3937 if (context.isRestricted()) { 3938 throw new IllegalStateException("The android:onClick attribute cannot " 3939 + "be used within a restricted context"); 3940 } 3941 3942 final String handlerName = a.getString(attr); 3943 if (handlerName != null) { 3944 setOnClickListener(new OnClickListener() { 3945 private Method mHandler; 3946 3947 public void onClick(View v) { 3948 if (mHandler == null) { 3949 try { 3950 mHandler = getContext().getClass().getMethod(handlerName, 3951 View.class); 3952 } catch (NoSuchMethodException e) { 3953 int id = getId(); 3954 String idText = id == NO_ID ? "" : " with id '" 3955 + getContext().getResources().getResourceEntryName( 3956 id) + "'"; 3957 throw new IllegalStateException("Could not find a method " + 3958 handlerName + "(View) in the activity " 3959 + getContext().getClass() + " for onClick handler" 3960 + " on view " + View.this.getClass() + idText, e); 3961 } 3962 } 3963 3964 try { 3965 mHandler.invoke(getContext(), View.this); 3966 } catch (IllegalAccessException e) { 3967 throw new IllegalStateException("Could not execute non " 3968 + "public method of the activity", e); 3969 } catch (InvocationTargetException e) { 3970 throw new IllegalStateException("Could not execute " 3971 + "method of the activity", e); 3972 } 3973 } 3974 }); 3975 } 3976 break; 3977 case R.styleable.View_overScrollMode: 3978 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3979 break; 3980 case R.styleable.View_verticalScrollbarPosition: 3981 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3982 break; 3983 case R.styleable.View_layerType: 3984 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3985 break; 3986 case R.styleable.View_textDirection: 3987 // Clear any text direction flag already set 3988 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3989 // Set the text direction flags depending on the value of the attribute 3990 final int textDirection = a.getInt(attr, -1); 3991 if (textDirection != -1) { 3992 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3993 } 3994 break; 3995 case R.styleable.View_textAlignment: 3996 // Clear any text alignment flag already set 3997 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3998 // Set the text alignment flag depending on the value of the attribute 3999 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4000 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4001 break; 4002 case R.styleable.View_importantForAccessibility: 4003 setImportantForAccessibility(a.getInt(attr, 4004 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4005 break; 4006 case R.styleable.View_accessibilityLiveRegion: 4007 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4008 break; 4009 case R.styleable.View_viewName: 4010 setViewName(a.getString(attr)); 4011 break; 4012 case R.styleable.View_nestedScrollingEnabled: 4013 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4014 break; 4015 case R.styleable.View_stateListAnimator: 4016 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4017 a.getResourceId(attr, 0))); 4018 break; 4019 } 4020 } 4021 4022 setOverScrollMode(overScrollMode); 4023 4024 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4025 // the resolved layout direction). Those cached values will be used later during padding 4026 // resolution. 4027 mUserPaddingStart = startPadding; 4028 mUserPaddingEnd = endPadding; 4029 4030 if (background != null) { 4031 setBackground(background); 4032 } 4033 4034 // setBackground above will record that padding is currently provided by the background. 4035 // If we have padding specified via xml, record that here instead and use it. 4036 mLeftPaddingDefined = leftPaddingDefined; 4037 mRightPaddingDefined = rightPaddingDefined; 4038 4039 if (padding >= 0) { 4040 leftPadding = padding; 4041 topPadding = padding; 4042 rightPadding = padding; 4043 bottomPadding = padding; 4044 mUserPaddingLeftInitial = padding; 4045 mUserPaddingRightInitial = padding; 4046 } 4047 4048 if (isRtlCompatibilityMode()) { 4049 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4050 // left / right padding are used if defined (meaning here nothing to do). If they are not 4051 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4052 // start / end and resolve them as left / right (layout direction is not taken into account). 4053 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4054 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4055 // defined. 4056 if (!mLeftPaddingDefined && startPaddingDefined) { 4057 leftPadding = startPadding; 4058 } 4059 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4060 if (!mRightPaddingDefined && endPaddingDefined) { 4061 rightPadding = endPadding; 4062 } 4063 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4064 } else { 4065 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4066 // values defined. Otherwise, left /right values are used. 4067 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4068 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4069 // defined. 4070 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4071 4072 if (mLeftPaddingDefined && !hasRelativePadding) { 4073 mUserPaddingLeftInitial = leftPadding; 4074 } 4075 if (mRightPaddingDefined && !hasRelativePadding) { 4076 mUserPaddingRightInitial = rightPadding; 4077 } 4078 } 4079 4080 internalSetPadding( 4081 mUserPaddingLeftInitial, 4082 topPadding >= 0 ? topPadding : mPaddingTop, 4083 mUserPaddingRightInitial, 4084 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4085 4086 if (viewFlagMasks != 0) { 4087 setFlags(viewFlagValues, viewFlagMasks); 4088 } 4089 4090 if (initializeScrollbars) { 4091 initializeScrollbars(a); 4092 } 4093 4094 a.recycle(); 4095 4096 // Needs to be called after mViewFlags is set 4097 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4098 recomputePadding(); 4099 } 4100 4101 if (x != 0 || y != 0) { 4102 scrollTo(x, y); 4103 } 4104 4105 if (transformSet) { 4106 setTranslationX(tx); 4107 setTranslationY(ty); 4108 setTranslationZ(tz); 4109 setElevation(elevation); 4110 setRotation(rotation); 4111 setRotationX(rotationX); 4112 setRotationY(rotationY); 4113 setScaleX(sx); 4114 setScaleY(sy); 4115 } 4116 4117 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4118 setScrollContainer(true); 4119 } 4120 4121 computeOpaqueFlags(); 4122 } 4123 4124 /** 4125 * Non-public constructor for use in testing 4126 */ 4127 View() { 4128 mResources = null; 4129 mRenderNode = RenderNode.create(getClass().getName()); 4130 } 4131 4132 public String toString() { 4133 StringBuilder out = new StringBuilder(128); 4134 out.append(getClass().getName()); 4135 out.append('{'); 4136 out.append(Integer.toHexString(System.identityHashCode(this))); 4137 out.append(' '); 4138 switch (mViewFlags&VISIBILITY_MASK) { 4139 case VISIBLE: out.append('V'); break; 4140 case INVISIBLE: out.append('I'); break; 4141 case GONE: out.append('G'); break; 4142 default: out.append('.'); break; 4143 } 4144 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4145 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4146 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4147 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4148 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4149 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4150 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4151 out.append(' '); 4152 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4153 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4154 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4155 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4156 out.append('p'); 4157 } else { 4158 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4159 } 4160 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4161 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4162 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4163 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4164 out.append(' '); 4165 out.append(mLeft); 4166 out.append(','); 4167 out.append(mTop); 4168 out.append('-'); 4169 out.append(mRight); 4170 out.append(','); 4171 out.append(mBottom); 4172 final int id = getId(); 4173 if (id != NO_ID) { 4174 out.append(" #"); 4175 out.append(Integer.toHexString(id)); 4176 final Resources r = mResources; 4177 if (Resources.resourceHasPackage(id) && r != null) { 4178 try { 4179 String pkgname; 4180 switch (id&0xff000000) { 4181 case 0x7f000000: 4182 pkgname="app"; 4183 break; 4184 case 0x01000000: 4185 pkgname="android"; 4186 break; 4187 default: 4188 pkgname = r.getResourcePackageName(id); 4189 break; 4190 } 4191 String typename = r.getResourceTypeName(id); 4192 String entryname = r.getResourceEntryName(id); 4193 out.append(" "); 4194 out.append(pkgname); 4195 out.append(":"); 4196 out.append(typename); 4197 out.append("/"); 4198 out.append(entryname); 4199 } catch (Resources.NotFoundException e) { 4200 } 4201 } 4202 } 4203 out.append("}"); 4204 return out.toString(); 4205 } 4206 4207 /** 4208 * <p> 4209 * Initializes the fading edges from a given set of styled attributes. This 4210 * method should be called by subclasses that need fading edges and when an 4211 * instance of these subclasses is created programmatically rather than 4212 * being inflated from XML. This method is automatically called when the XML 4213 * is inflated. 4214 * </p> 4215 * 4216 * @param a the styled attributes set to initialize the fading edges from 4217 */ 4218 protected void initializeFadingEdge(TypedArray a) { 4219 initScrollCache(); 4220 4221 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4222 R.styleable.View_fadingEdgeLength, 4223 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4224 } 4225 4226 /** 4227 * Returns the size of the vertical faded edges used to indicate that more 4228 * content in this view is visible. 4229 * 4230 * @return The size in pixels of the vertical faded edge or 0 if vertical 4231 * faded edges are not enabled for this view. 4232 * @attr ref android.R.styleable#View_fadingEdgeLength 4233 */ 4234 public int getVerticalFadingEdgeLength() { 4235 if (isVerticalFadingEdgeEnabled()) { 4236 ScrollabilityCache cache = mScrollCache; 4237 if (cache != null) { 4238 return cache.fadingEdgeLength; 4239 } 4240 } 4241 return 0; 4242 } 4243 4244 /** 4245 * Set the size of the faded edge used to indicate that more content in this 4246 * view is available. Will not change whether the fading edge is enabled; use 4247 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4248 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4249 * for the vertical or horizontal fading edges. 4250 * 4251 * @param length The size in pixels of the faded edge used to indicate that more 4252 * content in this view is visible. 4253 */ 4254 public void setFadingEdgeLength(int length) { 4255 initScrollCache(); 4256 mScrollCache.fadingEdgeLength = length; 4257 } 4258 4259 /** 4260 * Returns the size of the horizontal faded edges used to indicate that more 4261 * content in this view is visible. 4262 * 4263 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4264 * faded edges are not enabled for this view. 4265 * @attr ref android.R.styleable#View_fadingEdgeLength 4266 */ 4267 public int getHorizontalFadingEdgeLength() { 4268 if (isHorizontalFadingEdgeEnabled()) { 4269 ScrollabilityCache cache = mScrollCache; 4270 if (cache != null) { 4271 return cache.fadingEdgeLength; 4272 } 4273 } 4274 return 0; 4275 } 4276 4277 /** 4278 * Returns the width of the vertical scrollbar. 4279 * 4280 * @return The width in pixels of the vertical scrollbar or 0 if there 4281 * is no vertical scrollbar. 4282 */ 4283 public int getVerticalScrollbarWidth() { 4284 ScrollabilityCache cache = mScrollCache; 4285 if (cache != null) { 4286 ScrollBarDrawable scrollBar = cache.scrollBar; 4287 if (scrollBar != null) { 4288 int size = scrollBar.getSize(true); 4289 if (size <= 0) { 4290 size = cache.scrollBarSize; 4291 } 4292 return size; 4293 } 4294 return 0; 4295 } 4296 return 0; 4297 } 4298 4299 /** 4300 * Returns the height of the horizontal scrollbar. 4301 * 4302 * @return The height in pixels of the horizontal scrollbar or 0 if 4303 * there is no horizontal scrollbar. 4304 */ 4305 protected int getHorizontalScrollbarHeight() { 4306 ScrollabilityCache cache = mScrollCache; 4307 if (cache != null) { 4308 ScrollBarDrawable scrollBar = cache.scrollBar; 4309 if (scrollBar != null) { 4310 int size = scrollBar.getSize(false); 4311 if (size <= 0) { 4312 size = cache.scrollBarSize; 4313 } 4314 return size; 4315 } 4316 return 0; 4317 } 4318 return 0; 4319 } 4320 4321 /** 4322 * <p> 4323 * Initializes the scrollbars from a given set of styled attributes. This 4324 * method should be called by subclasses that need scrollbars and when an 4325 * instance of these subclasses is created programmatically rather than 4326 * being inflated from XML. This method is automatically called when the XML 4327 * is inflated. 4328 * </p> 4329 * 4330 * @param a the styled attributes set to initialize the scrollbars from 4331 */ 4332 protected void initializeScrollbars(TypedArray a) { 4333 initScrollCache(); 4334 4335 final ScrollabilityCache scrollabilityCache = mScrollCache; 4336 4337 if (scrollabilityCache.scrollBar == null) { 4338 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4339 } 4340 4341 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4342 4343 if (!fadeScrollbars) { 4344 scrollabilityCache.state = ScrollabilityCache.ON; 4345 } 4346 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4347 4348 4349 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4350 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4351 .getScrollBarFadeDuration()); 4352 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4353 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4354 ViewConfiguration.getScrollDefaultDelay()); 4355 4356 4357 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4358 com.android.internal.R.styleable.View_scrollbarSize, 4359 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4360 4361 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4362 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4363 4364 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4365 if (thumb != null) { 4366 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4367 } 4368 4369 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4370 false); 4371 if (alwaysDraw) { 4372 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4373 } 4374 4375 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4376 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4377 4378 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4379 if (thumb != null) { 4380 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4381 } 4382 4383 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4384 false); 4385 if (alwaysDraw) { 4386 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4387 } 4388 4389 // Apply layout direction to the new Drawables if needed 4390 final int layoutDirection = getLayoutDirection(); 4391 if (track != null) { 4392 track.setLayoutDirection(layoutDirection); 4393 } 4394 if (thumb != null) { 4395 thumb.setLayoutDirection(layoutDirection); 4396 } 4397 4398 // Re-apply user/background padding so that scrollbar(s) get added 4399 resolvePadding(); 4400 } 4401 4402 /** 4403 * <p> 4404 * Initalizes the scrollability cache if necessary. 4405 * </p> 4406 */ 4407 private void initScrollCache() { 4408 if (mScrollCache == null) { 4409 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4410 } 4411 } 4412 4413 private ScrollabilityCache getScrollCache() { 4414 initScrollCache(); 4415 return mScrollCache; 4416 } 4417 4418 /** 4419 * Set the position of the vertical scroll bar. Should be one of 4420 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4421 * {@link #SCROLLBAR_POSITION_RIGHT}. 4422 * 4423 * @param position Where the vertical scroll bar should be positioned. 4424 */ 4425 public void setVerticalScrollbarPosition(int position) { 4426 if (mVerticalScrollbarPosition != position) { 4427 mVerticalScrollbarPosition = position; 4428 computeOpaqueFlags(); 4429 resolvePadding(); 4430 } 4431 } 4432 4433 /** 4434 * @return The position where the vertical scroll bar will show, if applicable. 4435 * @see #setVerticalScrollbarPosition(int) 4436 */ 4437 public int getVerticalScrollbarPosition() { 4438 return mVerticalScrollbarPosition; 4439 } 4440 4441 ListenerInfo getListenerInfo() { 4442 if (mListenerInfo != null) { 4443 return mListenerInfo; 4444 } 4445 mListenerInfo = new ListenerInfo(); 4446 return mListenerInfo; 4447 } 4448 4449 /** 4450 * Register a callback to be invoked when focus of this view changed. 4451 * 4452 * @param l The callback that will run. 4453 */ 4454 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4455 getListenerInfo().mOnFocusChangeListener = l; 4456 } 4457 4458 /** 4459 * Add a listener that will be called when the bounds of the view change due to 4460 * layout processing. 4461 * 4462 * @param listener The listener that will be called when layout bounds change. 4463 */ 4464 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4465 ListenerInfo li = getListenerInfo(); 4466 if (li.mOnLayoutChangeListeners == null) { 4467 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4468 } 4469 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4470 li.mOnLayoutChangeListeners.add(listener); 4471 } 4472 } 4473 4474 /** 4475 * Remove a listener for layout changes. 4476 * 4477 * @param listener The listener for layout bounds change. 4478 */ 4479 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4480 ListenerInfo li = mListenerInfo; 4481 if (li == null || li.mOnLayoutChangeListeners == null) { 4482 return; 4483 } 4484 li.mOnLayoutChangeListeners.remove(listener); 4485 } 4486 4487 /** 4488 * Add a listener for attach state changes. 4489 * 4490 * This listener will be called whenever this view is attached or detached 4491 * from a window. Remove the listener using 4492 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4493 * 4494 * @param listener Listener to attach 4495 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4496 */ 4497 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4498 ListenerInfo li = getListenerInfo(); 4499 if (li.mOnAttachStateChangeListeners == null) { 4500 li.mOnAttachStateChangeListeners 4501 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4502 } 4503 li.mOnAttachStateChangeListeners.add(listener); 4504 } 4505 4506 /** 4507 * Remove a listener for attach state changes. The listener will receive no further 4508 * notification of window attach/detach events. 4509 * 4510 * @param listener Listener to remove 4511 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4512 */ 4513 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4514 ListenerInfo li = mListenerInfo; 4515 if (li == null || li.mOnAttachStateChangeListeners == null) { 4516 return; 4517 } 4518 li.mOnAttachStateChangeListeners.remove(listener); 4519 } 4520 4521 /** 4522 * Returns the focus-change callback registered for this view. 4523 * 4524 * @return The callback, or null if one is not registered. 4525 */ 4526 public OnFocusChangeListener getOnFocusChangeListener() { 4527 ListenerInfo li = mListenerInfo; 4528 return li != null ? li.mOnFocusChangeListener : null; 4529 } 4530 4531 /** 4532 * Register a callback to be invoked when this view is clicked. If this view is not 4533 * clickable, it becomes clickable. 4534 * 4535 * @param l The callback that will run 4536 * 4537 * @see #setClickable(boolean) 4538 */ 4539 public void setOnClickListener(OnClickListener l) { 4540 if (!isClickable()) { 4541 setClickable(true); 4542 } 4543 getListenerInfo().mOnClickListener = l; 4544 } 4545 4546 /** 4547 * Return whether this view has an attached OnClickListener. Returns 4548 * true if there is a listener, false if there is none. 4549 */ 4550 public boolean hasOnClickListeners() { 4551 ListenerInfo li = mListenerInfo; 4552 return (li != null && li.mOnClickListener != null); 4553 } 4554 4555 /** 4556 * Register a callback to be invoked when this view is clicked and held. If this view is not 4557 * long clickable, it becomes long clickable. 4558 * 4559 * @param l The callback that will run 4560 * 4561 * @see #setLongClickable(boolean) 4562 */ 4563 public void setOnLongClickListener(OnLongClickListener l) { 4564 if (!isLongClickable()) { 4565 setLongClickable(true); 4566 } 4567 getListenerInfo().mOnLongClickListener = l; 4568 } 4569 4570 /** 4571 * Register a callback to be invoked when the context menu for this view is 4572 * being built. If this view is not long clickable, it becomes long clickable. 4573 * 4574 * @param l The callback that will run 4575 * 4576 */ 4577 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4578 if (!isLongClickable()) { 4579 setLongClickable(true); 4580 } 4581 getListenerInfo().mOnCreateContextMenuListener = l; 4582 } 4583 4584 /** 4585 * Call this view's OnClickListener, if it is defined. Performs all normal 4586 * actions associated with clicking: reporting accessibility event, playing 4587 * a sound, etc. 4588 * 4589 * @return True there was an assigned OnClickListener that was called, false 4590 * otherwise is returned. 4591 */ 4592 public boolean performClick() { 4593 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4594 4595 ListenerInfo li = mListenerInfo; 4596 if (li != null && li.mOnClickListener != null) { 4597 playSoundEffect(SoundEffectConstants.CLICK); 4598 li.mOnClickListener.onClick(this); 4599 return true; 4600 } 4601 4602 return false; 4603 } 4604 4605 /** 4606 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4607 * this only calls the listener, and does not do any associated clicking 4608 * actions like reporting an accessibility event. 4609 * 4610 * @return True there was an assigned OnClickListener that was called, false 4611 * otherwise is returned. 4612 */ 4613 public boolean callOnClick() { 4614 ListenerInfo li = mListenerInfo; 4615 if (li != null && li.mOnClickListener != null) { 4616 li.mOnClickListener.onClick(this); 4617 return true; 4618 } 4619 return false; 4620 } 4621 4622 /** 4623 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4624 * OnLongClickListener did not consume the event. 4625 * 4626 * @return True if one of the above receivers consumed the event, false otherwise. 4627 */ 4628 public boolean performLongClick() { 4629 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4630 4631 boolean handled = false; 4632 ListenerInfo li = mListenerInfo; 4633 if (li != null && li.mOnLongClickListener != null) { 4634 handled = li.mOnLongClickListener.onLongClick(View.this); 4635 } 4636 if (!handled) { 4637 handled = showContextMenu(); 4638 } 4639 if (handled) { 4640 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4641 } 4642 return handled; 4643 } 4644 4645 /** 4646 * Performs button-related actions during a touch down event. 4647 * 4648 * @param event The event. 4649 * @return True if the down was consumed. 4650 * 4651 * @hide 4652 */ 4653 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4654 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4655 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4656 return true; 4657 } 4658 } 4659 return false; 4660 } 4661 4662 /** 4663 * Bring up the context menu for this view. 4664 * 4665 * @return Whether a context menu was displayed. 4666 */ 4667 public boolean showContextMenu() { 4668 return getParent().showContextMenuForChild(this); 4669 } 4670 4671 /** 4672 * Bring up the context menu for this view, referring to the item under the specified point. 4673 * 4674 * @param x The referenced x coordinate. 4675 * @param y The referenced y coordinate. 4676 * @param metaState The keyboard modifiers that were pressed. 4677 * @return Whether a context menu was displayed. 4678 * 4679 * @hide 4680 */ 4681 public boolean showContextMenu(float x, float y, int metaState) { 4682 return showContextMenu(); 4683 } 4684 4685 /** 4686 * Start an action mode. 4687 * 4688 * @param callback Callback that will control the lifecycle of the action mode 4689 * @return The new action mode if it is started, null otherwise 4690 * 4691 * @see ActionMode 4692 */ 4693 public ActionMode startActionMode(ActionMode.Callback callback) { 4694 ViewParent parent = getParent(); 4695 if (parent == null) return null; 4696 return parent.startActionModeForChild(this, callback); 4697 } 4698 4699 /** 4700 * Register a callback to be invoked when a hardware key is pressed in this view. 4701 * Key presses in software input methods will generally not trigger the methods of 4702 * this listener. 4703 * @param l the key listener to attach to this view 4704 */ 4705 public void setOnKeyListener(OnKeyListener l) { 4706 getListenerInfo().mOnKeyListener = l; 4707 } 4708 4709 /** 4710 * Register a callback to be invoked when a touch event is sent to this view. 4711 * @param l the touch listener to attach to this view 4712 */ 4713 public void setOnTouchListener(OnTouchListener l) { 4714 getListenerInfo().mOnTouchListener = l; 4715 } 4716 4717 /** 4718 * Register a callback to be invoked when a generic motion event is sent to this view. 4719 * @param l the generic motion listener to attach to this view 4720 */ 4721 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4722 getListenerInfo().mOnGenericMotionListener = l; 4723 } 4724 4725 /** 4726 * Register a callback to be invoked when a hover event is sent to this view. 4727 * @param l the hover listener to attach to this view 4728 */ 4729 public void setOnHoverListener(OnHoverListener l) { 4730 getListenerInfo().mOnHoverListener = l; 4731 } 4732 4733 /** 4734 * Register a drag event listener callback object for this View. The parameter is 4735 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4736 * View, the system calls the 4737 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4738 * @param l An implementation of {@link android.view.View.OnDragListener}. 4739 */ 4740 public void setOnDragListener(OnDragListener l) { 4741 getListenerInfo().mOnDragListener = l; 4742 } 4743 4744 /** 4745 * Give this view focus. This will cause 4746 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4747 * 4748 * Note: this does not check whether this {@link View} should get focus, it just 4749 * gives it focus no matter what. It should only be called internally by framework 4750 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4751 * 4752 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4753 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4754 * focus moved when requestFocus() is called. It may not always 4755 * apply, in which case use the default View.FOCUS_DOWN. 4756 * @param previouslyFocusedRect The rectangle of the view that had focus 4757 * prior in this View's coordinate system. 4758 */ 4759 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4760 if (DBG) { 4761 System.out.println(this + " requestFocus()"); 4762 } 4763 4764 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4765 mPrivateFlags |= PFLAG_FOCUSED; 4766 4767 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4768 4769 if (mParent != null) { 4770 mParent.requestChildFocus(this, this); 4771 } 4772 4773 if (mAttachInfo != null) { 4774 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4775 } 4776 4777 manageFocusHotspot(true, oldFocus); 4778 onFocusChanged(true, direction, previouslyFocusedRect); 4779 refreshDrawableState(); 4780 } 4781 } 4782 4783 /** 4784 * Forwards focus information to the background drawable, if necessary. When 4785 * the view is gaining focus, <code>v</code> is the previous focus holder. 4786 * When the view is losing focus, <code>v</code> is the next focus holder. 4787 * 4788 * @param focused whether this view is focused 4789 * @param v previous or the next focus holder, or null if none 4790 */ 4791 private void manageFocusHotspot(boolean focused, View v) { 4792 if (mBackground != null && mBackground.supportsHotspots()) { 4793 final Rect r = new Rect(); 4794 if (!focused && v != null) { 4795 v.getBoundsOnScreen(r); 4796 final int[] location = new int[2]; 4797 getLocationOnScreen(location); 4798 r.offset(-location[0], -location[1]); 4799 } else { 4800 r.set(0, 0, mRight - mLeft, mBottom - mTop); 4801 } 4802 4803 final float x = r.exactCenterX(); 4804 final float y = r.exactCenterY(); 4805 mBackground.setHotspot(R.attr.state_focused, x, y); 4806 4807 if (!focused) { 4808 mBackground.removeHotspot(R.attr.state_focused); 4809 } 4810 } 4811 } 4812 4813 /** 4814 * Request that a rectangle of this view be visible on the screen, 4815 * scrolling if necessary just enough. 4816 * 4817 * <p>A View should call this if it maintains some notion of which part 4818 * of its content is interesting. For example, a text editing view 4819 * should call this when its cursor moves. 4820 * 4821 * @param rectangle The rectangle. 4822 * @return Whether any parent scrolled. 4823 */ 4824 public boolean requestRectangleOnScreen(Rect rectangle) { 4825 return requestRectangleOnScreen(rectangle, false); 4826 } 4827 4828 /** 4829 * Request that a rectangle of this view be visible on the screen, 4830 * scrolling if necessary just enough. 4831 * 4832 * <p>A View should call this if it maintains some notion of which part 4833 * of its content is interesting. For example, a text editing view 4834 * should call this when its cursor moves. 4835 * 4836 * <p>When <code>immediate</code> is set to true, scrolling will not be 4837 * animated. 4838 * 4839 * @param rectangle The rectangle. 4840 * @param immediate True to forbid animated scrolling, false otherwise 4841 * @return Whether any parent scrolled. 4842 */ 4843 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4844 if (mParent == null) { 4845 return false; 4846 } 4847 4848 View child = this; 4849 4850 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4851 position.set(rectangle); 4852 4853 ViewParent parent = mParent; 4854 boolean scrolled = false; 4855 while (parent != null) { 4856 rectangle.set((int) position.left, (int) position.top, 4857 (int) position.right, (int) position.bottom); 4858 4859 scrolled |= parent.requestChildRectangleOnScreen(child, 4860 rectangle, immediate); 4861 4862 if (!child.hasIdentityMatrix()) { 4863 child.getMatrix().mapRect(position); 4864 } 4865 4866 position.offset(child.mLeft, child.mTop); 4867 4868 if (!(parent instanceof View)) { 4869 break; 4870 } 4871 4872 View parentView = (View) parent; 4873 4874 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4875 4876 child = parentView; 4877 parent = child.getParent(); 4878 } 4879 4880 return scrolled; 4881 } 4882 4883 /** 4884 * Called when this view wants to give up focus. If focus is cleared 4885 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4886 * <p> 4887 * <strong>Note:</strong> When a View clears focus the framework is trying 4888 * to give focus to the first focusable View from the top. Hence, if this 4889 * View is the first from the top that can take focus, then all callbacks 4890 * related to clearing focus will be invoked after wich the framework will 4891 * give focus to this view. 4892 * </p> 4893 */ 4894 public void clearFocus() { 4895 if (DBG) { 4896 System.out.println(this + " clearFocus()"); 4897 } 4898 4899 clearFocusInternal(null, true, true); 4900 } 4901 4902 /** 4903 * Clears focus from the view, optionally propagating the change up through 4904 * the parent hierarchy and requesting that the root view place new focus. 4905 * 4906 * @param propagate whether to propagate the change up through the parent 4907 * hierarchy 4908 * @param refocus when propagate is true, specifies whether to request the 4909 * root view place new focus 4910 */ 4911 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 4912 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4913 mPrivateFlags &= ~PFLAG_FOCUSED; 4914 4915 if (propagate && mParent != null) { 4916 mParent.clearChildFocus(this); 4917 } 4918 4919 onFocusChanged(false, 0, null); 4920 4921 manageFocusHotspot(false, focused); 4922 refreshDrawableState(); 4923 4924 if (propagate && (!refocus || !rootViewRequestFocus())) { 4925 notifyGlobalFocusCleared(this); 4926 } 4927 } 4928 } 4929 4930 void notifyGlobalFocusCleared(View oldFocus) { 4931 if (oldFocus != null && mAttachInfo != null) { 4932 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 4933 } 4934 } 4935 4936 boolean rootViewRequestFocus() { 4937 final View root = getRootView(); 4938 return root != null && root.requestFocus(); 4939 } 4940 4941 /** 4942 * Called internally by the view system when a new view is getting focus. 4943 * This is what clears the old focus. 4944 * <p> 4945 * <b>NOTE:</b> The parent view's focused child must be updated manually 4946 * after calling this method. Otherwise, the view hierarchy may be left in 4947 * an inconstent state. 4948 */ 4949 void unFocus(View focused) { 4950 if (DBG) { 4951 System.out.println(this + " unFocus()"); 4952 } 4953 4954 clearFocusInternal(focused, false, false); 4955 } 4956 4957 /** 4958 * Returns true if this view has focus iteself, or is the ancestor of the 4959 * view that has focus. 4960 * 4961 * @return True if this view has or contains focus, false otherwise. 4962 */ 4963 @ViewDebug.ExportedProperty(category = "focus") 4964 public boolean hasFocus() { 4965 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4966 } 4967 4968 /** 4969 * Returns true if this view is focusable or if it contains a reachable View 4970 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4971 * is a View whose parents do not block descendants focus. 4972 * 4973 * Only {@link #VISIBLE} views are considered focusable. 4974 * 4975 * @return True if the view is focusable or if the view contains a focusable 4976 * View, false otherwise. 4977 * 4978 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4979 */ 4980 public boolean hasFocusable() { 4981 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4982 } 4983 4984 /** 4985 * Called by the view system when the focus state of this view changes. 4986 * When the focus change event is caused by directional navigation, direction 4987 * and previouslyFocusedRect provide insight into where the focus is coming from. 4988 * When overriding, be sure to call up through to the super class so that 4989 * the standard focus handling will occur. 4990 * 4991 * @param gainFocus True if the View has focus; false otherwise. 4992 * @param direction The direction focus has moved when requestFocus() 4993 * is called to give this view focus. Values are 4994 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4995 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4996 * It may not always apply, in which case use the default. 4997 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4998 * system, of the previously focused view. If applicable, this will be 4999 * passed in as finer grained information about where the focus is coming 5000 * from (in addition to direction). Will be <code>null</code> otherwise. 5001 */ 5002 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5003 @Nullable Rect previouslyFocusedRect) { 5004 if (gainFocus) { 5005 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5006 } else { 5007 notifyViewAccessibilityStateChangedIfNeeded( 5008 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5009 } 5010 5011 InputMethodManager imm = InputMethodManager.peekInstance(); 5012 if (!gainFocus) { 5013 if (isPressed()) { 5014 setPressed(false); 5015 } 5016 if (imm != null && mAttachInfo != null 5017 && mAttachInfo.mHasWindowFocus) { 5018 imm.focusOut(this); 5019 } 5020 onFocusLost(); 5021 } else if (imm != null && mAttachInfo != null 5022 && mAttachInfo.mHasWindowFocus) { 5023 imm.focusIn(this); 5024 } 5025 5026 invalidate(true); 5027 ListenerInfo li = mListenerInfo; 5028 if (li != null && li.mOnFocusChangeListener != null) { 5029 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5030 } 5031 5032 if (mAttachInfo != null) { 5033 mAttachInfo.mKeyDispatchState.reset(this); 5034 } 5035 } 5036 5037 /** 5038 * Sends an accessibility event of the given type. If accessibility is 5039 * not enabled this method has no effect. The default implementation calls 5040 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5041 * to populate information about the event source (this View), then calls 5042 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5043 * populate the text content of the event source including its descendants, 5044 * and last calls 5045 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5046 * on its parent to resuest sending of the event to interested parties. 5047 * <p> 5048 * If an {@link AccessibilityDelegate} has been specified via calling 5049 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5050 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5051 * responsible for handling this call. 5052 * </p> 5053 * 5054 * @param eventType The type of the event to send, as defined by several types from 5055 * {@link android.view.accessibility.AccessibilityEvent}, such as 5056 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5057 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5058 * 5059 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5060 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5061 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5062 * @see AccessibilityDelegate 5063 */ 5064 public void sendAccessibilityEvent(int eventType) { 5065 if (mAccessibilityDelegate != null) { 5066 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5067 } else { 5068 sendAccessibilityEventInternal(eventType); 5069 } 5070 } 5071 5072 /** 5073 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5074 * {@link AccessibilityEvent} to make an announcement which is related to some 5075 * sort of a context change for which none of the events representing UI transitions 5076 * is a good fit. For example, announcing a new page in a book. If accessibility 5077 * is not enabled this method does nothing. 5078 * 5079 * @param text The announcement text. 5080 */ 5081 public void announceForAccessibility(CharSequence text) { 5082 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5083 AccessibilityEvent event = AccessibilityEvent.obtain( 5084 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5085 onInitializeAccessibilityEvent(event); 5086 event.getText().add(text); 5087 event.setContentDescription(null); 5088 mParent.requestSendAccessibilityEvent(this, event); 5089 } 5090 } 5091 5092 /** 5093 * @see #sendAccessibilityEvent(int) 5094 * 5095 * Note: Called from the default {@link AccessibilityDelegate}. 5096 */ 5097 void sendAccessibilityEventInternal(int eventType) { 5098 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5099 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5100 } 5101 } 5102 5103 /** 5104 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5105 * takes as an argument an empty {@link AccessibilityEvent} and does not 5106 * perform a check whether accessibility is enabled. 5107 * <p> 5108 * If an {@link AccessibilityDelegate} has been specified via calling 5109 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5110 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5111 * is responsible for handling this call. 5112 * </p> 5113 * 5114 * @param event The event to send. 5115 * 5116 * @see #sendAccessibilityEvent(int) 5117 */ 5118 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5119 if (mAccessibilityDelegate != null) { 5120 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5121 } else { 5122 sendAccessibilityEventUncheckedInternal(event); 5123 } 5124 } 5125 5126 /** 5127 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5128 * 5129 * Note: Called from the default {@link AccessibilityDelegate}. 5130 */ 5131 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5132 if (!isShown()) { 5133 return; 5134 } 5135 onInitializeAccessibilityEvent(event); 5136 // Only a subset of accessibility events populates text content. 5137 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5138 dispatchPopulateAccessibilityEvent(event); 5139 } 5140 // In the beginning we called #isShown(), so we know that getParent() is not null. 5141 getParent().requestSendAccessibilityEvent(this, event); 5142 } 5143 5144 /** 5145 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5146 * to its children for adding their text content to the event. Note that the 5147 * event text is populated in a separate dispatch path since we add to the 5148 * event not only the text of the source but also the text of all its descendants. 5149 * A typical implementation will call 5150 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5151 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5152 * on each child. Override this method if custom population of the event text 5153 * content is required. 5154 * <p> 5155 * If an {@link AccessibilityDelegate} has been specified via calling 5156 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5157 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5158 * is responsible for handling this call. 5159 * </p> 5160 * <p> 5161 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5162 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5163 * </p> 5164 * 5165 * @param event The event. 5166 * 5167 * @return True if the event population was completed. 5168 */ 5169 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5170 if (mAccessibilityDelegate != null) { 5171 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5172 } else { 5173 return dispatchPopulateAccessibilityEventInternal(event); 5174 } 5175 } 5176 5177 /** 5178 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5179 * 5180 * Note: Called from the default {@link AccessibilityDelegate}. 5181 */ 5182 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5183 onPopulateAccessibilityEvent(event); 5184 return false; 5185 } 5186 5187 /** 5188 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5189 * giving a chance to this View to populate the accessibility event with its 5190 * text content. While this method is free to modify event 5191 * attributes other than text content, doing so should normally be performed in 5192 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5193 * <p> 5194 * Example: Adding formatted date string to an accessibility event in addition 5195 * to the text added by the super implementation: 5196 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5197 * super.onPopulateAccessibilityEvent(event); 5198 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5199 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5200 * mCurrentDate.getTimeInMillis(), flags); 5201 * event.getText().add(selectedDateUtterance); 5202 * }</pre> 5203 * <p> 5204 * If an {@link AccessibilityDelegate} has been specified via calling 5205 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5206 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5207 * is responsible for handling this call. 5208 * </p> 5209 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5210 * information to the event, in case the default implementation has basic information to add. 5211 * </p> 5212 * 5213 * @param event The accessibility event which to populate. 5214 * 5215 * @see #sendAccessibilityEvent(int) 5216 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5217 */ 5218 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5219 if (mAccessibilityDelegate != null) { 5220 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5221 } else { 5222 onPopulateAccessibilityEventInternal(event); 5223 } 5224 } 5225 5226 /** 5227 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5228 * 5229 * Note: Called from the default {@link AccessibilityDelegate}. 5230 */ 5231 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5232 } 5233 5234 /** 5235 * Initializes an {@link AccessibilityEvent} with information about 5236 * this View which is the event source. In other words, the source of 5237 * an accessibility event is the view whose state change triggered firing 5238 * the event. 5239 * <p> 5240 * Example: Setting the password property of an event in addition 5241 * to properties set by the super implementation: 5242 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5243 * super.onInitializeAccessibilityEvent(event); 5244 * event.setPassword(true); 5245 * }</pre> 5246 * <p> 5247 * If an {@link AccessibilityDelegate} has been specified via calling 5248 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5249 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5250 * is responsible for handling this call. 5251 * </p> 5252 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5253 * information to the event, in case the default implementation has basic information to add. 5254 * </p> 5255 * @param event The event to initialize. 5256 * 5257 * @see #sendAccessibilityEvent(int) 5258 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5259 */ 5260 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5261 if (mAccessibilityDelegate != null) { 5262 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5263 } else { 5264 onInitializeAccessibilityEventInternal(event); 5265 } 5266 } 5267 5268 /** 5269 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5270 * 5271 * Note: Called from the default {@link AccessibilityDelegate}. 5272 */ 5273 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5274 event.setSource(this); 5275 event.setClassName(View.class.getName()); 5276 event.setPackageName(getContext().getPackageName()); 5277 event.setEnabled(isEnabled()); 5278 event.setContentDescription(mContentDescription); 5279 5280 switch (event.getEventType()) { 5281 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5282 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5283 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5284 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5285 event.setItemCount(focusablesTempList.size()); 5286 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5287 if (mAttachInfo != null) { 5288 focusablesTempList.clear(); 5289 } 5290 } break; 5291 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5292 CharSequence text = getIterableTextForAccessibility(); 5293 if (text != null && text.length() > 0) { 5294 event.setFromIndex(getAccessibilitySelectionStart()); 5295 event.setToIndex(getAccessibilitySelectionEnd()); 5296 event.setItemCount(text.length()); 5297 } 5298 } break; 5299 } 5300 } 5301 5302 /** 5303 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5304 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5305 * This method is responsible for obtaining an accessibility node info from a 5306 * pool of reusable instances and calling 5307 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5308 * initialize the former. 5309 * <p> 5310 * Note: The client is responsible for recycling the obtained instance by calling 5311 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5312 * </p> 5313 * 5314 * @return A populated {@link AccessibilityNodeInfo}. 5315 * 5316 * @see AccessibilityNodeInfo 5317 */ 5318 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5319 if (mAccessibilityDelegate != null) { 5320 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5321 } else { 5322 return createAccessibilityNodeInfoInternal(); 5323 } 5324 } 5325 5326 /** 5327 * @see #createAccessibilityNodeInfo() 5328 */ 5329 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5330 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5331 if (provider != null) { 5332 return provider.createAccessibilityNodeInfo(View.NO_ID); 5333 } else { 5334 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5335 onInitializeAccessibilityNodeInfo(info); 5336 return info; 5337 } 5338 } 5339 5340 /** 5341 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5342 * The base implementation sets: 5343 * <ul> 5344 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5345 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5346 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5347 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5348 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5349 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5350 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5351 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5352 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5353 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5354 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5355 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5356 * </ul> 5357 * <p> 5358 * Subclasses should override this method, call the super implementation, 5359 * and set additional attributes. 5360 * </p> 5361 * <p> 5362 * If an {@link AccessibilityDelegate} has been specified via calling 5363 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5364 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5365 * is responsible for handling this call. 5366 * </p> 5367 * 5368 * @param info The instance to initialize. 5369 */ 5370 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5371 if (mAccessibilityDelegate != null) { 5372 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5373 } else { 5374 onInitializeAccessibilityNodeInfoInternal(info); 5375 } 5376 } 5377 5378 /** 5379 * Gets the location of this view in screen coordintates. 5380 * 5381 * @param outRect The output location 5382 */ 5383 void getBoundsOnScreen(Rect outRect) { 5384 if (mAttachInfo == null) { 5385 return; 5386 } 5387 5388 RectF position = mAttachInfo.mTmpTransformRect; 5389 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5390 5391 if (!hasIdentityMatrix()) { 5392 getMatrix().mapRect(position); 5393 } 5394 5395 position.offset(mLeft, mTop); 5396 5397 ViewParent parent = mParent; 5398 while (parent instanceof View) { 5399 View parentView = (View) parent; 5400 5401 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5402 5403 if (!parentView.hasIdentityMatrix()) { 5404 parentView.getMatrix().mapRect(position); 5405 } 5406 5407 position.offset(parentView.mLeft, parentView.mTop); 5408 5409 parent = parentView.mParent; 5410 } 5411 5412 if (parent instanceof ViewRootImpl) { 5413 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5414 position.offset(0, -viewRootImpl.mCurScrollY); 5415 } 5416 5417 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5418 5419 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5420 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5421 } 5422 5423 /** 5424 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5425 * 5426 * Note: Called from the default {@link AccessibilityDelegate}. 5427 */ 5428 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5429 Rect bounds = mAttachInfo.mTmpInvalRect; 5430 5431 getDrawingRect(bounds); 5432 info.setBoundsInParent(bounds); 5433 5434 getBoundsOnScreen(bounds); 5435 info.setBoundsInScreen(bounds); 5436 5437 ViewParent parent = getParentForAccessibility(); 5438 if (parent instanceof View) { 5439 info.setParent((View) parent); 5440 } 5441 5442 if (mID != View.NO_ID) { 5443 View rootView = getRootView(); 5444 if (rootView == null) { 5445 rootView = this; 5446 } 5447 View label = rootView.findLabelForView(this, mID); 5448 if (label != null) { 5449 info.setLabeledBy(label); 5450 } 5451 5452 if ((mAttachInfo.mAccessibilityFetchFlags 5453 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5454 && Resources.resourceHasPackage(mID)) { 5455 try { 5456 String viewId = getResources().getResourceName(mID); 5457 info.setViewIdResourceName(viewId); 5458 } catch (Resources.NotFoundException nfe) { 5459 /* ignore */ 5460 } 5461 } 5462 } 5463 5464 if (mLabelForId != View.NO_ID) { 5465 View rootView = getRootView(); 5466 if (rootView == null) { 5467 rootView = this; 5468 } 5469 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5470 if (labeled != null) { 5471 info.setLabelFor(labeled); 5472 } 5473 } 5474 5475 info.setVisibleToUser(isVisibleToUser()); 5476 5477 info.setPackageName(mContext.getPackageName()); 5478 info.setClassName(View.class.getName()); 5479 info.setContentDescription(getContentDescription()); 5480 5481 info.setEnabled(isEnabled()); 5482 info.setClickable(isClickable()); 5483 info.setFocusable(isFocusable()); 5484 info.setFocused(isFocused()); 5485 info.setAccessibilityFocused(isAccessibilityFocused()); 5486 info.setSelected(isSelected()); 5487 info.setLongClickable(isLongClickable()); 5488 info.setLiveRegion(getAccessibilityLiveRegion()); 5489 5490 // TODO: These make sense only if we are in an AdapterView but all 5491 // views can be selected. Maybe from accessibility perspective 5492 // we should report as selectable view in an AdapterView. 5493 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5494 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5495 5496 if (isFocusable()) { 5497 if (isFocused()) { 5498 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5499 } else { 5500 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5501 } 5502 } 5503 5504 if (!isAccessibilityFocused()) { 5505 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5506 } else { 5507 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5508 } 5509 5510 if (isClickable() && isEnabled()) { 5511 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5512 } 5513 5514 if (isLongClickable() && isEnabled()) { 5515 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5516 } 5517 5518 CharSequence text = getIterableTextForAccessibility(); 5519 if (text != null && text.length() > 0) { 5520 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5521 5522 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5523 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5524 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5525 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5526 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5527 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5528 } 5529 } 5530 5531 private View findLabelForView(View view, int labeledId) { 5532 if (mMatchLabelForPredicate == null) { 5533 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5534 } 5535 mMatchLabelForPredicate.mLabeledId = labeledId; 5536 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5537 } 5538 5539 /** 5540 * Computes whether this view is visible to the user. Such a view is 5541 * attached, visible, all its predecessors are visible, it is not clipped 5542 * entirely by its predecessors, and has an alpha greater than zero. 5543 * 5544 * @return Whether the view is visible on the screen. 5545 * 5546 * @hide 5547 */ 5548 protected boolean isVisibleToUser() { 5549 return isVisibleToUser(null); 5550 } 5551 5552 /** 5553 * Computes whether the given portion of this view is visible to the user. 5554 * Such a view is attached, visible, all its predecessors are visible, 5555 * has an alpha greater than zero, and the specified portion is not 5556 * clipped entirely by its predecessors. 5557 * 5558 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5559 * <code>null</code>, and the entire view will be tested in this case. 5560 * When <code>true</code> is returned by the function, the actual visible 5561 * region will be stored in this parameter; that is, if boundInView is fully 5562 * contained within the view, no modification will be made, otherwise regions 5563 * outside of the visible area of the view will be clipped. 5564 * 5565 * @return Whether the specified portion of the view is visible on the screen. 5566 * 5567 * @hide 5568 */ 5569 protected boolean isVisibleToUser(Rect boundInView) { 5570 if (mAttachInfo != null) { 5571 // Attached to invisible window means this view is not visible. 5572 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5573 return false; 5574 } 5575 // An invisible predecessor or one with alpha zero means 5576 // that this view is not visible to the user. 5577 Object current = this; 5578 while (current instanceof View) { 5579 View view = (View) current; 5580 // We have attach info so this view is attached and there is no 5581 // need to check whether we reach to ViewRootImpl on the way up. 5582 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5583 view.getVisibility() != VISIBLE) { 5584 return false; 5585 } 5586 current = view.mParent; 5587 } 5588 // Check if the view is entirely covered by its predecessors. 5589 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5590 Point offset = mAttachInfo.mPoint; 5591 if (!getGlobalVisibleRect(visibleRect, offset)) { 5592 return false; 5593 } 5594 // Check if the visible portion intersects the rectangle of interest. 5595 if (boundInView != null) { 5596 visibleRect.offset(-offset.x, -offset.y); 5597 return boundInView.intersect(visibleRect); 5598 } 5599 return true; 5600 } 5601 return false; 5602 } 5603 5604 /** 5605 * Returns the delegate for implementing accessibility support via 5606 * composition. For more details see {@link AccessibilityDelegate}. 5607 * 5608 * @return The delegate, or null if none set. 5609 * 5610 * @hide 5611 */ 5612 public AccessibilityDelegate getAccessibilityDelegate() { 5613 return mAccessibilityDelegate; 5614 } 5615 5616 /** 5617 * Sets a delegate for implementing accessibility support via composition as 5618 * opposed to inheritance. The delegate's primary use is for implementing 5619 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5620 * 5621 * @param delegate The delegate instance. 5622 * 5623 * @see AccessibilityDelegate 5624 */ 5625 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5626 mAccessibilityDelegate = delegate; 5627 } 5628 5629 /** 5630 * Gets the provider for managing a virtual view hierarchy rooted at this View 5631 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5632 * that explore the window content. 5633 * <p> 5634 * If this method returns an instance, this instance is responsible for managing 5635 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5636 * View including the one representing the View itself. Similarly the returned 5637 * instance is responsible for performing accessibility actions on any virtual 5638 * view or the root view itself. 5639 * </p> 5640 * <p> 5641 * If an {@link AccessibilityDelegate} has been specified via calling 5642 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5643 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5644 * is responsible for handling this call. 5645 * </p> 5646 * 5647 * @return The provider. 5648 * 5649 * @see AccessibilityNodeProvider 5650 */ 5651 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5652 if (mAccessibilityDelegate != null) { 5653 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5654 } else { 5655 return null; 5656 } 5657 } 5658 5659 /** 5660 * Gets the unique identifier of this view on the screen for accessibility purposes. 5661 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5662 * 5663 * @return The view accessibility id. 5664 * 5665 * @hide 5666 */ 5667 public int getAccessibilityViewId() { 5668 if (mAccessibilityViewId == NO_ID) { 5669 mAccessibilityViewId = sNextAccessibilityViewId++; 5670 } 5671 return mAccessibilityViewId; 5672 } 5673 5674 /** 5675 * Gets the unique identifier of the window in which this View reseides. 5676 * 5677 * @return The window accessibility id. 5678 * 5679 * @hide 5680 */ 5681 public int getAccessibilityWindowId() { 5682 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 5683 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 5684 } 5685 5686 /** 5687 * Gets the {@link View} description. It briefly describes the view and is 5688 * primarily used for accessibility support. Set this property to enable 5689 * better accessibility support for your application. This is especially 5690 * true for views that do not have textual representation (For example, 5691 * ImageButton). 5692 * 5693 * @return The content description. 5694 * 5695 * @attr ref android.R.styleable#View_contentDescription 5696 */ 5697 @ViewDebug.ExportedProperty(category = "accessibility") 5698 public CharSequence getContentDescription() { 5699 return mContentDescription; 5700 } 5701 5702 /** 5703 * Sets the {@link View} description. It briefly describes the view and is 5704 * primarily used for accessibility support. Set this property to enable 5705 * better accessibility support for your application. This is especially 5706 * true for views that do not have textual representation (For example, 5707 * ImageButton). 5708 * 5709 * @param contentDescription The content description. 5710 * 5711 * @attr ref android.R.styleable#View_contentDescription 5712 */ 5713 @RemotableViewMethod 5714 public void setContentDescription(CharSequence contentDescription) { 5715 if (mContentDescription == null) { 5716 if (contentDescription == null) { 5717 return; 5718 } 5719 } else if (mContentDescription.equals(contentDescription)) { 5720 return; 5721 } 5722 mContentDescription = contentDescription; 5723 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5724 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5725 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5726 notifySubtreeAccessibilityStateChangedIfNeeded(); 5727 } else { 5728 notifyViewAccessibilityStateChangedIfNeeded( 5729 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5730 } 5731 } 5732 5733 /** 5734 * Gets the id of a view for which this view serves as a label for 5735 * accessibility purposes. 5736 * 5737 * @return The labeled view id. 5738 */ 5739 @ViewDebug.ExportedProperty(category = "accessibility") 5740 public int getLabelFor() { 5741 return mLabelForId; 5742 } 5743 5744 /** 5745 * Sets the id of a view for which this view serves as a label for 5746 * accessibility purposes. 5747 * 5748 * @param id The labeled view id. 5749 */ 5750 @RemotableViewMethod 5751 public void setLabelFor(int id) { 5752 mLabelForId = id; 5753 if (mLabelForId != View.NO_ID 5754 && mID == View.NO_ID) { 5755 mID = generateViewId(); 5756 } 5757 } 5758 5759 /** 5760 * Invoked whenever this view loses focus, either by losing window focus or by losing 5761 * focus within its window. This method can be used to clear any state tied to the 5762 * focus. For instance, if a button is held pressed with the trackball and the window 5763 * loses focus, this method can be used to cancel the press. 5764 * 5765 * Subclasses of View overriding this method should always call super.onFocusLost(). 5766 * 5767 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5768 * @see #onWindowFocusChanged(boolean) 5769 * 5770 * @hide pending API council approval 5771 */ 5772 protected void onFocusLost() { 5773 resetPressedState(); 5774 } 5775 5776 private void resetPressedState() { 5777 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5778 return; 5779 } 5780 5781 if (isPressed()) { 5782 setPressed(false); 5783 5784 if (!mHasPerformedLongPress) { 5785 removeLongPressCallback(); 5786 } 5787 } 5788 } 5789 5790 /** 5791 * Returns true if this view has focus 5792 * 5793 * @return True if this view has focus, false otherwise. 5794 */ 5795 @ViewDebug.ExportedProperty(category = "focus") 5796 public boolean isFocused() { 5797 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5798 } 5799 5800 /** 5801 * Find the view in the hierarchy rooted at this view that currently has 5802 * focus. 5803 * 5804 * @return The view that currently has focus, or null if no focused view can 5805 * be found. 5806 */ 5807 public View findFocus() { 5808 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5809 } 5810 5811 /** 5812 * Indicates whether this view is one of the set of scrollable containers in 5813 * its window. 5814 * 5815 * @return whether this view is one of the set of scrollable containers in 5816 * its window 5817 * 5818 * @attr ref android.R.styleable#View_isScrollContainer 5819 */ 5820 public boolean isScrollContainer() { 5821 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5822 } 5823 5824 /** 5825 * Change whether this view is one of the set of scrollable containers in 5826 * its window. This will be used to determine whether the window can 5827 * resize or must pan when a soft input area is open -- scrollable 5828 * containers allow the window to use resize mode since the container 5829 * will appropriately shrink. 5830 * 5831 * @attr ref android.R.styleable#View_isScrollContainer 5832 */ 5833 public void setScrollContainer(boolean isScrollContainer) { 5834 if (isScrollContainer) { 5835 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5836 mAttachInfo.mScrollContainers.add(this); 5837 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5838 } 5839 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5840 } else { 5841 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5842 mAttachInfo.mScrollContainers.remove(this); 5843 } 5844 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5845 } 5846 } 5847 5848 /** 5849 * Returns the quality of the drawing cache. 5850 * 5851 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5852 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5853 * 5854 * @see #setDrawingCacheQuality(int) 5855 * @see #setDrawingCacheEnabled(boolean) 5856 * @see #isDrawingCacheEnabled() 5857 * 5858 * @attr ref android.R.styleable#View_drawingCacheQuality 5859 */ 5860 @DrawingCacheQuality 5861 public int getDrawingCacheQuality() { 5862 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5863 } 5864 5865 /** 5866 * Set the drawing cache quality of this view. This value is used only when the 5867 * drawing cache is enabled 5868 * 5869 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5870 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5871 * 5872 * @see #getDrawingCacheQuality() 5873 * @see #setDrawingCacheEnabled(boolean) 5874 * @see #isDrawingCacheEnabled() 5875 * 5876 * @attr ref android.R.styleable#View_drawingCacheQuality 5877 */ 5878 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 5879 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5880 } 5881 5882 /** 5883 * Returns whether the screen should remain on, corresponding to the current 5884 * value of {@link #KEEP_SCREEN_ON}. 5885 * 5886 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5887 * 5888 * @see #setKeepScreenOn(boolean) 5889 * 5890 * @attr ref android.R.styleable#View_keepScreenOn 5891 */ 5892 public boolean getKeepScreenOn() { 5893 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5894 } 5895 5896 /** 5897 * Controls whether the screen should remain on, modifying the 5898 * value of {@link #KEEP_SCREEN_ON}. 5899 * 5900 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5901 * 5902 * @see #getKeepScreenOn() 5903 * 5904 * @attr ref android.R.styleable#View_keepScreenOn 5905 */ 5906 public void setKeepScreenOn(boolean keepScreenOn) { 5907 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5908 } 5909 5910 /** 5911 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5912 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5913 * 5914 * @attr ref android.R.styleable#View_nextFocusLeft 5915 */ 5916 public int getNextFocusLeftId() { 5917 return mNextFocusLeftId; 5918 } 5919 5920 /** 5921 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5922 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5923 * decide automatically. 5924 * 5925 * @attr ref android.R.styleable#View_nextFocusLeft 5926 */ 5927 public void setNextFocusLeftId(int nextFocusLeftId) { 5928 mNextFocusLeftId = nextFocusLeftId; 5929 } 5930 5931 /** 5932 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5933 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5934 * 5935 * @attr ref android.R.styleable#View_nextFocusRight 5936 */ 5937 public int getNextFocusRightId() { 5938 return mNextFocusRightId; 5939 } 5940 5941 /** 5942 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5943 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5944 * decide automatically. 5945 * 5946 * @attr ref android.R.styleable#View_nextFocusRight 5947 */ 5948 public void setNextFocusRightId(int nextFocusRightId) { 5949 mNextFocusRightId = nextFocusRightId; 5950 } 5951 5952 /** 5953 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5954 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5955 * 5956 * @attr ref android.R.styleable#View_nextFocusUp 5957 */ 5958 public int getNextFocusUpId() { 5959 return mNextFocusUpId; 5960 } 5961 5962 /** 5963 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5964 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5965 * decide automatically. 5966 * 5967 * @attr ref android.R.styleable#View_nextFocusUp 5968 */ 5969 public void setNextFocusUpId(int nextFocusUpId) { 5970 mNextFocusUpId = nextFocusUpId; 5971 } 5972 5973 /** 5974 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5975 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5976 * 5977 * @attr ref android.R.styleable#View_nextFocusDown 5978 */ 5979 public int getNextFocusDownId() { 5980 return mNextFocusDownId; 5981 } 5982 5983 /** 5984 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5985 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 5986 * decide automatically. 5987 * 5988 * @attr ref android.R.styleable#View_nextFocusDown 5989 */ 5990 public void setNextFocusDownId(int nextFocusDownId) { 5991 mNextFocusDownId = nextFocusDownId; 5992 } 5993 5994 /** 5995 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5996 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5997 * 5998 * @attr ref android.R.styleable#View_nextFocusForward 5999 */ 6000 public int getNextFocusForwardId() { 6001 return mNextFocusForwardId; 6002 } 6003 6004 /** 6005 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6006 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6007 * decide automatically. 6008 * 6009 * @attr ref android.R.styleable#View_nextFocusForward 6010 */ 6011 public void setNextFocusForwardId(int nextFocusForwardId) { 6012 mNextFocusForwardId = nextFocusForwardId; 6013 } 6014 6015 /** 6016 * Returns the visibility of this view and all of its ancestors 6017 * 6018 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6019 */ 6020 public boolean isShown() { 6021 View current = this; 6022 //noinspection ConstantConditions 6023 do { 6024 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6025 return false; 6026 } 6027 ViewParent parent = current.mParent; 6028 if (parent == null) { 6029 return false; // We are not attached to the view root 6030 } 6031 if (!(parent instanceof View)) { 6032 return true; 6033 } 6034 current = (View) parent; 6035 } while (current != null); 6036 6037 return false; 6038 } 6039 6040 /** 6041 * Called by the view hierarchy when the content insets for a window have 6042 * changed, to allow it to adjust its content to fit within those windows. 6043 * The content insets tell you the space that the status bar, input method, 6044 * and other system windows infringe on the application's window. 6045 * 6046 * <p>You do not normally need to deal with this function, since the default 6047 * window decoration given to applications takes care of applying it to the 6048 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6049 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6050 * and your content can be placed under those system elements. You can then 6051 * use this method within your view hierarchy if you have parts of your UI 6052 * which you would like to ensure are not being covered. 6053 * 6054 * <p>The default implementation of this method simply applies the content 6055 * insets to the view's padding, consuming that content (modifying the 6056 * insets to be 0), and returning true. This behavior is off by default, but can 6057 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6058 * 6059 * <p>This function's traversal down the hierarchy is depth-first. The same content 6060 * insets object is propagated down the hierarchy, so any changes made to it will 6061 * be seen by all following views (including potentially ones above in 6062 * the hierarchy since this is a depth-first traversal). The first view 6063 * that returns true will abort the entire traversal. 6064 * 6065 * <p>The default implementation works well for a situation where it is 6066 * used with a container that covers the entire window, allowing it to 6067 * apply the appropriate insets to its content on all edges. If you need 6068 * a more complicated layout (such as two different views fitting system 6069 * windows, one on the top of the window, and one on the bottom), 6070 * you can override the method and handle the insets however you would like. 6071 * Note that the insets provided by the framework are always relative to the 6072 * far edges of the window, not accounting for the location of the called view 6073 * within that window. (In fact when this method is called you do not yet know 6074 * where the layout will place the view, as it is done before layout happens.) 6075 * 6076 * <p>Note: unlike many View methods, there is no dispatch phase to this 6077 * call. If you are overriding it in a ViewGroup and want to allow the 6078 * call to continue to your children, you must be sure to call the super 6079 * implementation. 6080 * 6081 * <p>Here is a sample layout that makes use of fitting system windows 6082 * to have controls for a video view placed inside of the window decorations 6083 * that it hides and shows. This can be used with code like the second 6084 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6085 * 6086 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6087 * 6088 * @param insets Current content insets of the window. Prior to 6089 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6090 * the insets or else you and Android will be unhappy. 6091 * 6092 * @return {@code true} if this view applied the insets and it should not 6093 * continue propagating further down the hierarchy, {@code false} otherwise. 6094 * @see #getFitsSystemWindows() 6095 * @see #setFitsSystemWindows(boolean) 6096 * @see #setSystemUiVisibility(int) 6097 * 6098 * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6099 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6100 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6101 * to implement handling their own insets. 6102 */ 6103 protected boolean fitSystemWindows(Rect insets) { 6104 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6105 // If we're not in the process of dispatching the newer apply insets call, 6106 // that means we're not in the compatibility path. Dispatch into the newer 6107 // apply insets path and take things from there. 6108 try { 6109 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6110 return !dispatchApplyWindowInsets(new WindowInsets(insets)).hasInsets(); 6111 } finally { 6112 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6113 } 6114 } else { 6115 // We're being called from the newer apply insets path. 6116 // Perform the standard fallback behavior. 6117 return fitSystemWindowsInt(insets); 6118 } 6119 } 6120 6121 private boolean fitSystemWindowsInt(Rect insets) { 6122 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6123 mUserPaddingStart = UNDEFINED_PADDING; 6124 mUserPaddingEnd = UNDEFINED_PADDING; 6125 Rect localInsets = sThreadLocal.get(); 6126 if (localInsets == null) { 6127 localInsets = new Rect(); 6128 sThreadLocal.set(localInsets); 6129 } 6130 boolean res = computeFitSystemWindows(insets, localInsets); 6131 mUserPaddingLeftInitial = localInsets.left; 6132 mUserPaddingRightInitial = localInsets.right; 6133 internalSetPadding(localInsets.left, localInsets.top, 6134 localInsets.right, localInsets.bottom); 6135 return res; 6136 } 6137 return false; 6138 } 6139 6140 /** 6141 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6142 * 6143 * <p>This method should be overridden by views that wish to apply a policy different from or 6144 * in addition to the default behavior. Clients that wish to force a view subtree 6145 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6146 * 6147 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6148 * it will be called during dispatch instead of this method. The listener may optionally 6149 * call this method from its own implementation if it wishes to apply the view's default 6150 * insets policy in addition to its own.</p> 6151 * 6152 * <p>Implementations of this method should either return the insets parameter unchanged 6153 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6154 * that this view applied itself. This allows new inset types added in future platform 6155 * versions to pass through existing implementations unchanged without being erroneously 6156 * consumed.</p> 6157 * 6158 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6159 * property is set then the view will consume the system window insets and apply them 6160 * as padding for the view.</p> 6161 * 6162 * @param insets Insets to apply 6163 * @return The supplied insets with any applied insets consumed 6164 */ 6165 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6166 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6167 // We weren't called from within a direct call to fitSystemWindows, 6168 // call into it as a fallback in case we're in a class that overrides it 6169 // and has logic to perform. 6170 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6171 return insets.consumeSystemWindowInsets(); 6172 } 6173 } else { 6174 // We were called from within a direct call to fitSystemWindows. 6175 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6176 return insets.consumeSystemWindowInsets(); 6177 } 6178 } 6179 return insets; 6180 } 6181 6182 /** 6183 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6184 * window insets to this view. The listener's 6185 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6186 * method will be called instead of the view's 6187 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6188 * 6189 * @param listener Listener to set 6190 * 6191 * @see #onApplyWindowInsets(WindowInsets) 6192 */ 6193 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6194 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6195 } 6196 6197 /** 6198 * Request to apply the given window insets to this view or another view in its subtree. 6199 * 6200 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6201 * obscured by window decorations or overlays. This can include the status and navigation bars, 6202 * action bars, input methods and more. New inset categories may be added in the future. 6203 * The method returns the insets provided minus any that were applied by this view or its 6204 * children.</p> 6205 * 6206 * <p>Clients wishing to provide custom behavior should override the 6207 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6208 * {@link OnApplyWindowInsetsListener} via the 6209 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6210 * method.</p> 6211 * 6212 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6213 * </p> 6214 * 6215 * @param insets Insets to apply 6216 * @return The provided insets minus the insets that were consumed 6217 */ 6218 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6219 try { 6220 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6221 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6222 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6223 } else { 6224 return onApplyWindowInsets(insets); 6225 } 6226 } finally { 6227 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6228 } 6229 } 6230 6231 /** 6232 * @hide Compute the insets that should be consumed by this view and the ones 6233 * that should propagate to those under it. 6234 */ 6235 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6236 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6237 || mAttachInfo == null 6238 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6239 && !mAttachInfo.mOverscanRequested)) { 6240 outLocalInsets.set(inoutInsets); 6241 inoutInsets.set(0, 0, 0, 0); 6242 return true; 6243 } else { 6244 // The application wants to take care of fitting system window for 6245 // the content... however we still need to take care of any overscan here. 6246 final Rect overscan = mAttachInfo.mOverscanInsets; 6247 outLocalInsets.set(overscan); 6248 inoutInsets.left -= overscan.left; 6249 inoutInsets.top -= overscan.top; 6250 inoutInsets.right -= overscan.right; 6251 inoutInsets.bottom -= overscan.bottom; 6252 return false; 6253 } 6254 } 6255 6256 /** 6257 * Sets whether or not this view should account for system screen decorations 6258 * such as the status bar and inset its content; that is, controlling whether 6259 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6260 * executed. See that method for more details. 6261 * 6262 * <p>Note that if you are providing your own implementation of 6263 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6264 * flag to true -- your implementation will be overriding the default 6265 * implementation that checks this flag. 6266 * 6267 * @param fitSystemWindows If true, then the default implementation of 6268 * {@link #fitSystemWindows(Rect)} will be executed. 6269 * 6270 * @attr ref android.R.styleable#View_fitsSystemWindows 6271 * @see #getFitsSystemWindows() 6272 * @see #fitSystemWindows(Rect) 6273 * @see #setSystemUiVisibility(int) 6274 */ 6275 public void setFitsSystemWindows(boolean fitSystemWindows) { 6276 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6277 } 6278 6279 /** 6280 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6281 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6282 * will be executed. 6283 * 6284 * @return {@code true} if the default implementation of 6285 * {@link #fitSystemWindows(Rect)} will be executed. 6286 * 6287 * @attr ref android.R.styleable#View_fitsSystemWindows 6288 * @see #setFitsSystemWindows(boolean) 6289 * @see #fitSystemWindows(Rect) 6290 * @see #setSystemUiVisibility(int) 6291 */ 6292 public boolean getFitsSystemWindows() { 6293 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6294 } 6295 6296 /** @hide */ 6297 public boolean fitsSystemWindows() { 6298 return getFitsSystemWindows(); 6299 } 6300 6301 /** 6302 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6303 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6304 */ 6305 public void requestFitSystemWindows() { 6306 if (mParent != null) { 6307 mParent.requestFitSystemWindows(); 6308 } 6309 } 6310 6311 /** 6312 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6313 */ 6314 public void requestApplyInsets() { 6315 requestFitSystemWindows(); 6316 } 6317 6318 /** 6319 * For use by PhoneWindow to make its own system window fitting optional. 6320 * @hide 6321 */ 6322 public void makeOptionalFitsSystemWindows() { 6323 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6324 } 6325 6326 /** 6327 * Returns the visibility status for this view. 6328 * 6329 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6330 * @attr ref android.R.styleable#View_visibility 6331 */ 6332 @ViewDebug.ExportedProperty(mapping = { 6333 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6334 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6335 @ViewDebug.IntToString(from = GONE, to = "GONE") 6336 }) 6337 @Visibility 6338 public int getVisibility() { 6339 return mViewFlags & VISIBILITY_MASK; 6340 } 6341 6342 /** 6343 * Set the enabled state of this view. 6344 * 6345 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6346 * @attr ref android.R.styleable#View_visibility 6347 */ 6348 @RemotableViewMethod 6349 public void setVisibility(@Visibility int visibility) { 6350 setFlags(visibility, VISIBILITY_MASK); 6351 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6352 } 6353 6354 /** 6355 * Returns the enabled status for this view. The interpretation of the 6356 * enabled state varies by subclass. 6357 * 6358 * @return True if this view is enabled, false otherwise. 6359 */ 6360 @ViewDebug.ExportedProperty 6361 public boolean isEnabled() { 6362 return (mViewFlags & ENABLED_MASK) == ENABLED; 6363 } 6364 6365 /** 6366 * Set the enabled state of this view. The interpretation of the enabled 6367 * state varies by subclass. 6368 * 6369 * @param enabled True if this view is enabled, false otherwise. 6370 */ 6371 @RemotableViewMethod 6372 public void setEnabled(boolean enabled) { 6373 if (enabled == isEnabled()) return; 6374 6375 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6376 6377 /* 6378 * The View most likely has to change its appearance, so refresh 6379 * the drawable state. 6380 */ 6381 refreshDrawableState(); 6382 6383 // Invalidate too, since the default behavior for views is to be 6384 // be drawn at 50% alpha rather than to change the drawable. 6385 invalidate(true); 6386 6387 if (!enabled) { 6388 cancelPendingInputEvents(); 6389 } 6390 } 6391 6392 /** 6393 * Set whether this view can receive the focus. 6394 * 6395 * Setting this to false will also ensure that this view is not focusable 6396 * in touch mode. 6397 * 6398 * @param focusable If true, this view can receive the focus. 6399 * 6400 * @see #setFocusableInTouchMode(boolean) 6401 * @attr ref android.R.styleable#View_focusable 6402 */ 6403 public void setFocusable(boolean focusable) { 6404 if (!focusable) { 6405 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6406 } 6407 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6408 } 6409 6410 /** 6411 * Set whether this view can receive focus while in touch mode. 6412 * 6413 * Setting this to true will also ensure that this view is focusable. 6414 * 6415 * @param focusableInTouchMode If true, this view can receive the focus while 6416 * in touch mode. 6417 * 6418 * @see #setFocusable(boolean) 6419 * @attr ref android.R.styleable#View_focusableInTouchMode 6420 */ 6421 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6422 // Focusable in touch mode should always be set before the focusable flag 6423 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6424 // which, in touch mode, will not successfully request focus on this view 6425 // because the focusable in touch mode flag is not set 6426 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6427 if (focusableInTouchMode) { 6428 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6429 } 6430 } 6431 6432 /** 6433 * Set whether this view should have sound effects enabled for events such as 6434 * clicking and touching. 6435 * 6436 * <p>You may wish to disable sound effects for a view if you already play sounds, 6437 * for instance, a dial key that plays dtmf tones. 6438 * 6439 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6440 * @see #isSoundEffectsEnabled() 6441 * @see #playSoundEffect(int) 6442 * @attr ref android.R.styleable#View_soundEffectsEnabled 6443 */ 6444 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6445 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6446 } 6447 6448 /** 6449 * @return whether this view should have sound effects enabled for events such as 6450 * clicking and touching. 6451 * 6452 * @see #setSoundEffectsEnabled(boolean) 6453 * @see #playSoundEffect(int) 6454 * @attr ref android.R.styleable#View_soundEffectsEnabled 6455 */ 6456 @ViewDebug.ExportedProperty 6457 public boolean isSoundEffectsEnabled() { 6458 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6459 } 6460 6461 /** 6462 * Set whether this view should have haptic feedback for events such as 6463 * long presses. 6464 * 6465 * <p>You may wish to disable haptic feedback if your view already controls 6466 * its own haptic feedback. 6467 * 6468 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6469 * @see #isHapticFeedbackEnabled() 6470 * @see #performHapticFeedback(int) 6471 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6472 */ 6473 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6474 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6475 } 6476 6477 /** 6478 * @return whether this view should have haptic feedback enabled for events 6479 * long presses. 6480 * 6481 * @see #setHapticFeedbackEnabled(boolean) 6482 * @see #performHapticFeedback(int) 6483 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6484 */ 6485 @ViewDebug.ExportedProperty 6486 public boolean isHapticFeedbackEnabled() { 6487 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6488 } 6489 6490 /** 6491 * Returns the layout direction for this view. 6492 * 6493 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6494 * {@link #LAYOUT_DIRECTION_RTL}, 6495 * {@link #LAYOUT_DIRECTION_INHERIT} or 6496 * {@link #LAYOUT_DIRECTION_LOCALE}. 6497 * 6498 * @attr ref android.R.styleable#View_layoutDirection 6499 * 6500 * @hide 6501 */ 6502 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6503 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6504 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6505 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6506 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6507 }) 6508 @LayoutDir 6509 public int getRawLayoutDirection() { 6510 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6511 } 6512 6513 /** 6514 * Set the layout direction for this view. This will propagate a reset of layout direction 6515 * resolution to the view's children and resolve layout direction for this view. 6516 * 6517 * @param layoutDirection the layout direction to set. Should be one of: 6518 * 6519 * {@link #LAYOUT_DIRECTION_LTR}, 6520 * {@link #LAYOUT_DIRECTION_RTL}, 6521 * {@link #LAYOUT_DIRECTION_INHERIT}, 6522 * {@link #LAYOUT_DIRECTION_LOCALE}. 6523 * 6524 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6525 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6526 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6527 * 6528 * @attr ref android.R.styleable#View_layoutDirection 6529 */ 6530 @RemotableViewMethod 6531 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6532 if (getRawLayoutDirection() != layoutDirection) { 6533 // Reset the current layout direction and the resolved one 6534 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6535 resetRtlProperties(); 6536 // Set the new layout direction (filtered) 6537 mPrivateFlags2 |= 6538 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6539 // We need to resolve all RTL properties as they all depend on layout direction 6540 resolveRtlPropertiesIfNeeded(); 6541 requestLayout(); 6542 invalidate(true); 6543 } 6544 } 6545 6546 /** 6547 * Returns the resolved layout direction for this view. 6548 * 6549 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6550 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6551 * 6552 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6553 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6554 * 6555 * @attr ref android.R.styleable#View_layoutDirection 6556 */ 6557 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6558 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6559 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6560 }) 6561 @ResolvedLayoutDir 6562 public int getLayoutDirection() { 6563 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6564 if (targetSdkVersion < JELLY_BEAN_MR1) { 6565 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6566 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6567 } 6568 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6569 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6570 } 6571 6572 /** 6573 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6574 * layout attribute and/or the inherited value from the parent 6575 * 6576 * @return true if the layout is right-to-left. 6577 * 6578 * @hide 6579 */ 6580 @ViewDebug.ExportedProperty(category = "layout") 6581 public boolean isLayoutRtl() { 6582 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6583 } 6584 6585 /** 6586 * Indicates whether the view is currently tracking transient state that the 6587 * app should not need to concern itself with saving and restoring, but that 6588 * the framework should take special note to preserve when possible. 6589 * 6590 * <p>A view with transient state cannot be trivially rebound from an external 6591 * data source, such as an adapter binding item views in a list. This may be 6592 * because the view is performing an animation, tracking user selection 6593 * of content, or similar.</p> 6594 * 6595 * @return true if the view has transient state 6596 */ 6597 @ViewDebug.ExportedProperty(category = "layout") 6598 public boolean hasTransientState() { 6599 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6600 } 6601 6602 /** 6603 * Set whether this view is currently tracking transient state that the 6604 * framework should attempt to preserve when possible. This flag is reference counted, 6605 * so every call to setHasTransientState(true) should be paired with a later call 6606 * to setHasTransientState(false). 6607 * 6608 * <p>A view with transient state cannot be trivially rebound from an external 6609 * data source, such as an adapter binding item views in a list. This may be 6610 * because the view is performing an animation, tracking user selection 6611 * of content, or similar.</p> 6612 * 6613 * @param hasTransientState true if this view has transient state 6614 */ 6615 public void setHasTransientState(boolean hasTransientState) { 6616 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6617 mTransientStateCount - 1; 6618 if (mTransientStateCount < 0) { 6619 mTransientStateCount = 0; 6620 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6621 "unmatched pair of setHasTransientState calls"); 6622 } else if ((hasTransientState && mTransientStateCount == 1) || 6623 (!hasTransientState && mTransientStateCount == 0)) { 6624 // update flag if we've just incremented up from 0 or decremented down to 0 6625 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6626 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6627 if (mParent != null) { 6628 try { 6629 mParent.childHasTransientStateChanged(this, hasTransientState); 6630 } catch (AbstractMethodError e) { 6631 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6632 " does not fully implement ViewParent", e); 6633 } 6634 } 6635 } 6636 } 6637 6638 /** 6639 * Returns true if this view is currently attached to a window. 6640 */ 6641 public boolean isAttachedToWindow() { 6642 return mAttachInfo != null; 6643 } 6644 6645 /** 6646 * Returns true if this view has been through at least one layout since it 6647 * was last attached to or detached from a window. 6648 */ 6649 public boolean isLaidOut() { 6650 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6651 } 6652 6653 /** 6654 * If this view doesn't do any drawing on its own, set this flag to 6655 * allow further optimizations. By default, this flag is not set on 6656 * View, but could be set on some View subclasses such as ViewGroup. 6657 * 6658 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6659 * you should clear this flag. 6660 * 6661 * @param willNotDraw whether or not this View draw on its own 6662 */ 6663 public void setWillNotDraw(boolean willNotDraw) { 6664 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6665 } 6666 6667 /** 6668 * Returns whether or not this View draws on its own. 6669 * 6670 * @return true if this view has nothing to draw, false otherwise 6671 */ 6672 @ViewDebug.ExportedProperty(category = "drawing") 6673 public boolean willNotDraw() { 6674 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6675 } 6676 6677 /** 6678 * When a View's drawing cache is enabled, drawing is redirected to an 6679 * offscreen bitmap. Some views, like an ImageView, must be able to 6680 * bypass this mechanism if they already draw a single bitmap, to avoid 6681 * unnecessary usage of the memory. 6682 * 6683 * @param willNotCacheDrawing true if this view does not cache its 6684 * drawing, false otherwise 6685 */ 6686 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6687 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6688 } 6689 6690 /** 6691 * Returns whether or not this View can cache its drawing or not. 6692 * 6693 * @return true if this view does not cache its drawing, false otherwise 6694 */ 6695 @ViewDebug.ExportedProperty(category = "drawing") 6696 public boolean willNotCacheDrawing() { 6697 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6698 } 6699 6700 /** 6701 * Indicates whether this view reacts to click events or not. 6702 * 6703 * @return true if the view is clickable, false otherwise 6704 * 6705 * @see #setClickable(boolean) 6706 * @attr ref android.R.styleable#View_clickable 6707 */ 6708 @ViewDebug.ExportedProperty 6709 public boolean isClickable() { 6710 return (mViewFlags & CLICKABLE) == CLICKABLE; 6711 } 6712 6713 /** 6714 * Enables or disables click events for this view. When a view 6715 * is clickable it will change its state to "pressed" on every click. 6716 * Subclasses should set the view clickable to visually react to 6717 * user's clicks. 6718 * 6719 * @param clickable true to make the view clickable, false otherwise 6720 * 6721 * @see #isClickable() 6722 * @attr ref android.R.styleable#View_clickable 6723 */ 6724 public void setClickable(boolean clickable) { 6725 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6726 } 6727 6728 /** 6729 * Indicates whether this view reacts to long click events or not. 6730 * 6731 * @return true if the view is long clickable, false otherwise 6732 * 6733 * @see #setLongClickable(boolean) 6734 * @attr ref android.R.styleable#View_longClickable 6735 */ 6736 public boolean isLongClickable() { 6737 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6738 } 6739 6740 /** 6741 * Enables or disables long click events for this view. When a view is long 6742 * clickable it reacts to the user holding down the button for a longer 6743 * duration than a tap. This event can either launch the listener or a 6744 * context menu. 6745 * 6746 * @param longClickable true to make the view long clickable, false otherwise 6747 * @see #isLongClickable() 6748 * @attr ref android.R.styleable#View_longClickable 6749 */ 6750 public void setLongClickable(boolean longClickable) { 6751 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6752 } 6753 6754 /** 6755 * Sets the pressed state for this view. 6756 * 6757 * @see #isClickable() 6758 * @see #setClickable(boolean) 6759 * 6760 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6761 * the View's internal state from a previously set "pressed" state. 6762 */ 6763 public void setPressed(boolean pressed) { 6764 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6765 6766 if (pressed) { 6767 mPrivateFlags |= PFLAG_PRESSED; 6768 } else { 6769 mPrivateFlags &= ~PFLAG_PRESSED; 6770 } 6771 6772 if (needsRefresh) { 6773 refreshDrawableState(); 6774 } 6775 dispatchSetPressed(pressed); 6776 } 6777 6778 /** 6779 * Dispatch setPressed to all of this View's children. 6780 * 6781 * @see #setPressed(boolean) 6782 * 6783 * @param pressed The new pressed state 6784 */ 6785 protected void dispatchSetPressed(boolean pressed) { 6786 } 6787 6788 /** 6789 * Indicates whether the view is currently in pressed state. Unless 6790 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6791 * the pressed state. 6792 * 6793 * @see #setPressed(boolean) 6794 * @see #isClickable() 6795 * @see #setClickable(boolean) 6796 * 6797 * @return true if the view is currently pressed, false otherwise 6798 */ 6799 public boolean isPressed() { 6800 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6801 } 6802 6803 /** 6804 * Indicates whether this view will save its state (that is, 6805 * whether its {@link #onSaveInstanceState} method will be called). 6806 * 6807 * @return Returns true if the view state saving is enabled, else false. 6808 * 6809 * @see #setSaveEnabled(boolean) 6810 * @attr ref android.R.styleable#View_saveEnabled 6811 */ 6812 public boolean isSaveEnabled() { 6813 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6814 } 6815 6816 /** 6817 * Controls whether the saving of this view's state is 6818 * enabled (that is, whether its {@link #onSaveInstanceState} method 6819 * will be called). Note that even if freezing is enabled, the 6820 * view still must have an id assigned to it (via {@link #setId(int)}) 6821 * for its state to be saved. This flag can only disable the 6822 * saving of this view; any child views may still have their state saved. 6823 * 6824 * @param enabled Set to false to <em>disable</em> state saving, or true 6825 * (the default) to allow it. 6826 * 6827 * @see #isSaveEnabled() 6828 * @see #setId(int) 6829 * @see #onSaveInstanceState() 6830 * @attr ref android.R.styleable#View_saveEnabled 6831 */ 6832 public void setSaveEnabled(boolean enabled) { 6833 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6834 } 6835 6836 /** 6837 * Gets whether the framework should discard touches when the view's 6838 * window is obscured by another visible window. 6839 * Refer to the {@link View} security documentation for more details. 6840 * 6841 * @return True if touch filtering is enabled. 6842 * 6843 * @see #setFilterTouchesWhenObscured(boolean) 6844 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6845 */ 6846 @ViewDebug.ExportedProperty 6847 public boolean getFilterTouchesWhenObscured() { 6848 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6849 } 6850 6851 /** 6852 * Sets whether the framework should discard touches when the view's 6853 * window is obscured by another visible window. 6854 * Refer to the {@link View} security documentation for more details. 6855 * 6856 * @param enabled True if touch filtering should be enabled. 6857 * 6858 * @see #getFilterTouchesWhenObscured 6859 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6860 */ 6861 public void setFilterTouchesWhenObscured(boolean enabled) { 6862 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 6863 FILTER_TOUCHES_WHEN_OBSCURED); 6864 } 6865 6866 /** 6867 * Indicates whether the entire hierarchy under this view will save its 6868 * state when a state saving traversal occurs from its parent. The default 6869 * is true; if false, these views will not be saved unless 6870 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6871 * 6872 * @return Returns true if the view state saving from parent is enabled, else false. 6873 * 6874 * @see #setSaveFromParentEnabled(boolean) 6875 */ 6876 public boolean isSaveFromParentEnabled() { 6877 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6878 } 6879 6880 /** 6881 * Controls whether the entire hierarchy under this view will save its 6882 * state when a state saving traversal occurs from its parent. The default 6883 * is true; if false, these views will not be saved unless 6884 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6885 * 6886 * @param enabled Set to false to <em>disable</em> state saving, or true 6887 * (the default) to allow it. 6888 * 6889 * @see #isSaveFromParentEnabled() 6890 * @see #setId(int) 6891 * @see #onSaveInstanceState() 6892 */ 6893 public void setSaveFromParentEnabled(boolean enabled) { 6894 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6895 } 6896 6897 6898 /** 6899 * Returns whether this View is able to take focus. 6900 * 6901 * @return True if this view can take focus, or false otherwise. 6902 * @attr ref android.R.styleable#View_focusable 6903 */ 6904 @ViewDebug.ExportedProperty(category = "focus") 6905 public final boolean isFocusable() { 6906 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6907 } 6908 6909 /** 6910 * When a view is focusable, it may not want to take focus when in touch mode. 6911 * For example, a button would like focus when the user is navigating via a D-pad 6912 * so that the user can click on it, but once the user starts touching the screen, 6913 * the button shouldn't take focus 6914 * @return Whether the view is focusable in touch mode. 6915 * @attr ref android.R.styleable#View_focusableInTouchMode 6916 */ 6917 @ViewDebug.ExportedProperty 6918 public final boolean isFocusableInTouchMode() { 6919 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6920 } 6921 6922 /** 6923 * Find the nearest view in the specified direction that can take focus. 6924 * This does not actually give focus to that view. 6925 * 6926 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6927 * 6928 * @return The nearest focusable in the specified direction, or null if none 6929 * can be found. 6930 */ 6931 public View focusSearch(@FocusRealDirection int direction) { 6932 if (mParent != null) { 6933 return mParent.focusSearch(this, direction); 6934 } else { 6935 return null; 6936 } 6937 } 6938 6939 /** 6940 * This method is the last chance for the focused view and its ancestors to 6941 * respond to an arrow key. This is called when the focused view did not 6942 * consume the key internally, nor could the view system find a new view in 6943 * the requested direction to give focus to. 6944 * 6945 * @param focused The currently focused view. 6946 * @param direction The direction focus wants to move. One of FOCUS_UP, 6947 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6948 * @return True if the this view consumed this unhandled move. 6949 */ 6950 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 6951 return false; 6952 } 6953 6954 /** 6955 * If a user manually specified the next view id for a particular direction, 6956 * use the root to look up the view. 6957 * @param root The root view of the hierarchy containing this view. 6958 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6959 * or FOCUS_BACKWARD. 6960 * @return The user specified next view, or null if there is none. 6961 */ 6962 View findUserSetNextFocus(View root, @FocusDirection int direction) { 6963 switch (direction) { 6964 case FOCUS_LEFT: 6965 if (mNextFocusLeftId == View.NO_ID) return null; 6966 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6967 case FOCUS_RIGHT: 6968 if (mNextFocusRightId == View.NO_ID) return null; 6969 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6970 case FOCUS_UP: 6971 if (mNextFocusUpId == View.NO_ID) return null; 6972 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6973 case FOCUS_DOWN: 6974 if (mNextFocusDownId == View.NO_ID) return null; 6975 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6976 case FOCUS_FORWARD: 6977 if (mNextFocusForwardId == View.NO_ID) return null; 6978 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6979 case FOCUS_BACKWARD: { 6980 if (mID == View.NO_ID) return null; 6981 final int id = mID; 6982 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6983 @Override 6984 public boolean apply(View t) { 6985 return t.mNextFocusForwardId == id; 6986 } 6987 }); 6988 } 6989 } 6990 return null; 6991 } 6992 6993 private View findViewInsideOutShouldExist(View root, int id) { 6994 if (mMatchIdPredicate == null) { 6995 mMatchIdPredicate = new MatchIdPredicate(); 6996 } 6997 mMatchIdPredicate.mId = id; 6998 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 6999 if (result == null) { 7000 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7001 } 7002 return result; 7003 } 7004 7005 /** 7006 * Find and return all focusable views that are descendants of this view, 7007 * possibly including this view if it is focusable itself. 7008 * 7009 * @param direction The direction of the focus 7010 * @return A list of focusable views 7011 */ 7012 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7013 ArrayList<View> result = new ArrayList<View>(24); 7014 addFocusables(result, direction); 7015 return result; 7016 } 7017 7018 /** 7019 * Add any focusable views that are descendants of this view (possibly 7020 * including this view if it is focusable itself) to views. If we are in touch mode, 7021 * only add views that are also focusable in touch mode. 7022 * 7023 * @param views Focusable views found so far 7024 * @param direction The direction of the focus 7025 */ 7026 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7027 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7028 } 7029 7030 /** 7031 * Adds any focusable views that are descendants of this view (possibly 7032 * including this view if it is focusable itself) to views. This method 7033 * adds all focusable views regardless if we are in touch mode or 7034 * only views focusable in touch mode if we are in touch mode or 7035 * only views that can take accessibility focus if accessibility is enabeld 7036 * depending on the focusable mode paramater. 7037 * 7038 * @param views Focusable views found so far or null if all we are interested is 7039 * the number of focusables. 7040 * @param direction The direction of the focus. 7041 * @param focusableMode The type of focusables to be added. 7042 * 7043 * @see #FOCUSABLES_ALL 7044 * @see #FOCUSABLES_TOUCH_MODE 7045 */ 7046 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7047 @FocusableMode int focusableMode) { 7048 if (views == null) { 7049 return; 7050 } 7051 if (!isFocusable()) { 7052 return; 7053 } 7054 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7055 && isInTouchMode() && !isFocusableInTouchMode()) { 7056 return; 7057 } 7058 views.add(this); 7059 } 7060 7061 /** 7062 * Finds the Views that contain given text. The containment is case insensitive. 7063 * The search is performed by either the text that the View renders or the content 7064 * description that describes the view for accessibility purposes and the view does 7065 * not render or both. Clients can specify how the search is to be performed via 7066 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7067 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7068 * 7069 * @param outViews The output list of matching Views. 7070 * @param searched The text to match against. 7071 * 7072 * @see #FIND_VIEWS_WITH_TEXT 7073 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7074 * @see #setContentDescription(CharSequence) 7075 */ 7076 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7077 @FindViewFlags int flags) { 7078 if (getAccessibilityNodeProvider() != null) { 7079 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7080 outViews.add(this); 7081 } 7082 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7083 && (searched != null && searched.length() > 0) 7084 && (mContentDescription != null && mContentDescription.length() > 0)) { 7085 String searchedLowerCase = searched.toString().toLowerCase(); 7086 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7087 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7088 outViews.add(this); 7089 } 7090 } 7091 } 7092 7093 /** 7094 * Find and return all touchable views that are descendants of this view, 7095 * possibly including this view if it is touchable itself. 7096 * 7097 * @return A list of touchable views 7098 */ 7099 public ArrayList<View> getTouchables() { 7100 ArrayList<View> result = new ArrayList<View>(); 7101 addTouchables(result); 7102 return result; 7103 } 7104 7105 /** 7106 * Add any touchable views that are descendants of this view (possibly 7107 * including this view if it is touchable itself) to views. 7108 * 7109 * @param views Touchable views found so far 7110 */ 7111 public void addTouchables(ArrayList<View> views) { 7112 final int viewFlags = mViewFlags; 7113 7114 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7115 && (viewFlags & ENABLED_MASK) == ENABLED) { 7116 views.add(this); 7117 } 7118 } 7119 7120 /** 7121 * Returns whether this View is accessibility focused. 7122 * 7123 * @return True if this View is accessibility focused. 7124 */ 7125 public boolean isAccessibilityFocused() { 7126 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7127 } 7128 7129 /** 7130 * Call this to try to give accessibility focus to this view. 7131 * 7132 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7133 * returns false or the view is no visible or the view already has accessibility 7134 * focus. 7135 * 7136 * See also {@link #focusSearch(int)}, which is what you call to say that you 7137 * have focus, and you want your parent to look for the next one. 7138 * 7139 * @return Whether this view actually took accessibility focus. 7140 * 7141 * @hide 7142 */ 7143 public boolean requestAccessibilityFocus() { 7144 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7145 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7146 return false; 7147 } 7148 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7149 return false; 7150 } 7151 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7152 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7153 ViewRootImpl viewRootImpl = getViewRootImpl(); 7154 if (viewRootImpl != null) { 7155 viewRootImpl.setAccessibilityFocus(this, null); 7156 } 7157 Rect rect = (mAttachInfo != null) ? mAttachInfo.mTmpInvalRect : new Rect(); 7158 getDrawingRect(rect); 7159 requestRectangleOnScreen(rect, false); 7160 invalidate(); 7161 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7162 return true; 7163 } 7164 return false; 7165 } 7166 7167 /** 7168 * Call this to try to clear accessibility focus of this view. 7169 * 7170 * See also {@link #focusSearch(int)}, which is what you call to say that you 7171 * have focus, and you want your parent to look for the next one. 7172 * 7173 * @hide 7174 */ 7175 public void clearAccessibilityFocus() { 7176 clearAccessibilityFocusNoCallbacks(); 7177 // Clear the global reference of accessibility focus if this 7178 // view or any of its descendants had accessibility focus. 7179 ViewRootImpl viewRootImpl = getViewRootImpl(); 7180 if (viewRootImpl != null) { 7181 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7182 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7183 viewRootImpl.setAccessibilityFocus(null, null); 7184 } 7185 } 7186 } 7187 7188 private void sendAccessibilityHoverEvent(int eventType) { 7189 // Since we are not delivering to a client accessibility events from not 7190 // important views (unless the clinet request that) we need to fire the 7191 // event from the deepest view exposed to the client. As a consequence if 7192 // the user crosses a not exposed view the client will see enter and exit 7193 // of the exposed predecessor followed by and enter and exit of that same 7194 // predecessor when entering and exiting the not exposed descendant. This 7195 // is fine since the client has a clear idea which view is hovered at the 7196 // price of a couple more events being sent. This is a simple and 7197 // working solution. 7198 View source = this; 7199 while (true) { 7200 if (source.includeForAccessibility()) { 7201 source.sendAccessibilityEvent(eventType); 7202 return; 7203 } 7204 ViewParent parent = source.getParent(); 7205 if (parent instanceof View) { 7206 source = (View) parent; 7207 } else { 7208 return; 7209 } 7210 } 7211 } 7212 7213 /** 7214 * Clears accessibility focus without calling any callback methods 7215 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7216 * is used for clearing accessibility focus when giving this focus to 7217 * another view. 7218 */ 7219 void clearAccessibilityFocusNoCallbacks() { 7220 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7221 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7222 invalidate(); 7223 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7224 } 7225 } 7226 7227 /** 7228 * Call this to try to give focus to a specific view or to one of its 7229 * descendants. 7230 * 7231 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7232 * false), or if it is focusable and it is not focusable in touch mode 7233 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7234 * 7235 * See also {@link #focusSearch(int)}, which is what you call to say that you 7236 * have focus, and you want your parent to look for the next one. 7237 * 7238 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7239 * {@link #FOCUS_DOWN} and <code>null</code>. 7240 * 7241 * @return Whether this view or one of its descendants actually took focus. 7242 */ 7243 public final boolean requestFocus() { 7244 return requestFocus(View.FOCUS_DOWN); 7245 } 7246 7247 /** 7248 * Call this to try to give focus to a specific view or to one of its 7249 * descendants and give it a hint about what direction focus is heading. 7250 * 7251 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7252 * false), or if it is focusable and it is not focusable in touch mode 7253 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7254 * 7255 * See also {@link #focusSearch(int)}, which is what you call to say that you 7256 * have focus, and you want your parent to look for the next one. 7257 * 7258 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7259 * <code>null</code> set for the previously focused rectangle. 7260 * 7261 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7262 * @return Whether this view or one of its descendants actually took focus. 7263 */ 7264 public final boolean requestFocus(int direction) { 7265 return requestFocus(direction, null); 7266 } 7267 7268 /** 7269 * Call this to try to give focus to a specific view or to one of its descendants 7270 * and give it hints about the direction and a specific rectangle that the focus 7271 * is coming from. The rectangle can help give larger views a finer grained hint 7272 * about where focus is coming from, and therefore, where to show selection, or 7273 * forward focus change internally. 7274 * 7275 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7276 * false), or if it is focusable and it is not focusable in touch mode 7277 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7278 * 7279 * A View will not take focus if it is not visible. 7280 * 7281 * A View will not take focus if one of its parents has 7282 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7283 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7284 * 7285 * See also {@link #focusSearch(int)}, which is what you call to say that you 7286 * have focus, and you want your parent to look for the next one. 7287 * 7288 * You may wish to override this method if your custom {@link View} has an internal 7289 * {@link View} that it wishes to forward the request to. 7290 * 7291 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7292 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7293 * to give a finer grained hint about where focus is coming from. May be null 7294 * if there is no hint. 7295 * @return Whether this view or one of its descendants actually took focus. 7296 */ 7297 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7298 return requestFocusNoSearch(direction, previouslyFocusedRect); 7299 } 7300 7301 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7302 // need to be focusable 7303 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7304 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7305 return false; 7306 } 7307 7308 // need to be focusable in touch mode if in touch mode 7309 if (isInTouchMode() && 7310 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7311 return false; 7312 } 7313 7314 // need to not have any parents blocking us 7315 if (hasAncestorThatBlocksDescendantFocus()) { 7316 return false; 7317 } 7318 7319 handleFocusGainInternal(direction, previouslyFocusedRect); 7320 return true; 7321 } 7322 7323 /** 7324 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7325 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7326 * touch mode to request focus when they are touched. 7327 * 7328 * @return Whether this view or one of its descendants actually took focus. 7329 * 7330 * @see #isInTouchMode() 7331 * 7332 */ 7333 public final boolean requestFocusFromTouch() { 7334 // Leave touch mode if we need to 7335 if (isInTouchMode()) { 7336 ViewRootImpl viewRoot = getViewRootImpl(); 7337 if (viewRoot != null) { 7338 viewRoot.ensureTouchMode(false); 7339 } 7340 } 7341 return requestFocus(View.FOCUS_DOWN); 7342 } 7343 7344 /** 7345 * @return Whether any ancestor of this view blocks descendant focus. 7346 */ 7347 private boolean hasAncestorThatBlocksDescendantFocus() { 7348 ViewParent ancestor = mParent; 7349 while (ancestor instanceof ViewGroup) { 7350 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7351 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 7352 return true; 7353 } else { 7354 ancestor = vgAncestor.getParent(); 7355 } 7356 } 7357 return false; 7358 } 7359 7360 /** 7361 * Gets the mode for determining whether this View is important for accessibility 7362 * which is if it fires accessibility events and if it is reported to 7363 * accessibility services that query the screen. 7364 * 7365 * @return The mode for determining whether a View is important for accessibility. 7366 * 7367 * @attr ref android.R.styleable#View_importantForAccessibility 7368 * 7369 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7370 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7371 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7372 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7373 */ 7374 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7375 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7376 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7377 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7378 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7379 to = "noHideDescendants") 7380 }) 7381 public int getImportantForAccessibility() { 7382 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7383 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7384 } 7385 7386 /** 7387 * Sets the live region mode for this view. This indicates to accessibility 7388 * services whether they should automatically notify the user about changes 7389 * to the view's content description or text, or to the content descriptions 7390 * or text of the view's children (where applicable). 7391 * <p> 7392 * For example, in a login screen with a TextView that displays an "incorrect 7393 * password" notification, that view should be marked as a live region with 7394 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7395 * <p> 7396 * To disable change notifications for this view, use 7397 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7398 * mode for most views. 7399 * <p> 7400 * To indicate that the user should be notified of changes, use 7401 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7402 * <p> 7403 * If the view's changes should interrupt ongoing speech and notify the user 7404 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7405 * 7406 * @param mode The live region mode for this view, one of: 7407 * <ul> 7408 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7409 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7410 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7411 * </ul> 7412 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7413 */ 7414 public void setAccessibilityLiveRegion(int mode) { 7415 if (mode != getAccessibilityLiveRegion()) { 7416 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7417 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7418 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7419 notifyViewAccessibilityStateChangedIfNeeded( 7420 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7421 } 7422 } 7423 7424 /** 7425 * Gets the live region mode for this View. 7426 * 7427 * @return The live region mode for the view. 7428 * 7429 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7430 * 7431 * @see #setAccessibilityLiveRegion(int) 7432 */ 7433 public int getAccessibilityLiveRegion() { 7434 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7435 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7436 } 7437 7438 /** 7439 * Sets how to determine whether this view is important for accessibility 7440 * which is if it fires accessibility events and if it is reported to 7441 * accessibility services that query the screen. 7442 * 7443 * @param mode How to determine whether this view is important for accessibility. 7444 * 7445 * @attr ref android.R.styleable#View_importantForAccessibility 7446 * 7447 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7448 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7449 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7450 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7451 */ 7452 public void setImportantForAccessibility(int mode) { 7453 final int oldMode = getImportantForAccessibility(); 7454 if (mode != oldMode) { 7455 // If we're moving between AUTO and another state, we might not need 7456 // to send a subtree changed notification. We'll store the computed 7457 // importance, since we'll need to check it later to make sure. 7458 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7459 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7460 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7461 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7462 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7463 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7464 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7465 notifySubtreeAccessibilityStateChangedIfNeeded(); 7466 } else { 7467 notifyViewAccessibilityStateChangedIfNeeded( 7468 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7469 } 7470 } 7471 } 7472 7473 /** 7474 * Computes whether this view should be exposed for accessibility. In 7475 * general, views that are interactive or provide information are exposed 7476 * while views that serve only as containers are hidden. 7477 * <p> 7478 * If an ancestor of this view has importance 7479 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7480 * returns <code>false</code>. 7481 * <p> 7482 * Otherwise, the value is computed according to the view's 7483 * {@link #getImportantForAccessibility()} value: 7484 * <ol> 7485 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7486 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7487 * </code> 7488 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7489 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7490 * view satisfies any of the following: 7491 * <ul> 7492 * <li>Is actionable, e.g. {@link #isClickable()}, 7493 * {@link #isLongClickable()}, or {@link #isFocusable()} 7494 * <li>Has an {@link AccessibilityDelegate} 7495 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7496 * {@link OnKeyListener}, etc. 7497 * <li>Is an accessibility live region, e.g. 7498 * {@link #getAccessibilityLiveRegion()} is not 7499 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7500 * </ul> 7501 * </ol> 7502 * 7503 * @return Whether the view is exposed for accessibility. 7504 * @see #setImportantForAccessibility(int) 7505 * @see #getImportantForAccessibility() 7506 */ 7507 public boolean isImportantForAccessibility() { 7508 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7509 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7510 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7511 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7512 return false; 7513 } 7514 7515 // Check parent mode to ensure we're not hidden. 7516 ViewParent parent = mParent; 7517 while (parent instanceof View) { 7518 if (((View) parent).getImportantForAccessibility() 7519 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7520 return false; 7521 } 7522 parent = parent.getParent(); 7523 } 7524 7525 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7526 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7527 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7528 } 7529 7530 /** 7531 * Gets the parent for accessibility purposes. Note that the parent for 7532 * accessibility is not necessary the immediate parent. It is the first 7533 * predecessor that is important for accessibility. 7534 * 7535 * @return The parent for accessibility purposes. 7536 */ 7537 public ViewParent getParentForAccessibility() { 7538 if (mParent instanceof View) { 7539 View parentView = (View) mParent; 7540 if (parentView.includeForAccessibility()) { 7541 return mParent; 7542 } else { 7543 return mParent.getParentForAccessibility(); 7544 } 7545 } 7546 return null; 7547 } 7548 7549 /** 7550 * Adds the children of a given View for accessibility. Since some Views are 7551 * not important for accessibility the children for accessibility are not 7552 * necessarily direct children of the view, rather they are the first level of 7553 * descendants important for accessibility. 7554 * 7555 * @param children The list of children for accessibility. 7556 */ 7557 public void addChildrenForAccessibility(ArrayList<View> children) { 7558 7559 } 7560 7561 /** 7562 * Whether to regard this view for accessibility. A view is regarded for 7563 * accessibility if it is important for accessibility or the querying 7564 * accessibility service has explicitly requested that view not 7565 * important for accessibility are regarded. 7566 * 7567 * @return Whether to regard the view for accessibility. 7568 * 7569 * @hide 7570 */ 7571 public boolean includeForAccessibility() { 7572 if (mAttachInfo != null) { 7573 return (mAttachInfo.mAccessibilityFetchFlags 7574 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7575 || isImportantForAccessibility(); 7576 } 7577 return false; 7578 } 7579 7580 /** 7581 * Returns whether the View is considered actionable from 7582 * accessibility perspective. Such view are important for 7583 * accessibility. 7584 * 7585 * @return True if the view is actionable for accessibility. 7586 * 7587 * @hide 7588 */ 7589 public boolean isActionableForAccessibility() { 7590 return (isClickable() || isLongClickable() || isFocusable()); 7591 } 7592 7593 /** 7594 * Returns whether the View has registered callbacks which makes it 7595 * important for accessibility. 7596 * 7597 * @return True if the view is actionable for accessibility. 7598 */ 7599 private boolean hasListenersForAccessibility() { 7600 ListenerInfo info = getListenerInfo(); 7601 return mTouchDelegate != null || info.mOnKeyListener != null 7602 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7603 || info.mOnHoverListener != null || info.mOnDragListener != null; 7604 } 7605 7606 /** 7607 * Notifies that the accessibility state of this view changed. The change 7608 * is local to this view and does not represent structural changes such 7609 * as children and parent. For example, the view became focusable. The 7610 * notification is at at most once every 7611 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7612 * to avoid unnecessary load to the system. Also once a view has a pending 7613 * notification this method is a NOP until the notification has been sent. 7614 * 7615 * @hide 7616 */ 7617 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7618 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7619 return; 7620 } 7621 if (mSendViewStateChangedAccessibilityEvent == null) { 7622 mSendViewStateChangedAccessibilityEvent = 7623 new SendViewStateChangedAccessibilityEvent(); 7624 } 7625 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7626 } 7627 7628 /** 7629 * Notifies that the accessibility state of this view changed. The change 7630 * is *not* local to this view and does represent structural changes such 7631 * as children and parent. For example, the view size changed. The 7632 * notification is at at most once every 7633 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7634 * to avoid unnecessary load to the system. Also once a view has a pending 7635 * notifucation this method is a NOP until the notification has been sent. 7636 * 7637 * @hide 7638 */ 7639 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7640 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7641 return; 7642 } 7643 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7644 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7645 if (mParent != null) { 7646 try { 7647 mParent.notifySubtreeAccessibilityStateChanged( 7648 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7649 } catch (AbstractMethodError e) { 7650 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7651 " does not fully implement ViewParent", e); 7652 } 7653 } 7654 } 7655 } 7656 7657 /** 7658 * Reset the flag indicating the accessibility state of the subtree rooted 7659 * at this view changed. 7660 */ 7661 void resetSubtreeAccessibilityStateChanged() { 7662 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7663 } 7664 7665 /** 7666 * Performs the specified accessibility action on the view. For 7667 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7668 * <p> 7669 * If an {@link AccessibilityDelegate} has been specified via calling 7670 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7671 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7672 * is responsible for handling this call. 7673 * </p> 7674 * 7675 * @param action The action to perform. 7676 * @param arguments Optional action arguments. 7677 * @return Whether the action was performed. 7678 */ 7679 public boolean performAccessibilityAction(int action, Bundle arguments) { 7680 if (mAccessibilityDelegate != null) { 7681 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7682 } else { 7683 return performAccessibilityActionInternal(action, arguments); 7684 } 7685 } 7686 7687 /** 7688 * @see #performAccessibilityAction(int, Bundle) 7689 * 7690 * Note: Called from the default {@link AccessibilityDelegate}. 7691 */ 7692 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7693 switch (action) { 7694 case AccessibilityNodeInfo.ACTION_CLICK: { 7695 if (isClickable()) { 7696 performClick(); 7697 return true; 7698 } 7699 } break; 7700 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7701 if (isLongClickable()) { 7702 performLongClick(); 7703 return true; 7704 } 7705 } break; 7706 case AccessibilityNodeInfo.ACTION_FOCUS: { 7707 if (!hasFocus()) { 7708 // Get out of touch mode since accessibility 7709 // wants to move focus around. 7710 getViewRootImpl().ensureTouchMode(false); 7711 return requestFocus(); 7712 } 7713 } break; 7714 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7715 if (hasFocus()) { 7716 clearFocus(); 7717 return !isFocused(); 7718 } 7719 } break; 7720 case AccessibilityNodeInfo.ACTION_SELECT: { 7721 if (!isSelected()) { 7722 setSelected(true); 7723 return isSelected(); 7724 } 7725 } break; 7726 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7727 if (isSelected()) { 7728 setSelected(false); 7729 return !isSelected(); 7730 } 7731 } break; 7732 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7733 if (!isAccessibilityFocused()) { 7734 return requestAccessibilityFocus(); 7735 } 7736 } break; 7737 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7738 if (isAccessibilityFocused()) { 7739 clearAccessibilityFocus(); 7740 return true; 7741 } 7742 } break; 7743 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7744 if (arguments != null) { 7745 final int granularity = arguments.getInt( 7746 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7747 final boolean extendSelection = arguments.getBoolean( 7748 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7749 return traverseAtGranularity(granularity, true, extendSelection); 7750 } 7751 } break; 7752 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7753 if (arguments != null) { 7754 final int granularity = arguments.getInt( 7755 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7756 final boolean extendSelection = arguments.getBoolean( 7757 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7758 return traverseAtGranularity(granularity, false, extendSelection); 7759 } 7760 } break; 7761 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7762 CharSequence text = getIterableTextForAccessibility(); 7763 if (text == null) { 7764 return false; 7765 } 7766 final int start = (arguments != null) ? arguments.getInt( 7767 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7768 final int end = (arguments != null) ? arguments.getInt( 7769 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7770 // Only cursor position can be specified (selection length == 0) 7771 if ((getAccessibilitySelectionStart() != start 7772 || getAccessibilitySelectionEnd() != end) 7773 && (start == end)) { 7774 setAccessibilitySelection(start, end); 7775 notifyViewAccessibilityStateChangedIfNeeded( 7776 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7777 return true; 7778 } 7779 } break; 7780 } 7781 return false; 7782 } 7783 7784 private boolean traverseAtGranularity(int granularity, boolean forward, 7785 boolean extendSelection) { 7786 CharSequence text = getIterableTextForAccessibility(); 7787 if (text == null || text.length() == 0) { 7788 return false; 7789 } 7790 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7791 if (iterator == null) { 7792 return false; 7793 } 7794 int current = getAccessibilitySelectionEnd(); 7795 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7796 current = forward ? 0 : text.length(); 7797 } 7798 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7799 if (range == null) { 7800 return false; 7801 } 7802 final int segmentStart = range[0]; 7803 final int segmentEnd = range[1]; 7804 int selectionStart; 7805 int selectionEnd; 7806 if (extendSelection && isAccessibilitySelectionExtendable()) { 7807 selectionStart = getAccessibilitySelectionStart(); 7808 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7809 selectionStart = forward ? segmentStart : segmentEnd; 7810 } 7811 selectionEnd = forward ? segmentEnd : segmentStart; 7812 } else { 7813 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7814 } 7815 setAccessibilitySelection(selectionStart, selectionEnd); 7816 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7817 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7818 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7819 return true; 7820 } 7821 7822 /** 7823 * Gets the text reported for accessibility purposes. 7824 * 7825 * @return The accessibility text. 7826 * 7827 * @hide 7828 */ 7829 public CharSequence getIterableTextForAccessibility() { 7830 return getContentDescription(); 7831 } 7832 7833 /** 7834 * Gets whether accessibility selection can be extended. 7835 * 7836 * @return If selection is extensible. 7837 * 7838 * @hide 7839 */ 7840 public boolean isAccessibilitySelectionExtendable() { 7841 return false; 7842 } 7843 7844 /** 7845 * @hide 7846 */ 7847 public int getAccessibilitySelectionStart() { 7848 return mAccessibilityCursorPosition; 7849 } 7850 7851 /** 7852 * @hide 7853 */ 7854 public int getAccessibilitySelectionEnd() { 7855 return getAccessibilitySelectionStart(); 7856 } 7857 7858 /** 7859 * @hide 7860 */ 7861 public void setAccessibilitySelection(int start, int end) { 7862 if (start == end && end == mAccessibilityCursorPosition) { 7863 return; 7864 } 7865 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7866 mAccessibilityCursorPosition = start; 7867 } else { 7868 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7869 } 7870 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7871 } 7872 7873 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7874 int fromIndex, int toIndex) { 7875 if (mParent == null) { 7876 return; 7877 } 7878 AccessibilityEvent event = AccessibilityEvent.obtain( 7879 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7880 onInitializeAccessibilityEvent(event); 7881 onPopulateAccessibilityEvent(event); 7882 event.setFromIndex(fromIndex); 7883 event.setToIndex(toIndex); 7884 event.setAction(action); 7885 event.setMovementGranularity(granularity); 7886 mParent.requestSendAccessibilityEvent(this, event); 7887 } 7888 7889 /** 7890 * @hide 7891 */ 7892 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7893 switch (granularity) { 7894 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7895 CharSequence text = getIterableTextForAccessibility(); 7896 if (text != null && text.length() > 0) { 7897 CharacterTextSegmentIterator iterator = 7898 CharacterTextSegmentIterator.getInstance( 7899 mContext.getResources().getConfiguration().locale); 7900 iterator.initialize(text.toString()); 7901 return iterator; 7902 } 7903 } break; 7904 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7905 CharSequence text = getIterableTextForAccessibility(); 7906 if (text != null && text.length() > 0) { 7907 WordTextSegmentIterator iterator = 7908 WordTextSegmentIterator.getInstance( 7909 mContext.getResources().getConfiguration().locale); 7910 iterator.initialize(text.toString()); 7911 return iterator; 7912 } 7913 } break; 7914 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7915 CharSequence text = getIterableTextForAccessibility(); 7916 if (text != null && text.length() > 0) { 7917 ParagraphTextSegmentIterator iterator = 7918 ParagraphTextSegmentIterator.getInstance(); 7919 iterator.initialize(text.toString()); 7920 return iterator; 7921 } 7922 } break; 7923 } 7924 return null; 7925 } 7926 7927 /** 7928 * @hide 7929 */ 7930 public void dispatchStartTemporaryDetach() { 7931 onStartTemporaryDetach(); 7932 } 7933 7934 /** 7935 * This is called when a container is going to temporarily detach a child, with 7936 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7937 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7938 * {@link #onDetachedFromWindow()} when the container is done. 7939 */ 7940 public void onStartTemporaryDetach() { 7941 removeUnsetPressCallback(); 7942 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7943 } 7944 7945 /** 7946 * @hide 7947 */ 7948 public void dispatchFinishTemporaryDetach() { 7949 onFinishTemporaryDetach(); 7950 } 7951 7952 /** 7953 * Called after {@link #onStartTemporaryDetach} when the container is done 7954 * changing the view. 7955 */ 7956 public void onFinishTemporaryDetach() { 7957 } 7958 7959 /** 7960 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7961 * for this view's window. Returns null if the view is not currently attached 7962 * to the window. Normally you will not need to use this directly, but 7963 * just use the standard high-level event callbacks like 7964 * {@link #onKeyDown(int, KeyEvent)}. 7965 */ 7966 public KeyEvent.DispatcherState getKeyDispatcherState() { 7967 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7968 } 7969 7970 /** 7971 * Dispatch a key event before it is processed by any input method 7972 * associated with the view hierarchy. This can be used to intercept 7973 * key events in special situations before the IME consumes them; a 7974 * typical example would be handling the BACK key to update the application's 7975 * UI instead of allowing the IME to see it and close itself. 7976 * 7977 * @param event The key event to be dispatched. 7978 * @return True if the event was handled, false otherwise. 7979 */ 7980 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7981 return onKeyPreIme(event.getKeyCode(), event); 7982 } 7983 7984 /** 7985 * Dispatch a key event to the next view on the focus path. This path runs 7986 * from the top of the view tree down to the currently focused view. If this 7987 * view has focus, it will dispatch to itself. Otherwise it will dispatch 7988 * the next node down the focus path. This method also fires any key 7989 * listeners. 7990 * 7991 * @param event The key event to be dispatched. 7992 * @return True if the event was handled, false otherwise. 7993 */ 7994 public boolean dispatchKeyEvent(KeyEvent event) { 7995 if (mInputEventConsistencyVerifier != null) { 7996 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 7997 } 7998 7999 // Give any attached key listener a first crack at the event. 8000 //noinspection SimplifiableIfStatement 8001 ListenerInfo li = mListenerInfo; 8002 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8003 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8004 return true; 8005 } 8006 8007 if (event.dispatch(this, mAttachInfo != null 8008 ? mAttachInfo.mKeyDispatchState : null, this)) { 8009 return true; 8010 } 8011 8012 if (mInputEventConsistencyVerifier != null) { 8013 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8014 } 8015 return false; 8016 } 8017 8018 /** 8019 * Dispatches a key shortcut event. 8020 * 8021 * @param event The key event to be dispatched. 8022 * @return True if the event was handled by the view, false otherwise. 8023 */ 8024 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8025 return onKeyShortcut(event.getKeyCode(), event); 8026 } 8027 8028 /** 8029 * Pass the touch screen motion event down to the target view, or this 8030 * view if it is the target. 8031 * 8032 * @param event The motion event to be dispatched. 8033 * @return True if the event was handled by the view, false otherwise. 8034 */ 8035 public boolean dispatchTouchEvent(MotionEvent event) { 8036 boolean result = false; 8037 8038 if (mInputEventConsistencyVerifier != null) { 8039 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8040 } 8041 8042 final int actionMasked = event.getActionMasked(); 8043 if (actionMasked == MotionEvent.ACTION_DOWN) { 8044 // Defensive cleanup for new gesture 8045 stopNestedScroll(); 8046 } 8047 8048 if (onFilterTouchEventForSecurity(event)) { 8049 //noinspection SimplifiableIfStatement 8050 ListenerInfo li = mListenerInfo; 8051 if (li != null && li.mOnTouchListener != null 8052 && (mViewFlags & ENABLED_MASK) == ENABLED 8053 && li.mOnTouchListener.onTouch(this, event)) { 8054 result = true; 8055 } 8056 8057 if (!result && onTouchEvent(event)) { 8058 result = true; 8059 } 8060 } 8061 8062 if (!result && mInputEventConsistencyVerifier != null) { 8063 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8064 } 8065 8066 // Clean up after nested scrolls if this is the end of a gesture; 8067 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8068 // of the gesture. 8069 if (actionMasked == MotionEvent.ACTION_UP || 8070 actionMasked == MotionEvent.ACTION_CANCEL || 8071 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8072 stopNestedScroll(); 8073 } 8074 8075 return result; 8076 } 8077 8078 /** 8079 * Filter the touch event to apply security policies. 8080 * 8081 * @param event The motion event to be filtered. 8082 * @return True if the event should be dispatched, false if the event should be dropped. 8083 * 8084 * @see #getFilterTouchesWhenObscured 8085 */ 8086 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8087 //noinspection RedundantIfStatement 8088 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8089 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8090 // Window is obscured, drop this touch. 8091 return false; 8092 } 8093 return true; 8094 } 8095 8096 /** 8097 * Pass a trackball motion event down to the focused view. 8098 * 8099 * @param event The motion event to be dispatched. 8100 * @return True if the event was handled by the view, false otherwise. 8101 */ 8102 public boolean dispatchTrackballEvent(MotionEvent event) { 8103 if (mInputEventConsistencyVerifier != null) { 8104 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8105 } 8106 8107 return onTrackballEvent(event); 8108 } 8109 8110 /** 8111 * Dispatch a generic motion event. 8112 * <p> 8113 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8114 * are delivered to the view under the pointer. All other generic motion events are 8115 * delivered to the focused view. Hover events are handled specially and are delivered 8116 * to {@link #onHoverEvent(MotionEvent)}. 8117 * </p> 8118 * 8119 * @param event The motion event to be dispatched. 8120 * @return True if the event was handled by the view, false otherwise. 8121 */ 8122 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8123 if (mInputEventConsistencyVerifier != null) { 8124 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8125 } 8126 8127 final int source = event.getSource(); 8128 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8129 final int action = event.getAction(); 8130 if (action == MotionEvent.ACTION_HOVER_ENTER 8131 || action == MotionEvent.ACTION_HOVER_MOVE 8132 || action == MotionEvent.ACTION_HOVER_EXIT) { 8133 if (dispatchHoverEvent(event)) { 8134 return true; 8135 } 8136 } else if (dispatchGenericPointerEvent(event)) { 8137 return true; 8138 } 8139 } else if (dispatchGenericFocusedEvent(event)) { 8140 return true; 8141 } 8142 8143 if (dispatchGenericMotionEventInternal(event)) { 8144 return true; 8145 } 8146 8147 if (mInputEventConsistencyVerifier != null) { 8148 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8149 } 8150 return false; 8151 } 8152 8153 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8154 //noinspection SimplifiableIfStatement 8155 ListenerInfo li = mListenerInfo; 8156 if (li != null && li.mOnGenericMotionListener != null 8157 && (mViewFlags & ENABLED_MASK) == ENABLED 8158 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8159 return true; 8160 } 8161 8162 if (onGenericMotionEvent(event)) { 8163 return true; 8164 } 8165 8166 if (mInputEventConsistencyVerifier != null) { 8167 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8168 } 8169 return false; 8170 } 8171 8172 /** 8173 * Dispatch a hover event. 8174 * <p> 8175 * Do not call this method directly. 8176 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8177 * </p> 8178 * 8179 * @param event The motion event to be dispatched. 8180 * @return True if the event was handled by the view, false otherwise. 8181 */ 8182 protected boolean dispatchHoverEvent(MotionEvent event) { 8183 ListenerInfo li = mListenerInfo; 8184 //noinspection SimplifiableIfStatement 8185 if (li != null && li.mOnHoverListener != null 8186 && (mViewFlags & ENABLED_MASK) == ENABLED 8187 && li.mOnHoverListener.onHover(this, event)) { 8188 return true; 8189 } 8190 8191 return onHoverEvent(event); 8192 } 8193 8194 /** 8195 * Returns true if the view has a child to which it has recently sent 8196 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8197 * it does not have a hovered child, then it must be the innermost hovered view. 8198 * @hide 8199 */ 8200 protected boolean hasHoveredChild() { 8201 return false; 8202 } 8203 8204 /** 8205 * Dispatch a generic motion event to the view under the first pointer. 8206 * <p> 8207 * Do not call this method directly. 8208 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8209 * </p> 8210 * 8211 * @param event The motion event to be dispatched. 8212 * @return True if the event was handled by the view, false otherwise. 8213 */ 8214 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8215 return false; 8216 } 8217 8218 /** 8219 * Dispatch a generic motion event to the currently focused view. 8220 * <p> 8221 * Do not call this method directly. 8222 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8223 * </p> 8224 * 8225 * @param event The motion event to be dispatched. 8226 * @return True if the event was handled by the view, false otherwise. 8227 */ 8228 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8229 return false; 8230 } 8231 8232 /** 8233 * Dispatch a pointer event. 8234 * <p> 8235 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8236 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8237 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8238 * and should not be expected to handle other pointing device features. 8239 * </p> 8240 * 8241 * @param event The motion event to be dispatched. 8242 * @return True if the event was handled by the view, false otherwise. 8243 * @hide 8244 */ 8245 public final boolean dispatchPointerEvent(MotionEvent event) { 8246 if (event.isTouchEvent()) { 8247 return dispatchTouchEvent(event); 8248 } else { 8249 return dispatchGenericMotionEvent(event); 8250 } 8251 } 8252 8253 /** 8254 * Called when the window containing this view gains or loses window focus. 8255 * ViewGroups should override to route to their children. 8256 * 8257 * @param hasFocus True if the window containing this view now has focus, 8258 * false otherwise. 8259 */ 8260 public void dispatchWindowFocusChanged(boolean hasFocus) { 8261 onWindowFocusChanged(hasFocus); 8262 } 8263 8264 /** 8265 * Called when the window containing this view gains or loses focus. Note 8266 * that this is separate from view focus: to receive key events, both 8267 * your view and its window must have focus. If a window is displayed 8268 * on top of yours that takes input focus, then your own window will lose 8269 * focus but the view focus will remain unchanged. 8270 * 8271 * @param hasWindowFocus True if the window containing this view now has 8272 * focus, false otherwise. 8273 */ 8274 public void onWindowFocusChanged(boolean hasWindowFocus) { 8275 InputMethodManager imm = InputMethodManager.peekInstance(); 8276 if (!hasWindowFocus) { 8277 if (isPressed()) { 8278 setPressed(false); 8279 } 8280 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8281 imm.focusOut(this); 8282 } 8283 removeLongPressCallback(); 8284 removeTapCallback(); 8285 onFocusLost(); 8286 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8287 imm.focusIn(this); 8288 } 8289 refreshDrawableState(); 8290 } 8291 8292 /** 8293 * Returns true if this view is in a window that currently has window focus. 8294 * Note that this is not the same as the view itself having focus. 8295 * 8296 * @return True if this view is in a window that currently has window focus. 8297 */ 8298 public boolean hasWindowFocus() { 8299 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8300 } 8301 8302 /** 8303 * Dispatch a view visibility change down the view hierarchy. 8304 * ViewGroups should override to route to their children. 8305 * @param changedView The view whose visibility changed. Could be 'this' or 8306 * an ancestor view. 8307 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8308 * {@link #INVISIBLE} or {@link #GONE}. 8309 */ 8310 protected void dispatchVisibilityChanged(@NonNull View changedView, 8311 @Visibility int visibility) { 8312 onVisibilityChanged(changedView, visibility); 8313 } 8314 8315 /** 8316 * Called when the visibility of the view or an ancestor of the view is changed. 8317 * @param changedView The view whose visibility changed. Could be 'this' or 8318 * an ancestor view. 8319 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8320 * {@link #INVISIBLE} or {@link #GONE}. 8321 */ 8322 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8323 if (visibility == VISIBLE) { 8324 if (mAttachInfo != null) { 8325 initialAwakenScrollBars(); 8326 } else { 8327 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8328 } 8329 } 8330 } 8331 8332 /** 8333 * Dispatch a hint about whether this view is displayed. For instance, when 8334 * a View moves out of the screen, it might receives a display hint indicating 8335 * the view is not displayed. Applications should not <em>rely</em> on this hint 8336 * as there is no guarantee that they will receive one. 8337 * 8338 * @param hint A hint about whether or not this view is displayed: 8339 * {@link #VISIBLE} or {@link #INVISIBLE}. 8340 */ 8341 public void dispatchDisplayHint(@Visibility int hint) { 8342 onDisplayHint(hint); 8343 } 8344 8345 /** 8346 * Gives this view a hint about whether is displayed or not. For instance, when 8347 * a View moves out of the screen, it might receives a display hint indicating 8348 * the view is not displayed. Applications should not <em>rely</em> on this hint 8349 * as there is no guarantee that they will receive one. 8350 * 8351 * @param hint A hint about whether or not this view is displayed: 8352 * {@link #VISIBLE} or {@link #INVISIBLE}. 8353 */ 8354 protected void onDisplayHint(@Visibility int hint) { 8355 } 8356 8357 /** 8358 * Dispatch a window visibility change down the view hierarchy. 8359 * ViewGroups should override to route to their children. 8360 * 8361 * @param visibility The new visibility of the window. 8362 * 8363 * @see #onWindowVisibilityChanged(int) 8364 */ 8365 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8366 onWindowVisibilityChanged(visibility); 8367 } 8368 8369 /** 8370 * Called when the window containing has change its visibility 8371 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8372 * that this tells you whether or not your window is being made visible 8373 * to the window manager; this does <em>not</em> tell you whether or not 8374 * your window is obscured by other windows on the screen, even if it 8375 * is itself visible. 8376 * 8377 * @param visibility The new visibility of the window. 8378 */ 8379 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8380 if (visibility == VISIBLE) { 8381 initialAwakenScrollBars(); 8382 } 8383 } 8384 8385 /** 8386 * Returns the current visibility of the window this view is attached to 8387 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8388 * 8389 * @return Returns the current visibility of the view's window. 8390 */ 8391 @Visibility 8392 public int getWindowVisibility() { 8393 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8394 } 8395 8396 /** 8397 * Retrieve the overall visible display size in which the window this view is 8398 * attached to has been positioned in. This takes into account screen 8399 * decorations above the window, for both cases where the window itself 8400 * is being position inside of them or the window is being placed under 8401 * then and covered insets are used for the window to position its content 8402 * inside. In effect, this tells you the available area where content can 8403 * be placed and remain visible to users. 8404 * 8405 * <p>This function requires an IPC back to the window manager to retrieve 8406 * the requested information, so should not be used in performance critical 8407 * code like drawing. 8408 * 8409 * @param outRect Filled in with the visible display frame. If the view 8410 * is not attached to a window, this is simply the raw display size. 8411 */ 8412 public void getWindowVisibleDisplayFrame(Rect outRect) { 8413 if (mAttachInfo != null) { 8414 try { 8415 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8416 } catch (RemoteException e) { 8417 return; 8418 } 8419 // XXX This is really broken, and probably all needs to be done 8420 // in the window manager, and we need to know more about whether 8421 // we want the area behind or in front of the IME. 8422 final Rect insets = mAttachInfo.mVisibleInsets; 8423 outRect.left += insets.left; 8424 outRect.top += insets.top; 8425 outRect.right -= insets.right; 8426 outRect.bottom -= insets.bottom; 8427 return; 8428 } 8429 // The view is not attached to a display so we don't have a context. 8430 // Make a best guess about the display size. 8431 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8432 d.getRectSize(outRect); 8433 } 8434 8435 /** 8436 * Dispatch a notification about a resource configuration change down 8437 * the view hierarchy. 8438 * ViewGroups should override to route to their children. 8439 * 8440 * @param newConfig The new resource configuration. 8441 * 8442 * @see #onConfigurationChanged(android.content.res.Configuration) 8443 */ 8444 public void dispatchConfigurationChanged(Configuration newConfig) { 8445 onConfigurationChanged(newConfig); 8446 } 8447 8448 /** 8449 * Called when the current configuration of the resources being used 8450 * by the application have changed. You can use this to decide when 8451 * to reload resources that can changed based on orientation and other 8452 * configuration characterstics. You only need to use this if you are 8453 * not relying on the normal {@link android.app.Activity} mechanism of 8454 * recreating the activity instance upon a configuration change. 8455 * 8456 * @param newConfig The new resource configuration. 8457 */ 8458 protected void onConfigurationChanged(Configuration newConfig) { 8459 } 8460 8461 /** 8462 * Private function to aggregate all per-view attributes in to the view 8463 * root. 8464 */ 8465 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8466 performCollectViewAttributes(attachInfo, visibility); 8467 } 8468 8469 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8470 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8471 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8472 attachInfo.mKeepScreenOn = true; 8473 } 8474 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8475 ListenerInfo li = mListenerInfo; 8476 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8477 attachInfo.mHasSystemUiListeners = true; 8478 } 8479 } 8480 } 8481 8482 void needGlobalAttributesUpdate(boolean force) { 8483 final AttachInfo ai = mAttachInfo; 8484 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8485 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8486 || ai.mHasSystemUiListeners) { 8487 ai.mRecomputeGlobalAttributes = true; 8488 } 8489 } 8490 } 8491 8492 /** 8493 * Returns whether the device is currently in touch mode. Touch mode is entered 8494 * once the user begins interacting with the device by touch, and affects various 8495 * things like whether focus is always visible to the user. 8496 * 8497 * @return Whether the device is in touch mode. 8498 */ 8499 @ViewDebug.ExportedProperty 8500 public boolean isInTouchMode() { 8501 if (mAttachInfo != null) { 8502 return mAttachInfo.mInTouchMode; 8503 } else { 8504 return ViewRootImpl.isInTouchMode(); 8505 } 8506 } 8507 8508 /** 8509 * Returns the context the view is running in, through which it can 8510 * access the current theme, resources, etc. 8511 * 8512 * @return The view's Context. 8513 */ 8514 @ViewDebug.CapturedViewProperty 8515 public final Context getContext() { 8516 return mContext; 8517 } 8518 8519 /** 8520 * Handle a key event before it is processed by any input method 8521 * associated with the view hierarchy. This can be used to intercept 8522 * key events in special situations before the IME consumes them; a 8523 * typical example would be handling the BACK key to update the application's 8524 * UI instead of allowing the IME to see it and close itself. 8525 * 8526 * @param keyCode The value in event.getKeyCode(). 8527 * @param event Description of the key event. 8528 * @return If you handled the event, return true. If you want to allow the 8529 * event to be handled by the next receiver, return false. 8530 */ 8531 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8532 return false; 8533 } 8534 8535 /** 8536 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8537 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8538 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8539 * is released, if the view is enabled and clickable. 8540 * 8541 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8542 * although some may elect to do so in some situations. Do not rely on this to 8543 * catch software key presses. 8544 * 8545 * @param keyCode A key code that represents the button pressed, from 8546 * {@link android.view.KeyEvent}. 8547 * @param event The KeyEvent object that defines the button action. 8548 */ 8549 public boolean onKeyDown(int keyCode, KeyEvent event) { 8550 boolean result = false; 8551 8552 if (KeyEvent.isConfirmKey(keyCode)) { 8553 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8554 return true; 8555 } 8556 // Long clickable items don't necessarily have to be clickable 8557 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8558 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8559 (event.getRepeatCount() == 0)) { 8560 setPressed(true); 8561 checkForLongClick(0); 8562 return true; 8563 } 8564 } 8565 return result; 8566 } 8567 8568 /** 8569 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8570 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8571 * the event). 8572 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8573 * although some may elect to do so in some situations. Do not rely on this to 8574 * catch software key presses. 8575 */ 8576 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8577 return false; 8578 } 8579 8580 /** 8581 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8582 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8583 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8584 * {@link KeyEvent#KEYCODE_ENTER} is released. 8585 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8586 * although some may elect to do so in some situations. Do not rely on this to 8587 * catch software key presses. 8588 * 8589 * @param keyCode A key code that represents the button pressed, from 8590 * {@link android.view.KeyEvent}. 8591 * @param event The KeyEvent object that defines the button action. 8592 */ 8593 public boolean onKeyUp(int keyCode, KeyEvent event) { 8594 if (KeyEvent.isConfirmKey(keyCode)) { 8595 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8596 return true; 8597 } 8598 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8599 setPressed(false); 8600 8601 if (!mHasPerformedLongPress) { 8602 // This is a tap, so remove the longpress check 8603 removeLongPressCallback(); 8604 return performClick(); 8605 } 8606 } 8607 } 8608 return false; 8609 } 8610 8611 /** 8612 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8613 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8614 * the event). 8615 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8616 * although some may elect to do so in some situations. Do not rely on this to 8617 * catch software key presses. 8618 * 8619 * @param keyCode A key code that represents the button pressed, from 8620 * {@link android.view.KeyEvent}. 8621 * @param repeatCount The number of times the action was made. 8622 * @param event The KeyEvent object that defines the button action. 8623 */ 8624 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8625 return false; 8626 } 8627 8628 /** 8629 * Called on the focused view when a key shortcut event is not handled. 8630 * Override this method to implement local key shortcuts for the View. 8631 * Key shortcuts can also be implemented by setting the 8632 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8633 * 8634 * @param keyCode The value in event.getKeyCode(). 8635 * @param event Description of the key event. 8636 * @return If you handled the event, return true. If you want to allow the 8637 * event to be handled by the next receiver, return false. 8638 */ 8639 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8640 return false; 8641 } 8642 8643 /** 8644 * Check whether the called view is a text editor, in which case it 8645 * would make sense to automatically display a soft input window for 8646 * it. Subclasses should override this if they implement 8647 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8648 * a call on that method would return a non-null InputConnection, and 8649 * they are really a first-class editor that the user would normally 8650 * start typing on when the go into a window containing your view. 8651 * 8652 * <p>The default implementation always returns false. This does 8653 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8654 * will not be called or the user can not otherwise perform edits on your 8655 * view; it is just a hint to the system that this is not the primary 8656 * purpose of this view. 8657 * 8658 * @return Returns true if this view is a text editor, else false. 8659 */ 8660 public boolean onCheckIsTextEditor() { 8661 return false; 8662 } 8663 8664 /** 8665 * Create a new InputConnection for an InputMethod to interact 8666 * with the view. The default implementation returns null, since it doesn't 8667 * support input methods. You can override this to implement such support. 8668 * This is only needed for views that take focus and text input. 8669 * 8670 * <p>When implementing this, you probably also want to implement 8671 * {@link #onCheckIsTextEditor()} to indicate you will return a 8672 * non-null InputConnection.</p> 8673 * 8674 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 8675 * object correctly and in its entirety, so that the connected IME can rely 8676 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 8677 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 8678 * must be filled in with the correct cursor position for IMEs to work correctly 8679 * with your application.</p> 8680 * 8681 * @param outAttrs Fill in with attribute information about the connection. 8682 */ 8683 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8684 return null; 8685 } 8686 8687 /** 8688 * Called by the {@link android.view.inputmethod.InputMethodManager} 8689 * when a view who is not the current 8690 * input connection target is trying to make a call on the manager. The 8691 * default implementation returns false; you can override this to return 8692 * true for certain views if you are performing InputConnection proxying 8693 * to them. 8694 * @param view The View that is making the InputMethodManager call. 8695 * @return Return true to allow the call, false to reject. 8696 */ 8697 public boolean checkInputConnectionProxy(View view) { 8698 return false; 8699 } 8700 8701 /** 8702 * Show the context menu for this view. It is not safe to hold on to the 8703 * menu after returning from this method. 8704 * 8705 * You should normally not overload this method. Overload 8706 * {@link #onCreateContextMenu(ContextMenu)} or define an 8707 * {@link OnCreateContextMenuListener} to add items to the context menu. 8708 * 8709 * @param menu The context menu to populate 8710 */ 8711 public void createContextMenu(ContextMenu menu) { 8712 ContextMenuInfo menuInfo = getContextMenuInfo(); 8713 8714 // Sets the current menu info so all items added to menu will have 8715 // my extra info set. 8716 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8717 8718 onCreateContextMenu(menu); 8719 ListenerInfo li = mListenerInfo; 8720 if (li != null && li.mOnCreateContextMenuListener != null) { 8721 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8722 } 8723 8724 // Clear the extra information so subsequent items that aren't mine don't 8725 // have my extra info. 8726 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8727 8728 if (mParent != null) { 8729 mParent.createContextMenu(menu); 8730 } 8731 } 8732 8733 /** 8734 * Views should implement this if they have extra information to associate 8735 * with the context menu. The return result is supplied as a parameter to 8736 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8737 * callback. 8738 * 8739 * @return Extra information about the item for which the context menu 8740 * should be shown. This information will vary across different 8741 * subclasses of View. 8742 */ 8743 protected ContextMenuInfo getContextMenuInfo() { 8744 return null; 8745 } 8746 8747 /** 8748 * Views should implement this if the view itself is going to add items to 8749 * the context menu. 8750 * 8751 * @param menu the context menu to populate 8752 */ 8753 protected void onCreateContextMenu(ContextMenu menu) { 8754 } 8755 8756 /** 8757 * Implement this method to handle trackball motion events. The 8758 * <em>relative</em> movement of the trackball since the last event 8759 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8760 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8761 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8762 * they will often be fractional values, representing the more fine-grained 8763 * movement information available from a trackball). 8764 * 8765 * @param event The motion event. 8766 * @return True if the event was handled, false otherwise. 8767 */ 8768 public boolean onTrackballEvent(MotionEvent event) { 8769 return false; 8770 } 8771 8772 /** 8773 * Implement this method to handle generic motion events. 8774 * <p> 8775 * Generic motion events describe joystick movements, mouse hovers, track pad 8776 * touches, scroll wheel movements and other input events. The 8777 * {@link MotionEvent#getSource() source} of the motion event specifies 8778 * the class of input that was received. Implementations of this method 8779 * must examine the bits in the source before processing the event. 8780 * The following code example shows how this is done. 8781 * </p><p> 8782 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8783 * are delivered to the view under the pointer. All other generic motion events are 8784 * delivered to the focused view. 8785 * </p> 8786 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8787 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8788 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8789 * // process the joystick movement... 8790 * return true; 8791 * } 8792 * } 8793 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8794 * switch (event.getAction()) { 8795 * case MotionEvent.ACTION_HOVER_MOVE: 8796 * // process the mouse hover movement... 8797 * return true; 8798 * case MotionEvent.ACTION_SCROLL: 8799 * // process the scroll wheel movement... 8800 * return true; 8801 * } 8802 * } 8803 * return super.onGenericMotionEvent(event); 8804 * }</pre> 8805 * 8806 * @param event The generic motion event being processed. 8807 * @return True if the event was handled, false otherwise. 8808 */ 8809 public boolean onGenericMotionEvent(MotionEvent event) { 8810 return false; 8811 } 8812 8813 /** 8814 * Implement this method to handle hover events. 8815 * <p> 8816 * This method is called whenever a pointer is hovering into, over, or out of the 8817 * bounds of a view and the view is not currently being touched. 8818 * Hover events are represented as pointer events with action 8819 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8820 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8821 * </p> 8822 * <ul> 8823 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8824 * when the pointer enters the bounds of the view.</li> 8825 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8826 * when the pointer has already entered the bounds of the view and has moved.</li> 8827 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8828 * when the pointer has exited the bounds of the view or when the pointer is 8829 * about to go down due to a button click, tap, or similar user action that 8830 * causes the view to be touched.</li> 8831 * </ul> 8832 * <p> 8833 * The view should implement this method to return true to indicate that it is 8834 * handling the hover event, such as by changing its drawable state. 8835 * </p><p> 8836 * The default implementation calls {@link #setHovered} to update the hovered state 8837 * of the view when a hover enter or hover exit event is received, if the view 8838 * is enabled and is clickable. The default implementation also sends hover 8839 * accessibility events. 8840 * </p> 8841 * 8842 * @param event The motion event that describes the hover. 8843 * @return True if the view handled the hover event. 8844 * 8845 * @see #isHovered 8846 * @see #setHovered 8847 * @see #onHoverChanged 8848 */ 8849 public boolean onHoverEvent(MotionEvent event) { 8850 // The root view may receive hover (or touch) events that are outside the bounds of 8851 // the window. This code ensures that we only send accessibility events for 8852 // hovers that are actually within the bounds of the root view. 8853 final int action = event.getActionMasked(); 8854 if (!mSendingHoverAccessibilityEvents) { 8855 if ((action == MotionEvent.ACTION_HOVER_ENTER 8856 || action == MotionEvent.ACTION_HOVER_MOVE) 8857 && !hasHoveredChild() 8858 && pointInView(event.getX(), event.getY())) { 8859 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8860 mSendingHoverAccessibilityEvents = true; 8861 } 8862 } else { 8863 if (action == MotionEvent.ACTION_HOVER_EXIT 8864 || (action == MotionEvent.ACTION_MOVE 8865 && !pointInView(event.getX(), event.getY()))) { 8866 mSendingHoverAccessibilityEvents = false; 8867 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8868 } 8869 } 8870 8871 if (isHoverable()) { 8872 switch (action) { 8873 case MotionEvent.ACTION_HOVER_ENTER: 8874 setHovered(true); 8875 break; 8876 case MotionEvent.ACTION_HOVER_EXIT: 8877 setHovered(false); 8878 break; 8879 } 8880 8881 // Dispatch the event to onGenericMotionEvent before returning true. 8882 // This is to provide compatibility with existing applications that 8883 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8884 // break because of the new default handling for hoverable views 8885 // in onHoverEvent. 8886 // Note that onGenericMotionEvent will be called by default when 8887 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8888 dispatchGenericMotionEventInternal(event); 8889 // The event was already handled by calling setHovered(), so always 8890 // return true. 8891 return true; 8892 } 8893 8894 return false; 8895 } 8896 8897 /** 8898 * Returns true if the view should handle {@link #onHoverEvent} 8899 * by calling {@link #setHovered} to change its hovered state. 8900 * 8901 * @return True if the view is hoverable. 8902 */ 8903 private boolean isHoverable() { 8904 final int viewFlags = mViewFlags; 8905 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8906 return false; 8907 } 8908 8909 return (viewFlags & CLICKABLE) == CLICKABLE 8910 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8911 } 8912 8913 /** 8914 * Returns true if the view is currently hovered. 8915 * 8916 * @return True if the view is currently hovered. 8917 * 8918 * @see #setHovered 8919 * @see #onHoverChanged 8920 */ 8921 @ViewDebug.ExportedProperty 8922 public boolean isHovered() { 8923 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8924 } 8925 8926 /** 8927 * Sets whether the view is currently hovered. 8928 * <p> 8929 * Calling this method also changes the drawable state of the view. This 8930 * enables the view to react to hover by using different drawable resources 8931 * to change its appearance. 8932 * </p><p> 8933 * The {@link #onHoverChanged} method is called when the hovered state changes. 8934 * </p> 8935 * 8936 * @param hovered True if the view is hovered. 8937 * 8938 * @see #isHovered 8939 * @see #onHoverChanged 8940 */ 8941 public void setHovered(boolean hovered) { 8942 if (hovered) { 8943 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8944 mPrivateFlags |= PFLAG_HOVERED; 8945 refreshDrawableState(); 8946 onHoverChanged(true); 8947 } 8948 } else { 8949 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8950 mPrivateFlags &= ~PFLAG_HOVERED; 8951 refreshDrawableState(); 8952 onHoverChanged(false); 8953 } 8954 } 8955 } 8956 8957 /** 8958 * Implement this method to handle hover state changes. 8959 * <p> 8960 * This method is called whenever the hover state changes as a result of a 8961 * call to {@link #setHovered}. 8962 * </p> 8963 * 8964 * @param hovered The current hover state, as returned by {@link #isHovered}. 8965 * 8966 * @see #isHovered 8967 * @see #setHovered 8968 */ 8969 public void onHoverChanged(boolean hovered) { 8970 } 8971 8972 /** 8973 * Implement this method to handle touch screen motion events. 8974 * <p> 8975 * If this method is used to detect click actions, it is recommended that 8976 * the actions be performed by implementing and calling 8977 * {@link #performClick()}. This will ensure consistent system behavior, 8978 * including: 8979 * <ul> 8980 * <li>obeying click sound preferences 8981 * <li>dispatching OnClickListener calls 8982 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 8983 * accessibility features are enabled 8984 * </ul> 8985 * 8986 * @param event The motion event. 8987 * @return True if the event was handled, false otherwise. 8988 */ 8989 public boolean onTouchEvent(MotionEvent event) { 8990 final float x = event.getX(); 8991 final float y = event.getY(); 8992 final int viewFlags = mViewFlags; 8993 8994 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8995 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 8996 clearHotspot(R.attr.state_pressed); 8997 setPressed(false); 8998 } 8999 // A disabled view that is clickable still consumes the touch 9000 // events, it just doesn't respond to them. 9001 return (((viewFlags & CLICKABLE) == CLICKABLE || 9002 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9003 } 9004 9005 if (mTouchDelegate != null) { 9006 if (mTouchDelegate.onTouchEvent(event)) { 9007 return true; 9008 } 9009 } 9010 9011 if (((viewFlags & CLICKABLE) == CLICKABLE || 9012 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9013 switch (event.getAction()) { 9014 case MotionEvent.ACTION_UP: 9015 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9016 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9017 // take focus if we don't have it already and we should in 9018 // touch mode. 9019 boolean focusTaken = false; 9020 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9021 focusTaken = requestFocus(); 9022 } 9023 9024 if (prepressed) { 9025 // The button is being released before we actually 9026 // showed it as pressed. Make it show the pressed 9027 // state now (before scheduling the click) to ensure 9028 // the user sees it. 9029 setHotspot(R.attr.state_pressed, x, y); 9030 setPressed(true); 9031 } 9032 9033 if (!mHasPerformedLongPress) { 9034 // This is a tap, so remove the longpress check 9035 removeLongPressCallback(); 9036 9037 // Only perform take click actions if we were in the pressed state 9038 if (!focusTaken) { 9039 // Use a Runnable and post this rather than calling 9040 // performClick directly. This lets other visual state 9041 // of the view update before click actions start. 9042 if (mPerformClick == null) { 9043 mPerformClick = new PerformClick(); 9044 } 9045 if (!post(mPerformClick)) { 9046 performClick(); 9047 } 9048 } 9049 } 9050 9051 if (mUnsetPressedState == null) { 9052 mUnsetPressedState = new UnsetPressedState(); 9053 } 9054 9055 if (prepressed) { 9056 postDelayed(mUnsetPressedState, 9057 ViewConfiguration.getPressedStateDuration()); 9058 } else if (!post(mUnsetPressedState)) { 9059 // If the post failed, unpress right now 9060 mUnsetPressedState.run(); 9061 } 9062 9063 removeTapCallback(); 9064 } else { 9065 clearHotspot(R.attr.state_pressed); 9066 } 9067 break; 9068 9069 case MotionEvent.ACTION_DOWN: 9070 mHasPerformedLongPress = false; 9071 9072 if (performButtonActionOnTouchDown(event)) { 9073 break; 9074 } 9075 9076 // Walk up the hierarchy to determine if we're inside a scrolling container. 9077 boolean isInScrollingContainer = isInScrollingContainer(); 9078 9079 // For views inside a scrolling container, delay the pressed feedback for 9080 // a short period in case this is a scroll. 9081 if (isInScrollingContainer) { 9082 mPrivateFlags |= PFLAG_PREPRESSED; 9083 if (mPendingCheckForTap == null) { 9084 mPendingCheckForTap = new CheckForTap(); 9085 } 9086 mPendingCheckForTap.x = event.getX(); 9087 mPendingCheckForTap.y = event.getY(); 9088 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9089 } else { 9090 // Not inside a scrolling container, so show the feedback right away 9091 setHotspot(R.attr.state_pressed, x, y); 9092 setPressed(true); 9093 checkForLongClick(0); 9094 } 9095 break; 9096 9097 case MotionEvent.ACTION_CANCEL: 9098 clearHotspot(R.attr.state_pressed); 9099 setPressed(false); 9100 removeTapCallback(); 9101 removeLongPressCallback(); 9102 break; 9103 9104 case MotionEvent.ACTION_MOVE: 9105 setHotspot(R.attr.state_pressed, x, y); 9106 9107 // Be lenient about moving outside of buttons 9108 if (!pointInView(x, y, mTouchSlop)) { 9109 // Outside button 9110 removeTapCallback(); 9111 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9112 // Remove any future long press/tap checks 9113 removeLongPressCallback(); 9114 9115 setPressed(false); 9116 } 9117 } 9118 break; 9119 } 9120 9121 return true; 9122 } 9123 9124 return false; 9125 } 9126 9127 private void setHotspot(int id, float x, float y) { 9128 final Drawable bg = mBackground; 9129 if (bg != null && bg.supportsHotspots()) { 9130 bg.setHotspot(id, x, y); 9131 } 9132 } 9133 9134 private void clearHotspot(int id) { 9135 final Drawable bg = mBackground; 9136 if (bg != null && bg.supportsHotspots()) { 9137 bg.removeHotspot(id); 9138 } 9139 } 9140 9141 /** 9142 * @hide 9143 */ 9144 public boolean isInScrollingContainer() { 9145 ViewParent p = getParent(); 9146 while (p != null && p instanceof ViewGroup) { 9147 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9148 return true; 9149 } 9150 p = p.getParent(); 9151 } 9152 return false; 9153 } 9154 9155 /** 9156 * Remove the longpress detection timer. 9157 */ 9158 private void removeLongPressCallback() { 9159 if (mPendingCheckForLongPress != null) { 9160 removeCallbacks(mPendingCheckForLongPress); 9161 } 9162 } 9163 9164 /** 9165 * Remove the pending click action 9166 */ 9167 private void removePerformClickCallback() { 9168 if (mPerformClick != null) { 9169 removeCallbacks(mPerformClick); 9170 } 9171 } 9172 9173 /** 9174 * Remove the prepress detection timer. 9175 */ 9176 private void removeUnsetPressCallback() { 9177 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9178 clearHotspot(R.attr.state_pressed); 9179 setPressed(false); 9180 removeCallbacks(mUnsetPressedState); 9181 } 9182 } 9183 9184 /** 9185 * Remove the tap detection timer. 9186 */ 9187 private void removeTapCallback() { 9188 if (mPendingCheckForTap != null) { 9189 mPrivateFlags &= ~PFLAG_PREPRESSED; 9190 removeCallbacks(mPendingCheckForTap); 9191 } 9192 } 9193 9194 /** 9195 * Cancels a pending long press. Your subclass can use this if you 9196 * want the context menu to come up if the user presses and holds 9197 * at the same place, but you don't want it to come up if they press 9198 * and then move around enough to cause scrolling. 9199 */ 9200 public void cancelLongPress() { 9201 removeLongPressCallback(); 9202 9203 /* 9204 * The prepressed state handled by the tap callback is a display 9205 * construct, but the tap callback will post a long press callback 9206 * less its own timeout. Remove it here. 9207 */ 9208 removeTapCallback(); 9209 } 9210 9211 /** 9212 * Remove the pending callback for sending a 9213 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9214 */ 9215 private void removeSendViewScrolledAccessibilityEventCallback() { 9216 if (mSendViewScrolledAccessibilityEvent != null) { 9217 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9218 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9219 } 9220 } 9221 9222 /** 9223 * Sets the TouchDelegate for this View. 9224 */ 9225 public void setTouchDelegate(TouchDelegate delegate) { 9226 mTouchDelegate = delegate; 9227 } 9228 9229 /** 9230 * Gets the TouchDelegate for this View. 9231 */ 9232 public TouchDelegate getTouchDelegate() { 9233 return mTouchDelegate; 9234 } 9235 9236 /** 9237 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 9238 * 9239 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 9240 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 9241 * available. This method should only be called for touch events. 9242 * 9243 * <p class="note">This api is not intended for most applications. Buffered dispatch 9244 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 9245 * streams will not improve your input latency. Side effects include: increased latency, 9246 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 9247 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 9248 * you.</p> 9249 */ 9250 public final void requestUnbufferedDispatch(MotionEvent event) { 9251 final int action = event.getAction(); 9252 if (mAttachInfo == null 9253 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 9254 || !event.isTouchEvent()) { 9255 return; 9256 } 9257 mAttachInfo.mUnbufferedDispatchRequested = true; 9258 } 9259 9260 /** 9261 * Set flags controlling behavior of this view. 9262 * 9263 * @param flags Constant indicating the value which should be set 9264 * @param mask Constant indicating the bit range that should be changed 9265 */ 9266 void setFlags(int flags, int mask) { 9267 final boolean accessibilityEnabled = 9268 AccessibilityManager.getInstance(mContext).isEnabled(); 9269 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9270 9271 int old = mViewFlags; 9272 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9273 9274 int changed = mViewFlags ^ old; 9275 if (changed == 0) { 9276 return; 9277 } 9278 int privateFlags = mPrivateFlags; 9279 9280 /* Check if the FOCUSABLE bit has changed */ 9281 if (((changed & FOCUSABLE_MASK) != 0) && 9282 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9283 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9284 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9285 /* Give up focus if we are no longer focusable */ 9286 clearFocus(); 9287 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9288 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9289 /* 9290 * Tell the view system that we are now available to take focus 9291 * if no one else already has it. 9292 */ 9293 if (mParent != null) mParent.focusableViewAvailable(this); 9294 } 9295 } 9296 9297 final int newVisibility = flags & VISIBILITY_MASK; 9298 if (newVisibility == VISIBLE) { 9299 if ((changed & VISIBILITY_MASK) != 0) { 9300 /* 9301 * If this view is becoming visible, invalidate it in case it changed while 9302 * it was not visible. Marking it drawn ensures that the invalidation will 9303 * go through. 9304 */ 9305 mPrivateFlags |= PFLAG_DRAWN; 9306 invalidate(true); 9307 9308 needGlobalAttributesUpdate(true); 9309 9310 // a view becoming visible is worth notifying the parent 9311 // about in case nothing has focus. even if this specific view 9312 // isn't focusable, it may contain something that is, so let 9313 // the root view try to give this focus if nothing else does. 9314 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9315 mParent.focusableViewAvailable(this); 9316 } 9317 } 9318 } 9319 9320 /* Check if the GONE bit has changed */ 9321 if ((changed & GONE) != 0) { 9322 needGlobalAttributesUpdate(false); 9323 requestLayout(); 9324 9325 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9326 if (hasFocus()) clearFocus(); 9327 clearAccessibilityFocus(); 9328 destroyDrawingCache(); 9329 if (mParent instanceof View) { 9330 // GONE views noop invalidation, so invalidate the parent 9331 ((View) mParent).invalidate(true); 9332 } 9333 // Mark the view drawn to ensure that it gets invalidated properly the next 9334 // time it is visible and gets invalidated 9335 mPrivateFlags |= PFLAG_DRAWN; 9336 } 9337 if (mAttachInfo != null) { 9338 mAttachInfo.mViewVisibilityChanged = true; 9339 } 9340 } 9341 9342 /* Check if the VISIBLE bit has changed */ 9343 if ((changed & INVISIBLE) != 0) { 9344 needGlobalAttributesUpdate(false); 9345 /* 9346 * If this view is becoming invisible, set the DRAWN flag so that 9347 * the next invalidate() will not be skipped. 9348 */ 9349 mPrivateFlags |= PFLAG_DRAWN; 9350 9351 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9352 // root view becoming invisible shouldn't clear focus and accessibility focus 9353 if (getRootView() != this) { 9354 if (hasFocus()) clearFocus(); 9355 clearAccessibilityFocus(); 9356 } 9357 } 9358 if (mAttachInfo != null) { 9359 mAttachInfo.mViewVisibilityChanged = true; 9360 } 9361 } 9362 9363 if ((changed & VISIBILITY_MASK) != 0) { 9364 // If the view is invisible, cleanup its display list to free up resources 9365 if (newVisibility != VISIBLE && mAttachInfo != null) { 9366 cleanupDraw(); 9367 } 9368 9369 if (mParent instanceof ViewGroup) { 9370 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9371 (changed & VISIBILITY_MASK), newVisibility); 9372 ((View) mParent).invalidate(true); 9373 } else if (mParent != null) { 9374 mParent.invalidateChild(this, null); 9375 } 9376 dispatchVisibilityChanged(this, newVisibility); 9377 9378 notifySubtreeAccessibilityStateChangedIfNeeded(); 9379 } 9380 9381 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9382 destroyDrawingCache(); 9383 } 9384 9385 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9386 destroyDrawingCache(); 9387 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9388 invalidateParentCaches(); 9389 } 9390 9391 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9392 destroyDrawingCache(); 9393 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9394 } 9395 9396 if ((changed & DRAW_MASK) != 0) { 9397 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9398 if (mBackground != null) { 9399 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9400 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9401 } else { 9402 mPrivateFlags |= PFLAG_SKIP_DRAW; 9403 } 9404 } else { 9405 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9406 } 9407 requestLayout(); 9408 invalidate(true); 9409 } 9410 9411 if ((changed & KEEP_SCREEN_ON) != 0) { 9412 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9413 mParent.recomputeViewAttributes(this); 9414 } 9415 } 9416 9417 if (accessibilityEnabled) { 9418 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9419 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9420 if (oldIncludeForAccessibility != includeForAccessibility()) { 9421 notifySubtreeAccessibilityStateChangedIfNeeded(); 9422 } else { 9423 notifyViewAccessibilityStateChangedIfNeeded( 9424 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9425 } 9426 } else if ((changed & ENABLED_MASK) != 0) { 9427 notifyViewAccessibilityStateChangedIfNeeded( 9428 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9429 } 9430 } 9431 } 9432 9433 /** 9434 * Change the view's z order in the tree, so it's on top of other sibling 9435 * views. This ordering change may affect layout, if the parent container 9436 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9437 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9438 * method should be followed by calls to {@link #requestLayout()} and 9439 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9440 * with the new child ordering. 9441 * 9442 * @see ViewGroup#bringChildToFront(View) 9443 */ 9444 public void bringToFront() { 9445 if (mParent != null) { 9446 mParent.bringChildToFront(this); 9447 } 9448 } 9449 9450 /** 9451 * This is called in response to an internal scroll in this view (i.e., the 9452 * view scrolled its own contents). This is typically as a result of 9453 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9454 * called. 9455 * 9456 * @param l Current horizontal scroll origin. 9457 * @param t Current vertical scroll origin. 9458 * @param oldl Previous horizontal scroll origin. 9459 * @param oldt Previous vertical scroll origin. 9460 */ 9461 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9462 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9463 postSendViewScrolledAccessibilityEventCallback(); 9464 } 9465 9466 mBackgroundSizeChanged = true; 9467 9468 final AttachInfo ai = mAttachInfo; 9469 if (ai != null) { 9470 ai.mViewScrollChanged = true; 9471 } 9472 } 9473 9474 /** 9475 * Interface definition for a callback to be invoked when the layout bounds of a view 9476 * changes due to layout processing. 9477 */ 9478 public interface OnLayoutChangeListener { 9479 /** 9480 * Called when the layout bounds of a view changes due to layout processing. 9481 * 9482 * @param v The view whose bounds have changed. 9483 * @param left The new value of the view's left property. 9484 * @param top The new value of the view's top property. 9485 * @param right The new value of the view's right property. 9486 * @param bottom The new value of the view's bottom property. 9487 * @param oldLeft The previous value of the view's left property. 9488 * @param oldTop The previous value of the view's top property. 9489 * @param oldRight The previous value of the view's right property. 9490 * @param oldBottom The previous value of the view's bottom property. 9491 */ 9492 void onLayoutChange(View v, int left, int top, int right, int bottom, 9493 int oldLeft, int oldTop, int oldRight, int oldBottom); 9494 } 9495 9496 /** 9497 * This is called during layout when the size of this view has changed. If 9498 * you were just added to the view hierarchy, you're called with the old 9499 * values of 0. 9500 * 9501 * @param w Current width of this view. 9502 * @param h Current height of this view. 9503 * @param oldw Old width of this view. 9504 * @param oldh Old height of this view. 9505 */ 9506 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9507 } 9508 9509 /** 9510 * Called by draw to draw the child views. This may be overridden 9511 * by derived classes to gain control just before its children are drawn 9512 * (but after its own view has been drawn). 9513 * @param canvas the canvas on which to draw the view 9514 */ 9515 protected void dispatchDraw(Canvas canvas) { 9516 9517 } 9518 9519 /** 9520 * Gets the parent of this view. Note that the parent is a 9521 * ViewParent and not necessarily a View. 9522 * 9523 * @return Parent of this view. 9524 */ 9525 public final ViewParent getParent() { 9526 return mParent; 9527 } 9528 9529 /** 9530 * Set the horizontal scrolled position of your view. This will cause a call to 9531 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9532 * invalidated. 9533 * @param value the x position to scroll to 9534 */ 9535 public void setScrollX(int value) { 9536 scrollTo(value, mScrollY); 9537 } 9538 9539 /** 9540 * Set the vertical scrolled position of your view. This will cause a call to 9541 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9542 * invalidated. 9543 * @param value the y position to scroll to 9544 */ 9545 public void setScrollY(int value) { 9546 scrollTo(mScrollX, value); 9547 } 9548 9549 /** 9550 * Return the scrolled left position of this view. This is the left edge of 9551 * the displayed part of your view. You do not need to draw any pixels 9552 * farther left, since those are outside of the frame of your view on 9553 * screen. 9554 * 9555 * @return The left edge of the displayed part of your view, in pixels. 9556 */ 9557 public final int getScrollX() { 9558 return mScrollX; 9559 } 9560 9561 /** 9562 * Return the scrolled top position of this view. This is the top edge of 9563 * the displayed part of your view. You do not need to draw any pixels above 9564 * it, since those are outside of the frame of your view on screen. 9565 * 9566 * @return The top edge of the displayed part of your view, in pixels. 9567 */ 9568 public final int getScrollY() { 9569 return mScrollY; 9570 } 9571 9572 /** 9573 * Return the width of the your view. 9574 * 9575 * @return The width of your view, in pixels. 9576 */ 9577 @ViewDebug.ExportedProperty(category = "layout") 9578 public final int getWidth() { 9579 return mRight - mLeft; 9580 } 9581 9582 /** 9583 * Return the height of your view. 9584 * 9585 * @return The height of your view, in pixels. 9586 */ 9587 @ViewDebug.ExportedProperty(category = "layout") 9588 public final int getHeight() { 9589 return mBottom - mTop; 9590 } 9591 9592 /** 9593 * Return the visible drawing bounds of your view. Fills in the output 9594 * rectangle with the values from getScrollX(), getScrollY(), 9595 * getWidth(), and getHeight(). These bounds do not account for any 9596 * transformation properties currently set on the view, such as 9597 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9598 * 9599 * @param outRect The (scrolled) drawing bounds of the view. 9600 */ 9601 public void getDrawingRect(Rect outRect) { 9602 outRect.left = mScrollX; 9603 outRect.top = mScrollY; 9604 outRect.right = mScrollX + (mRight - mLeft); 9605 outRect.bottom = mScrollY + (mBottom - mTop); 9606 } 9607 9608 /** 9609 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9610 * raw width component (that is the result is masked by 9611 * {@link #MEASURED_SIZE_MASK}). 9612 * 9613 * @return The raw measured width of this view. 9614 */ 9615 public final int getMeasuredWidth() { 9616 return mMeasuredWidth & MEASURED_SIZE_MASK; 9617 } 9618 9619 /** 9620 * Return the full width measurement information for this view as computed 9621 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9622 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9623 * This should be used during measurement and layout calculations only. Use 9624 * {@link #getWidth()} to see how wide a view is after layout. 9625 * 9626 * @return The measured width of this view as a bit mask. 9627 */ 9628 public final int getMeasuredWidthAndState() { 9629 return mMeasuredWidth; 9630 } 9631 9632 /** 9633 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9634 * raw width component (that is the result is masked by 9635 * {@link #MEASURED_SIZE_MASK}). 9636 * 9637 * @return The raw measured height of this view. 9638 */ 9639 public final int getMeasuredHeight() { 9640 return mMeasuredHeight & MEASURED_SIZE_MASK; 9641 } 9642 9643 /** 9644 * Return the full height measurement information for this view as computed 9645 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9646 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9647 * This should be used during measurement and layout calculations only. Use 9648 * {@link #getHeight()} to see how wide a view is after layout. 9649 * 9650 * @return The measured width of this view as a bit mask. 9651 */ 9652 public final int getMeasuredHeightAndState() { 9653 return mMeasuredHeight; 9654 } 9655 9656 /** 9657 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9658 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9659 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9660 * and the height component is at the shifted bits 9661 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9662 */ 9663 public final int getMeasuredState() { 9664 return (mMeasuredWidth&MEASURED_STATE_MASK) 9665 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9666 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9667 } 9668 9669 /** 9670 * The transform matrix of this view, which is calculated based on the current 9671 * roation, scale, and pivot properties. 9672 * 9673 * @see #getRotation() 9674 * @see #getScaleX() 9675 * @see #getScaleY() 9676 * @see #getPivotX() 9677 * @see #getPivotY() 9678 * @return The current transform matrix for the view 9679 */ 9680 public Matrix getMatrix() { 9681 ensureTransformationInfo(); 9682 final Matrix matrix = mTransformationInfo.mMatrix; 9683 mRenderNode.getMatrix(matrix); 9684 return matrix; 9685 } 9686 9687 /** 9688 * Returns true if the transform matrix is the identity matrix. 9689 * Recomputes the matrix if necessary. 9690 * 9691 * @return True if the transform matrix is the identity matrix, false otherwise. 9692 */ 9693 final boolean hasIdentityMatrix() { 9694 return mRenderNode.hasIdentityMatrix(); 9695 } 9696 9697 void ensureTransformationInfo() { 9698 if (mTransformationInfo == null) { 9699 mTransformationInfo = new TransformationInfo(); 9700 } 9701 } 9702 9703 /** 9704 * Utility method to retrieve the inverse of the current mMatrix property. 9705 * We cache the matrix to avoid recalculating it when transform properties 9706 * have not changed. 9707 * 9708 * @return The inverse of the current matrix of this view. 9709 */ 9710 final Matrix getInverseMatrix() { 9711 ensureTransformationInfo(); 9712 if (mTransformationInfo.mInverseMatrix == null) { 9713 mTransformationInfo.mInverseMatrix = new Matrix(); 9714 } 9715 final Matrix matrix = mTransformationInfo.mInverseMatrix; 9716 mRenderNode.getInverseMatrix(matrix); 9717 return matrix; 9718 } 9719 9720 /** 9721 * Gets the distance along the Z axis from the camera to this view. 9722 * 9723 * @see #setCameraDistance(float) 9724 * 9725 * @return The distance along the Z axis. 9726 */ 9727 public float getCameraDistance() { 9728 final float dpi = mResources.getDisplayMetrics().densityDpi; 9729 return -(mRenderNode.getCameraDistance() * dpi); 9730 } 9731 9732 /** 9733 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9734 * views are drawn) from the camera to this view. The camera's distance 9735 * affects 3D transformations, for instance rotations around the X and Y 9736 * axis. If the rotationX or rotationY properties are changed and this view is 9737 * large (more than half the size of the screen), it is recommended to always 9738 * use a camera distance that's greater than the height (X axis rotation) or 9739 * the width (Y axis rotation) of this view.</p> 9740 * 9741 * <p>The distance of the camera from the view plane can have an affect on the 9742 * perspective distortion of the view when it is rotated around the x or y axis. 9743 * For example, a large distance will result in a large viewing angle, and there 9744 * will not be much perspective distortion of the view as it rotates. A short 9745 * distance may cause much more perspective distortion upon rotation, and can 9746 * also result in some drawing artifacts if the rotated view ends up partially 9747 * behind the camera (which is why the recommendation is to use a distance at 9748 * least as far as the size of the view, if the view is to be rotated.)</p> 9749 * 9750 * <p>The distance is expressed in "depth pixels." The default distance depends 9751 * on the screen density. For instance, on a medium density display, the 9752 * default distance is 1280. On a high density display, the default distance 9753 * is 1920.</p> 9754 * 9755 * <p>If you want to specify a distance that leads to visually consistent 9756 * results across various densities, use the following formula:</p> 9757 * <pre> 9758 * float scale = context.getResources().getDisplayMetrics().density; 9759 * view.setCameraDistance(distance * scale); 9760 * </pre> 9761 * 9762 * <p>The density scale factor of a high density display is 1.5, 9763 * and 1920 = 1280 * 1.5.</p> 9764 * 9765 * @param distance The distance in "depth pixels", if negative the opposite 9766 * value is used 9767 * 9768 * @see #setRotationX(float) 9769 * @see #setRotationY(float) 9770 */ 9771 public void setCameraDistance(float distance) { 9772 final float dpi = mResources.getDisplayMetrics().densityDpi; 9773 9774 invalidateViewProperty(true, false); 9775 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 9776 invalidateViewProperty(false, false); 9777 9778 invalidateParentIfNeededAndWasQuickRejected(); 9779 } 9780 9781 /** 9782 * The degrees that the view is rotated around the pivot point. 9783 * 9784 * @see #setRotation(float) 9785 * @see #getPivotX() 9786 * @see #getPivotY() 9787 * 9788 * @return The degrees of rotation. 9789 */ 9790 @ViewDebug.ExportedProperty(category = "drawing") 9791 public float getRotation() { 9792 return mRenderNode.getRotation(); 9793 } 9794 9795 /** 9796 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9797 * result in clockwise rotation. 9798 * 9799 * @param rotation The degrees of rotation. 9800 * 9801 * @see #getRotation() 9802 * @see #getPivotX() 9803 * @see #getPivotY() 9804 * @see #setRotationX(float) 9805 * @see #setRotationY(float) 9806 * 9807 * @attr ref android.R.styleable#View_rotation 9808 */ 9809 public void setRotation(float rotation) { 9810 if (rotation != getRotation()) { 9811 // Double-invalidation is necessary to capture view's old and new areas 9812 invalidateViewProperty(true, false); 9813 mRenderNode.setRotation(rotation); 9814 invalidateViewProperty(false, true); 9815 9816 invalidateParentIfNeededAndWasQuickRejected(); 9817 notifySubtreeAccessibilityStateChangedIfNeeded(); 9818 } 9819 } 9820 9821 /** 9822 * The degrees that the view is rotated around the vertical axis through the pivot point. 9823 * 9824 * @see #getPivotX() 9825 * @see #getPivotY() 9826 * @see #setRotationY(float) 9827 * 9828 * @return The degrees of Y rotation. 9829 */ 9830 @ViewDebug.ExportedProperty(category = "drawing") 9831 public float getRotationY() { 9832 return mRenderNode.getRotationY(); 9833 } 9834 9835 /** 9836 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9837 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9838 * down the y axis. 9839 * 9840 * When rotating large views, it is recommended to adjust the camera distance 9841 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9842 * 9843 * @param rotationY The degrees of Y rotation. 9844 * 9845 * @see #getRotationY() 9846 * @see #getPivotX() 9847 * @see #getPivotY() 9848 * @see #setRotation(float) 9849 * @see #setRotationX(float) 9850 * @see #setCameraDistance(float) 9851 * 9852 * @attr ref android.R.styleable#View_rotationY 9853 */ 9854 public void setRotationY(float rotationY) { 9855 if (rotationY != getRotationY()) { 9856 invalidateViewProperty(true, false); 9857 mRenderNode.setRotationY(rotationY); 9858 invalidateViewProperty(false, true); 9859 9860 invalidateParentIfNeededAndWasQuickRejected(); 9861 notifySubtreeAccessibilityStateChangedIfNeeded(); 9862 } 9863 } 9864 9865 /** 9866 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9867 * 9868 * @see #getPivotX() 9869 * @see #getPivotY() 9870 * @see #setRotationX(float) 9871 * 9872 * @return The degrees of X rotation. 9873 */ 9874 @ViewDebug.ExportedProperty(category = "drawing") 9875 public float getRotationX() { 9876 return mRenderNode.getRotationX(); 9877 } 9878 9879 /** 9880 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9881 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9882 * x axis. 9883 * 9884 * When rotating large views, it is recommended to adjust the camera distance 9885 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9886 * 9887 * @param rotationX The degrees of X rotation. 9888 * 9889 * @see #getRotationX() 9890 * @see #getPivotX() 9891 * @see #getPivotY() 9892 * @see #setRotation(float) 9893 * @see #setRotationY(float) 9894 * @see #setCameraDistance(float) 9895 * 9896 * @attr ref android.R.styleable#View_rotationX 9897 */ 9898 public void setRotationX(float rotationX) { 9899 if (rotationX != getRotationX()) { 9900 invalidateViewProperty(true, false); 9901 mRenderNode.setRotationX(rotationX); 9902 invalidateViewProperty(false, true); 9903 9904 invalidateParentIfNeededAndWasQuickRejected(); 9905 notifySubtreeAccessibilityStateChangedIfNeeded(); 9906 } 9907 } 9908 9909 /** 9910 * The amount that the view is scaled in x around the pivot point, as a proportion of 9911 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9912 * 9913 * <p>By default, this is 1.0f. 9914 * 9915 * @see #getPivotX() 9916 * @see #getPivotY() 9917 * @return The scaling factor. 9918 */ 9919 @ViewDebug.ExportedProperty(category = "drawing") 9920 public float getScaleX() { 9921 return mRenderNode.getScaleX(); 9922 } 9923 9924 /** 9925 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9926 * the view's unscaled width. A value of 1 means that no scaling is applied. 9927 * 9928 * @param scaleX The scaling factor. 9929 * @see #getPivotX() 9930 * @see #getPivotY() 9931 * 9932 * @attr ref android.R.styleable#View_scaleX 9933 */ 9934 public void setScaleX(float scaleX) { 9935 if (scaleX != getScaleX()) { 9936 invalidateViewProperty(true, false); 9937 mRenderNode.setScaleX(scaleX); 9938 invalidateViewProperty(false, true); 9939 9940 invalidateParentIfNeededAndWasQuickRejected(); 9941 notifySubtreeAccessibilityStateChangedIfNeeded(); 9942 } 9943 } 9944 9945 /** 9946 * The amount that the view is scaled in y around the pivot point, as a proportion of 9947 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9948 * 9949 * <p>By default, this is 1.0f. 9950 * 9951 * @see #getPivotX() 9952 * @see #getPivotY() 9953 * @return The scaling factor. 9954 */ 9955 @ViewDebug.ExportedProperty(category = "drawing") 9956 public float getScaleY() { 9957 return mRenderNode.getScaleY(); 9958 } 9959 9960 /** 9961 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9962 * the view's unscaled width. A value of 1 means that no scaling is applied. 9963 * 9964 * @param scaleY The scaling factor. 9965 * @see #getPivotX() 9966 * @see #getPivotY() 9967 * 9968 * @attr ref android.R.styleable#View_scaleY 9969 */ 9970 public void setScaleY(float scaleY) { 9971 if (scaleY != getScaleY()) { 9972 invalidateViewProperty(true, false); 9973 mRenderNode.setScaleY(scaleY); 9974 invalidateViewProperty(false, true); 9975 9976 invalidateParentIfNeededAndWasQuickRejected(); 9977 notifySubtreeAccessibilityStateChangedIfNeeded(); 9978 } 9979 } 9980 9981 /** 9982 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9983 * and {@link #setScaleX(float) scaled}. 9984 * 9985 * @see #getRotation() 9986 * @see #getScaleX() 9987 * @see #getScaleY() 9988 * @see #getPivotY() 9989 * @return The x location of the pivot point. 9990 * 9991 * @attr ref android.R.styleable#View_transformPivotX 9992 */ 9993 @ViewDebug.ExportedProperty(category = "drawing") 9994 public float getPivotX() { 9995 return mRenderNode.getPivotX(); 9996 } 9997 9998 /** 9999 * Sets the x location of the point around which the view is 10000 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 10001 * By default, the pivot point is centered on the object. 10002 * Setting this property disables this behavior and causes the view to use only the 10003 * explicitly set pivotX and pivotY values. 10004 * 10005 * @param pivotX The x location of the pivot point. 10006 * @see #getRotation() 10007 * @see #getScaleX() 10008 * @see #getScaleY() 10009 * @see #getPivotY() 10010 * 10011 * @attr ref android.R.styleable#View_transformPivotX 10012 */ 10013 public void setPivotX(float pivotX) { 10014 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 10015 invalidateViewProperty(true, false); 10016 mRenderNode.setPivotX(pivotX); 10017 invalidateViewProperty(false, true); 10018 10019 invalidateParentIfNeededAndWasQuickRejected(); 10020 } 10021 } 10022 10023 /** 10024 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10025 * and {@link #setScaleY(float) scaled}. 10026 * 10027 * @see #getRotation() 10028 * @see #getScaleX() 10029 * @see #getScaleY() 10030 * @see #getPivotY() 10031 * @return The y location of the pivot point. 10032 * 10033 * @attr ref android.R.styleable#View_transformPivotY 10034 */ 10035 @ViewDebug.ExportedProperty(category = "drawing") 10036 public float getPivotY() { 10037 return mRenderNode.getPivotY(); 10038 } 10039 10040 /** 10041 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10042 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10043 * Setting this property disables this behavior and causes the view to use only the 10044 * explicitly set pivotX and pivotY values. 10045 * 10046 * @param pivotY The y location of the pivot point. 10047 * @see #getRotation() 10048 * @see #getScaleX() 10049 * @see #getScaleY() 10050 * @see #getPivotY() 10051 * 10052 * @attr ref android.R.styleable#View_transformPivotY 10053 */ 10054 public void setPivotY(float pivotY) { 10055 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10056 invalidateViewProperty(true, false); 10057 mRenderNode.setPivotY(pivotY); 10058 invalidateViewProperty(false, true); 10059 10060 invalidateParentIfNeededAndWasQuickRejected(); 10061 } 10062 } 10063 10064 /** 10065 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10066 * completely transparent and 1 means the view is completely opaque. 10067 * 10068 * <p>By default this is 1.0f. 10069 * @return The opacity of the view. 10070 */ 10071 @ViewDebug.ExportedProperty(category = "drawing") 10072 public float getAlpha() { 10073 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10074 } 10075 10076 /** 10077 * Returns whether this View has content which overlaps. 10078 * 10079 * <p>This function, intended to be overridden by specific View types, is an optimization when 10080 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10081 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10082 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10083 * directly. An example of overlapping rendering is a TextView with a background image, such as 10084 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10085 * ImageView with only the foreground image. The default implementation returns true; subclasses 10086 * should override if they have cases which can be optimized.</p> 10087 * 10088 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10089 * necessitates that a View return true if it uses the methods internally without passing the 10090 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10091 * 10092 * @return true if the content in this view might overlap, false otherwise. 10093 */ 10094 public boolean hasOverlappingRendering() { 10095 return true; 10096 } 10097 10098 /** 10099 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10100 * completely transparent and 1 means the view is completely opaque.</p> 10101 * 10102 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10103 * performance implications, especially for large views. It is best to use the alpha property 10104 * sparingly and transiently, as in the case of fading animations.</p> 10105 * 10106 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10107 * strongly recommended for performance reasons to either override 10108 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10109 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10110 * 10111 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10112 * responsible for applying the opacity itself.</p> 10113 * 10114 * <p>Note that if the view is backed by a 10115 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10116 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10117 * 1.0 will supercede the alpha of the layer paint.</p> 10118 * 10119 * @param alpha The opacity of the view. 10120 * 10121 * @see #hasOverlappingRendering() 10122 * @see #setLayerType(int, android.graphics.Paint) 10123 * 10124 * @attr ref android.R.styleable#View_alpha 10125 */ 10126 public void setAlpha(float alpha) { 10127 ensureTransformationInfo(); 10128 if (mTransformationInfo.mAlpha != alpha) { 10129 mTransformationInfo.mAlpha = alpha; 10130 if (onSetAlpha((int) (alpha * 255))) { 10131 mPrivateFlags |= PFLAG_ALPHA_SET; 10132 // subclass is handling alpha - don't optimize rendering cache invalidation 10133 invalidateParentCaches(); 10134 invalidate(true); 10135 } else { 10136 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10137 invalidateViewProperty(true, false); 10138 mRenderNode.setAlpha(getFinalAlpha()); 10139 notifyViewAccessibilityStateChangedIfNeeded( 10140 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10141 } 10142 } 10143 } 10144 10145 /** 10146 * Faster version of setAlpha() which performs the same steps except there are 10147 * no calls to invalidate(). The caller of this function should perform proper invalidation 10148 * on the parent and this object. The return value indicates whether the subclass handles 10149 * alpha (the return value for onSetAlpha()). 10150 * 10151 * @param alpha The new value for the alpha property 10152 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10153 * the new value for the alpha property is different from the old value 10154 */ 10155 boolean setAlphaNoInvalidation(float alpha) { 10156 ensureTransformationInfo(); 10157 if (mTransformationInfo.mAlpha != alpha) { 10158 mTransformationInfo.mAlpha = alpha; 10159 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10160 if (subclassHandlesAlpha) { 10161 mPrivateFlags |= PFLAG_ALPHA_SET; 10162 return true; 10163 } else { 10164 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10165 mRenderNode.setAlpha(getFinalAlpha()); 10166 } 10167 } 10168 return false; 10169 } 10170 10171 /** 10172 * This property is hidden and intended only for use by the Fade transition, which 10173 * animates it to produce a visual translucency that does not side-effect (or get 10174 * affected by) the real alpha property. This value is composited with the other 10175 * alpha value (and the AlphaAnimation value, when that is present) to produce 10176 * a final visual translucency result, which is what is passed into the DisplayList. 10177 * 10178 * @hide 10179 */ 10180 public void setTransitionAlpha(float alpha) { 10181 ensureTransformationInfo(); 10182 if (mTransformationInfo.mTransitionAlpha != alpha) { 10183 mTransformationInfo.mTransitionAlpha = alpha; 10184 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10185 invalidateViewProperty(true, false); 10186 mRenderNode.setAlpha(getFinalAlpha()); 10187 } 10188 } 10189 10190 /** 10191 * Calculates the visual alpha of this view, which is a combination of the actual 10192 * alpha value and the transitionAlpha value (if set). 10193 */ 10194 private float getFinalAlpha() { 10195 if (mTransformationInfo != null) { 10196 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10197 } 10198 return 1; 10199 } 10200 10201 /** 10202 * This property is hidden and intended only for use by the Fade transition, which 10203 * animates it to produce a visual translucency that does not side-effect (or get 10204 * affected by) the real alpha property. This value is composited with the other 10205 * alpha value (and the AlphaAnimation value, when that is present) to produce 10206 * a final visual translucency result, which is what is passed into the DisplayList. 10207 * 10208 * @hide 10209 */ 10210 public float getTransitionAlpha() { 10211 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10212 } 10213 10214 /** 10215 * Top position of this view relative to its parent. 10216 * 10217 * @return The top of this view, in pixels. 10218 */ 10219 @ViewDebug.CapturedViewProperty 10220 public final int getTop() { 10221 return mTop; 10222 } 10223 10224 /** 10225 * Sets the top position of this view relative to its parent. This method is meant to be called 10226 * by the layout system and should not generally be called otherwise, because the property 10227 * may be changed at any time by the layout. 10228 * 10229 * @param top The top of this view, in pixels. 10230 */ 10231 public final void setTop(int top) { 10232 if (top != mTop) { 10233 final boolean matrixIsIdentity = hasIdentityMatrix(); 10234 if (matrixIsIdentity) { 10235 if (mAttachInfo != null) { 10236 int minTop; 10237 int yLoc; 10238 if (top < mTop) { 10239 minTop = top; 10240 yLoc = top - mTop; 10241 } else { 10242 minTop = mTop; 10243 yLoc = 0; 10244 } 10245 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10246 } 10247 } else { 10248 // Double-invalidation is necessary to capture view's old and new areas 10249 invalidate(true); 10250 } 10251 10252 int width = mRight - mLeft; 10253 int oldHeight = mBottom - mTop; 10254 10255 mTop = top; 10256 mRenderNode.setTop(mTop); 10257 10258 sizeChange(width, mBottom - mTop, width, oldHeight); 10259 10260 if (!matrixIsIdentity) { 10261 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10262 invalidate(true); 10263 } 10264 mBackgroundSizeChanged = true; 10265 invalidateParentIfNeeded(); 10266 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10267 // View was rejected last time it was drawn by its parent; this may have changed 10268 invalidateParentIfNeeded(); 10269 } 10270 } 10271 } 10272 10273 /** 10274 * Bottom position of this view relative to its parent. 10275 * 10276 * @return The bottom of this view, in pixels. 10277 */ 10278 @ViewDebug.CapturedViewProperty 10279 public final int getBottom() { 10280 return mBottom; 10281 } 10282 10283 /** 10284 * True if this view has changed since the last time being drawn. 10285 * 10286 * @return The dirty state of this view. 10287 */ 10288 public boolean isDirty() { 10289 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10290 } 10291 10292 /** 10293 * Sets the bottom position of this view relative to its parent. This method is meant to be 10294 * called by the layout system and should not generally be called otherwise, because the 10295 * property may be changed at any time by the layout. 10296 * 10297 * @param bottom The bottom of this view, in pixels. 10298 */ 10299 public final void setBottom(int bottom) { 10300 if (bottom != mBottom) { 10301 final boolean matrixIsIdentity = hasIdentityMatrix(); 10302 if (matrixIsIdentity) { 10303 if (mAttachInfo != null) { 10304 int maxBottom; 10305 if (bottom < mBottom) { 10306 maxBottom = mBottom; 10307 } else { 10308 maxBottom = bottom; 10309 } 10310 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10311 } 10312 } else { 10313 // Double-invalidation is necessary to capture view's old and new areas 10314 invalidate(true); 10315 } 10316 10317 int width = mRight - mLeft; 10318 int oldHeight = mBottom - mTop; 10319 10320 mBottom = bottom; 10321 mRenderNode.setBottom(mBottom); 10322 10323 sizeChange(width, mBottom - mTop, width, oldHeight); 10324 10325 if (!matrixIsIdentity) { 10326 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10327 invalidate(true); 10328 } 10329 mBackgroundSizeChanged = true; 10330 invalidateParentIfNeeded(); 10331 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10332 // View was rejected last time it was drawn by its parent; this may have changed 10333 invalidateParentIfNeeded(); 10334 } 10335 } 10336 } 10337 10338 /** 10339 * Left position of this view relative to its parent. 10340 * 10341 * @return The left edge of this view, in pixels. 10342 */ 10343 @ViewDebug.CapturedViewProperty 10344 public final int getLeft() { 10345 return mLeft; 10346 } 10347 10348 /** 10349 * Sets the left position of this view relative to its parent. This method is meant to be called 10350 * by the layout system and should not generally be called otherwise, because the property 10351 * may be changed at any time by the layout. 10352 * 10353 * @param left The left of this view, in pixels. 10354 */ 10355 public final void setLeft(int left) { 10356 if (left != mLeft) { 10357 final boolean matrixIsIdentity = hasIdentityMatrix(); 10358 if (matrixIsIdentity) { 10359 if (mAttachInfo != null) { 10360 int minLeft; 10361 int xLoc; 10362 if (left < mLeft) { 10363 minLeft = left; 10364 xLoc = left - mLeft; 10365 } else { 10366 minLeft = mLeft; 10367 xLoc = 0; 10368 } 10369 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10370 } 10371 } else { 10372 // Double-invalidation is necessary to capture view's old and new areas 10373 invalidate(true); 10374 } 10375 10376 int oldWidth = mRight - mLeft; 10377 int height = mBottom - mTop; 10378 10379 mLeft = left; 10380 mRenderNode.setLeft(left); 10381 10382 sizeChange(mRight - mLeft, height, oldWidth, height); 10383 10384 if (!matrixIsIdentity) { 10385 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10386 invalidate(true); 10387 } 10388 mBackgroundSizeChanged = true; 10389 invalidateParentIfNeeded(); 10390 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10391 // View was rejected last time it was drawn by its parent; this may have changed 10392 invalidateParentIfNeeded(); 10393 } 10394 } 10395 } 10396 10397 /** 10398 * Right position of this view relative to its parent. 10399 * 10400 * @return The right edge of this view, in pixels. 10401 */ 10402 @ViewDebug.CapturedViewProperty 10403 public final int getRight() { 10404 return mRight; 10405 } 10406 10407 /** 10408 * Sets the right position of this view relative to its parent. This method is meant to be called 10409 * by the layout system and should not generally be called otherwise, because the property 10410 * may be changed at any time by the layout. 10411 * 10412 * @param right The right of this view, in pixels. 10413 */ 10414 public final void setRight(int right) { 10415 if (right != mRight) { 10416 final boolean matrixIsIdentity = hasIdentityMatrix(); 10417 if (matrixIsIdentity) { 10418 if (mAttachInfo != null) { 10419 int maxRight; 10420 if (right < mRight) { 10421 maxRight = mRight; 10422 } else { 10423 maxRight = right; 10424 } 10425 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10426 } 10427 } else { 10428 // Double-invalidation is necessary to capture view's old and new areas 10429 invalidate(true); 10430 } 10431 10432 int oldWidth = mRight - mLeft; 10433 int height = mBottom - mTop; 10434 10435 mRight = right; 10436 mRenderNode.setRight(mRight); 10437 10438 sizeChange(mRight - mLeft, height, oldWidth, height); 10439 10440 if (!matrixIsIdentity) { 10441 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10442 invalidate(true); 10443 } 10444 mBackgroundSizeChanged = true; 10445 invalidateParentIfNeeded(); 10446 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10447 // View was rejected last time it was drawn by its parent; this may have changed 10448 invalidateParentIfNeeded(); 10449 } 10450 } 10451 } 10452 10453 /** 10454 * The visual x position of this view, in pixels. This is equivalent to the 10455 * {@link #setTranslationX(float) translationX} property plus the current 10456 * {@link #getLeft() left} property. 10457 * 10458 * @return The visual x position of this view, in pixels. 10459 */ 10460 @ViewDebug.ExportedProperty(category = "drawing") 10461 public float getX() { 10462 return mLeft + getTranslationX(); 10463 } 10464 10465 /** 10466 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10467 * {@link #setTranslationX(float) translationX} property to be the difference between 10468 * the x value passed in and the current {@link #getLeft() left} property. 10469 * 10470 * @param x The visual x position of this view, in pixels. 10471 */ 10472 public void setX(float x) { 10473 setTranslationX(x - mLeft); 10474 } 10475 10476 /** 10477 * The visual y position of this view, in pixels. This is equivalent to the 10478 * {@link #setTranslationY(float) translationY} property plus the current 10479 * {@link #getTop() top} property. 10480 * 10481 * @return The visual y position of this view, in pixels. 10482 */ 10483 @ViewDebug.ExportedProperty(category = "drawing") 10484 public float getY() { 10485 return mTop + getTranslationY(); 10486 } 10487 10488 /** 10489 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10490 * {@link #setTranslationY(float) translationY} property to be the difference between 10491 * the y value passed in and the current {@link #getTop() top} property. 10492 * 10493 * @param y The visual y position of this view, in pixels. 10494 */ 10495 public void setY(float y) { 10496 setTranslationY(y - mTop); 10497 } 10498 10499 /** 10500 * The visual z position of this view, in pixels. This is equivalent to the 10501 * {@link #setTranslationZ(float) translationZ} property plus the current 10502 * {@link #getElevation() elevation} property. 10503 * 10504 * @return The visual z position of this view, in pixels. 10505 */ 10506 @ViewDebug.ExportedProperty(category = "drawing") 10507 public float getZ() { 10508 return getElevation() + getTranslationZ(); 10509 } 10510 10511 /** 10512 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 10513 * {@link #setTranslationZ(float) translationZ} property to be the difference between 10514 * the x value passed in and the current {@link #getElevation() elevation} property. 10515 * 10516 * @param z The visual z position of this view, in pixels. 10517 */ 10518 public void setZ(float z) { 10519 setTranslationZ(z - getElevation()); 10520 } 10521 10522 @ViewDebug.ExportedProperty(category = "drawing") 10523 public float getElevation() { 10524 return mRenderNode.getElevation(); 10525 } 10526 10527 /** 10528 * Sets the base depth location of this view. 10529 * 10530 * @attr ref android.R.styleable#View_elevation 10531 */ 10532 public void setElevation(float elevation) { 10533 if (elevation != getElevation()) { 10534 invalidateViewProperty(true, false); 10535 mRenderNode.setElevation(elevation); 10536 invalidateViewProperty(false, true); 10537 10538 invalidateParentIfNeededAndWasQuickRejected(); 10539 } 10540 } 10541 10542 /** 10543 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10544 * This position is post-layout, in addition to wherever the object's 10545 * layout placed it. 10546 * 10547 * @return The horizontal position of this view relative to its left position, in pixels. 10548 */ 10549 @ViewDebug.ExportedProperty(category = "drawing") 10550 public float getTranslationX() { 10551 return mRenderNode.getTranslationX(); 10552 } 10553 10554 /** 10555 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10556 * This effectively positions the object post-layout, in addition to wherever the object's 10557 * layout placed it. 10558 * 10559 * @param translationX The horizontal position of this view relative to its left position, 10560 * in pixels. 10561 * 10562 * @attr ref android.R.styleable#View_translationX 10563 */ 10564 public void setTranslationX(float translationX) { 10565 if (translationX != getTranslationX()) { 10566 invalidateViewProperty(true, false); 10567 mRenderNode.setTranslationX(translationX); 10568 invalidateViewProperty(false, true); 10569 10570 invalidateParentIfNeededAndWasQuickRejected(); 10571 notifySubtreeAccessibilityStateChangedIfNeeded(); 10572 } 10573 } 10574 10575 /** 10576 * The vertical location of this view relative to its {@link #getTop() top} position. 10577 * This position is post-layout, in addition to wherever the object's 10578 * layout placed it. 10579 * 10580 * @return The vertical position of this view relative to its top position, 10581 * in pixels. 10582 */ 10583 @ViewDebug.ExportedProperty(category = "drawing") 10584 public float getTranslationY() { 10585 return mRenderNode.getTranslationY(); 10586 } 10587 10588 /** 10589 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10590 * This effectively positions the object post-layout, in addition to wherever the object's 10591 * layout placed it. 10592 * 10593 * @param translationY The vertical position of this view relative to its top position, 10594 * in pixels. 10595 * 10596 * @attr ref android.R.styleable#View_translationY 10597 */ 10598 public void setTranslationY(float translationY) { 10599 if (translationY != getTranslationY()) { 10600 invalidateViewProperty(true, false); 10601 mRenderNode.setTranslationY(translationY); 10602 invalidateViewProperty(false, true); 10603 10604 invalidateParentIfNeededAndWasQuickRejected(); 10605 } 10606 } 10607 10608 /** 10609 * The depth location of this view relative to its {@link #getElevation() elevation}. 10610 * 10611 * @return The depth of this view relative to its elevation. 10612 */ 10613 @ViewDebug.ExportedProperty(category = "drawing") 10614 public float getTranslationZ() { 10615 return mRenderNode.getTranslationZ(); 10616 } 10617 10618 /** 10619 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 10620 * 10621 * @attr ref android.R.styleable#View_translationZ 10622 */ 10623 public void setTranslationZ(float translationZ) { 10624 if (translationZ != getTranslationZ()) { 10625 invalidateViewProperty(true, false); 10626 mRenderNode.setTranslationZ(translationZ); 10627 invalidateViewProperty(false, true); 10628 10629 invalidateParentIfNeededAndWasQuickRejected(); 10630 } 10631 } 10632 10633 /** 10634 * Returns a ValueAnimator which can animate a clipping circle. 10635 * <p> 10636 * The View will be clipped to the animating circle. 10637 * <p> 10638 * Any shadow cast by the View will respect the circular clip from this animator. 10639 * 10640 * @param centerX The x coordinate of the center of the animating circle. 10641 * @param centerY The y coordinate of the center of the animating circle. 10642 * @param startRadius The starting radius of the animating circle. 10643 * @param endRadius The ending radius of the animating circle. 10644 */ 10645 public final ValueAnimator createRevealAnimator(int centerX, int centerY, 10646 float startRadius, float endRadius) { 10647 return RevealAnimator.ofRevealCircle(this, centerX, centerY, 10648 startRadius, endRadius, false); 10649 } 10650 10651 /** 10652 * Returns a ValueAnimator which can animate a clearing circle. 10653 * <p> 10654 * The View is prevented from drawing within the circle, so the content 10655 * behind the View shows through. 10656 * 10657 * @param centerX The x coordinate of the center of the animating circle. 10658 * @param centerY The y coordinate of the center of the animating circle. 10659 * @param startRadius The starting radius of the animating circle. 10660 * @param endRadius The ending radius of the animating circle. 10661 * 10662 * @hide 10663 */ 10664 public final ValueAnimator createClearCircleAnimator(int centerX, int centerY, 10665 float startRadius, float endRadius) { 10666 return RevealAnimator.ofRevealCircle(this, centerX, centerY, 10667 startRadius, endRadius, true); 10668 } 10669 10670 /** 10671 * Returns the current StateListAnimator if exists. 10672 * 10673 * @return StateListAnimator or null if it does not exists 10674 * @see #setStateListAnimator(android.animation.StateListAnimator) 10675 */ 10676 public StateListAnimator getStateListAnimator() { 10677 return mStateListAnimator; 10678 } 10679 10680 /** 10681 * Attaches the provided StateListAnimator to this View. 10682 * <p> 10683 * Any previously attached StateListAnimator will be detached. 10684 * 10685 * @param stateListAnimator The StateListAnimator to update the view 10686 * @see {@link android.animation.StateListAnimator} 10687 */ 10688 public void setStateListAnimator(StateListAnimator stateListAnimator) { 10689 if (mStateListAnimator == stateListAnimator) { 10690 return; 10691 } 10692 if (mStateListAnimator != null) { 10693 mStateListAnimator.setTarget(null); 10694 } 10695 mStateListAnimator = stateListAnimator; 10696 if (stateListAnimator != null) { 10697 stateListAnimator.setTarget(this); 10698 if (isAttachedToWindow()) { 10699 stateListAnimator.setState(getDrawableState()); 10700 } 10701 } 10702 } 10703 10704 /** 10705 * Sets the outline of the view, which defines the shape of the shadow it 10706 * casts. 10707 * <p> 10708 * If the outline is not set or is null, shadows will be cast from the 10709 * bounds of the View. 10710 * 10711 * @param outline The new outline of the view. 10712 * Must be {@link android.graphics.Outline#isValid() valid.} 10713 */ 10714 public void setOutline(@Nullable Outline outline) { 10715 if (outline != null && !outline.isValid()) { 10716 throw new IllegalArgumentException("Outline must not be invalid"); 10717 } 10718 10719 mPrivateFlags3 |= PFLAG3_OUTLINE_DEFINED; 10720 10721 if (outline == null) { 10722 mOutline = null; 10723 } else { 10724 // always copy the path since caller may reuse 10725 if (mOutline == null) { 10726 mOutline = new Outline(); 10727 } 10728 mOutline.set(outline); 10729 } 10730 mRenderNode.setOutline(mOutline); 10731 } 10732 10733 public final boolean getClipToOutline() { 10734 return mRenderNode.getClipToOutline(); 10735 } 10736 10737 public void setClipToOutline(boolean clipToOutline) { 10738 // TODO: add a fast invalidation here 10739 if (getClipToOutline() != clipToOutline) { 10740 mRenderNode.setClipToOutline(clipToOutline); 10741 } 10742 } 10743 10744 private void queryOutlineFromBackgroundIfUndefined() { 10745 if ((mPrivateFlags3 & PFLAG3_OUTLINE_DEFINED) == 0) { 10746 // Outline not currently defined, query from background 10747 if (mOutline == null) { 10748 mOutline = new Outline(); 10749 } else { 10750 //invalidate outline, to ensure background calculates it 10751 mOutline.reset(); 10752 } 10753 if (mBackground.getOutline(mOutline)) { 10754 if (!mOutline.isValid()) { 10755 throw new IllegalStateException("Background drawable failed to build outline"); 10756 } 10757 mRenderNode.setOutline(mOutline); 10758 } else { 10759 mRenderNode.setOutline(null); 10760 } 10761 notifySubtreeAccessibilityStateChangedIfNeeded(); 10762 } 10763 } 10764 10765 /** 10766 * Private API to be used for reveal animation 10767 * 10768 * @hide 10769 */ 10770 public void setRevealClip(boolean shouldClip, boolean inverseClip, 10771 float x, float y, float radius) { 10772 mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius); 10773 // TODO: Handle this invalidate in a better way, or purely in native. 10774 invalidate(); 10775 } 10776 10777 /** 10778 * Hit rectangle in parent's coordinates 10779 * 10780 * @param outRect The hit rectangle of the view. 10781 */ 10782 public void getHitRect(Rect outRect) { 10783 if (hasIdentityMatrix() || mAttachInfo == null) { 10784 outRect.set(mLeft, mTop, mRight, mBottom); 10785 } else { 10786 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10787 tmpRect.set(0, 0, getWidth(), getHeight()); 10788 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 10789 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10790 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10791 } 10792 } 10793 10794 /** 10795 * Determines whether the given point, in local coordinates is inside the view. 10796 */ 10797 /*package*/ final boolean pointInView(float localX, float localY) { 10798 return localX >= 0 && localX < (mRight - mLeft) 10799 && localY >= 0 && localY < (mBottom - mTop); 10800 } 10801 10802 /** 10803 * Utility method to determine whether the given point, in local coordinates, 10804 * is inside the view, where the area of the view is expanded by the slop factor. 10805 * This method is called while processing touch-move events to determine if the event 10806 * is still within the view. 10807 * 10808 * @hide 10809 */ 10810 public boolean pointInView(float localX, float localY, float slop) { 10811 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10812 localY < ((mBottom - mTop) + slop); 10813 } 10814 10815 /** 10816 * When a view has focus and the user navigates away from it, the next view is searched for 10817 * starting from the rectangle filled in by this method. 10818 * 10819 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10820 * of the view. However, if your view maintains some idea of internal selection, 10821 * such as a cursor, or a selected row or column, you should override this method and 10822 * fill in a more specific rectangle. 10823 * 10824 * @param r The rectangle to fill in, in this view's coordinates. 10825 */ 10826 public void getFocusedRect(Rect r) { 10827 getDrawingRect(r); 10828 } 10829 10830 /** 10831 * If some part of this view is not clipped by any of its parents, then 10832 * return that area in r in global (root) coordinates. To convert r to local 10833 * coordinates (without taking possible View rotations into account), offset 10834 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10835 * If the view is completely clipped or translated out, return false. 10836 * 10837 * @param r If true is returned, r holds the global coordinates of the 10838 * visible portion of this view. 10839 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10840 * between this view and its root. globalOffet may be null. 10841 * @return true if r is non-empty (i.e. part of the view is visible at the 10842 * root level. 10843 */ 10844 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10845 int width = mRight - mLeft; 10846 int height = mBottom - mTop; 10847 if (width > 0 && height > 0) { 10848 r.set(0, 0, width, height); 10849 if (globalOffset != null) { 10850 globalOffset.set(-mScrollX, -mScrollY); 10851 } 10852 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10853 } 10854 return false; 10855 } 10856 10857 public final boolean getGlobalVisibleRect(Rect r) { 10858 return getGlobalVisibleRect(r, null); 10859 } 10860 10861 public final boolean getLocalVisibleRect(Rect r) { 10862 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10863 if (getGlobalVisibleRect(r, offset)) { 10864 r.offset(-offset.x, -offset.y); // make r local 10865 return true; 10866 } 10867 return false; 10868 } 10869 10870 /** 10871 * Offset this view's vertical location by the specified number of pixels. 10872 * 10873 * @param offset the number of pixels to offset the view by 10874 */ 10875 public void offsetTopAndBottom(int offset) { 10876 if (offset != 0) { 10877 final boolean matrixIsIdentity = hasIdentityMatrix(); 10878 if (matrixIsIdentity) { 10879 if (isHardwareAccelerated()) { 10880 invalidateViewProperty(false, false); 10881 } else { 10882 final ViewParent p = mParent; 10883 if (p != null && mAttachInfo != null) { 10884 final Rect r = mAttachInfo.mTmpInvalRect; 10885 int minTop; 10886 int maxBottom; 10887 int yLoc; 10888 if (offset < 0) { 10889 minTop = mTop + offset; 10890 maxBottom = mBottom; 10891 yLoc = offset; 10892 } else { 10893 minTop = mTop; 10894 maxBottom = mBottom + offset; 10895 yLoc = 0; 10896 } 10897 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10898 p.invalidateChild(this, r); 10899 } 10900 } 10901 } else { 10902 invalidateViewProperty(false, false); 10903 } 10904 10905 mTop += offset; 10906 mBottom += offset; 10907 mRenderNode.offsetTopAndBottom(offset); 10908 if (isHardwareAccelerated()) { 10909 invalidateViewProperty(false, false); 10910 } else { 10911 if (!matrixIsIdentity) { 10912 invalidateViewProperty(false, true); 10913 } 10914 invalidateParentIfNeeded(); 10915 } 10916 notifySubtreeAccessibilityStateChangedIfNeeded(); 10917 } 10918 } 10919 10920 /** 10921 * Offset this view's horizontal location by the specified amount of pixels. 10922 * 10923 * @param offset the number of pixels to offset the view by 10924 */ 10925 public void offsetLeftAndRight(int offset) { 10926 if (offset != 0) { 10927 final boolean matrixIsIdentity = hasIdentityMatrix(); 10928 if (matrixIsIdentity) { 10929 if (isHardwareAccelerated()) { 10930 invalidateViewProperty(false, false); 10931 } else { 10932 final ViewParent p = mParent; 10933 if (p != null && mAttachInfo != null) { 10934 final Rect r = mAttachInfo.mTmpInvalRect; 10935 int minLeft; 10936 int maxRight; 10937 if (offset < 0) { 10938 minLeft = mLeft + offset; 10939 maxRight = mRight; 10940 } else { 10941 minLeft = mLeft; 10942 maxRight = mRight + offset; 10943 } 10944 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 10945 p.invalidateChild(this, r); 10946 } 10947 } 10948 } else { 10949 invalidateViewProperty(false, false); 10950 } 10951 10952 mLeft += offset; 10953 mRight += offset; 10954 mRenderNode.offsetLeftAndRight(offset); 10955 if (isHardwareAccelerated()) { 10956 invalidateViewProperty(false, false); 10957 } else { 10958 if (!matrixIsIdentity) { 10959 invalidateViewProperty(false, true); 10960 } 10961 invalidateParentIfNeeded(); 10962 } 10963 notifySubtreeAccessibilityStateChangedIfNeeded(); 10964 } 10965 } 10966 10967 /** 10968 * Get the LayoutParams associated with this view. All views should have 10969 * layout parameters. These supply parameters to the <i>parent</i> of this 10970 * view specifying how it should be arranged. There are many subclasses of 10971 * ViewGroup.LayoutParams, and these correspond to the different subclasses 10972 * of ViewGroup that are responsible for arranging their children. 10973 * 10974 * This method may return null if this View is not attached to a parent 10975 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 10976 * was not invoked successfully. When a View is attached to a parent 10977 * ViewGroup, this method must not return null. 10978 * 10979 * @return The LayoutParams associated with this view, or null if no 10980 * parameters have been set yet 10981 */ 10982 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 10983 public ViewGroup.LayoutParams getLayoutParams() { 10984 return mLayoutParams; 10985 } 10986 10987 /** 10988 * Set the layout parameters associated with this view. These supply 10989 * parameters to the <i>parent</i> of this view specifying how it should be 10990 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 10991 * correspond to the different subclasses of ViewGroup that are responsible 10992 * for arranging their children. 10993 * 10994 * @param params The layout parameters for this view, cannot be null 10995 */ 10996 public void setLayoutParams(ViewGroup.LayoutParams params) { 10997 if (params == null) { 10998 throw new NullPointerException("Layout parameters cannot be null"); 10999 } 11000 mLayoutParams = params; 11001 resolveLayoutParams(); 11002 if (mParent instanceof ViewGroup) { 11003 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11004 } 11005 requestLayout(); 11006 } 11007 11008 /** 11009 * Resolve the layout parameters depending on the resolved layout direction 11010 * 11011 * @hide 11012 */ 11013 public void resolveLayoutParams() { 11014 if (mLayoutParams != null) { 11015 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11016 } 11017 } 11018 11019 /** 11020 * Set the scrolled position of your view. This will cause a call to 11021 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11022 * invalidated. 11023 * @param x the x position to scroll to 11024 * @param y the y position to scroll to 11025 */ 11026 public void scrollTo(int x, int y) { 11027 if (mScrollX != x || mScrollY != y) { 11028 int oldX = mScrollX; 11029 int oldY = mScrollY; 11030 mScrollX = x; 11031 mScrollY = y; 11032 invalidateParentCaches(); 11033 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11034 if (!awakenScrollBars()) { 11035 postInvalidateOnAnimation(); 11036 } 11037 } 11038 } 11039 11040 /** 11041 * Move the scrolled position of your view. This will cause a call to 11042 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11043 * invalidated. 11044 * @param x the amount of pixels to scroll by horizontally 11045 * @param y the amount of pixels to scroll by vertically 11046 */ 11047 public void scrollBy(int x, int y) { 11048 scrollTo(mScrollX + x, mScrollY + y); 11049 } 11050 11051 /** 11052 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11053 * animation to fade the scrollbars out after a default delay. If a subclass 11054 * provides animated scrolling, the start delay should equal the duration 11055 * of the scrolling animation.</p> 11056 * 11057 * <p>The animation starts only if at least one of the scrollbars is 11058 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11059 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11060 * this method returns true, and false otherwise. If the animation is 11061 * started, this method calls {@link #invalidate()}; in that case the 11062 * caller should not call {@link #invalidate()}.</p> 11063 * 11064 * <p>This method should be invoked every time a subclass directly updates 11065 * the scroll parameters.</p> 11066 * 11067 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11068 * and {@link #scrollTo(int, int)}.</p> 11069 * 11070 * @return true if the animation is played, false otherwise 11071 * 11072 * @see #awakenScrollBars(int) 11073 * @see #scrollBy(int, int) 11074 * @see #scrollTo(int, int) 11075 * @see #isHorizontalScrollBarEnabled() 11076 * @see #isVerticalScrollBarEnabled() 11077 * @see #setHorizontalScrollBarEnabled(boolean) 11078 * @see #setVerticalScrollBarEnabled(boolean) 11079 */ 11080 protected boolean awakenScrollBars() { 11081 return mScrollCache != null && 11082 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11083 } 11084 11085 /** 11086 * Trigger the scrollbars to draw. 11087 * This method differs from awakenScrollBars() only in its default duration. 11088 * initialAwakenScrollBars() will show the scroll bars for longer than 11089 * usual to give the user more of a chance to notice them. 11090 * 11091 * @return true if the animation is played, false otherwise. 11092 */ 11093 private boolean initialAwakenScrollBars() { 11094 return mScrollCache != null && 11095 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11096 } 11097 11098 /** 11099 * <p> 11100 * Trigger the scrollbars to draw. When invoked this method starts an 11101 * animation to fade the scrollbars out after a fixed delay. If a subclass 11102 * provides animated scrolling, the start delay should equal the duration of 11103 * the scrolling animation. 11104 * </p> 11105 * 11106 * <p> 11107 * The animation starts only if at least one of the scrollbars is enabled, 11108 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11109 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11110 * this method returns true, and false otherwise. If the animation is 11111 * started, this method calls {@link #invalidate()}; in that case the caller 11112 * should not call {@link #invalidate()}. 11113 * </p> 11114 * 11115 * <p> 11116 * This method should be invoked everytime a subclass directly updates the 11117 * scroll parameters. 11118 * </p> 11119 * 11120 * @param startDelay the delay, in milliseconds, after which the animation 11121 * should start; when the delay is 0, the animation starts 11122 * immediately 11123 * @return true if the animation is played, false otherwise 11124 * 11125 * @see #scrollBy(int, int) 11126 * @see #scrollTo(int, int) 11127 * @see #isHorizontalScrollBarEnabled() 11128 * @see #isVerticalScrollBarEnabled() 11129 * @see #setHorizontalScrollBarEnabled(boolean) 11130 * @see #setVerticalScrollBarEnabled(boolean) 11131 */ 11132 protected boolean awakenScrollBars(int startDelay) { 11133 return awakenScrollBars(startDelay, true); 11134 } 11135 11136 /** 11137 * <p> 11138 * Trigger the scrollbars to draw. When invoked this method starts an 11139 * animation to fade the scrollbars out after a fixed delay. If a subclass 11140 * provides animated scrolling, the start delay should equal the duration of 11141 * the scrolling animation. 11142 * </p> 11143 * 11144 * <p> 11145 * The animation starts only if at least one of the scrollbars is enabled, 11146 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11147 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11148 * this method returns true, and false otherwise. If the animation is 11149 * started, this method calls {@link #invalidate()} if the invalidate parameter 11150 * is set to true; in that case the caller 11151 * should not call {@link #invalidate()}. 11152 * </p> 11153 * 11154 * <p> 11155 * This method should be invoked everytime a subclass directly updates the 11156 * scroll parameters. 11157 * </p> 11158 * 11159 * @param startDelay the delay, in milliseconds, after which the animation 11160 * should start; when the delay is 0, the animation starts 11161 * immediately 11162 * 11163 * @param invalidate Wheter this method should call invalidate 11164 * 11165 * @return true if the animation is played, false otherwise 11166 * 11167 * @see #scrollBy(int, int) 11168 * @see #scrollTo(int, int) 11169 * @see #isHorizontalScrollBarEnabled() 11170 * @see #isVerticalScrollBarEnabled() 11171 * @see #setHorizontalScrollBarEnabled(boolean) 11172 * @see #setVerticalScrollBarEnabled(boolean) 11173 */ 11174 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11175 final ScrollabilityCache scrollCache = mScrollCache; 11176 11177 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11178 return false; 11179 } 11180 11181 if (scrollCache.scrollBar == null) { 11182 scrollCache.scrollBar = new ScrollBarDrawable(); 11183 } 11184 11185 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11186 11187 if (invalidate) { 11188 // Invalidate to show the scrollbars 11189 postInvalidateOnAnimation(); 11190 } 11191 11192 if (scrollCache.state == ScrollabilityCache.OFF) { 11193 // FIXME: this is copied from WindowManagerService. 11194 // We should get this value from the system when it 11195 // is possible to do so. 11196 final int KEY_REPEAT_FIRST_DELAY = 750; 11197 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11198 } 11199 11200 // Tell mScrollCache when we should start fading. This may 11201 // extend the fade start time if one was already scheduled 11202 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11203 scrollCache.fadeStartTime = fadeStartTime; 11204 scrollCache.state = ScrollabilityCache.ON; 11205 11206 // Schedule our fader to run, unscheduling any old ones first 11207 if (mAttachInfo != null) { 11208 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11209 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11210 } 11211 11212 return true; 11213 } 11214 11215 return false; 11216 } 11217 11218 /** 11219 * Do not invalidate views which are not visible and which are not running an animation. They 11220 * will not get drawn and they should not set dirty flags as if they will be drawn 11221 */ 11222 private boolean skipInvalidate() { 11223 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11224 (!(mParent instanceof ViewGroup) || 11225 !((ViewGroup) mParent).isViewTransitioning(this)); 11226 } 11227 11228 /** 11229 * Mark the area defined by dirty as needing to be drawn. If the view is 11230 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11231 * point in the future. 11232 * <p> 11233 * This must be called from a UI thread. To call from a non-UI thread, call 11234 * {@link #postInvalidate()}. 11235 * <p> 11236 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11237 * {@code dirty}. 11238 * 11239 * @param dirty the rectangle representing the bounds of the dirty region 11240 */ 11241 public void invalidate(Rect dirty) { 11242 final int scrollX = mScrollX; 11243 final int scrollY = mScrollY; 11244 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11245 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11246 } 11247 11248 /** 11249 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11250 * coordinates of the dirty rect are relative to the view. If the view is 11251 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11252 * point in the future. 11253 * <p> 11254 * This must be called from a UI thread. To call from a non-UI thread, call 11255 * {@link #postInvalidate()}. 11256 * 11257 * @param l the left position of the dirty region 11258 * @param t the top position of the dirty region 11259 * @param r the right position of the dirty region 11260 * @param b the bottom position of the dirty region 11261 */ 11262 public void invalidate(int l, int t, int r, int b) { 11263 final int scrollX = mScrollX; 11264 final int scrollY = mScrollY; 11265 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11266 } 11267 11268 /** 11269 * Invalidate the whole view. If the view is visible, 11270 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11271 * the future. 11272 * <p> 11273 * This must be called from a UI thread. To call from a non-UI thread, call 11274 * {@link #postInvalidate()}. 11275 */ 11276 public void invalidate() { 11277 invalidate(true); 11278 } 11279 11280 /** 11281 * This is where the invalidate() work actually happens. A full invalidate() 11282 * causes the drawing cache to be invalidated, but this function can be 11283 * called with invalidateCache set to false to skip that invalidation step 11284 * for cases that do not need it (for example, a component that remains at 11285 * the same dimensions with the same content). 11286 * 11287 * @param invalidateCache Whether the drawing cache for this view should be 11288 * invalidated as well. This is usually true for a full 11289 * invalidate, but may be set to false if the View's contents or 11290 * dimensions have not changed. 11291 */ 11292 void invalidate(boolean invalidateCache) { 11293 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11294 } 11295 11296 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11297 boolean fullInvalidate) { 11298 if (skipInvalidate()) { 11299 return; 11300 } 11301 11302 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11303 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11304 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11305 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11306 if (fullInvalidate) { 11307 mLastIsOpaque = isOpaque(); 11308 mPrivateFlags &= ~PFLAG_DRAWN; 11309 } 11310 11311 mPrivateFlags |= PFLAG_DIRTY; 11312 11313 if (invalidateCache) { 11314 mPrivateFlags |= PFLAG_INVALIDATED; 11315 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11316 } 11317 11318 // Propagate the damage rectangle to the parent view. 11319 final AttachInfo ai = mAttachInfo; 11320 final ViewParent p = mParent; 11321 if (p != null && ai != null && l < r && t < b) { 11322 final Rect damage = ai.mTmpInvalRect; 11323 damage.set(l, t, r, b); 11324 p.invalidateChild(this, damage); 11325 } 11326 11327 // Damage the entire projection receiver, if necessary. 11328 if (mBackground != null && mBackground.isProjected()) { 11329 final View receiver = getProjectionReceiver(); 11330 if (receiver != null) { 11331 receiver.damageInParent(); 11332 } 11333 } 11334 11335 // Damage the entire IsolatedZVolume recieving this view's shadow. 11336 if (isHardwareAccelerated() && getZ() != 0) { 11337 damageShadowReceiver(); 11338 } 11339 } 11340 } 11341 11342 /** 11343 * @return this view's projection receiver, or {@code null} if none exists 11344 */ 11345 private View getProjectionReceiver() { 11346 ViewParent p = getParent(); 11347 while (p != null && p instanceof View) { 11348 final View v = (View) p; 11349 if (v.isProjectionReceiver()) { 11350 return v; 11351 } 11352 p = p.getParent(); 11353 } 11354 11355 return null; 11356 } 11357 11358 /** 11359 * @return whether the view is a projection receiver 11360 */ 11361 private boolean isProjectionReceiver() { 11362 return mBackground != null; 11363 } 11364 11365 /** 11366 * Damage area of the screen that can be covered by this View's shadow. 11367 * 11368 * This method will guarantee that any changes to shadows cast by a View 11369 * are damaged on the screen for future redraw. 11370 */ 11371 private void damageShadowReceiver() { 11372 final AttachInfo ai = mAttachInfo; 11373 if (ai != null) { 11374 ViewParent p = getParent(); 11375 if (p != null && p instanceof ViewGroup) { 11376 final ViewGroup vg = (ViewGroup) p; 11377 vg.damageInParent(); 11378 } 11379 } 11380 } 11381 11382 /** 11383 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11384 * set any flags or handle all of the cases handled by the default invalidation methods. 11385 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11386 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11387 * walk up the hierarchy, transforming the dirty rect as necessary. 11388 * 11389 * The method also handles normal invalidation logic if display list properties are not 11390 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11391 * backup approach, to handle these cases used in the various property-setting methods. 11392 * 11393 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11394 * are not being used in this view 11395 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11396 * list properties are not being used in this view 11397 */ 11398 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11399 if (!isHardwareAccelerated() 11400 || !mRenderNode.isValid() 11401 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11402 if (invalidateParent) { 11403 invalidateParentCaches(); 11404 } 11405 if (forceRedraw) { 11406 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11407 } 11408 invalidate(false); 11409 } else { 11410 damageInParent(); 11411 } 11412 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 11413 damageShadowReceiver(); 11414 } 11415 } 11416 11417 /** 11418 * Tells the parent view to damage this view's bounds. 11419 * 11420 * @hide 11421 */ 11422 protected void damageInParent() { 11423 final AttachInfo ai = mAttachInfo; 11424 final ViewParent p = mParent; 11425 if (p != null && ai != null) { 11426 final Rect r = ai.mTmpInvalRect; 11427 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11428 if (mParent instanceof ViewGroup) { 11429 ((ViewGroup) mParent).damageChild(this, r); 11430 } else { 11431 mParent.invalidateChild(this, r); 11432 } 11433 } 11434 } 11435 11436 /** 11437 * Utility method to transform a given Rect by the current matrix of this view. 11438 */ 11439 void transformRect(final Rect rect) { 11440 if (!getMatrix().isIdentity()) { 11441 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11442 boundingRect.set(rect); 11443 getMatrix().mapRect(boundingRect); 11444 rect.set((int) Math.floor(boundingRect.left), 11445 (int) Math.floor(boundingRect.top), 11446 (int) Math.ceil(boundingRect.right), 11447 (int) Math.ceil(boundingRect.bottom)); 11448 } 11449 } 11450 11451 /** 11452 * Used to indicate that the parent of this view should clear its caches. This functionality 11453 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11454 * which is necessary when various parent-managed properties of the view change, such as 11455 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11456 * clears the parent caches and does not causes an invalidate event. 11457 * 11458 * @hide 11459 */ 11460 protected void invalidateParentCaches() { 11461 if (mParent instanceof View) { 11462 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11463 } 11464 } 11465 11466 /** 11467 * Used to indicate that the parent of this view should be invalidated. This functionality 11468 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11469 * which is necessary when various parent-managed properties of the view change, such as 11470 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11471 * an invalidation event to the parent. 11472 * 11473 * @hide 11474 */ 11475 protected void invalidateParentIfNeeded() { 11476 if (isHardwareAccelerated() && mParent instanceof View) { 11477 ((View) mParent).invalidate(true); 11478 } 11479 } 11480 11481 /** 11482 * @hide 11483 */ 11484 protected void invalidateParentIfNeededAndWasQuickRejected() { 11485 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 11486 // View was rejected last time it was drawn by its parent; this may have changed 11487 invalidateParentIfNeeded(); 11488 } 11489 } 11490 11491 /** 11492 * Indicates whether this View is opaque. An opaque View guarantees that it will 11493 * draw all the pixels overlapping its bounds using a fully opaque color. 11494 * 11495 * Subclasses of View should override this method whenever possible to indicate 11496 * whether an instance is opaque. Opaque Views are treated in a special way by 11497 * the View hierarchy, possibly allowing it to perform optimizations during 11498 * invalidate/draw passes. 11499 * 11500 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11501 */ 11502 @ViewDebug.ExportedProperty(category = "drawing") 11503 public boolean isOpaque() { 11504 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11505 getFinalAlpha() >= 1.0f; 11506 } 11507 11508 /** 11509 * @hide 11510 */ 11511 protected void computeOpaqueFlags() { 11512 // Opaque if: 11513 // - Has a background 11514 // - Background is opaque 11515 // - Doesn't have scrollbars or scrollbars overlay 11516 11517 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11518 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11519 } else { 11520 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11521 } 11522 11523 final int flags = mViewFlags; 11524 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11525 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11526 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11527 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11528 } else { 11529 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11530 } 11531 } 11532 11533 /** 11534 * @hide 11535 */ 11536 protected boolean hasOpaqueScrollbars() { 11537 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11538 } 11539 11540 /** 11541 * @return A handler associated with the thread running the View. This 11542 * handler can be used to pump events in the UI events queue. 11543 */ 11544 public Handler getHandler() { 11545 final AttachInfo attachInfo = mAttachInfo; 11546 if (attachInfo != null) { 11547 return attachInfo.mHandler; 11548 } 11549 return null; 11550 } 11551 11552 /** 11553 * Gets the view root associated with the View. 11554 * @return The view root, or null if none. 11555 * @hide 11556 */ 11557 public ViewRootImpl getViewRootImpl() { 11558 if (mAttachInfo != null) { 11559 return mAttachInfo.mViewRootImpl; 11560 } 11561 return null; 11562 } 11563 11564 /** 11565 * @hide 11566 */ 11567 public HardwareRenderer getHardwareRenderer() { 11568 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 11569 } 11570 11571 /** 11572 * <p>Causes the Runnable to be added to the message queue. 11573 * The runnable will be run on the user interface thread.</p> 11574 * 11575 * @param action The Runnable that will be executed. 11576 * 11577 * @return Returns true if the Runnable was successfully placed in to the 11578 * message queue. Returns false on failure, usually because the 11579 * looper processing the message queue is exiting. 11580 * 11581 * @see #postDelayed 11582 * @see #removeCallbacks 11583 */ 11584 public boolean post(Runnable action) { 11585 final AttachInfo attachInfo = mAttachInfo; 11586 if (attachInfo != null) { 11587 return attachInfo.mHandler.post(action); 11588 } 11589 // Assume that post will succeed later 11590 ViewRootImpl.getRunQueue().post(action); 11591 return true; 11592 } 11593 11594 /** 11595 * <p>Causes the Runnable to be added to the message queue, to be run 11596 * after the specified amount of time elapses. 11597 * The runnable will be run on the user interface thread.</p> 11598 * 11599 * @param action The Runnable that will be executed. 11600 * @param delayMillis The delay (in milliseconds) until the Runnable 11601 * will be executed. 11602 * 11603 * @return true if the Runnable was successfully placed in to the 11604 * message queue. Returns false on failure, usually because the 11605 * looper processing the message queue is exiting. Note that a 11606 * result of true does not mean the Runnable will be processed -- 11607 * if the looper is quit before the delivery time of the message 11608 * occurs then the message will be dropped. 11609 * 11610 * @see #post 11611 * @see #removeCallbacks 11612 */ 11613 public boolean postDelayed(Runnable action, long delayMillis) { 11614 final AttachInfo attachInfo = mAttachInfo; 11615 if (attachInfo != null) { 11616 return attachInfo.mHandler.postDelayed(action, delayMillis); 11617 } 11618 // Assume that post will succeed later 11619 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11620 return true; 11621 } 11622 11623 /** 11624 * <p>Causes the Runnable to execute on the next animation time step. 11625 * The runnable will be run on the user interface thread.</p> 11626 * 11627 * @param action The Runnable that will be executed. 11628 * 11629 * @see #postOnAnimationDelayed 11630 * @see #removeCallbacks 11631 */ 11632 public void postOnAnimation(Runnable action) { 11633 final AttachInfo attachInfo = mAttachInfo; 11634 if (attachInfo != null) { 11635 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11636 Choreographer.CALLBACK_ANIMATION, action, null); 11637 } else { 11638 // Assume that post will succeed later 11639 ViewRootImpl.getRunQueue().post(action); 11640 } 11641 } 11642 11643 /** 11644 * <p>Causes the Runnable to execute on the next animation time step, 11645 * after the specified amount of time elapses. 11646 * The runnable will be run on the user interface thread.</p> 11647 * 11648 * @param action The Runnable that will be executed. 11649 * @param delayMillis The delay (in milliseconds) until the Runnable 11650 * will be executed. 11651 * 11652 * @see #postOnAnimation 11653 * @see #removeCallbacks 11654 */ 11655 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11656 final AttachInfo attachInfo = mAttachInfo; 11657 if (attachInfo != null) { 11658 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11659 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11660 } else { 11661 // Assume that post will succeed later 11662 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11663 } 11664 } 11665 11666 /** 11667 * <p>Removes the specified Runnable from the message queue.</p> 11668 * 11669 * @param action The Runnable to remove from the message handling queue 11670 * 11671 * @return true if this view could ask the Handler to remove the Runnable, 11672 * false otherwise. When the returned value is true, the Runnable 11673 * may or may not have been actually removed from the message queue 11674 * (for instance, if the Runnable was not in the queue already.) 11675 * 11676 * @see #post 11677 * @see #postDelayed 11678 * @see #postOnAnimation 11679 * @see #postOnAnimationDelayed 11680 */ 11681 public boolean removeCallbacks(Runnable action) { 11682 if (action != null) { 11683 final AttachInfo attachInfo = mAttachInfo; 11684 if (attachInfo != null) { 11685 attachInfo.mHandler.removeCallbacks(action); 11686 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11687 Choreographer.CALLBACK_ANIMATION, action, null); 11688 } 11689 // Assume that post will succeed later 11690 ViewRootImpl.getRunQueue().removeCallbacks(action); 11691 } 11692 return true; 11693 } 11694 11695 /** 11696 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11697 * Use this to invalidate the View from a non-UI thread.</p> 11698 * 11699 * <p>This method can be invoked from outside of the UI thread 11700 * only when this View is attached to a window.</p> 11701 * 11702 * @see #invalidate() 11703 * @see #postInvalidateDelayed(long) 11704 */ 11705 public void postInvalidate() { 11706 postInvalidateDelayed(0); 11707 } 11708 11709 /** 11710 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11711 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11712 * 11713 * <p>This method can be invoked from outside of the UI thread 11714 * only when this View is attached to a window.</p> 11715 * 11716 * @param left The left coordinate of the rectangle to invalidate. 11717 * @param top The top coordinate of the rectangle to invalidate. 11718 * @param right The right coordinate of the rectangle to invalidate. 11719 * @param bottom The bottom coordinate of the rectangle to invalidate. 11720 * 11721 * @see #invalidate(int, int, int, int) 11722 * @see #invalidate(Rect) 11723 * @see #postInvalidateDelayed(long, int, int, int, int) 11724 */ 11725 public void postInvalidate(int left, int top, int right, int bottom) { 11726 postInvalidateDelayed(0, left, top, right, bottom); 11727 } 11728 11729 /** 11730 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11731 * loop. Waits for the specified amount of time.</p> 11732 * 11733 * <p>This method can be invoked from outside of the UI thread 11734 * only when this View is attached to a window.</p> 11735 * 11736 * @param delayMilliseconds the duration in milliseconds to delay the 11737 * invalidation by 11738 * 11739 * @see #invalidate() 11740 * @see #postInvalidate() 11741 */ 11742 public void postInvalidateDelayed(long delayMilliseconds) { 11743 // We try only with the AttachInfo because there's no point in invalidating 11744 // if we are not attached to our window 11745 final AttachInfo attachInfo = mAttachInfo; 11746 if (attachInfo != null) { 11747 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11748 } 11749 } 11750 11751 /** 11752 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11753 * through the event loop. Waits for the specified amount of time.</p> 11754 * 11755 * <p>This method can be invoked from outside of the UI thread 11756 * only when this View is attached to a window.</p> 11757 * 11758 * @param delayMilliseconds the duration in milliseconds to delay the 11759 * invalidation by 11760 * @param left The left coordinate of the rectangle to invalidate. 11761 * @param top The top coordinate of the rectangle to invalidate. 11762 * @param right The right coordinate of the rectangle to invalidate. 11763 * @param bottom The bottom coordinate of the rectangle to invalidate. 11764 * 11765 * @see #invalidate(int, int, int, int) 11766 * @see #invalidate(Rect) 11767 * @see #postInvalidate(int, int, int, int) 11768 */ 11769 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11770 int right, int bottom) { 11771 11772 // We try only with the AttachInfo because there's no point in invalidating 11773 // if we are not attached to our window 11774 final AttachInfo attachInfo = mAttachInfo; 11775 if (attachInfo != null) { 11776 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11777 info.target = this; 11778 info.left = left; 11779 info.top = top; 11780 info.right = right; 11781 info.bottom = bottom; 11782 11783 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11784 } 11785 } 11786 11787 /** 11788 * <p>Cause an invalidate to happen on the next animation time step, typically the 11789 * next display frame.</p> 11790 * 11791 * <p>This method can be invoked from outside of the UI thread 11792 * only when this View is attached to a window.</p> 11793 * 11794 * @see #invalidate() 11795 */ 11796 public void postInvalidateOnAnimation() { 11797 // We try only with the AttachInfo because there's no point in invalidating 11798 // if we are not attached to our window 11799 final AttachInfo attachInfo = mAttachInfo; 11800 if (attachInfo != null) { 11801 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11802 } 11803 } 11804 11805 /** 11806 * <p>Cause an invalidate of the specified area to happen on the next animation 11807 * time step, typically the next display frame.</p> 11808 * 11809 * <p>This method can be invoked from outside of the UI thread 11810 * only when this View is attached to a window.</p> 11811 * 11812 * @param left The left coordinate of the rectangle to invalidate. 11813 * @param top The top coordinate of the rectangle to invalidate. 11814 * @param right The right coordinate of the rectangle to invalidate. 11815 * @param bottom The bottom coordinate of the rectangle to invalidate. 11816 * 11817 * @see #invalidate(int, int, int, int) 11818 * @see #invalidate(Rect) 11819 */ 11820 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11821 // We try only with the AttachInfo because there's no point in invalidating 11822 // if we are not attached to our window 11823 final AttachInfo attachInfo = mAttachInfo; 11824 if (attachInfo != null) { 11825 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11826 info.target = this; 11827 info.left = left; 11828 info.top = top; 11829 info.right = right; 11830 info.bottom = bottom; 11831 11832 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11833 } 11834 } 11835 11836 /** 11837 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11838 * This event is sent at most once every 11839 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11840 */ 11841 private void postSendViewScrolledAccessibilityEventCallback() { 11842 if (mSendViewScrolledAccessibilityEvent == null) { 11843 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11844 } 11845 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11846 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11847 postDelayed(mSendViewScrolledAccessibilityEvent, 11848 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11849 } 11850 } 11851 11852 /** 11853 * Called by a parent to request that a child update its values for mScrollX 11854 * and mScrollY if necessary. This will typically be done if the child is 11855 * animating a scroll using a {@link android.widget.Scroller Scroller} 11856 * object. 11857 */ 11858 public void computeScroll() { 11859 } 11860 11861 /** 11862 * <p>Indicate whether the horizontal edges are faded when the view is 11863 * scrolled horizontally.</p> 11864 * 11865 * @return true if the horizontal edges should are faded on scroll, false 11866 * otherwise 11867 * 11868 * @see #setHorizontalFadingEdgeEnabled(boolean) 11869 * 11870 * @attr ref android.R.styleable#View_requiresFadingEdge 11871 */ 11872 public boolean isHorizontalFadingEdgeEnabled() { 11873 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11874 } 11875 11876 /** 11877 * <p>Define whether the horizontal edges should be faded when this view 11878 * is scrolled horizontally.</p> 11879 * 11880 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11881 * be faded when the view is scrolled 11882 * horizontally 11883 * 11884 * @see #isHorizontalFadingEdgeEnabled() 11885 * 11886 * @attr ref android.R.styleable#View_requiresFadingEdge 11887 */ 11888 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11889 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11890 if (horizontalFadingEdgeEnabled) { 11891 initScrollCache(); 11892 } 11893 11894 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11895 } 11896 } 11897 11898 /** 11899 * <p>Indicate whether the vertical edges are faded when the view is 11900 * scrolled horizontally.</p> 11901 * 11902 * @return true if the vertical edges should are faded on scroll, false 11903 * otherwise 11904 * 11905 * @see #setVerticalFadingEdgeEnabled(boolean) 11906 * 11907 * @attr ref android.R.styleable#View_requiresFadingEdge 11908 */ 11909 public boolean isVerticalFadingEdgeEnabled() { 11910 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 11911 } 11912 11913 /** 11914 * <p>Define whether the vertical edges should be faded when this view 11915 * is scrolled vertically.</p> 11916 * 11917 * @param verticalFadingEdgeEnabled true if the vertical edges should 11918 * be faded when the view is scrolled 11919 * vertically 11920 * 11921 * @see #isVerticalFadingEdgeEnabled() 11922 * 11923 * @attr ref android.R.styleable#View_requiresFadingEdge 11924 */ 11925 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 11926 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 11927 if (verticalFadingEdgeEnabled) { 11928 initScrollCache(); 11929 } 11930 11931 mViewFlags ^= FADING_EDGE_VERTICAL; 11932 } 11933 } 11934 11935 /** 11936 * Returns the strength, or intensity, of the top faded edge. The strength is 11937 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11938 * returns 0.0 or 1.0 but no value in between. 11939 * 11940 * Subclasses should override this method to provide a smoother fade transition 11941 * when scrolling occurs. 11942 * 11943 * @return the intensity of the top fade as a float between 0.0f and 1.0f 11944 */ 11945 protected float getTopFadingEdgeStrength() { 11946 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 11947 } 11948 11949 /** 11950 * Returns the strength, or intensity, of the bottom faded edge. The strength is 11951 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11952 * returns 0.0 or 1.0 but no value in between. 11953 * 11954 * Subclasses should override this method to provide a smoother fade transition 11955 * when scrolling occurs. 11956 * 11957 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 11958 */ 11959 protected float getBottomFadingEdgeStrength() { 11960 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 11961 computeVerticalScrollRange() ? 1.0f : 0.0f; 11962 } 11963 11964 /** 11965 * Returns the strength, or intensity, of the left faded edge. The strength is 11966 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11967 * returns 0.0 or 1.0 but no value in between. 11968 * 11969 * Subclasses should override this method to provide a smoother fade transition 11970 * when scrolling occurs. 11971 * 11972 * @return the intensity of the left fade as a float between 0.0f and 1.0f 11973 */ 11974 protected float getLeftFadingEdgeStrength() { 11975 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 11976 } 11977 11978 /** 11979 * Returns the strength, or intensity, of the right faded edge. The strength is 11980 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11981 * returns 0.0 or 1.0 but no value in between. 11982 * 11983 * Subclasses should override this method to provide a smoother fade transition 11984 * when scrolling occurs. 11985 * 11986 * @return the intensity of the right fade as a float between 0.0f and 1.0f 11987 */ 11988 protected float getRightFadingEdgeStrength() { 11989 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 11990 computeHorizontalScrollRange() ? 1.0f : 0.0f; 11991 } 11992 11993 /** 11994 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 11995 * scrollbar is not drawn by default.</p> 11996 * 11997 * @return true if the horizontal scrollbar should be painted, false 11998 * otherwise 11999 * 12000 * @see #setHorizontalScrollBarEnabled(boolean) 12001 */ 12002 public boolean isHorizontalScrollBarEnabled() { 12003 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12004 } 12005 12006 /** 12007 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12008 * scrollbar is not drawn by default.</p> 12009 * 12010 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12011 * be painted 12012 * 12013 * @see #isHorizontalScrollBarEnabled() 12014 */ 12015 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12016 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12017 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12018 computeOpaqueFlags(); 12019 resolvePadding(); 12020 } 12021 } 12022 12023 /** 12024 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12025 * scrollbar is not drawn by default.</p> 12026 * 12027 * @return true if the vertical scrollbar should be painted, false 12028 * otherwise 12029 * 12030 * @see #setVerticalScrollBarEnabled(boolean) 12031 */ 12032 public boolean isVerticalScrollBarEnabled() { 12033 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12034 } 12035 12036 /** 12037 * <p>Define whether the vertical scrollbar should be drawn or not. The 12038 * scrollbar is not drawn by default.</p> 12039 * 12040 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12041 * be painted 12042 * 12043 * @see #isVerticalScrollBarEnabled() 12044 */ 12045 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12046 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12047 mViewFlags ^= SCROLLBARS_VERTICAL; 12048 computeOpaqueFlags(); 12049 resolvePadding(); 12050 } 12051 } 12052 12053 /** 12054 * @hide 12055 */ 12056 protected void recomputePadding() { 12057 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12058 } 12059 12060 /** 12061 * Define whether scrollbars will fade when the view is not scrolling. 12062 * 12063 * @param fadeScrollbars wheter to enable fading 12064 * 12065 * @attr ref android.R.styleable#View_fadeScrollbars 12066 */ 12067 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12068 initScrollCache(); 12069 final ScrollabilityCache scrollabilityCache = mScrollCache; 12070 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12071 if (fadeScrollbars) { 12072 scrollabilityCache.state = ScrollabilityCache.OFF; 12073 } else { 12074 scrollabilityCache.state = ScrollabilityCache.ON; 12075 } 12076 } 12077 12078 /** 12079 * 12080 * Returns true if scrollbars will fade when this view is not scrolling 12081 * 12082 * @return true if scrollbar fading is enabled 12083 * 12084 * @attr ref android.R.styleable#View_fadeScrollbars 12085 */ 12086 public boolean isScrollbarFadingEnabled() { 12087 return mScrollCache != null && mScrollCache.fadeScrollBars; 12088 } 12089 12090 /** 12091 * 12092 * Returns the delay before scrollbars fade. 12093 * 12094 * @return the delay before scrollbars fade 12095 * 12096 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12097 */ 12098 public int getScrollBarDefaultDelayBeforeFade() { 12099 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12100 mScrollCache.scrollBarDefaultDelayBeforeFade; 12101 } 12102 12103 /** 12104 * Define the delay before scrollbars fade. 12105 * 12106 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12107 * 12108 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12109 */ 12110 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12111 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12112 } 12113 12114 /** 12115 * 12116 * Returns the scrollbar fade duration. 12117 * 12118 * @return the scrollbar fade duration 12119 * 12120 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12121 */ 12122 public int getScrollBarFadeDuration() { 12123 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12124 mScrollCache.scrollBarFadeDuration; 12125 } 12126 12127 /** 12128 * Define the scrollbar fade duration. 12129 * 12130 * @param scrollBarFadeDuration - the scrollbar fade duration 12131 * 12132 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12133 */ 12134 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12135 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12136 } 12137 12138 /** 12139 * 12140 * Returns the scrollbar size. 12141 * 12142 * @return the scrollbar size 12143 * 12144 * @attr ref android.R.styleable#View_scrollbarSize 12145 */ 12146 public int getScrollBarSize() { 12147 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12148 mScrollCache.scrollBarSize; 12149 } 12150 12151 /** 12152 * Define the scrollbar size. 12153 * 12154 * @param scrollBarSize - the scrollbar size 12155 * 12156 * @attr ref android.R.styleable#View_scrollbarSize 12157 */ 12158 public void setScrollBarSize(int scrollBarSize) { 12159 getScrollCache().scrollBarSize = scrollBarSize; 12160 } 12161 12162 /** 12163 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12164 * inset. When inset, they add to the padding of the view. And the scrollbars 12165 * can be drawn inside the padding area or on the edge of the view. For example, 12166 * if a view has a background drawable and you want to draw the scrollbars 12167 * inside the padding specified by the drawable, you can use 12168 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12169 * appear at the edge of the view, ignoring the padding, then you can use 12170 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12171 * @param style the style of the scrollbars. Should be one of 12172 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12173 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12174 * @see #SCROLLBARS_INSIDE_OVERLAY 12175 * @see #SCROLLBARS_INSIDE_INSET 12176 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12177 * @see #SCROLLBARS_OUTSIDE_INSET 12178 * 12179 * @attr ref android.R.styleable#View_scrollbarStyle 12180 */ 12181 public void setScrollBarStyle(@ScrollBarStyle int style) { 12182 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12183 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12184 computeOpaqueFlags(); 12185 resolvePadding(); 12186 } 12187 } 12188 12189 /** 12190 * <p>Returns the current scrollbar style.</p> 12191 * @return the current scrollbar style 12192 * @see #SCROLLBARS_INSIDE_OVERLAY 12193 * @see #SCROLLBARS_INSIDE_INSET 12194 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12195 * @see #SCROLLBARS_OUTSIDE_INSET 12196 * 12197 * @attr ref android.R.styleable#View_scrollbarStyle 12198 */ 12199 @ViewDebug.ExportedProperty(mapping = { 12200 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12201 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12202 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12203 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12204 }) 12205 @ScrollBarStyle 12206 public int getScrollBarStyle() { 12207 return mViewFlags & SCROLLBARS_STYLE_MASK; 12208 } 12209 12210 /** 12211 * <p>Compute the horizontal range that the horizontal scrollbar 12212 * represents.</p> 12213 * 12214 * <p>The range is expressed in arbitrary units that must be the same as the 12215 * units used by {@link #computeHorizontalScrollExtent()} and 12216 * {@link #computeHorizontalScrollOffset()}.</p> 12217 * 12218 * <p>The default range is the drawing width of this view.</p> 12219 * 12220 * @return the total horizontal range represented by the horizontal 12221 * scrollbar 12222 * 12223 * @see #computeHorizontalScrollExtent() 12224 * @see #computeHorizontalScrollOffset() 12225 * @see android.widget.ScrollBarDrawable 12226 */ 12227 protected int computeHorizontalScrollRange() { 12228 return getWidth(); 12229 } 12230 12231 /** 12232 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12233 * within the horizontal range. This value is used to compute the position 12234 * of the thumb within the scrollbar's track.</p> 12235 * 12236 * <p>The range is expressed in arbitrary units that must be the same as the 12237 * units used by {@link #computeHorizontalScrollRange()} and 12238 * {@link #computeHorizontalScrollExtent()}.</p> 12239 * 12240 * <p>The default offset is the scroll offset of this view.</p> 12241 * 12242 * @return the horizontal offset of the scrollbar's thumb 12243 * 12244 * @see #computeHorizontalScrollRange() 12245 * @see #computeHorizontalScrollExtent() 12246 * @see android.widget.ScrollBarDrawable 12247 */ 12248 protected int computeHorizontalScrollOffset() { 12249 return mScrollX; 12250 } 12251 12252 /** 12253 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12254 * within the horizontal range. This value is used to compute the length 12255 * of the thumb within the scrollbar's track.</p> 12256 * 12257 * <p>The range is expressed in arbitrary units that must be the same as the 12258 * units used by {@link #computeHorizontalScrollRange()} and 12259 * {@link #computeHorizontalScrollOffset()}.</p> 12260 * 12261 * <p>The default extent is the drawing width of this view.</p> 12262 * 12263 * @return the horizontal extent of the scrollbar's thumb 12264 * 12265 * @see #computeHorizontalScrollRange() 12266 * @see #computeHorizontalScrollOffset() 12267 * @see android.widget.ScrollBarDrawable 12268 */ 12269 protected int computeHorizontalScrollExtent() { 12270 return getWidth(); 12271 } 12272 12273 /** 12274 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12275 * 12276 * <p>The range is expressed in arbitrary units that must be the same as the 12277 * units used by {@link #computeVerticalScrollExtent()} and 12278 * {@link #computeVerticalScrollOffset()}.</p> 12279 * 12280 * @return the total vertical range represented by the vertical scrollbar 12281 * 12282 * <p>The default range is the drawing height of this view.</p> 12283 * 12284 * @see #computeVerticalScrollExtent() 12285 * @see #computeVerticalScrollOffset() 12286 * @see android.widget.ScrollBarDrawable 12287 */ 12288 protected int computeVerticalScrollRange() { 12289 return getHeight(); 12290 } 12291 12292 /** 12293 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12294 * within the horizontal range. This value is used to compute the position 12295 * of the thumb within the scrollbar's track.</p> 12296 * 12297 * <p>The range is expressed in arbitrary units that must be the same as the 12298 * units used by {@link #computeVerticalScrollRange()} and 12299 * {@link #computeVerticalScrollExtent()}.</p> 12300 * 12301 * <p>The default offset is the scroll offset of this view.</p> 12302 * 12303 * @return the vertical offset of the scrollbar's thumb 12304 * 12305 * @see #computeVerticalScrollRange() 12306 * @see #computeVerticalScrollExtent() 12307 * @see android.widget.ScrollBarDrawable 12308 */ 12309 protected int computeVerticalScrollOffset() { 12310 return mScrollY; 12311 } 12312 12313 /** 12314 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12315 * within the vertical range. This value is used to compute the length 12316 * of the thumb within the scrollbar's track.</p> 12317 * 12318 * <p>The range is expressed in arbitrary units that must be the same as the 12319 * units used by {@link #computeVerticalScrollRange()} and 12320 * {@link #computeVerticalScrollOffset()}.</p> 12321 * 12322 * <p>The default extent is the drawing height of this view.</p> 12323 * 12324 * @return the vertical extent of the scrollbar's thumb 12325 * 12326 * @see #computeVerticalScrollRange() 12327 * @see #computeVerticalScrollOffset() 12328 * @see android.widget.ScrollBarDrawable 12329 */ 12330 protected int computeVerticalScrollExtent() { 12331 return getHeight(); 12332 } 12333 12334 /** 12335 * Check if this view can be scrolled horizontally in a certain direction. 12336 * 12337 * @param direction Negative to check scrolling left, positive to check scrolling right. 12338 * @return true if this view can be scrolled in the specified direction, false otherwise. 12339 */ 12340 public boolean canScrollHorizontally(int direction) { 12341 final int offset = computeHorizontalScrollOffset(); 12342 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12343 if (range == 0) return false; 12344 if (direction < 0) { 12345 return offset > 0; 12346 } else { 12347 return offset < range - 1; 12348 } 12349 } 12350 12351 /** 12352 * Check if this view can be scrolled vertically in a certain direction. 12353 * 12354 * @param direction Negative to check scrolling up, positive to check scrolling down. 12355 * @return true if this view can be scrolled in the specified direction, false otherwise. 12356 */ 12357 public boolean canScrollVertically(int direction) { 12358 final int offset = computeVerticalScrollOffset(); 12359 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12360 if (range == 0) return false; 12361 if (direction < 0) { 12362 return offset > 0; 12363 } else { 12364 return offset < range - 1; 12365 } 12366 } 12367 12368 /** 12369 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12370 * scrollbars are painted only if they have been awakened first.</p> 12371 * 12372 * @param canvas the canvas on which to draw the scrollbars 12373 * 12374 * @see #awakenScrollBars(int) 12375 */ 12376 protected final void onDrawScrollBars(Canvas canvas) { 12377 // scrollbars are drawn only when the animation is running 12378 final ScrollabilityCache cache = mScrollCache; 12379 if (cache != null) { 12380 12381 int state = cache.state; 12382 12383 if (state == ScrollabilityCache.OFF) { 12384 return; 12385 } 12386 12387 boolean invalidate = false; 12388 12389 if (state == ScrollabilityCache.FADING) { 12390 // We're fading -- get our fade interpolation 12391 if (cache.interpolatorValues == null) { 12392 cache.interpolatorValues = new float[1]; 12393 } 12394 12395 float[] values = cache.interpolatorValues; 12396 12397 // Stops the animation if we're done 12398 if (cache.scrollBarInterpolator.timeToValues(values) == 12399 Interpolator.Result.FREEZE_END) { 12400 cache.state = ScrollabilityCache.OFF; 12401 } else { 12402 cache.scrollBar.setAlpha(Math.round(values[0])); 12403 } 12404 12405 // This will make the scroll bars inval themselves after 12406 // drawing. We only want this when we're fading so that 12407 // we prevent excessive redraws 12408 invalidate = true; 12409 } else { 12410 // We're just on -- but we may have been fading before so 12411 // reset alpha 12412 cache.scrollBar.setAlpha(255); 12413 } 12414 12415 12416 final int viewFlags = mViewFlags; 12417 12418 final boolean drawHorizontalScrollBar = 12419 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12420 final boolean drawVerticalScrollBar = 12421 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12422 && !isVerticalScrollBarHidden(); 12423 12424 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12425 final int width = mRight - mLeft; 12426 final int height = mBottom - mTop; 12427 12428 final ScrollBarDrawable scrollBar = cache.scrollBar; 12429 12430 final int scrollX = mScrollX; 12431 final int scrollY = mScrollY; 12432 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12433 12434 int left; 12435 int top; 12436 int right; 12437 int bottom; 12438 12439 if (drawHorizontalScrollBar) { 12440 int size = scrollBar.getSize(false); 12441 if (size <= 0) { 12442 size = cache.scrollBarSize; 12443 } 12444 12445 scrollBar.setParameters(computeHorizontalScrollRange(), 12446 computeHorizontalScrollOffset(), 12447 computeHorizontalScrollExtent(), false); 12448 final int verticalScrollBarGap = drawVerticalScrollBar ? 12449 getVerticalScrollbarWidth() : 0; 12450 top = scrollY + height - size - (mUserPaddingBottom & inside); 12451 left = scrollX + (mPaddingLeft & inside); 12452 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12453 bottom = top + size; 12454 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12455 if (invalidate) { 12456 invalidate(left, top, right, bottom); 12457 } 12458 } 12459 12460 if (drawVerticalScrollBar) { 12461 int size = scrollBar.getSize(true); 12462 if (size <= 0) { 12463 size = cache.scrollBarSize; 12464 } 12465 12466 scrollBar.setParameters(computeVerticalScrollRange(), 12467 computeVerticalScrollOffset(), 12468 computeVerticalScrollExtent(), true); 12469 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12470 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12471 verticalScrollbarPosition = isLayoutRtl() ? 12472 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12473 } 12474 switch (verticalScrollbarPosition) { 12475 default: 12476 case SCROLLBAR_POSITION_RIGHT: 12477 left = scrollX + width - size - (mUserPaddingRight & inside); 12478 break; 12479 case SCROLLBAR_POSITION_LEFT: 12480 left = scrollX + (mUserPaddingLeft & inside); 12481 break; 12482 } 12483 top = scrollY + (mPaddingTop & inside); 12484 right = left + size; 12485 bottom = scrollY + height - (mUserPaddingBottom & inside); 12486 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12487 if (invalidate) { 12488 invalidate(left, top, right, bottom); 12489 } 12490 } 12491 } 12492 } 12493 } 12494 12495 /** 12496 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12497 * FastScroller is visible. 12498 * @return whether to temporarily hide the vertical scrollbar 12499 * @hide 12500 */ 12501 protected boolean isVerticalScrollBarHidden() { 12502 return false; 12503 } 12504 12505 /** 12506 * <p>Draw the horizontal scrollbar if 12507 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12508 * 12509 * @param canvas the canvas on which to draw the scrollbar 12510 * @param scrollBar the scrollbar's drawable 12511 * 12512 * @see #isHorizontalScrollBarEnabled() 12513 * @see #computeHorizontalScrollRange() 12514 * @see #computeHorizontalScrollExtent() 12515 * @see #computeHorizontalScrollOffset() 12516 * @see android.widget.ScrollBarDrawable 12517 * @hide 12518 */ 12519 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12520 int l, int t, int r, int b) { 12521 scrollBar.setBounds(l, t, r, b); 12522 scrollBar.draw(canvas); 12523 } 12524 12525 /** 12526 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12527 * returns true.</p> 12528 * 12529 * @param canvas the canvas on which to draw the scrollbar 12530 * @param scrollBar the scrollbar's drawable 12531 * 12532 * @see #isVerticalScrollBarEnabled() 12533 * @see #computeVerticalScrollRange() 12534 * @see #computeVerticalScrollExtent() 12535 * @see #computeVerticalScrollOffset() 12536 * @see android.widget.ScrollBarDrawable 12537 * @hide 12538 */ 12539 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12540 int l, int t, int r, int b) { 12541 scrollBar.setBounds(l, t, r, b); 12542 scrollBar.draw(canvas); 12543 } 12544 12545 /** 12546 * Implement this to do your drawing. 12547 * 12548 * @param canvas the canvas on which the background will be drawn 12549 */ 12550 protected void onDraw(Canvas canvas) { 12551 } 12552 12553 /* 12554 * Caller is responsible for calling requestLayout if necessary. 12555 * (This allows addViewInLayout to not request a new layout.) 12556 */ 12557 void assignParent(ViewParent parent) { 12558 if (mParent == null) { 12559 mParent = parent; 12560 } else if (parent == null) { 12561 mParent = null; 12562 } else { 12563 throw new RuntimeException("view " + this + " being added, but" 12564 + " it already has a parent"); 12565 } 12566 } 12567 12568 /** 12569 * This is called when the view is attached to a window. At this point it 12570 * has a Surface and will start drawing. Note that this function is 12571 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12572 * however it may be called any time before the first onDraw -- including 12573 * before or after {@link #onMeasure(int, int)}. 12574 * 12575 * @see #onDetachedFromWindow() 12576 */ 12577 protected void onAttachedToWindow() { 12578 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12579 mParent.requestTransparentRegion(this); 12580 } 12581 12582 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12583 initialAwakenScrollBars(); 12584 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12585 } 12586 12587 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12588 12589 jumpDrawablesToCurrentState(); 12590 12591 resetSubtreeAccessibilityStateChanged(); 12592 12593 if (isFocused()) { 12594 InputMethodManager imm = InputMethodManager.peekInstance(); 12595 imm.focusIn(this); 12596 } 12597 } 12598 12599 /** 12600 * Resolve all RTL related properties. 12601 * 12602 * @return true if resolution of RTL properties has been done 12603 * 12604 * @hide 12605 */ 12606 public boolean resolveRtlPropertiesIfNeeded() { 12607 if (!needRtlPropertiesResolution()) return false; 12608 12609 // Order is important here: LayoutDirection MUST be resolved first 12610 if (!isLayoutDirectionResolved()) { 12611 resolveLayoutDirection(); 12612 resolveLayoutParams(); 12613 } 12614 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12615 if (!isTextDirectionResolved()) { 12616 resolveTextDirection(); 12617 } 12618 if (!isTextAlignmentResolved()) { 12619 resolveTextAlignment(); 12620 } 12621 // Should resolve Drawables before Padding because we need the layout direction of the 12622 // Drawable to correctly resolve Padding. 12623 if (!isDrawablesResolved()) { 12624 resolveDrawables(); 12625 } 12626 if (!isPaddingResolved()) { 12627 resolvePadding(); 12628 } 12629 onRtlPropertiesChanged(getLayoutDirection()); 12630 return true; 12631 } 12632 12633 /** 12634 * Reset resolution of all RTL related properties. 12635 * 12636 * @hide 12637 */ 12638 public void resetRtlProperties() { 12639 resetResolvedLayoutDirection(); 12640 resetResolvedTextDirection(); 12641 resetResolvedTextAlignment(); 12642 resetResolvedPadding(); 12643 resetResolvedDrawables(); 12644 } 12645 12646 /** 12647 * @see #onScreenStateChanged(int) 12648 */ 12649 void dispatchScreenStateChanged(int screenState) { 12650 onScreenStateChanged(screenState); 12651 } 12652 12653 /** 12654 * This method is called whenever the state of the screen this view is 12655 * attached to changes. A state change will usually occurs when the screen 12656 * turns on or off (whether it happens automatically or the user does it 12657 * manually.) 12658 * 12659 * @param screenState The new state of the screen. Can be either 12660 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12661 */ 12662 public void onScreenStateChanged(int screenState) { 12663 } 12664 12665 /** 12666 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12667 */ 12668 private boolean hasRtlSupport() { 12669 return mContext.getApplicationInfo().hasRtlSupport(); 12670 } 12671 12672 /** 12673 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12674 * RTL not supported) 12675 */ 12676 private boolean isRtlCompatibilityMode() { 12677 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12678 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12679 } 12680 12681 /** 12682 * @return true if RTL properties need resolution. 12683 * 12684 */ 12685 private boolean needRtlPropertiesResolution() { 12686 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12687 } 12688 12689 /** 12690 * Called when any RTL property (layout direction or text direction or text alignment) has 12691 * been changed. 12692 * 12693 * Subclasses need to override this method to take care of cached information that depends on the 12694 * resolved layout direction, or to inform child views that inherit their layout direction. 12695 * 12696 * The default implementation does nothing. 12697 * 12698 * @param layoutDirection the direction of the layout 12699 * 12700 * @see #LAYOUT_DIRECTION_LTR 12701 * @see #LAYOUT_DIRECTION_RTL 12702 */ 12703 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 12704 } 12705 12706 /** 12707 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12708 * that the parent directionality can and will be resolved before its children. 12709 * 12710 * @return true if resolution has been done, false otherwise. 12711 * 12712 * @hide 12713 */ 12714 public boolean resolveLayoutDirection() { 12715 // Clear any previous layout direction resolution 12716 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12717 12718 if (hasRtlSupport()) { 12719 // Set resolved depending on layout direction 12720 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12721 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12722 case LAYOUT_DIRECTION_INHERIT: 12723 // We cannot resolve yet. LTR is by default and let the resolution happen again 12724 // later to get the correct resolved value 12725 if (!canResolveLayoutDirection()) return false; 12726 12727 // Parent has not yet resolved, LTR is still the default 12728 try { 12729 if (!mParent.isLayoutDirectionResolved()) return false; 12730 12731 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12732 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12733 } 12734 } catch (AbstractMethodError e) { 12735 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12736 " does not fully implement ViewParent", e); 12737 } 12738 break; 12739 case LAYOUT_DIRECTION_RTL: 12740 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12741 break; 12742 case LAYOUT_DIRECTION_LOCALE: 12743 if((LAYOUT_DIRECTION_RTL == 12744 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12745 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12746 } 12747 break; 12748 default: 12749 // Nothing to do, LTR by default 12750 } 12751 } 12752 12753 // Set to resolved 12754 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12755 return true; 12756 } 12757 12758 /** 12759 * Check if layout direction resolution can be done. 12760 * 12761 * @return true if layout direction resolution can be done otherwise return false. 12762 */ 12763 public boolean canResolveLayoutDirection() { 12764 switch (getRawLayoutDirection()) { 12765 case LAYOUT_DIRECTION_INHERIT: 12766 if (mParent != null) { 12767 try { 12768 return mParent.canResolveLayoutDirection(); 12769 } catch (AbstractMethodError e) { 12770 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12771 " does not fully implement ViewParent", e); 12772 } 12773 } 12774 return false; 12775 12776 default: 12777 return true; 12778 } 12779 } 12780 12781 /** 12782 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12783 * {@link #onMeasure(int, int)}. 12784 * 12785 * @hide 12786 */ 12787 public void resetResolvedLayoutDirection() { 12788 // Reset the current resolved bits 12789 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12790 } 12791 12792 /** 12793 * @return true if the layout direction is inherited. 12794 * 12795 * @hide 12796 */ 12797 public boolean isLayoutDirectionInherited() { 12798 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12799 } 12800 12801 /** 12802 * @return true if layout direction has been resolved. 12803 */ 12804 public boolean isLayoutDirectionResolved() { 12805 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12806 } 12807 12808 /** 12809 * Return if padding has been resolved 12810 * 12811 * @hide 12812 */ 12813 boolean isPaddingResolved() { 12814 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12815 } 12816 12817 /** 12818 * Resolves padding depending on layout direction, if applicable, and 12819 * recomputes internal padding values to adjust for scroll bars. 12820 * 12821 * @hide 12822 */ 12823 public void resolvePadding() { 12824 final int resolvedLayoutDirection = getLayoutDirection(); 12825 12826 if (!isRtlCompatibilityMode()) { 12827 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12828 // If start / end padding are defined, they will be resolved (hence overriding) to 12829 // left / right or right / left depending on the resolved layout direction. 12830 // If start / end padding are not defined, use the left / right ones. 12831 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 12832 Rect padding = sThreadLocal.get(); 12833 if (padding == null) { 12834 padding = new Rect(); 12835 sThreadLocal.set(padding); 12836 } 12837 mBackground.getPadding(padding); 12838 if (!mLeftPaddingDefined) { 12839 mUserPaddingLeftInitial = padding.left; 12840 } 12841 if (!mRightPaddingDefined) { 12842 mUserPaddingRightInitial = padding.right; 12843 } 12844 } 12845 switch (resolvedLayoutDirection) { 12846 case LAYOUT_DIRECTION_RTL: 12847 if (mUserPaddingStart != UNDEFINED_PADDING) { 12848 mUserPaddingRight = mUserPaddingStart; 12849 } else { 12850 mUserPaddingRight = mUserPaddingRightInitial; 12851 } 12852 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12853 mUserPaddingLeft = mUserPaddingEnd; 12854 } else { 12855 mUserPaddingLeft = mUserPaddingLeftInitial; 12856 } 12857 break; 12858 case LAYOUT_DIRECTION_LTR: 12859 default: 12860 if (mUserPaddingStart != UNDEFINED_PADDING) { 12861 mUserPaddingLeft = mUserPaddingStart; 12862 } else { 12863 mUserPaddingLeft = mUserPaddingLeftInitial; 12864 } 12865 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12866 mUserPaddingRight = mUserPaddingEnd; 12867 } else { 12868 mUserPaddingRight = mUserPaddingRightInitial; 12869 } 12870 } 12871 12872 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12873 } 12874 12875 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12876 onRtlPropertiesChanged(resolvedLayoutDirection); 12877 12878 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12879 } 12880 12881 /** 12882 * Reset the resolved layout direction. 12883 * 12884 * @hide 12885 */ 12886 public void resetResolvedPadding() { 12887 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12888 } 12889 12890 /** 12891 * This is called when the view is detached from a window. At this point it 12892 * no longer has a surface for drawing. 12893 * 12894 * @see #onAttachedToWindow() 12895 */ 12896 protected void onDetachedFromWindow() { 12897 } 12898 12899 /** 12900 * This is a framework-internal mirror of onDetachedFromWindow() that's called 12901 * after onDetachedFromWindow(). 12902 * 12903 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 12904 * The super method should be called at the end of the overriden method to ensure 12905 * subclasses are destroyed first 12906 * 12907 * @hide 12908 */ 12909 protected void onDetachedFromWindowInternal() { 12910 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 12911 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12912 12913 if (mBackground != null) { 12914 mBackground.clearHotspots(); 12915 } 12916 12917 removeUnsetPressCallback(); 12918 removeLongPressCallback(); 12919 removePerformClickCallback(); 12920 removeSendViewScrolledAccessibilityEventCallback(); 12921 stopNestedScroll(); 12922 12923 destroyDrawingCache(); 12924 destroyLayer(false); 12925 12926 cleanupDraw(); 12927 mCurrentAnimation = null; 12928 } 12929 12930 private void cleanupDraw() { 12931 resetDisplayList(); 12932 if (mAttachInfo != null) { 12933 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 12934 } 12935 } 12936 12937 /** 12938 * This method ensures the hardware renderer is in a valid state 12939 * before executing the specified action. 12940 * 12941 * This method will attempt to set a valid state even if the window 12942 * the renderer is attached to was destroyed. 12943 * 12944 * This method is not guaranteed to work. If the hardware renderer 12945 * does not exist or cannot be put in a valid state, this method 12946 * will not executed the specified action. 12947 * 12948 * The specified action is executed synchronously. 12949 * 12950 * @param action The action to execute after the renderer is in a valid state 12951 * 12952 * @return True if the specified Runnable was executed, false otherwise 12953 * 12954 * @hide 12955 */ 12956 public boolean executeHardwareAction(Runnable action) { 12957 //noinspection SimplifiableIfStatement 12958 if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) { 12959 return mAttachInfo.mHardwareRenderer.safelyRun(action); 12960 } 12961 return false; 12962 } 12963 12964 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 12965 } 12966 12967 /** 12968 * @return The number of times this view has been attached to a window 12969 */ 12970 protected int getWindowAttachCount() { 12971 return mWindowAttachCount; 12972 } 12973 12974 /** 12975 * Retrieve a unique token identifying the window this view is attached to. 12976 * @return Return the window's token for use in 12977 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 12978 */ 12979 public IBinder getWindowToken() { 12980 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 12981 } 12982 12983 /** 12984 * Retrieve the {@link WindowId} for the window this view is 12985 * currently attached to. 12986 */ 12987 public WindowId getWindowId() { 12988 if (mAttachInfo == null) { 12989 return null; 12990 } 12991 if (mAttachInfo.mWindowId == null) { 12992 try { 12993 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 12994 mAttachInfo.mWindowToken); 12995 mAttachInfo.mWindowId = new WindowId( 12996 mAttachInfo.mIWindowId); 12997 } catch (RemoteException e) { 12998 } 12999 } 13000 return mAttachInfo.mWindowId; 13001 } 13002 13003 /** 13004 * Retrieve a unique token identifying the top-level "real" window of 13005 * the window that this view is attached to. That is, this is like 13006 * {@link #getWindowToken}, except if the window this view in is a panel 13007 * window (attached to another containing window), then the token of 13008 * the containing window is returned instead. 13009 * 13010 * @return Returns the associated window token, either 13011 * {@link #getWindowToken()} or the containing window's token. 13012 */ 13013 public IBinder getApplicationWindowToken() { 13014 AttachInfo ai = mAttachInfo; 13015 if (ai != null) { 13016 IBinder appWindowToken = ai.mPanelParentWindowToken; 13017 if (appWindowToken == null) { 13018 appWindowToken = ai.mWindowToken; 13019 } 13020 return appWindowToken; 13021 } 13022 return null; 13023 } 13024 13025 /** 13026 * Gets the logical display to which the view's window has been attached. 13027 * 13028 * @return The logical display, or null if the view is not currently attached to a window. 13029 */ 13030 public Display getDisplay() { 13031 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13032 } 13033 13034 /** 13035 * Retrieve private session object this view hierarchy is using to 13036 * communicate with the window manager. 13037 * @return the session object to communicate with the window manager 13038 */ 13039 /*package*/ IWindowSession getWindowSession() { 13040 return mAttachInfo != null ? mAttachInfo.mSession : null; 13041 } 13042 13043 /** 13044 * @param info the {@link android.view.View.AttachInfo} to associated with 13045 * this view 13046 */ 13047 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13048 //System.out.println("Attached! " + this); 13049 mAttachInfo = info; 13050 if (mOverlay != null) { 13051 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13052 } 13053 mWindowAttachCount++; 13054 // We will need to evaluate the drawable state at least once. 13055 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13056 if (mFloatingTreeObserver != null) { 13057 info.mTreeObserver.merge(mFloatingTreeObserver); 13058 mFloatingTreeObserver = null; 13059 } 13060 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13061 mAttachInfo.mScrollContainers.add(this); 13062 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13063 } 13064 performCollectViewAttributes(mAttachInfo, visibility); 13065 onAttachedToWindow(); 13066 13067 ListenerInfo li = mListenerInfo; 13068 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13069 li != null ? li.mOnAttachStateChangeListeners : null; 13070 if (listeners != null && listeners.size() > 0) { 13071 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13072 // perform the dispatching. The iterator is a safe guard against listeners that 13073 // could mutate the list by calling the various add/remove methods. This prevents 13074 // the array from being modified while we iterate it. 13075 for (OnAttachStateChangeListener listener : listeners) { 13076 listener.onViewAttachedToWindow(this); 13077 } 13078 } 13079 13080 int vis = info.mWindowVisibility; 13081 if (vis != GONE) { 13082 onWindowVisibilityChanged(vis); 13083 } 13084 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13085 // If nobody has evaluated the drawable state yet, then do it now. 13086 refreshDrawableState(); 13087 } 13088 needGlobalAttributesUpdate(false); 13089 } 13090 13091 void dispatchDetachedFromWindow() { 13092 AttachInfo info = mAttachInfo; 13093 if (info != null) { 13094 int vis = info.mWindowVisibility; 13095 if (vis != GONE) { 13096 onWindowVisibilityChanged(GONE); 13097 } 13098 } 13099 13100 onDetachedFromWindow(); 13101 onDetachedFromWindowInternal(); 13102 13103 ListenerInfo li = mListenerInfo; 13104 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13105 li != null ? li.mOnAttachStateChangeListeners : null; 13106 if (listeners != null && listeners.size() > 0) { 13107 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13108 // perform the dispatching. The iterator is a safe guard against listeners that 13109 // could mutate the list by calling the various add/remove methods. This prevents 13110 // the array from being modified while we iterate it. 13111 for (OnAttachStateChangeListener listener : listeners) { 13112 listener.onViewDetachedFromWindow(this); 13113 } 13114 } 13115 13116 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13117 mAttachInfo.mScrollContainers.remove(this); 13118 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13119 } 13120 13121 mAttachInfo = null; 13122 if (mOverlay != null) { 13123 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13124 } 13125 } 13126 13127 /** 13128 * Cancel any deferred high-level input events that were previously posted to the event queue. 13129 * 13130 * <p>Many views post high-level events such as click handlers to the event queue 13131 * to run deferred in order to preserve a desired user experience - clearing visible 13132 * pressed states before executing, etc. This method will abort any events of this nature 13133 * that are currently in flight.</p> 13134 * 13135 * <p>Custom views that generate their own high-level deferred input events should override 13136 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13137 * 13138 * <p>This will also cancel pending input events for any child views.</p> 13139 * 13140 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13141 * This will not impact newer events posted after this call that may occur as a result of 13142 * lower-level input events still waiting in the queue. If you are trying to prevent 13143 * double-submitted events for the duration of some sort of asynchronous transaction 13144 * you should also take other steps to protect against unexpected double inputs e.g. calling 13145 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13146 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13147 */ 13148 public final void cancelPendingInputEvents() { 13149 dispatchCancelPendingInputEvents(); 13150 } 13151 13152 /** 13153 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13154 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13155 */ 13156 void dispatchCancelPendingInputEvents() { 13157 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13158 onCancelPendingInputEvents(); 13159 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13160 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13161 " did not call through to super.onCancelPendingInputEvents()"); 13162 } 13163 } 13164 13165 /** 13166 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13167 * a parent view. 13168 * 13169 * <p>This method is responsible for removing any pending high-level input events that were 13170 * posted to the event queue to run later. Custom view classes that post their own deferred 13171 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13172 * {@link android.os.Handler} should override this method, call 13173 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13174 * </p> 13175 */ 13176 public void onCancelPendingInputEvents() { 13177 removePerformClickCallback(); 13178 cancelLongPress(); 13179 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13180 } 13181 13182 /** 13183 * Store this view hierarchy's frozen state into the given container. 13184 * 13185 * @param container The SparseArray in which to save the view's state. 13186 * 13187 * @see #restoreHierarchyState(android.util.SparseArray) 13188 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13189 * @see #onSaveInstanceState() 13190 */ 13191 public void saveHierarchyState(SparseArray<Parcelable> container) { 13192 dispatchSaveInstanceState(container); 13193 } 13194 13195 /** 13196 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13197 * this view and its children. May be overridden to modify how freezing happens to a 13198 * view's children; for example, some views may want to not store state for their children. 13199 * 13200 * @param container The SparseArray in which to save the view's state. 13201 * 13202 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13203 * @see #saveHierarchyState(android.util.SparseArray) 13204 * @see #onSaveInstanceState() 13205 */ 13206 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13207 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13208 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13209 Parcelable state = onSaveInstanceState(); 13210 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13211 throw new IllegalStateException( 13212 "Derived class did not call super.onSaveInstanceState()"); 13213 } 13214 if (state != null) { 13215 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13216 // + ": " + state); 13217 container.put(mID, state); 13218 } 13219 } 13220 } 13221 13222 /** 13223 * Hook allowing a view to generate a representation of its internal state 13224 * that can later be used to create a new instance with that same state. 13225 * This state should only contain information that is not persistent or can 13226 * not be reconstructed later. For example, you will never store your 13227 * current position on screen because that will be computed again when a 13228 * new instance of the view is placed in its view hierarchy. 13229 * <p> 13230 * Some examples of things you may store here: the current cursor position 13231 * in a text view (but usually not the text itself since that is stored in a 13232 * content provider or other persistent storage), the currently selected 13233 * item in a list view. 13234 * 13235 * @return Returns a Parcelable object containing the view's current dynamic 13236 * state, or null if there is nothing interesting to save. The 13237 * default implementation returns null. 13238 * @see #onRestoreInstanceState(android.os.Parcelable) 13239 * @see #saveHierarchyState(android.util.SparseArray) 13240 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13241 * @see #setSaveEnabled(boolean) 13242 */ 13243 protected Parcelable onSaveInstanceState() { 13244 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13245 return BaseSavedState.EMPTY_STATE; 13246 } 13247 13248 /** 13249 * Restore this view hierarchy's frozen state from the given container. 13250 * 13251 * @param container The SparseArray which holds previously frozen states. 13252 * 13253 * @see #saveHierarchyState(android.util.SparseArray) 13254 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13255 * @see #onRestoreInstanceState(android.os.Parcelable) 13256 */ 13257 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13258 dispatchRestoreInstanceState(container); 13259 } 13260 13261 /** 13262 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13263 * state for this view and its children. May be overridden to modify how restoring 13264 * happens to a view's children; for example, some views may want to not store state 13265 * for their children. 13266 * 13267 * @param container The SparseArray which holds previously saved state. 13268 * 13269 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13270 * @see #restoreHierarchyState(android.util.SparseArray) 13271 * @see #onRestoreInstanceState(android.os.Parcelable) 13272 */ 13273 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13274 if (mID != NO_ID) { 13275 Parcelable state = container.get(mID); 13276 if (state != null) { 13277 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13278 // + ": " + state); 13279 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13280 onRestoreInstanceState(state); 13281 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13282 throw new IllegalStateException( 13283 "Derived class did not call super.onRestoreInstanceState()"); 13284 } 13285 } 13286 } 13287 } 13288 13289 /** 13290 * Hook allowing a view to re-apply a representation of its internal state that had previously 13291 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13292 * null state. 13293 * 13294 * @param state The frozen state that had previously been returned by 13295 * {@link #onSaveInstanceState}. 13296 * 13297 * @see #onSaveInstanceState() 13298 * @see #restoreHierarchyState(android.util.SparseArray) 13299 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13300 */ 13301 protected void onRestoreInstanceState(Parcelable state) { 13302 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13303 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13304 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13305 + "received " + state.getClass().toString() + " instead. This usually happens " 13306 + "when two views of different type have the same id in the same hierarchy. " 13307 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13308 + "other views do not use the same id."); 13309 } 13310 } 13311 13312 /** 13313 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13314 * 13315 * @return the drawing start time in milliseconds 13316 */ 13317 public long getDrawingTime() { 13318 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13319 } 13320 13321 /** 13322 * <p>Enables or disables the duplication of the parent's state into this view. When 13323 * duplication is enabled, this view gets its drawable state from its parent rather 13324 * than from its own internal properties.</p> 13325 * 13326 * <p>Note: in the current implementation, setting this property to true after the 13327 * view was added to a ViewGroup might have no effect at all. This property should 13328 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13329 * 13330 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13331 * property is enabled, an exception will be thrown.</p> 13332 * 13333 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13334 * parent, these states should not be affected by this method.</p> 13335 * 13336 * @param enabled True to enable duplication of the parent's drawable state, false 13337 * to disable it. 13338 * 13339 * @see #getDrawableState() 13340 * @see #isDuplicateParentStateEnabled() 13341 */ 13342 public void setDuplicateParentStateEnabled(boolean enabled) { 13343 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13344 } 13345 13346 /** 13347 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13348 * 13349 * @return True if this view's drawable state is duplicated from the parent, 13350 * false otherwise 13351 * 13352 * @see #getDrawableState() 13353 * @see #setDuplicateParentStateEnabled(boolean) 13354 */ 13355 public boolean isDuplicateParentStateEnabled() { 13356 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13357 } 13358 13359 /** 13360 * <p>Specifies the type of layer backing this view. The layer can be 13361 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13362 * {@link #LAYER_TYPE_HARDWARE}.</p> 13363 * 13364 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13365 * instance that controls how the layer is composed on screen. The following 13366 * properties of the paint are taken into account when composing the layer:</p> 13367 * <ul> 13368 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13369 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13370 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13371 * </ul> 13372 * 13373 * <p>If this view has an alpha value set to < 1.0 by calling 13374 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13375 * by this view's alpha value.</p> 13376 * 13377 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13378 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13379 * for more information on when and how to use layers.</p> 13380 * 13381 * @param layerType The type of layer to use with this view, must be one of 13382 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13383 * {@link #LAYER_TYPE_HARDWARE} 13384 * @param paint The paint used to compose the layer. This argument is optional 13385 * and can be null. It is ignored when the layer type is 13386 * {@link #LAYER_TYPE_NONE} 13387 * 13388 * @see #getLayerType() 13389 * @see #LAYER_TYPE_NONE 13390 * @see #LAYER_TYPE_SOFTWARE 13391 * @see #LAYER_TYPE_HARDWARE 13392 * @see #setAlpha(float) 13393 * 13394 * @attr ref android.R.styleable#View_layerType 13395 */ 13396 public void setLayerType(int layerType, Paint paint) { 13397 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13398 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13399 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13400 } 13401 13402 if (layerType == mLayerType) { 13403 setLayerPaint(paint); 13404 return; 13405 } 13406 13407 // Destroy any previous software drawing cache if needed 13408 switch (mLayerType) { 13409 case LAYER_TYPE_HARDWARE: 13410 destroyLayer(false); 13411 // fall through - non-accelerated views may use software layer mechanism instead 13412 case LAYER_TYPE_SOFTWARE: 13413 destroyDrawingCache(); 13414 break; 13415 default: 13416 break; 13417 } 13418 13419 mLayerType = layerType; 13420 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 13421 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13422 mLocalDirtyRect = layerDisabled ? null : new Rect(); 13423 13424 invalidateParentCaches(); 13425 invalidate(true); 13426 } 13427 13428 /** 13429 * Updates the {@link Paint} object used with the current layer (used only if the current 13430 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13431 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13432 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13433 * ensure that the view gets redrawn immediately. 13434 * 13435 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13436 * instance that controls how the layer is composed on screen. The following 13437 * properties of the paint are taken into account when composing the layer:</p> 13438 * <ul> 13439 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13440 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13441 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13442 * </ul> 13443 * 13444 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13445 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13446 * 13447 * @param paint The paint used to compose the layer. This argument is optional 13448 * and can be null. It is ignored when the layer type is 13449 * {@link #LAYER_TYPE_NONE} 13450 * 13451 * @see #setLayerType(int, android.graphics.Paint) 13452 */ 13453 public void setLayerPaint(Paint paint) { 13454 int layerType = getLayerType(); 13455 if (layerType != LAYER_TYPE_NONE) { 13456 mLayerPaint = paint == null ? new Paint() : paint; 13457 if (layerType == LAYER_TYPE_HARDWARE) { 13458 HardwareLayer layer = getHardwareLayer(); 13459 if (layer != null) { 13460 layer.setLayerPaint(mLayerPaint); 13461 } 13462 invalidateViewProperty(false, false); 13463 } else { 13464 invalidate(); 13465 } 13466 } 13467 } 13468 13469 /** 13470 * Indicates whether this view has a static layer. A view with layer type 13471 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13472 * dynamic. 13473 */ 13474 boolean hasStaticLayer() { 13475 return true; 13476 } 13477 13478 /** 13479 * Indicates what type of layer is currently associated with this view. By default 13480 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13481 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13482 * for more information on the different types of layers. 13483 * 13484 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13485 * {@link #LAYER_TYPE_HARDWARE} 13486 * 13487 * @see #setLayerType(int, android.graphics.Paint) 13488 * @see #buildLayer() 13489 * @see #LAYER_TYPE_NONE 13490 * @see #LAYER_TYPE_SOFTWARE 13491 * @see #LAYER_TYPE_HARDWARE 13492 */ 13493 public int getLayerType() { 13494 return mLayerType; 13495 } 13496 13497 /** 13498 * Forces this view's layer to be created and this view to be rendered 13499 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13500 * invoking this method will have no effect. 13501 * 13502 * This method can for instance be used to render a view into its layer before 13503 * starting an animation. If this view is complex, rendering into the layer 13504 * before starting the animation will avoid skipping frames. 13505 * 13506 * @throws IllegalStateException If this view is not attached to a window 13507 * 13508 * @see #setLayerType(int, android.graphics.Paint) 13509 */ 13510 public void buildLayer() { 13511 if (mLayerType == LAYER_TYPE_NONE) return; 13512 13513 final AttachInfo attachInfo = mAttachInfo; 13514 if (attachInfo == null) { 13515 throw new IllegalStateException("This view must be attached to a window first"); 13516 } 13517 13518 switch (mLayerType) { 13519 case LAYER_TYPE_HARDWARE: 13520 getHardwareLayer(); 13521 // TODO: We need a better way to handle this case 13522 // If views have registered pre-draw listeners they need 13523 // to be notified before we build the layer. Those listeners 13524 // may however rely on other events to happen first so we 13525 // cannot just invoke them here until they don't cancel the 13526 // current frame 13527 if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) { 13528 attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates(); 13529 } 13530 break; 13531 case LAYER_TYPE_SOFTWARE: 13532 buildDrawingCache(true); 13533 break; 13534 } 13535 } 13536 13537 /** 13538 * <p>Returns a hardware layer that can be used to draw this view again 13539 * without executing its draw method.</p> 13540 * 13541 * @return A HardwareLayer ready to render, or null if an error occurred. 13542 */ 13543 HardwareLayer getHardwareLayer() { 13544 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 13545 !mAttachInfo.mHardwareRenderer.isEnabled()) { 13546 return null; 13547 } 13548 13549 final int width = mRight - mLeft; 13550 final int height = mBottom - mTop; 13551 13552 if (width == 0 || height == 0) { 13553 return null; 13554 } 13555 13556 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 13557 if (mHardwareLayer == null) { 13558 mHardwareLayer = mAttachInfo.mHardwareRenderer.createDisplayListLayer( 13559 width, height); 13560 mLocalDirtyRect.set(0, 0, width, height); 13561 } else if (mHardwareLayer.isValid()) { 13562 // This should not be necessary but applications that change 13563 // the parameters of their background drawable without calling 13564 // this.setBackground(Drawable) can leave the view in a bad state 13565 // (for instance isOpaque() returns true, but the background is 13566 // not opaque.) 13567 computeOpaqueFlags(); 13568 13569 if (mHardwareLayer.prepare(width, height, isOpaque())) { 13570 mLocalDirtyRect.set(0, 0, width, height); 13571 } 13572 } 13573 13574 // The layer is not valid if the underlying GPU resources cannot be allocated 13575 mHardwareLayer.flushChanges(); 13576 if (!mHardwareLayer.isValid()) { 13577 return null; 13578 } 13579 13580 mHardwareLayer.setLayerPaint(mLayerPaint); 13581 RenderNode displayList = mHardwareLayer.startRecording(); 13582 updateDisplayListIfDirty(displayList, true); 13583 mHardwareLayer.endRecording(mLocalDirtyRect); 13584 mLocalDirtyRect.setEmpty(); 13585 } 13586 13587 return mHardwareLayer; 13588 } 13589 13590 /** 13591 * Destroys this View's hardware layer if possible. 13592 * 13593 * @return True if the layer was destroyed, false otherwise. 13594 * 13595 * @see #setLayerType(int, android.graphics.Paint) 13596 * @see #LAYER_TYPE_HARDWARE 13597 */ 13598 boolean destroyLayer(boolean valid) { 13599 if (mHardwareLayer != null) { 13600 mHardwareLayer.destroy(); 13601 mHardwareLayer = null; 13602 13603 invalidate(true); 13604 invalidateParentCaches(); 13605 return true; 13606 } 13607 return false; 13608 } 13609 13610 /** 13611 * Destroys all hardware rendering resources. This method is invoked 13612 * when the system needs to reclaim resources. Upon execution of this 13613 * method, you should free any OpenGL resources created by the view. 13614 * 13615 * Note: you <strong>must</strong> call 13616 * <code>super.destroyHardwareResources()</code> when overriding 13617 * this method. 13618 * 13619 * @hide 13620 */ 13621 protected void destroyHardwareResources() { 13622 resetDisplayList(); 13623 destroyLayer(true); 13624 } 13625 13626 /** 13627 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13628 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13629 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13630 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13631 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13632 * null.</p> 13633 * 13634 * <p>Enabling the drawing cache is similar to 13635 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13636 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13637 * drawing cache has no effect on rendering because the system uses a different mechanism 13638 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13639 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13640 * for information on how to enable software and hardware layers.</p> 13641 * 13642 * <p>This API can be used to manually generate 13643 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13644 * {@link #getDrawingCache()}.</p> 13645 * 13646 * @param enabled true to enable the drawing cache, false otherwise 13647 * 13648 * @see #isDrawingCacheEnabled() 13649 * @see #getDrawingCache() 13650 * @see #buildDrawingCache() 13651 * @see #setLayerType(int, android.graphics.Paint) 13652 */ 13653 public void setDrawingCacheEnabled(boolean enabled) { 13654 mCachingFailed = false; 13655 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13656 } 13657 13658 /** 13659 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13660 * 13661 * @return true if the drawing cache is enabled 13662 * 13663 * @see #setDrawingCacheEnabled(boolean) 13664 * @see #getDrawingCache() 13665 */ 13666 @ViewDebug.ExportedProperty(category = "drawing") 13667 public boolean isDrawingCacheEnabled() { 13668 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13669 } 13670 13671 /** 13672 * Debugging utility which recursively outputs the dirty state of a view and its 13673 * descendants. 13674 * 13675 * @hide 13676 */ 13677 @SuppressWarnings({"UnusedDeclaration"}) 13678 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13679 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13680 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13681 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13682 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13683 if (clear) { 13684 mPrivateFlags &= clearMask; 13685 } 13686 if (this instanceof ViewGroup) { 13687 ViewGroup parent = (ViewGroup) this; 13688 final int count = parent.getChildCount(); 13689 for (int i = 0; i < count; i++) { 13690 final View child = parent.getChildAt(i); 13691 child.outputDirtyFlags(indent + " ", clear, clearMask); 13692 } 13693 } 13694 } 13695 13696 /** 13697 * This method is used by ViewGroup to cause its children to restore or recreate their 13698 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13699 * to recreate its own display list, which would happen if it went through the normal 13700 * draw/dispatchDraw mechanisms. 13701 * 13702 * @hide 13703 */ 13704 protected void dispatchGetDisplayList() {} 13705 13706 /** 13707 * A view that is not attached or hardware accelerated cannot create a display list. 13708 * This method checks these conditions and returns the appropriate result. 13709 * 13710 * @return true if view has the ability to create a display list, false otherwise. 13711 * 13712 * @hide 13713 */ 13714 public boolean canHaveDisplayList() { 13715 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13716 } 13717 13718 /** 13719 * Returns a DisplayList. If the incoming displayList is null, one will be created. 13720 * Otherwise, the same display list will be returned (after having been rendered into 13721 * along the way, depending on the invalidation state of the view). 13722 * 13723 * @param renderNode The previous version of this displayList, could be null. 13724 * @param isLayer Whether the requester of the display list is a layer. If so, 13725 * the view will avoid creating a layer inside the resulting display list. 13726 * @return A new or reused DisplayList object. 13727 */ 13728 private void updateDisplayListIfDirty(@NonNull RenderNode renderNode, boolean isLayer) { 13729 if (renderNode == null) { 13730 throw new IllegalArgumentException("RenderNode must not be null"); 13731 } 13732 if (!canHaveDisplayList()) { 13733 // can't populate RenderNode, don't try 13734 return; 13735 } 13736 13737 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 13738 || !renderNode.isValid() 13739 || (!isLayer && mRecreateDisplayList)) { 13740 // Don't need to recreate the display list, just need to tell our 13741 // children to restore/recreate theirs 13742 if (renderNode.isValid() 13743 && !isLayer 13744 && !mRecreateDisplayList) { 13745 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13746 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13747 dispatchGetDisplayList(); 13748 13749 return; // no work needed 13750 } 13751 13752 if (!isLayer) { 13753 // If we got here, we're recreating it. Mark it as such to ensure that 13754 // we copy in child display lists into ours in drawChild() 13755 mRecreateDisplayList = true; 13756 } 13757 13758 boolean caching = false; 13759 int width = mRight - mLeft; 13760 int height = mBottom - mTop; 13761 int layerType = getLayerType(); 13762 13763 final HardwareCanvas canvas = renderNode.start(width, height); 13764 13765 try { 13766 if (!isLayer && layerType != LAYER_TYPE_NONE) { 13767 if (layerType == LAYER_TYPE_HARDWARE) { 13768 final HardwareLayer layer = getHardwareLayer(); 13769 if (layer != null && layer.isValid()) { 13770 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13771 } else { 13772 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 13773 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 13774 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13775 } 13776 caching = true; 13777 } else { 13778 buildDrawingCache(true); 13779 Bitmap cache = getDrawingCache(true); 13780 if (cache != null) { 13781 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13782 caching = true; 13783 } 13784 } 13785 } else { 13786 13787 computeScroll(); 13788 13789 canvas.translate(-mScrollX, -mScrollY); 13790 if (!isLayer) { 13791 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13792 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13793 } 13794 13795 // Fast path for layouts with no backgrounds 13796 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13797 dispatchDraw(canvas); 13798 if (mOverlay != null && !mOverlay.isEmpty()) { 13799 mOverlay.getOverlayView().draw(canvas); 13800 } 13801 } else { 13802 draw(canvas); 13803 } 13804 } 13805 } finally { 13806 renderNode.end(canvas); 13807 renderNode.setCaching(caching); 13808 if (isLayer) { 13809 renderNode.setLeftTopRightBottom(0, 0, width, height); 13810 } else { 13811 setDisplayListProperties(renderNode); 13812 } 13813 } 13814 } else if (!isLayer) { 13815 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13816 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13817 } 13818 } 13819 13820 /** 13821 * Returns a RenderNode with View draw content recorded, which can be 13822 * used to draw this view again without executing its draw method. 13823 * 13824 * @return A RenderNode ready to replay, or null if caching is not enabled. 13825 * 13826 * @hide 13827 */ 13828 public RenderNode getDisplayList() { 13829 updateDisplayListIfDirty(mRenderNode, false); 13830 return mRenderNode; 13831 } 13832 13833 private void resetDisplayList() { 13834 if (mRenderNode.isValid()) { 13835 mRenderNode.destroyDisplayListData(); 13836 } 13837 13838 if (mBackgroundDisplayList != null && mBackgroundDisplayList.isValid()) { 13839 mBackgroundDisplayList.destroyDisplayListData(); 13840 } 13841 } 13842 13843 /** 13844 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13845 * 13846 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13847 * 13848 * @see #getDrawingCache(boolean) 13849 */ 13850 public Bitmap getDrawingCache() { 13851 return getDrawingCache(false); 13852 } 13853 13854 /** 13855 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13856 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13857 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13858 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13859 * request the drawing cache by calling this method and draw it on screen if the 13860 * returned bitmap is not null.</p> 13861 * 13862 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13863 * this method will create a bitmap of the same size as this view. Because this bitmap 13864 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13865 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13866 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13867 * size than the view. This implies that your application must be able to handle this 13868 * size.</p> 13869 * 13870 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13871 * the current density of the screen when the application is in compatibility 13872 * mode. 13873 * 13874 * @return A bitmap representing this view or null if cache is disabled. 13875 * 13876 * @see #setDrawingCacheEnabled(boolean) 13877 * @see #isDrawingCacheEnabled() 13878 * @see #buildDrawingCache(boolean) 13879 * @see #destroyDrawingCache() 13880 */ 13881 public Bitmap getDrawingCache(boolean autoScale) { 13882 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13883 return null; 13884 } 13885 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13886 buildDrawingCache(autoScale); 13887 } 13888 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13889 } 13890 13891 /** 13892 * <p>Frees the resources used by the drawing cache. If you call 13893 * {@link #buildDrawingCache()} manually without calling 13894 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13895 * should cleanup the cache with this method afterwards.</p> 13896 * 13897 * @see #setDrawingCacheEnabled(boolean) 13898 * @see #buildDrawingCache() 13899 * @see #getDrawingCache() 13900 */ 13901 public void destroyDrawingCache() { 13902 if (mDrawingCache != null) { 13903 mDrawingCache.recycle(); 13904 mDrawingCache = null; 13905 } 13906 if (mUnscaledDrawingCache != null) { 13907 mUnscaledDrawingCache.recycle(); 13908 mUnscaledDrawingCache = null; 13909 } 13910 } 13911 13912 /** 13913 * Setting a solid background color for the drawing cache's bitmaps will improve 13914 * performance and memory usage. Note, though that this should only be used if this 13915 * view will always be drawn on top of a solid color. 13916 * 13917 * @param color The background color to use for the drawing cache's bitmap 13918 * 13919 * @see #setDrawingCacheEnabled(boolean) 13920 * @see #buildDrawingCache() 13921 * @see #getDrawingCache() 13922 */ 13923 public void setDrawingCacheBackgroundColor(int color) { 13924 if (color != mDrawingCacheBackgroundColor) { 13925 mDrawingCacheBackgroundColor = color; 13926 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13927 } 13928 } 13929 13930 /** 13931 * @see #setDrawingCacheBackgroundColor(int) 13932 * 13933 * @return The background color to used for the drawing cache's bitmap 13934 */ 13935 public int getDrawingCacheBackgroundColor() { 13936 return mDrawingCacheBackgroundColor; 13937 } 13938 13939 /** 13940 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13941 * 13942 * @see #buildDrawingCache(boolean) 13943 */ 13944 public void buildDrawingCache() { 13945 buildDrawingCache(false); 13946 } 13947 13948 /** 13949 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13950 * 13951 * <p>If you call {@link #buildDrawingCache()} manually without calling 13952 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13953 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13954 * 13955 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13956 * this method will create a bitmap of the same size as this view. Because this bitmap 13957 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13958 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13959 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13960 * size than the view. This implies that your application must be able to handle this 13961 * size.</p> 13962 * 13963 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13964 * you do not need the drawing cache bitmap, calling this method will increase memory 13965 * usage and cause the view to be rendered in software once, thus negatively impacting 13966 * performance.</p> 13967 * 13968 * @see #getDrawingCache() 13969 * @see #destroyDrawingCache() 13970 */ 13971 public void buildDrawingCache(boolean autoScale) { 13972 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13973 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13974 mCachingFailed = false; 13975 13976 int width = mRight - mLeft; 13977 int height = mBottom - mTop; 13978 13979 final AttachInfo attachInfo = mAttachInfo; 13980 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13981 13982 if (autoScale && scalingRequired) { 13983 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13984 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13985 } 13986 13987 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13988 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13989 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13990 13991 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13992 final long drawingCacheSize = 13993 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13994 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13995 if (width > 0 && height > 0) { 13996 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13997 + projectedBitmapSize + " bytes, only " 13998 + drawingCacheSize + " available"); 13999 } 14000 destroyDrawingCache(); 14001 mCachingFailed = true; 14002 return; 14003 } 14004 14005 boolean clear = true; 14006 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 14007 14008 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 14009 Bitmap.Config quality; 14010 if (!opaque) { 14011 // Never pick ARGB_4444 because it looks awful 14012 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 14013 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 14014 case DRAWING_CACHE_QUALITY_AUTO: 14015 case DRAWING_CACHE_QUALITY_LOW: 14016 case DRAWING_CACHE_QUALITY_HIGH: 14017 default: 14018 quality = Bitmap.Config.ARGB_8888; 14019 break; 14020 } 14021 } else { 14022 // Optimization for translucent windows 14023 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 14024 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 14025 } 14026 14027 // Try to cleanup memory 14028 if (bitmap != null) bitmap.recycle(); 14029 14030 try { 14031 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14032 width, height, quality); 14033 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 14034 if (autoScale) { 14035 mDrawingCache = bitmap; 14036 } else { 14037 mUnscaledDrawingCache = bitmap; 14038 } 14039 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 14040 } catch (OutOfMemoryError e) { 14041 // If there is not enough memory to create the bitmap cache, just 14042 // ignore the issue as bitmap caches are not required to draw the 14043 // view hierarchy 14044 if (autoScale) { 14045 mDrawingCache = null; 14046 } else { 14047 mUnscaledDrawingCache = null; 14048 } 14049 mCachingFailed = true; 14050 return; 14051 } 14052 14053 clear = drawingCacheBackgroundColor != 0; 14054 } 14055 14056 Canvas canvas; 14057 if (attachInfo != null) { 14058 canvas = attachInfo.mCanvas; 14059 if (canvas == null) { 14060 canvas = new Canvas(); 14061 } 14062 canvas.setBitmap(bitmap); 14063 // Temporarily clobber the cached Canvas in case one of our children 14064 // is also using a drawing cache. Without this, the children would 14065 // steal the canvas by attaching their own bitmap to it and bad, bad 14066 // thing would happen (invisible views, corrupted drawings, etc.) 14067 attachInfo.mCanvas = null; 14068 } else { 14069 // This case should hopefully never or seldom happen 14070 canvas = new Canvas(bitmap); 14071 } 14072 14073 if (clear) { 14074 bitmap.eraseColor(drawingCacheBackgroundColor); 14075 } 14076 14077 computeScroll(); 14078 final int restoreCount = canvas.save(); 14079 14080 if (autoScale && scalingRequired) { 14081 final float scale = attachInfo.mApplicationScale; 14082 canvas.scale(scale, scale); 14083 } 14084 14085 canvas.translate(-mScrollX, -mScrollY); 14086 14087 mPrivateFlags |= PFLAG_DRAWN; 14088 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 14089 mLayerType != LAYER_TYPE_NONE) { 14090 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 14091 } 14092 14093 // Fast path for layouts with no backgrounds 14094 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14095 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14096 dispatchDraw(canvas); 14097 if (mOverlay != null && !mOverlay.isEmpty()) { 14098 mOverlay.getOverlayView().draw(canvas); 14099 } 14100 } else { 14101 draw(canvas); 14102 } 14103 14104 canvas.restoreToCount(restoreCount); 14105 canvas.setBitmap(null); 14106 14107 if (attachInfo != null) { 14108 // Restore the cached Canvas for our siblings 14109 attachInfo.mCanvas = canvas; 14110 } 14111 } 14112 } 14113 14114 /** 14115 * Create a snapshot of the view into a bitmap. We should probably make 14116 * some form of this public, but should think about the API. 14117 */ 14118 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14119 int width = mRight - mLeft; 14120 int height = mBottom - mTop; 14121 14122 final AttachInfo attachInfo = mAttachInfo; 14123 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14124 width = (int) ((width * scale) + 0.5f); 14125 height = (int) ((height * scale) + 0.5f); 14126 14127 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14128 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14129 if (bitmap == null) { 14130 throw new OutOfMemoryError(); 14131 } 14132 14133 Resources resources = getResources(); 14134 if (resources != null) { 14135 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14136 } 14137 14138 Canvas canvas; 14139 if (attachInfo != null) { 14140 canvas = attachInfo.mCanvas; 14141 if (canvas == null) { 14142 canvas = new Canvas(); 14143 } 14144 canvas.setBitmap(bitmap); 14145 // Temporarily clobber the cached Canvas in case one of our children 14146 // is also using a drawing cache. Without this, the children would 14147 // steal the canvas by attaching their own bitmap to it and bad, bad 14148 // things would happen (invisible views, corrupted drawings, etc.) 14149 attachInfo.mCanvas = null; 14150 } else { 14151 // This case should hopefully never or seldom happen 14152 canvas = new Canvas(bitmap); 14153 } 14154 14155 if ((backgroundColor & 0xff000000) != 0) { 14156 bitmap.eraseColor(backgroundColor); 14157 } 14158 14159 computeScroll(); 14160 final int restoreCount = canvas.save(); 14161 canvas.scale(scale, scale); 14162 canvas.translate(-mScrollX, -mScrollY); 14163 14164 // Temporarily remove the dirty mask 14165 int flags = mPrivateFlags; 14166 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14167 14168 // Fast path for layouts with no backgrounds 14169 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14170 dispatchDraw(canvas); 14171 if (mOverlay != null && !mOverlay.isEmpty()) { 14172 mOverlay.getOverlayView().draw(canvas); 14173 } 14174 } else { 14175 draw(canvas); 14176 } 14177 14178 mPrivateFlags = flags; 14179 14180 canvas.restoreToCount(restoreCount); 14181 canvas.setBitmap(null); 14182 14183 if (attachInfo != null) { 14184 // Restore the cached Canvas for our siblings 14185 attachInfo.mCanvas = canvas; 14186 } 14187 14188 return bitmap; 14189 } 14190 14191 /** 14192 * Indicates whether this View is currently in edit mode. A View is usually 14193 * in edit mode when displayed within a developer tool. For instance, if 14194 * this View is being drawn by a visual user interface builder, this method 14195 * should return true. 14196 * 14197 * Subclasses should check the return value of this method to provide 14198 * different behaviors if their normal behavior might interfere with the 14199 * host environment. For instance: the class spawns a thread in its 14200 * constructor, the drawing code relies on device-specific features, etc. 14201 * 14202 * This method is usually checked in the drawing code of custom widgets. 14203 * 14204 * @return True if this View is in edit mode, false otherwise. 14205 */ 14206 public boolean isInEditMode() { 14207 return false; 14208 } 14209 14210 /** 14211 * If the View draws content inside its padding and enables fading edges, 14212 * it needs to support padding offsets. Padding offsets are added to the 14213 * fading edges to extend the length of the fade so that it covers pixels 14214 * drawn inside the padding. 14215 * 14216 * Subclasses of this class should override this method if they need 14217 * to draw content inside the padding. 14218 * 14219 * @return True if padding offset must be applied, false otherwise. 14220 * 14221 * @see #getLeftPaddingOffset() 14222 * @see #getRightPaddingOffset() 14223 * @see #getTopPaddingOffset() 14224 * @see #getBottomPaddingOffset() 14225 * 14226 * @since CURRENT 14227 */ 14228 protected boolean isPaddingOffsetRequired() { 14229 return false; 14230 } 14231 14232 /** 14233 * Amount by which to extend the left fading region. Called only when 14234 * {@link #isPaddingOffsetRequired()} returns true. 14235 * 14236 * @return The left padding offset in pixels. 14237 * 14238 * @see #isPaddingOffsetRequired() 14239 * 14240 * @since CURRENT 14241 */ 14242 protected int getLeftPaddingOffset() { 14243 return 0; 14244 } 14245 14246 /** 14247 * Amount by which to extend the right fading region. Called only when 14248 * {@link #isPaddingOffsetRequired()} returns true. 14249 * 14250 * @return The right padding offset in pixels. 14251 * 14252 * @see #isPaddingOffsetRequired() 14253 * 14254 * @since CURRENT 14255 */ 14256 protected int getRightPaddingOffset() { 14257 return 0; 14258 } 14259 14260 /** 14261 * Amount by which to extend the top fading region. Called only when 14262 * {@link #isPaddingOffsetRequired()} returns true. 14263 * 14264 * @return The top padding offset in pixels. 14265 * 14266 * @see #isPaddingOffsetRequired() 14267 * 14268 * @since CURRENT 14269 */ 14270 protected int getTopPaddingOffset() { 14271 return 0; 14272 } 14273 14274 /** 14275 * Amount by which to extend the bottom fading region. Called only when 14276 * {@link #isPaddingOffsetRequired()} returns true. 14277 * 14278 * @return The bottom padding offset in pixels. 14279 * 14280 * @see #isPaddingOffsetRequired() 14281 * 14282 * @since CURRENT 14283 */ 14284 protected int getBottomPaddingOffset() { 14285 return 0; 14286 } 14287 14288 /** 14289 * @hide 14290 * @param offsetRequired 14291 */ 14292 protected int getFadeTop(boolean offsetRequired) { 14293 int top = mPaddingTop; 14294 if (offsetRequired) top += getTopPaddingOffset(); 14295 return top; 14296 } 14297 14298 /** 14299 * @hide 14300 * @param offsetRequired 14301 */ 14302 protected int getFadeHeight(boolean offsetRequired) { 14303 int padding = mPaddingTop; 14304 if (offsetRequired) padding += getTopPaddingOffset(); 14305 return mBottom - mTop - mPaddingBottom - padding; 14306 } 14307 14308 /** 14309 * <p>Indicates whether this view is attached to a hardware accelerated 14310 * window or not.</p> 14311 * 14312 * <p>Even if this method returns true, it does not mean that every call 14313 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14314 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14315 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14316 * window is hardware accelerated, 14317 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14318 * return false, and this method will return true.</p> 14319 * 14320 * @return True if the view is attached to a window and the window is 14321 * hardware accelerated; false in any other case. 14322 */ 14323 public boolean isHardwareAccelerated() { 14324 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14325 } 14326 14327 /** 14328 * Sets a rectangular area on this view to which the view will be clipped 14329 * when it is drawn. Setting the value to null will remove the clip bounds 14330 * and the view will draw normally, using its full bounds. 14331 * 14332 * @param clipBounds The rectangular area, in the local coordinates of 14333 * this view, to which future drawing operations will be clipped. 14334 */ 14335 public void setClipBounds(Rect clipBounds) { 14336 if (clipBounds != null) { 14337 if (clipBounds.equals(mClipBounds)) { 14338 return; 14339 } 14340 if (mClipBounds == null) { 14341 invalidate(); 14342 mClipBounds = new Rect(clipBounds); 14343 } else { 14344 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14345 Math.min(mClipBounds.top, clipBounds.top), 14346 Math.max(mClipBounds.right, clipBounds.right), 14347 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14348 mClipBounds.set(clipBounds); 14349 } 14350 } else { 14351 if (mClipBounds != null) { 14352 invalidate(); 14353 mClipBounds = null; 14354 } 14355 } 14356 } 14357 14358 /** 14359 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14360 * 14361 * @return A copy of the current clip bounds if clip bounds are set, 14362 * otherwise null. 14363 */ 14364 public Rect getClipBounds() { 14365 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14366 } 14367 14368 /** 14369 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14370 * case of an active Animation being run on the view. 14371 */ 14372 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14373 Animation a, boolean scalingRequired) { 14374 Transformation invalidationTransform; 14375 final int flags = parent.mGroupFlags; 14376 final boolean initialized = a.isInitialized(); 14377 if (!initialized) { 14378 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14379 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14380 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14381 onAnimationStart(); 14382 } 14383 14384 final Transformation t = parent.getChildTransformation(); 14385 boolean more = a.getTransformation(drawingTime, t, 1f); 14386 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14387 if (parent.mInvalidationTransformation == null) { 14388 parent.mInvalidationTransformation = new Transformation(); 14389 } 14390 invalidationTransform = parent.mInvalidationTransformation; 14391 a.getTransformation(drawingTime, invalidationTransform, 1f); 14392 } else { 14393 invalidationTransform = t; 14394 } 14395 14396 if (more) { 14397 if (!a.willChangeBounds()) { 14398 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14399 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14400 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14401 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14402 // The child need to draw an animation, potentially offscreen, so 14403 // make sure we do not cancel invalidate requests 14404 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14405 parent.invalidate(mLeft, mTop, mRight, mBottom); 14406 } 14407 } else { 14408 if (parent.mInvalidateRegion == null) { 14409 parent.mInvalidateRegion = new RectF(); 14410 } 14411 final RectF region = parent.mInvalidateRegion; 14412 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14413 invalidationTransform); 14414 14415 // The child need to draw an animation, potentially offscreen, so 14416 // make sure we do not cancel invalidate requests 14417 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14418 14419 final int left = mLeft + (int) region.left; 14420 final int top = mTop + (int) region.top; 14421 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14422 top + (int) (region.height() + .5f)); 14423 } 14424 } 14425 return more; 14426 } 14427 14428 /** 14429 * This method is called by getDisplayList() when a display list is recorded for a View. 14430 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14431 */ 14432 void setDisplayListProperties(RenderNode renderNode) { 14433 if (renderNode != null) { 14434 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14435 if (mParent instanceof ViewGroup) { 14436 renderNode.setClipToBounds( 14437 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14438 } 14439 float alpha = 1; 14440 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14441 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14442 ViewGroup parentVG = (ViewGroup) mParent; 14443 final Transformation t = parentVG.getChildTransformation(); 14444 if (parentVG.getChildStaticTransformation(this, t)) { 14445 final int transformType = t.getTransformationType(); 14446 if (transformType != Transformation.TYPE_IDENTITY) { 14447 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14448 alpha = t.getAlpha(); 14449 } 14450 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14451 renderNode.setStaticMatrix(t.getMatrix()); 14452 } 14453 } 14454 } 14455 } 14456 if (mTransformationInfo != null) { 14457 alpha *= getFinalAlpha(); 14458 if (alpha < 1) { 14459 final int multipliedAlpha = (int) (255 * alpha); 14460 if (onSetAlpha(multipliedAlpha)) { 14461 alpha = 1; 14462 } 14463 } 14464 renderNode.setAlpha(alpha); 14465 } else if (alpha < 1) { 14466 renderNode.setAlpha(alpha); 14467 } 14468 } 14469 } 14470 14471 /** 14472 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14473 * This draw() method is an implementation detail and is not intended to be overridden or 14474 * to be called from anywhere else other than ViewGroup.drawChild(). 14475 */ 14476 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14477 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14478 boolean more = false; 14479 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14480 final int flags = parent.mGroupFlags; 14481 14482 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14483 parent.getChildTransformation().clear(); 14484 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14485 } 14486 14487 Transformation transformToApply = null; 14488 boolean concatMatrix = false; 14489 14490 boolean scalingRequired = false; 14491 boolean caching; 14492 int layerType = getLayerType(); 14493 14494 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14495 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14496 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14497 caching = true; 14498 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14499 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14500 } else { 14501 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14502 } 14503 14504 final Animation a = getAnimation(); 14505 if (a != null) { 14506 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14507 concatMatrix = a.willChangeTransformationMatrix(); 14508 if (concatMatrix) { 14509 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14510 } 14511 transformToApply = parent.getChildTransformation(); 14512 } else { 14513 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14514 // No longer animating: clear out old animation matrix 14515 mRenderNode.setAnimationMatrix(null); 14516 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14517 } 14518 if (!useDisplayListProperties && 14519 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14520 final Transformation t = parent.getChildTransformation(); 14521 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14522 if (hasTransform) { 14523 final int transformType = t.getTransformationType(); 14524 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14525 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14526 } 14527 } 14528 } 14529 14530 concatMatrix |= !childHasIdentityMatrix; 14531 14532 // Sets the flag as early as possible to allow draw() implementations 14533 // to call invalidate() successfully when doing animations 14534 mPrivateFlags |= PFLAG_DRAWN; 14535 14536 if (!concatMatrix && 14537 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14538 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14539 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14540 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14541 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14542 return more; 14543 } 14544 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14545 14546 if (hardwareAccelerated) { 14547 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14548 // retain the flag's value temporarily in the mRecreateDisplayList flag 14549 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14550 mPrivateFlags &= ~PFLAG_INVALIDATED; 14551 } 14552 14553 RenderNode displayList = null; 14554 Bitmap cache = null; 14555 boolean hasDisplayList = false; 14556 if (caching) { 14557 if (!hardwareAccelerated) { 14558 if (layerType != LAYER_TYPE_NONE) { 14559 layerType = LAYER_TYPE_SOFTWARE; 14560 buildDrawingCache(true); 14561 } 14562 cache = getDrawingCache(true); 14563 } else { 14564 switch (layerType) { 14565 case LAYER_TYPE_SOFTWARE: 14566 if (useDisplayListProperties) { 14567 hasDisplayList = canHaveDisplayList(); 14568 } else { 14569 buildDrawingCache(true); 14570 cache = getDrawingCache(true); 14571 } 14572 break; 14573 case LAYER_TYPE_HARDWARE: 14574 if (useDisplayListProperties) { 14575 hasDisplayList = canHaveDisplayList(); 14576 } 14577 break; 14578 case LAYER_TYPE_NONE: 14579 // Delay getting the display list until animation-driven alpha values are 14580 // set up and possibly passed on to the view 14581 hasDisplayList = canHaveDisplayList(); 14582 break; 14583 } 14584 } 14585 } 14586 useDisplayListProperties &= hasDisplayList; 14587 if (useDisplayListProperties) { 14588 displayList = getDisplayList(); 14589 if (!displayList.isValid()) { 14590 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14591 // to getDisplayList(), the display list will be marked invalid and we should not 14592 // try to use it again. 14593 displayList = null; 14594 hasDisplayList = false; 14595 useDisplayListProperties = false; 14596 } 14597 } 14598 14599 int sx = 0; 14600 int sy = 0; 14601 if (!hasDisplayList) { 14602 computeScroll(); 14603 sx = mScrollX; 14604 sy = mScrollY; 14605 } 14606 14607 final boolean hasNoCache = cache == null || hasDisplayList; 14608 final boolean offsetForScroll = cache == null && !hasDisplayList && 14609 layerType != LAYER_TYPE_HARDWARE; 14610 14611 int restoreTo = -1; 14612 if (!useDisplayListProperties || transformToApply != null) { 14613 restoreTo = canvas.save(); 14614 } 14615 if (offsetForScroll) { 14616 canvas.translate(mLeft - sx, mTop - sy); 14617 } else { 14618 if (!useDisplayListProperties) { 14619 canvas.translate(mLeft, mTop); 14620 } 14621 if (scalingRequired) { 14622 if (useDisplayListProperties) { 14623 // TODO: Might not need this if we put everything inside the DL 14624 restoreTo = canvas.save(); 14625 } 14626 // mAttachInfo cannot be null, otherwise scalingRequired == false 14627 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14628 canvas.scale(scale, scale); 14629 } 14630 } 14631 14632 float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14633 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14634 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14635 if (transformToApply != null || !childHasIdentityMatrix) { 14636 int transX = 0; 14637 int transY = 0; 14638 14639 if (offsetForScroll) { 14640 transX = -sx; 14641 transY = -sy; 14642 } 14643 14644 if (transformToApply != null) { 14645 if (concatMatrix) { 14646 if (useDisplayListProperties) { 14647 displayList.setAnimationMatrix(transformToApply.getMatrix()); 14648 } else { 14649 // Undo the scroll translation, apply the transformation matrix, 14650 // then redo the scroll translate to get the correct result. 14651 canvas.translate(-transX, -transY); 14652 canvas.concat(transformToApply.getMatrix()); 14653 canvas.translate(transX, transY); 14654 } 14655 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14656 } 14657 14658 float transformAlpha = transformToApply.getAlpha(); 14659 if (transformAlpha < 1) { 14660 alpha *= transformAlpha; 14661 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14662 } 14663 } 14664 14665 if (!childHasIdentityMatrix && !useDisplayListProperties) { 14666 canvas.translate(-transX, -transY); 14667 canvas.concat(getMatrix()); 14668 canvas.translate(transX, transY); 14669 } 14670 } 14671 14672 // Deal with alpha if it is or used to be <1 14673 if (alpha < 1 || 14674 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14675 if (alpha < 1) { 14676 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14677 } else { 14678 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14679 } 14680 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14681 if (hasNoCache) { 14682 final int multipliedAlpha = (int) (255 * alpha); 14683 if (!onSetAlpha(multipliedAlpha)) { 14684 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14685 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14686 layerType != LAYER_TYPE_NONE) { 14687 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14688 } 14689 if (useDisplayListProperties) { 14690 displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14691 } else if (layerType == LAYER_TYPE_NONE) { 14692 final int scrollX = hasDisplayList ? 0 : sx; 14693 final int scrollY = hasDisplayList ? 0 : sy; 14694 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 14695 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 14696 } 14697 } else { 14698 // Alpha is handled by the child directly, clobber the layer's alpha 14699 mPrivateFlags |= PFLAG_ALPHA_SET; 14700 } 14701 } 14702 } 14703 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14704 onSetAlpha(255); 14705 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14706 } 14707 14708 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 14709 !useDisplayListProperties && cache == null) { 14710 if (offsetForScroll) { 14711 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14712 } else { 14713 if (!scalingRequired || cache == null) { 14714 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14715 } else { 14716 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14717 } 14718 } 14719 } 14720 14721 if (!useDisplayListProperties && hasDisplayList) { 14722 displayList = getDisplayList(); 14723 if (!displayList.isValid()) { 14724 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14725 // to getDisplayList(), the display list will be marked invalid and we should not 14726 // try to use it again. 14727 displayList = null; 14728 hasDisplayList = false; 14729 } 14730 } 14731 14732 if (hasNoCache) { 14733 boolean layerRendered = false; 14734 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 14735 final HardwareLayer layer = getHardwareLayer(); 14736 if (layer != null && layer.isValid()) { 14737 mLayerPaint.setAlpha((int) (alpha * 255)); 14738 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14739 layerRendered = true; 14740 } else { 14741 final int scrollX = hasDisplayList ? 0 : sx; 14742 final int scrollY = hasDisplayList ? 0 : sy; 14743 canvas.saveLayer(scrollX, scrollY, 14744 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14745 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14746 } 14747 } 14748 14749 if (!layerRendered) { 14750 if (!hasDisplayList) { 14751 // Fast path for layouts with no backgrounds 14752 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14753 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14754 dispatchDraw(canvas); 14755 } else { 14756 draw(canvas); 14757 } 14758 } else { 14759 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14760 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 14761 } 14762 } 14763 } else if (cache != null) { 14764 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14765 Paint cachePaint; 14766 14767 if (layerType == LAYER_TYPE_NONE) { 14768 cachePaint = parent.mCachePaint; 14769 if (cachePaint == null) { 14770 cachePaint = new Paint(); 14771 cachePaint.setDither(false); 14772 parent.mCachePaint = cachePaint; 14773 } 14774 if (alpha < 1) { 14775 cachePaint.setAlpha((int) (alpha * 255)); 14776 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14777 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14778 cachePaint.setAlpha(255); 14779 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14780 } 14781 } else { 14782 cachePaint = mLayerPaint; 14783 cachePaint.setAlpha((int) (alpha * 255)); 14784 } 14785 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14786 } 14787 14788 if (restoreTo >= 0) { 14789 canvas.restoreToCount(restoreTo); 14790 } 14791 14792 if (a != null && !more) { 14793 if (!hardwareAccelerated && !a.getFillAfter()) { 14794 onSetAlpha(255); 14795 } 14796 parent.finishAnimatingView(this, a); 14797 } 14798 14799 if (more && hardwareAccelerated) { 14800 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14801 // alpha animations should cause the child to recreate its display list 14802 invalidate(true); 14803 } 14804 } 14805 14806 mRecreateDisplayList = false; 14807 14808 return more; 14809 } 14810 14811 /** 14812 * Manually render this view (and all of its children) to the given Canvas. 14813 * The view must have already done a full layout before this function is 14814 * called. When implementing a view, implement 14815 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14816 * If you do need to override this method, call the superclass version. 14817 * 14818 * @param canvas The Canvas to which the View is rendered. 14819 */ 14820 public void draw(Canvas canvas) { 14821 if (mClipBounds != null) { 14822 canvas.clipRect(mClipBounds); 14823 } 14824 final int privateFlags = mPrivateFlags; 14825 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14826 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14827 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14828 14829 /* 14830 * Draw traversal performs several drawing steps which must be executed 14831 * in the appropriate order: 14832 * 14833 * 1. Draw the background 14834 * 2. If necessary, save the canvas' layers to prepare for fading 14835 * 3. Draw view's content 14836 * 4. Draw children 14837 * 5. If necessary, draw the fading edges and restore layers 14838 * 6. Draw decorations (scrollbars for instance) 14839 */ 14840 14841 // Step 1, draw the background, if needed 14842 int saveCount; 14843 14844 if (!dirtyOpaque) { 14845 drawBackground(canvas); 14846 } 14847 14848 // skip step 2 & 5 if possible (common case) 14849 final int viewFlags = mViewFlags; 14850 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14851 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14852 if (!verticalEdges && !horizontalEdges) { 14853 // Step 3, draw the content 14854 if (!dirtyOpaque) onDraw(canvas); 14855 14856 // Step 4, draw the children 14857 dispatchDraw(canvas); 14858 14859 // Step 6, draw decorations (scrollbars) 14860 onDrawScrollBars(canvas); 14861 14862 if (mOverlay != null && !mOverlay.isEmpty()) { 14863 mOverlay.getOverlayView().dispatchDraw(canvas); 14864 } 14865 14866 // we're done... 14867 return; 14868 } 14869 14870 /* 14871 * Here we do the full fledged routine... 14872 * (this is an uncommon case where speed matters less, 14873 * this is why we repeat some of the tests that have been 14874 * done above) 14875 */ 14876 14877 boolean drawTop = false; 14878 boolean drawBottom = false; 14879 boolean drawLeft = false; 14880 boolean drawRight = false; 14881 14882 float topFadeStrength = 0.0f; 14883 float bottomFadeStrength = 0.0f; 14884 float leftFadeStrength = 0.0f; 14885 float rightFadeStrength = 0.0f; 14886 14887 // Step 2, save the canvas' layers 14888 int paddingLeft = mPaddingLeft; 14889 14890 final boolean offsetRequired = isPaddingOffsetRequired(); 14891 if (offsetRequired) { 14892 paddingLeft += getLeftPaddingOffset(); 14893 } 14894 14895 int left = mScrollX + paddingLeft; 14896 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14897 int top = mScrollY + getFadeTop(offsetRequired); 14898 int bottom = top + getFadeHeight(offsetRequired); 14899 14900 if (offsetRequired) { 14901 right += getRightPaddingOffset(); 14902 bottom += getBottomPaddingOffset(); 14903 } 14904 14905 final ScrollabilityCache scrollabilityCache = mScrollCache; 14906 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14907 int length = (int) fadeHeight; 14908 14909 // clip the fade length if top and bottom fades overlap 14910 // overlapping fades produce odd-looking artifacts 14911 if (verticalEdges && (top + length > bottom - length)) { 14912 length = (bottom - top) / 2; 14913 } 14914 14915 // also clip horizontal fades if necessary 14916 if (horizontalEdges && (left + length > right - length)) { 14917 length = (right - left) / 2; 14918 } 14919 14920 if (verticalEdges) { 14921 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14922 drawTop = topFadeStrength * fadeHeight > 1.0f; 14923 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14924 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14925 } 14926 14927 if (horizontalEdges) { 14928 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14929 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14930 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14931 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14932 } 14933 14934 saveCount = canvas.getSaveCount(); 14935 14936 int solidColor = getSolidColor(); 14937 if (solidColor == 0) { 14938 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14939 14940 if (drawTop) { 14941 canvas.saveLayer(left, top, right, top + length, null, flags); 14942 } 14943 14944 if (drawBottom) { 14945 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14946 } 14947 14948 if (drawLeft) { 14949 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14950 } 14951 14952 if (drawRight) { 14953 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14954 } 14955 } else { 14956 scrollabilityCache.setFadeColor(solidColor); 14957 } 14958 14959 // Step 3, draw the content 14960 if (!dirtyOpaque) onDraw(canvas); 14961 14962 // Step 4, draw the children 14963 dispatchDraw(canvas); 14964 14965 // Step 5, draw the fade effect and restore layers 14966 final Paint p = scrollabilityCache.paint; 14967 final Matrix matrix = scrollabilityCache.matrix; 14968 final Shader fade = scrollabilityCache.shader; 14969 14970 if (drawTop) { 14971 matrix.setScale(1, fadeHeight * topFadeStrength); 14972 matrix.postTranslate(left, top); 14973 fade.setLocalMatrix(matrix); 14974 canvas.drawRect(left, top, right, top + length, p); 14975 } 14976 14977 if (drawBottom) { 14978 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14979 matrix.postRotate(180); 14980 matrix.postTranslate(left, bottom); 14981 fade.setLocalMatrix(matrix); 14982 canvas.drawRect(left, bottom - length, right, bottom, p); 14983 } 14984 14985 if (drawLeft) { 14986 matrix.setScale(1, fadeHeight * leftFadeStrength); 14987 matrix.postRotate(-90); 14988 matrix.postTranslate(left, top); 14989 fade.setLocalMatrix(matrix); 14990 canvas.drawRect(left, top, left + length, bottom, p); 14991 } 14992 14993 if (drawRight) { 14994 matrix.setScale(1, fadeHeight * rightFadeStrength); 14995 matrix.postRotate(90); 14996 matrix.postTranslate(right, top); 14997 fade.setLocalMatrix(matrix); 14998 canvas.drawRect(right - length, top, right, bottom, p); 14999 } 15000 15001 canvas.restoreToCount(saveCount); 15002 15003 // Step 6, draw decorations (scrollbars) 15004 onDrawScrollBars(canvas); 15005 15006 if (mOverlay != null && !mOverlay.isEmpty()) { 15007 mOverlay.getOverlayView().dispatchDraw(canvas); 15008 } 15009 } 15010 15011 /** 15012 * Draws the background onto the specified canvas. 15013 * 15014 * @param canvas Canvas on which to draw the background 15015 */ 15016 private void drawBackground(Canvas canvas) { 15017 final Drawable background = mBackground; 15018 if (background == null) { 15019 return; 15020 } 15021 15022 if (mBackgroundSizeChanged) { 15023 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 15024 mBackgroundSizeChanged = false; 15025 queryOutlineFromBackgroundIfUndefined(); 15026 } 15027 15028 // Attempt to use a display list if requested. 15029 if (canvas.isHardwareAccelerated() && mAttachInfo != null 15030 && mAttachInfo.mHardwareRenderer != null) { 15031 mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList); 15032 15033 final RenderNode displayList = mBackgroundDisplayList; 15034 if (displayList != null && displayList.isValid()) { 15035 setBackgroundDisplayListProperties(displayList); 15036 ((HardwareCanvas) canvas).drawDisplayList(displayList); 15037 return; 15038 } 15039 } 15040 15041 final int scrollX = mScrollX; 15042 final int scrollY = mScrollY; 15043 if ((scrollX | scrollY) == 0) { 15044 background.draw(canvas); 15045 } else { 15046 canvas.translate(scrollX, scrollY); 15047 background.draw(canvas); 15048 canvas.translate(-scrollX, -scrollY); 15049 } 15050 } 15051 15052 /** 15053 * Set up background drawable display list properties. 15054 * 15055 * @param displayList Valid display list for the background drawable 15056 */ 15057 private void setBackgroundDisplayListProperties(RenderNode displayList) { 15058 displayList.setTranslationX(mScrollX); 15059 displayList.setTranslationY(mScrollY); 15060 } 15061 15062 /** 15063 * Creates a new display list or updates the existing display list for the 15064 * specified Drawable. 15065 * 15066 * @param drawable Drawable for which to create a display list 15067 * @param displayList Existing display list, or {@code null} 15068 * @return A valid display list for the specified drawable 15069 */ 15070 private RenderNode getDrawableDisplayList(Drawable drawable, RenderNode displayList) { 15071 if (displayList == null) { 15072 displayList = RenderNode.create(drawable.getClass().getName()); 15073 } 15074 15075 final Rect bounds = drawable.getBounds(); 15076 final int width = bounds.width(); 15077 final int height = bounds.height(); 15078 final HardwareCanvas canvas = displayList.start(width, height); 15079 try { 15080 drawable.draw(canvas); 15081 } finally { 15082 displayList.end(canvas); 15083 } 15084 15085 // Set up drawable properties that are view-independent. 15086 displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15087 displayList.setProjectBackwards(drawable.isProjected()); 15088 displayList.setProjectionReceiver(true); 15089 displayList.setClipToBounds(false); 15090 return displayList; 15091 } 15092 15093 /** 15094 * Returns the overlay for this view, creating it if it does not yet exist. 15095 * Adding drawables to the overlay will cause them to be displayed whenever 15096 * the view itself is redrawn. Objects in the overlay should be actively 15097 * managed: remove them when they should not be displayed anymore. The 15098 * overlay will always have the same size as its host view. 15099 * 15100 * <p>Note: Overlays do not currently work correctly with {@link 15101 * SurfaceView} or {@link TextureView}; contents in overlays for these 15102 * types of views may not display correctly.</p> 15103 * 15104 * @return The ViewOverlay object for this view. 15105 * @see ViewOverlay 15106 */ 15107 public ViewOverlay getOverlay() { 15108 if (mOverlay == null) { 15109 mOverlay = new ViewOverlay(mContext, this); 15110 } 15111 return mOverlay; 15112 } 15113 15114 /** 15115 * Override this if your view is known to always be drawn on top of a solid color background, 15116 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15117 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15118 * should be set to 0xFF. 15119 * 15120 * @see #setVerticalFadingEdgeEnabled(boolean) 15121 * @see #setHorizontalFadingEdgeEnabled(boolean) 15122 * 15123 * @return The known solid color background for this view, or 0 if the color may vary 15124 */ 15125 @ViewDebug.ExportedProperty(category = "drawing") 15126 public int getSolidColor() { 15127 return 0; 15128 } 15129 15130 /** 15131 * Build a human readable string representation of the specified view flags. 15132 * 15133 * @param flags the view flags to convert to a string 15134 * @return a String representing the supplied flags 15135 */ 15136 private static String printFlags(int flags) { 15137 String output = ""; 15138 int numFlags = 0; 15139 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15140 output += "TAKES_FOCUS"; 15141 numFlags++; 15142 } 15143 15144 switch (flags & VISIBILITY_MASK) { 15145 case INVISIBLE: 15146 if (numFlags > 0) { 15147 output += " "; 15148 } 15149 output += "INVISIBLE"; 15150 // USELESS HERE numFlags++; 15151 break; 15152 case GONE: 15153 if (numFlags > 0) { 15154 output += " "; 15155 } 15156 output += "GONE"; 15157 // USELESS HERE numFlags++; 15158 break; 15159 default: 15160 break; 15161 } 15162 return output; 15163 } 15164 15165 /** 15166 * Build a human readable string representation of the specified private 15167 * view flags. 15168 * 15169 * @param privateFlags the private view flags to convert to a string 15170 * @return a String representing the supplied flags 15171 */ 15172 private static String printPrivateFlags(int privateFlags) { 15173 String output = ""; 15174 int numFlags = 0; 15175 15176 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15177 output += "WANTS_FOCUS"; 15178 numFlags++; 15179 } 15180 15181 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15182 if (numFlags > 0) { 15183 output += " "; 15184 } 15185 output += "FOCUSED"; 15186 numFlags++; 15187 } 15188 15189 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15190 if (numFlags > 0) { 15191 output += " "; 15192 } 15193 output += "SELECTED"; 15194 numFlags++; 15195 } 15196 15197 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15198 if (numFlags > 0) { 15199 output += " "; 15200 } 15201 output += "IS_ROOT_NAMESPACE"; 15202 numFlags++; 15203 } 15204 15205 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15206 if (numFlags > 0) { 15207 output += " "; 15208 } 15209 output += "HAS_BOUNDS"; 15210 numFlags++; 15211 } 15212 15213 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15214 if (numFlags > 0) { 15215 output += " "; 15216 } 15217 output += "DRAWN"; 15218 // USELESS HERE numFlags++; 15219 } 15220 return output; 15221 } 15222 15223 /** 15224 * <p>Indicates whether or not this view's layout will be requested during 15225 * the next hierarchy layout pass.</p> 15226 * 15227 * @return true if the layout will be forced during next layout pass 15228 */ 15229 public boolean isLayoutRequested() { 15230 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15231 } 15232 15233 /** 15234 * Return true if o is a ViewGroup that is laying out using optical bounds. 15235 * @hide 15236 */ 15237 public static boolean isLayoutModeOptical(Object o) { 15238 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15239 } 15240 15241 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15242 Insets parentInsets = mParent instanceof View ? 15243 ((View) mParent).getOpticalInsets() : Insets.NONE; 15244 Insets childInsets = getOpticalInsets(); 15245 return setFrame( 15246 left + parentInsets.left - childInsets.left, 15247 top + parentInsets.top - childInsets.top, 15248 right + parentInsets.left + childInsets.right, 15249 bottom + parentInsets.top + childInsets.bottom); 15250 } 15251 15252 /** 15253 * Assign a size and position to a view and all of its 15254 * descendants 15255 * 15256 * <p>This is the second phase of the layout mechanism. 15257 * (The first is measuring). In this phase, each parent calls 15258 * layout on all of its children to position them. 15259 * This is typically done using the child measurements 15260 * that were stored in the measure pass().</p> 15261 * 15262 * <p>Derived classes should not override this method. 15263 * Derived classes with children should override 15264 * onLayout. In that method, they should 15265 * call layout on each of their children.</p> 15266 * 15267 * @param l Left position, relative to parent 15268 * @param t Top position, relative to parent 15269 * @param r Right position, relative to parent 15270 * @param b Bottom position, relative to parent 15271 */ 15272 @SuppressWarnings({"unchecked"}) 15273 public void layout(int l, int t, int r, int b) { 15274 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15275 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15276 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15277 } 15278 15279 int oldL = mLeft; 15280 int oldT = mTop; 15281 int oldB = mBottom; 15282 int oldR = mRight; 15283 15284 boolean changed = isLayoutModeOptical(mParent) ? 15285 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15286 15287 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15288 onLayout(changed, l, t, r, b); 15289 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15290 15291 ListenerInfo li = mListenerInfo; 15292 if (li != null && li.mOnLayoutChangeListeners != null) { 15293 ArrayList<OnLayoutChangeListener> listenersCopy = 15294 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15295 int numListeners = listenersCopy.size(); 15296 for (int i = 0; i < numListeners; ++i) { 15297 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15298 } 15299 } 15300 } 15301 15302 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15303 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15304 } 15305 15306 /** 15307 * Called from layout when this view should 15308 * assign a size and position to each of its children. 15309 * 15310 * Derived classes with children should override 15311 * this method and call layout on each of 15312 * their children. 15313 * @param changed This is a new size or position for this view 15314 * @param left Left position, relative to parent 15315 * @param top Top position, relative to parent 15316 * @param right Right position, relative to parent 15317 * @param bottom Bottom position, relative to parent 15318 */ 15319 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15320 } 15321 15322 /** 15323 * Assign a size and position to this view. 15324 * 15325 * This is called from layout. 15326 * 15327 * @param left Left position, relative to parent 15328 * @param top Top position, relative to parent 15329 * @param right Right position, relative to parent 15330 * @param bottom Bottom position, relative to parent 15331 * @return true if the new size and position are different than the 15332 * previous ones 15333 * {@hide} 15334 */ 15335 protected boolean setFrame(int left, int top, int right, int bottom) { 15336 boolean changed = false; 15337 15338 if (DBG) { 15339 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15340 + right + "," + bottom + ")"); 15341 } 15342 15343 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15344 changed = true; 15345 15346 // Remember our drawn bit 15347 int drawn = mPrivateFlags & PFLAG_DRAWN; 15348 15349 int oldWidth = mRight - mLeft; 15350 int oldHeight = mBottom - mTop; 15351 int newWidth = right - left; 15352 int newHeight = bottom - top; 15353 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15354 15355 // Invalidate our old position 15356 invalidate(sizeChanged); 15357 15358 mLeft = left; 15359 mTop = top; 15360 mRight = right; 15361 mBottom = bottom; 15362 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15363 15364 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15365 15366 15367 if (sizeChanged) { 15368 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15369 } 15370 15371 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 15372 // If we are visible, force the DRAWN bit to on so that 15373 // this invalidate will go through (at least to our parent). 15374 // This is because someone may have invalidated this view 15375 // before this call to setFrame came in, thereby clearing 15376 // the DRAWN bit. 15377 mPrivateFlags |= PFLAG_DRAWN; 15378 invalidate(sizeChanged); 15379 // parent display list may need to be recreated based on a change in the bounds 15380 // of any child 15381 invalidateParentCaches(); 15382 } 15383 15384 // Reset drawn bit to original value (invalidate turns it off) 15385 mPrivateFlags |= drawn; 15386 15387 mBackgroundSizeChanged = true; 15388 15389 notifySubtreeAccessibilityStateChangedIfNeeded(); 15390 } 15391 return changed; 15392 } 15393 15394 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15395 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15396 if (mOverlay != null) { 15397 mOverlay.getOverlayView().setRight(newWidth); 15398 mOverlay.getOverlayView().setBottom(newHeight); 15399 } 15400 } 15401 15402 /** 15403 * Finalize inflating a view from XML. This is called as the last phase 15404 * of inflation, after all child views have been added. 15405 * 15406 * <p>Even if the subclass overrides onFinishInflate, they should always be 15407 * sure to call the super method, so that we get called. 15408 */ 15409 protected void onFinishInflate() { 15410 } 15411 15412 /** 15413 * Returns the resources associated with this view. 15414 * 15415 * @return Resources object. 15416 */ 15417 public Resources getResources() { 15418 return mResources; 15419 } 15420 15421 /** 15422 * Invalidates the specified Drawable. 15423 * 15424 * @param drawable the drawable to invalidate 15425 */ 15426 @Override 15427 public void invalidateDrawable(@NonNull Drawable drawable) { 15428 if (verifyDrawable(drawable)) { 15429 final Rect dirty = drawable.getDirtyBounds(); 15430 final int scrollX = mScrollX; 15431 final int scrollY = mScrollY; 15432 15433 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15434 dirty.right + scrollX, dirty.bottom + scrollY); 15435 15436 if (drawable == mBackground) { 15437 queryOutlineFromBackgroundIfUndefined(); 15438 } 15439 } 15440 } 15441 15442 /** 15443 * Schedules an action on a drawable to occur at a specified time. 15444 * 15445 * @param who the recipient of the action 15446 * @param what the action to run on the drawable 15447 * @param when the time at which the action must occur. Uses the 15448 * {@link SystemClock#uptimeMillis} timebase. 15449 */ 15450 @Override 15451 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15452 if (verifyDrawable(who) && what != null) { 15453 final long delay = when - SystemClock.uptimeMillis(); 15454 if (mAttachInfo != null) { 15455 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15456 Choreographer.CALLBACK_ANIMATION, what, who, 15457 Choreographer.subtractFrameDelay(delay)); 15458 } else { 15459 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15460 } 15461 } 15462 } 15463 15464 /** 15465 * Cancels a scheduled action on a drawable. 15466 * 15467 * @param who the recipient of the action 15468 * @param what the action to cancel 15469 */ 15470 @Override 15471 public void unscheduleDrawable(Drawable who, Runnable what) { 15472 if (verifyDrawable(who) && what != null) { 15473 if (mAttachInfo != null) { 15474 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15475 Choreographer.CALLBACK_ANIMATION, what, who); 15476 } 15477 ViewRootImpl.getRunQueue().removeCallbacks(what); 15478 } 15479 } 15480 15481 /** 15482 * Unschedule any events associated with the given Drawable. This can be 15483 * used when selecting a new Drawable into a view, so that the previous 15484 * one is completely unscheduled. 15485 * 15486 * @param who The Drawable to unschedule. 15487 * 15488 * @see #drawableStateChanged 15489 */ 15490 public void unscheduleDrawable(Drawable who) { 15491 if (mAttachInfo != null && who != null) { 15492 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15493 Choreographer.CALLBACK_ANIMATION, null, who); 15494 } 15495 } 15496 15497 /** 15498 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15499 * that the View directionality can and will be resolved before its Drawables. 15500 * 15501 * Will call {@link View#onResolveDrawables} when resolution is done. 15502 * 15503 * @hide 15504 */ 15505 protected void resolveDrawables() { 15506 // Drawables resolution may need to happen before resolving the layout direction (which is 15507 // done only during the measure() call). 15508 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15509 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15510 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15511 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15512 // direction to be resolved as its resolved value will be the same as its raw value. 15513 if (!isLayoutDirectionResolved() && 15514 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15515 return; 15516 } 15517 15518 final int layoutDirection = isLayoutDirectionResolved() ? 15519 getLayoutDirection() : getRawLayoutDirection(); 15520 15521 if (mBackground != null) { 15522 mBackground.setLayoutDirection(layoutDirection); 15523 } 15524 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15525 onResolveDrawables(layoutDirection); 15526 } 15527 15528 /** 15529 * Called when layout direction has been resolved. 15530 * 15531 * The default implementation does nothing. 15532 * 15533 * @param layoutDirection The resolved layout direction. 15534 * 15535 * @see #LAYOUT_DIRECTION_LTR 15536 * @see #LAYOUT_DIRECTION_RTL 15537 * 15538 * @hide 15539 */ 15540 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15541 } 15542 15543 /** 15544 * @hide 15545 */ 15546 protected void resetResolvedDrawables() { 15547 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15548 } 15549 15550 private boolean isDrawablesResolved() { 15551 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15552 } 15553 15554 /** 15555 * If your view subclass is displaying its own Drawable objects, it should 15556 * override this function and return true for any Drawable it is 15557 * displaying. This allows animations for those drawables to be 15558 * scheduled. 15559 * 15560 * <p>Be sure to call through to the super class when overriding this 15561 * function. 15562 * 15563 * @param who The Drawable to verify. Return true if it is one you are 15564 * displaying, else return the result of calling through to the 15565 * super class. 15566 * 15567 * @return boolean If true than the Drawable is being displayed in the 15568 * view; else false and it is not allowed to animate. 15569 * 15570 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15571 * @see #drawableStateChanged() 15572 */ 15573 protected boolean verifyDrawable(Drawable who) { 15574 return who == mBackground; 15575 } 15576 15577 /** 15578 * This function is called whenever the state of the view changes in such 15579 * a way that it impacts the state of drawables being shown. 15580 * <p> 15581 * If the View has a StateListAnimator, it will also be called to run necessary state 15582 * change animations. 15583 * <p> 15584 * Be sure to call through to the superclass when overriding this function. 15585 * 15586 * @see Drawable#setState(int[]) 15587 */ 15588 protected void drawableStateChanged() { 15589 final Drawable d = mBackground; 15590 if (d != null && d.isStateful()) { 15591 d.setState(getDrawableState()); 15592 } 15593 15594 if (mStateListAnimator != null) { 15595 mStateListAnimator.setState(getDrawableState()); 15596 } 15597 } 15598 15599 /** 15600 * Call this to force a view to update its drawable state. This will cause 15601 * drawableStateChanged to be called on this view. Views that are interested 15602 * in the new state should call getDrawableState. 15603 * 15604 * @see #drawableStateChanged 15605 * @see #getDrawableState 15606 */ 15607 public void refreshDrawableState() { 15608 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15609 drawableStateChanged(); 15610 15611 ViewParent parent = mParent; 15612 if (parent != null) { 15613 parent.childDrawableStateChanged(this); 15614 } 15615 } 15616 15617 /** 15618 * Return an array of resource IDs of the drawable states representing the 15619 * current state of the view. 15620 * 15621 * @return The current drawable state 15622 * 15623 * @see Drawable#setState(int[]) 15624 * @see #drawableStateChanged() 15625 * @see #onCreateDrawableState(int) 15626 */ 15627 public final int[] getDrawableState() { 15628 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15629 return mDrawableState; 15630 } else { 15631 mDrawableState = onCreateDrawableState(0); 15632 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15633 return mDrawableState; 15634 } 15635 } 15636 15637 /** 15638 * Generate the new {@link android.graphics.drawable.Drawable} state for 15639 * this view. This is called by the view 15640 * system when the cached Drawable state is determined to be invalid. To 15641 * retrieve the current state, you should use {@link #getDrawableState}. 15642 * 15643 * @param extraSpace if non-zero, this is the number of extra entries you 15644 * would like in the returned array in which you can place your own 15645 * states. 15646 * 15647 * @return Returns an array holding the current {@link Drawable} state of 15648 * the view. 15649 * 15650 * @see #mergeDrawableStates(int[], int[]) 15651 */ 15652 protected int[] onCreateDrawableState(int extraSpace) { 15653 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15654 mParent instanceof View) { 15655 return ((View) mParent).onCreateDrawableState(extraSpace); 15656 } 15657 15658 int[] drawableState; 15659 15660 int privateFlags = mPrivateFlags; 15661 15662 int viewStateIndex = 0; 15663 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15664 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15665 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15666 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15667 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15668 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15669 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15670 HardwareRenderer.isAvailable()) { 15671 // This is set if HW acceleration is requested, even if the current 15672 // process doesn't allow it. This is just to allow app preview 15673 // windows to better match their app. 15674 viewStateIndex |= VIEW_STATE_ACCELERATED; 15675 } 15676 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15677 15678 final int privateFlags2 = mPrivateFlags2; 15679 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15680 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15681 15682 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15683 15684 //noinspection ConstantIfStatement 15685 if (false) { 15686 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15687 Log.i("View", toString() 15688 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15689 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15690 + " fo=" + hasFocus() 15691 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15692 + " wf=" + hasWindowFocus() 15693 + ": " + Arrays.toString(drawableState)); 15694 } 15695 15696 if (extraSpace == 0) { 15697 return drawableState; 15698 } 15699 15700 final int[] fullState; 15701 if (drawableState != null) { 15702 fullState = new int[drawableState.length + extraSpace]; 15703 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15704 } else { 15705 fullState = new int[extraSpace]; 15706 } 15707 15708 return fullState; 15709 } 15710 15711 /** 15712 * Merge your own state values in <var>additionalState</var> into the base 15713 * state values <var>baseState</var> that were returned by 15714 * {@link #onCreateDrawableState(int)}. 15715 * 15716 * @param baseState The base state values returned by 15717 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15718 * own additional state values. 15719 * 15720 * @param additionalState The additional state values you would like 15721 * added to <var>baseState</var>; this array is not modified. 15722 * 15723 * @return As a convenience, the <var>baseState</var> array you originally 15724 * passed into the function is returned. 15725 * 15726 * @see #onCreateDrawableState(int) 15727 */ 15728 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15729 final int N = baseState.length; 15730 int i = N - 1; 15731 while (i >= 0 && baseState[i] == 0) { 15732 i--; 15733 } 15734 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15735 return baseState; 15736 } 15737 15738 /** 15739 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15740 * on all Drawable objects associated with this view. 15741 * <p> 15742 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 15743 * attached to this view. 15744 */ 15745 public void jumpDrawablesToCurrentState() { 15746 if (mBackground != null) { 15747 mBackground.jumpToCurrentState(); 15748 } 15749 if (mStateListAnimator != null) { 15750 mStateListAnimator.jumpToCurrentState(); 15751 } 15752 } 15753 15754 /** 15755 * Sets the background color for this view. 15756 * @param color the color of the background 15757 */ 15758 @RemotableViewMethod 15759 public void setBackgroundColor(int color) { 15760 if (mBackground instanceof ColorDrawable) { 15761 ((ColorDrawable) mBackground.mutate()).setColor(color); 15762 computeOpaqueFlags(); 15763 mBackgroundResource = 0; 15764 } else { 15765 setBackground(new ColorDrawable(color)); 15766 } 15767 } 15768 15769 /** 15770 * Set the background to a given resource. The resource should refer to 15771 * a Drawable object or 0 to remove the background. 15772 * @param resid The identifier of the resource. 15773 * 15774 * @attr ref android.R.styleable#View_background 15775 */ 15776 @RemotableViewMethod 15777 public void setBackgroundResource(int resid) { 15778 if (resid != 0 && resid == mBackgroundResource) { 15779 return; 15780 } 15781 15782 Drawable d= null; 15783 if (resid != 0) { 15784 d = mContext.getDrawable(resid); 15785 } 15786 setBackground(d); 15787 15788 mBackgroundResource = resid; 15789 } 15790 15791 /** 15792 * Set the background to a given Drawable, or remove the background. If the 15793 * background has padding, this View's padding is set to the background's 15794 * padding. However, when a background is removed, this View's padding isn't 15795 * touched. If setting the padding is desired, please use 15796 * {@link #setPadding(int, int, int, int)}. 15797 * 15798 * @param background The Drawable to use as the background, or null to remove the 15799 * background 15800 */ 15801 public void setBackground(Drawable background) { 15802 //noinspection deprecation 15803 setBackgroundDrawable(background); 15804 } 15805 15806 /** 15807 * @deprecated use {@link #setBackground(Drawable)} instead 15808 */ 15809 @Deprecated 15810 public void setBackgroundDrawable(Drawable background) { 15811 computeOpaqueFlags(); 15812 15813 if (background == mBackground) { 15814 return; 15815 } 15816 15817 boolean requestLayout = false; 15818 15819 mBackgroundResource = 0; 15820 15821 /* 15822 * Regardless of whether we're setting a new background or not, we want 15823 * to clear the previous drawable. 15824 */ 15825 if (mBackground != null) { 15826 mBackground.setCallback(null); 15827 unscheduleDrawable(mBackground); 15828 } 15829 15830 if (background != null) { 15831 Rect padding = sThreadLocal.get(); 15832 if (padding == null) { 15833 padding = new Rect(); 15834 sThreadLocal.set(padding); 15835 } 15836 resetResolvedDrawables(); 15837 background.setLayoutDirection(getLayoutDirection()); 15838 if (background.getPadding(padding)) { 15839 resetResolvedPadding(); 15840 switch (background.getLayoutDirection()) { 15841 case LAYOUT_DIRECTION_RTL: 15842 mUserPaddingLeftInitial = padding.right; 15843 mUserPaddingRightInitial = padding.left; 15844 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15845 break; 15846 case LAYOUT_DIRECTION_LTR: 15847 default: 15848 mUserPaddingLeftInitial = padding.left; 15849 mUserPaddingRightInitial = padding.right; 15850 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15851 } 15852 mLeftPaddingDefined = false; 15853 mRightPaddingDefined = false; 15854 } 15855 15856 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15857 // if it has a different minimum size, we should layout again 15858 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 15859 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15860 requestLayout = true; 15861 } 15862 15863 background.setCallback(this); 15864 if (background.isStateful()) { 15865 background.setState(getDrawableState()); 15866 } 15867 background.setVisible(getVisibility() == VISIBLE, false); 15868 mBackground = background; 15869 15870 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15871 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15872 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15873 requestLayout = true; 15874 } 15875 } else { 15876 /* Remove the background */ 15877 mBackground = null; 15878 15879 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15880 /* 15881 * This view ONLY drew the background before and we're removing 15882 * the background, so now it won't draw anything 15883 * (hence we SKIP_DRAW) 15884 */ 15885 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15886 mPrivateFlags |= PFLAG_SKIP_DRAW; 15887 } 15888 15889 /* 15890 * When the background is set, we try to apply its padding to this 15891 * View. When the background is removed, we don't touch this View's 15892 * padding. This is noted in the Javadocs. Hence, we don't need to 15893 * requestLayout(), the invalidate() below is sufficient. 15894 */ 15895 15896 // The old background's minimum size could have affected this 15897 // View's layout, so let's requestLayout 15898 requestLayout = true; 15899 } 15900 15901 computeOpaqueFlags(); 15902 15903 if (requestLayout) { 15904 requestLayout(); 15905 } 15906 15907 mBackgroundSizeChanged = true; 15908 invalidate(true); 15909 } 15910 15911 /** 15912 * Gets the background drawable 15913 * 15914 * @return The drawable used as the background for this view, if any. 15915 * 15916 * @see #setBackground(Drawable) 15917 * 15918 * @attr ref android.R.styleable#View_background 15919 */ 15920 public Drawable getBackground() { 15921 return mBackground; 15922 } 15923 15924 /** 15925 * Sets the padding. The view may add on the space required to display 15926 * the scrollbars, depending on the style and visibility of the scrollbars. 15927 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15928 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 15929 * from the values set in this call. 15930 * 15931 * @attr ref android.R.styleable#View_padding 15932 * @attr ref android.R.styleable#View_paddingBottom 15933 * @attr ref android.R.styleable#View_paddingLeft 15934 * @attr ref android.R.styleable#View_paddingRight 15935 * @attr ref android.R.styleable#View_paddingTop 15936 * @param left the left padding in pixels 15937 * @param top the top padding in pixels 15938 * @param right the right padding in pixels 15939 * @param bottom the bottom padding in pixels 15940 */ 15941 public void setPadding(int left, int top, int right, int bottom) { 15942 resetResolvedPadding(); 15943 15944 mUserPaddingStart = UNDEFINED_PADDING; 15945 mUserPaddingEnd = UNDEFINED_PADDING; 15946 15947 mUserPaddingLeftInitial = left; 15948 mUserPaddingRightInitial = right; 15949 15950 mLeftPaddingDefined = true; 15951 mRightPaddingDefined = true; 15952 15953 internalSetPadding(left, top, right, bottom); 15954 } 15955 15956 /** 15957 * @hide 15958 */ 15959 protected void internalSetPadding(int left, int top, int right, int bottom) { 15960 mUserPaddingLeft = left; 15961 mUserPaddingRight = right; 15962 mUserPaddingBottom = bottom; 15963 15964 final int viewFlags = mViewFlags; 15965 boolean changed = false; 15966 15967 // Common case is there are no scroll bars. 15968 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 15969 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 15970 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 15971 ? 0 : getVerticalScrollbarWidth(); 15972 switch (mVerticalScrollbarPosition) { 15973 case SCROLLBAR_POSITION_DEFAULT: 15974 if (isLayoutRtl()) { 15975 left += offset; 15976 } else { 15977 right += offset; 15978 } 15979 break; 15980 case SCROLLBAR_POSITION_RIGHT: 15981 right += offset; 15982 break; 15983 case SCROLLBAR_POSITION_LEFT: 15984 left += offset; 15985 break; 15986 } 15987 } 15988 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 15989 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 15990 ? 0 : getHorizontalScrollbarHeight(); 15991 } 15992 } 15993 15994 if (mPaddingLeft != left) { 15995 changed = true; 15996 mPaddingLeft = left; 15997 } 15998 if (mPaddingTop != top) { 15999 changed = true; 16000 mPaddingTop = top; 16001 } 16002 if (mPaddingRight != right) { 16003 changed = true; 16004 mPaddingRight = right; 16005 } 16006 if (mPaddingBottom != bottom) { 16007 changed = true; 16008 mPaddingBottom = bottom; 16009 } 16010 16011 if (changed) { 16012 requestLayout(); 16013 } 16014 } 16015 16016 /** 16017 * Sets the relative padding. The view may add on the space required to display 16018 * the scrollbars, depending on the style and visibility of the scrollbars. 16019 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16020 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16021 * from the values set in this call. 16022 * 16023 * @attr ref android.R.styleable#View_padding 16024 * @attr ref android.R.styleable#View_paddingBottom 16025 * @attr ref android.R.styleable#View_paddingStart 16026 * @attr ref android.R.styleable#View_paddingEnd 16027 * @attr ref android.R.styleable#View_paddingTop 16028 * @param start the start padding in pixels 16029 * @param top the top padding in pixels 16030 * @param end the end padding in pixels 16031 * @param bottom the bottom padding in pixels 16032 */ 16033 public void setPaddingRelative(int start, int top, int end, int bottom) { 16034 resetResolvedPadding(); 16035 16036 mUserPaddingStart = start; 16037 mUserPaddingEnd = end; 16038 mLeftPaddingDefined = true; 16039 mRightPaddingDefined = true; 16040 16041 switch(getLayoutDirection()) { 16042 case LAYOUT_DIRECTION_RTL: 16043 mUserPaddingLeftInitial = end; 16044 mUserPaddingRightInitial = start; 16045 internalSetPadding(end, top, start, bottom); 16046 break; 16047 case LAYOUT_DIRECTION_LTR: 16048 default: 16049 mUserPaddingLeftInitial = start; 16050 mUserPaddingRightInitial = end; 16051 internalSetPadding(start, top, end, bottom); 16052 } 16053 } 16054 16055 /** 16056 * Returns the top padding of this view. 16057 * 16058 * @return the top padding in pixels 16059 */ 16060 public int getPaddingTop() { 16061 return mPaddingTop; 16062 } 16063 16064 /** 16065 * Returns the bottom padding of this view. If there are inset and enabled 16066 * scrollbars, this value may include the space required to display the 16067 * scrollbars as well. 16068 * 16069 * @return the bottom padding in pixels 16070 */ 16071 public int getPaddingBottom() { 16072 return mPaddingBottom; 16073 } 16074 16075 /** 16076 * Returns the left padding of this view. If there are inset and enabled 16077 * scrollbars, this value may include the space required to display the 16078 * scrollbars as well. 16079 * 16080 * @return the left padding in pixels 16081 */ 16082 public int getPaddingLeft() { 16083 if (!isPaddingResolved()) { 16084 resolvePadding(); 16085 } 16086 return mPaddingLeft; 16087 } 16088 16089 /** 16090 * Returns the start padding of this view depending on its resolved layout direction. 16091 * If there are inset and enabled scrollbars, this value may include the space 16092 * required to display the scrollbars as well. 16093 * 16094 * @return the start padding in pixels 16095 */ 16096 public int getPaddingStart() { 16097 if (!isPaddingResolved()) { 16098 resolvePadding(); 16099 } 16100 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16101 mPaddingRight : mPaddingLeft; 16102 } 16103 16104 /** 16105 * Returns the right padding of this view. If there are inset and enabled 16106 * scrollbars, this value may include the space required to display the 16107 * scrollbars as well. 16108 * 16109 * @return the right padding in pixels 16110 */ 16111 public int getPaddingRight() { 16112 if (!isPaddingResolved()) { 16113 resolvePadding(); 16114 } 16115 return mPaddingRight; 16116 } 16117 16118 /** 16119 * Returns the end padding of this view depending on its resolved layout direction. 16120 * If there are inset and enabled scrollbars, this value may include the space 16121 * required to display the scrollbars as well. 16122 * 16123 * @return the end padding in pixels 16124 */ 16125 public int getPaddingEnd() { 16126 if (!isPaddingResolved()) { 16127 resolvePadding(); 16128 } 16129 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16130 mPaddingLeft : mPaddingRight; 16131 } 16132 16133 /** 16134 * Return if the padding as been set thru relative values 16135 * {@link #setPaddingRelative(int, int, int, int)} or thru 16136 * @attr ref android.R.styleable#View_paddingStart or 16137 * @attr ref android.R.styleable#View_paddingEnd 16138 * 16139 * @return true if the padding is relative or false if it is not. 16140 */ 16141 public boolean isPaddingRelative() { 16142 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16143 } 16144 16145 Insets computeOpticalInsets() { 16146 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16147 } 16148 16149 /** 16150 * @hide 16151 */ 16152 public void resetPaddingToInitialValues() { 16153 if (isRtlCompatibilityMode()) { 16154 mPaddingLeft = mUserPaddingLeftInitial; 16155 mPaddingRight = mUserPaddingRightInitial; 16156 return; 16157 } 16158 if (isLayoutRtl()) { 16159 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16160 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16161 } else { 16162 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16163 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16164 } 16165 } 16166 16167 /** 16168 * @hide 16169 */ 16170 public Insets getOpticalInsets() { 16171 if (mLayoutInsets == null) { 16172 mLayoutInsets = computeOpticalInsets(); 16173 } 16174 return mLayoutInsets; 16175 } 16176 16177 /** 16178 * Changes the selection state of this view. A view can be selected or not. 16179 * Note that selection is not the same as focus. Views are typically 16180 * selected in the context of an AdapterView like ListView or GridView; 16181 * the selected view is the view that is highlighted. 16182 * 16183 * @param selected true if the view must be selected, false otherwise 16184 */ 16185 public void setSelected(boolean selected) { 16186 //noinspection DoubleNegation 16187 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16188 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16189 if (!selected) resetPressedState(); 16190 invalidate(true); 16191 refreshDrawableState(); 16192 dispatchSetSelected(selected); 16193 notifyViewAccessibilityStateChangedIfNeeded( 16194 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16195 } 16196 } 16197 16198 /** 16199 * Dispatch setSelected to all of this View's children. 16200 * 16201 * @see #setSelected(boolean) 16202 * 16203 * @param selected The new selected state 16204 */ 16205 protected void dispatchSetSelected(boolean selected) { 16206 } 16207 16208 /** 16209 * Indicates the selection state of this view. 16210 * 16211 * @return true if the view is selected, false otherwise 16212 */ 16213 @ViewDebug.ExportedProperty 16214 public boolean isSelected() { 16215 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16216 } 16217 16218 /** 16219 * Changes the activated state of this view. A view can be activated or not. 16220 * Note that activation is not the same as selection. Selection is 16221 * a transient property, representing the view (hierarchy) the user is 16222 * currently interacting with. Activation is a longer-term state that the 16223 * user can move views in and out of. For example, in a list view with 16224 * single or multiple selection enabled, the views in the current selection 16225 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16226 * here.) The activated state is propagated down to children of the view it 16227 * is set on. 16228 * 16229 * @param activated true if the view must be activated, false otherwise 16230 */ 16231 public void setActivated(boolean activated) { 16232 //noinspection DoubleNegation 16233 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16234 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16235 invalidate(true); 16236 refreshDrawableState(); 16237 dispatchSetActivated(activated); 16238 } 16239 } 16240 16241 /** 16242 * Dispatch setActivated to all of this View's children. 16243 * 16244 * @see #setActivated(boolean) 16245 * 16246 * @param activated The new activated state 16247 */ 16248 protected void dispatchSetActivated(boolean activated) { 16249 } 16250 16251 /** 16252 * Indicates the activation state of this view. 16253 * 16254 * @return true if the view is activated, false otherwise 16255 */ 16256 @ViewDebug.ExportedProperty 16257 public boolean isActivated() { 16258 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16259 } 16260 16261 /** 16262 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16263 * observer can be used to get notifications when global events, like 16264 * layout, happen. 16265 * 16266 * The returned ViewTreeObserver observer is not guaranteed to remain 16267 * valid for the lifetime of this View. If the caller of this method keeps 16268 * a long-lived reference to ViewTreeObserver, it should always check for 16269 * the return value of {@link ViewTreeObserver#isAlive()}. 16270 * 16271 * @return The ViewTreeObserver for this view's hierarchy. 16272 */ 16273 public ViewTreeObserver getViewTreeObserver() { 16274 if (mAttachInfo != null) { 16275 return mAttachInfo.mTreeObserver; 16276 } 16277 if (mFloatingTreeObserver == null) { 16278 mFloatingTreeObserver = new ViewTreeObserver(); 16279 } 16280 return mFloatingTreeObserver; 16281 } 16282 16283 /** 16284 * <p>Finds the topmost view in the current view hierarchy.</p> 16285 * 16286 * @return the topmost view containing this view 16287 */ 16288 public View getRootView() { 16289 if (mAttachInfo != null) { 16290 final View v = mAttachInfo.mRootView; 16291 if (v != null) { 16292 return v; 16293 } 16294 } 16295 16296 View parent = this; 16297 16298 while (parent.mParent != null && parent.mParent instanceof View) { 16299 parent = (View) parent.mParent; 16300 } 16301 16302 return parent; 16303 } 16304 16305 /** 16306 * Transforms a motion event from view-local coordinates to on-screen 16307 * coordinates. 16308 * 16309 * @param ev the view-local motion event 16310 * @return false if the transformation could not be applied 16311 * @hide 16312 */ 16313 public boolean toGlobalMotionEvent(MotionEvent ev) { 16314 final AttachInfo info = mAttachInfo; 16315 if (info == null) { 16316 return false; 16317 } 16318 16319 final Matrix m = info.mTmpMatrix; 16320 m.set(Matrix.IDENTITY_MATRIX); 16321 transformMatrixToGlobal(m); 16322 ev.transform(m); 16323 return true; 16324 } 16325 16326 /** 16327 * Transforms a motion event from on-screen coordinates to view-local 16328 * coordinates. 16329 * 16330 * @param ev the on-screen motion event 16331 * @return false if the transformation could not be applied 16332 * @hide 16333 */ 16334 public boolean toLocalMotionEvent(MotionEvent ev) { 16335 final AttachInfo info = mAttachInfo; 16336 if (info == null) { 16337 return false; 16338 } 16339 16340 final Matrix m = info.mTmpMatrix; 16341 m.set(Matrix.IDENTITY_MATRIX); 16342 transformMatrixToLocal(m); 16343 ev.transform(m); 16344 return true; 16345 } 16346 16347 /** 16348 * Modifies the input matrix such that it maps view-local coordinates to 16349 * on-screen coordinates. 16350 * 16351 * @param m input matrix to modify 16352 */ 16353 void transformMatrixToGlobal(Matrix m) { 16354 final ViewParent parent = mParent; 16355 if (parent instanceof View) { 16356 final View vp = (View) parent; 16357 vp.transformMatrixToGlobal(m); 16358 m.postTranslate(-vp.mScrollX, -vp.mScrollY); 16359 } else if (parent instanceof ViewRootImpl) { 16360 final ViewRootImpl vr = (ViewRootImpl) parent; 16361 vr.transformMatrixToGlobal(m); 16362 m.postTranslate(0, -vr.mCurScrollY); 16363 } 16364 16365 m.postTranslate(mLeft, mTop); 16366 16367 if (!hasIdentityMatrix()) { 16368 m.postConcat(getMatrix()); 16369 } 16370 } 16371 16372 /** 16373 * Modifies the input matrix such that it maps on-screen coordinates to 16374 * view-local coordinates. 16375 * 16376 * @param m input matrix to modify 16377 */ 16378 void transformMatrixToLocal(Matrix m) { 16379 final ViewParent parent = mParent; 16380 if (parent instanceof View) { 16381 final View vp = (View) parent; 16382 vp.transformMatrixToLocal(m); 16383 m.preTranslate(vp.mScrollX, vp.mScrollY); 16384 } else if (parent instanceof ViewRootImpl) { 16385 final ViewRootImpl vr = (ViewRootImpl) parent; 16386 vr.transformMatrixToLocal(m); 16387 m.preTranslate(0, vr.mCurScrollY); 16388 } 16389 16390 m.preTranslate(-mLeft, -mTop); 16391 16392 if (!hasIdentityMatrix()) { 16393 m.preConcat(getInverseMatrix()); 16394 } 16395 } 16396 16397 /** 16398 * <p>Computes the coordinates of this view on the screen. The argument 16399 * must be an array of two integers. After the method returns, the array 16400 * contains the x and y location in that order.</p> 16401 * 16402 * @param location an array of two integers in which to hold the coordinates 16403 */ 16404 public void getLocationOnScreen(int[] location) { 16405 getLocationInWindow(location); 16406 16407 final AttachInfo info = mAttachInfo; 16408 if (info != null) { 16409 location[0] += info.mWindowLeft; 16410 location[1] += info.mWindowTop; 16411 } 16412 } 16413 16414 /** 16415 * <p>Computes the coordinates of this view in its window. The argument 16416 * must be an array of two integers. After the method returns, the array 16417 * contains the x and y location in that order.</p> 16418 * 16419 * @param location an array of two integers in which to hold the coordinates 16420 */ 16421 public void getLocationInWindow(int[] location) { 16422 if (location == null || location.length < 2) { 16423 throw new IllegalArgumentException("location must be an array of two integers"); 16424 } 16425 16426 if (mAttachInfo == null) { 16427 // When the view is not attached to a window, this method does not make sense 16428 location[0] = location[1] = 0; 16429 return; 16430 } 16431 16432 float[] position = mAttachInfo.mTmpTransformLocation; 16433 position[0] = position[1] = 0.0f; 16434 16435 if (!hasIdentityMatrix()) { 16436 getMatrix().mapPoints(position); 16437 } 16438 16439 position[0] += mLeft; 16440 position[1] += mTop; 16441 16442 ViewParent viewParent = mParent; 16443 while (viewParent instanceof View) { 16444 final View view = (View) viewParent; 16445 16446 position[0] -= view.mScrollX; 16447 position[1] -= view.mScrollY; 16448 16449 if (!view.hasIdentityMatrix()) { 16450 view.getMatrix().mapPoints(position); 16451 } 16452 16453 position[0] += view.mLeft; 16454 position[1] += view.mTop; 16455 16456 viewParent = view.mParent; 16457 } 16458 16459 if (viewParent instanceof ViewRootImpl) { 16460 // *cough* 16461 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16462 position[1] -= vr.mCurScrollY; 16463 } 16464 16465 location[0] = (int) (position[0] + 0.5f); 16466 location[1] = (int) (position[1] + 0.5f); 16467 } 16468 16469 /** 16470 * {@hide} 16471 * @param id the id of the view to be found 16472 * @return the view of the specified id, null if cannot be found 16473 */ 16474 protected View findViewTraversal(int id) { 16475 if (id == mID) { 16476 return this; 16477 } 16478 return null; 16479 } 16480 16481 /** 16482 * {@hide} 16483 * @param tag the tag of the view to be found 16484 * @return the view of specified tag, null if cannot be found 16485 */ 16486 protected View findViewWithTagTraversal(Object tag) { 16487 if (tag != null && tag.equals(mTag)) { 16488 return this; 16489 } 16490 return null; 16491 } 16492 16493 /** 16494 * {@hide} 16495 * @param predicate The predicate to evaluate. 16496 * @param childToSkip If not null, ignores this child during the recursive traversal. 16497 * @return The first view that matches the predicate or null. 16498 */ 16499 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16500 if (predicate.apply(this)) { 16501 return this; 16502 } 16503 return null; 16504 } 16505 16506 /** 16507 * Look for a child view with the given id. If this view has the given 16508 * id, return this view. 16509 * 16510 * @param id The id to search for. 16511 * @return The view that has the given id in the hierarchy or null 16512 */ 16513 public final View findViewById(int id) { 16514 if (id < 0) { 16515 return null; 16516 } 16517 return findViewTraversal(id); 16518 } 16519 16520 /** 16521 * Finds a view by its unuque and stable accessibility id. 16522 * 16523 * @param accessibilityId The searched accessibility id. 16524 * @return The found view. 16525 */ 16526 final View findViewByAccessibilityId(int accessibilityId) { 16527 if (accessibilityId < 0) { 16528 return null; 16529 } 16530 return findViewByAccessibilityIdTraversal(accessibilityId); 16531 } 16532 16533 /** 16534 * Performs the traversal to find a view by its unuque and stable accessibility id. 16535 * 16536 * <strong>Note:</strong>This method does not stop at the root namespace 16537 * boundary since the user can touch the screen at an arbitrary location 16538 * potentially crossing the root namespace bounday which will send an 16539 * accessibility event to accessibility services and they should be able 16540 * to obtain the event source. Also accessibility ids are guaranteed to be 16541 * unique in the window. 16542 * 16543 * @param accessibilityId The accessibility id. 16544 * @return The found view. 16545 * 16546 * @hide 16547 */ 16548 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16549 if (getAccessibilityViewId() == accessibilityId) { 16550 return this; 16551 } 16552 return null; 16553 } 16554 16555 /** 16556 * Look for a child view with the given tag. If this view has the given 16557 * tag, return this view. 16558 * 16559 * @param tag The tag to search for, using "tag.equals(getTag())". 16560 * @return The View that has the given tag in the hierarchy or null 16561 */ 16562 public final View findViewWithTag(Object tag) { 16563 if (tag == null) { 16564 return null; 16565 } 16566 return findViewWithTagTraversal(tag); 16567 } 16568 16569 /** 16570 * {@hide} 16571 * Look for a child view that matches the specified predicate. 16572 * If this view matches the predicate, return this view. 16573 * 16574 * @param predicate The predicate to evaluate. 16575 * @return The first view that matches the predicate or null. 16576 */ 16577 public final View findViewByPredicate(Predicate<View> predicate) { 16578 return findViewByPredicateTraversal(predicate, null); 16579 } 16580 16581 /** 16582 * {@hide} 16583 * Look for a child view that matches the specified predicate, 16584 * starting with the specified view and its descendents and then 16585 * recusively searching the ancestors and siblings of that view 16586 * until this view is reached. 16587 * 16588 * This method is useful in cases where the predicate does not match 16589 * a single unique view (perhaps multiple views use the same id) 16590 * and we are trying to find the view that is "closest" in scope to the 16591 * starting view. 16592 * 16593 * @param start The view to start from. 16594 * @param predicate The predicate to evaluate. 16595 * @return The first view that matches the predicate or null. 16596 */ 16597 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16598 View childToSkip = null; 16599 for (;;) { 16600 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16601 if (view != null || start == this) { 16602 return view; 16603 } 16604 16605 ViewParent parent = start.getParent(); 16606 if (parent == null || !(parent instanceof View)) { 16607 return null; 16608 } 16609 16610 childToSkip = start; 16611 start = (View) parent; 16612 } 16613 } 16614 16615 /** 16616 * Sets the identifier for this view. The identifier does not have to be 16617 * unique in this view's hierarchy. The identifier should be a positive 16618 * number. 16619 * 16620 * @see #NO_ID 16621 * @see #getId() 16622 * @see #findViewById(int) 16623 * 16624 * @param id a number used to identify the view 16625 * 16626 * @attr ref android.R.styleable#View_id 16627 */ 16628 public void setId(int id) { 16629 mID = id; 16630 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 16631 mID = generateViewId(); 16632 } 16633 } 16634 16635 /** 16636 * {@hide} 16637 * 16638 * @param isRoot true if the view belongs to the root namespace, false 16639 * otherwise 16640 */ 16641 public void setIsRootNamespace(boolean isRoot) { 16642 if (isRoot) { 16643 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 16644 } else { 16645 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 16646 } 16647 } 16648 16649 /** 16650 * {@hide} 16651 * 16652 * @return true if the view belongs to the root namespace, false otherwise 16653 */ 16654 public boolean isRootNamespace() { 16655 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 16656 } 16657 16658 /** 16659 * Returns this view's identifier. 16660 * 16661 * @return a positive integer used to identify the view or {@link #NO_ID} 16662 * if the view has no ID 16663 * 16664 * @see #setId(int) 16665 * @see #findViewById(int) 16666 * @attr ref android.R.styleable#View_id 16667 */ 16668 @ViewDebug.CapturedViewProperty 16669 public int getId() { 16670 return mID; 16671 } 16672 16673 /** 16674 * Returns this view's tag. 16675 * 16676 * @return the Object stored in this view as a tag, or {@code null} if not 16677 * set 16678 * 16679 * @see #setTag(Object) 16680 * @see #getTag(int) 16681 */ 16682 @ViewDebug.ExportedProperty 16683 public Object getTag() { 16684 return mTag; 16685 } 16686 16687 /** 16688 * Sets the tag associated with this view. A tag can be used to mark 16689 * a view in its hierarchy and does not have to be unique within the 16690 * hierarchy. Tags can also be used to store data within a view without 16691 * resorting to another data structure. 16692 * 16693 * @param tag an Object to tag the view with 16694 * 16695 * @see #getTag() 16696 * @see #setTag(int, Object) 16697 */ 16698 public void setTag(final Object tag) { 16699 mTag = tag; 16700 } 16701 16702 /** 16703 * Returns the tag associated with this view and the specified key. 16704 * 16705 * @param key The key identifying the tag 16706 * 16707 * @return the Object stored in this view as a tag, or {@code null} if not 16708 * set 16709 * 16710 * @see #setTag(int, Object) 16711 * @see #getTag() 16712 */ 16713 public Object getTag(int key) { 16714 if (mKeyedTags != null) return mKeyedTags.get(key); 16715 return null; 16716 } 16717 16718 /** 16719 * Sets a tag associated with this view and a key. A tag can be used 16720 * to mark a view in its hierarchy and does not have to be unique within 16721 * the hierarchy. Tags can also be used to store data within a view 16722 * without resorting to another data structure. 16723 * 16724 * The specified key should be an id declared in the resources of the 16725 * application to ensure it is unique (see the <a 16726 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 16727 * Keys identified as belonging to 16728 * the Android framework or not associated with any package will cause 16729 * an {@link IllegalArgumentException} to be thrown. 16730 * 16731 * @param key The key identifying the tag 16732 * @param tag An Object to tag the view with 16733 * 16734 * @throws IllegalArgumentException If they specified key is not valid 16735 * 16736 * @see #setTag(Object) 16737 * @see #getTag(int) 16738 */ 16739 public void setTag(int key, final Object tag) { 16740 // If the package id is 0x00 or 0x01, it's either an undefined package 16741 // or a framework id 16742 if ((key >>> 24) < 2) { 16743 throw new IllegalArgumentException("The key must be an application-specific " 16744 + "resource id."); 16745 } 16746 16747 setKeyedTag(key, tag); 16748 } 16749 16750 /** 16751 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16752 * framework id. 16753 * 16754 * @hide 16755 */ 16756 public void setTagInternal(int key, Object tag) { 16757 if ((key >>> 24) != 0x1) { 16758 throw new IllegalArgumentException("The key must be a framework-specific " 16759 + "resource id."); 16760 } 16761 16762 setKeyedTag(key, tag); 16763 } 16764 16765 private void setKeyedTag(int key, Object tag) { 16766 if (mKeyedTags == null) { 16767 mKeyedTags = new SparseArray<Object>(2); 16768 } 16769 16770 mKeyedTags.put(key, tag); 16771 } 16772 16773 /** 16774 * Prints information about this view in the log output, with the tag 16775 * {@link #VIEW_LOG_TAG}. 16776 * 16777 * @hide 16778 */ 16779 public void debug() { 16780 debug(0); 16781 } 16782 16783 /** 16784 * Prints information about this view in the log output, with the tag 16785 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16786 * indentation defined by the <code>depth</code>. 16787 * 16788 * @param depth the indentation level 16789 * 16790 * @hide 16791 */ 16792 protected void debug(int depth) { 16793 String output = debugIndent(depth - 1); 16794 16795 output += "+ " + this; 16796 int id = getId(); 16797 if (id != -1) { 16798 output += " (id=" + id + ")"; 16799 } 16800 Object tag = getTag(); 16801 if (tag != null) { 16802 output += " (tag=" + tag + ")"; 16803 } 16804 Log.d(VIEW_LOG_TAG, output); 16805 16806 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16807 output = debugIndent(depth) + " FOCUSED"; 16808 Log.d(VIEW_LOG_TAG, output); 16809 } 16810 16811 output = debugIndent(depth); 16812 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16813 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16814 + "} "; 16815 Log.d(VIEW_LOG_TAG, output); 16816 16817 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16818 || mPaddingBottom != 0) { 16819 output = debugIndent(depth); 16820 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16821 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16822 Log.d(VIEW_LOG_TAG, output); 16823 } 16824 16825 output = debugIndent(depth); 16826 output += "mMeasureWidth=" + mMeasuredWidth + 16827 " mMeasureHeight=" + mMeasuredHeight; 16828 Log.d(VIEW_LOG_TAG, output); 16829 16830 output = debugIndent(depth); 16831 if (mLayoutParams == null) { 16832 output += "BAD! no layout params"; 16833 } else { 16834 output = mLayoutParams.debug(output); 16835 } 16836 Log.d(VIEW_LOG_TAG, output); 16837 16838 output = debugIndent(depth); 16839 output += "flags={"; 16840 output += View.printFlags(mViewFlags); 16841 output += "}"; 16842 Log.d(VIEW_LOG_TAG, output); 16843 16844 output = debugIndent(depth); 16845 output += "privateFlags={"; 16846 output += View.printPrivateFlags(mPrivateFlags); 16847 output += "}"; 16848 Log.d(VIEW_LOG_TAG, output); 16849 } 16850 16851 /** 16852 * Creates a string of whitespaces used for indentation. 16853 * 16854 * @param depth the indentation level 16855 * @return a String containing (depth * 2 + 3) * 2 white spaces 16856 * 16857 * @hide 16858 */ 16859 protected static String debugIndent(int depth) { 16860 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16861 for (int i = 0; i < (depth * 2) + 3; i++) { 16862 spaces.append(' ').append(' '); 16863 } 16864 return spaces.toString(); 16865 } 16866 16867 /** 16868 * <p>Return the offset of the widget's text baseline from the widget's top 16869 * boundary. If this widget does not support baseline alignment, this 16870 * method returns -1. </p> 16871 * 16872 * @return the offset of the baseline within the widget's bounds or -1 16873 * if baseline alignment is not supported 16874 */ 16875 @ViewDebug.ExportedProperty(category = "layout") 16876 public int getBaseline() { 16877 return -1; 16878 } 16879 16880 /** 16881 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16882 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16883 * a layout pass. 16884 * 16885 * @return whether the view hierarchy is currently undergoing a layout pass 16886 */ 16887 public boolean isInLayout() { 16888 ViewRootImpl viewRoot = getViewRootImpl(); 16889 return (viewRoot != null && viewRoot.isInLayout()); 16890 } 16891 16892 /** 16893 * Call this when something has changed which has invalidated the 16894 * layout of this view. This will schedule a layout pass of the view 16895 * tree. This should not be called while the view hierarchy is currently in a layout 16896 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16897 * end of the current layout pass (and then layout will run again) or after the current 16898 * frame is drawn and the next layout occurs. 16899 * 16900 * <p>Subclasses which override this method should call the superclass method to 16901 * handle possible request-during-layout errors correctly.</p> 16902 */ 16903 public void requestLayout() { 16904 if (mMeasureCache != null) mMeasureCache.clear(); 16905 16906 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16907 // Only trigger request-during-layout logic if this is the view requesting it, 16908 // not the views in its parent hierarchy 16909 ViewRootImpl viewRoot = getViewRootImpl(); 16910 if (viewRoot != null && viewRoot.isInLayout()) { 16911 if (!viewRoot.requestLayoutDuringLayout(this)) { 16912 return; 16913 } 16914 } 16915 mAttachInfo.mViewRequestingLayout = this; 16916 } 16917 16918 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16919 mPrivateFlags |= PFLAG_INVALIDATED; 16920 16921 if (mParent != null && !mParent.isLayoutRequested()) { 16922 mParent.requestLayout(); 16923 } 16924 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 16925 mAttachInfo.mViewRequestingLayout = null; 16926 } 16927 } 16928 16929 /** 16930 * Forces this view to be laid out during the next layout pass. 16931 * This method does not call requestLayout() or forceLayout() 16932 * on the parent. 16933 */ 16934 public void forceLayout() { 16935 if (mMeasureCache != null) mMeasureCache.clear(); 16936 16937 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16938 mPrivateFlags |= PFLAG_INVALIDATED; 16939 } 16940 16941 /** 16942 * <p> 16943 * This is called to find out how big a view should be. The parent 16944 * supplies constraint information in the width and height parameters. 16945 * </p> 16946 * 16947 * <p> 16948 * The actual measurement work of a view is performed in 16949 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 16950 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 16951 * </p> 16952 * 16953 * 16954 * @param widthMeasureSpec Horizontal space requirements as imposed by the 16955 * parent 16956 * @param heightMeasureSpec Vertical space requirements as imposed by the 16957 * parent 16958 * 16959 * @see #onMeasure(int, int) 16960 */ 16961 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 16962 boolean optical = isLayoutModeOptical(this); 16963 if (optical != isLayoutModeOptical(mParent)) { 16964 Insets insets = getOpticalInsets(); 16965 int oWidth = insets.left + insets.right; 16966 int oHeight = insets.top + insets.bottom; 16967 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 16968 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 16969 } 16970 16971 // Suppress sign extension for the low bytes 16972 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 16973 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 16974 16975 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 16976 widthMeasureSpec != mOldWidthMeasureSpec || 16977 heightMeasureSpec != mOldHeightMeasureSpec) { 16978 16979 // first clears the measured dimension flag 16980 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 16981 16982 resolveRtlPropertiesIfNeeded(); 16983 16984 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 16985 mMeasureCache.indexOfKey(key); 16986 if (cacheIndex < 0 || sIgnoreMeasureCache) { 16987 // measure ourselves, this should set the measured dimension flag back 16988 onMeasure(widthMeasureSpec, heightMeasureSpec); 16989 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16990 } else { 16991 long value = mMeasureCache.valueAt(cacheIndex); 16992 // Casting a long to int drops the high 32 bits, no mask needed 16993 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 16994 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16995 } 16996 16997 // flag not set, setMeasuredDimension() was not invoked, we raise 16998 // an exception to warn the developer 16999 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 17000 throw new IllegalStateException("onMeasure() did not set the" 17001 + " measured dimension by calling" 17002 + " setMeasuredDimension()"); 17003 } 17004 17005 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17006 } 17007 17008 mOldWidthMeasureSpec = widthMeasureSpec; 17009 mOldHeightMeasureSpec = heightMeasureSpec; 17010 17011 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17012 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17013 } 17014 17015 /** 17016 * <p> 17017 * Measure the view and its content to determine the measured width and the 17018 * measured height. This method is invoked by {@link #measure(int, int)} and 17019 * should be overriden by subclasses to provide accurate and efficient 17020 * measurement of their contents. 17021 * </p> 17022 * 17023 * <p> 17024 * <strong>CONTRACT:</strong> When overriding this method, you 17025 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17026 * measured width and height of this view. Failure to do so will trigger an 17027 * <code>IllegalStateException</code>, thrown by 17028 * {@link #measure(int, int)}. Calling the superclass' 17029 * {@link #onMeasure(int, int)} is a valid use. 17030 * </p> 17031 * 17032 * <p> 17033 * The base class implementation of measure defaults to the background size, 17034 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17035 * override {@link #onMeasure(int, int)} to provide better measurements of 17036 * their content. 17037 * </p> 17038 * 17039 * <p> 17040 * If this method is overridden, it is the subclass's responsibility to make 17041 * sure the measured height and width are at least the view's minimum height 17042 * and width ({@link #getSuggestedMinimumHeight()} and 17043 * {@link #getSuggestedMinimumWidth()}). 17044 * </p> 17045 * 17046 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17047 * The requirements are encoded with 17048 * {@link android.view.View.MeasureSpec}. 17049 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17050 * The requirements are encoded with 17051 * {@link android.view.View.MeasureSpec}. 17052 * 17053 * @see #getMeasuredWidth() 17054 * @see #getMeasuredHeight() 17055 * @see #setMeasuredDimension(int, int) 17056 * @see #getSuggestedMinimumHeight() 17057 * @see #getSuggestedMinimumWidth() 17058 * @see android.view.View.MeasureSpec#getMode(int) 17059 * @see android.view.View.MeasureSpec#getSize(int) 17060 */ 17061 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17062 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17063 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17064 } 17065 17066 /** 17067 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17068 * measured width and measured height. Failing to do so will trigger an 17069 * exception at measurement time.</p> 17070 * 17071 * @param measuredWidth The measured width of this view. May be a complex 17072 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17073 * {@link #MEASURED_STATE_TOO_SMALL}. 17074 * @param measuredHeight The measured height of this view. May be a complex 17075 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17076 * {@link #MEASURED_STATE_TOO_SMALL}. 17077 */ 17078 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17079 boolean optical = isLayoutModeOptical(this); 17080 if (optical != isLayoutModeOptical(mParent)) { 17081 Insets insets = getOpticalInsets(); 17082 int opticalWidth = insets.left + insets.right; 17083 int opticalHeight = insets.top + insets.bottom; 17084 17085 measuredWidth += optical ? opticalWidth : -opticalWidth; 17086 measuredHeight += optical ? opticalHeight : -opticalHeight; 17087 } 17088 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17089 } 17090 17091 /** 17092 * Sets the measured dimension without extra processing for things like optical bounds. 17093 * Useful for reapplying consistent values that have already been cooked with adjustments 17094 * for optical bounds, etc. such as those from the measurement cache. 17095 * 17096 * @param measuredWidth The measured width of this view. May be a complex 17097 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17098 * {@link #MEASURED_STATE_TOO_SMALL}. 17099 * @param measuredHeight The measured height of this view. May be a complex 17100 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17101 * {@link #MEASURED_STATE_TOO_SMALL}. 17102 */ 17103 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17104 mMeasuredWidth = measuredWidth; 17105 mMeasuredHeight = measuredHeight; 17106 17107 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17108 } 17109 17110 /** 17111 * Merge two states as returned by {@link #getMeasuredState()}. 17112 * @param curState The current state as returned from a view or the result 17113 * of combining multiple views. 17114 * @param newState The new view state to combine. 17115 * @return Returns a new integer reflecting the combination of the two 17116 * states. 17117 */ 17118 public static int combineMeasuredStates(int curState, int newState) { 17119 return curState | newState; 17120 } 17121 17122 /** 17123 * Version of {@link #resolveSizeAndState(int, int, int)} 17124 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17125 */ 17126 public static int resolveSize(int size, int measureSpec) { 17127 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17128 } 17129 17130 /** 17131 * Utility to reconcile a desired size and state, with constraints imposed 17132 * by a MeasureSpec. Will take the desired size, unless a different size 17133 * is imposed by the constraints. The returned value is a compound integer, 17134 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17135 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17136 * size is smaller than the size the view wants to be. 17137 * 17138 * @param size How big the view wants to be 17139 * @param measureSpec Constraints imposed by the parent 17140 * @return Size information bit mask as defined by 17141 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17142 */ 17143 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17144 int result = size; 17145 int specMode = MeasureSpec.getMode(measureSpec); 17146 int specSize = MeasureSpec.getSize(measureSpec); 17147 switch (specMode) { 17148 case MeasureSpec.UNSPECIFIED: 17149 result = size; 17150 break; 17151 case MeasureSpec.AT_MOST: 17152 if (specSize < size) { 17153 result = specSize | MEASURED_STATE_TOO_SMALL; 17154 } else { 17155 result = size; 17156 } 17157 break; 17158 case MeasureSpec.EXACTLY: 17159 result = specSize; 17160 break; 17161 } 17162 return result | (childMeasuredState&MEASURED_STATE_MASK); 17163 } 17164 17165 /** 17166 * Utility to return a default size. Uses the supplied size if the 17167 * MeasureSpec imposed no constraints. Will get larger if allowed 17168 * by the MeasureSpec. 17169 * 17170 * @param size Default size for this view 17171 * @param measureSpec Constraints imposed by the parent 17172 * @return The size this view should be. 17173 */ 17174 public static int getDefaultSize(int size, int measureSpec) { 17175 int result = size; 17176 int specMode = MeasureSpec.getMode(measureSpec); 17177 int specSize = MeasureSpec.getSize(measureSpec); 17178 17179 switch (specMode) { 17180 case MeasureSpec.UNSPECIFIED: 17181 result = size; 17182 break; 17183 case MeasureSpec.AT_MOST: 17184 case MeasureSpec.EXACTLY: 17185 result = specSize; 17186 break; 17187 } 17188 return result; 17189 } 17190 17191 /** 17192 * Returns the suggested minimum height that the view should use. This 17193 * returns the maximum of the view's minimum height 17194 * and the background's minimum height 17195 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17196 * <p> 17197 * When being used in {@link #onMeasure(int, int)}, the caller should still 17198 * ensure the returned height is within the requirements of the parent. 17199 * 17200 * @return The suggested minimum height of the view. 17201 */ 17202 protected int getSuggestedMinimumHeight() { 17203 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17204 17205 } 17206 17207 /** 17208 * Returns the suggested minimum width that the view should use. This 17209 * returns the maximum of the view's minimum width) 17210 * and the background's minimum width 17211 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17212 * <p> 17213 * When being used in {@link #onMeasure(int, int)}, the caller should still 17214 * ensure the returned width is within the requirements of the parent. 17215 * 17216 * @return The suggested minimum width of the view. 17217 */ 17218 protected int getSuggestedMinimumWidth() { 17219 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17220 } 17221 17222 /** 17223 * Returns the minimum height of the view. 17224 * 17225 * @return the minimum height the view will try to be. 17226 * 17227 * @see #setMinimumHeight(int) 17228 * 17229 * @attr ref android.R.styleable#View_minHeight 17230 */ 17231 public int getMinimumHeight() { 17232 return mMinHeight; 17233 } 17234 17235 /** 17236 * Sets the minimum height of the view. It is not guaranteed the view will 17237 * be able to achieve this minimum height (for example, if its parent layout 17238 * constrains it with less available height). 17239 * 17240 * @param minHeight The minimum height the view will try to be. 17241 * 17242 * @see #getMinimumHeight() 17243 * 17244 * @attr ref android.R.styleable#View_minHeight 17245 */ 17246 public void setMinimumHeight(int minHeight) { 17247 mMinHeight = minHeight; 17248 requestLayout(); 17249 } 17250 17251 /** 17252 * Returns the minimum width of the view. 17253 * 17254 * @return the minimum width the view will try to be. 17255 * 17256 * @see #setMinimumWidth(int) 17257 * 17258 * @attr ref android.R.styleable#View_minWidth 17259 */ 17260 public int getMinimumWidth() { 17261 return mMinWidth; 17262 } 17263 17264 /** 17265 * Sets the minimum width of the view. It is not guaranteed the view will 17266 * be able to achieve this minimum width (for example, if its parent layout 17267 * constrains it with less available width). 17268 * 17269 * @param minWidth The minimum width the view will try to be. 17270 * 17271 * @see #getMinimumWidth() 17272 * 17273 * @attr ref android.R.styleable#View_minWidth 17274 */ 17275 public void setMinimumWidth(int minWidth) { 17276 mMinWidth = minWidth; 17277 requestLayout(); 17278 17279 } 17280 17281 /** 17282 * Get the animation currently associated with this view. 17283 * 17284 * @return The animation that is currently playing or 17285 * scheduled to play for this view. 17286 */ 17287 public Animation getAnimation() { 17288 return mCurrentAnimation; 17289 } 17290 17291 /** 17292 * Start the specified animation now. 17293 * 17294 * @param animation the animation to start now 17295 */ 17296 public void startAnimation(Animation animation) { 17297 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17298 setAnimation(animation); 17299 invalidateParentCaches(); 17300 invalidate(true); 17301 } 17302 17303 /** 17304 * Cancels any animations for this view. 17305 */ 17306 public void clearAnimation() { 17307 if (mCurrentAnimation != null) { 17308 mCurrentAnimation.detach(); 17309 } 17310 mCurrentAnimation = null; 17311 invalidateParentIfNeeded(); 17312 } 17313 17314 /** 17315 * Sets the next animation to play for this view. 17316 * If you want the animation to play immediately, use 17317 * {@link #startAnimation(android.view.animation.Animation)} instead. 17318 * This method provides allows fine-grained 17319 * control over the start time and invalidation, but you 17320 * must make sure that 1) the animation has a start time set, and 17321 * 2) the view's parent (which controls animations on its children) 17322 * will be invalidated when the animation is supposed to 17323 * start. 17324 * 17325 * @param animation The next animation, or null. 17326 */ 17327 public void setAnimation(Animation animation) { 17328 mCurrentAnimation = animation; 17329 17330 if (animation != null) { 17331 // If the screen is off assume the animation start time is now instead of 17332 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17333 // would cause the animation to start when the screen turns back on 17334 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 17335 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17336 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17337 } 17338 animation.reset(); 17339 } 17340 } 17341 17342 /** 17343 * Invoked by a parent ViewGroup to notify the start of the animation 17344 * currently associated with this view. If you override this method, 17345 * always call super.onAnimationStart(); 17346 * 17347 * @see #setAnimation(android.view.animation.Animation) 17348 * @see #getAnimation() 17349 */ 17350 protected void onAnimationStart() { 17351 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17352 } 17353 17354 /** 17355 * Invoked by a parent ViewGroup to notify the end of the animation 17356 * currently associated with this view. If you override this method, 17357 * always call super.onAnimationEnd(); 17358 * 17359 * @see #setAnimation(android.view.animation.Animation) 17360 * @see #getAnimation() 17361 */ 17362 protected void onAnimationEnd() { 17363 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17364 } 17365 17366 /** 17367 * Invoked if there is a Transform that involves alpha. Subclass that can 17368 * draw themselves with the specified alpha should return true, and then 17369 * respect that alpha when their onDraw() is called. If this returns false 17370 * then the view may be redirected to draw into an offscreen buffer to 17371 * fulfill the request, which will look fine, but may be slower than if the 17372 * subclass handles it internally. The default implementation returns false. 17373 * 17374 * @param alpha The alpha (0..255) to apply to the view's drawing 17375 * @return true if the view can draw with the specified alpha. 17376 */ 17377 protected boolean onSetAlpha(int alpha) { 17378 return false; 17379 } 17380 17381 /** 17382 * This is used by the RootView to perform an optimization when 17383 * the view hierarchy contains one or several SurfaceView. 17384 * SurfaceView is always considered transparent, but its children are not, 17385 * therefore all View objects remove themselves from the global transparent 17386 * region (passed as a parameter to this function). 17387 * 17388 * @param region The transparent region for this ViewAncestor (window). 17389 * 17390 * @return Returns true if the effective visibility of the view at this 17391 * point is opaque, regardless of the transparent region; returns false 17392 * if it is possible for underlying windows to be seen behind the view. 17393 * 17394 * {@hide} 17395 */ 17396 public boolean gatherTransparentRegion(Region region) { 17397 final AttachInfo attachInfo = mAttachInfo; 17398 if (region != null && attachInfo != null) { 17399 final int pflags = mPrivateFlags; 17400 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 17401 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 17402 // remove it from the transparent region. 17403 final int[] location = attachInfo.mTransparentLocation; 17404 getLocationInWindow(location); 17405 region.op(location[0], location[1], location[0] + mRight - mLeft, 17406 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 17407 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 17408 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 17409 // exists, so we remove the background drawable's non-transparent 17410 // parts from this transparent region. 17411 applyDrawableToTransparentRegion(mBackground, region); 17412 } 17413 } 17414 return true; 17415 } 17416 17417 /** 17418 * Play a sound effect for this view. 17419 * 17420 * <p>The framework will play sound effects for some built in actions, such as 17421 * clicking, but you may wish to play these effects in your widget, 17422 * for instance, for internal navigation. 17423 * 17424 * <p>The sound effect will only be played if sound effects are enabled by the user, and 17425 * {@link #isSoundEffectsEnabled()} is true. 17426 * 17427 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 17428 */ 17429 public void playSoundEffect(int soundConstant) { 17430 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 17431 return; 17432 } 17433 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 17434 } 17435 17436 /** 17437 * BZZZTT!!1! 17438 * 17439 * <p>Provide haptic feedback to the user for this view. 17440 * 17441 * <p>The framework will provide haptic feedback for some built in actions, 17442 * such as long presses, but you may wish to provide feedback for your 17443 * own widget. 17444 * 17445 * <p>The feedback will only be performed if 17446 * {@link #isHapticFeedbackEnabled()} is true. 17447 * 17448 * @param feedbackConstant One of the constants defined in 17449 * {@link HapticFeedbackConstants} 17450 */ 17451 public boolean performHapticFeedback(int feedbackConstant) { 17452 return performHapticFeedback(feedbackConstant, 0); 17453 } 17454 17455 /** 17456 * BZZZTT!!1! 17457 * 17458 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17459 * 17460 * @param feedbackConstant One of the constants defined in 17461 * {@link HapticFeedbackConstants} 17462 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17463 */ 17464 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17465 if (mAttachInfo == null) { 17466 return false; 17467 } 17468 //noinspection SimplifiableIfStatement 17469 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17470 && !isHapticFeedbackEnabled()) { 17471 return false; 17472 } 17473 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17474 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17475 } 17476 17477 /** 17478 * Request that the visibility of the status bar or other screen/window 17479 * decorations be changed. 17480 * 17481 * <p>This method is used to put the over device UI into temporary modes 17482 * where the user's attention is focused more on the application content, 17483 * by dimming or hiding surrounding system affordances. This is typically 17484 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17485 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17486 * to be placed behind the action bar (and with these flags other system 17487 * affordances) so that smooth transitions between hiding and showing them 17488 * can be done. 17489 * 17490 * <p>Two representative examples of the use of system UI visibility is 17491 * implementing a content browsing application (like a magazine reader) 17492 * and a video playing application. 17493 * 17494 * <p>The first code shows a typical implementation of a View in a content 17495 * browsing application. In this implementation, the application goes 17496 * into a content-oriented mode by hiding the status bar and action bar, 17497 * and putting the navigation elements into lights out mode. The user can 17498 * then interact with content while in this mode. Such an application should 17499 * provide an easy way for the user to toggle out of the mode (such as to 17500 * check information in the status bar or access notifications). In the 17501 * implementation here, this is done simply by tapping on the content. 17502 * 17503 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17504 * content} 17505 * 17506 * <p>This second code sample shows a typical implementation of a View 17507 * in a video playing application. In this situation, while the video is 17508 * playing the application would like to go into a complete full-screen mode, 17509 * to use as much of the display as possible for the video. When in this state 17510 * the user can not interact with the application; the system intercepts 17511 * touching on the screen to pop the UI out of full screen mode. See 17512 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17513 * 17514 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17515 * content} 17516 * 17517 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17518 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17519 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17520 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17521 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17522 */ 17523 public void setSystemUiVisibility(int visibility) { 17524 if (visibility != mSystemUiVisibility) { 17525 mSystemUiVisibility = visibility; 17526 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17527 mParent.recomputeViewAttributes(this); 17528 } 17529 } 17530 } 17531 17532 /** 17533 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17534 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17535 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17536 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17537 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17538 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17539 */ 17540 public int getSystemUiVisibility() { 17541 return mSystemUiVisibility; 17542 } 17543 17544 /** 17545 * Returns the current system UI visibility that is currently set for 17546 * the entire window. This is the combination of the 17547 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17548 * views in the window. 17549 */ 17550 public int getWindowSystemUiVisibility() { 17551 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17552 } 17553 17554 /** 17555 * Override to find out when the window's requested system UI visibility 17556 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17557 * This is different from the callbacks received through 17558 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17559 * in that this is only telling you about the local request of the window, 17560 * not the actual values applied by the system. 17561 */ 17562 public void onWindowSystemUiVisibilityChanged(int visible) { 17563 } 17564 17565 /** 17566 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17567 * the view hierarchy. 17568 */ 17569 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17570 onWindowSystemUiVisibilityChanged(visible); 17571 } 17572 17573 /** 17574 * Set a listener to receive callbacks when the visibility of the system bar changes. 17575 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17576 */ 17577 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17578 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17579 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17580 mParent.recomputeViewAttributes(this); 17581 } 17582 } 17583 17584 /** 17585 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17586 * the view hierarchy. 17587 */ 17588 public void dispatchSystemUiVisibilityChanged(int visibility) { 17589 ListenerInfo li = mListenerInfo; 17590 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17591 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17592 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17593 } 17594 } 17595 17596 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17597 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17598 if (val != mSystemUiVisibility) { 17599 setSystemUiVisibility(val); 17600 return true; 17601 } 17602 return false; 17603 } 17604 17605 /** @hide */ 17606 public void setDisabledSystemUiVisibility(int flags) { 17607 if (mAttachInfo != null) { 17608 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17609 mAttachInfo.mDisabledSystemUiVisibility = flags; 17610 if (mParent != null) { 17611 mParent.recomputeViewAttributes(this); 17612 } 17613 } 17614 } 17615 } 17616 17617 /** 17618 * Creates an image that the system displays during the drag and drop 17619 * operation. This is called a "drag shadow". The default implementation 17620 * for a DragShadowBuilder based on a View returns an image that has exactly the same 17621 * appearance as the given View. The default also positions the center of the drag shadow 17622 * directly under the touch point. If no View is provided (the constructor with no parameters 17623 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 17624 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 17625 * default is an invisible drag shadow. 17626 * <p> 17627 * You are not required to use the View you provide to the constructor as the basis of the 17628 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 17629 * anything you want as the drag shadow. 17630 * </p> 17631 * <p> 17632 * You pass a DragShadowBuilder object to the system when you start the drag. The system 17633 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 17634 * size and position of the drag shadow. It uses this data to construct a 17635 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 17636 * so that your application can draw the shadow image in the Canvas. 17637 * </p> 17638 * 17639 * <div class="special reference"> 17640 * <h3>Developer Guides</h3> 17641 * <p>For a guide to implementing drag and drop features, read the 17642 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17643 * </div> 17644 */ 17645 public static class DragShadowBuilder { 17646 private final WeakReference<View> mView; 17647 17648 /** 17649 * Constructs a shadow image builder based on a View. By default, the resulting drag 17650 * shadow will have the same appearance and dimensions as the View, with the touch point 17651 * over the center of the View. 17652 * @param view A View. Any View in scope can be used. 17653 */ 17654 public DragShadowBuilder(View view) { 17655 mView = new WeakReference<View>(view); 17656 } 17657 17658 /** 17659 * Construct a shadow builder object with no associated View. This 17660 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 17661 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 17662 * to supply the drag shadow's dimensions and appearance without 17663 * reference to any View object. If they are not overridden, then the result is an 17664 * invisible drag shadow. 17665 */ 17666 public DragShadowBuilder() { 17667 mView = new WeakReference<View>(null); 17668 } 17669 17670 /** 17671 * Returns the View object that had been passed to the 17672 * {@link #View.DragShadowBuilder(View)} 17673 * constructor. If that View parameter was {@code null} or if the 17674 * {@link #View.DragShadowBuilder()} 17675 * constructor was used to instantiate the builder object, this method will return 17676 * null. 17677 * 17678 * @return The View object associate with this builder object. 17679 */ 17680 @SuppressWarnings({"JavadocReference"}) 17681 final public View getView() { 17682 return mView.get(); 17683 } 17684 17685 /** 17686 * Provides the metrics for the shadow image. These include the dimensions of 17687 * the shadow image, and the point within that shadow that should 17688 * be centered under the touch location while dragging. 17689 * <p> 17690 * The default implementation sets the dimensions of the shadow to be the 17691 * same as the dimensions of the View itself and centers the shadow under 17692 * the touch point. 17693 * </p> 17694 * 17695 * @param shadowSize A {@link android.graphics.Point} containing the width and height 17696 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 17697 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 17698 * image. 17699 * 17700 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 17701 * shadow image that should be underneath the touch point during the drag and drop 17702 * operation. Your application must set {@link android.graphics.Point#x} to the 17703 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 17704 */ 17705 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 17706 final View view = mView.get(); 17707 if (view != null) { 17708 shadowSize.set(view.getWidth(), view.getHeight()); 17709 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 17710 } else { 17711 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 17712 } 17713 } 17714 17715 /** 17716 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 17717 * based on the dimensions it received from the 17718 * {@link #onProvideShadowMetrics(Point, Point)} callback. 17719 * 17720 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 17721 */ 17722 public void onDrawShadow(Canvas canvas) { 17723 final View view = mView.get(); 17724 if (view != null) { 17725 view.draw(canvas); 17726 } else { 17727 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 17728 } 17729 } 17730 } 17731 17732 /** 17733 * Starts a drag and drop operation. When your application calls this method, it passes a 17734 * {@link android.view.View.DragShadowBuilder} object to the system. The 17735 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 17736 * to get metrics for the drag shadow, and then calls the object's 17737 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 17738 * <p> 17739 * Once the system has the drag shadow, it begins the drag and drop operation by sending 17740 * drag events to all the View objects in your application that are currently visible. It does 17741 * this either by calling the View object's drag listener (an implementation of 17742 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 17743 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17744 * Both are passed a {@link android.view.DragEvent} object that has a 17745 * {@link android.view.DragEvent#getAction()} value of 17746 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17747 * </p> 17748 * <p> 17749 * Your application can invoke startDrag() on any attached View object. The View object does not 17750 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17751 * be related to the View the user selected for dragging. 17752 * </p> 17753 * @param data A {@link android.content.ClipData} object pointing to the data to be 17754 * transferred by the drag and drop operation. 17755 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17756 * drag shadow. 17757 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17758 * drop operation. This Object is put into every DragEvent object sent by the system during the 17759 * current drag. 17760 * <p> 17761 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17762 * to the target Views. For example, it can contain flags that differentiate between a 17763 * a copy operation and a move operation. 17764 * </p> 17765 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17766 * so the parameter should be set to 0. 17767 * @return {@code true} if the method completes successfully, or 17768 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17769 * do a drag, and so no drag operation is in progress. 17770 */ 17771 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17772 Object myLocalState, int flags) { 17773 if (ViewDebug.DEBUG_DRAG) { 17774 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17775 } 17776 boolean okay = false; 17777 17778 Point shadowSize = new Point(); 17779 Point shadowTouchPoint = new Point(); 17780 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17781 17782 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17783 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17784 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17785 } 17786 17787 if (ViewDebug.DEBUG_DRAG) { 17788 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17789 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17790 } 17791 Surface surface = new Surface(); 17792 try { 17793 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17794 flags, shadowSize.x, shadowSize.y, surface); 17795 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17796 + " surface=" + surface); 17797 if (token != null) { 17798 Canvas canvas = surface.lockCanvas(null); 17799 try { 17800 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17801 shadowBuilder.onDrawShadow(canvas); 17802 } finally { 17803 surface.unlockCanvasAndPost(canvas); 17804 } 17805 17806 final ViewRootImpl root = getViewRootImpl(); 17807 17808 // Cache the local state object for delivery with DragEvents 17809 root.setLocalDragState(myLocalState); 17810 17811 // repurpose 'shadowSize' for the last touch point 17812 root.getLastTouchPoint(shadowSize); 17813 17814 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17815 shadowSize.x, shadowSize.y, 17816 shadowTouchPoint.x, shadowTouchPoint.y, data); 17817 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17818 17819 // Off and running! Release our local surface instance; the drag 17820 // shadow surface is now managed by the system process. 17821 surface.release(); 17822 } 17823 } catch (Exception e) { 17824 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17825 surface.destroy(); 17826 } 17827 17828 return okay; 17829 } 17830 17831 /** 17832 * Handles drag events sent by the system following a call to 17833 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17834 *<p> 17835 * When the system calls this method, it passes a 17836 * {@link android.view.DragEvent} object. A call to 17837 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17838 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17839 * operation. 17840 * @param event The {@link android.view.DragEvent} sent by the system. 17841 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17842 * in DragEvent, indicating the type of drag event represented by this object. 17843 * @return {@code true} if the method was successful, otherwise {@code false}. 17844 * <p> 17845 * The method should return {@code true} in response to an action type of 17846 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17847 * operation. 17848 * </p> 17849 * <p> 17850 * The method should also return {@code true} in response to an action type of 17851 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17852 * {@code false} if it didn't. 17853 * </p> 17854 */ 17855 public boolean onDragEvent(DragEvent event) { 17856 return false; 17857 } 17858 17859 /** 17860 * Detects if this View is enabled and has a drag event listener. 17861 * If both are true, then it calls the drag event listener with the 17862 * {@link android.view.DragEvent} it received. If the drag event listener returns 17863 * {@code true}, then dispatchDragEvent() returns {@code true}. 17864 * <p> 17865 * For all other cases, the method calls the 17866 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17867 * method and returns its result. 17868 * </p> 17869 * <p> 17870 * This ensures that a drag event is always consumed, even if the View does not have a drag 17871 * event listener. However, if the View has a listener and the listener returns true, then 17872 * onDragEvent() is not called. 17873 * </p> 17874 */ 17875 public boolean dispatchDragEvent(DragEvent event) { 17876 ListenerInfo li = mListenerInfo; 17877 //noinspection SimplifiableIfStatement 17878 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17879 && li.mOnDragListener.onDrag(this, event)) { 17880 return true; 17881 } 17882 return onDragEvent(event); 17883 } 17884 17885 boolean canAcceptDrag() { 17886 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17887 } 17888 17889 /** 17890 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17891 * it is ever exposed at all. 17892 * @hide 17893 */ 17894 public void onCloseSystemDialogs(String reason) { 17895 } 17896 17897 /** 17898 * Given a Drawable whose bounds have been set to draw into this view, 17899 * update a Region being computed for 17900 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17901 * that any non-transparent parts of the Drawable are removed from the 17902 * given transparent region. 17903 * 17904 * @param dr The Drawable whose transparency is to be applied to the region. 17905 * @param region A Region holding the current transparency information, 17906 * where any parts of the region that are set are considered to be 17907 * transparent. On return, this region will be modified to have the 17908 * transparency information reduced by the corresponding parts of the 17909 * Drawable that are not transparent. 17910 * {@hide} 17911 */ 17912 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17913 if (DBG) { 17914 Log.i("View", "Getting transparent region for: " + this); 17915 } 17916 final Region r = dr.getTransparentRegion(); 17917 final Rect db = dr.getBounds(); 17918 final AttachInfo attachInfo = mAttachInfo; 17919 if (r != null && attachInfo != null) { 17920 final int w = getRight()-getLeft(); 17921 final int h = getBottom()-getTop(); 17922 if (db.left > 0) { 17923 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 17924 r.op(0, 0, db.left, h, Region.Op.UNION); 17925 } 17926 if (db.right < w) { 17927 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 17928 r.op(db.right, 0, w, h, Region.Op.UNION); 17929 } 17930 if (db.top > 0) { 17931 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 17932 r.op(0, 0, w, db.top, Region.Op.UNION); 17933 } 17934 if (db.bottom < h) { 17935 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 17936 r.op(0, db.bottom, w, h, Region.Op.UNION); 17937 } 17938 final int[] location = attachInfo.mTransparentLocation; 17939 getLocationInWindow(location); 17940 r.translate(location[0], location[1]); 17941 region.op(r, Region.Op.INTERSECT); 17942 } else { 17943 region.op(db, Region.Op.DIFFERENCE); 17944 } 17945 } 17946 17947 private void checkForLongClick(int delayOffset) { 17948 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 17949 mHasPerformedLongPress = false; 17950 17951 if (mPendingCheckForLongPress == null) { 17952 mPendingCheckForLongPress = new CheckForLongPress(); 17953 } 17954 mPendingCheckForLongPress.rememberWindowAttachCount(); 17955 postDelayed(mPendingCheckForLongPress, 17956 ViewConfiguration.getLongPressTimeout() - delayOffset); 17957 } 17958 } 17959 17960 /** 17961 * Inflate a view from an XML resource. This convenience method wraps the {@link 17962 * LayoutInflater} class, which provides a full range of options for view inflation. 17963 * 17964 * @param context The Context object for your activity or application. 17965 * @param resource The resource ID to inflate 17966 * @param root A view group that will be the parent. Used to properly inflate the 17967 * layout_* parameters. 17968 * @see LayoutInflater 17969 */ 17970 public static View inflate(Context context, int resource, ViewGroup root) { 17971 LayoutInflater factory = LayoutInflater.from(context); 17972 return factory.inflate(resource, root); 17973 } 17974 17975 /** 17976 * Scroll the view with standard behavior for scrolling beyond the normal 17977 * content boundaries. Views that call this method should override 17978 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 17979 * results of an over-scroll operation. 17980 * 17981 * Views can use this method to handle any touch or fling-based scrolling. 17982 * 17983 * @param deltaX Change in X in pixels 17984 * @param deltaY Change in Y in pixels 17985 * @param scrollX Current X scroll value in pixels before applying deltaX 17986 * @param scrollY Current Y scroll value in pixels before applying deltaY 17987 * @param scrollRangeX Maximum content scroll range along the X axis 17988 * @param scrollRangeY Maximum content scroll range along the Y axis 17989 * @param maxOverScrollX Number of pixels to overscroll by in either direction 17990 * along the X axis. 17991 * @param maxOverScrollY Number of pixels to overscroll by in either direction 17992 * along the Y axis. 17993 * @param isTouchEvent true if this scroll operation is the result of a touch event. 17994 * @return true if scrolling was clamped to an over-scroll boundary along either 17995 * axis, false otherwise. 17996 */ 17997 @SuppressWarnings({"UnusedParameters"}) 17998 protected boolean overScrollBy(int deltaX, int deltaY, 17999 int scrollX, int scrollY, 18000 int scrollRangeX, int scrollRangeY, 18001 int maxOverScrollX, int maxOverScrollY, 18002 boolean isTouchEvent) { 18003 final int overScrollMode = mOverScrollMode; 18004 final boolean canScrollHorizontal = 18005 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18006 final boolean canScrollVertical = 18007 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18008 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18009 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18010 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18011 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18012 18013 int newScrollX = scrollX + deltaX; 18014 if (!overScrollHorizontal) { 18015 maxOverScrollX = 0; 18016 } 18017 18018 int newScrollY = scrollY + deltaY; 18019 if (!overScrollVertical) { 18020 maxOverScrollY = 0; 18021 } 18022 18023 // Clamp values if at the limits and record 18024 final int left = -maxOverScrollX; 18025 final int right = maxOverScrollX + scrollRangeX; 18026 final int top = -maxOverScrollY; 18027 final int bottom = maxOverScrollY + scrollRangeY; 18028 18029 boolean clampedX = false; 18030 if (newScrollX > right) { 18031 newScrollX = right; 18032 clampedX = true; 18033 } else if (newScrollX < left) { 18034 newScrollX = left; 18035 clampedX = true; 18036 } 18037 18038 boolean clampedY = false; 18039 if (newScrollY > bottom) { 18040 newScrollY = bottom; 18041 clampedY = true; 18042 } else if (newScrollY < top) { 18043 newScrollY = top; 18044 clampedY = true; 18045 } 18046 18047 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18048 18049 return clampedX || clampedY; 18050 } 18051 18052 /** 18053 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18054 * respond to the results of an over-scroll operation. 18055 * 18056 * @param scrollX New X scroll value in pixels 18057 * @param scrollY New Y scroll value in pixels 18058 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18059 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18060 */ 18061 protected void onOverScrolled(int scrollX, int scrollY, 18062 boolean clampedX, boolean clampedY) { 18063 // Intentionally empty. 18064 } 18065 18066 /** 18067 * Returns the over-scroll mode for this view. The result will be 18068 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18069 * (allow over-scrolling only if the view content is larger than the container), 18070 * or {@link #OVER_SCROLL_NEVER}. 18071 * 18072 * @return This view's over-scroll mode. 18073 */ 18074 public int getOverScrollMode() { 18075 return mOverScrollMode; 18076 } 18077 18078 /** 18079 * Set the over-scroll mode for this view. Valid over-scroll modes are 18080 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18081 * (allow over-scrolling only if the view content is larger than the container), 18082 * or {@link #OVER_SCROLL_NEVER}. 18083 * 18084 * Setting the over-scroll mode of a view will have an effect only if the 18085 * view is capable of scrolling. 18086 * 18087 * @param overScrollMode The new over-scroll mode for this view. 18088 */ 18089 public void setOverScrollMode(int overScrollMode) { 18090 if (overScrollMode != OVER_SCROLL_ALWAYS && 18091 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18092 overScrollMode != OVER_SCROLL_NEVER) { 18093 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18094 } 18095 mOverScrollMode = overScrollMode; 18096 } 18097 18098 /** 18099 * Enable or disable nested scrolling for this view. 18100 * 18101 * <p>If this property is set to true the view will be permitted to initiate nested 18102 * scrolling operations with a compatible parent view in the current hierarchy. If this 18103 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 18104 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 18105 * the nested scroll.</p> 18106 * 18107 * @param enabled true to enable nested scrolling, false to disable 18108 * 18109 * @see #isNestedScrollingEnabled() 18110 */ 18111 public void setNestedScrollingEnabled(boolean enabled) { 18112 if (enabled) { 18113 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18114 } else { 18115 stopNestedScroll(); 18116 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18117 } 18118 } 18119 18120 /** 18121 * Returns true if nested scrolling is enabled for this view. 18122 * 18123 * <p>If nested scrolling is enabled and this View class implementation supports it, 18124 * this view will act as a nested scrolling child view when applicable, forwarding data 18125 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18126 * parent.</p> 18127 * 18128 * @return true if nested scrolling is enabled 18129 * 18130 * @see #setNestedScrollingEnabled(boolean) 18131 */ 18132 public boolean isNestedScrollingEnabled() { 18133 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18134 PFLAG3_NESTED_SCROLLING_ENABLED; 18135 } 18136 18137 /** 18138 * Begin a nestable scroll operation along the given axes. 18139 * 18140 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18141 * 18142 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18143 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18144 * In the case of touch scrolling the nested scroll will be terminated automatically in 18145 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18146 * In the event of programmatic scrolling the caller must explicitly call 18147 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18148 * 18149 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18150 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18151 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18152 * 18153 * <p>At each incremental step of the scroll the caller should invoke 18154 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18155 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18156 * parent at least partially consumed the scroll and the caller should adjust the amount it 18157 * scrolls by.</p> 18158 * 18159 * <p>After applying the remainder of the scroll delta the caller should invoke 18160 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18161 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18162 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18163 * </p> 18164 * 18165 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18166 * {@link #SCROLL_AXIS_VERTICAL}. 18167 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18168 * the current gesture. 18169 * 18170 * @see #stopNestedScroll() 18171 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18172 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18173 */ 18174 public boolean startNestedScroll(int axes) { 18175 if (hasNestedScrollingParent()) { 18176 // Already in progress 18177 return true; 18178 } 18179 if (isNestedScrollingEnabled()) { 18180 ViewParent p = getParent(); 18181 View child = this; 18182 while (p != null) { 18183 try { 18184 if (p.onStartNestedScroll(child, this, axes)) { 18185 mNestedScrollingParent = p; 18186 p.onNestedScrollAccepted(child, this, axes); 18187 return true; 18188 } 18189 } catch (AbstractMethodError e) { 18190 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18191 "method onStartNestedScroll", e); 18192 // Allow the search upward to continue 18193 } 18194 if (p instanceof View) { 18195 child = (View) p; 18196 } 18197 p = p.getParent(); 18198 } 18199 } 18200 return false; 18201 } 18202 18203 /** 18204 * Stop a nested scroll in progress. 18205 * 18206 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18207 * 18208 * @see #startNestedScroll(int) 18209 */ 18210 public void stopNestedScroll() { 18211 if (mNestedScrollingParent != null) { 18212 mNestedScrollingParent.onStopNestedScroll(this); 18213 mNestedScrollingParent = null; 18214 } 18215 } 18216 18217 /** 18218 * Returns true if this view has a nested scrolling parent. 18219 * 18220 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18221 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18222 * 18223 * @return whether this view has a nested scrolling parent 18224 */ 18225 public boolean hasNestedScrollingParent() { 18226 return mNestedScrollingParent != null; 18227 } 18228 18229 /** 18230 * Dispatch one step of a nested scroll in progress. 18231 * 18232 * <p>Implementations of views that support nested scrolling should call this to report 18233 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18234 * is not currently in progress or nested scrolling is not 18235 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18236 * 18237 * <p>Compatible View implementations should also call 18238 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18239 * consuming a component of the scroll event themselves.</p> 18240 * 18241 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18242 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18243 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18244 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18245 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18246 * in local view coordinates of this view from before this operation 18247 * to after it completes. View implementations may use this to adjust 18248 * expected input coordinate tracking. 18249 * @return true if the event was dispatched, false if it could not be dispatched. 18250 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18251 */ 18252 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18253 int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { 18254 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18255 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18256 int startX = 0; 18257 int startY = 0; 18258 if (offsetInWindow != null) { 18259 getLocationInWindow(offsetInWindow); 18260 startX = offsetInWindow[0]; 18261 startY = offsetInWindow[1]; 18262 } 18263 18264 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18265 dxUnconsumed, dyUnconsumed); 18266 18267 if (offsetInWindow != null) { 18268 getLocationInWindow(offsetInWindow); 18269 offsetInWindow[0] -= startX; 18270 offsetInWindow[1] -= startY; 18271 } 18272 return true; 18273 } else if (offsetInWindow != null) { 18274 // No motion, no dispatch. Keep offsetInWindow up to date. 18275 offsetInWindow[0] = 0; 18276 offsetInWindow[1] = 0; 18277 } 18278 } 18279 return false; 18280 } 18281 18282 /** 18283 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18284 * 18285 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18286 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18287 * scrolling operation to consume some or all of the scroll operation before the child view 18288 * consumes it.</p> 18289 * 18290 * @param dx Horizontal scroll distance in pixels 18291 * @param dy Vertical scroll distance in pixels 18292 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18293 * and consumed[1] the consumed dy. 18294 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18295 * in local view coordinates of this view from before this operation 18296 * to after it completes. View implementations may use this to adjust 18297 * expected input coordinate tracking. 18298 * @return true if the parent consumed some or all of the scroll delta 18299 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18300 */ 18301 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 18302 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18303 if (dx != 0 || dy != 0) { 18304 int startX = 0; 18305 int startY = 0; 18306 if (offsetInWindow != null) { 18307 getLocationInWindow(offsetInWindow); 18308 startX = offsetInWindow[0]; 18309 startY = offsetInWindow[1]; 18310 } 18311 18312 if (consumed == null) { 18313 if (mTempNestedScrollConsumed == null) { 18314 mTempNestedScrollConsumed = new int[2]; 18315 } 18316 consumed = mTempNestedScrollConsumed; 18317 } 18318 consumed[0] = 0; 18319 consumed[1] = 0; 18320 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 18321 18322 if (offsetInWindow != null) { 18323 getLocationInWindow(offsetInWindow); 18324 offsetInWindow[0] -= startX; 18325 offsetInWindow[1] -= startY; 18326 } 18327 return consumed[0] != 0 || consumed[1] != 0; 18328 } else if (offsetInWindow != null) { 18329 offsetInWindow[0] = 0; 18330 offsetInWindow[1] = 0; 18331 } 18332 } 18333 return false; 18334 } 18335 18336 /** 18337 * Dispatch a fling to a nested scrolling parent. 18338 * 18339 * <p>This method should be used to indicate that a nested scrolling child has detected 18340 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 18341 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 18342 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 18343 * along a scrollable axis.</p> 18344 * 18345 * <p>If a nested scrolling child view would normally fling but it is at the edge of 18346 * its own content, it can use this method to delegate the fling to its nested scrolling 18347 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 18348 * 18349 * @param velocityX Horizontal fling velocity in pixels per second 18350 * @param velocityY Vertical fling velocity in pixels per second 18351 * @param consumed true if the child consumed the fling, false otherwise 18352 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 18353 */ 18354 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 18355 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18356 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 18357 } 18358 return false; 18359 } 18360 18361 /** 18362 * Gets a scale factor that determines the distance the view should scroll 18363 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 18364 * @return The vertical scroll scale factor. 18365 * @hide 18366 */ 18367 protected float getVerticalScrollFactor() { 18368 if (mVerticalScrollFactor == 0) { 18369 TypedValue outValue = new TypedValue(); 18370 if (!mContext.getTheme().resolveAttribute( 18371 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 18372 throw new IllegalStateException( 18373 "Expected theme to define listPreferredItemHeight."); 18374 } 18375 mVerticalScrollFactor = outValue.getDimension( 18376 mContext.getResources().getDisplayMetrics()); 18377 } 18378 return mVerticalScrollFactor; 18379 } 18380 18381 /** 18382 * Gets a scale factor that determines the distance the view should scroll 18383 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 18384 * @return The horizontal scroll scale factor. 18385 * @hide 18386 */ 18387 protected float getHorizontalScrollFactor() { 18388 // TODO: Should use something else. 18389 return getVerticalScrollFactor(); 18390 } 18391 18392 /** 18393 * Return the value specifying the text direction or policy that was set with 18394 * {@link #setTextDirection(int)}. 18395 * 18396 * @return the defined text direction. It can be one of: 18397 * 18398 * {@link #TEXT_DIRECTION_INHERIT}, 18399 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18400 * {@link #TEXT_DIRECTION_ANY_RTL}, 18401 * {@link #TEXT_DIRECTION_LTR}, 18402 * {@link #TEXT_DIRECTION_RTL}, 18403 * {@link #TEXT_DIRECTION_LOCALE} 18404 * 18405 * @attr ref android.R.styleable#View_textDirection 18406 * 18407 * @hide 18408 */ 18409 @ViewDebug.ExportedProperty(category = "text", mapping = { 18410 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18411 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18412 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18413 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18414 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18415 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18416 }) 18417 public int getRawTextDirection() { 18418 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 18419 } 18420 18421 /** 18422 * Set the text direction. 18423 * 18424 * @param textDirection the direction to set. Should be one of: 18425 * 18426 * {@link #TEXT_DIRECTION_INHERIT}, 18427 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18428 * {@link #TEXT_DIRECTION_ANY_RTL}, 18429 * {@link #TEXT_DIRECTION_LTR}, 18430 * {@link #TEXT_DIRECTION_RTL}, 18431 * {@link #TEXT_DIRECTION_LOCALE} 18432 * 18433 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 18434 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 18435 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 18436 * 18437 * @attr ref android.R.styleable#View_textDirection 18438 */ 18439 public void setTextDirection(int textDirection) { 18440 if (getRawTextDirection() != textDirection) { 18441 // Reset the current text direction and the resolved one 18442 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 18443 resetResolvedTextDirection(); 18444 // Set the new text direction 18445 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 18446 // Do resolution 18447 resolveTextDirection(); 18448 // Notify change 18449 onRtlPropertiesChanged(getLayoutDirection()); 18450 // Refresh 18451 requestLayout(); 18452 invalidate(true); 18453 } 18454 } 18455 18456 /** 18457 * Return the resolved text direction. 18458 * 18459 * @return the resolved text direction. Returns one of: 18460 * 18461 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18462 * {@link #TEXT_DIRECTION_ANY_RTL}, 18463 * {@link #TEXT_DIRECTION_LTR}, 18464 * {@link #TEXT_DIRECTION_RTL}, 18465 * {@link #TEXT_DIRECTION_LOCALE} 18466 * 18467 * @attr ref android.R.styleable#View_textDirection 18468 */ 18469 @ViewDebug.ExportedProperty(category = "text", mapping = { 18470 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18471 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18472 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18473 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18474 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18475 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18476 }) 18477 public int getTextDirection() { 18478 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 18479 } 18480 18481 /** 18482 * Resolve the text direction. 18483 * 18484 * @return true if resolution has been done, false otherwise. 18485 * 18486 * @hide 18487 */ 18488 public boolean resolveTextDirection() { 18489 // Reset any previous text direction resolution 18490 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18491 18492 if (hasRtlSupport()) { 18493 // Set resolved text direction flag depending on text direction flag 18494 final int textDirection = getRawTextDirection(); 18495 switch(textDirection) { 18496 case TEXT_DIRECTION_INHERIT: 18497 if (!canResolveTextDirection()) { 18498 // We cannot do the resolution if there is no parent, so use the default one 18499 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18500 // Resolution will need to happen again later 18501 return false; 18502 } 18503 18504 // Parent has not yet resolved, so we still return the default 18505 try { 18506 if (!mParent.isTextDirectionResolved()) { 18507 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18508 // Resolution will need to happen again later 18509 return false; 18510 } 18511 } catch (AbstractMethodError e) { 18512 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18513 " does not fully implement ViewParent", e); 18514 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 18515 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18516 return true; 18517 } 18518 18519 // Set current resolved direction to the same value as the parent's one 18520 int parentResolvedDirection; 18521 try { 18522 parentResolvedDirection = mParent.getTextDirection(); 18523 } catch (AbstractMethodError e) { 18524 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18525 " does not fully implement ViewParent", e); 18526 parentResolvedDirection = TEXT_DIRECTION_LTR; 18527 } 18528 switch (parentResolvedDirection) { 18529 case TEXT_DIRECTION_FIRST_STRONG: 18530 case TEXT_DIRECTION_ANY_RTL: 18531 case TEXT_DIRECTION_LTR: 18532 case TEXT_DIRECTION_RTL: 18533 case TEXT_DIRECTION_LOCALE: 18534 mPrivateFlags2 |= 18535 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18536 break; 18537 default: 18538 // Default resolved direction is "first strong" heuristic 18539 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18540 } 18541 break; 18542 case TEXT_DIRECTION_FIRST_STRONG: 18543 case TEXT_DIRECTION_ANY_RTL: 18544 case TEXT_DIRECTION_LTR: 18545 case TEXT_DIRECTION_RTL: 18546 case TEXT_DIRECTION_LOCALE: 18547 // Resolved direction is the same as text direction 18548 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18549 break; 18550 default: 18551 // Default resolved direction is "first strong" heuristic 18552 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18553 } 18554 } else { 18555 // Default resolved direction is "first strong" heuristic 18556 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18557 } 18558 18559 // Set to resolved 18560 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 18561 return true; 18562 } 18563 18564 /** 18565 * Check if text direction resolution can be done. 18566 * 18567 * @return true if text direction resolution can be done otherwise return false. 18568 */ 18569 public boolean canResolveTextDirection() { 18570 switch (getRawTextDirection()) { 18571 case TEXT_DIRECTION_INHERIT: 18572 if (mParent != null) { 18573 try { 18574 return mParent.canResolveTextDirection(); 18575 } catch (AbstractMethodError e) { 18576 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18577 " does not fully implement ViewParent", e); 18578 } 18579 } 18580 return false; 18581 18582 default: 18583 return true; 18584 } 18585 } 18586 18587 /** 18588 * Reset resolved text direction. Text direction will be resolved during a call to 18589 * {@link #onMeasure(int, int)}. 18590 * 18591 * @hide 18592 */ 18593 public void resetResolvedTextDirection() { 18594 // Reset any previous text direction resolution 18595 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18596 // Set to default value 18597 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18598 } 18599 18600 /** 18601 * @return true if text direction is inherited. 18602 * 18603 * @hide 18604 */ 18605 public boolean isTextDirectionInherited() { 18606 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 18607 } 18608 18609 /** 18610 * @return true if text direction is resolved. 18611 */ 18612 public boolean isTextDirectionResolved() { 18613 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 18614 } 18615 18616 /** 18617 * Return the value specifying the text alignment or policy that was set with 18618 * {@link #setTextAlignment(int)}. 18619 * 18620 * @return the defined text alignment. It can be one of: 18621 * 18622 * {@link #TEXT_ALIGNMENT_INHERIT}, 18623 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18624 * {@link #TEXT_ALIGNMENT_CENTER}, 18625 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18626 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18627 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18628 * {@link #TEXT_ALIGNMENT_VIEW_END} 18629 * 18630 * @attr ref android.R.styleable#View_textAlignment 18631 * 18632 * @hide 18633 */ 18634 @ViewDebug.ExportedProperty(category = "text", mapping = { 18635 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18636 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18637 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18638 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18639 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18640 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18641 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18642 }) 18643 @TextAlignment 18644 public int getRawTextAlignment() { 18645 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 18646 } 18647 18648 /** 18649 * Set the text alignment. 18650 * 18651 * @param textAlignment The text alignment to set. Should be one of 18652 * 18653 * {@link #TEXT_ALIGNMENT_INHERIT}, 18654 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18655 * {@link #TEXT_ALIGNMENT_CENTER}, 18656 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18657 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18658 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18659 * {@link #TEXT_ALIGNMENT_VIEW_END} 18660 * 18661 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 18662 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 18663 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 18664 * 18665 * @attr ref android.R.styleable#View_textAlignment 18666 */ 18667 public void setTextAlignment(@TextAlignment int textAlignment) { 18668 if (textAlignment != getRawTextAlignment()) { 18669 // Reset the current and resolved text alignment 18670 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 18671 resetResolvedTextAlignment(); 18672 // Set the new text alignment 18673 mPrivateFlags2 |= 18674 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 18675 // Do resolution 18676 resolveTextAlignment(); 18677 // Notify change 18678 onRtlPropertiesChanged(getLayoutDirection()); 18679 // Refresh 18680 requestLayout(); 18681 invalidate(true); 18682 } 18683 } 18684 18685 /** 18686 * Return the resolved text alignment. 18687 * 18688 * @return the resolved text alignment. Returns one of: 18689 * 18690 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18691 * {@link #TEXT_ALIGNMENT_CENTER}, 18692 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18693 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18694 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18695 * {@link #TEXT_ALIGNMENT_VIEW_END} 18696 * 18697 * @attr ref android.R.styleable#View_textAlignment 18698 */ 18699 @ViewDebug.ExportedProperty(category = "text", mapping = { 18700 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18701 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18702 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18703 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18704 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18705 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18706 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18707 }) 18708 @TextAlignment 18709 public int getTextAlignment() { 18710 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 18711 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 18712 } 18713 18714 /** 18715 * Resolve the text alignment. 18716 * 18717 * @return true if resolution has been done, false otherwise. 18718 * 18719 * @hide 18720 */ 18721 public boolean resolveTextAlignment() { 18722 // Reset any previous text alignment resolution 18723 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18724 18725 if (hasRtlSupport()) { 18726 // Set resolved text alignment flag depending on text alignment flag 18727 final int textAlignment = getRawTextAlignment(); 18728 switch (textAlignment) { 18729 case TEXT_ALIGNMENT_INHERIT: 18730 // Check if we can resolve the text alignment 18731 if (!canResolveTextAlignment()) { 18732 // We cannot do the resolution if there is no parent so use the default 18733 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18734 // Resolution will need to happen again later 18735 return false; 18736 } 18737 18738 // Parent has not yet resolved, so we still return the default 18739 try { 18740 if (!mParent.isTextAlignmentResolved()) { 18741 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18742 // Resolution will need to happen again later 18743 return false; 18744 } 18745 } catch (AbstractMethodError e) { 18746 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18747 " does not fully implement ViewParent", e); 18748 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 18749 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18750 return true; 18751 } 18752 18753 int parentResolvedTextAlignment; 18754 try { 18755 parentResolvedTextAlignment = mParent.getTextAlignment(); 18756 } catch (AbstractMethodError e) { 18757 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18758 " does not fully implement ViewParent", e); 18759 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 18760 } 18761 switch (parentResolvedTextAlignment) { 18762 case TEXT_ALIGNMENT_GRAVITY: 18763 case TEXT_ALIGNMENT_TEXT_START: 18764 case TEXT_ALIGNMENT_TEXT_END: 18765 case TEXT_ALIGNMENT_CENTER: 18766 case TEXT_ALIGNMENT_VIEW_START: 18767 case TEXT_ALIGNMENT_VIEW_END: 18768 // Resolved text alignment is the same as the parent resolved 18769 // text alignment 18770 mPrivateFlags2 |= 18771 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18772 break; 18773 default: 18774 // Use default resolved text alignment 18775 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18776 } 18777 break; 18778 case TEXT_ALIGNMENT_GRAVITY: 18779 case TEXT_ALIGNMENT_TEXT_START: 18780 case TEXT_ALIGNMENT_TEXT_END: 18781 case TEXT_ALIGNMENT_CENTER: 18782 case TEXT_ALIGNMENT_VIEW_START: 18783 case TEXT_ALIGNMENT_VIEW_END: 18784 // Resolved text alignment is the same as text alignment 18785 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18786 break; 18787 default: 18788 // Use default resolved text alignment 18789 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18790 } 18791 } else { 18792 // Use default resolved text alignment 18793 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18794 } 18795 18796 // Set the resolved 18797 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18798 return true; 18799 } 18800 18801 /** 18802 * Check if text alignment resolution can be done. 18803 * 18804 * @return true if text alignment resolution can be done otherwise return false. 18805 */ 18806 public boolean canResolveTextAlignment() { 18807 switch (getRawTextAlignment()) { 18808 case TEXT_DIRECTION_INHERIT: 18809 if (mParent != null) { 18810 try { 18811 return mParent.canResolveTextAlignment(); 18812 } catch (AbstractMethodError e) { 18813 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18814 " does not fully implement ViewParent", e); 18815 } 18816 } 18817 return false; 18818 18819 default: 18820 return true; 18821 } 18822 } 18823 18824 /** 18825 * Reset resolved text alignment. Text alignment will be resolved during a call to 18826 * {@link #onMeasure(int, int)}. 18827 * 18828 * @hide 18829 */ 18830 public void resetResolvedTextAlignment() { 18831 // Reset any previous text alignment resolution 18832 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18833 // Set to default 18834 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18835 } 18836 18837 /** 18838 * @return true if text alignment is inherited. 18839 * 18840 * @hide 18841 */ 18842 public boolean isTextAlignmentInherited() { 18843 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 18844 } 18845 18846 /** 18847 * @return true if text alignment is resolved. 18848 */ 18849 public boolean isTextAlignmentResolved() { 18850 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18851 } 18852 18853 /** 18854 * Generate a value suitable for use in {@link #setId(int)}. 18855 * This value will not collide with ID values generated at build time by aapt for R.id. 18856 * 18857 * @return a generated ID value 18858 */ 18859 public static int generateViewId() { 18860 for (;;) { 18861 final int result = sNextGeneratedId.get(); 18862 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 18863 int newValue = result + 1; 18864 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 18865 if (sNextGeneratedId.compareAndSet(result, newValue)) { 18866 return result; 18867 } 18868 } 18869 } 18870 18871 /** 18872 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 18873 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 18874 * a normal View or a ViewGroup with 18875 * {@link android.view.ViewGroup#isTransitionGroup()} true. 18876 * @hide 18877 */ 18878 public void captureTransitioningViews(List<View> transitioningViews) { 18879 if (getVisibility() == View.VISIBLE) { 18880 transitioningViews.add(this); 18881 } 18882 } 18883 18884 /** 18885 * Adds all Views that have {@link #getViewName()} non-null to namedElements. 18886 * @param namedElements Will contain all Views in the hierarchy having a view name. 18887 * @hide 18888 */ 18889 public void findNamedViews(Map<String, View> namedElements) { 18890 if (getVisibility() == VISIBLE) { 18891 String viewName = getViewName(); 18892 if (viewName != null) { 18893 namedElements.put(viewName, this); 18894 } 18895 } 18896 } 18897 18898 // 18899 // Properties 18900 // 18901 /** 18902 * A Property wrapper around the <code>alpha</code> functionality handled by the 18903 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 18904 */ 18905 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 18906 @Override 18907 public void setValue(View object, float value) { 18908 object.setAlpha(value); 18909 } 18910 18911 @Override 18912 public Float get(View object) { 18913 return object.getAlpha(); 18914 } 18915 }; 18916 18917 /** 18918 * A Property wrapper around the <code>translationX</code> functionality handled by the 18919 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 18920 */ 18921 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 18922 @Override 18923 public void setValue(View object, float value) { 18924 object.setTranslationX(value); 18925 } 18926 18927 @Override 18928 public Float get(View object) { 18929 return object.getTranslationX(); 18930 } 18931 }; 18932 18933 /** 18934 * A Property wrapper around the <code>translationY</code> functionality handled by the 18935 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 18936 */ 18937 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 18938 @Override 18939 public void setValue(View object, float value) { 18940 object.setTranslationY(value); 18941 } 18942 18943 @Override 18944 public Float get(View object) { 18945 return object.getTranslationY(); 18946 } 18947 }; 18948 18949 /** 18950 * A Property wrapper around the <code>translationZ</code> functionality handled by the 18951 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 18952 */ 18953 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 18954 @Override 18955 public void setValue(View object, float value) { 18956 object.setTranslationZ(value); 18957 } 18958 18959 @Override 18960 public Float get(View object) { 18961 return object.getTranslationZ(); 18962 } 18963 }; 18964 18965 /** 18966 * A Property wrapper around the <code>x</code> functionality handled by the 18967 * {@link View#setX(float)} and {@link View#getX()} methods. 18968 */ 18969 public static final Property<View, Float> X = new FloatProperty<View>("x") { 18970 @Override 18971 public void setValue(View object, float value) { 18972 object.setX(value); 18973 } 18974 18975 @Override 18976 public Float get(View object) { 18977 return object.getX(); 18978 } 18979 }; 18980 18981 /** 18982 * A Property wrapper around the <code>y</code> functionality handled by the 18983 * {@link View#setY(float)} and {@link View#getY()} methods. 18984 */ 18985 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 18986 @Override 18987 public void setValue(View object, float value) { 18988 object.setY(value); 18989 } 18990 18991 @Override 18992 public Float get(View object) { 18993 return object.getY(); 18994 } 18995 }; 18996 18997 /** 18998 * A Property wrapper around the <code>z</code> functionality handled by the 18999 * {@link View#setZ(float)} and {@link View#getZ()} methods. 19000 */ 19001 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 19002 @Override 19003 public void setValue(View object, float value) { 19004 object.setZ(value); 19005 } 19006 19007 @Override 19008 public Float get(View object) { 19009 return object.getZ(); 19010 } 19011 }; 19012 19013 /** 19014 * A Property wrapper around the <code>rotation</code> functionality handled by the 19015 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 19016 */ 19017 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 19018 @Override 19019 public void setValue(View object, float value) { 19020 object.setRotation(value); 19021 } 19022 19023 @Override 19024 public Float get(View object) { 19025 return object.getRotation(); 19026 } 19027 }; 19028 19029 /** 19030 * A Property wrapper around the <code>rotationX</code> functionality handled by the 19031 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 19032 */ 19033 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 19034 @Override 19035 public void setValue(View object, float value) { 19036 object.setRotationX(value); 19037 } 19038 19039 @Override 19040 public Float get(View object) { 19041 return object.getRotationX(); 19042 } 19043 }; 19044 19045 /** 19046 * A Property wrapper around the <code>rotationY</code> functionality handled by the 19047 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 19048 */ 19049 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 19050 @Override 19051 public void setValue(View object, float value) { 19052 object.setRotationY(value); 19053 } 19054 19055 @Override 19056 public Float get(View object) { 19057 return object.getRotationY(); 19058 } 19059 }; 19060 19061 /** 19062 * A Property wrapper around the <code>scaleX</code> functionality handled by the 19063 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 19064 */ 19065 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 19066 @Override 19067 public void setValue(View object, float value) { 19068 object.setScaleX(value); 19069 } 19070 19071 @Override 19072 public Float get(View object) { 19073 return object.getScaleX(); 19074 } 19075 }; 19076 19077 /** 19078 * A Property wrapper around the <code>scaleY</code> functionality handled by the 19079 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 19080 */ 19081 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 19082 @Override 19083 public void setValue(View object, float value) { 19084 object.setScaleY(value); 19085 } 19086 19087 @Override 19088 public Float get(View object) { 19089 return object.getScaleY(); 19090 } 19091 }; 19092 19093 /** 19094 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 19095 * Each MeasureSpec represents a requirement for either the width or the height. 19096 * A MeasureSpec is comprised of a size and a mode. There are three possible 19097 * modes: 19098 * <dl> 19099 * <dt>UNSPECIFIED</dt> 19100 * <dd> 19101 * The parent has not imposed any constraint on the child. It can be whatever size 19102 * it wants. 19103 * </dd> 19104 * 19105 * <dt>EXACTLY</dt> 19106 * <dd> 19107 * The parent has determined an exact size for the child. The child is going to be 19108 * given those bounds regardless of how big it wants to be. 19109 * </dd> 19110 * 19111 * <dt>AT_MOST</dt> 19112 * <dd> 19113 * The child can be as large as it wants up to the specified size. 19114 * </dd> 19115 * </dl> 19116 * 19117 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19118 * is provided to pack and unpack the <size, mode> tuple into the int. 19119 */ 19120 public static class MeasureSpec { 19121 private static final int MODE_SHIFT = 30; 19122 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19123 19124 /** 19125 * Measure specification mode: The parent has not imposed any constraint 19126 * on the child. It can be whatever size it wants. 19127 */ 19128 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19129 19130 /** 19131 * Measure specification mode: The parent has determined an exact size 19132 * for the child. The child is going to be given those bounds regardless 19133 * of how big it wants to be. 19134 */ 19135 public static final int EXACTLY = 1 << MODE_SHIFT; 19136 19137 /** 19138 * Measure specification mode: The child can be as large as it wants up 19139 * to the specified size. 19140 */ 19141 public static final int AT_MOST = 2 << MODE_SHIFT; 19142 19143 /** 19144 * Creates a measure specification based on the supplied size and mode. 19145 * 19146 * The mode must always be one of the following: 19147 * <ul> 19148 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19149 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19150 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19151 * </ul> 19152 * 19153 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19154 * implementation was such that the order of arguments did not matter 19155 * and overflow in either value could impact the resulting MeasureSpec. 19156 * {@link android.widget.RelativeLayout} was affected by this bug. 19157 * Apps targeting API levels greater than 17 will get the fixed, more strict 19158 * behavior.</p> 19159 * 19160 * @param size the size of the measure specification 19161 * @param mode the mode of the measure specification 19162 * @return the measure specification based on size and mode 19163 */ 19164 public static int makeMeasureSpec(int size, int mode) { 19165 if (sUseBrokenMakeMeasureSpec) { 19166 return size + mode; 19167 } else { 19168 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19169 } 19170 } 19171 19172 /** 19173 * Extracts the mode from the supplied measure specification. 19174 * 19175 * @param measureSpec the measure specification to extract the mode from 19176 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19177 * {@link android.view.View.MeasureSpec#AT_MOST} or 19178 * {@link android.view.View.MeasureSpec#EXACTLY} 19179 */ 19180 public static int getMode(int measureSpec) { 19181 return (measureSpec & MODE_MASK); 19182 } 19183 19184 /** 19185 * Extracts the size from the supplied measure specification. 19186 * 19187 * @param measureSpec the measure specification to extract the size from 19188 * @return the size in pixels defined in the supplied measure specification 19189 */ 19190 public static int getSize(int measureSpec) { 19191 return (measureSpec & ~MODE_MASK); 19192 } 19193 19194 static int adjust(int measureSpec, int delta) { 19195 final int mode = getMode(measureSpec); 19196 if (mode == UNSPECIFIED) { 19197 // No need to adjust size for UNSPECIFIED mode. 19198 return makeMeasureSpec(0, UNSPECIFIED); 19199 } 19200 int size = getSize(measureSpec) + delta; 19201 if (size < 0) { 19202 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19203 ") spec: " + toString(measureSpec) + " delta: " + delta); 19204 size = 0; 19205 } 19206 return makeMeasureSpec(size, mode); 19207 } 19208 19209 /** 19210 * Returns a String representation of the specified measure 19211 * specification. 19212 * 19213 * @param measureSpec the measure specification to convert to a String 19214 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19215 */ 19216 public static String toString(int measureSpec) { 19217 int mode = getMode(measureSpec); 19218 int size = getSize(measureSpec); 19219 19220 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19221 19222 if (mode == UNSPECIFIED) 19223 sb.append("UNSPECIFIED "); 19224 else if (mode == EXACTLY) 19225 sb.append("EXACTLY "); 19226 else if (mode == AT_MOST) 19227 sb.append("AT_MOST "); 19228 else 19229 sb.append(mode).append(" "); 19230 19231 sb.append(size); 19232 return sb.toString(); 19233 } 19234 } 19235 19236 private final class CheckForLongPress implements Runnable { 19237 private int mOriginalWindowAttachCount; 19238 19239 @Override 19240 public void run() { 19241 if (isPressed() && (mParent != null) 19242 && mOriginalWindowAttachCount == mWindowAttachCount) { 19243 if (performLongClick()) { 19244 mHasPerformedLongPress = true; 19245 } 19246 } 19247 } 19248 19249 public void rememberWindowAttachCount() { 19250 mOriginalWindowAttachCount = mWindowAttachCount; 19251 } 19252 } 19253 19254 private final class CheckForTap implements Runnable { 19255 public float x; 19256 public float y; 19257 19258 @Override 19259 public void run() { 19260 mPrivateFlags &= ~PFLAG_PREPRESSED; 19261 setHotspot(R.attr.state_pressed, x, y); 19262 setPressed(true); 19263 checkForLongClick(ViewConfiguration.getTapTimeout()); 19264 } 19265 } 19266 19267 private final class PerformClick implements Runnable { 19268 @Override 19269 public void run() { 19270 performClick(); 19271 } 19272 } 19273 19274 /** @hide */ 19275 public void hackTurnOffWindowResizeAnim(boolean off) { 19276 mAttachInfo.mTurnOffWindowResizeAnim = off; 19277 } 19278 19279 /** 19280 * This method returns a ViewPropertyAnimator object, which can be used to animate 19281 * specific properties on this View. 19282 * 19283 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19284 */ 19285 public ViewPropertyAnimator animate() { 19286 if (mAnimator == null) { 19287 mAnimator = new ViewPropertyAnimator(this); 19288 } 19289 return mAnimator; 19290 } 19291 19292 /** 19293 * Sets the name of the View to be used to identify Views in Transitions. 19294 * Names should be unique in the View hierarchy. 19295 * 19296 * @param viewName The name of the View to uniquely identify it for Transitions. 19297 */ 19298 public final void setViewName(String viewName) { 19299 mViewName = viewName; 19300 } 19301 19302 /** 19303 * Returns the name of the View to be used to identify Views in Transitions. 19304 * Names should be unique in the View hierarchy. 19305 * 19306 * <p>This returns null if the View has not been given a name.</p> 19307 * 19308 * @return The name used of the View to be used to identify Views in Transitions or null 19309 * if no name has been given. 19310 */ 19311 public String getViewName() { 19312 return mViewName; 19313 } 19314 19315 /** 19316 * Interface definition for a callback to be invoked when a hardware key event is 19317 * dispatched to this view. The callback will be invoked before the key event is 19318 * given to the view. This is only useful for hardware keyboards; a software input 19319 * method has no obligation to trigger this listener. 19320 */ 19321 public interface OnKeyListener { 19322 /** 19323 * Called when a hardware key is dispatched to a view. This allows listeners to 19324 * get a chance to respond before the target view. 19325 * <p>Key presses in software keyboards will generally NOT trigger this method, 19326 * although some may elect to do so in some situations. Do not assume a 19327 * software input method has to be key-based; even if it is, it may use key presses 19328 * in a different way than you expect, so there is no way to reliably catch soft 19329 * input key presses. 19330 * 19331 * @param v The view the key has been dispatched to. 19332 * @param keyCode The code for the physical key that was pressed 19333 * @param event The KeyEvent object containing full information about 19334 * the event. 19335 * @return True if the listener has consumed the event, false otherwise. 19336 */ 19337 boolean onKey(View v, int keyCode, KeyEvent event); 19338 } 19339 19340 /** 19341 * Interface definition for a callback to be invoked when a touch event is 19342 * dispatched to this view. The callback will be invoked before the touch 19343 * event is given to the view. 19344 */ 19345 public interface OnTouchListener { 19346 /** 19347 * Called when a touch event is dispatched to a view. This allows listeners to 19348 * get a chance to respond before the target view. 19349 * 19350 * @param v The view the touch event has been dispatched to. 19351 * @param event The MotionEvent object containing full information about 19352 * the event. 19353 * @return True if the listener has consumed the event, false otherwise. 19354 */ 19355 boolean onTouch(View v, MotionEvent event); 19356 } 19357 19358 /** 19359 * Interface definition for a callback to be invoked when a hover event is 19360 * dispatched to this view. The callback will be invoked before the hover 19361 * event is given to the view. 19362 */ 19363 public interface OnHoverListener { 19364 /** 19365 * Called when a hover event is dispatched to a view. This allows listeners to 19366 * get a chance to respond before the target view. 19367 * 19368 * @param v The view the hover event has been dispatched to. 19369 * @param event The MotionEvent object containing full information about 19370 * the event. 19371 * @return True if the listener has consumed the event, false otherwise. 19372 */ 19373 boolean onHover(View v, MotionEvent event); 19374 } 19375 19376 /** 19377 * Interface definition for a callback to be invoked when a generic motion event is 19378 * dispatched to this view. The callback will be invoked before the generic motion 19379 * event is given to the view. 19380 */ 19381 public interface OnGenericMotionListener { 19382 /** 19383 * Called when a generic motion event is dispatched to a view. This allows listeners to 19384 * get a chance to respond before the target view. 19385 * 19386 * @param v The view the generic motion event has been dispatched to. 19387 * @param event The MotionEvent object containing full information about 19388 * the event. 19389 * @return True if the listener has consumed the event, false otherwise. 19390 */ 19391 boolean onGenericMotion(View v, MotionEvent event); 19392 } 19393 19394 /** 19395 * Interface definition for a callback to be invoked when a view has been clicked and held. 19396 */ 19397 public interface OnLongClickListener { 19398 /** 19399 * Called when a view has been clicked and held. 19400 * 19401 * @param v The view that was clicked and held. 19402 * 19403 * @return true if the callback consumed the long click, false otherwise. 19404 */ 19405 boolean onLongClick(View v); 19406 } 19407 19408 /** 19409 * Interface definition for a callback to be invoked when a drag is being dispatched 19410 * to this view. The callback will be invoked before the hosting view's own 19411 * onDrag(event) method. If the listener wants to fall back to the hosting view's 19412 * onDrag(event) behavior, it should return 'false' from this callback. 19413 * 19414 * <div class="special reference"> 19415 * <h3>Developer Guides</h3> 19416 * <p>For a guide to implementing drag and drop features, read the 19417 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 19418 * </div> 19419 */ 19420 public interface OnDragListener { 19421 /** 19422 * Called when a drag event is dispatched to a view. This allows listeners 19423 * to get a chance to override base View behavior. 19424 * 19425 * @param v The View that received the drag event. 19426 * @param event The {@link android.view.DragEvent} object for the drag event. 19427 * @return {@code true} if the drag event was handled successfully, or {@code false} 19428 * if the drag event was not handled. Note that {@code false} will trigger the View 19429 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 19430 */ 19431 boolean onDrag(View v, DragEvent event); 19432 } 19433 19434 /** 19435 * Interface definition for a callback to be invoked when the focus state of 19436 * a view changed. 19437 */ 19438 public interface OnFocusChangeListener { 19439 /** 19440 * Called when the focus state of a view has changed. 19441 * 19442 * @param v The view whose state has changed. 19443 * @param hasFocus The new focus state of v. 19444 */ 19445 void onFocusChange(View v, boolean hasFocus); 19446 } 19447 19448 /** 19449 * Interface definition for a callback to be invoked when a view is clicked. 19450 */ 19451 public interface OnClickListener { 19452 /** 19453 * Called when a view has been clicked. 19454 * 19455 * @param v The view that was clicked. 19456 */ 19457 void onClick(View v); 19458 } 19459 19460 /** 19461 * Interface definition for a callback to be invoked when the context menu 19462 * for this view is being built. 19463 */ 19464 public interface OnCreateContextMenuListener { 19465 /** 19466 * Called when the context menu for this view is being built. It is not 19467 * safe to hold onto the menu after this method returns. 19468 * 19469 * @param menu The context menu that is being built 19470 * @param v The view for which the context menu is being built 19471 * @param menuInfo Extra information about the item for which the 19472 * context menu should be shown. This information will vary 19473 * depending on the class of v. 19474 */ 19475 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 19476 } 19477 19478 /** 19479 * Interface definition for a callback to be invoked when the status bar changes 19480 * visibility. This reports <strong>global</strong> changes to the system UI 19481 * state, not what the application is requesting. 19482 * 19483 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 19484 */ 19485 public interface OnSystemUiVisibilityChangeListener { 19486 /** 19487 * Called when the status bar changes visibility because of a call to 19488 * {@link View#setSystemUiVisibility(int)}. 19489 * 19490 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19491 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 19492 * This tells you the <strong>global</strong> state of these UI visibility 19493 * flags, not what your app is currently applying. 19494 */ 19495 public void onSystemUiVisibilityChange(int visibility); 19496 } 19497 19498 /** 19499 * Interface definition for a callback to be invoked when this view is attached 19500 * or detached from its window. 19501 */ 19502 public interface OnAttachStateChangeListener { 19503 /** 19504 * Called when the view is attached to a window. 19505 * @param v The view that was attached 19506 */ 19507 public void onViewAttachedToWindow(View v); 19508 /** 19509 * Called when the view is detached from a window. 19510 * @param v The view that was detached 19511 */ 19512 public void onViewDetachedFromWindow(View v); 19513 } 19514 19515 /** 19516 * Listener for applying window insets on a view in a custom way. 19517 * 19518 * <p>Apps may choose to implement this interface if they want to apply custom policy 19519 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 19520 * is set, its 19521 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 19522 * method will be called instead of the View's own 19523 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 19524 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 19525 * the View's normal behavior as part of its own.</p> 19526 */ 19527 public interface OnApplyWindowInsetsListener { 19528 /** 19529 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 19530 * on a View, this listener method will be called instead of the view's own 19531 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 19532 * 19533 * @param v The view applying window insets 19534 * @param insets The insets to apply 19535 * @return The insets supplied, minus any insets that were consumed 19536 */ 19537 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 19538 } 19539 19540 private final class UnsetPressedState implements Runnable { 19541 @Override 19542 public void run() { 19543 clearHotspot(R.attr.state_pressed); 19544 setPressed(false); 19545 } 19546 } 19547 19548 /** 19549 * Base class for derived classes that want to save and restore their own 19550 * state in {@link android.view.View#onSaveInstanceState()}. 19551 */ 19552 public static class BaseSavedState extends AbsSavedState { 19553 /** 19554 * Constructor used when reading from a parcel. Reads the state of the superclass. 19555 * 19556 * @param source 19557 */ 19558 public BaseSavedState(Parcel source) { 19559 super(source); 19560 } 19561 19562 /** 19563 * Constructor called by derived classes when creating their SavedState objects 19564 * 19565 * @param superState The state of the superclass of this view 19566 */ 19567 public BaseSavedState(Parcelable superState) { 19568 super(superState); 19569 } 19570 19571 public static final Parcelable.Creator<BaseSavedState> CREATOR = 19572 new Parcelable.Creator<BaseSavedState>() { 19573 public BaseSavedState createFromParcel(Parcel in) { 19574 return new BaseSavedState(in); 19575 } 19576 19577 public BaseSavedState[] newArray(int size) { 19578 return new BaseSavedState[size]; 19579 } 19580 }; 19581 } 19582 19583 /** 19584 * A set of information given to a view when it is attached to its parent 19585 * window. 19586 */ 19587 final static class AttachInfo { 19588 interface Callbacks { 19589 void playSoundEffect(int effectId); 19590 boolean performHapticFeedback(int effectId, boolean always); 19591 } 19592 19593 /** 19594 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 19595 * to a Handler. This class contains the target (View) to invalidate and 19596 * the coordinates of the dirty rectangle. 19597 * 19598 * For performance purposes, this class also implements a pool of up to 19599 * POOL_LIMIT objects that get reused. This reduces memory allocations 19600 * whenever possible. 19601 */ 19602 static class InvalidateInfo { 19603 private static final int POOL_LIMIT = 10; 19604 19605 private static final SynchronizedPool<InvalidateInfo> sPool = 19606 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 19607 19608 View target; 19609 19610 int left; 19611 int top; 19612 int right; 19613 int bottom; 19614 19615 public static InvalidateInfo obtain() { 19616 InvalidateInfo instance = sPool.acquire(); 19617 return (instance != null) ? instance : new InvalidateInfo(); 19618 } 19619 19620 public void recycle() { 19621 target = null; 19622 sPool.release(this); 19623 } 19624 } 19625 19626 final IWindowSession mSession; 19627 19628 final IWindow mWindow; 19629 19630 final IBinder mWindowToken; 19631 19632 final Display mDisplay; 19633 19634 final Callbacks mRootCallbacks; 19635 19636 IWindowId mIWindowId; 19637 WindowId mWindowId; 19638 19639 /** 19640 * The top view of the hierarchy. 19641 */ 19642 View mRootView; 19643 19644 IBinder mPanelParentWindowToken; 19645 19646 boolean mHardwareAccelerated; 19647 boolean mHardwareAccelerationRequested; 19648 HardwareRenderer mHardwareRenderer; 19649 19650 /** 19651 * The state of the display to which the window is attached, as reported 19652 * by {@link Display#getState()}. Note that the display state constants 19653 * declared by {@link Display} do not exactly line up with the screen state 19654 * constants declared by {@link View} (there are more display states than 19655 * screen states). 19656 */ 19657 int mDisplayState = Display.STATE_UNKNOWN; 19658 19659 /** 19660 * Scale factor used by the compatibility mode 19661 */ 19662 float mApplicationScale; 19663 19664 /** 19665 * Indicates whether the application is in compatibility mode 19666 */ 19667 boolean mScalingRequired; 19668 19669 /** 19670 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 19671 */ 19672 boolean mTurnOffWindowResizeAnim; 19673 19674 /** 19675 * Left position of this view's window 19676 */ 19677 int mWindowLeft; 19678 19679 /** 19680 * Top position of this view's window 19681 */ 19682 int mWindowTop; 19683 19684 /** 19685 * Indicates whether views need to use 32-bit drawing caches 19686 */ 19687 boolean mUse32BitDrawingCache; 19688 19689 /** 19690 * For windows that are full-screen but using insets to layout inside 19691 * of the screen areas, these are the current insets to appear inside 19692 * the overscan area of the display. 19693 */ 19694 final Rect mOverscanInsets = new Rect(); 19695 19696 /** 19697 * For windows that are full-screen but using insets to layout inside 19698 * of the screen decorations, these are the current insets for the 19699 * content of the window. 19700 */ 19701 final Rect mContentInsets = new Rect(); 19702 19703 /** 19704 * For windows that are full-screen but using insets to layout inside 19705 * of the screen decorations, these are the current insets for the 19706 * actual visible parts of the window. 19707 */ 19708 final Rect mVisibleInsets = new Rect(); 19709 19710 /** 19711 * The internal insets given by this window. This value is 19712 * supplied by the client (through 19713 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 19714 * be given to the window manager when changed to be used in laying 19715 * out windows behind it. 19716 */ 19717 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 19718 = new ViewTreeObserver.InternalInsetsInfo(); 19719 19720 /** 19721 * Set to true when mGivenInternalInsets is non-empty. 19722 */ 19723 boolean mHasNonEmptyGivenInternalInsets; 19724 19725 /** 19726 * All views in the window's hierarchy that serve as scroll containers, 19727 * used to determine if the window can be resized or must be panned 19728 * to adjust for a soft input area. 19729 */ 19730 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 19731 19732 final KeyEvent.DispatcherState mKeyDispatchState 19733 = new KeyEvent.DispatcherState(); 19734 19735 /** 19736 * Indicates whether the view's window currently has the focus. 19737 */ 19738 boolean mHasWindowFocus; 19739 19740 /** 19741 * The current visibility of the window. 19742 */ 19743 int mWindowVisibility; 19744 19745 /** 19746 * Indicates the time at which drawing started to occur. 19747 */ 19748 long mDrawingTime; 19749 19750 /** 19751 * Indicates whether or not ignoring the DIRTY_MASK flags. 19752 */ 19753 boolean mIgnoreDirtyState; 19754 19755 /** 19756 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 19757 * to avoid clearing that flag prematurely. 19758 */ 19759 boolean mSetIgnoreDirtyState = false; 19760 19761 /** 19762 * Indicates whether the view's window is currently in touch mode. 19763 */ 19764 boolean mInTouchMode; 19765 19766 /** 19767 * Indicates whether the view has requested unbuffered input dispatching for the current 19768 * event stream. 19769 */ 19770 boolean mUnbufferedDispatchRequested; 19771 19772 /** 19773 * Indicates that ViewAncestor should trigger a global layout change 19774 * the next time it performs a traversal 19775 */ 19776 boolean mRecomputeGlobalAttributes; 19777 19778 /** 19779 * Always report new attributes at next traversal. 19780 */ 19781 boolean mForceReportNewAttributes; 19782 19783 /** 19784 * Set during a traveral if any views want to keep the screen on. 19785 */ 19786 boolean mKeepScreenOn; 19787 19788 /** 19789 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 19790 */ 19791 int mSystemUiVisibility; 19792 19793 /** 19794 * Hack to force certain system UI visibility flags to be cleared. 19795 */ 19796 int mDisabledSystemUiVisibility; 19797 19798 /** 19799 * Last global system UI visibility reported by the window manager. 19800 */ 19801 int mGlobalSystemUiVisibility; 19802 19803 /** 19804 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 19805 * attached. 19806 */ 19807 boolean mHasSystemUiListeners; 19808 19809 /** 19810 * Set if the window has requested to extend into the overscan region 19811 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 19812 */ 19813 boolean mOverscanRequested; 19814 19815 /** 19816 * Set if the visibility of any views has changed. 19817 */ 19818 boolean mViewVisibilityChanged; 19819 19820 /** 19821 * Set to true if a view has been scrolled. 19822 */ 19823 boolean mViewScrollChanged; 19824 19825 /** 19826 * Global to the view hierarchy used as a temporary for dealing with 19827 * x/y points in the transparent region computations. 19828 */ 19829 final int[] mTransparentLocation = new int[2]; 19830 19831 /** 19832 * Global to the view hierarchy used as a temporary for dealing with 19833 * x/y points in the ViewGroup.invalidateChild implementation. 19834 */ 19835 final int[] mInvalidateChildLocation = new int[2]; 19836 19837 19838 /** 19839 * Global to the view hierarchy used as a temporary for dealing with 19840 * x/y location when view is transformed. 19841 */ 19842 final float[] mTmpTransformLocation = new float[2]; 19843 19844 /** 19845 * The view tree observer used to dispatch global events like 19846 * layout, pre-draw, touch mode change, etc. 19847 */ 19848 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 19849 19850 /** 19851 * A Canvas used by the view hierarchy to perform bitmap caching. 19852 */ 19853 Canvas mCanvas; 19854 19855 /** 19856 * The view root impl. 19857 */ 19858 final ViewRootImpl mViewRootImpl; 19859 19860 /** 19861 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 19862 * handler can be used to pump events in the UI events queue. 19863 */ 19864 final Handler mHandler; 19865 19866 /** 19867 * Temporary for use in computing invalidate rectangles while 19868 * calling up the hierarchy. 19869 */ 19870 final Rect mTmpInvalRect = new Rect(); 19871 19872 /** 19873 * Temporary for use in computing hit areas with transformed views 19874 */ 19875 final RectF mTmpTransformRect = new RectF(); 19876 19877 /** 19878 * Temporary for use in transforming invalidation rect 19879 */ 19880 final Matrix mTmpMatrix = new Matrix(); 19881 19882 /** 19883 * Temporary for use in transforming invalidation rect 19884 */ 19885 final Transformation mTmpTransformation = new Transformation(); 19886 19887 /** 19888 * Temporary list for use in collecting focusable descendents of a view. 19889 */ 19890 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 19891 19892 /** 19893 * The id of the window for accessibility purposes. 19894 */ 19895 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 19896 19897 /** 19898 * Flags related to accessibility processing. 19899 * 19900 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 19901 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 19902 */ 19903 int mAccessibilityFetchFlags; 19904 19905 /** 19906 * The drawable for highlighting accessibility focus. 19907 */ 19908 Drawable mAccessibilityFocusDrawable; 19909 19910 /** 19911 * Show where the margins, bounds and layout bounds are for each view. 19912 */ 19913 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 19914 19915 /** 19916 * Point used to compute visible regions. 19917 */ 19918 final Point mPoint = new Point(); 19919 19920 /** 19921 * Used to track which View originated a requestLayout() call, used when 19922 * requestLayout() is called during layout. 19923 */ 19924 View mViewRequestingLayout; 19925 19926 /** 19927 * Creates a new set of attachment information with the specified 19928 * events handler and thread. 19929 * 19930 * @param handler the events handler the view must use 19931 */ 19932 AttachInfo(IWindowSession session, IWindow window, Display display, 19933 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 19934 mSession = session; 19935 mWindow = window; 19936 mWindowToken = window.asBinder(); 19937 mDisplay = display; 19938 mViewRootImpl = viewRootImpl; 19939 mHandler = handler; 19940 mRootCallbacks = effectPlayer; 19941 } 19942 } 19943 19944 /** 19945 * <p>ScrollabilityCache holds various fields used by a View when scrolling 19946 * is supported. This avoids keeping too many unused fields in most 19947 * instances of View.</p> 19948 */ 19949 private static class ScrollabilityCache implements Runnable { 19950 19951 /** 19952 * Scrollbars are not visible 19953 */ 19954 public static final int OFF = 0; 19955 19956 /** 19957 * Scrollbars are visible 19958 */ 19959 public static final int ON = 1; 19960 19961 /** 19962 * Scrollbars are fading away 19963 */ 19964 public static final int FADING = 2; 19965 19966 public boolean fadeScrollBars; 19967 19968 public int fadingEdgeLength; 19969 public int scrollBarDefaultDelayBeforeFade; 19970 public int scrollBarFadeDuration; 19971 19972 public int scrollBarSize; 19973 public ScrollBarDrawable scrollBar; 19974 public float[] interpolatorValues; 19975 public View host; 19976 19977 public final Paint paint; 19978 public final Matrix matrix; 19979 public Shader shader; 19980 19981 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 19982 19983 private static final float[] OPAQUE = { 255 }; 19984 private static final float[] TRANSPARENT = { 0.0f }; 19985 19986 /** 19987 * When fading should start. This time moves into the future every time 19988 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 19989 */ 19990 public long fadeStartTime; 19991 19992 19993 /** 19994 * The current state of the scrollbars: ON, OFF, or FADING 19995 */ 19996 public int state = OFF; 19997 19998 private int mLastColor; 19999 20000 public ScrollabilityCache(ViewConfiguration configuration, View host) { 20001 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 20002 scrollBarSize = configuration.getScaledScrollBarSize(); 20003 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 20004 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 20005 20006 paint = new Paint(); 20007 matrix = new Matrix(); 20008 // use use a height of 1, and then wack the matrix each time we 20009 // actually use it. 20010 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20011 paint.setShader(shader); 20012 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20013 20014 this.host = host; 20015 } 20016 20017 public void setFadeColor(int color) { 20018 if (color != mLastColor) { 20019 mLastColor = color; 20020 20021 if (color != 0) { 20022 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 20023 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 20024 paint.setShader(shader); 20025 // Restore the default transfer mode (src_over) 20026 paint.setXfermode(null); 20027 } else { 20028 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20029 paint.setShader(shader); 20030 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20031 } 20032 } 20033 } 20034 20035 public void run() { 20036 long now = AnimationUtils.currentAnimationTimeMillis(); 20037 if (now >= fadeStartTime) { 20038 20039 // the animation fades the scrollbars out by changing 20040 // the opacity (alpha) from fully opaque to fully 20041 // transparent 20042 int nextFrame = (int) now; 20043 int framesCount = 0; 20044 20045 Interpolator interpolator = scrollBarInterpolator; 20046 20047 // Start opaque 20048 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 20049 20050 // End transparent 20051 nextFrame += scrollBarFadeDuration; 20052 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 20053 20054 state = FADING; 20055 20056 // Kick off the fade animation 20057 host.invalidate(true); 20058 } 20059 } 20060 } 20061 20062 /** 20063 * Resuable callback for sending 20064 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 20065 */ 20066 private class SendViewScrolledAccessibilityEvent implements Runnable { 20067 public volatile boolean mIsPending; 20068 20069 public void run() { 20070 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 20071 mIsPending = false; 20072 } 20073 } 20074 20075 /** 20076 * <p> 20077 * This class represents a delegate that can be registered in a {@link View} 20078 * to enhance accessibility support via composition rather via inheritance. 20079 * It is specifically targeted to widget developers that extend basic View 20080 * classes i.e. classes in package android.view, that would like their 20081 * applications to be backwards compatible. 20082 * </p> 20083 * <div class="special reference"> 20084 * <h3>Developer Guides</h3> 20085 * <p>For more information about making applications accessible, read the 20086 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 20087 * developer guide.</p> 20088 * </div> 20089 * <p> 20090 * A scenario in which a developer would like to use an accessibility delegate 20091 * is overriding a method introduced in a later API version then the minimal API 20092 * version supported by the application. For example, the method 20093 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 20094 * in API version 4 when the accessibility APIs were first introduced. If a 20095 * developer would like his application to run on API version 4 devices (assuming 20096 * all other APIs used by the application are version 4 or lower) and take advantage 20097 * of this method, instead of overriding the method which would break the application's 20098 * backwards compatibility, he can override the corresponding method in this 20099 * delegate and register the delegate in the target View if the API version of 20100 * the system is high enough i.e. the API version is same or higher to the API 20101 * version that introduced 20102 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 20103 * </p> 20104 * <p> 20105 * Here is an example implementation: 20106 * </p> 20107 * <code><pre><p> 20108 * if (Build.VERSION.SDK_INT >= 14) { 20109 * // If the API version is equal of higher than the version in 20110 * // which onInitializeAccessibilityNodeInfo was introduced we 20111 * // register a delegate with a customized implementation. 20112 * View view = findViewById(R.id.view_id); 20113 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20114 * public void onInitializeAccessibilityNodeInfo(View host, 20115 * AccessibilityNodeInfo info) { 20116 * // Let the default implementation populate the info. 20117 * super.onInitializeAccessibilityNodeInfo(host, info); 20118 * // Set some other information. 20119 * info.setEnabled(host.isEnabled()); 20120 * } 20121 * }); 20122 * } 20123 * </code></pre></p> 20124 * <p> 20125 * This delegate contains methods that correspond to the accessibility methods 20126 * in View. If a delegate has been specified the implementation in View hands 20127 * off handling to the corresponding method in this delegate. The default 20128 * implementation the delegate methods behaves exactly as the corresponding 20129 * method in View for the case of no accessibility delegate been set. Hence, 20130 * to customize the behavior of a View method, clients can override only the 20131 * corresponding delegate method without altering the behavior of the rest 20132 * accessibility related methods of the host view. 20133 * </p> 20134 */ 20135 public static class AccessibilityDelegate { 20136 20137 /** 20138 * Sends an accessibility event of the given type. If accessibility is not 20139 * enabled this method has no effect. 20140 * <p> 20141 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20142 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20143 * been set. 20144 * </p> 20145 * 20146 * @param host The View hosting the delegate. 20147 * @param eventType The type of the event to send. 20148 * 20149 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20150 */ 20151 public void sendAccessibilityEvent(View host, int eventType) { 20152 host.sendAccessibilityEventInternal(eventType); 20153 } 20154 20155 /** 20156 * Performs the specified accessibility action on the view. For 20157 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20158 * <p> 20159 * The default implementation behaves as 20160 * {@link View#performAccessibilityAction(int, Bundle) 20161 * View#performAccessibilityAction(int, Bundle)} for the case of 20162 * no accessibility delegate been set. 20163 * </p> 20164 * 20165 * @param action The action to perform. 20166 * @return Whether the action was performed. 20167 * 20168 * @see View#performAccessibilityAction(int, Bundle) 20169 * View#performAccessibilityAction(int, Bundle) 20170 */ 20171 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20172 return host.performAccessibilityActionInternal(action, args); 20173 } 20174 20175 /** 20176 * Sends an accessibility event. This method behaves exactly as 20177 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20178 * empty {@link AccessibilityEvent} and does not perform a check whether 20179 * accessibility is enabled. 20180 * <p> 20181 * The default implementation behaves as 20182 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20183 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20184 * the case of no accessibility delegate been set. 20185 * </p> 20186 * 20187 * @param host The View hosting the delegate. 20188 * @param event The event to send. 20189 * 20190 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20191 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20192 */ 20193 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20194 host.sendAccessibilityEventUncheckedInternal(event); 20195 } 20196 20197 /** 20198 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20199 * to its children for adding their text content to the event. 20200 * <p> 20201 * The default implementation behaves as 20202 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20203 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20204 * the case of no accessibility delegate been set. 20205 * </p> 20206 * 20207 * @param host The View hosting the delegate. 20208 * @param event The event. 20209 * @return True if the event population was completed. 20210 * 20211 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20212 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20213 */ 20214 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20215 return host.dispatchPopulateAccessibilityEventInternal(event); 20216 } 20217 20218 /** 20219 * Gives a chance to the host View to populate the accessibility event with its 20220 * text content. 20221 * <p> 20222 * The default implementation behaves as 20223 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20224 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20225 * the case of no accessibility delegate been set. 20226 * </p> 20227 * 20228 * @param host The View hosting the delegate. 20229 * @param event The accessibility event which to populate. 20230 * 20231 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20232 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20233 */ 20234 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20235 host.onPopulateAccessibilityEventInternal(event); 20236 } 20237 20238 /** 20239 * Initializes an {@link AccessibilityEvent} with information about the 20240 * the host View which is the event source. 20241 * <p> 20242 * The default implementation behaves as 20243 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20244 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20245 * the case of no accessibility delegate been set. 20246 * </p> 20247 * 20248 * @param host The View hosting the delegate. 20249 * @param event The event to initialize. 20250 * 20251 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 20252 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 20253 */ 20254 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 20255 host.onInitializeAccessibilityEventInternal(event); 20256 } 20257 20258 /** 20259 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 20260 * <p> 20261 * The default implementation behaves as 20262 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20263 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 20264 * the case of no accessibility delegate been set. 20265 * </p> 20266 * 20267 * @param host The View hosting the delegate. 20268 * @param info The instance to initialize. 20269 * 20270 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20271 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20272 */ 20273 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 20274 host.onInitializeAccessibilityNodeInfoInternal(info); 20275 } 20276 20277 /** 20278 * Called when a child of the host View has requested sending an 20279 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 20280 * to augment the event. 20281 * <p> 20282 * The default implementation behaves as 20283 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20284 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 20285 * the case of no accessibility delegate been set. 20286 * </p> 20287 * 20288 * @param host The View hosting the delegate. 20289 * @param child The child which requests sending the event. 20290 * @param event The event to be sent. 20291 * @return True if the event should be sent 20292 * 20293 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20294 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20295 */ 20296 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 20297 AccessibilityEvent event) { 20298 return host.onRequestSendAccessibilityEventInternal(child, event); 20299 } 20300 20301 /** 20302 * Gets the provider for managing a virtual view hierarchy rooted at this View 20303 * and reported to {@link android.accessibilityservice.AccessibilityService}s 20304 * that explore the window content. 20305 * <p> 20306 * The default implementation behaves as 20307 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 20308 * the case of no accessibility delegate been set. 20309 * </p> 20310 * 20311 * @return The provider. 20312 * 20313 * @see AccessibilityNodeProvider 20314 */ 20315 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 20316 return null; 20317 } 20318 20319 /** 20320 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 20321 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 20322 * This method is responsible for obtaining an accessibility node info from a 20323 * pool of reusable instances and calling 20324 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 20325 * view to initialize the former. 20326 * <p> 20327 * <strong>Note:</strong> The client is responsible for recycling the obtained 20328 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 20329 * creation. 20330 * </p> 20331 * <p> 20332 * The default implementation behaves as 20333 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 20334 * the case of no accessibility delegate been set. 20335 * </p> 20336 * @return A populated {@link AccessibilityNodeInfo}. 20337 * 20338 * @see AccessibilityNodeInfo 20339 * 20340 * @hide 20341 */ 20342 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 20343 return host.createAccessibilityNodeInfoInternal(); 20344 } 20345 } 20346 20347 private class MatchIdPredicate implements Predicate<View> { 20348 public int mId; 20349 20350 @Override 20351 public boolean apply(View view) { 20352 return (view.mID == mId); 20353 } 20354 } 20355 20356 private class MatchLabelForPredicate implements Predicate<View> { 20357 private int mLabeledId; 20358 20359 @Override 20360 public boolean apply(View view) { 20361 return (view.mLabelForId == mLabeledId); 20362 } 20363 } 20364 20365 private class SendViewStateChangedAccessibilityEvent implements Runnable { 20366 private int mChangeTypes = 0; 20367 private boolean mPosted; 20368 private boolean mPostedWithDelay; 20369 private long mLastEventTimeMillis; 20370 20371 @Override 20372 public void run() { 20373 mPosted = false; 20374 mPostedWithDelay = false; 20375 mLastEventTimeMillis = SystemClock.uptimeMillis(); 20376 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 20377 final AccessibilityEvent event = AccessibilityEvent.obtain(); 20378 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 20379 event.setContentChangeTypes(mChangeTypes); 20380 sendAccessibilityEventUnchecked(event); 20381 } 20382 mChangeTypes = 0; 20383 } 20384 20385 public void runOrPost(int changeType) { 20386 mChangeTypes |= changeType; 20387 20388 // If this is a live region or the child of a live region, collect 20389 // all events from this frame and send them on the next frame. 20390 if (inLiveRegion()) { 20391 // If we're already posted with a delay, remove that. 20392 if (mPostedWithDelay) { 20393 removeCallbacks(this); 20394 mPostedWithDelay = false; 20395 } 20396 // Only post if we're not already posted. 20397 if (!mPosted) { 20398 post(this); 20399 mPosted = true; 20400 } 20401 return; 20402 } 20403 20404 if (mPosted) { 20405 return; 20406 } 20407 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 20408 final long minEventIntevalMillis = 20409 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 20410 if (timeSinceLastMillis >= minEventIntevalMillis) { 20411 removeCallbacks(this); 20412 run(); 20413 } else { 20414 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 20415 mPosted = true; 20416 mPostedWithDelay = true; 20417 } 20418 } 20419 } 20420 20421 private boolean inLiveRegion() { 20422 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20423 return true; 20424 } 20425 20426 ViewParent parent = getParent(); 20427 while (parent instanceof View) { 20428 if (((View) parent).getAccessibilityLiveRegion() 20429 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20430 return true; 20431 } 20432 parent = parent.getParent(); 20433 } 20434 20435 return false; 20436 } 20437 20438 /** 20439 * Dump all private flags in readable format, useful for documentation and 20440 * sanity checking. 20441 */ 20442 private static void dumpFlags() { 20443 final HashMap<String, String> found = Maps.newHashMap(); 20444 try { 20445 for (Field field : View.class.getDeclaredFields()) { 20446 final int modifiers = field.getModifiers(); 20447 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 20448 if (field.getType().equals(int.class)) { 20449 final int value = field.getInt(null); 20450 dumpFlag(found, field.getName(), value); 20451 } else if (field.getType().equals(int[].class)) { 20452 final int[] values = (int[]) field.get(null); 20453 for (int i = 0; i < values.length; i++) { 20454 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 20455 } 20456 } 20457 } 20458 } 20459 } catch (IllegalAccessException e) { 20460 throw new RuntimeException(e); 20461 } 20462 20463 final ArrayList<String> keys = Lists.newArrayList(); 20464 keys.addAll(found.keySet()); 20465 Collections.sort(keys); 20466 for (String key : keys) { 20467 Log.d(VIEW_LOG_TAG, found.get(key)); 20468 } 20469 } 20470 20471 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 20472 // Sort flags by prefix, then by bits, always keeping unique keys 20473 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 20474 final int prefix = name.indexOf('_'); 20475 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 20476 final String output = bits + " " + name; 20477 found.put(key, output); 20478 } 20479} 20480