View.java revision 84a4c887a07c1c2939443f4e0587d7f1ac109e4b
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 onFocusChanged(true, direction, previouslyFocusedRect); 4778 manageFocusHotspot(true, oldFocus); 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) { 4793 return; 4794 } 4795 4796 final Rect r = new Rect(); 4797 if (!focused && v != null) { 4798 v.getBoundsOnScreen(r); 4799 final int[] location = new int[2]; 4800 getLocationOnScreen(location); 4801 r.offset(-location[0], -location[1]); 4802 } else { 4803 r.set(0, 0, mRight - mLeft, mBottom - mTop); 4804 } 4805 4806 final float x = r.exactCenterX(); 4807 final float y = r.exactCenterY(); 4808 mBackground.setHotspot(x, y); 4809 } 4810 4811 /** 4812 * Request that a rectangle of this view be visible on the screen, 4813 * scrolling if necessary just enough. 4814 * 4815 * <p>A View should call this if it maintains some notion of which part 4816 * of its content is interesting. For example, a text editing view 4817 * should call this when its cursor moves. 4818 * 4819 * @param rectangle The rectangle. 4820 * @return Whether any parent scrolled. 4821 */ 4822 public boolean requestRectangleOnScreen(Rect rectangle) { 4823 return requestRectangleOnScreen(rectangle, false); 4824 } 4825 4826 /** 4827 * Request that a rectangle of this view be visible on the screen, 4828 * scrolling if necessary just enough. 4829 * 4830 * <p>A View should call this if it maintains some notion of which part 4831 * of its content is interesting. For example, a text editing view 4832 * should call this when its cursor moves. 4833 * 4834 * <p>When <code>immediate</code> is set to true, scrolling will not be 4835 * animated. 4836 * 4837 * @param rectangle The rectangle. 4838 * @param immediate True to forbid animated scrolling, false otherwise 4839 * @return Whether any parent scrolled. 4840 */ 4841 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4842 if (mParent == null) { 4843 return false; 4844 } 4845 4846 View child = this; 4847 4848 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4849 position.set(rectangle); 4850 4851 ViewParent parent = mParent; 4852 boolean scrolled = false; 4853 while (parent != null) { 4854 rectangle.set((int) position.left, (int) position.top, 4855 (int) position.right, (int) position.bottom); 4856 4857 scrolled |= parent.requestChildRectangleOnScreen(child, 4858 rectangle, immediate); 4859 4860 if (!child.hasIdentityMatrix()) { 4861 child.getMatrix().mapRect(position); 4862 } 4863 4864 position.offset(child.mLeft, child.mTop); 4865 4866 if (!(parent instanceof View)) { 4867 break; 4868 } 4869 4870 View parentView = (View) parent; 4871 4872 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4873 4874 child = parentView; 4875 parent = child.getParent(); 4876 } 4877 4878 return scrolled; 4879 } 4880 4881 /** 4882 * Called when this view wants to give up focus. If focus is cleared 4883 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4884 * <p> 4885 * <strong>Note:</strong> When a View clears focus the framework is trying 4886 * to give focus to the first focusable View from the top. Hence, if this 4887 * View is the first from the top that can take focus, then all callbacks 4888 * related to clearing focus will be invoked after wich the framework will 4889 * give focus to this view. 4890 * </p> 4891 */ 4892 public void clearFocus() { 4893 if (DBG) { 4894 System.out.println(this + " clearFocus()"); 4895 } 4896 4897 clearFocusInternal(null, true, true); 4898 } 4899 4900 /** 4901 * Clears focus from the view, optionally propagating the change up through 4902 * the parent hierarchy and requesting that the root view place new focus. 4903 * 4904 * @param propagate whether to propagate the change up through the parent 4905 * hierarchy 4906 * @param refocus when propagate is true, specifies whether to request the 4907 * root view place new focus 4908 */ 4909 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 4910 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4911 mPrivateFlags &= ~PFLAG_FOCUSED; 4912 4913 if (propagate && mParent != null) { 4914 mParent.clearChildFocus(this); 4915 } 4916 4917 onFocusChanged(false, 0, null); 4918 4919 manageFocusHotspot(false, focused); 4920 refreshDrawableState(); 4921 4922 if (propagate && (!refocus || !rootViewRequestFocus())) { 4923 notifyGlobalFocusCleared(this); 4924 } 4925 } 4926 } 4927 4928 void notifyGlobalFocusCleared(View oldFocus) { 4929 if (oldFocus != null && mAttachInfo != null) { 4930 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 4931 } 4932 } 4933 4934 boolean rootViewRequestFocus() { 4935 final View root = getRootView(); 4936 return root != null && root.requestFocus(); 4937 } 4938 4939 /** 4940 * Called internally by the view system when a new view is getting focus. 4941 * This is what clears the old focus. 4942 * <p> 4943 * <b>NOTE:</b> The parent view's focused child must be updated manually 4944 * after calling this method. Otherwise, the view hierarchy may be left in 4945 * an inconstent state. 4946 */ 4947 void unFocus(View focused) { 4948 if (DBG) { 4949 System.out.println(this + " unFocus()"); 4950 } 4951 4952 clearFocusInternal(focused, false, false); 4953 } 4954 4955 /** 4956 * Returns true if this view has focus iteself, or is the ancestor of the 4957 * view that has focus. 4958 * 4959 * @return True if this view has or contains focus, false otherwise. 4960 */ 4961 @ViewDebug.ExportedProperty(category = "focus") 4962 public boolean hasFocus() { 4963 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4964 } 4965 4966 /** 4967 * Returns true if this view is focusable or if it contains a reachable View 4968 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4969 * is a View whose parents do not block descendants focus. 4970 * 4971 * Only {@link #VISIBLE} views are considered focusable. 4972 * 4973 * @return True if the view is focusable or if the view contains a focusable 4974 * View, false otherwise. 4975 * 4976 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4977 */ 4978 public boolean hasFocusable() { 4979 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4980 } 4981 4982 /** 4983 * Called by the view system when the focus state of this view changes. 4984 * When the focus change event is caused by directional navigation, direction 4985 * and previouslyFocusedRect provide insight into where the focus is coming from. 4986 * When overriding, be sure to call up through to the super class so that 4987 * the standard focus handling will occur. 4988 * 4989 * @param gainFocus True if the View has focus; false otherwise. 4990 * @param direction The direction focus has moved when requestFocus() 4991 * is called to give this view focus. Values are 4992 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4993 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4994 * It may not always apply, in which case use the default. 4995 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4996 * system, of the previously focused view. If applicable, this will be 4997 * passed in as finer grained information about where the focus is coming 4998 * from (in addition to direction). Will be <code>null</code> otherwise. 4999 */ 5000 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5001 @Nullable Rect previouslyFocusedRect) { 5002 if (gainFocus) { 5003 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5004 } else { 5005 notifyViewAccessibilityStateChangedIfNeeded( 5006 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5007 } 5008 5009 InputMethodManager imm = InputMethodManager.peekInstance(); 5010 if (!gainFocus) { 5011 if (isPressed()) { 5012 setPressed(false); 5013 } 5014 if (imm != null && mAttachInfo != null 5015 && mAttachInfo.mHasWindowFocus) { 5016 imm.focusOut(this); 5017 } 5018 onFocusLost(); 5019 } else if (imm != null && mAttachInfo != null 5020 && mAttachInfo.mHasWindowFocus) { 5021 imm.focusIn(this); 5022 } 5023 5024 invalidate(true); 5025 ListenerInfo li = mListenerInfo; 5026 if (li != null && li.mOnFocusChangeListener != null) { 5027 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5028 } 5029 5030 if (mAttachInfo != null) { 5031 mAttachInfo.mKeyDispatchState.reset(this); 5032 } 5033 } 5034 5035 /** 5036 * Sends an accessibility event of the given type. If accessibility is 5037 * not enabled this method has no effect. The default implementation calls 5038 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5039 * to populate information about the event source (this View), then calls 5040 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5041 * populate the text content of the event source including its descendants, 5042 * and last calls 5043 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5044 * on its parent to resuest sending of the event to interested parties. 5045 * <p> 5046 * If an {@link AccessibilityDelegate} has been specified via calling 5047 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5048 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5049 * responsible for handling this call. 5050 * </p> 5051 * 5052 * @param eventType The type of the event to send, as defined by several types from 5053 * {@link android.view.accessibility.AccessibilityEvent}, such as 5054 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5055 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5056 * 5057 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5058 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5059 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5060 * @see AccessibilityDelegate 5061 */ 5062 public void sendAccessibilityEvent(int eventType) { 5063 if (mAccessibilityDelegate != null) { 5064 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5065 } else { 5066 sendAccessibilityEventInternal(eventType); 5067 } 5068 } 5069 5070 /** 5071 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5072 * {@link AccessibilityEvent} to make an announcement which is related to some 5073 * sort of a context change for which none of the events representing UI transitions 5074 * is a good fit. For example, announcing a new page in a book. If accessibility 5075 * is not enabled this method does nothing. 5076 * 5077 * @param text The announcement text. 5078 */ 5079 public void announceForAccessibility(CharSequence text) { 5080 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5081 AccessibilityEvent event = AccessibilityEvent.obtain( 5082 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5083 onInitializeAccessibilityEvent(event); 5084 event.getText().add(text); 5085 event.setContentDescription(null); 5086 mParent.requestSendAccessibilityEvent(this, event); 5087 } 5088 } 5089 5090 /** 5091 * @see #sendAccessibilityEvent(int) 5092 * 5093 * Note: Called from the default {@link AccessibilityDelegate}. 5094 */ 5095 void sendAccessibilityEventInternal(int eventType) { 5096 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5097 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5098 } 5099 } 5100 5101 /** 5102 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5103 * takes as an argument an empty {@link AccessibilityEvent} and does not 5104 * perform a check whether accessibility is enabled. 5105 * <p> 5106 * If an {@link AccessibilityDelegate} has been specified via calling 5107 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5108 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5109 * is responsible for handling this call. 5110 * </p> 5111 * 5112 * @param event The event to send. 5113 * 5114 * @see #sendAccessibilityEvent(int) 5115 */ 5116 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5117 if (mAccessibilityDelegate != null) { 5118 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5119 } else { 5120 sendAccessibilityEventUncheckedInternal(event); 5121 } 5122 } 5123 5124 /** 5125 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5126 * 5127 * Note: Called from the default {@link AccessibilityDelegate}. 5128 */ 5129 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5130 if (!isShown()) { 5131 return; 5132 } 5133 onInitializeAccessibilityEvent(event); 5134 // Only a subset of accessibility events populates text content. 5135 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5136 dispatchPopulateAccessibilityEvent(event); 5137 } 5138 // In the beginning we called #isShown(), so we know that getParent() is not null. 5139 getParent().requestSendAccessibilityEvent(this, event); 5140 } 5141 5142 /** 5143 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5144 * to its children for adding their text content to the event. Note that the 5145 * event text is populated in a separate dispatch path since we add to the 5146 * event not only the text of the source but also the text of all its descendants. 5147 * A typical implementation will call 5148 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5149 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5150 * on each child. Override this method if custom population of the event text 5151 * content is required. 5152 * <p> 5153 * If an {@link AccessibilityDelegate} has been specified via calling 5154 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5155 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5156 * is responsible for handling this call. 5157 * </p> 5158 * <p> 5159 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5160 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5161 * </p> 5162 * 5163 * @param event The event. 5164 * 5165 * @return True if the event population was completed. 5166 */ 5167 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5168 if (mAccessibilityDelegate != null) { 5169 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5170 } else { 5171 return dispatchPopulateAccessibilityEventInternal(event); 5172 } 5173 } 5174 5175 /** 5176 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5177 * 5178 * Note: Called from the default {@link AccessibilityDelegate}. 5179 */ 5180 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5181 onPopulateAccessibilityEvent(event); 5182 return false; 5183 } 5184 5185 /** 5186 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5187 * giving a chance to this View to populate the accessibility event with its 5188 * text content. While this method is free to modify event 5189 * attributes other than text content, doing so should normally be performed in 5190 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5191 * <p> 5192 * Example: Adding formatted date string to an accessibility event in addition 5193 * to the text added by the super implementation: 5194 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5195 * super.onPopulateAccessibilityEvent(event); 5196 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5197 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5198 * mCurrentDate.getTimeInMillis(), flags); 5199 * event.getText().add(selectedDateUtterance); 5200 * }</pre> 5201 * <p> 5202 * If an {@link AccessibilityDelegate} has been specified via calling 5203 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5204 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5205 * is responsible for handling this call. 5206 * </p> 5207 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5208 * information to the event, in case the default implementation has basic information to add. 5209 * </p> 5210 * 5211 * @param event The accessibility event which to populate. 5212 * 5213 * @see #sendAccessibilityEvent(int) 5214 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5215 */ 5216 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5217 if (mAccessibilityDelegate != null) { 5218 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5219 } else { 5220 onPopulateAccessibilityEventInternal(event); 5221 } 5222 } 5223 5224 /** 5225 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5226 * 5227 * Note: Called from the default {@link AccessibilityDelegate}. 5228 */ 5229 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5230 } 5231 5232 /** 5233 * Initializes an {@link AccessibilityEvent} with information about 5234 * this View which is the event source. In other words, the source of 5235 * an accessibility event is the view whose state change triggered firing 5236 * the event. 5237 * <p> 5238 * Example: Setting the password property of an event in addition 5239 * to properties set by the super implementation: 5240 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5241 * super.onInitializeAccessibilityEvent(event); 5242 * event.setPassword(true); 5243 * }</pre> 5244 * <p> 5245 * If an {@link AccessibilityDelegate} has been specified via calling 5246 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5247 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5248 * is responsible for handling this call. 5249 * </p> 5250 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5251 * information to the event, in case the default implementation has basic information to add. 5252 * </p> 5253 * @param event The event to initialize. 5254 * 5255 * @see #sendAccessibilityEvent(int) 5256 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5257 */ 5258 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5259 if (mAccessibilityDelegate != null) { 5260 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5261 } else { 5262 onInitializeAccessibilityEventInternal(event); 5263 } 5264 } 5265 5266 /** 5267 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5268 * 5269 * Note: Called from the default {@link AccessibilityDelegate}. 5270 */ 5271 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5272 event.setSource(this); 5273 event.setClassName(View.class.getName()); 5274 event.setPackageName(getContext().getPackageName()); 5275 event.setEnabled(isEnabled()); 5276 event.setContentDescription(mContentDescription); 5277 5278 switch (event.getEventType()) { 5279 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5280 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5281 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5282 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5283 event.setItemCount(focusablesTempList.size()); 5284 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5285 if (mAttachInfo != null) { 5286 focusablesTempList.clear(); 5287 } 5288 } break; 5289 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5290 CharSequence text = getIterableTextForAccessibility(); 5291 if (text != null && text.length() > 0) { 5292 event.setFromIndex(getAccessibilitySelectionStart()); 5293 event.setToIndex(getAccessibilitySelectionEnd()); 5294 event.setItemCount(text.length()); 5295 } 5296 } break; 5297 } 5298 } 5299 5300 /** 5301 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5302 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5303 * This method is responsible for obtaining an accessibility node info from a 5304 * pool of reusable instances and calling 5305 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5306 * initialize the former. 5307 * <p> 5308 * Note: The client is responsible for recycling the obtained instance by calling 5309 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5310 * </p> 5311 * 5312 * @return A populated {@link AccessibilityNodeInfo}. 5313 * 5314 * @see AccessibilityNodeInfo 5315 */ 5316 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5317 if (mAccessibilityDelegate != null) { 5318 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5319 } else { 5320 return createAccessibilityNodeInfoInternal(); 5321 } 5322 } 5323 5324 /** 5325 * @see #createAccessibilityNodeInfo() 5326 */ 5327 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5328 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5329 if (provider != null) { 5330 return provider.createAccessibilityNodeInfo(View.NO_ID); 5331 } else { 5332 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5333 onInitializeAccessibilityNodeInfo(info); 5334 return info; 5335 } 5336 } 5337 5338 /** 5339 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5340 * The base implementation sets: 5341 * <ul> 5342 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5343 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5344 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5345 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5346 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5347 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5348 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5349 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5350 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5351 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5352 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5353 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5354 * </ul> 5355 * <p> 5356 * Subclasses should override this method, call the super implementation, 5357 * and set additional attributes. 5358 * </p> 5359 * <p> 5360 * If an {@link AccessibilityDelegate} has been specified via calling 5361 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5362 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5363 * is responsible for handling this call. 5364 * </p> 5365 * 5366 * @param info The instance to initialize. 5367 */ 5368 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5369 if (mAccessibilityDelegate != null) { 5370 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5371 } else { 5372 onInitializeAccessibilityNodeInfoInternal(info); 5373 } 5374 } 5375 5376 /** 5377 * Gets the location of this view in screen coordintates. 5378 * 5379 * @param outRect The output location 5380 */ 5381 void getBoundsOnScreen(Rect outRect) { 5382 if (mAttachInfo == null) { 5383 return; 5384 } 5385 5386 RectF position = mAttachInfo.mTmpTransformRect; 5387 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5388 5389 if (!hasIdentityMatrix()) { 5390 getMatrix().mapRect(position); 5391 } 5392 5393 position.offset(mLeft, mTop); 5394 5395 ViewParent parent = mParent; 5396 while (parent instanceof View) { 5397 View parentView = (View) parent; 5398 5399 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5400 5401 if (!parentView.hasIdentityMatrix()) { 5402 parentView.getMatrix().mapRect(position); 5403 } 5404 5405 position.offset(parentView.mLeft, parentView.mTop); 5406 5407 parent = parentView.mParent; 5408 } 5409 5410 if (parent instanceof ViewRootImpl) { 5411 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5412 position.offset(0, -viewRootImpl.mCurScrollY); 5413 } 5414 5415 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5416 5417 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5418 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5419 } 5420 5421 /** 5422 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5423 * 5424 * Note: Called from the default {@link AccessibilityDelegate}. 5425 */ 5426 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5427 Rect bounds = mAttachInfo.mTmpInvalRect; 5428 5429 getDrawingRect(bounds); 5430 info.setBoundsInParent(bounds); 5431 5432 getBoundsOnScreen(bounds); 5433 info.setBoundsInScreen(bounds); 5434 5435 ViewParent parent = getParentForAccessibility(); 5436 if (parent instanceof View) { 5437 info.setParent((View) parent); 5438 } 5439 5440 if (mID != View.NO_ID) { 5441 View rootView = getRootView(); 5442 if (rootView == null) { 5443 rootView = this; 5444 } 5445 View label = rootView.findLabelForView(this, mID); 5446 if (label != null) { 5447 info.setLabeledBy(label); 5448 } 5449 5450 if ((mAttachInfo.mAccessibilityFetchFlags 5451 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5452 && Resources.resourceHasPackage(mID)) { 5453 try { 5454 String viewId = getResources().getResourceName(mID); 5455 info.setViewIdResourceName(viewId); 5456 } catch (Resources.NotFoundException nfe) { 5457 /* ignore */ 5458 } 5459 } 5460 } 5461 5462 if (mLabelForId != View.NO_ID) { 5463 View rootView = getRootView(); 5464 if (rootView == null) { 5465 rootView = this; 5466 } 5467 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5468 if (labeled != null) { 5469 info.setLabelFor(labeled); 5470 } 5471 } 5472 5473 info.setVisibleToUser(isVisibleToUser()); 5474 5475 info.setPackageName(mContext.getPackageName()); 5476 info.setClassName(View.class.getName()); 5477 info.setContentDescription(getContentDescription()); 5478 5479 info.setEnabled(isEnabled()); 5480 info.setClickable(isClickable()); 5481 info.setFocusable(isFocusable()); 5482 info.setFocused(isFocused()); 5483 info.setAccessibilityFocused(isAccessibilityFocused()); 5484 info.setSelected(isSelected()); 5485 info.setLongClickable(isLongClickable()); 5486 info.setLiveRegion(getAccessibilityLiveRegion()); 5487 5488 // TODO: These make sense only if we are in an AdapterView but all 5489 // views can be selected. Maybe from accessibility perspective 5490 // we should report as selectable view in an AdapterView. 5491 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5492 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5493 5494 if (isFocusable()) { 5495 if (isFocused()) { 5496 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5497 } else { 5498 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5499 } 5500 } 5501 5502 if (!isAccessibilityFocused()) { 5503 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5504 } else { 5505 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5506 } 5507 5508 if (isClickable() && isEnabled()) { 5509 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5510 } 5511 5512 if (isLongClickable() && isEnabled()) { 5513 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5514 } 5515 5516 CharSequence text = getIterableTextForAccessibility(); 5517 if (text != null && text.length() > 0) { 5518 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5519 5520 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5521 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5522 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5523 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5524 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5525 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5526 } 5527 } 5528 5529 private View findLabelForView(View view, int labeledId) { 5530 if (mMatchLabelForPredicate == null) { 5531 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5532 } 5533 mMatchLabelForPredicate.mLabeledId = labeledId; 5534 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5535 } 5536 5537 /** 5538 * Computes whether this view is visible to the user. Such a view is 5539 * attached, visible, all its predecessors are visible, it is not clipped 5540 * entirely by its predecessors, and has an alpha greater than zero. 5541 * 5542 * @return Whether the view is visible on the screen. 5543 * 5544 * @hide 5545 */ 5546 protected boolean isVisibleToUser() { 5547 return isVisibleToUser(null); 5548 } 5549 5550 /** 5551 * Computes whether the given portion of this view is visible to the user. 5552 * Such a view is attached, visible, all its predecessors are visible, 5553 * has an alpha greater than zero, and the specified portion is not 5554 * clipped entirely by its predecessors. 5555 * 5556 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5557 * <code>null</code>, and the entire view will be tested in this case. 5558 * When <code>true</code> is returned by the function, the actual visible 5559 * region will be stored in this parameter; that is, if boundInView is fully 5560 * contained within the view, no modification will be made, otherwise regions 5561 * outside of the visible area of the view will be clipped. 5562 * 5563 * @return Whether the specified portion of the view is visible on the screen. 5564 * 5565 * @hide 5566 */ 5567 protected boolean isVisibleToUser(Rect boundInView) { 5568 if (mAttachInfo != null) { 5569 // Attached to invisible window means this view is not visible. 5570 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5571 return false; 5572 } 5573 // An invisible predecessor or one with alpha zero means 5574 // that this view is not visible to the user. 5575 Object current = this; 5576 while (current instanceof View) { 5577 View view = (View) current; 5578 // We have attach info so this view is attached and there is no 5579 // need to check whether we reach to ViewRootImpl on the way up. 5580 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5581 view.getVisibility() != VISIBLE) { 5582 return false; 5583 } 5584 current = view.mParent; 5585 } 5586 // Check if the view is entirely covered by its predecessors. 5587 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5588 Point offset = mAttachInfo.mPoint; 5589 if (!getGlobalVisibleRect(visibleRect, offset)) { 5590 return false; 5591 } 5592 // Check if the visible portion intersects the rectangle of interest. 5593 if (boundInView != null) { 5594 visibleRect.offset(-offset.x, -offset.y); 5595 return boundInView.intersect(visibleRect); 5596 } 5597 return true; 5598 } 5599 return false; 5600 } 5601 5602 /** 5603 * Returns the delegate for implementing accessibility support via 5604 * composition. For more details see {@link AccessibilityDelegate}. 5605 * 5606 * @return The delegate, or null if none set. 5607 * 5608 * @hide 5609 */ 5610 public AccessibilityDelegate getAccessibilityDelegate() { 5611 return mAccessibilityDelegate; 5612 } 5613 5614 /** 5615 * Sets a delegate for implementing accessibility support via composition as 5616 * opposed to inheritance. The delegate's primary use is for implementing 5617 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5618 * 5619 * @param delegate The delegate instance. 5620 * 5621 * @see AccessibilityDelegate 5622 */ 5623 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5624 mAccessibilityDelegate = delegate; 5625 } 5626 5627 /** 5628 * Gets the provider for managing a virtual view hierarchy rooted at this View 5629 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5630 * that explore the window content. 5631 * <p> 5632 * If this method returns an instance, this instance is responsible for managing 5633 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5634 * View including the one representing the View itself. Similarly the returned 5635 * instance is responsible for performing accessibility actions on any virtual 5636 * view or the root view itself. 5637 * </p> 5638 * <p> 5639 * If an {@link AccessibilityDelegate} has been specified via calling 5640 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5641 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5642 * is responsible for handling this call. 5643 * </p> 5644 * 5645 * @return The provider. 5646 * 5647 * @see AccessibilityNodeProvider 5648 */ 5649 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5650 if (mAccessibilityDelegate != null) { 5651 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5652 } else { 5653 return null; 5654 } 5655 } 5656 5657 /** 5658 * Gets the unique identifier of this view on the screen for accessibility purposes. 5659 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5660 * 5661 * @return The view accessibility id. 5662 * 5663 * @hide 5664 */ 5665 public int getAccessibilityViewId() { 5666 if (mAccessibilityViewId == NO_ID) { 5667 mAccessibilityViewId = sNextAccessibilityViewId++; 5668 } 5669 return mAccessibilityViewId; 5670 } 5671 5672 /** 5673 * Gets the unique identifier of the window in which this View reseides. 5674 * 5675 * @return The window accessibility id. 5676 * 5677 * @hide 5678 */ 5679 public int getAccessibilityWindowId() { 5680 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 5681 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 5682 } 5683 5684 /** 5685 * Gets the {@link View} description. It briefly describes the view and is 5686 * primarily used for accessibility support. Set this property to enable 5687 * better accessibility support for your application. This is especially 5688 * true for views that do not have textual representation (For example, 5689 * ImageButton). 5690 * 5691 * @return The content description. 5692 * 5693 * @attr ref android.R.styleable#View_contentDescription 5694 */ 5695 @ViewDebug.ExportedProperty(category = "accessibility") 5696 public CharSequence getContentDescription() { 5697 return mContentDescription; 5698 } 5699 5700 /** 5701 * Sets the {@link View} description. It briefly describes the view and is 5702 * primarily used for accessibility support. Set this property to enable 5703 * better accessibility support for your application. This is especially 5704 * true for views that do not have textual representation (For example, 5705 * ImageButton). 5706 * 5707 * @param contentDescription The content description. 5708 * 5709 * @attr ref android.R.styleable#View_contentDescription 5710 */ 5711 @RemotableViewMethod 5712 public void setContentDescription(CharSequence contentDescription) { 5713 if (mContentDescription == null) { 5714 if (contentDescription == null) { 5715 return; 5716 } 5717 } else if (mContentDescription.equals(contentDescription)) { 5718 return; 5719 } 5720 mContentDescription = contentDescription; 5721 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5722 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5723 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5724 notifySubtreeAccessibilityStateChangedIfNeeded(); 5725 } else { 5726 notifyViewAccessibilityStateChangedIfNeeded( 5727 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5728 } 5729 } 5730 5731 /** 5732 * Gets the id of a view for which this view serves as a label for 5733 * accessibility purposes. 5734 * 5735 * @return The labeled view id. 5736 */ 5737 @ViewDebug.ExportedProperty(category = "accessibility") 5738 public int getLabelFor() { 5739 return mLabelForId; 5740 } 5741 5742 /** 5743 * Sets the id of a view for which this view serves as a label for 5744 * accessibility purposes. 5745 * 5746 * @param id The labeled view id. 5747 */ 5748 @RemotableViewMethod 5749 public void setLabelFor(int id) { 5750 mLabelForId = id; 5751 if (mLabelForId != View.NO_ID 5752 && mID == View.NO_ID) { 5753 mID = generateViewId(); 5754 } 5755 } 5756 5757 /** 5758 * Invoked whenever this view loses focus, either by losing window focus or by losing 5759 * focus within its window. This method can be used to clear any state tied to the 5760 * focus. For instance, if a button is held pressed with the trackball and the window 5761 * loses focus, this method can be used to cancel the press. 5762 * 5763 * Subclasses of View overriding this method should always call super.onFocusLost(). 5764 * 5765 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5766 * @see #onWindowFocusChanged(boolean) 5767 * 5768 * @hide pending API council approval 5769 */ 5770 protected void onFocusLost() { 5771 resetPressedState(); 5772 } 5773 5774 private void resetPressedState() { 5775 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5776 return; 5777 } 5778 5779 if (isPressed()) { 5780 setPressed(false); 5781 5782 if (!mHasPerformedLongPress) { 5783 removeLongPressCallback(); 5784 } 5785 } 5786 } 5787 5788 /** 5789 * Returns true if this view has focus 5790 * 5791 * @return True if this view has focus, false otherwise. 5792 */ 5793 @ViewDebug.ExportedProperty(category = "focus") 5794 public boolean isFocused() { 5795 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5796 } 5797 5798 /** 5799 * Find the view in the hierarchy rooted at this view that currently has 5800 * focus. 5801 * 5802 * @return The view that currently has focus, or null if no focused view can 5803 * be found. 5804 */ 5805 public View findFocus() { 5806 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5807 } 5808 5809 /** 5810 * Indicates whether this view is one of the set of scrollable containers in 5811 * its window. 5812 * 5813 * @return whether this view is one of the set of scrollable containers in 5814 * its window 5815 * 5816 * @attr ref android.R.styleable#View_isScrollContainer 5817 */ 5818 public boolean isScrollContainer() { 5819 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5820 } 5821 5822 /** 5823 * Change whether this view is one of the set of scrollable containers in 5824 * its window. This will be used to determine whether the window can 5825 * resize or must pan when a soft input area is open -- scrollable 5826 * containers allow the window to use resize mode since the container 5827 * will appropriately shrink. 5828 * 5829 * @attr ref android.R.styleable#View_isScrollContainer 5830 */ 5831 public void setScrollContainer(boolean isScrollContainer) { 5832 if (isScrollContainer) { 5833 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5834 mAttachInfo.mScrollContainers.add(this); 5835 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5836 } 5837 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5838 } else { 5839 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5840 mAttachInfo.mScrollContainers.remove(this); 5841 } 5842 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5843 } 5844 } 5845 5846 /** 5847 * Returns the quality of the drawing cache. 5848 * 5849 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5850 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5851 * 5852 * @see #setDrawingCacheQuality(int) 5853 * @see #setDrawingCacheEnabled(boolean) 5854 * @see #isDrawingCacheEnabled() 5855 * 5856 * @attr ref android.R.styleable#View_drawingCacheQuality 5857 */ 5858 @DrawingCacheQuality 5859 public int getDrawingCacheQuality() { 5860 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5861 } 5862 5863 /** 5864 * Set the drawing cache quality of this view. This value is used only when the 5865 * drawing cache is enabled 5866 * 5867 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5868 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5869 * 5870 * @see #getDrawingCacheQuality() 5871 * @see #setDrawingCacheEnabled(boolean) 5872 * @see #isDrawingCacheEnabled() 5873 * 5874 * @attr ref android.R.styleable#View_drawingCacheQuality 5875 */ 5876 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 5877 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5878 } 5879 5880 /** 5881 * Returns whether the screen should remain on, corresponding to the current 5882 * value of {@link #KEEP_SCREEN_ON}. 5883 * 5884 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5885 * 5886 * @see #setKeepScreenOn(boolean) 5887 * 5888 * @attr ref android.R.styleable#View_keepScreenOn 5889 */ 5890 public boolean getKeepScreenOn() { 5891 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5892 } 5893 5894 /** 5895 * Controls whether the screen should remain on, modifying the 5896 * value of {@link #KEEP_SCREEN_ON}. 5897 * 5898 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5899 * 5900 * @see #getKeepScreenOn() 5901 * 5902 * @attr ref android.R.styleable#View_keepScreenOn 5903 */ 5904 public void setKeepScreenOn(boolean keepScreenOn) { 5905 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5906 } 5907 5908 /** 5909 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5910 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5911 * 5912 * @attr ref android.R.styleable#View_nextFocusLeft 5913 */ 5914 public int getNextFocusLeftId() { 5915 return mNextFocusLeftId; 5916 } 5917 5918 /** 5919 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5920 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5921 * decide automatically. 5922 * 5923 * @attr ref android.R.styleable#View_nextFocusLeft 5924 */ 5925 public void setNextFocusLeftId(int nextFocusLeftId) { 5926 mNextFocusLeftId = nextFocusLeftId; 5927 } 5928 5929 /** 5930 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5931 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5932 * 5933 * @attr ref android.R.styleable#View_nextFocusRight 5934 */ 5935 public int getNextFocusRightId() { 5936 return mNextFocusRightId; 5937 } 5938 5939 /** 5940 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5941 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5942 * decide automatically. 5943 * 5944 * @attr ref android.R.styleable#View_nextFocusRight 5945 */ 5946 public void setNextFocusRightId(int nextFocusRightId) { 5947 mNextFocusRightId = nextFocusRightId; 5948 } 5949 5950 /** 5951 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5952 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5953 * 5954 * @attr ref android.R.styleable#View_nextFocusUp 5955 */ 5956 public int getNextFocusUpId() { 5957 return mNextFocusUpId; 5958 } 5959 5960 /** 5961 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5962 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5963 * decide automatically. 5964 * 5965 * @attr ref android.R.styleable#View_nextFocusUp 5966 */ 5967 public void setNextFocusUpId(int nextFocusUpId) { 5968 mNextFocusUpId = nextFocusUpId; 5969 } 5970 5971 /** 5972 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5973 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5974 * 5975 * @attr ref android.R.styleable#View_nextFocusDown 5976 */ 5977 public int getNextFocusDownId() { 5978 return mNextFocusDownId; 5979 } 5980 5981 /** 5982 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5983 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 5984 * decide automatically. 5985 * 5986 * @attr ref android.R.styleable#View_nextFocusDown 5987 */ 5988 public void setNextFocusDownId(int nextFocusDownId) { 5989 mNextFocusDownId = nextFocusDownId; 5990 } 5991 5992 /** 5993 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5994 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5995 * 5996 * @attr ref android.R.styleable#View_nextFocusForward 5997 */ 5998 public int getNextFocusForwardId() { 5999 return mNextFocusForwardId; 6000 } 6001 6002 /** 6003 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6004 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6005 * decide automatically. 6006 * 6007 * @attr ref android.R.styleable#View_nextFocusForward 6008 */ 6009 public void setNextFocusForwardId(int nextFocusForwardId) { 6010 mNextFocusForwardId = nextFocusForwardId; 6011 } 6012 6013 /** 6014 * Returns the visibility of this view and all of its ancestors 6015 * 6016 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6017 */ 6018 public boolean isShown() { 6019 View current = this; 6020 //noinspection ConstantConditions 6021 do { 6022 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6023 return false; 6024 } 6025 ViewParent parent = current.mParent; 6026 if (parent == null) { 6027 return false; // We are not attached to the view root 6028 } 6029 if (!(parent instanceof View)) { 6030 return true; 6031 } 6032 current = (View) parent; 6033 } while (current != null); 6034 6035 return false; 6036 } 6037 6038 /** 6039 * Called by the view hierarchy when the content insets for a window have 6040 * changed, to allow it to adjust its content to fit within those windows. 6041 * The content insets tell you the space that the status bar, input method, 6042 * and other system windows infringe on the application's window. 6043 * 6044 * <p>You do not normally need to deal with this function, since the default 6045 * window decoration given to applications takes care of applying it to the 6046 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6047 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6048 * and your content can be placed under those system elements. You can then 6049 * use this method within your view hierarchy if you have parts of your UI 6050 * which you would like to ensure are not being covered. 6051 * 6052 * <p>The default implementation of this method simply applies the content 6053 * insets to the view's padding, consuming that content (modifying the 6054 * insets to be 0), and returning true. This behavior is off by default, but can 6055 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6056 * 6057 * <p>This function's traversal down the hierarchy is depth-first. The same content 6058 * insets object is propagated down the hierarchy, so any changes made to it will 6059 * be seen by all following views (including potentially ones above in 6060 * the hierarchy since this is a depth-first traversal). The first view 6061 * that returns true will abort the entire traversal. 6062 * 6063 * <p>The default implementation works well for a situation where it is 6064 * used with a container that covers the entire window, allowing it to 6065 * apply the appropriate insets to its content on all edges. If you need 6066 * a more complicated layout (such as two different views fitting system 6067 * windows, one on the top of the window, and one on the bottom), 6068 * you can override the method and handle the insets however you would like. 6069 * Note that the insets provided by the framework are always relative to the 6070 * far edges of the window, not accounting for the location of the called view 6071 * within that window. (In fact when this method is called you do not yet know 6072 * where the layout will place the view, as it is done before layout happens.) 6073 * 6074 * <p>Note: unlike many View methods, there is no dispatch phase to this 6075 * call. If you are overriding it in a ViewGroup and want to allow the 6076 * call to continue to your children, you must be sure to call the super 6077 * implementation. 6078 * 6079 * <p>Here is a sample layout that makes use of fitting system windows 6080 * to have controls for a video view placed inside of the window decorations 6081 * that it hides and shows. This can be used with code like the second 6082 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6083 * 6084 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6085 * 6086 * @param insets Current content insets of the window. Prior to 6087 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6088 * the insets or else you and Android will be unhappy. 6089 * 6090 * @return {@code true} if this view applied the insets and it should not 6091 * continue propagating further down the hierarchy, {@code false} otherwise. 6092 * @see #getFitsSystemWindows() 6093 * @see #setFitsSystemWindows(boolean) 6094 * @see #setSystemUiVisibility(int) 6095 * 6096 * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6097 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6098 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6099 * to implement handling their own insets. 6100 */ 6101 protected boolean fitSystemWindows(Rect insets) { 6102 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6103 // If we're not in the process of dispatching the newer apply insets call, 6104 // that means we're not in the compatibility path. Dispatch into the newer 6105 // apply insets path and take things from there. 6106 try { 6107 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6108 return !dispatchApplyWindowInsets(new WindowInsets(insets)).hasInsets(); 6109 } finally { 6110 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6111 } 6112 } else { 6113 // We're being called from the newer apply insets path. 6114 // Perform the standard fallback behavior. 6115 return fitSystemWindowsInt(insets); 6116 } 6117 } 6118 6119 private boolean fitSystemWindowsInt(Rect insets) { 6120 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6121 mUserPaddingStart = UNDEFINED_PADDING; 6122 mUserPaddingEnd = UNDEFINED_PADDING; 6123 Rect localInsets = sThreadLocal.get(); 6124 if (localInsets == null) { 6125 localInsets = new Rect(); 6126 sThreadLocal.set(localInsets); 6127 } 6128 boolean res = computeFitSystemWindows(insets, localInsets); 6129 mUserPaddingLeftInitial = localInsets.left; 6130 mUserPaddingRightInitial = localInsets.right; 6131 internalSetPadding(localInsets.left, localInsets.top, 6132 localInsets.right, localInsets.bottom); 6133 return res; 6134 } 6135 return false; 6136 } 6137 6138 /** 6139 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6140 * 6141 * <p>This method should be overridden by views that wish to apply a policy different from or 6142 * in addition to the default behavior. Clients that wish to force a view subtree 6143 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6144 * 6145 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6146 * it will be called during dispatch instead of this method. The listener may optionally 6147 * call this method from its own implementation if it wishes to apply the view's default 6148 * insets policy in addition to its own.</p> 6149 * 6150 * <p>Implementations of this method should either return the insets parameter unchanged 6151 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6152 * that this view applied itself. This allows new inset types added in future platform 6153 * versions to pass through existing implementations unchanged without being erroneously 6154 * consumed.</p> 6155 * 6156 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6157 * property is set then the view will consume the system window insets and apply them 6158 * as padding for the view.</p> 6159 * 6160 * @param insets Insets to apply 6161 * @return The supplied insets with any applied insets consumed 6162 */ 6163 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6164 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6165 // We weren't called from within a direct call to fitSystemWindows, 6166 // call into it as a fallback in case we're in a class that overrides it 6167 // and has logic to perform. 6168 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6169 return insets.consumeSystemWindowInsets(); 6170 } 6171 } else { 6172 // We were called from within a direct call to fitSystemWindows. 6173 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6174 return insets.consumeSystemWindowInsets(); 6175 } 6176 } 6177 return insets; 6178 } 6179 6180 /** 6181 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6182 * window insets to this view. The listener's 6183 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6184 * method will be called instead of the view's 6185 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6186 * 6187 * @param listener Listener to set 6188 * 6189 * @see #onApplyWindowInsets(WindowInsets) 6190 */ 6191 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6192 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6193 } 6194 6195 /** 6196 * Request to apply the given window insets to this view or another view in its subtree. 6197 * 6198 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6199 * obscured by window decorations or overlays. This can include the status and navigation bars, 6200 * action bars, input methods and more. New inset categories may be added in the future. 6201 * The method returns the insets provided minus any that were applied by this view or its 6202 * children.</p> 6203 * 6204 * <p>Clients wishing to provide custom behavior should override the 6205 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6206 * {@link OnApplyWindowInsetsListener} via the 6207 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6208 * method.</p> 6209 * 6210 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6211 * </p> 6212 * 6213 * @param insets Insets to apply 6214 * @return The provided insets minus the insets that were consumed 6215 */ 6216 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6217 try { 6218 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6219 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6220 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6221 } else { 6222 return onApplyWindowInsets(insets); 6223 } 6224 } finally { 6225 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6226 } 6227 } 6228 6229 /** 6230 * @hide Compute the insets that should be consumed by this view and the ones 6231 * that should propagate to those under it. 6232 */ 6233 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6234 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6235 || mAttachInfo == null 6236 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6237 && !mAttachInfo.mOverscanRequested)) { 6238 outLocalInsets.set(inoutInsets); 6239 inoutInsets.set(0, 0, 0, 0); 6240 return true; 6241 } else { 6242 // The application wants to take care of fitting system window for 6243 // the content... however we still need to take care of any overscan here. 6244 final Rect overscan = mAttachInfo.mOverscanInsets; 6245 outLocalInsets.set(overscan); 6246 inoutInsets.left -= overscan.left; 6247 inoutInsets.top -= overscan.top; 6248 inoutInsets.right -= overscan.right; 6249 inoutInsets.bottom -= overscan.bottom; 6250 return false; 6251 } 6252 } 6253 6254 /** 6255 * Sets whether or not this view should account for system screen decorations 6256 * such as the status bar and inset its content; that is, controlling whether 6257 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6258 * executed. See that method for more details. 6259 * 6260 * <p>Note that if you are providing your own implementation of 6261 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6262 * flag to true -- your implementation will be overriding the default 6263 * implementation that checks this flag. 6264 * 6265 * @param fitSystemWindows If true, then the default implementation of 6266 * {@link #fitSystemWindows(Rect)} will be executed. 6267 * 6268 * @attr ref android.R.styleable#View_fitsSystemWindows 6269 * @see #getFitsSystemWindows() 6270 * @see #fitSystemWindows(Rect) 6271 * @see #setSystemUiVisibility(int) 6272 */ 6273 public void setFitsSystemWindows(boolean fitSystemWindows) { 6274 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6275 } 6276 6277 /** 6278 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6279 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6280 * will be executed. 6281 * 6282 * @return {@code true} if the default implementation of 6283 * {@link #fitSystemWindows(Rect)} will be executed. 6284 * 6285 * @attr ref android.R.styleable#View_fitsSystemWindows 6286 * @see #setFitsSystemWindows(boolean) 6287 * @see #fitSystemWindows(Rect) 6288 * @see #setSystemUiVisibility(int) 6289 */ 6290 public boolean getFitsSystemWindows() { 6291 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6292 } 6293 6294 /** @hide */ 6295 public boolean fitsSystemWindows() { 6296 return getFitsSystemWindows(); 6297 } 6298 6299 /** 6300 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6301 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6302 */ 6303 public void requestFitSystemWindows() { 6304 if (mParent != null) { 6305 mParent.requestFitSystemWindows(); 6306 } 6307 } 6308 6309 /** 6310 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6311 */ 6312 public void requestApplyInsets() { 6313 requestFitSystemWindows(); 6314 } 6315 6316 /** 6317 * For use by PhoneWindow to make its own system window fitting optional. 6318 * @hide 6319 */ 6320 public void makeOptionalFitsSystemWindows() { 6321 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6322 } 6323 6324 /** 6325 * Returns the visibility status for this view. 6326 * 6327 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6328 * @attr ref android.R.styleable#View_visibility 6329 */ 6330 @ViewDebug.ExportedProperty(mapping = { 6331 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6332 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6333 @ViewDebug.IntToString(from = GONE, to = "GONE") 6334 }) 6335 @Visibility 6336 public int getVisibility() { 6337 return mViewFlags & VISIBILITY_MASK; 6338 } 6339 6340 /** 6341 * Set the enabled state of this view. 6342 * 6343 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6344 * @attr ref android.R.styleable#View_visibility 6345 */ 6346 @RemotableViewMethod 6347 public void setVisibility(@Visibility int visibility) { 6348 setFlags(visibility, VISIBILITY_MASK); 6349 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6350 } 6351 6352 /** 6353 * Returns the enabled status for this view. The interpretation of the 6354 * enabled state varies by subclass. 6355 * 6356 * @return True if this view is enabled, false otherwise. 6357 */ 6358 @ViewDebug.ExportedProperty 6359 public boolean isEnabled() { 6360 return (mViewFlags & ENABLED_MASK) == ENABLED; 6361 } 6362 6363 /** 6364 * Set the enabled state of this view. The interpretation of the enabled 6365 * state varies by subclass. 6366 * 6367 * @param enabled True if this view is enabled, false otherwise. 6368 */ 6369 @RemotableViewMethod 6370 public void setEnabled(boolean enabled) { 6371 if (enabled == isEnabled()) return; 6372 6373 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6374 6375 /* 6376 * The View most likely has to change its appearance, so refresh 6377 * the drawable state. 6378 */ 6379 refreshDrawableState(); 6380 6381 // Invalidate too, since the default behavior for views is to be 6382 // be drawn at 50% alpha rather than to change the drawable. 6383 invalidate(true); 6384 6385 if (!enabled) { 6386 cancelPendingInputEvents(); 6387 } 6388 } 6389 6390 /** 6391 * Set whether this view can receive the focus. 6392 * 6393 * Setting this to false will also ensure that this view is not focusable 6394 * in touch mode. 6395 * 6396 * @param focusable If true, this view can receive the focus. 6397 * 6398 * @see #setFocusableInTouchMode(boolean) 6399 * @attr ref android.R.styleable#View_focusable 6400 */ 6401 public void setFocusable(boolean focusable) { 6402 if (!focusable) { 6403 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6404 } 6405 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6406 } 6407 6408 /** 6409 * Set whether this view can receive focus while in touch mode. 6410 * 6411 * Setting this to true will also ensure that this view is focusable. 6412 * 6413 * @param focusableInTouchMode If true, this view can receive the focus while 6414 * in touch mode. 6415 * 6416 * @see #setFocusable(boolean) 6417 * @attr ref android.R.styleable#View_focusableInTouchMode 6418 */ 6419 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6420 // Focusable in touch mode should always be set before the focusable flag 6421 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6422 // which, in touch mode, will not successfully request focus on this view 6423 // because the focusable in touch mode flag is not set 6424 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6425 if (focusableInTouchMode) { 6426 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6427 } 6428 } 6429 6430 /** 6431 * Set whether this view should have sound effects enabled for events such as 6432 * clicking and touching. 6433 * 6434 * <p>You may wish to disable sound effects for a view if you already play sounds, 6435 * for instance, a dial key that plays dtmf tones. 6436 * 6437 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6438 * @see #isSoundEffectsEnabled() 6439 * @see #playSoundEffect(int) 6440 * @attr ref android.R.styleable#View_soundEffectsEnabled 6441 */ 6442 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6443 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6444 } 6445 6446 /** 6447 * @return whether this view should have sound effects enabled for events such as 6448 * clicking and touching. 6449 * 6450 * @see #setSoundEffectsEnabled(boolean) 6451 * @see #playSoundEffect(int) 6452 * @attr ref android.R.styleable#View_soundEffectsEnabled 6453 */ 6454 @ViewDebug.ExportedProperty 6455 public boolean isSoundEffectsEnabled() { 6456 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6457 } 6458 6459 /** 6460 * Set whether this view should have haptic feedback for events such as 6461 * long presses. 6462 * 6463 * <p>You may wish to disable haptic feedback if your view already controls 6464 * its own haptic feedback. 6465 * 6466 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6467 * @see #isHapticFeedbackEnabled() 6468 * @see #performHapticFeedback(int) 6469 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6470 */ 6471 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6472 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6473 } 6474 6475 /** 6476 * @return whether this view should have haptic feedback enabled for events 6477 * long presses. 6478 * 6479 * @see #setHapticFeedbackEnabled(boolean) 6480 * @see #performHapticFeedback(int) 6481 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6482 */ 6483 @ViewDebug.ExportedProperty 6484 public boolean isHapticFeedbackEnabled() { 6485 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6486 } 6487 6488 /** 6489 * Returns the layout direction for this view. 6490 * 6491 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6492 * {@link #LAYOUT_DIRECTION_RTL}, 6493 * {@link #LAYOUT_DIRECTION_INHERIT} or 6494 * {@link #LAYOUT_DIRECTION_LOCALE}. 6495 * 6496 * @attr ref android.R.styleable#View_layoutDirection 6497 * 6498 * @hide 6499 */ 6500 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6501 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6502 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6503 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6504 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6505 }) 6506 @LayoutDir 6507 public int getRawLayoutDirection() { 6508 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6509 } 6510 6511 /** 6512 * Set the layout direction for this view. This will propagate a reset of layout direction 6513 * resolution to the view's children and resolve layout direction for this view. 6514 * 6515 * @param layoutDirection the layout direction to set. Should be one of: 6516 * 6517 * {@link #LAYOUT_DIRECTION_LTR}, 6518 * {@link #LAYOUT_DIRECTION_RTL}, 6519 * {@link #LAYOUT_DIRECTION_INHERIT}, 6520 * {@link #LAYOUT_DIRECTION_LOCALE}. 6521 * 6522 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6523 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6524 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6525 * 6526 * @attr ref android.R.styleable#View_layoutDirection 6527 */ 6528 @RemotableViewMethod 6529 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6530 if (getRawLayoutDirection() != layoutDirection) { 6531 // Reset the current layout direction and the resolved one 6532 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6533 resetRtlProperties(); 6534 // Set the new layout direction (filtered) 6535 mPrivateFlags2 |= 6536 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6537 // We need to resolve all RTL properties as they all depend on layout direction 6538 resolveRtlPropertiesIfNeeded(); 6539 requestLayout(); 6540 invalidate(true); 6541 } 6542 } 6543 6544 /** 6545 * Returns the resolved layout direction for this view. 6546 * 6547 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6548 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6549 * 6550 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6551 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6552 * 6553 * @attr ref android.R.styleable#View_layoutDirection 6554 */ 6555 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6556 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6557 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6558 }) 6559 @ResolvedLayoutDir 6560 public int getLayoutDirection() { 6561 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6562 if (targetSdkVersion < JELLY_BEAN_MR1) { 6563 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6564 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6565 } 6566 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6567 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6568 } 6569 6570 /** 6571 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6572 * layout attribute and/or the inherited value from the parent 6573 * 6574 * @return true if the layout is right-to-left. 6575 * 6576 * @hide 6577 */ 6578 @ViewDebug.ExportedProperty(category = "layout") 6579 public boolean isLayoutRtl() { 6580 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6581 } 6582 6583 /** 6584 * Indicates whether the view is currently tracking transient state that the 6585 * app should not need to concern itself with saving and restoring, but that 6586 * the framework should take special note to preserve when possible. 6587 * 6588 * <p>A view with transient state cannot be trivially rebound from an external 6589 * data source, such as an adapter binding item views in a list. This may be 6590 * because the view is performing an animation, tracking user selection 6591 * of content, or similar.</p> 6592 * 6593 * @return true if the view has transient state 6594 */ 6595 @ViewDebug.ExportedProperty(category = "layout") 6596 public boolean hasTransientState() { 6597 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6598 } 6599 6600 /** 6601 * Set whether this view is currently tracking transient state that the 6602 * framework should attempt to preserve when possible. This flag is reference counted, 6603 * so every call to setHasTransientState(true) should be paired with a later call 6604 * to setHasTransientState(false). 6605 * 6606 * <p>A view with transient state cannot be trivially rebound from an external 6607 * data source, such as an adapter binding item views in a list. This may be 6608 * because the view is performing an animation, tracking user selection 6609 * of content, or similar.</p> 6610 * 6611 * @param hasTransientState true if this view has transient state 6612 */ 6613 public void setHasTransientState(boolean hasTransientState) { 6614 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6615 mTransientStateCount - 1; 6616 if (mTransientStateCount < 0) { 6617 mTransientStateCount = 0; 6618 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6619 "unmatched pair of setHasTransientState calls"); 6620 } else if ((hasTransientState && mTransientStateCount == 1) || 6621 (!hasTransientState && mTransientStateCount == 0)) { 6622 // update flag if we've just incremented up from 0 or decremented down to 0 6623 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6624 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6625 if (mParent != null) { 6626 try { 6627 mParent.childHasTransientStateChanged(this, hasTransientState); 6628 } catch (AbstractMethodError e) { 6629 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6630 " does not fully implement ViewParent", e); 6631 } 6632 } 6633 } 6634 } 6635 6636 /** 6637 * Returns true if this view is currently attached to a window. 6638 */ 6639 public boolean isAttachedToWindow() { 6640 return mAttachInfo != null; 6641 } 6642 6643 /** 6644 * Returns true if this view has been through at least one layout since it 6645 * was last attached to or detached from a window. 6646 */ 6647 public boolean isLaidOut() { 6648 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6649 } 6650 6651 /** 6652 * If this view doesn't do any drawing on its own, set this flag to 6653 * allow further optimizations. By default, this flag is not set on 6654 * View, but could be set on some View subclasses such as ViewGroup. 6655 * 6656 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6657 * you should clear this flag. 6658 * 6659 * @param willNotDraw whether or not this View draw on its own 6660 */ 6661 public void setWillNotDraw(boolean willNotDraw) { 6662 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6663 } 6664 6665 /** 6666 * Returns whether or not this View draws on its own. 6667 * 6668 * @return true if this view has nothing to draw, false otherwise 6669 */ 6670 @ViewDebug.ExportedProperty(category = "drawing") 6671 public boolean willNotDraw() { 6672 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6673 } 6674 6675 /** 6676 * When a View's drawing cache is enabled, drawing is redirected to an 6677 * offscreen bitmap. Some views, like an ImageView, must be able to 6678 * bypass this mechanism if they already draw a single bitmap, to avoid 6679 * unnecessary usage of the memory. 6680 * 6681 * @param willNotCacheDrawing true if this view does not cache its 6682 * drawing, false otherwise 6683 */ 6684 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6685 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6686 } 6687 6688 /** 6689 * Returns whether or not this View can cache its drawing or not. 6690 * 6691 * @return true if this view does not cache its drawing, false otherwise 6692 */ 6693 @ViewDebug.ExportedProperty(category = "drawing") 6694 public boolean willNotCacheDrawing() { 6695 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6696 } 6697 6698 /** 6699 * Indicates whether this view reacts to click events or not. 6700 * 6701 * @return true if the view is clickable, false otherwise 6702 * 6703 * @see #setClickable(boolean) 6704 * @attr ref android.R.styleable#View_clickable 6705 */ 6706 @ViewDebug.ExportedProperty 6707 public boolean isClickable() { 6708 return (mViewFlags & CLICKABLE) == CLICKABLE; 6709 } 6710 6711 /** 6712 * Enables or disables click events for this view. When a view 6713 * is clickable it will change its state to "pressed" on every click. 6714 * Subclasses should set the view clickable to visually react to 6715 * user's clicks. 6716 * 6717 * @param clickable true to make the view clickable, false otherwise 6718 * 6719 * @see #isClickable() 6720 * @attr ref android.R.styleable#View_clickable 6721 */ 6722 public void setClickable(boolean clickable) { 6723 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6724 } 6725 6726 /** 6727 * Indicates whether this view reacts to long click events or not. 6728 * 6729 * @return true if the view is long clickable, false otherwise 6730 * 6731 * @see #setLongClickable(boolean) 6732 * @attr ref android.R.styleable#View_longClickable 6733 */ 6734 public boolean isLongClickable() { 6735 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6736 } 6737 6738 /** 6739 * Enables or disables long click events for this view. When a view is long 6740 * clickable it reacts to the user holding down the button for a longer 6741 * duration than a tap. This event can either launch the listener or a 6742 * context menu. 6743 * 6744 * @param longClickable true to make the view long clickable, false otherwise 6745 * @see #isLongClickable() 6746 * @attr ref android.R.styleable#View_longClickable 6747 */ 6748 public void setLongClickable(boolean longClickable) { 6749 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6750 } 6751 6752 /** 6753 * Sets the pressed state for this view and provides a touch coordinate for 6754 * animation hinting. 6755 * 6756 * @param pressed Pass true to set the View's internal state to "pressed", 6757 * or false to reverts the View's internal state from a 6758 * previously set "pressed" state. 6759 * @param x The x coordinate of the touch that caused the press 6760 * @param y The y coordinate of the touch that caused the press 6761 */ 6762 private void setPressed(boolean pressed, float x, float y) { 6763 if (pressed) { 6764 setHotspot(x, y); 6765 } 6766 6767 setPressed(pressed); 6768 } 6769 6770 /** 6771 * Sets the pressed state for this view. 6772 * 6773 * @see #isClickable() 6774 * @see #setClickable(boolean) 6775 * 6776 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6777 * the View's internal state from a previously set "pressed" state. 6778 */ 6779 public void setPressed(boolean pressed) { 6780 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6781 6782 if (pressed) { 6783 mPrivateFlags |= PFLAG_PRESSED; 6784 } else { 6785 mPrivateFlags &= ~PFLAG_PRESSED; 6786 } 6787 6788 if (needsRefresh) { 6789 refreshDrawableState(); 6790 } 6791 dispatchSetPressed(pressed); 6792 } 6793 6794 /** 6795 * Dispatch setPressed to all of this View's children. 6796 * 6797 * @see #setPressed(boolean) 6798 * 6799 * @param pressed The new pressed state 6800 */ 6801 protected void dispatchSetPressed(boolean pressed) { 6802 } 6803 6804 /** 6805 * Indicates whether the view is currently in pressed state. Unless 6806 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6807 * the pressed state. 6808 * 6809 * @see #setPressed(boolean) 6810 * @see #isClickable() 6811 * @see #setClickable(boolean) 6812 * 6813 * @return true if the view is currently pressed, false otherwise 6814 */ 6815 public boolean isPressed() { 6816 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6817 } 6818 6819 /** 6820 * Indicates whether this view will save its state (that is, 6821 * whether its {@link #onSaveInstanceState} method will be called). 6822 * 6823 * @return Returns true if the view state saving is enabled, else false. 6824 * 6825 * @see #setSaveEnabled(boolean) 6826 * @attr ref android.R.styleable#View_saveEnabled 6827 */ 6828 public boolean isSaveEnabled() { 6829 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6830 } 6831 6832 /** 6833 * Controls whether the saving of this view's state is 6834 * enabled (that is, whether its {@link #onSaveInstanceState} method 6835 * will be called). Note that even if freezing is enabled, the 6836 * view still must have an id assigned to it (via {@link #setId(int)}) 6837 * for its state to be saved. This flag can only disable the 6838 * saving of this view; any child views may still have their state saved. 6839 * 6840 * @param enabled Set to false to <em>disable</em> state saving, or true 6841 * (the default) to allow it. 6842 * 6843 * @see #isSaveEnabled() 6844 * @see #setId(int) 6845 * @see #onSaveInstanceState() 6846 * @attr ref android.R.styleable#View_saveEnabled 6847 */ 6848 public void setSaveEnabled(boolean enabled) { 6849 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6850 } 6851 6852 /** 6853 * Gets whether the framework should discard touches when the view's 6854 * window is obscured by another visible window. 6855 * Refer to the {@link View} security documentation for more details. 6856 * 6857 * @return True if touch filtering is enabled. 6858 * 6859 * @see #setFilterTouchesWhenObscured(boolean) 6860 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6861 */ 6862 @ViewDebug.ExportedProperty 6863 public boolean getFilterTouchesWhenObscured() { 6864 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6865 } 6866 6867 /** 6868 * Sets whether the framework should discard touches when the view's 6869 * window is obscured by another visible window. 6870 * Refer to the {@link View} security documentation for more details. 6871 * 6872 * @param enabled True if touch filtering should be enabled. 6873 * 6874 * @see #getFilterTouchesWhenObscured 6875 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6876 */ 6877 public void setFilterTouchesWhenObscured(boolean enabled) { 6878 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 6879 FILTER_TOUCHES_WHEN_OBSCURED); 6880 } 6881 6882 /** 6883 * Indicates whether the entire hierarchy under this view will save its 6884 * state when a state saving traversal occurs from its parent. The default 6885 * is true; if false, these views will not be saved unless 6886 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6887 * 6888 * @return Returns true if the view state saving from parent is enabled, else false. 6889 * 6890 * @see #setSaveFromParentEnabled(boolean) 6891 */ 6892 public boolean isSaveFromParentEnabled() { 6893 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6894 } 6895 6896 /** 6897 * Controls whether the entire hierarchy under this view will save its 6898 * state when a state saving traversal occurs from its parent. The default 6899 * is true; if false, these views will not be saved unless 6900 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6901 * 6902 * @param enabled Set to false to <em>disable</em> state saving, or true 6903 * (the default) to allow it. 6904 * 6905 * @see #isSaveFromParentEnabled() 6906 * @see #setId(int) 6907 * @see #onSaveInstanceState() 6908 */ 6909 public void setSaveFromParentEnabled(boolean enabled) { 6910 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6911 } 6912 6913 6914 /** 6915 * Returns whether this View is able to take focus. 6916 * 6917 * @return True if this view can take focus, or false otherwise. 6918 * @attr ref android.R.styleable#View_focusable 6919 */ 6920 @ViewDebug.ExportedProperty(category = "focus") 6921 public final boolean isFocusable() { 6922 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6923 } 6924 6925 /** 6926 * When a view is focusable, it may not want to take focus when in touch mode. 6927 * For example, a button would like focus when the user is navigating via a D-pad 6928 * so that the user can click on it, but once the user starts touching the screen, 6929 * the button shouldn't take focus 6930 * @return Whether the view is focusable in touch mode. 6931 * @attr ref android.R.styleable#View_focusableInTouchMode 6932 */ 6933 @ViewDebug.ExportedProperty 6934 public final boolean isFocusableInTouchMode() { 6935 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6936 } 6937 6938 /** 6939 * Find the nearest view in the specified direction that can take focus. 6940 * This does not actually give focus to that view. 6941 * 6942 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6943 * 6944 * @return The nearest focusable in the specified direction, or null if none 6945 * can be found. 6946 */ 6947 public View focusSearch(@FocusRealDirection int direction) { 6948 if (mParent != null) { 6949 return mParent.focusSearch(this, direction); 6950 } else { 6951 return null; 6952 } 6953 } 6954 6955 /** 6956 * This method is the last chance for the focused view and its ancestors to 6957 * respond to an arrow key. This is called when the focused view did not 6958 * consume the key internally, nor could the view system find a new view in 6959 * the requested direction to give focus to. 6960 * 6961 * @param focused The currently focused view. 6962 * @param direction The direction focus wants to move. One of FOCUS_UP, 6963 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6964 * @return True if the this view consumed this unhandled move. 6965 */ 6966 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 6967 return false; 6968 } 6969 6970 /** 6971 * If a user manually specified the next view id for a particular direction, 6972 * use the root to look up the view. 6973 * @param root The root view of the hierarchy containing this view. 6974 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6975 * or FOCUS_BACKWARD. 6976 * @return The user specified next view, or null if there is none. 6977 */ 6978 View findUserSetNextFocus(View root, @FocusDirection int direction) { 6979 switch (direction) { 6980 case FOCUS_LEFT: 6981 if (mNextFocusLeftId == View.NO_ID) return null; 6982 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6983 case FOCUS_RIGHT: 6984 if (mNextFocusRightId == View.NO_ID) return null; 6985 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6986 case FOCUS_UP: 6987 if (mNextFocusUpId == View.NO_ID) return null; 6988 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6989 case FOCUS_DOWN: 6990 if (mNextFocusDownId == View.NO_ID) return null; 6991 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6992 case FOCUS_FORWARD: 6993 if (mNextFocusForwardId == View.NO_ID) return null; 6994 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6995 case FOCUS_BACKWARD: { 6996 if (mID == View.NO_ID) return null; 6997 final int id = mID; 6998 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6999 @Override 7000 public boolean apply(View t) { 7001 return t.mNextFocusForwardId == id; 7002 } 7003 }); 7004 } 7005 } 7006 return null; 7007 } 7008 7009 private View findViewInsideOutShouldExist(View root, int id) { 7010 if (mMatchIdPredicate == null) { 7011 mMatchIdPredicate = new MatchIdPredicate(); 7012 } 7013 mMatchIdPredicate.mId = id; 7014 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 7015 if (result == null) { 7016 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7017 } 7018 return result; 7019 } 7020 7021 /** 7022 * Find and return all focusable views that are descendants of this view, 7023 * possibly including this view if it is focusable itself. 7024 * 7025 * @param direction The direction of the focus 7026 * @return A list of focusable views 7027 */ 7028 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7029 ArrayList<View> result = new ArrayList<View>(24); 7030 addFocusables(result, direction); 7031 return result; 7032 } 7033 7034 /** 7035 * Add any focusable views that are descendants of this view (possibly 7036 * including this view if it is focusable itself) to views. If we are in touch mode, 7037 * only add views that are also focusable in touch mode. 7038 * 7039 * @param views Focusable views found so far 7040 * @param direction The direction of the focus 7041 */ 7042 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7043 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7044 } 7045 7046 /** 7047 * Adds any focusable views that are descendants of this view (possibly 7048 * including this view if it is focusable itself) to views. This method 7049 * adds all focusable views regardless if we are in touch mode or 7050 * only views focusable in touch mode if we are in touch mode or 7051 * only views that can take accessibility focus if accessibility is enabeld 7052 * depending on the focusable mode paramater. 7053 * 7054 * @param views Focusable views found so far or null if all we are interested is 7055 * the number of focusables. 7056 * @param direction The direction of the focus. 7057 * @param focusableMode The type of focusables to be added. 7058 * 7059 * @see #FOCUSABLES_ALL 7060 * @see #FOCUSABLES_TOUCH_MODE 7061 */ 7062 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7063 @FocusableMode int focusableMode) { 7064 if (views == null) { 7065 return; 7066 } 7067 if (!isFocusable()) { 7068 return; 7069 } 7070 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7071 && isInTouchMode() && !isFocusableInTouchMode()) { 7072 return; 7073 } 7074 views.add(this); 7075 } 7076 7077 /** 7078 * Finds the Views that contain given text. The containment is case insensitive. 7079 * The search is performed by either the text that the View renders or the content 7080 * description that describes the view for accessibility purposes and the view does 7081 * not render or both. Clients can specify how the search is to be performed via 7082 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7083 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7084 * 7085 * @param outViews The output list of matching Views. 7086 * @param searched The text to match against. 7087 * 7088 * @see #FIND_VIEWS_WITH_TEXT 7089 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7090 * @see #setContentDescription(CharSequence) 7091 */ 7092 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7093 @FindViewFlags int flags) { 7094 if (getAccessibilityNodeProvider() != null) { 7095 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7096 outViews.add(this); 7097 } 7098 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7099 && (searched != null && searched.length() > 0) 7100 && (mContentDescription != null && mContentDescription.length() > 0)) { 7101 String searchedLowerCase = searched.toString().toLowerCase(); 7102 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7103 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7104 outViews.add(this); 7105 } 7106 } 7107 } 7108 7109 /** 7110 * Find and return all touchable views that are descendants of this view, 7111 * possibly including this view if it is touchable itself. 7112 * 7113 * @return A list of touchable views 7114 */ 7115 public ArrayList<View> getTouchables() { 7116 ArrayList<View> result = new ArrayList<View>(); 7117 addTouchables(result); 7118 return result; 7119 } 7120 7121 /** 7122 * Add any touchable views that are descendants of this view (possibly 7123 * including this view if it is touchable itself) to views. 7124 * 7125 * @param views Touchable views found so far 7126 */ 7127 public void addTouchables(ArrayList<View> views) { 7128 final int viewFlags = mViewFlags; 7129 7130 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7131 && (viewFlags & ENABLED_MASK) == ENABLED) { 7132 views.add(this); 7133 } 7134 } 7135 7136 /** 7137 * Returns whether this View is accessibility focused. 7138 * 7139 * @return True if this View is accessibility focused. 7140 */ 7141 public boolean isAccessibilityFocused() { 7142 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7143 } 7144 7145 /** 7146 * Call this to try to give accessibility focus to this view. 7147 * 7148 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7149 * returns false or the view is no visible or the view already has accessibility 7150 * focus. 7151 * 7152 * See also {@link #focusSearch(int)}, which is what you call to say that you 7153 * have focus, and you want your parent to look for the next one. 7154 * 7155 * @return Whether this view actually took accessibility focus. 7156 * 7157 * @hide 7158 */ 7159 public boolean requestAccessibilityFocus() { 7160 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7161 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7162 return false; 7163 } 7164 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7165 return false; 7166 } 7167 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7168 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7169 ViewRootImpl viewRootImpl = getViewRootImpl(); 7170 if (viewRootImpl != null) { 7171 viewRootImpl.setAccessibilityFocus(this, null); 7172 } 7173 Rect rect = (mAttachInfo != null) ? mAttachInfo.mTmpInvalRect : new Rect(); 7174 getDrawingRect(rect); 7175 requestRectangleOnScreen(rect, false); 7176 invalidate(); 7177 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7178 return true; 7179 } 7180 return false; 7181 } 7182 7183 /** 7184 * Call this to try to clear accessibility focus of this view. 7185 * 7186 * See also {@link #focusSearch(int)}, which is what you call to say that you 7187 * have focus, and you want your parent to look for the next one. 7188 * 7189 * @hide 7190 */ 7191 public void clearAccessibilityFocus() { 7192 clearAccessibilityFocusNoCallbacks(); 7193 // Clear the global reference of accessibility focus if this 7194 // view or any of its descendants had accessibility focus. 7195 ViewRootImpl viewRootImpl = getViewRootImpl(); 7196 if (viewRootImpl != null) { 7197 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7198 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7199 viewRootImpl.setAccessibilityFocus(null, null); 7200 } 7201 } 7202 } 7203 7204 private void sendAccessibilityHoverEvent(int eventType) { 7205 // Since we are not delivering to a client accessibility events from not 7206 // important views (unless the clinet request that) we need to fire the 7207 // event from the deepest view exposed to the client. As a consequence if 7208 // the user crosses a not exposed view the client will see enter and exit 7209 // of the exposed predecessor followed by and enter and exit of that same 7210 // predecessor when entering and exiting the not exposed descendant. This 7211 // is fine since the client has a clear idea which view is hovered at the 7212 // price of a couple more events being sent. This is a simple and 7213 // working solution. 7214 View source = this; 7215 while (true) { 7216 if (source.includeForAccessibility()) { 7217 source.sendAccessibilityEvent(eventType); 7218 return; 7219 } 7220 ViewParent parent = source.getParent(); 7221 if (parent instanceof View) { 7222 source = (View) parent; 7223 } else { 7224 return; 7225 } 7226 } 7227 } 7228 7229 /** 7230 * Clears accessibility focus without calling any callback methods 7231 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7232 * is used for clearing accessibility focus when giving this focus to 7233 * another view. 7234 */ 7235 void clearAccessibilityFocusNoCallbacks() { 7236 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7237 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7238 invalidate(); 7239 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7240 } 7241 } 7242 7243 /** 7244 * Call this to try to give focus to a specific view or to one of its 7245 * descendants. 7246 * 7247 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7248 * false), or if it is focusable and it is not focusable in touch mode 7249 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7250 * 7251 * See also {@link #focusSearch(int)}, which is what you call to say that you 7252 * have focus, and you want your parent to look for the next one. 7253 * 7254 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7255 * {@link #FOCUS_DOWN} and <code>null</code>. 7256 * 7257 * @return Whether this view or one of its descendants actually took focus. 7258 */ 7259 public final boolean requestFocus() { 7260 return requestFocus(View.FOCUS_DOWN); 7261 } 7262 7263 /** 7264 * Call this to try to give focus to a specific view or to one of its 7265 * descendants and give it a hint about what direction focus is heading. 7266 * 7267 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7268 * false), or if it is focusable and it is not focusable in touch mode 7269 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7270 * 7271 * See also {@link #focusSearch(int)}, which is what you call to say that you 7272 * have focus, and you want your parent to look for the next one. 7273 * 7274 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7275 * <code>null</code> set for the previously focused rectangle. 7276 * 7277 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7278 * @return Whether this view or one of its descendants actually took focus. 7279 */ 7280 public final boolean requestFocus(int direction) { 7281 return requestFocus(direction, null); 7282 } 7283 7284 /** 7285 * Call this to try to give focus to a specific view or to one of its descendants 7286 * and give it hints about the direction and a specific rectangle that the focus 7287 * is coming from. The rectangle can help give larger views a finer grained hint 7288 * about where focus is coming from, and therefore, where to show selection, or 7289 * forward focus change internally. 7290 * 7291 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7292 * false), or if it is focusable and it is not focusable in touch mode 7293 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7294 * 7295 * A View will not take focus if it is not visible. 7296 * 7297 * A View will not take focus if one of its parents has 7298 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7299 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7300 * 7301 * See also {@link #focusSearch(int)}, which is what you call to say that you 7302 * have focus, and you want your parent to look for the next one. 7303 * 7304 * You may wish to override this method if your custom {@link View} has an internal 7305 * {@link View} that it wishes to forward the request to. 7306 * 7307 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7308 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7309 * to give a finer grained hint about where focus is coming from. May be null 7310 * if there is no hint. 7311 * @return Whether this view or one of its descendants actually took focus. 7312 */ 7313 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7314 return requestFocusNoSearch(direction, previouslyFocusedRect); 7315 } 7316 7317 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7318 // need to be focusable 7319 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7320 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7321 return false; 7322 } 7323 7324 // need to be focusable in touch mode if in touch mode 7325 if (isInTouchMode() && 7326 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7327 return false; 7328 } 7329 7330 // need to not have any parents blocking us 7331 if (hasAncestorThatBlocksDescendantFocus()) { 7332 return false; 7333 } 7334 7335 handleFocusGainInternal(direction, previouslyFocusedRect); 7336 return true; 7337 } 7338 7339 /** 7340 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7341 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7342 * touch mode to request focus when they are touched. 7343 * 7344 * @return Whether this view or one of its descendants actually took focus. 7345 * 7346 * @see #isInTouchMode() 7347 * 7348 */ 7349 public final boolean requestFocusFromTouch() { 7350 // Leave touch mode if we need to 7351 if (isInTouchMode()) { 7352 ViewRootImpl viewRoot = getViewRootImpl(); 7353 if (viewRoot != null) { 7354 viewRoot.ensureTouchMode(false); 7355 } 7356 } 7357 return requestFocus(View.FOCUS_DOWN); 7358 } 7359 7360 /** 7361 * @return Whether any ancestor of this view blocks descendant focus. 7362 */ 7363 private boolean hasAncestorThatBlocksDescendantFocus() { 7364 ViewParent ancestor = mParent; 7365 while (ancestor instanceof ViewGroup) { 7366 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7367 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 7368 return true; 7369 } else { 7370 ancestor = vgAncestor.getParent(); 7371 } 7372 } 7373 return false; 7374 } 7375 7376 /** 7377 * Gets the mode for determining whether this View is important for accessibility 7378 * which is if it fires accessibility events and if it is reported to 7379 * accessibility services that query the screen. 7380 * 7381 * @return The mode for determining whether a View is important for accessibility. 7382 * 7383 * @attr ref android.R.styleable#View_importantForAccessibility 7384 * 7385 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7386 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7387 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7388 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7389 */ 7390 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7391 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7392 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7393 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7394 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7395 to = "noHideDescendants") 7396 }) 7397 public int getImportantForAccessibility() { 7398 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7399 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7400 } 7401 7402 /** 7403 * Sets the live region mode for this view. This indicates to accessibility 7404 * services whether they should automatically notify the user about changes 7405 * to the view's content description or text, or to the content descriptions 7406 * or text of the view's children (where applicable). 7407 * <p> 7408 * For example, in a login screen with a TextView that displays an "incorrect 7409 * password" notification, that view should be marked as a live region with 7410 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7411 * <p> 7412 * To disable change notifications for this view, use 7413 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7414 * mode for most views. 7415 * <p> 7416 * To indicate that the user should be notified of changes, use 7417 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7418 * <p> 7419 * If the view's changes should interrupt ongoing speech and notify the user 7420 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7421 * 7422 * @param mode The live region mode for this view, one of: 7423 * <ul> 7424 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7425 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7426 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7427 * </ul> 7428 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7429 */ 7430 public void setAccessibilityLiveRegion(int mode) { 7431 if (mode != getAccessibilityLiveRegion()) { 7432 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7433 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7434 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7435 notifyViewAccessibilityStateChangedIfNeeded( 7436 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7437 } 7438 } 7439 7440 /** 7441 * Gets the live region mode for this View. 7442 * 7443 * @return The live region mode for the view. 7444 * 7445 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7446 * 7447 * @see #setAccessibilityLiveRegion(int) 7448 */ 7449 public int getAccessibilityLiveRegion() { 7450 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7451 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7452 } 7453 7454 /** 7455 * Sets how to determine whether this view is important for accessibility 7456 * which is if it fires accessibility events and if it is reported to 7457 * accessibility services that query the screen. 7458 * 7459 * @param mode How to determine whether this view is important for accessibility. 7460 * 7461 * @attr ref android.R.styleable#View_importantForAccessibility 7462 * 7463 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7464 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7465 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7466 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7467 */ 7468 public void setImportantForAccessibility(int mode) { 7469 final int oldMode = getImportantForAccessibility(); 7470 if (mode != oldMode) { 7471 // If we're moving between AUTO and another state, we might not need 7472 // to send a subtree changed notification. We'll store the computed 7473 // importance, since we'll need to check it later to make sure. 7474 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7475 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7476 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7477 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7478 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7479 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7480 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7481 notifySubtreeAccessibilityStateChangedIfNeeded(); 7482 } else { 7483 notifyViewAccessibilityStateChangedIfNeeded( 7484 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7485 } 7486 } 7487 } 7488 7489 /** 7490 * Computes whether this view should be exposed for accessibility. In 7491 * general, views that are interactive or provide information are exposed 7492 * while views that serve only as containers are hidden. 7493 * <p> 7494 * If an ancestor of this view has importance 7495 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7496 * returns <code>false</code>. 7497 * <p> 7498 * Otherwise, the value is computed according to the view's 7499 * {@link #getImportantForAccessibility()} value: 7500 * <ol> 7501 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7502 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7503 * </code> 7504 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7505 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7506 * view satisfies any of the following: 7507 * <ul> 7508 * <li>Is actionable, e.g. {@link #isClickable()}, 7509 * {@link #isLongClickable()}, or {@link #isFocusable()} 7510 * <li>Has an {@link AccessibilityDelegate} 7511 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7512 * {@link OnKeyListener}, etc. 7513 * <li>Is an accessibility live region, e.g. 7514 * {@link #getAccessibilityLiveRegion()} is not 7515 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7516 * </ul> 7517 * </ol> 7518 * 7519 * @return Whether the view is exposed for accessibility. 7520 * @see #setImportantForAccessibility(int) 7521 * @see #getImportantForAccessibility() 7522 */ 7523 public boolean isImportantForAccessibility() { 7524 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7525 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7526 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7527 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7528 return false; 7529 } 7530 7531 // Check parent mode to ensure we're not hidden. 7532 ViewParent parent = mParent; 7533 while (parent instanceof View) { 7534 if (((View) parent).getImportantForAccessibility() 7535 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7536 return false; 7537 } 7538 parent = parent.getParent(); 7539 } 7540 7541 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7542 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7543 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7544 } 7545 7546 /** 7547 * Gets the parent for accessibility purposes. Note that the parent for 7548 * accessibility is not necessary the immediate parent. It is the first 7549 * predecessor that is important for accessibility. 7550 * 7551 * @return The parent for accessibility purposes. 7552 */ 7553 public ViewParent getParentForAccessibility() { 7554 if (mParent instanceof View) { 7555 View parentView = (View) mParent; 7556 if (parentView.includeForAccessibility()) { 7557 return mParent; 7558 } else { 7559 return mParent.getParentForAccessibility(); 7560 } 7561 } 7562 return null; 7563 } 7564 7565 /** 7566 * Adds the children of a given View for accessibility. Since some Views are 7567 * not important for accessibility the children for accessibility are not 7568 * necessarily direct children of the view, rather they are the first level of 7569 * descendants important for accessibility. 7570 * 7571 * @param children The list of children for accessibility. 7572 */ 7573 public void addChildrenForAccessibility(ArrayList<View> children) { 7574 7575 } 7576 7577 /** 7578 * Whether to regard this view for accessibility. A view is regarded for 7579 * accessibility if it is important for accessibility or the querying 7580 * accessibility service has explicitly requested that view not 7581 * important for accessibility are regarded. 7582 * 7583 * @return Whether to regard the view for accessibility. 7584 * 7585 * @hide 7586 */ 7587 public boolean includeForAccessibility() { 7588 if (mAttachInfo != null) { 7589 return (mAttachInfo.mAccessibilityFetchFlags 7590 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7591 || isImportantForAccessibility(); 7592 } 7593 return false; 7594 } 7595 7596 /** 7597 * Returns whether the View is considered actionable from 7598 * accessibility perspective. Such view are important for 7599 * accessibility. 7600 * 7601 * @return True if the view is actionable for accessibility. 7602 * 7603 * @hide 7604 */ 7605 public boolean isActionableForAccessibility() { 7606 return (isClickable() || isLongClickable() || isFocusable()); 7607 } 7608 7609 /** 7610 * Returns whether the View has registered callbacks which makes it 7611 * important for accessibility. 7612 * 7613 * @return True if the view is actionable for accessibility. 7614 */ 7615 private boolean hasListenersForAccessibility() { 7616 ListenerInfo info = getListenerInfo(); 7617 return mTouchDelegate != null || info.mOnKeyListener != null 7618 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7619 || info.mOnHoverListener != null || info.mOnDragListener != null; 7620 } 7621 7622 /** 7623 * Notifies that the accessibility state of this view changed. The change 7624 * is local to this view and does not represent structural changes such 7625 * as children and parent. For example, the view became focusable. The 7626 * notification is at at most once every 7627 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7628 * to avoid unnecessary load to the system. Also once a view has a pending 7629 * notification this method is a NOP until the notification has been sent. 7630 * 7631 * @hide 7632 */ 7633 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7634 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7635 return; 7636 } 7637 if (mSendViewStateChangedAccessibilityEvent == null) { 7638 mSendViewStateChangedAccessibilityEvent = 7639 new SendViewStateChangedAccessibilityEvent(); 7640 } 7641 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7642 } 7643 7644 /** 7645 * Notifies that the accessibility state of this view changed. The change 7646 * is *not* local to this view and does represent structural changes such 7647 * as children and parent. For example, the view size changed. The 7648 * notification is at at most once every 7649 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7650 * to avoid unnecessary load to the system. Also once a view has a pending 7651 * notifucation this method is a NOP until the notification has been sent. 7652 * 7653 * @hide 7654 */ 7655 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7656 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7657 return; 7658 } 7659 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7660 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7661 if (mParent != null) { 7662 try { 7663 mParent.notifySubtreeAccessibilityStateChanged( 7664 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7665 } catch (AbstractMethodError e) { 7666 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7667 " does not fully implement ViewParent", e); 7668 } 7669 } 7670 } 7671 } 7672 7673 /** 7674 * Reset the flag indicating the accessibility state of the subtree rooted 7675 * at this view changed. 7676 */ 7677 void resetSubtreeAccessibilityStateChanged() { 7678 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7679 } 7680 7681 /** 7682 * Performs the specified accessibility action on the view. For 7683 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7684 * <p> 7685 * If an {@link AccessibilityDelegate} has been specified via calling 7686 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7687 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7688 * is responsible for handling this call. 7689 * </p> 7690 * 7691 * @param action The action to perform. 7692 * @param arguments Optional action arguments. 7693 * @return Whether the action was performed. 7694 */ 7695 public boolean performAccessibilityAction(int action, Bundle arguments) { 7696 if (mAccessibilityDelegate != null) { 7697 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7698 } else { 7699 return performAccessibilityActionInternal(action, arguments); 7700 } 7701 } 7702 7703 /** 7704 * @see #performAccessibilityAction(int, Bundle) 7705 * 7706 * Note: Called from the default {@link AccessibilityDelegate}. 7707 */ 7708 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7709 switch (action) { 7710 case AccessibilityNodeInfo.ACTION_CLICK: { 7711 if (isClickable()) { 7712 performClick(); 7713 return true; 7714 } 7715 } break; 7716 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7717 if (isLongClickable()) { 7718 performLongClick(); 7719 return true; 7720 } 7721 } break; 7722 case AccessibilityNodeInfo.ACTION_FOCUS: { 7723 if (!hasFocus()) { 7724 // Get out of touch mode since accessibility 7725 // wants to move focus around. 7726 getViewRootImpl().ensureTouchMode(false); 7727 return requestFocus(); 7728 } 7729 } break; 7730 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7731 if (hasFocus()) { 7732 clearFocus(); 7733 return !isFocused(); 7734 } 7735 } break; 7736 case AccessibilityNodeInfo.ACTION_SELECT: { 7737 if (!isSelected()) { 7738 setSelected(true); 7739 return isSelected(); 7740 } 7741 } break; 7742 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7743 if (isSelected()) { 7744 setSelected(false); 7745 return !isSelected(); 7746 } 7747 } break; 7748 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7749 if (!isAccessibilityFocused()) { 7750 return requestAccessibilityFocus(); 7751 } 7752 } break; 7753 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7754 if (isAccessibilityFocused()) { 7755 clearAccessibilityFocus(); 7756 return true; 7757 } 7758 } break; 7759 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7760 if (arguments != null) { 7761 final int granularity = arguments.getInt( 7762 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7763 final boolean extendSelection = arguments.getBoolean( 7764 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7765 return traverseAtGranularity(granularity, true, extendSelection); 7766 } 7767 } break; 7768 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7769 if (arguments != null) { 7770 final int granularity = arguments.getInt( 7771 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7772 final boolean extendSelection = arguments.getBoolean( 7773 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7774 return traverseAtGranularity(granularity, false, extendSelection); 7775 } 7776 } break; 7777 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7778 CharSequence text = getIterableTextForAccessibility(); 7779 if (text == null) { 7780 return false; 7781 } 7782 final int start = (arguments != null) ? arguments.getInt( 7783 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7784 final int end = (arguments != null) ? arguments.getInt( 7785 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7786 // Only cursor position can be specified (selection length == 0) 7787 if ((getAccessibilitySelectionStart() != start 7788 || getAccessibilitySelectionEnd() != end) 7789 && (start == end)) { 7790 setAccessibilitySelection(start, end); 7791 notifyViewAccessibilityStateChangedIfNeeded( 7792 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7793 return true; 7794 } 7795 } break; 7796 } 7797 return false; 7798 } 7799 7800 private boolean traverseAtGranularity(int granularity, boolean forward, 7801 boolean extendSelection) { 7802 CharSequence text = getIterableTextForAccessibility(); 7803 if (text == null || text.length() == 0) { 7804 return false; 7805 } 7806 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7807 if (iterator == null) { 7808 return false; 7809 } 7810 int current = getAccessibilitySelectionEnd(); 7811 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7812 current = forward ? 0 : text.length(); 7813 } 7814 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7815 if (range == null) { 7816 return false; 7817 } 7818 final int segmentStart = range[0]; 7819 final int segmentEnd = range[1]; 7820 int selectionStart; 7821 int selectionEnd; 7822 if (extendSelection && isAccessibilitySelectionExtendable()) { 7823 selectionStart = getAccessibilitySelectionStart(); 7824 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7825 selectionStart = forward ? segmentStart : segmentEnd; 7826 } 7827 selectionEnd = forward ? segmentEnd : segmentStart; 7828 } else { 7829 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7830 } 7831 setAccessibilitySelection(selectionStart, selectionEnd); 7832 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7833 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7834 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7835 return true; 7836 } 7837 7838 /** 7839 * Gets the text reported for accessibility purposes. 7840 * 7841 * @return The accessibility text. 7842 * 7843 * @hide 7844 */ 7845 public CharSequence getIterableTextForAccessibility() { 7846 return getContentDescription(); 7847 } 7848 7849 /** 7850 * Gets whether accessibility selection can be extended. 7851 * 7852 * @return If selection is extensible. 7853 * 7854 * @hide 7855 */ 7856 public boolean isAccessibilitySelectionExtendable() { 7857 return false; 7858 } 7859 7860 /** 7861 * @hide 7862 */ 7863 public int getAccessibilitySelectionStart() { 7864 return mAccessibilityCursorPosition; 7865 } 7866 7867 /** 7868 * @hide 7869 */ 7870 public int getAccessibilitySelectionEnd() { 7871 return getAccessibilitySelectionStart(); 7872 } 7873 7874 /** 7875 * @hide 7876 */ 7877 public void setAccessibilitySelection(int start, int end) { 7878 if (start == end && end == mAccessibilityCursorPosition) { 7879 return; 7880 } 7881 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7882 mAccessibilityCursorPosition = start; 7883 } else { 7884 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7885 } 7886 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7887 } 7888 7889 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7890 int fromIndex, int toIndex) { 7891 if (mParent == null) { 7892 return; 7893 } 7894 AccessibilityEvent event = AccessibilityEvent.obtain( 7895 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7896 onInitializeAccessibilityEvent(event); 7897 onPopulateAccessibilityEvent(event); 7898 event.setFromIndex(fromIndex); 7899 event.setToIndex(toIndex); 7900 event.setAction(action); 7901 event.setMovementGranularity(granularity); 7902 mParent.requestSendAccessibilityEvent(this, event); 7903 } 7904 7905 /** 7906 * @hide 7907 */ 7908 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7909 switch (granularity) { 7910 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7911 CharSequence text = getIterableTextForAccessibility(); 7912 if (text != null && text.length() > 0) { 7913 CharacterTextSegmentIterator iterator = 7914 CharacterTextSegmentIterator.getInstance( 7915 mContext.getResources().getConfiguration().locale); 7916 iterator.initialize(text.toString()); 7917 return iterator; 7918 } 7919 } break; 7920 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7921 CharSequence text = getIterableTextForAccessibility(); 7922 if (text != null && text.length() > 0) { 7923 WordTextSegmentIterator iterator = 7924 WordTextSegmentIterator.getInstance( 7925 mContext.getResources().getConfiguration().locale); 7926 iterator.initialize(text.toString()); 7927 return iterator; 7928 } 7929 } break; 7930 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7931 CharSequence text = getIterableTextForAccessibility(); 7932 if (text != null && text.length() > 0) { 7933 ParagraphTextSegmentIterator iterator = 7934 ParagraphTextSegmentIterator.getInstance(); 7935 iterator.initialize(text.toString()); 7936 return iterator; 7937 } 7938 } break; 7939 } 7940 return null; 7941 } 7942 7943 /** 7944 * @hide 7945 */ 7946 public void dispatchStartTemporaryDetach() { 7947 onStartTemporaryDetach(); 7948 } 7949 7950 /** 7951 * This is called when a container is going to temporarily detach a child, with 7952 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7953 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7954 * {@link #onDetachedFromWindow()} when the container is done. 7955 */ 7956 public void onStartTemporaryDetach() { 7957 removeUnsetPressCallback(); 7958 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7959 } 7960 7961 /** 7962 * @hide 7963 */ 7964 public void dispatchFinishTemporaryDetach() { 7965 onFinishTemporaryDetach(); 7966 } 7967 7968 /** 7969 * Called after {@link #onStartTemporaryDetach} when the container is done 7970 * changing the view. 7971 */ 7972 public void onFinishTemporaryDetach() { 7973 } 7974 7975 /** 7976 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7977 * for this view's window. Returns null if the view is not currently attached 7978 * to the window. Normally you will not need to use this directly, but 7979 * just use the standard high-level event callbacks like 7980 * {@link #onKeyDown(int, KeyEvent)}. 7981 */ 7982 public KeyEvent.DispatcherState getKeyDispatcherState() { 7983 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7984 } 7985 7986 /** 7987 * Dispatch a key event before it is processed by any input method 7988 * associated with the view hierarchy. This can be used to intercept 7989 * key events in special situations before the IME consumes them; a 7990 * typical example would be handling the BACK key to update the application's 7991 * UI instead of allowing the IME to see it and close itself. 7992 * 7993 * @param event The key event to be dispatched. 7994 * @return True if the event was handled, false otherwise. 7995 */ 7996 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7997 return onKeyPreIme(event.getKeyCode(), event); 7998 } 7999 8000 /** 8001 * Dispatch a key event to the next view on the focus path. This path runs 8002 * from the top of the view tree down to the currently focused view. If this 8003 * view has focus, it will dispatch to itself. Otherwise it will dispatch 8004 * the next node down the focus path. This method also fires any key 8005 * listeners. 8006 * 8007 * @param event The key event to be dispatched. 8008 * @return True if the event was handled, false otherwise. 8009 */ 8010 public boolean dispatchKeyEvent(KeyEvent event) { 8011 if (mInputEventConsistencyVerifier != null) { 8012 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 8013 } 8014 8015 // Give any attached key listener a first crack at the event. 8016 //noinspection SimplifiableIfStatement 8017 ListenerInfo li = mListenerInfo; 8018 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8019 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8020 return true; 8021 } 8022 8023 if (event.dispatch(this, mAttachInfo != null 8024 ? mAttachInfo.mKeyDispatchState : null, this)) { 8025 return true; 8026 } 8027 8028 if (mInputEventConsistencyVerifier != null) { 8029 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8030 } 8031 return false; 8032 } 8033 8034 /** 8035 * Dispatches a key shortcut event. 8036 * 8037 * @param event The key event to be dispatched. 8038 * @return True if the event was handled by the view, false otherwise. 8039 */ 8040 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8041 return onKeyShortcut(event.getKeyCode(), event); 8042 } 8043 8044 /** 8045 * Pass the touch screen motion event down to the target view, or this 8046 * view if it is the target. 8047 * 8048 * @param event The motion event to be dispatched. 8049 * @return True if the event was handled by the view, false otherwise. 8050 */ 8051 public boolean dispatchTouchEvent(MotionEvent event) { 8052 boolean result = false; 8053 8054 if (mInputEventConsistencyVerifier != null) { 8055 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8056 } 8057 8058 final int actionMasked = event.getActionMasked(); 8059 if (actionMasked == MotionEvent.ACTION_DOWN) { 8060 // Defensive cleanup for new gesture 8061 stopNestedScroll(); 8062 } 8063 8064 if (onFilterTouchEventForSecurity(event)) { 8065 //noinspection SimplifiableIfStatement 8066 ListenerInfo li = mListenerInfo; 8067 if (li != null && li.mOnTouchListener != null 8068 && (mViewFlags & ENABLED_MASK) == ENABLED 8069 && li.mOnTouchListener.onTouch(this, event)) { 8070 result = true; 8071 } 8072 8073 if (!result && onTouchEvent(event)) { 8074 result = true; 8075 } 8076 } 8077 8078 if (!result && mInputEventConsistencyVerifier != null) { 8079 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8080 } 8081 8082 // Clean up after nested scrolls if this is the end of a gesture; 8083 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8084 // of the gesture. 8085 if (actionMasked == MotionEvent.ACTION_UP || 8086 actionMasked == MotionEvent.ACTION_CANCEL || 8087 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8088 stopNestedScroll(); 8089 } 8090 8091 return result; 8092 } 8093 8094 /** 8095 * Filter the touch event to apply security policies. 8096 * 8097 * @param event The motion event to be filtered. 8098 * @return True if the event should be dispatched, false if the event should be dropped. 8099 * 8100 * @see #getFilterTouchesWhenObscured 8101 */ 8102 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8103 //noinspection RedundantIfStatement 8104 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8105 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8106 // Window is obscured, drop this touch. 8107 return false; 8108 } 8109 return true; 8110 } 8111 8112 /** 8113 * Pass a trackball motion event down to the focused view. 8114 * 8115 * @param event The motion event to be dispatched. 8116 * @return True if the event was handled by the view, false otherwise. 8117 */ 8118 public boolean dispatchTrackballEvent(MotionEvent event) { 8119 if (mInputEventConsistencyVerifier != null) { 8120 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8121 } 8122 8123 return onTrackballEvent(event); 8124 } 8125 8126 /** 8127 * Dispatch a generic motion event. 8128 * <p> 8129 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8130 * are delivered to the view under the pointer. All other generic motion events are 8131 * delivered to the focused view. Hover events are handled specially and are delivered 8132 * to {@link #onHoverEvent(MotionEvent)}. 8133 * </p> 8134 * 8135 * @param event The motion event to be dispatched. 8136 * @return True if the event was handled by the view, false otherwise. 8137 */ 8138 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8139 if (mInputEventConsistencyVerifier != null) { 8140 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8141 } 8142 8143 final int source = event.getSource(); 8144 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8145 final int action = event.getAction(); 8146 if (action == MotionEvent.ACTION_HOVER_ENTER 8147 || action == MotionEvent.ACTION_HOVER_MOVE 8148 || action == MotionEvent.ACTION_HOVER_EXIT) { 8149 if (dispatchHoverEvent(event)) { 8150 return true; 8151 } 8152 } else if (dispatchGenericPointerEvent(event)) { 8153 return true; 8154 } 8155 } else if (dispatchGenericFocusedEvent(event)) { 8156 return true; 8157 } 8158 8159 if (dispatchGenericMotionEventInternal(event)) { 8160 return true; 8161 } 8162 8163 if (mInputEventConsistencyVerifier != null) { 8164 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8165 } 8166 return false; 8167 } 8168 8169 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8170 //noinspection SimplifiableIfStatement 8171 ListenerInfo li = mListenerInfo; 8172 if (li != null && li.mOnGenericMotionListener != null 8173 && (mViewFlags & ENABLED_MASK) == ENABLED 8174 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8175 return true; 8176 } 8177 8178 if (onGenericMotionEvent(event)) { 8179 return true; 8180 } 8181 8182 if (mInputEventConsistencyVerifier != null) { 8183 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8184 } 8185 return false; 8186 } 8187 8188 /** 8189 * Dispatch a hover event. 8190 * <p> 8191 * Do not call this method directly. 8192 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8193 * </p> 8194 * 8195 * @param event The motion event to be dispatched. 8196 * @return True if the event was handled by the view, false otherwise. 8197 */ 8198 protected boolean dispatchHoverEvent(MotionEvent event) { 8199 ListenerInfo li = mListenerInfo; 8200 //noinspection SimplifiableIfStatement 8201 if (li != null && li.mOnHoverListener != null 8202 && (mViewFlags & ENABLED_MASK) == ENABLED 8203 && li.mOnHoverListener.onHover(this, event)) { 8204 return true; 8205 } 8206 8207 return onHoverEvent(event); 8208 } 8209 8210 /** 8211 * Returns true if the view has a child to which it has recently sent 8212 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8213 * it does not have a hovered child, then it must be the innermost hovered view. 8214 * @hide 8215 */ 8216 protected boolean hasHoveredChild() { 8217 return false; 8218 } 8219 8220 /** 8221 * Dispatch a generic motion event to the view under the first pointer. 8222 * <p> 8223 * Do not call this method directly. 8224 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8225 * </p> 8226 * 8227 * @param event The motion event to be dispatched. 8228 * @return True if the event was handled by the view, false otherwise. 8229 */ 8230 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8231 return false; 8232 } 8233 8234 /** 8235 * Dispatch a generic motion event to the currently focused view. 8236 * <p> 8237 * Do not call this method directly. 8238 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 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 */ 8244 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8245 return false; 8246 } 8247 8248 /** 8249 * Dispatch a pointer event. 8250 * <p> 8251 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8252 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8253 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8254 * and should not be expected to handle other pointing device features. 8255 * </p> 8256 * 8257 * @param event The motion event to be dispatched. 8258 * @return True if the event was handled by the view, false otherwise. 8259 * @hide 8260 */ 8261 public final boolean dispatchPointerEvent(MotionEvent event) { 8262 if (event.isTouchEvent()) { 8263 return dispatchTouchEvent(event); 8264 } else { 8265 return dispatchGenericMotionEvent(event); 8266 } 8267 } 8268 8269 /** 8270 * Called when the window containing this view gains or loses window focus. 8271 * ViewGroups should override to route to their children. 8272 * 8273 * @param hasFocus True if the window containing this view now has focus, 8274 * false otherwise. 8275 */ 8276 public void dispatchWindowFocusChanged(boolean hasFocus) { 8277 onWindowFocusChanged(hasFocus); 8278 } 8279 8280 /** 8281 * Called when the window containing this view gains or loses focus. Note 8282 * that this is separate from view focus: to receive key events, both 8283 * your view and its window must have focus. If a window is displayed 8284 * on top of yours that takes input focus, then your own window will lose 8285 * focus but the view focus will remain unchanged. 8286 * 8287 * @param hasWindowFocus True if the window containing this view now has 8288 * focus, false otherwise. 8289 */ 8290 public void onWindowFocusChanged(boolean hasWindowFocus) { 8291 InputMethodManager imm = InputMethodManager.peekInstance(); 8292 if (!hasWindowFocus) { 8293 if (isPressed()) { 8294 setPressed(false); 8295 } 8296 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8297 imm.focusOut(this); 8298 } 8299 removeLongPressCallback(); 8300 removeTapCallback(); 8301 onFocusLost(); 8302 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8303 imm.focusIn(this); 8304 } 8305 refreshDrawableState(); 8306 } 8307 8308 /** 8309 * Returns true if this view is in a window that currently has window focus. 8310 * Note that this is not the same as the view itself having focus. 8311 * 8312 * @return True if this view is in a window that currently has window focus. 8313 */ 8314 public boolean hasWindowFocus() { 8315 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8316 } 8317 8318 /** 8319 * Dispatch a view visibility change down the view hierarchy. 8320 * ViewGroups should override to route to their children. 8321 * @param changedView The view whose visibility changed. Could be 'this' or 8322 * an ancestor view. 8323 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8324 * {@link #INVISIBLE} or {@link #GONE}. 8325 */ 8326 protected void dispatchVisibilityChanged(@NonNull View changedView, 8327 @Visibility int visibility) { 8328 onVisibilityChanged(changedView, visibility); 8329 } 8330 8331 /** 8332 * Called when the visibility of the view or an ancestor of the view is changed. 8333 * @param changedView The view whose visibility changed. Could be 'this' or 8334 * an ancestor view. 8335 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8336 * {@link #INVISIBLE} or {@link #GONE}. 8337 */ 8338 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8339 if (visibility == VISIBLE) { 8340 if (mAttachInfo != null) { 8341 initialAwakenScrollBars(); 8342 } else { 8343 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8344 } 8345 } 8346 } 8347 8348 /** 8349 * Dispatch a hint about whether this view is displayed. For instance, when 8350 * a View moves out of the screen, it might receives a display hint indicating 8351 * the view is not displayed. Applications should not <em>rely</em> on this hint 8352 * as there is no guarantee that they will receive one. 8353 * 8354 * @param hint A hint about whether or not this view is displayed: 8355 * {@link #VISIBLE} or {@link #INVISIBLE}. 8356 */ 8357 public void dispatchDisplayHint(@Visibility int hint) { 8358 onDisplayHint(hint); 8359 } 8360 8361 /** 8362 * Gives this view a hint about whether is displayed or not. For instance, when 8363 * a View moves out of the screen, it might receives a display hint indicating 8364 * the view is not displayed. Applications should not <em>rely</em> on this hint 8365 * as there is no guarantee that they will receive one. 8366 * 8367 * @param hint A hint about whether or not this view is displayed: 8368 * {@link #VISIBLE} or {@link #INVISIBLE}. 8369 */ 8370 protected void onDisplayHint(@Visibility int hint) { 8371 } 8372 8373 /** 8374 * Dispatch a window visibility change down the view hierarchy. 8375 * ViewGroups should override to route to their children. 8376 * 8377 * @param visibility The new visibility of the window. 8378 * 8379 * @see #onWindowVisibilityChanged(int) 8380 */ 8381 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8382 onWindowVisibilityChanged(visibility); 8383 } 8384 8385 /** 8386 * Called when the window containing has change its visibility 8387 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8388 * that this tells you whether or not your window is being made visible 8389 * to the window manager; this does <em>not</em> tell you whether or not 8390 * your window is obscured by other windows on the screen, even if it 8391 * is itself visible. 8392 * 8393 * @param visibility The new visibility of the window. 8394 */ 8395 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8396 if (visibility == VISIBLE) { 8397 initialAwakenScrollBars(); 8398 } 8399 } 8400 8401 /** 8402 * Returns the current visibility of the window this view is attached to 8403 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8404 * 8405 * @return Returns the current visibility of the view's window. 8406 */ 8407 @Visibility 8408 public int getWindowVisibility() { 8409 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8410 } 8411 8412 /** 8413 * Retrieve the overall visible display size in which the window this view is 8414 * attached to has been positioned in. This takes into account screen 8415 * decorations above the window, for both cases where the window itself 8416 * is being position inside of them or the window is being placed under 8417 * then and covered insets are used for the window to position its content 8418 * inside. In effect, this tells you the available area where content can 8419 * be placed and remain visible to users. 8420 * 8421 * <p>This function requires an IPC back to the window manager to retrieve 8422 * the requested information, so should not be used in performance critical 8423 * code like drawing. 8424 * 8425 * @param outRect Filled in with the visible display frame. If the view 8426 * is not attached to a window, this is simply the raw display size. 8427 */ 8428 public void getWindowVisibleDisplayFrame(Rect outRect) { 8429 if (mAttachInfo != null) { 8430 try { 8431 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8432 } catch (RemoteException e) { 8433 return; 8434 } 8435 // XXX This is really broken, and probably all needs to be done 8436 // in the window manager, and we need to know more about whether 8437 // we want the area behind or in front of the IME. 8438 final Rect insets = mAttachInfo.mVisibleInsets; 8439 outRect.left += insets.left; 8440 outRect.top += insets.top; 8441 outRect.right -= insets.right; 8442 outRect.bottom -= insets.bottom; 8443 return; 8444 } 8445 // The view is not attached to a display so we don't have a context. 8446 // Make a best guess about the display size. 8447 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8448 d.getRectSize(outRect); 8449 } 8450 8451 /** 8452 * Dispatch a notification about a resource configuration change down 8453 * the view hierarchy. 8454 * ViewGroups should override to route to their children. 8455 * 8456 * @param newConfig The new resource configuration. 8457 * 8458 * @see #onConfigurationChanged(android.content.res.Configuration) 8459 */ 8460 public void dispatchConfigurationChanged(Configuration newConfig) { 8461 onConfigurationChanged(newConfig); 8462 } 8463 8464 /** 8465 * Called when the current configuration of the resources being used 8466 * by the application have changed. You can use this to decide when 8467 * to reload resources that can changed based on orientation and other 8468 * configuration characterstics. You only need to use this if you are 8469 * not relying on the normal {@link android.app.Activity} mechanism of 8470 * recreating the activity instance upon a configuration change. 8471 * 8472 * @param newConfig The new resource configuration. 8473 */ 8474 protected void onConfigurationChanged(Configuration newConfig) { 8475 } 8476 8477 /** 8478 * Private function to aggregate all per-view attributes in to the view 8479 * root. 8480 */ 8481 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8482 performCollectViewAttributes(attachInfo, visibility); 8483 } 8484 8485 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8486 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8487 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8488 attachInfo.mKeepScreenOn = true; 8489 } 8490 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8491 ListenerInfo li = mListenerInfo; 8492 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8493 attachInfo.mHasSystemUiListeners = true; 8494 } 8495 } 8496 } 8497 8498 void needGlobalAttributesUpdate(boolean force) { 8499 final AttachInfo ai = mAttachInfo; 8500 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8501 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8502 || ai.mHasSystemUiListeners) { 8503 ai.mRecomputeGlobalAttributes = true; 8504 } 8505 } 8506 } 8507 8508 /** 8509 * Returns whether the device is currently in touch mode. Touch mode is entered 8510 * once the user begins interacting with the device by touch, and affects various 8511 * things like whether focus is always visible to the user. 8512 * 8513 * @return Whether the device is in touch mode. 8514 */ 8515 @ViewDebug.ExportedProperty 8516 public boolean isInTouchMode() { 8517 if (mAttachInfo != null) { 8518 return mAttachInfo.mInTouchMode; 8519 } else { 8520 return ViewRootImpl.isInTouchMode(); 8521 } 8522 } 8523 8524 /** 8525 * Returns the context the view is running in, through which it can 8526 * access the current theme, resources, etc. 8527 * 8528 * @return The view's Context. 8529 */ 8530 @ViewDebug.CapturedViewProperty 8531 public final Context getContext() { 8532 return mContext; 8533 } 8534 8535 /** 8536 * Handle a key event before it is processed by any input method 8537 * associated with the view hierarchy. This can be used to intercept 8538 * key events in special situations before the IME consumes them; a 8539 * typical example would be handling the BACK key to update the application's 8540 * UI instead of allowing the IME to see it and close itself. 8541 * 8542 * @param keyCode The value in event.getKeyCode(). 8543 * @param event Description of the key event. 8544 * @return If you handled the event, return true. If you want to allow the 8545 * event to be handled by the next receiver, return false. 8546 */ 8547 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8548 return false; 8549 } 8550 8551 /** 8552 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8553 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8554 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8555 * is released, if the view is enabled and clickable. 8556 * 8557 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8558 * although some may elect to do so in some situations. Do not rely on this to 8559 * catch software key presses. 8560 * 8561 * @param keyCode A key code that represents the button pressed, from 8562 * {@link android.view.KeyEvent}. 8563 * @param event The KeyEvent object that defines the button action. 8564 */ 8565 public boolean onKeyDown(int keyCode, KeyEvent event) { 8566 boolean result = false; 8567 8568 if (KeyEvent.isConfirmKey(keyCode)) { 8569 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8570 return true; 8571 } 8572 // Long clickable items don't necessarily have to be clickable 8573 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8574 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8575 (event.getRepeatCount() == 0)) { 8576 setPressed(true); 8577 checkForLongClick(0); 8578 return true; 8579 } 8580 } 8581 return result; 8582 } 8583 8584 /** 8585 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8586 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8587 * the event). 8588 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8589 * although some may elect to do so in some situations. Do not rely on this to 8590 * catch software key presses. 8591 */ 8592 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8593 return false; 8594 } 8595 8596 /** 8597 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8598 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8599 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8600 * {@link KeyEvent#KEYCODE_ENTER} is released. 8601 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8602 * although some may elect to do so in some situations. Do not rely on this to 8603 * catch software key presses. 8604 * 8605 * @param keyCode A key code that represents the button pressed, from 8606 * {@link android.view.KeyEvent}. 8607 * @param event The KeyEvent object that defines the button action. 8608 */ 8609 public boolean onKeyUp(int keyCode, KeyEvent event) { 8610 if (KeyEvent.isConfirmKey(keyCode)) { 8611 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8612 return true; 8613 } 8614 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8615 setPressed(false); 8616 8617 if (!mHasPerformedLongPress) { 8618 // This is a tap, so remove the longpress check 8619 removeLongPressCallback(); 8620 return performClick(); 8621 } 8622 } 8623 } 8624 return false; 8625 } 8626 8627 /** 8628 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8629 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8630 * the event). 8631 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8632 * although some may elect to do so in some situations. Do not rely on this to 8633 * catch software key presses. 8634 * 8635 * @param keyCode A key code that represents the button pressed, from 8636 * {@link android.view.KeyEvent}. 8637 * @param repeatCount The number of times the action was made. 8638 * @param event The KeyEvent object that defines the button action. 8639 */ 8640 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8641 return false; 8642 } 8643 8644 /** 8645 * Called on the focused view when a key shortcut event is not handled. 8646 * Override this method to implement local key shortcuts for the View. 8647 * Key shortcuts can also be implemented by setting the 8648 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8649 * 8650 * @param keyCode The value in event.getKeyCode(). 8651 * @param event Description of the key event. 8652 * @return If you handled the event, return true. If you want to allow the 8653 * event to be handled by the next receiver, return false. 8654 */ 8655 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8656 return false; 8657 } 8658 8659 /** 8660 * Check whether the called view is a text editor, in which case it 8661 * would make sense to automatically display a soft input window for 8662 * it. Subclasses should override this if they implement 8663 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8664 * a call on that method would return a non-null InputConnection, and 8665 * they are really a first-class editor that the user would normally 8666 * start typing on when the go into a window containing your view. 8667 * 8668 * <p>The default implementation always returns false. This does 8669 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8670 * will not be called or the user can not otherwise perform edits on your 8671 * view; it is just a hint to the system that this is not the primary 8672 * purpose of this view. 8673 * 8674 * @return Returns true if this view is a text editor, else false. 8675 */ 8676 public boolean onCheckIsTextEditor() { 8677 return false; 8678 } 8679 8680 /** 8681 * Create a new InputConnection for an InputMethod to interact 8682 * with the view. The default implementation returns null, since it doesn't 8683 * support input methods. You can override this to implement such support. 8684 * This is only needed for views that take focus and text input. 8685 * 8686 * <p>When implementing this, you probably also want to implement 8687 * {@link #onCheckIsTextEditor()} to indicate you will return a 8688 * non-null InputConnection.</p> 8689 * 8690 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 8691 * object correctly and in its entirety, so that the connected IME can rely 8692 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 8693 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 8694 * must be filled in with the correct cursor position for IMEs to work correctly 8695 * with your application.</p> 8696 * 8697 * @param outAttrs Fill in with attribute information about the connection. 8698 */ 8699 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8700 return null; 8701 } 8702 8703 /** 8704 * Called by the {@link android.view.inputmethod.InputMethodManager} 8705 * when a view who is not the current 8706 * input connection target is trying to make a call on the manager. The 8707 * default implementation returns false; you can override this to return 8708 * true for certain views if you are performing InputConnection proxying 8709 * to them. 8710 * @param view The View that is making the InputMethodManager call. 8711 * @return Return true to allow the call, false to reject. 8712 */ 8713 public boolean checkInputConnectionProxy(View view) { 8714 return false; 8715 } 8716 8717 /** 8718 * Show the context menu for this view. It is not safe to hold on to the 8719 * menu after returning from this method. 8720 * 8721 * You should normally not overload this method. Overload 8722 * {@link #onCreateContextMenu(ContextMenu)} or define an 8723 * {@link OnCreateContextMenuListener} to add items to the context menu. 8724 * 8725 * @param menu The context menu to populate 8726 */ 8727 public void createContextMenu(ContextMenu menu) { 8728 ContextMenuInfo menuInfo = getContextMenuInfo(); 8729 8730 // Sets the current menu info so all items added to menu will have 8731 // my extra info set. 8732 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8733 8734 onCreateContextMenu(menu); 8735 ListenerInfo li = mListenerInfo; 8736 if (li != null && li.mOnCreateContextMenuListener != null) { 8737 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8738 } 8739 8740 // Clear the extra information so subsequent items that aren't mine don't 8741 // have my extra info. 8742 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8743 8744 if (mParent != null) { 8745 mParent.createContextMenu(menu); 8746 } 8747 } 8748 8749 /** 8750 * Views should implement this if they have extra information to associate 8751 * with the context menu. The return result is supplied as a parameter to 8752 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8753 * callback. 8754 * 8755 * @return Extra information about the item for which the context menu 8756 * should be shown. This information will vary across different 8757 * subclasses of View. 8758 */ 8759 protected ContextMenuInfo getContextMenuInfo() { 8760 return null; 8761 } 8762 8763 /** 8764 * Views should implement this if the view itself is going to add items to 8765 * the context menu. 8766 * 8767 * @param menu the context menu to populate 8768 */ 8769 protected void onCreateContextMenu(ContextMenu menu) { 8770 } 8771 8772 /** 8773 * Implement this method to handle trackball motion events. The 8774 * <em>relative</em> movement of the trackball since the last event 8775 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8776 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8777 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8778 * they will often be fractional values, representing the more fine-grained 8779 * movement information available from a trackball). 8780 * 8781 * @param event The motion event. 8782 * @return True if the event was handled, false otherwise. 8783 */ 8784 public boolean onTrackballEvent(MotionEvent event) { 8785 return false; 8786 } 8787 8788 /** 8789 * Implement this method to handle generic motion events. 8790 * <p> 8791 * Generic motion events describe joystick movements, mouse hovers, track pad 8792 * touches, scroll wheel movements and other input events. The 8793 * {@link MotionEvent#getSource() source} of the motion event specifies 8794 * the class of input that was received. Implementations of this method 8795 * must examine the bits in the source before processing the event. 8796 * The following code example shows how this is done. 8797 * </p><p> 8798 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8799 * are delivered to the view under the pointer. All other generic motion events are 8800 * delivered to the focused view. 8801 * </p> 8802 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8803 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8804 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8805 * // process the joystick movement... 8806 * return true; 8807 * } 8808 * } 8809 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8810 * switch (event.getAction()) { 8811 * case MotionEvent.ACTION_HOVER_MOVE: 8812 * // process the mouse hover movement... 8813 * return true; 8814 * case MotionEvent.ACTION_SCROLL: 8815 * // process the scroll wheel movement... 8816 * return true; 8817 * } 8818 * } 8819 * return super.onGenericMotionEvent(event); 8820 * }</pre> 8821 * 8822 * @param event The generic motion event being processed. 8823 * @return True if the event was handled, false otherwise. 8824 */ 8825 public boolean onGenericMotionEvent(MotionEvent event) { 8826 return false; 8827 } 8828 8829 /** 8830 * Implement this method to handle hover events. 8831 * <p> 8832 * This method is called whenever a pointer is hovering into, over, or out of the 8833 * bounds of a view and the view is not currently being touched. 8834 * Hover events are represented as pointer events with action 8835 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8836 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8837 * </p> 8838 * <ul> 8839 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8840 * when the pointer enters the bounds of the view.</li> 8841 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8842 * when the pointer has already entered the bounds of the view and has moved.</li> 8843 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8844 * when the pointer has exited the bounds of the view or when the pointer is 8845 * about to go down due to a button click, tap, or similar user action that 8846 * causes the view to be touched.</li> 8847 * </ul> 8848 * <p> 8849 * The view should implement this method to return true to indicate that it is 8850 * handling the hover event, such as by changing its drawable state. 8851 * </p><p> 8852 * The default implementation calls {@link #setHovered} to update the hovered state 8853 * of the view when a hover enter or hover exit event is received, if the view 8854 * is enabled and is clickable. The default implementation also sends hover 8855 * accessibility events. 8856 * </p> 8857 * 8858 * @param event The motion event that describes the hover. 8859 * @return True if the view handled the hover event. 8860 * 8861 * @see #isHovered 8862 * @see #setHovered 8863 * @see #onHoverChanged 8864 */ 8865 public boolean onHoverEvent(MotionEvent event) { 8866 // The root view may receive hover (or touch) events that are outside the bounds of 8867 // the window. This code ensures that we only send accessibility events for 8868 // hovers that are actually within the bounds of the root view. 8869 final int action = event.getActionMasked(); 8870 if (!mSendingHoverAccessibilityEvents) { 8871 if ((action == MotionEvent.ACTION_HOVER_ENTER 8872 || action == MotionEvent.ACTION_HOVER_MOVE) 8873 && !hasHoveredChild() 8874 && pointInView(event.getX(), event.getY())) { 8875 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8876 mSendingHoverAccessibilityEvents = true; 8877 } 8878 } else { 8879 if (action == MotionEvent.ACTION_HOVER_EXIT 8880 || (action == MotionEvent.ACTION_MOVE 8881 && !pointInView(event.getX(), event.getY()))) { 8882 mSendingHoverAccessibilityEvents = false; 8883 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8884 } 8885 } 8886 8887 if (isHoverable()) { 8888 switch (action) { 8889 case MotionEvent.ACTION_HOVER_ENTER: 8890 setHovered(true); 8891 break; 8892 case MotionEvent.ACTION_HOVER_EXIT: 8893 setHovered(false); 8894 break; 8895 } 8896 8897 // Dispatch the event to onGenericMotionEvent before returning true. 8898 // This is to provide compatibility with existing applications that 8899 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8900 // break because of the new default handling for hoverable views 8901 // in onHoverEvent. 8902 // Note that onGenericMotionEvent will be called by default when 8903 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8904 dispatchGenericMotionEventInternal(event); 8905 // The event was already handled by calling setHovered(), so always 8906 // return true. 8907 return true; 8908 } 8909 8910 return false; 8911 } 8912 8913 /** 8914 * Returns true if the view should handle {@link #onHoverEvent} 8915 * by calling {@link #setHovered} to change its hovered state. 8916 * 8917 * @return True if the view is hoverable. 8918 */ 8919 private boolean isHoverable() { 8920 final int viewFlags = mViewFlags; 8921 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8922 return false; 8923 } 8924 8925 return (viewFlags & CLICKABLE) == CLICKABLE 8926 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8927 } 8928 8929 /** 8930 * Returns true if the view is currently hovered. 8931 * 8932 * @return True if the view is currently hovered. 8933 * 8934 * @see #setHovered 8935 * @see #onHoverChanged 8936 */ 8937 @ViewDebug.ExportedProperty 8938 public boolean isHovered() { 8939 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8940 } 8941 8942 /** 8943 * Sets whether the view is currently hovered. 8944 * <p> 8945 * Calling this method also changes the drawable state of the view. This 8946 * enables the view to react to hover by using different drawable resources 8947 * to change its appearance. 8948 * </p><p> 8949 * The {@link #onHoverChanged} method is called when the hovered state changes. 8950 * </p> 8951 * 8952 * @param hovered True if the view is hovered. 8953 * 8954 * @see #isHovered 8955 * @see #onHoverChanged 8956 */ 8957 public void setHovered(boolean hovered) { 8958 if (hovered) { 8959 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8960 mPrivateFlags |= PFLAG_HOVERED; 8961 refreshDrawableState(); 8962 onHoverChanged(true); 8963 } 8964 } else { 8965 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8966 mPrivateFlags &= ~PFLAG_HOVERED; 8967 refreshDrawableState(); 8968 onHoverChanged(false); 8969 } 8970 } 8971 } 8972 8973 /** 8974 * Implement this method to handle hover state changes. 8975 * <p> 8976 * This method is called whenever the hover state changes as a result of a 8977 * call to {@link #setHovered}. 8978 * </p> 8979 * 8980 * @param hovered The current hover state, as returned by {@link #isHovered}. 8981 * 8982 * @see #isHovered 8983 * @see #setHovered 8984 */ 8985 public void onHoverChanged(boolean hovered) { 8986 } 8987 8988 /** 8989 * Implement this method to handle touch screen motion events. 8990 * <p> 8991 * If this method is used to detect click actions, it is recommended that 8992 * the actions be performed by implementing and calling 8993 * {@link #performClick()}. This will ensure consistent system behavior, 8994 * including: 8995 * <ul> 8996 * <li>obeying click sound preferences 8997 * <li>dispatching OnClickListener calls 8998 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 8999 * accessibility features are enabled 9000 * </ul> 9001 * 9002 * @param event The motion event. 9003 * @return True if the event was handled, false otherwise. 9004 */ 9005 public boolean onTouchEvent(MotionEvent event) { 9006 final float x = event.getX(); 9007 final float y = event.getY(); 9008 final int viewFlags = mViewFlags; 9009 9010 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9011 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9012 setPressed(false); 9013 } 9014 // A disabled view that is clickable still consumes the touch 9015 // events, it just doesn't respond to them. 9016 return (((viewFlags & CLICKABLE) == CLICKABLE || 9017 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9018 } 9019 9020 if (mTouchDelegate != null) { 9021 if (mTouchDelegate.onTouchEvent(event)) { 9022 return true; 9023 } 9024 } 9025 9026 if (((viewFlags & CLICKABLE) == CLICKABLE || 9027 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9028 switch (event.getAction()) { 9029 case MotionEvent.ACTION_UP: 9030 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9031 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9032 // take focus if we don't have it already and we should in 9033 // touch mode. 9034 boolean focusTaken = false; 9035 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9036 focusTaken = requestFocus(); 9037 } 9038 9039 if (prepressed) { 9040 // The button is being released before we actually 9041 // showed it as pressed. Make it show the pressed 9042 // state now (before scheduling the click) to ensure 9043 // the user sees it. 9044 setPressed(true, x, y); 9045 } 9046 9047 if (!mHasPerformedLongPress) { 9048 // This is a tap, so remove the longpress check 9049 removeLongPressCallback(); 9050 9051 // Only perform take click actions if we were in the pressed state 9052 if (!focusTaken) { 9053 // Use a Runnable and post this rather than calling 9054 // performClick directly. This lets other visual state 9055 // of the view update before click actions start. 9056 if (mPerformClick == null) { 9057 mPerformClick = new PerformClick(); 9058 } 9059 if (!post(mPerformClick)) { 9060 performClick(); 9061 } 9062 } 9063 } 9064 9065 if (mUnsetPressedState == null) { 9066 mUnsetPressedState = new UnsetPressedState(); 9067 } 9068 9069 if (prepressed) { 9070 postDelayed(mUnsetPressedState, 9071 ViewConfiguration.getPressedStateDuration()); 9072 } else if (!post(mUnsetPressedState)) { 9073 // If the post failed, unpress right now 9074 mUnsetPressedState.run(); 9075 } 9076 9077 removeTapCallback(); 9078 } 9079 break; 9080 9081 case MotionEvent.ACTION_DOWN: 9082 mHasPerformedLongPress = false; 9083 9084 if (performButtonActionOnTouchDown(event)) { 9085 break; 9086 } 9087 9088 // Walk up the hierarchy to determine if we're inside a scrolling container. 9089 boolean isInScrollingContainer = isInScrollingContainer(); 9090 9091 // For views inside a scrolling container, delay the pressed feedback for 9092 // a short period in case this is a scroll. 9093 if (isInScrollingContainer) { 9094 mPrivateFlags |= PFLAG_PREPRESSED; 9095 if (mPendingCheckForTap == null) { 9096 mPendingCheckForTap = new CheckForTap(); 9097 } 9098 mPendingCheckForTap.x = event.getX(); 9099 mPendingCheckForTap.y = event.getY(); 9100 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9101 } else { 9102 // Not inside a scrolling container, so show the feedback right away 9103 setHotspot(x, y); 9104 setPressed(true); 9105 checkForLongClick(0); 9106 } 9107 break; 9108 9109 case MotionEvent.ACTION_CANCEL: 9110 setPressed(false); 9111 removeTapCallback(); 9112 removeLongPressCallback(); 9113 break; 9114 9115 case MotionEvent.ACTION_MOVE: 9116 setHotspot(x, y); 9117 9118 // Be lenient about moving outside of buttons 9119 if (!pointInView(x, y, mTouchSlop)) { 9120 // Outside button 9121 removeTapCallback(); 9122 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9123 // Remove any future long press/tap checks 9124 removeLongPressCallback(); 9125 9126 setPressed(false); 9127 } 9128 } 9129 break; 9130 } 9131 9132 return true; 9133 } 9134 9135 return false; 9136 } 9137 9138 private void setHotspot(float x, float y) { 9139 if (mBackground != null) { 9140 mBackground.setHotspot(x, y); 9141 } 9142 } 9143 9144 /** 9145 * @hide 9146 */ 9147 public boolean isInScrollingContainer() { 9148 ViewParent p = getParent(); 9149 while (p != null && p instanceof ViewGroup) { 9150 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9151 return true; 9152 } 9153 p = p.getParent(); 9154 } 9155 return false; 9156 } 9157 9158 /** 9159 * Remove the longpress detection timer. 9160 */ 9161 private void removeLongPressCallback() { 9162 if (mPendingCheckForLongPress != null) { 9163 removeCallbacks(mPendingCheckForLongPress); 9164 } 9165 } 9166 9167 /** 9168 * Remove the pending click action 9169 */ 9170 private void removePerformClickCallback() { 9171 if (mPerformClick != null) { 9172 removeCallbacks(mPerformClick); 9173 } 9174 } 9175 9176 /** 9177 * Remove the prepress detection timer. 9178 */ 9179 private void removeUnsetPressCallback() { 9180 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9181 setPressed(false); 9182 removeCallbacks(mUnsetPressedState); 9183 } 9184 } 9185 9186 /** 9187 * Remove the tap detection timer. 9188 */ 9189 private void removeTapCallback() { 9190 if (mPendingCheckForTap != null) { 9191 mPrivateFlags &= ~PFLAG_PREPRESSED; 9192 removeCallbacks(mPendingCheckForTap); 9193 } 9194 } 9195 9196 /** 9197 * Cancels a pending long press. Your subclass can use this if you 9198 * want the context menu to come up if the user presses and holds 9199 * at the same place, but you don't want it to come up if they press 9200 * and then move around enough to cause scrolling. 9201 */ 9202 public void cancelLongPress() { 9203 removeLongPressCallback(); 9204 9205 /* 9206 * The prepressed state handled by the tap callback is a display 9207 * construct, but the tap callback will post a long press callback 9208 * less its own timeout. Remove it here. 9209 */ 9210 removeTapCallback(); 9211 } 9212 9213 /** 9214 * Remove the pending callback for sending a 9215 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9216 */ 9217 private void removeSendViewScrolledAccessibilityEventCallback() { 9218 if (mSendViewScrolledAccessibilityEvent != null) { 9219 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9220 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9221 } 9222 } 9223 9224 /** 9225 * Sets the TouchDelegate for this View. 9226 */ 9227 public void setTouchDelegate(TouchDelegate delegate) { 9228 mTouchDelegate = delegate; 9229 } 9230 9231 /** 9232 * Gets the TouchDelegate for this View. 9233 */ 9234 public TouchDelegate getTouchDelegate() { 9235 return mTouchDelegate; 9236 } 9237 9238 /** 9239 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 9240 * 9241 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 9242 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 9243 * available. This method should only be called for touch events. 9244 * 9245 * <p class="note">This api is not intended for most applications. Buffered dispatch 9246 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 9247 * streams will not improve your input latency. Side effects include: increased latency, 9248 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 9249 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 9250 * you.</p> 9251 */ 9252 public final void requestUnbufferedDispatch(MotionEvent event) { 9253 final int action = event.getAction(); 9254 if (mAttachInfo == null 9255 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 9256 || !event.isTouchEvent()) { 9257 return; 9258 } 9259 mAttachInfo.mUnbufferedDispatchRequested = true; 9260 } 9261 9262 /** 9263 * Set flags controlling behavior of this view. 9264 * 9265 * @param flags Constant indicating the value which should be set 9266 * @param mask Constant indicating the bit range that should be changed 9267 */ 9268 void setFlags(int flags, int mask) { 9269 final boolean accessibilityEnabled = 9270 AccessibilityManager.getInstance(mContext).isEnabled(); 9271 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9272 9273 int old = mViewFlags; 9274 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9275 9276 int changed = mViewFlags ^ old; 9277 if (changed == 0) { 9278 return; 9279 } 9280 int privateFlags = mPrivateFlags; 9281 9282 /* Check if the FOCUSABLE bit has changed */ 9283 if (((changed & FOCUSABLE_MASK) != 0) && 9284 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9285 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9286 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9287 /* Give up focus if we are no longer focusable */ 9288 clearFocus(); 9289 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9290 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9291 /* 9292 * Tell the view system that we are now available to take focus 9293 * if no one else already has it. 9294 */ 9295 if (mParent != null) mParent.focusableViewAvailable(this); 9296 } 9297 } 9298 9299 final int newVisibility = flags & VISIBILITY_MASK; 9300 if (newVisibility == VISIBLE) { 9301 if ((changed & VISIBILITY_MASK) != 0) { 9302 /* 9303 * If this view is becoming visible, invalidate it in case it changed while 9304 * it was not visible. Marking it drawn ensures that the invalidation will 9305 * go through. 9306 */ 9307 mPrivateFlags |= PFLAG_DRAWN; 9308 invalidate(true); 9309 9310 needGlobalAttributesUpdate(true); 9311 9312 // a view becoming visible is worth notifying the parent 9313 // about in case nothing has focus. even if this specific view 9314 // isn't focusable, it may contain something that is, so let 9315 // the root view try to give this focus if nothing else does. 9316 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9317 mParent.focusableViewAvailable(this); 9318 } 9319 } 9320 } 9321 9322 /* Check if the GONE bit has changed */ 9323 if ((changed & GONE) != 0) { 9324 needGlobalAttributesUpdate(false); 9325 requestLayout(); 9326 9327 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9328 if (hasFocus()) clearFocus(); 9329 clearAccessibilityFocus(); 9330 destroyDrawingCache(); 9331 if (mParent instanceof View) { 9332 // GONE views noop invalidation, so invalidate the parent 9333 ((View) mParent).invalidate(true); 9334 } 9335 // Mark the view drawn to ensure that it gets invalidated properly the next 9336 // time it is visible and gets invalidated 9337 mPrivateFlags |= PFLAG_DRAWN; 9338 } 9339 if (mAttachInfo != null) { 9340 mAttachInfo.mViewVisibilityChanged = true; 9341 } 9342 } 9343 9344 /* Check if the VISIBLE bit has changed */ 9345 if ((changed & INVISIBLE) != 0) { 9346 needGlobalAttributesUpdate(false); 9347 /* 9348 * If this view is becoming invisible, set the DRAWN flag so that 9349 * the next invalidate() will not be skipped. 9350 */ 9351 mPrivateFlags |= PFLAG_DRAWN; 9352 9353 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9354 // root view becoming invisible shouldn't clear focus and accessibility focus 9355 if (getRootView() != this) { 9356 if (hasFocus()) clearFocus(); 9357 clearAccessibilityFocus(); 9358 } 9359 } 9360 if (mAttachInfo != null) { 9361 mAttachInfo.mViewVisibilityChanged = true; 9362 } 9363 } 9364 9365 if ((changed & VISIBILITY_MASK) != 0) { 9366 // If the view is invisible, cleanup its display list to free up resources 9367 if (newVisibility != VISIBLE && mAttachInfo != null) { 9368 cleanupDraw(); 9369 } 9370 9371 if (mParent instanceof ViewGroup) { 9372 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9373 (changed & VISIBILITY_MASK), newVisibility); 9374 ((View) mParent).invalidate(true); 9375 } else if (mParent != null) { 9376 mParent.invalidateChild(this, null); 9377 } 9378 dispatchVisibilityChanged(this, newVisibility); 9379 9380 notifySubtreeAccessibilityStateChangedIfNeeded(); 9381 } 9382 9383 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9384 destroyDrawingCache(); 9385 } 9386 9387 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9388 destroyDrawingCache(); 9389 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9390 invalidateParentCaches(); 9391 } 9392 9393 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9394 destroyDrawingCache(); 9395 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9396 } 9397 9398 if ((changed & DRAW_MASK) != 0) { 9399 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9400 if (mBackground != null) { 9401 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9402 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9403 } else { 9404 mPrivateFlags |= PFLAG_SKIP_DRAW; 9405 } 9406 } else { 9407 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9408 } 9409 requestLayout(); 9410 invalidate(true); 9411 } 9412 9413 if ((changed & KEEP_SCREEN_ON) != 0) { 9414 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9415 mParent.recomputeViewAttributes(this); 9416 } 9417 } 9418 9419 if (accessibilityEnabled) { 9420 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9421 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9422 if (oldIncludeForAccessibility != includeForAccessibility()) { 9423 notifySubtreeAccessibilityStateChangedIfNeeded(); 9424 } else { 9425 notifyViewAccessibilityStateChangedIfNeeded( 9426 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9427 } 9428 } else if ((changed & ENABLED_MASK) != 0) { 9429 notifyViewAccessibilityStateChangedIfNeeded( 9430 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9431 } 9432 } 9433 } 9434 9435 /** 9436 * Change the view's z order in the tree, so it's on top of other sibling 9437 * views. This ordering change may affect layout, if the parent container 9438 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9439 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9440 * method should be followed by calls to {@link #requestLayout()} and 9441 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9442 * with the new child ordering. 9443 * 9444 * @see ViewGroup#bringChildToFront(View) 9445 */ 9446 public void bringToFront() { 9447 if (mParent != null) { 9448 mParent.bringChildToFront(this); 9449 } 9450 } 9451 9452 /** 9453 * This is called in response to an internal scroll in this view (i.e., the 9454 * view scrolled its own contents). This is typically as a result of 9455 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9456 * called. 9457 * 9458 * @param l Current horizontal scroll origin. 9459 * @param t Current vertical scroll origin. 9460 * @param oldl Previous horizontal scroll origin. 9461 * @param oldt Previous vertical scroll origin. 9462 */ 9463 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9464 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9465 postSendViewScrolledAccessibilityEventCallback(); 9466 } 9467 9468 mBackgroundSizeChanged = true; 9469 9470 final AttachInfo ai = mAttachInfo; 9471 if (ai != null) { 9472 ai.mViewScrollChanged = true; 9473 } 9474 } 9475 9476 /** 9477 * Interface definition for a callback to be invoked when the layout bounds of a view 9478 * changes due to layout processing. 9479 */ 9480 public interface OnLayoutChangeListener { 9481 /** 9482 * Called when the layout bounds of a view changes due to layout processing. 9483 * 9484 * @param v The view whose bounds have changed. 9485 * @param left The new value of the view's left property. 9486 * @param top The new value of the view's top property. 9487 * @param right The new value of the view's right property. 9488 * @param bottom The new value of the view's bottom property. 9489 * @param oldLeft The previous value of the view's left property. 9490 * @param oldTop The previous value of the view's top property. 9491 * @param oldRight The previous value of the view's right property. 9492 * @param oldBottom The previous value of the view's bottom property. 9493 */ 9494 void onLayoutChange(View v, int left, int top, int right, int bottom, 9495 int oldLeft, int oldTop, int oldRight, int oldBottom); 9496 } 9497 9498 /** 9499 * This is called during layout when the size of this view has changed. If 9500 * you were just added to the view hierarchy, you're called with the old 9501 * values of 0. 9502 * 9503 * @param w Current width of this view. 9504 * @param h Current height of this view. 9505 * @param oldw Old width of this view. 9506 * @param oldh Old height of this view. 9507 */ 9508 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9509 } 9510 9511 /** 9512 * Called by draw to draw the child views. This may be overridden 9513 * by derived classes to gain control just before its children are drawn 9514 * (but after its own view has been drawn). 9515 * @param canvas the canvas on which to draw the view 9516 */ 9517 protected void dispatchDraw(Canvas canvas) { 9518 9519 } 9520 9521 /** 9522 * Gets the parent of this view. Note that the parent is a 9523 * ViewParent and not necessarily a View. 9524 * 9525 * @return Parent of this view. 9526 */ 9527 public final ViewParent getParent() { 9528 return mParent; 9529 } 9530 9531 /** 9532 * Set the horizontal scrolled position of your view. This will cause a call to 9533 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9534 * invalidated. 9535 * @param value the x position to scroll to 9536 */ 9537 public void setScrollX(int value) { 9538 scrollTo(value, mScrollY); 9539 } 9540 9541 /** 9542 * Set the vertical scrolled position of your view. This will cause a call to 9543 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9544 * invalidated. 9545 * @param value the y position to scroll to 9546 */ 9547 public void setScrollY(int value) { 9548 scrollTo(mScrollX, value); 9549 } 9550 9551 /** 9552 * Return the scrolled left position of this view. This is the left edge of 9553 * the displayed part of your view. You do not need to draw any pixels 9554 * farther left, since those are outside of the frame of your view on 9555 * screen. 9556 * 9557 * @return The left edge of the displayed part of your view, in pixels. 9558 */ 9559 public final int getScrollX() { 9560 return mScrollX; 9561 } 9562 9563 /** 9564 * Return the scrolled top position of this view. This is the top edge of 9565 * the displayed part of your view. You do not need to draw any pixels above 9566 * it, since those are outside of the frame of your view on screen. 9567 * 9568 * @return The top edge of the displayed part of your view, in pixels. 9569 */ 9570 public final int getScrollY() { 9571 return mScrollY; 9572 } 9573 9574 /** 9575 * Return the width of the your view. 9576 * 9577 * @return The width of your view, in pixels. 9578 */ 9579 @ViewDebug.ExportedProperty(category = "layout") 9580 public final int getWidth() { 9581 return mRight - mLeft; 9582 } 9583 9584 /** 9585 * Return the height of your view. 9586 * 9587 * @return The height of your view, in pixels. 9588 */ 9589 @ViewDebug.ExportedProperty(category = "layout") 9590 public final int getHeight() { 9591 return mBottom - mTop; 9592 } 9593 9594 /** 9595 * Return the visible drawing bounds of your view. Fills in the output 9596 * rectangle with the values from getScrollX(), getScrollY(), 9597 * getWidth(), and getHeight(). These bounds do not account for any 9598 * transformation properties currently set on the view, such as 9599 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9600 * 9601 * @param outRect The (scrolled) drawing bounds of the view. 9602 */ 9603 public void getDrawingRect(Rect outRect) { 9604 outRect.left = mScrollX; 9605 outRect.top = mScrollY; 9606 outRect.right = mScrollX + (mRight - mLeft); 9607 outRect.bottom = mScrollY + (mBottom - mTop); 9608 } 9609 9610 /** 9611 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9612 * raw width component (that is the result is masked by 9613 * {@link #MEASURED_SIZE_MASK}). 9614 * 9615 * @return The raw measured width of this view. 9616 */ 9617 public final int getMeasuredWidth() { 9618 return mMeasuredWidth & MEASURED_SIZE_MASK; 9619 } 9620 9621 /** 9622 * Return the full width measurement information for this view as computed 9623 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9624 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9625 * This should be used during measurement and layout calculations only. Use 9626 * {@link #getWidth()} to see how wide a view is after layout. 9627 * 9628 * @return The measured width of this view as a bit mask. 9629 */ 9630 public final int getMeasuredWidthAndState() { 9631 return mMeasuredWidth; 9632 } 9633 9634 /** 9635 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9636 * raw width component (that is the result is masked by 9637 * {@link #MEASURED_SIZE_MASK}). 9638 * 9639 * @return The raw measured height of this view. 9640 */ 9641 public final int getMeasuredHeight() { 9642 return mMeasuredHeight & MEASURED_SIZE_MASK; 9643 } 9644 9645 /** 9646 * Return the full height measurement information for this view as computed 9647 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9648 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9649 * This should be used during measurement and layout calculations only. Use 9650 * {@link #getHeight()} to see how wide a view is after layout. 9651 * 9652 * @return The measured width of this view as a bit mask. 9653 */ 9654 public final int getMeasuredHeightAndState() { 9655 return mMeasuredHeight; 9656 } 9657 9658 /** 9659 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9660 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9661 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9662 * and the height component is at the shifted bits 9663 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9664 */ 9665 public final int getMeasuredState() { 9666 return (mMeasuredWidth&MEASURED_STATE_MASK) 9667 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9668 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9669 } 9670 9671 /** 9672 * The transform matrix of this view, which is calculated based on the current 9673 * roation, scale, and pivot properties. 9674 * 9675 * @see #getRotation() 9676 * @see #getScaleX() 9677 * @see #getScaleY() 9678 * @see #getPivotX() 9679 * @see #getPivotY() 9680 * @return The current transform matrix for the view 9681 */ 9682 public Matrix getMatrix() { 9683 ensureTransformationInfo(); 9684 final Matrix matrix = mTransformationInfo.mMatrix; 9685 mRenderNode.getMatrix(matrix); 9686 return matrix; 9687 } 9688 9689 /** 9690 * Returns true if the transform matrix is the identity matrix. 9691 * Recomputes the matrix if necessary. 9692 * 9693 * @return True if the transform matrix is the identity matrix, false otherwise. 9694 */ 9695 final boolean hasIdentityMatrix() { 9696 return mRenderNode.hasIdentityMatrix(); 9697 } 9698 9699 void ensureTransformationInfo() { 9700 if (mTransformationInfo == null) { 9701 mTransformationInfo = new TransformationInfo(); 9702 } 9703 } 9704 9705 /** 9706 * Utility method to retrieve the inverse of the current mMatrix property. 9707 * We cache the matrix to avoid recalculating it when transform properties 9708 * have not changed. 9709 * 9710 * @return The inverse of the current matrix of this view. 9711 */ 9712 final Matrix getInverseMatrix() { 9713 ensureTransformationInfo(); 9714 if (mTransformationInfo.mInverseMatrix == null) { 9715 mTransformationInfo.mInverseMatrix = new Matrix(); 9716 } 9717 final Matrix matrix = mTransformationInfo.mInverseMatrix; 9718 mRenderNode.getInverseMatrix(matrix); 9719 return matrix; 9720 } 9721 9722 /** 9723 * Gets the distance along the Z axis from the camera to this view. 9724 * 9725 * @see #setCameraDistance(float) 9726 * 9727 * @return The distance along the Z axis. 9728 */ 9729 public float getCameraDistance() { 9730 final float dpi = mResources.getDisplayMetrics().densityDpi; 9731 return -(mRenderNode.getCameraDistance() * dpi); 9732 } 9733 9734 /** 9735 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9736 * views are drawn) from the camera to this view. The camera's distance 9737 * affects 3D transformations, for instance rotations around the X and Y 9738 * axis. If the rotationX or rotationY properties are changed and this view is 9739 * large (more than half the size of the screen), it is recommended to always 9740 * use a camera distance that's greater than the height (X axis rotation) or 9741 * the width (Y axis rotation) of this view.</p> 9742 * 9743 * <p>The distance of the camera from the view plane can have an affect on the 9744 * perspective distortion of the view when it is rotated around the x or y axis. 9745 * For example, a large distance will result in a large viewing angle, and there 9746 * will not be much perspective distortion of the view as it rotates. A short 9747 * distance may cause much more perspective distortion upon rotation, and can 9748 * also result in some drawing artifacts if the rotated view ends up partially 9749 * behind the camera (which is why the recommendation is to use a distance at 9750 * least as far as the size of the view, if the view is to be rotated.)</p> 9751 * 9752 * <p>The distance is expressed in "depth pixels." The default distance depends 9753 * on the screen density. For instance, on a medium density display, the 9754 * default distance is 1280. On a high density display, the default distance 9755 * is 1920.</p> 9756 * 9757 * <p>If you want to specify a distance that leads to visually consistent 9758 * results across various densities, use the following formula:</p> 9759 * <pre> 9760 * float scale = context.getResources().getDisplayMetrics().density; 9761 * view.setCameraDistance(distance * scale); 9762 * </pre> 9763 * 9764 * <p>The density scale factor of a high density display is 1.5, 9765 * and 1920 = 1280 * 1.5.</p> 9766 * 9767 * @param distance The distance in "depth pixels", if negative the opposite 9768 * value is used 9769 * 9770 * @see #setRotationX(float) 9771 * @see #setRotationY(float) 9772 */ 9773 public void setCameraDistance(float distance) { 9774 final float dpi = mResources.getDisplayMetrics().densityDpi; 9775 9776 invalidateViewProperty(true, false); 9777 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 9778 invalidateViewProperty(false, false); 9779 9780 invalidateParentIfNeededAndWasQuickRejected(); 9781 } 9782 9783 /** 9784 * The degrees that the view is rotated around the pivot point. 9785 * 9786 * @see #setRotation(float) 9787 * @see #getPivotX() 9788 * @see #getPivotY() 9789 * 9790 * @return The degrees of rotation. 9791 */ 9792 @ViewDebug.ExportedProperty(category = "drawing") 9793 public float getRotation() { 9794 return mRenderNode.getRotation(); 9795 } 9796 9797 /** 9798 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9799 * result in clockwise rotation. 9800 * 9801 * @param rotation The degrees of rotation. 9802 * 9803 * @see #getRotation() 9804 * @see #getPivotX() 9805 * @see #getPivotY() 9806 * @see #setRotationX(float) 9807 * @see #setRotationY(float) 9808 * 9809 * @attr ref android.R.styleable#View_rotation 9810 */ 9811 public void setRotation(float rotation) { 9812 if (rotation != getRotation()) { 9813 // Double-invalidation is necessary to capture view's old and new areas 9814 invalidateViewProperty(true, false); 9815 mRenderNode.setRotation(rotation); 9816 invalidateViewProperty(false, true); 9817 9818 invalidateParentIfNeededAndWasQuickRejected(); 9819 notifySubtreeAccessibilityStateChangedIfNeeded(); 9820 } 9821 } 9822 9823 /** 9824 * The degrees that the view is rotated around the vertical axis through the pivot point. 9825 * 9826 * @see #getPivotX() 9827 * @see #getPivotY() 9828 * @see #setRotationY(float) 9829 * 9830 * @return The degrees of Y rotation. 9831 */ 9832 @ViewDebug.ExportedProperty(category = "drawing") 9833 public float getRotationY() { 9834 return mRenderNode.getRotationY(); 9835 } 9836 9837 /** 9838 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9839 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9840 * down the y axis. 9841 * 9842 * When rotating large views, it is recommended to adjust the camera distance 9843 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9844 * 9845 * @param rotationY The degrees of Y rotation. 9846 * 9847 * @see #getRotationY() 9848 * @see #getPivotX() 9849 * @see #getPivotY() 9850 * @see #setRotation(float) 9851 * @see #setRotationX(float) 9852 * @see #setCameraDistance(float) 9853 * 9854 * @attr ref android.R.styleable#View_rotationY 9855 */ 9856 public void setRotationY(float rotationY) { 9857 if (rotationY != getRotationY()) { 9858 invalidateViewProperty(true, false); 9859 mRenderNode.setRotationY(rotationY); 9860 invalidateViewProperty(false, true); 9861 9862 invalidateParentIfNeededAndWasQuickRejected(); 9863 notifySubtreeAccessibilityStateChangedIfNeeded(); 9864 } 9865 } 9866 9867 /** 9868 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9869 * 9870 * @see #getPivotX() 9871 * @see #getPivotY() 9872 * @see #setRotationX(float) 9873 * 9874 * @return The degrees of X rotation. 9875 */ 9876 @ViewDebug.ExportedProperty(category = "drawing") 9877 public float getRotationX() { 9878 return mRenderNode.getRotationX(); 9879 } 9880 9881 /** 9882 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9883 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9884 * x axis. 9885 * 9886 * When rotating large views, it is recommended to adjust the camera distance 9887 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9888 * 9889 * @param rotationX The degrees of X rotation. 9890 * 9891 * @see #getRotationX() 9892 * @see #getPivotX() 9893 * @see #getPivotY() 9894 * @see #setRotation(float) 9895 * @see #setRotationY(float) 9896 * @see #setCameraDistance(float) 9897 * 9898 * @attr ref android.R.styleable#View_rotationX 9899 */ 9900 public void setRotationX(float rotationX) { 9901 if (rotationX != getRotationX()) { 9902 invalidateViewProperty(true, false); 9903 mRenderNode.setRotationX(rotationX); 9904 invalidateViewProperty(false, true); 9905 9906 invalidateParentIfNeededAndWasQuickRejected(); 9907 notifySubtreeAccessibilityStateChangedIfNeeded(); 9908 } 9909 } 9910 9911 /** 9912 * The amount that the view is scaled in x around the pivot point, as a proportion of 9913 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9914 * 9915 * <p>By default, this is 1.0f. 9916 * 9917 * @see #getPivotX() 9918 * @see #getPivotY() 9919 * @return The scaling factor. 9920 */ 9921 @ViewDebug.ExportedProperty(category = "drawing") 9922 public float getScaleX() { 9923 return mRenderNode.getScaleX(); 9924 } 9925 9926 /** 9927 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9928 * the view's unscaled width. A value of 1 means that no scaling is applied. 9929 * 9930 * @param scaleX The scaling factor. 9931 * @see #getPivotX() 9932 * @see #getPivotY() 9933 * 9934 * @attr ref android.R.styleable#View_scaleX 9935 */ 9936 public void setScaleX(float scaleX) { 9937 if (scaleX != getScaleX()) { 9938 invalidateViewProperty(true, false); 9939 mRenderNode.setScaleX(scaleX); 9940 invalidateViewProperty(false, true); 9941 9942 invalidateParentIfNeededAndWasQuickRejected(); 9943 notifySubtreeAccessibilityStateChangedIfNeeded(); 9944 } 9945 } 9946 9947 /** 9948 * The amount that the view is scaled in y around the pivot point, as a proportion of 9949 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9950 * 9951 * <p>By default, this is 1.0f. 9952 * 9953 * @see #getPivotX() 9954 * @see #getPivotY() 9955 * @return The scaling factor. 9956 */ 9957 @ViewDebug.ExportedProperty(category = "drawing") 9958 public float getScaleY() { 9959 return mRenderNode.getScaleY(); 9960 } 9961 9962 /** 9963 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9964 * the view's unscaled width. A value of 1 means that no scaling is applied. 9965 * 9966 * @param scaleY The scaling factor. 9967 * @see #getPivotX() 9968 * @see #getPivotY() 9969 * 9970 * @attr ref android.R.styleable#View_scaleY 9971 */ 9972 public void setScaleY(float scaleY) { 9973 if (scaleY != getScaleY()) { 9974 invalidateViewProperty(true, false); 9975 mRenderNode.setScaleY(scaleY); 9976 invalidateViewProperty(false, true); 9977 9978 invalidateParentIfNeededAndWasQuickRejected(); 9979 notifySubtreeAccessibilityStateChangedIfNeeded(); 9980 } 9981 } 9982 9983 /** 9984 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9985 * and {@link #setScaleX(float) scaled}. 9986 * 9987 * @see #getRotation() 9988 * @see #getScaleX() 9989 * @see #getScaleY() 9990 * @see #getPivotY() 9991 * @return The x location of the pivot point. 9992 * 9993 * @attr ref android.R.styleable#View_transformPivotX 9994 */ 9995 @ViewDebug.ExportedProperty(category = "drawing") 9996 public float getPivotX() { 9997 return mRenderNode.getPivotX(); 9998 } 9999 10000 /** 10001 * Sets the x location of the point around which the view is 10002 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 10003 * By default, the pivot point is centered on the object. 10004 * Setting this property disables this behavior and causes the view to use only the 10005 * explicitly set pivotX and pivotY values. 10006 * 10007 * @param pivotX The x location of the pivot point. 10008 * @see #getRotation() 10009 * @see #getScaleX() 10010 * @see #getScaleY() 10011 * @see #getPivotY() 10012 * 10013 * @attr ref android.R.styleable#View_transformPivotX 10014 */ 10015 public void setPivotX(float pivotX) { 10016 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 10017 invalidateViewProperty(true, false); 10018 mRenderNode.setPivotX(pivotX); 10019 invalidateViewProperty(false, true); 10020 10021 invalidateParentIfNeededAndWasQuickRejected(); 10022 } 10023 } 10024 10025 /** 10026 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10027 * and {@link #setScaleY(float) scaled}. 10028 * 10029 * @see #getRotation() 10030 * @see #getScaleX() 10031 * @see #getScaleY() 10032 * @see #getPivotY() 10033 * @return The y location of the pivot point. 10034 * 10035 * @attr ref android.R.styleable#View_transformPivotY 10036 */ 10037 @ViewDebug.ExportedProperty(category = "drawing") 10038 public float getPivotY() { 10039 return mRenderNode.getPivotY(); 10040 } 10041 10042 /** 10043 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10044 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10045 * Setting this property disables this behavior and causes the view to use only the 10046 * explicitly set pivotX and pivotY values. 10047 * 10048 * @param pivotY The y location of the pivot point. 10049 * @see #getRotation() 10050 * @see #getScaleX() 10051 * @see #getScaleY() 10052 * @see #getPivotY() 10053 * 10054 * @attr ref android.R.styleable#View_transformPivotY 10055 */ 10056 public void setPivotY(float pivotY) { 10057 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10058 invalidateViewProperty(true, false); 10059 mRenderNode.setPivotY(pivotY); 10060 invalidateViewProperty(false, true); 10061 10062 invalidateParentIfNeededAndWasQuickRejected(); 10063 } 10064 } 10065 10066 /** 10067 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10068 * completely transparent and 1 means the view is completely opaque. 10069 * 10070 * <p>By default this is 1.0f. 10071 * @return The opacity of the view. 10072 */ 10073 @ViewDebug.ExportedProperty(category = "drawing") 10074 public float getAlpha() { 10075 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10076 } 10077 10078 /** 10079 * Returns whether this View has content which overlaps. 10080 * 10081 * <p>This function, intended to be overridden by specific View types, is an optimization when 10082 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10083 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10084 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10085 * directly. An example of overlapping rendering is a TextView with a background image, such as 10086 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10087 * ImageView with only the foreground image. The default implementation returns true; subclasses 10088 * should override if they have cases which can be optimized.</p> 10089 * 10090 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10091 * necessitates that a View return true if it uses the methods internally without passing the 10092 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10093 * 10094 * @return true if the content in this view might overlap, false otherwise. 10095 */ 10096 public boolean hasOverlappingRendering() { 10097 return true; 10098 } 10099 10100 /** 10101 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10102 * completely transparent and 1 means the view is completely opaque.</p> 10103 * 10104 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10105 * performance implications, especially for large views. It is best to use the alpha property 10106 * sparingly and transiently, as in the case of fading animations.</p> 10107 * 10108 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10109 * strongly recommended for performance reasons to either override 10110 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10111 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10112 * 10113 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10114 * responsible for applying the opacity itself.</p> 10115 * 10116 * <p>Note that if the view is backed by a 10117 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10118 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10119 * 1.0 will supercede the alpha of the layer paint.</p> 10120 * 10121 * @param alpha The opacity of the view. 10122 * 10123 * @see #hasOverlappingRendering() 10124 * @see #setLayerType(int, android.graphics.Paint) 10125 * 10126 * @attr ref android.R.styleable#View_alpha 10127 */ 10128 public void setAlpha(float alpha) { 10129 ensureTransformationInfo(); 10130 if (mTransformationInfo.mAlpha != alpha) { 10131 mTransformationInfo.mAlpha = alpha; 10132 if (onSetAlpha((int) (alpha * 255))) { 10133 mPrivateFlags |= PFLAG_ALPHA_SET; 10134 // subclass is handling alpha - don't optimize rendering cache invalidation 10135 invalidateParentCaches(); 10136 invalidate(true); 10137 } else { 10138 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10139 invalidateViewProperty(true, false); 10140 mRenderNode.setAlpha(getFinalAlpha()); 10141 notifyViewAccessibilityStateChangedIfNeeded( 10142 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10143 } 10144 } 10145 } 10146 10147 /** 10148 * Faster version of setAlpha() which performs the same steps except there are 10149 * no calls to invalidate(). The caller of this function should perform proper invalidation 10150 * on the parent and this object. The return value indicates whether the subclass handles 10151 * alpha (the return value for onSetAlpha()). 10152 * 10153 * @param alpha The new value for the alpha property 10154 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10155 * the new value for the alpha property is different from the old value 10156 */ 10157 boolean setAlphaNoInvalidation(float alpha) { 10158 ensureTransformationInfo(); 10159 if (mTransformationInfo.mAlpha != alpha) { 10160 mTransformationInfo.mAlpha = alpha; 10161 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10162 if (subclassHandlesAlpha) { 10163 mPrivateFlags |= PFLAG_ALPHA_SET; 10164 return true; 10165 } else { 10166 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10167 mRenderNode.setAlpha(getFinalAlpha()); 10168 } 10169 } 10170 return false; 10171 } 10172 10173 /** 10174 * This property is hidden and intended only for use by the Fade transition, which 10175 * animates it to produce a visual translucency that does not side-effect (or get 10176 * affected by) the real alpha property. This value is composited with the other 10177 * alpha value (and the AlphaAnimation value, when that is present) to produce 10178 * a final visual translucency result, which is what is passed into the DisplayList. 10179 * 10180 * @hide 10181 */ 10182 public void setTransitionAlpha(float alpha) { 10183 ensureTransformationInfo(); 10184 if (mTransformationInfo.mTransitionAlpha != alpha) { 10185 mTransformationInfo.mTransitionAlpha = alpha; 10186 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10187 invalidateViewProperty(true, false); 10188 mRenderNode.setAlpha(getFinalAlpha()); 10189 } 10190 } 10191 10192 /** 10193 * Calculates the visual alpha of this view, which is a combination of the actual 10194 * alpha value and the transitionAlpha value (if set). 10195 */ 10196 private float getFinalAlpha() { 10197 if (mTransformationInfo != null) { 10198 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10199 } 10200 return 1; 10201 } 10202 10203 /** 10204 * This property is hidden and intended only for use by the Fade transition, which 10205 * animates it to produce a visual translucency that does not side-effect (or get 10206 * affected by) the real alpha property. This value is composited with the other 10207 * alpha value (and the AlphaAnimation value, when that is present) to produce 10208 * a final visual translucency result, which is what is passed into the DisplayList. 10209 * 10210 * @hide 10211 */ 10212 public float getTransitionAlpha() { 10213 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10214 } 10215 10216 /** 10217 * Top position of this view relative to its parent. 10218 * 10219 * @return The top of this view, in pixels. 10220 */ 10221 @ViewDebug.CapturedViewProperty 10222 public final int getTop() { 10223 return mTop; 10224 } 10225 10226 /** 10227 * Sets the top position of this view relative to its parent. This method is meant to be called 10228 * by the layout system and should not generally be called otherwise, because the property 10229 * may be changed at any time by the layout. 10230 * 10231 * @param top The top of this view, in pixels. 10232 */ 10233 public final void setTop(int top) { 10234 if (top != mTop) { 10235 final boolean matrixIsIdentity = hasIdentityMatrix(); 10236 if (matrixIsIdentity) { 10237 if (mAttachInfo != null) { 10238 int minTop; 10239 int yLoc; 10240 if (top < mTop) { 10241 minTop = top; 10242 yLoc = top - mTop; 10243 } else { 10244 minTop = mTop; 10245 yLoc = 0; 10246 } 10247 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10248 } 10249 } else { 10250 // Double-invalidation is necessary to capture view's old and new areas 10251 invalidate(true); 10252 } 10253 10254 int width = mRight - mLeft; 10255 int oldHeight = mBottom - mTop; 10256 10257 mTop = top; 10258 mRenderNode.setTop(mTop); 10259 10260 sizeChange(width, mBottom - mTop, width, oldHeight); 10261 10262 if (!matrixIsIdentity) { 10263 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10264 invalidate(true); 10265 } 10266 mBackgroundSizeChanged = true; 10267 invalidateParentIfNeeded(); 10268 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10269 // View was rejected last time it was drawn by its parent; this may have changed 10270 invalidateParentIfNeeded(); 10271 } 10272 } 10273 } 10274 10275 /** 10276 * Bottom position of this view relative to its parent. 10277 * 10278 * @return The bottom of this view, in pixels. 10279 */ 10280 @ViewDebug.CapturedViewProperty 10281 public final int getBottom() { 10282 return mBottom; 10283 } 10284 10285 /** 10286 * True if this view has changed since the last time being drawn. 10287 * 10288 * @return The dirty state of this view. 10289 */ 10290 public boolean isDirty() { 10291 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10292 } 10293 10294 /** 10295 * Sets the bottom position of this view relative to its parent. This method is meant to be 10296 * called by the layout system and should not generally be called otherwise, because the 10297 * property may be changed at any time by the layout. 10298 * 10299 * @param bottom The bottom of this view, in pixels. 10300 */ 10301 public final void setBottom(int bottom) { 10302 if (bottom != mBottom) { 10303 final boolean matrixIsIdentity = hasIdentityMatrix(); 10304 if (matrixIsIdentity) { 10305 if (mAttachInfo != null) { 10306 int maxBottom; 10307 if (bottom < mBottom) { 10308 maxBottom = mBottom; 10309 } else { 10310 maxBottom = bottom; 10311 } 10312 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10313 } 10314 } else { 10315 // Double-invalidation is necessary to capture view's old and new areas 10316 invalidate(true); 10317 } 10318 10319 int width = mRight - mLeft; 10320 int oldHeight = mBottom - mTop; 10321 10322 mBottom = bottom; 10323 mRenderNode.setBottom(mBottom); 10324 10325 sizeChange(width, mBottom - mTop, width, oldHeight); 10326 10327 if (!matrixIsIdentity) { 10328 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10329 invalidate(true); 10330 } 10331 mBackgroundSizeChanged = true; 10332 invalidateParentIfNeeded(); 10333 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10334 // View was rejected last time it was drawn by its parent; this may have changed 10335 invalidateParentIfNeeded(); 10336 } 10337 } 10338 } 10339 10340 /** 10341 * Left position of this view relative to its parent. 10342 * 10343 * @return The left edge of this view, in pixels. 10344 */ 10345 @ViewDebug.CapturedViewProperty 10346 public final int getLeft() { 10347 return mLeft; 10348 } 10349 10350 /** 10351 * Sets the left position of this view relative to its parent. This method is meant to be called 10352 * by the layout system and should not generally be called otherwise, because the property 10353 * may be changed at any time by the layout. 10354 * 10355 * @param left The left of this view, in pixels. 10356 */ 10357 public final void setLeft(int left) { 10358 if (left != mLeft) { 10359 final boolean matrixIsIdentity = hasIdentityMatrix(); 10360 if (matrixIsIdentity) { 10361 if (mAttachInfo != null) { 10362 int minLeft; 10363 int xLoc; 10364 if (left < mLeft) { 10365 minLeft = left; 10366 xLoc = left - mLeft; 10367 } else { 10368 minLeft = mLeft; 10369 xLoc = 0; 10370 } 10371 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10372 } 10373 } else { 10374 // Double-invalidation is necessary to capture view's old and new areas 10375 invalidate(true); 10376 } 10377 10378 int oldWidth = mRight - mLeft; 10379 int height = mBottom - mTop; 10380 10381 mLeft = left; 10382 mRenderNode.setLeft(left); 10383 10384 sizeChange(mRight - mLeft, height, oldWidth, height); 10385 10386 if (!matrixIsIdentity) { 10387 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10388 invalidate(true); 10389 } 10390 mBackgroundSizeChanged = true; 10391 invalidateParentIfNeeded(); 10392 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10393 // View was rejected last time it was drawn by its parent; this may have changed 10394 invalidateParentIfNeeded(); 10395 } 10396 } 10397 } 10398 10399 /** 10400 * Right position of this view relative to its parent. 10401 * 10402 * @return The right edge of this view, in pixels. 10403 */ 10404 @ViewDebug.CapturedViewProperty 10405 public final int getRight() { 10406 return mRight; 10407 } 10408 10409 /** 10410 * Sets the right position of this view relative to its parent. This method is meant to be called 10411 * by the layout system and should not generally be called otherwise, because the property 10412 * may be changed at any time by the layout. 10413 * 10414 * @param right The right of this view, in pixels. 10415 */ 10416 public final void setRight(int right) { 10417 if (right != mRight) { 10418 final boolean matrixIsIdentity = hasIdentityMatrix(); 10419 if (matrixIsIdentity) { 10420 if (mAttachInfo != null) { 10421 int maxRight; 10422 if (right < mRight) { 10423 maxRight = mRight; 10424 } else { 10425 maxRight = right; 10426 } 10427 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10428 } 10429 } else { 10430 // Double-invalidation is necessary to capture view's old and new areas 10431 invalidate(true); 10432 } 10433 10434 int oldWidth = mRight - mLeft; 10435 int height = mBottom - mTop; 10436 10437 mRight = right; 10438 mRenderNode.setRight(mRight); 10439 10440 sizeChange(mRight - mLeft, height, oldWidth, height); 10441 10442 if (!matrixIsIdentity) { 10443 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10444 invalidate(true); 10445 } 10446 mBackgroundSizeChanged = true; 10447 invalidateParentIfNeeded(); 10448 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10449 // View was rejected last time it was drawn by its parent; this may have changed 10450 invalidateParentIfNeeded(); 10451 } 10452 } 10453 } 10454 10455 /** 10456 * The visual x position of this view, in pixels. This is equivalent to the 10457 * {@link #setTranslationX(float) translationX} property plus the current 10458 * {@link #getLeft() left} property. 10459 * 10460 * @return The visual x position of this view, in pixels. 10461 */ 10462 @ViewDebug.ExportedProperty(category = "drawing") 10463 public float getX() { 10464 return mLeft + getTranslationX(); 10465 } 10466 10467 /** 10468 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10469 * {@link #setTranslationX(float) translationX} property to be the difference between 10470 * the x value passed in and the current {@link #getLeft() left} property. 10471 * 10472 * @param x The visual x position of this view, in pixels. 10473 */ 10474 public void setX(float x) { 10475 setTranslationX(x - mLeft); 10476 } 10477 10478 /** 10479 * The visual y position of this view, in pixels. This is equivalent to the 10480 * {@link #setTranslationY(float) translationY} property plus the current 10481 * {@link #getTop() top} property. 10482 * 10483 * @return The visual y position of this view, in pixels. 10484 */ 10485 @ViewDebug.ExportedProperty(category = "drawing") 10486 public float getY() { 10487 return mTop + getTranslationY(); 10488 } 10489 10490 /** 10491 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10492 * {@link #setTranslationY(float) translationY} property to be the difference between 10493 * the y value passed in and the current {@link #getTop() top} property. 10494 * 10495 * @param y The visual y position of this view, in pixels. 10496 */ 10497 public void setY(float y) { 10498 setTranslationY(y - mTop); 10499 } 10500 10501 /** 10502 * The visual z position of this view, in pixels. This is equivalent to the 10503 * {@link #setTranslationZ(float) translationZ} property plus the current 10504 * {@link #getElevation() elevation} property. 10505 * 10506 * @return The visual z position of this view, in pixels. 10507 */ 10508 @ViewDebug.ExportedProperty(category = "drawing") 10509 public float getZ() { 10510 return getElevation() + getTranslationZ(); 10511 } 10512 10513 /** 10514 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 10515 * {@link #setTranslationZ(float) translationZ} property to be the difference between 10516 * the x value passed in and the current {@link #getElevation() elevation} property. 10517 * 10518 * @param z The visual z position of this view, in pixels. 10519 */ 10520 public void setZ(float z) { 10521 setTranslationZ(z - getElevation()); 10522 } 10523 10524 @ViewDebug.ExportedProperty(category = "drawing") 10525 public float getElevation() { 10526 return mRenderNode.getElevation(); 10527 } 10528 10529 /** 10530 * Sets the base depth location of this view. 10531 * 10532 * @attr ref android.R.styleable#View_elevation 10533 */ 10534 public void setElevation(float elevation) { 10535 if (elevation != getElevation()) { 10536 invalidateViewProperty(true, false); 10537 mRenderNode.setElevation(elevation); 10538 invalidateViewProperty(false, true); 10539 10540 invalidateParentIfNeededAndWasQuickRejected(); 10541 } 10542 } 10543 10544 /** 10545 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10546 * This position is post-layout, in addition to wherever the object's 10547 * layout placed it. 10548 * 10549 * @return The horizontal position of this view relative to its left position, in pixels. 10550 */ 10551 @ViewDebug.ExportedProperty(category = "drawing") 10552 public float getTranslationX() { 10553 return mRenderNode.getTranslationX(); 10554 } 10555 10556 /** 10557 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10558 * This effectively positions the object post-layout, in addition to wherever the object's 10559 * layout placed it. 10560 * 10561 * @param translationX The horizontal position of this view relative to its left position, 10562 * in pixels. 10563 * 10564 * @attr ref android.R.styleable#View_translationX 10565 */ 10566 public void setTranslationX(float translationX) { 10567 if (translationX != getTranslationX()) { 10568 invalidateViewProperty(true, false); 10569 mRenderNode.setTranslationX(translationX); 10570 invalidateViewProperty(false, true); 10571 10572 invalidateParentIfNeededAndWasQuickRejected(); 10573 notifySubtreeAccessibilityStateChangedIfNeeded(); 10574 } 10575 } 10576 10577 /** 10578 * The vertical location of this view relative to its {@link #getTop() top} position. 10579 * This position is post-layout, in addition to wherever the object's 10580 * layout placed it. 10581 * 10582 * @return The vertical position of this view relative to its top position, 10583 * in pixels. 10584 */ 10585 @ViewDebug.ExportedProperty(category = "drawing") 10586 public float getTranslationY() { 10587 return mRenderNode.getTranslationY(); 10588 } 10589 10590 /** 10591 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10592 * This effectively positions the object post-layout, in addition to wherever the object's 10593 * layout placed it. 10594 * 10595 * @param translationY The vertical position of this view relative to its top position, 10596 * in pixels. 10597 * 10598 * @attr ref android.R.styleable#View_translationY 10599 */ 10600 public void setTranslationY(float translationY) { 10601 if (translationY != getTranslationY()) { 10602 invalidateViewProperty(true, false); 10603 mRenderNode.setTranslationY(translationY); 10604 invalidateViewProperty(false, true); 10605 10606 invalidateParentIfNeededAndWasQuickRejected(); 10607 } 10608 } 10609 10610 /** 10611 * The depth location of this view relative to its {@link #getElevation() elevation}. 10612 * 10613 * @return The depth of this view relative to its elevation. 10614 */ 10615 @ViewDebug.ExportedProperty(category = "drawing") 10616 public float getTranslationZ() { 10617 return mRenderNode.getTranslationZ(); 10618 } 10619 10620 /** 10621 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 10622 * 10623 * @attr ref android.R.styleable#View_translationZ 10624 */ 10625 public void setTranslationZ(float translationZ) { 10626 if (translationZ != getTranslationZ()) { 10627 invalidateViewProperty(true, false); 10628 mRenderNode.setTranslationZ(translationZ); 10629 invalidateViewProperty(false, true); 10630 10631 invalidateParentIfNeededAndWasQuickRejected(); 10632 } 10633 } 10634 10635 /** 10636 * Returns a ValueAnimator which can animate a clipping circle. 10637 * <p> 10638 * The View will be clipped to the animating circle. 10639 * <p> 10640 * Any shadow cast by the View will respect the circular clip from this animator. 10641 * 10642 * @param centerX The x coordinate of the center of the animating circle. 10643 * @param centerY The y coordinate of the center of the animating circle. 10644 * @param startRadius The starting radius of the animating circle. 10645 * @param endRadius The ending radius of the animating circle. 10646 */ 10647 public final ValueAnimator createRevealAnimator(int centerX, int centerY, 10648 float startRadius, float endRadius) { 10649 return RevealAnimator.ofRevealCircle(this, centerX, centerY, 10650 startRadius, endRadius, false); 10651 } 10652 10653 /** 10654 * Returns a ValueAnimator which can animate a clearing circle. 10655 * <p> 10656 * The View is prevented from drawing within the circle, so the content 10657 * behind the View shows through. 10658 * 10659 * @param centerX The x coordinate of the center of the animating circle. 10660 * @param centerY The y coordinate of the center of the animating circle. 10661 * @param startRadius The starting radius of the animating circle. 10662 * @param endRadius The ending radius of the animating circle. 10663 * 10664 * @hide 10665 */ 10666 public final ValueAnimator createClearCircleAnimator(int centerX, int centerY, 10667 float startRadius, float endRadius) { 10668 return RevealAnimator.ofRevealCircle(this, centerX, centerY, 10669 startRadius, endRadius, true); 10670 } 10671 10672 /** 10673 * Returns the current StateListAnimator if exists. 10674 * 10675 * @return StateListAnimator or null if it does not exists 10676 * @see #setStateListAnimator(android.animation.StateListAnimator) 10677 */ 10678 public StateListAnimator getStateListAnimator() { 10679 return mStateListAnimator; 10680 } 10681 10682 /** 10683 * Attaches the provided StateListAnimator to this View. 10684 * <p> 10685 * Any previously attached StateListAnimator will be detached. 10686 * 10687 * @param stateListAnimator The StateListAnimator to update the view 10688 * @see {@link android.animation.StateListAnimator} 10689 */ 10690 public void setStateListAnimator(StateListAnimator stateListAnimator) { 10691 if (mStateListAnimator == stateListAnimator) { 10692 return; 10693 } 10694 if (mStateListAnimator != null) { 10695 mStateListAnimator.setTarget(null); 10696 } 10697 mStateListAnimator = stateListAnimator; 10698 if (stateListAnimator != null) { 10699 stateListAnimator.setTarget(this); 10700 if (isAttachedToWindow()) { 10701 stateListAnimator.setState(getDrawableState()); 10702 } 10703 } 10704 } 10705 10706 /** 10707 * Sets the {@link Outline} of the view, which defines the shape of the shadow it 10708 * casts, and enables outline clipping. 10709 * <p> 10710 * By default, a View queries its Outline from its background drawable, via 10711 * {@link Drawable#getOutline(Outline)}. Manually setting the Outline with this method allows 10712 * this behavior to be overridden. 10713 * <p> 10714 * If the outline is {@link Outline#isEmpty()} or is <code>null</code>, 10715 * shadows will not be cast. 10716 * <p> 10717 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 10718 * 10719 * @param outline The new outline of the view. 10720 * 10721 * @see #setClipToOutline(boolean) 10722 * @see #getClipToOutline() 10723 */ 10724 public void setOutline(@Nullable Outline outline) { 10725 mPrivateFlags3 |= PFLAG3_OUTLINE_DEFINED; 10726 10727 if (outline == null || outline.isEmpty()) { 10728 if (mOutline != null) { 10729 mOutline.setEmpty(); 10730 } 10731 } else { 10732 // always copy the path since caller may reuse 10733 if (mOutline == null) { 10734 mOutline = new Outline(); 10735 } 10736 mOutline.set(outline); 10737 } 10738 mRenderNode.setOutline(mOutline); 10739 } 10740 10741 /** 10742 * Returns whether the Outline should be used to clip the contents of the View. 10743 * <p> 10744 * Note that this flag will only be respected if the View's Outline returns true from 10745 * {@link Outline#canClip()}. 10746 * 10747 * @see #setOutline(Outline) 10748 * @see #setClipToOutline(boolean) 10749 */ 10750 public final boolean getClipToOutline() { 10751 return mRenderNode.getClipToOutline(); 10752 } 10753 10754 /** 10755 * Sets whether the View's Outline should be used to clip the contents of the View. 10756 * <p> 10757 * Note that this flag will only be respected if the View's Outline returns true from 10758 * {@link Outline#canClip()}. 10759 * 10760 * @see #setOutline(Outline) 10761 * @see #getClipToOutline() 10762 */ 10763 public void setClipToOutline(boolean clipToOutline) { 10764 damageInParent(); 10765 if (getClipToOutline() != clipToOutline) { 10766 mRenderNode.setClipToOutline(clipToOutline); 10767 } 10768 } 10769 10770 private void queryOutlineFromBackgroundIfUndefined() { 10771 if ((mPrivateFlags3 & PFLAG3_OUTLINE_DEFINED) == 0) { 10772 // Outline not currently defined, query from background 10773 if (mOutline == null) { 10774 mOutline = new Outline(); 10775 } else { 10776 //invalidate outline, to ensure background calculates it 10777 mOutline.setEmpty(); 10778 } 10779 if (mBackground.getOutline(mOutline)) { 10780 if (mOutline.isEmpty()) { 10781 throw new IllegalStateException("Background drawable failed to build outline"); 10782 } 10783 mRenderNode.setOutline(mOutline); 10784 } else { 10785 mRenderNode.setOutline(null); 10786 } 10787 notifySubtreeAccessibilityStateChangedIfNeeded(); 10788 } 10789 } 10790 10791 /** 10792 * Private API to be used for reveal animation 10793 * 10794 * @hide 10795 */ 10796 public void setRevealClip(boolean shouldClip, boolean inverseClip, 10797 float x, float y, float radius) { 10798 mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius); 10799 // TODO: Handle this invalidate in a better way, or purely in native. 10800 invalidate(); 10801 } 10802 10803 /** 10804 * Hit rectangle in parent's coordinates 10805 * 10806 * @param outRect The hit rectangle of the view. 10807 */ 10808 public void getHitRect(Rect outRect) { 10809 if (hasIdentityMatrix() || mAttachInfo == null) { 10810 outRect.set(mLeft, mTop, mRight, mBottom); 10811 } else { 10812 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10813 tmpRect.set(0, 0, getWidth(), getHeight()); 10814 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 10815 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10816 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10817 } 10818 } 10819 10820 /** 10821 * Determines whether the given point, in local coordinates is inside the view. 10822 */ 10823 /*package*/ final boolean pointInView(float localX, float localY) { 10824 return localX >= 0 && localX < (mRight - mLeft) 10825 && localY >= 0 && localY < (mBottom - mTop); 10826 } 10827 10828 /** 10829 * Utility method to determine whether the given point, in local coordinates, 10830 * is inside the view, where the area of the view is expanded by the slop factor. 10831 * This method is called while processing touch-move events to determine if the event 10832 * is still within the view. 10833 * 10834 * @hide 10835 */ 10836 public boolean pointInView(float localX, float localY, float slop) { 10837 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10838 localY < ((mBottom - mTop) + slop); 10839 } 10840 10841 /** 10842 * When a view has focus and the user navigates away from it, the next view is searched for 10843 * starting from the rectangle filled in by this method. 10844 * 10845 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10846 * of the view. However, if your view maintains some idea of internal selection, 10847 * such as a cursor, or a selected row or column, you should override this method and 10848 * fill in a more specific rectangle. 10849 * 10850 * @param r The rectangle to fill in, in this view's coordinates. 10851 */ 10852 public void getFocusedRect(Rect r) { 10853 getDrawingRect(r); 10854 } 10855 10856 /** 10857 * If some part of this view is not clipped by any of its parents, then 10858 * return that area in r in global (root) coordinates. To convert r to local 10859 * coordinates (without taking possible View rotations into account), offset 10860 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10861 * If the view is completely clipped or translated out, return false. 10862 * 10863 * @param r If true is returned, r holds the global coordinates of the 10864 * visible portion of this view. 10865 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10866 * between this view and its root. globalOffet may be null. 10867 * @return true if r is non-empty (i.e. part of the view is visible at the 10868 * root level. 10869 */ 10870 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10871 int width = mRight - mLeft; 10872 int height = mBottom - mTop; 10873 if (width > 0 && height > 0) { 10874 r.set(0, 0, width, height); 10875 if (globalOffset != null) { 10876 globalOffset.set(-mScrollX, -mScrollY); 10877 } 10878 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10879 } 10880 return false; 10881 } 10882 10883 public final boolean getGlobalVisibleRect(Rect r) { 10884 return getGlobalVisibleRect(r, null); 10885 } 10886 10887 public final boolean getLocalVisibleRect(Rect r) { 10888 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10889 if (getGlobalVisibleRect(r, offset)) { 10890 r.offset(-offset.x, -offset.y); // make r local 10891 return true; 10892 } 10893 return false; 10894 } 10895 10896 /** 10897 * Offset this view's vertical location by the specified number of pixels. 10898 * 10899 * @param offset the number of pixels to offset the view by 10900 */ 10901 public void offsetTopAndBottom(int offset) { 10902 if (offset != 0) { 10903 final boolean matrixIsIdentity = hasIdentityMatrix(); 10904 if (matrixIsIdentity) { 10905 if (isHardwareAccelerated()) { 10906 invalidateViewProperty(false, false); 10907 } else { 10908 final ViewParent p = mParent; 10909 if (p != null && mAttachInfo != null) { 10910 final Rect r = mAttachInfo.mTmpInvalRect; 10911 int minTop; 10912 int maxBottom; 10913 int yLoc; 10914 if (offset < 0) { 10915 minTop = mTop + offset; 10916 maxBottom = mBottom; 10917 yLoc = offset; 10918 } else { 10919 minTop = mTop; 10920 maxBottom = mBottom + offset; 10921 yLoc = 0; 10922 } 10923 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10924 p.invalidateChild(this, r); 10925 } 10926 } 10927 } else { 10928 invalidateViewProperty(false, false); 10929 } 10930 10931 mTop += offset; 10932 mBottom += offset; 10933 mRenderNode.offsetTopAndBottom(offset); 10934 if (isHardwareAccelerated()) { 10935 invalidateViewProperty(false, false); 10936 } else { 10937 if (!matrixIsIdentity) { 10938 invalidateViewProperty(false, true); 10939 } 10940 invalidateParentIfNeeded(); 10941 } 10942 notifySubtreeAccessibilityStateChangedIfNeeded(); 10943 } 10944 } 10945 10946 /** 10947 * Offset this view's horizontal location by the specified amount of pixels. 10948 * 10949 * @param offset the number of pixels to offset the view by 10950 */ 10951 public void offsetLeftAndRight(int offset) { 10952 if (offset != 0) { 10953 final boolean matrixIsIdentity = hasIdentityMatrix(); 10954 if (matrixIsIdentity) { 10955 if (isHardwareAccelerated()) { 10956 invalidateViewProperty(false, false); 10957 } else { 10958 final ViewParent p = mParent; 10959 if (p != null && mAttachInfo != null) { 10960 final Rect r = mAttachInfo.mTmpInvalRect; 10961 int minLeft; 10962 int maxRight; 10963 if (offset < 0) { 10964 minLeft = mLeft + offset; 10965 maxRight = mRight; 10966 } else { 10967 minLeft = mLeft; 10968 maxRight = mRight + offset; 10969 } 10970 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 10971 p.invalidateChild(this, r); 10972 } 10973 } 10974 } else { 10975 invalidateViewProperty(false, false); 10976 } 10977 10978 mLeft += offset; 10979 mRight += offset; 10980 mRenderNode.offsetLeftAndRight(offset); 10981 if (isHardwareAccelerated()) { 10982 invalidateViewProperty(false, false); 10983 } else { 10984 if (!matrixIsIdentity) { 10985 invalidateViewProperty(false, true); 10986 } 10987 invalidateParentIfNeeded(); 10988 } 10989 notifySubtreeAccessibilityStateChangedIfNeeded(); 10990 } 10991 } 10992 10993 /** 10994 * Get the LayoutParams associated with this view. All views should have 10995 * layout parameters. These supply parameters to the <i>parent</i> of this 10996 * view specifying how it should be arranged. There are many subclasses of 10997 * ViewGroup.LayoutParams, and these correspond to the different subclasses 10998 * of ViewGroup that are responsible for arranging their children. 10999 * 11000 * This method may return null if this View is not attached to a parent 11001 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 11002 * was not invoked successfully. When a View is attached to a parent 11003 * ViewGroup, this method must not return null. 11004 * 11005 * @return The LayoutParams associated with this view, or null if no 11006 * parameters have been set yet 11007 */ 11008 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 11009 public ViewGroup.LayoutParams getLayoutParams() { 11010 return mLayoutParams; 11011 } 11012 11013 /** 11014 * Set the layout parameters associated with this view. These supply 11015 * parameters to the <i>parent</i> of this view specifying how it should be 11016 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 11017 * correspond to the different subclasses of ViewGroup that are responsible 11018 * for arranging their children. 11019 * 11020 * @param params The layout parameters for this view, cannot be null 11021 */ 11022 public void setLayoutParams(ViewGroup.LayoutParams params) { 11023 if (params == null) { 11024 throw new NullPointerException("Layout parameters cannot be null"); 11025 } 11026 mLayoutParams = params; 11027 resolveLayoutParams(); 11028 if (mParent instanceof ViewGroup) { 11029 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11030 } 11031 requestLayout(); 11032 } 11033 11034 /** 11035 * Resolve the layout parameters depending on the resolved layout direction 11036 * 11037 * @hide 11038 */ 11039 public void resolveLayoutParams() { 11040 if (mLayoutParams != null) { 11041 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11042 } 11043 } 11044 11045 /** 11046 * Set the scrolled position of your view. This will cause a call to 11047 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11048 * invalidated. 11049 * @param x the x position to scroll to 11050 * @param y the y position to scroll to 11051 */ 11052 public void scrollTo(int x, int y) { 11053 if (mScrollX != x || mScrollY != y) { 11054 int oldX = mScrollX; 11055 int oldY = mScrollY; 11056 mScrollX = x; 11057 mScrollY = y; 11058 invalidateParentCaches(); 11059 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11060 if (!awakenScrollBars()) { 11061 postInvalidateOnAnimation(); 11062 } 11063 } 11064 } 11065 11066 /** 11067 * Move the scrolled position of your view. This will cause a call to 11068 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11069 * invalidated. 11070 * @param x the amount of pixels to scroll by horizontally 11071 * @param y the amount of pixels to scroll by vertically 11072 */ 11073 public void scrollBy(int x, int y) { 11074 scrollTo(mScrollX + x, mScrollY + y); 11075 } 11076 11077 /** 11078 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11079 * animation to fade the scrollbars out after a default delay. If a subclass 11080 * provides animated scrolling, the start delay should equal the duration 11081 * of the scrolling animation.</p> 11082 * 11083 * <p>The animation starts only if at least one of the scrollbars is 11084 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11085 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11086 * this method returns true, and false otherwise. If the animation is 11087 * started, this method calls {@link #invalidate()}; in that case the 11088 * caller should not call {@link #invalidate()}.</p> 11089 * 11090 * <p>This method should be invoked every time a subclass directly updates 11091 * the scroll parameters.</p> 11092 * 11093 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11094 * and {@link #scrollTo(int, int)}.</p> 11095 * 11096 * @return true if the animation is played, false otherwise 11097 * 11098 * @see #awakenScrollBars(int) 11099 * @see #scrollBy(int, int) 11100 * @see #scrollTo(int, int) 11101 * @see #isHorizontalScrollBarEnabled() 11102 * @see #isVerticalScrollBarEnabled() 11103 * @see #setHorizontalScrollBarEnabled(boolean) 11104 * @see #setVerticalScrollBarEnabled(boolean) 11105 */ 11106 protected boolean awakenScrollBars() { 11107 return mScrollCache != null && 11108 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11109 } 11110 11111 /** 11112 * Trigger the scrollbars to draw. 11113 * This method differs from awakenScrollBars() only in its default duration. 11114 * initialAwakenScrollBars() will show the scroll bars for longer than 11115 * usual to give the user more of a chance to notice them. 11116 * 11117 * @return true if the animation is played, false otherwise. 11118 */ 11119 private boolean initialAwakenScrollBars() { 11120 return mScrollCache != null && 11121 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11122 } 11123 11124 /** 11125 * <p> 11126 * Trigger the scrollbars to draw. When invoked this method starts an 11127 * animation to fade the scrollbars out after a fixed delay. If a subclass 11128 * provides animated scrolling, the start delay should equal the duration of 11129 * the scrolling animation. 11130 * </p> 11131 * 11132 * <p> 11133 * The animation starts only if at least one of the scrollbars is enabled, 11134 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11135 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11136 * this method returns true, and false otherwise. If the animation is 11137 * started, this method calls {@link #invalidate()}; in that case the caller 11138 * should not call {@link #invalidate()}. 11139 * </p> 11140 * 11141 * <p> 11142 * This method should be invoked everytime a subclass directly updates the 11143 * scroll parameters. 11144 * </p> 11145 * 11146 * @param startDelay the delay, in milliseconds, after which the animation 11147 * should start; when the delay is 0, the animation starts 11148 * immediately 11149 * @return true if the animation is played, false otherwise 11150 * 11151 * @see #scrollBy(int, int) 11152 * @see #scrollTo(int, int) 11153 * @see #isHorizontalScrollBarEnabled() 11154 * @see #isVerticalScrollBarEnabled() 11155 * @see #setHorizontalScrollBarEnabled(boolean) 11156 * @see #setVerticalScrollBarEnabled(boolean) 11157 */ 11158 protected boolean awakenScrollBars(int startDelay) { 11159 return awakenScrollBars(startDelay, true); 11160 } 11161 11162 /** 11163 * <p> 11164 * Trigger the scrollbars to draw. When invoked this method starts an 11165 * animation to fade the scrollbars out after a fixed delay. If a subclass 11166 * provides animated scrolling, the start delay should equal the duration of 11167 * the scrolling animation. 11168 * </p> 11169 * 11170 * <p> 11171 * The animation starts only if at least one of the scrollbars is enabled, 11172 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11173 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11174 * this method returns true, and false otherwise. If the animation is 11175 * started, this method calls {@link #invalidate()} if the invalidate parameter 11176 * is set to true; in that case the caller 11177 * should not call {@link #invalidate()}. 11178 * </p> 11179 * 11180 * <p> 11181 * This method should be invoked everytime a subclass directly updates the 11182 * scroll parameters. 11183 * </p> 11184 * 11185 * @param startDelay the delay, in milliseconds, after which the animation 11186 * should start; when the delay is 0, the animation starts 11187 * immediately 11188 * 11189 * @param invalidate Wheter this method should call invalidate 11190 * 11191 * @return true if the animation is played, false otherwise 11192 * 11193 * @see #scrollBy(int, int) 11194 * @see #scrollTo(int, int) 11195 * @see #isHorizontalScrollBarEnabled() 11196 * @see #isVerticalScrollBarEnabled() 11197 * @see #setHorizontalScrollBarEnabled(boolean) 11198 * @see #setVerticalScrollBarEnabled(boolean) 11199 */ 11200 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11201 final ScrollabilityCache scrollCache = mScrollCache; 11202 11203 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11204 return false; 11205 } 11206 11207 if (scrollCache.scrollBar == null) { 11208 scrollCache.scrollBar = new ScrollBarDrawable(); 11209 } 11210 11211 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11212 11213 if (invalidate) { 11214 // Invalidate to show the scrollbars 11215 postInvalidateOnAnimation(); 11216 } 11217 11218 if (scrollCache.state == ScrollabilityCache.OFF) { 11219 // FIXME: this is copied from WindowManagerService. 11220 // We should get this value from the system when it 11221 // is possible to do so. 11222 final int KEY_REPEAT_FIRST_DELAY = 750; 11223 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11224 } 11225 11226 // Tell mScrollCache when we should start fading. This may 11227 // extend the fade start time if one was already scheduled 11228 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11229 scrollCache.fadeStartTime = fadeStartTime; 11230 scrollCache.state = ScrollabilityCache.ON; 11231 11232 // Schedule our fader to run, unscheduling any old ones first 11233 if (mAttachInfo != null) { 11234 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11235 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11236 } 11237 11238 return true; 11239 } 11240 11241 return false; 11242 } 11243 11244 /** 11245 * Do not invalidate views which are not visible and which are not running an animation. They 11246 * will not get drawn and they should not set dirty flags as if they will be drawn 11247 */ 11248 private boolean skipInvalidate() { 11249 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11250 (!(mParent instanceof ViewGroup) || 11251 !((ViewGroup) mParent).isViewTransitioning(this)); 11252 } 11253 11254 /** 11255 * Mark the area defined by dirty as needing to be drawn. If the view is 11256 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11257 * point in the future. 11258 * <p> 11259 * This must be called from a UI thread. To call from a non-UI thread, call 11260 * {@link #postInvalidate()}. 11261 * <p> 11262 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11263 * {@code dirty}. 11264 * 11265 * @param dirty the rectangle representing the bounds of the dirty region 11266 */ 11267 public void invalidate(Rect dirty) { 11268 final int scrollX = mScrollX; 11269 final int scrollY = mScrollY; 11270 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11271 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11272 } 11273 11274 /** 11275 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11276 * coordinates of the dirty rect are relative to the view. If the view is 11277 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11278 * point in the future. 11279 * <p> 11280 * This must be called from a UI thread. To call from a non-UI thread, call 11281 * {@link #postInvalidate()}. 11282 * 11283 * @param l the left position of the dirty region 11284 * @param t the top position of the dirty region 11285 * @param r the right position of the dirty region 11286 * @param b the bottom position of the dirty region 11287 */ 11288 public void invalidate(int l, int t, int r, int b) { 11289 final int scrollX = mScrollX; 11290 final int scrollY = mScrollY; 11291 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11292 } 11293 11294 /** 11295 * Invalidate the whole view. If the view is visible, 11296 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11297 * the future. 11298 * <p> 11299 * This must be called from a UI thread. To call from a non-UI thread, call 11300 * {@link #postInvalidate()}. 11301 */ 11302 public void invalidate() { 11303 invalidate(true); 11304 } 11305 11306 /** 11307 * This is where the invalidate() work actually happens. A full invalidate() 11308 * causes the drawing cache to be invalidated, but this function can be 11309 * called with invalidateCache set to false to skip that invalidation step 11310 * for cases that do not need it (for example, a component that remains at 11311 * the same dimensions with the same content). 11312 * 11313 * @param invalidateCache Whether the drawing cache for this view should be 11314 * invalidated as well. This is usually true for a full 11315 * invalidate, but may be set to false if the View's contents or 11316 * dimensions have not changed. 11317 */ 11318 void invalidate(boolean invalidateCache) { 11319 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11320 } 11321 11322 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11323 boolean fullInvalidate) { 11324 if (skipInvalidate()) { 11325 return; 11326 } 11327 11328 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11329 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11330 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11331 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11332 if (fullInvalidate) { 11333 mLastIsOpaque = isOpaque(); 11334 mPrivateFlags &= ~PFLAG_DRAWN; 11335 } 11336 11337 mPrivateFlags |= PFLAG_DIRTY; 11338 11339 if (invalidateCache) { 11340 mPrivateFlags |= PFLAG_INVALIDATED; 11341 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11342 } 11343 11344 // Propagate the damage rectangle to the parent view. 11345 final AttachInfo ai = mAttachInfo; 11346 final ViewParent p = mParent; 11347 if (p != null && ai != null && l < r && t < b) { 11348 final Rect damage = ai.mTmpInvalRect; 11349 damage.set(l, t, r, b); 11350 p.invalidateChild(this, damage); 11351 } 11352 11353 // Damage the entire projection receiver, if necessary. 11354 if (mBackground != null && mBackground.isProjected()) { 11355 final View receiver = getProjectionReceiver(); 11356 if (receiver != null) { 11357 receiver.damageInParent(); 11358 } 11359 } 11360 11361 // Damage the entire IsolatedZVolume recieving this view's shadow. 11362 if (isHardwareAccelerated() && getZ() != 0) { 11363 damageShadowReceiver(); 11364 } 11365 } 11366 } 11367 11368 /** 11369 * @return this view's projection receiver, or {@code null} if none exists 11370 */ 11371 private View getProjectionReceiver() { 11372 ViewParent p = getParent(); 11373 while (p != null && p instanceof View) { 11374 final View v = (View) p; 11375 if (v.isProjectionReceiver()) { 11376 return v; 11377 } 11378 p = p.getParent(); 11379 } 11380 11381 return null; 11382 } 11383 11384 /** 11385 * @return whether the view is a projection receiver 11386 */ 11387 private boolean isProjectionReceiver() { 11388 return mBackground != null; 11389 } 11390 11391 /** 11392 * Damage area of the screen that can be covered by this View's shadow. 11393 * 11394 * This method will guarantee that any changes to shadows cast by a View 11395 * are damaged on the screen for future redraw. 11396 */ 11397 private void damageShadowReceiver() { 11398 final AttachInfo ai = mAttachInfo; 11399 if (ai != null) { 11400 ViewParent p = getParent(); 11401 if (p != null && p instanceof ViewGroup) { 11402 final ViewGroup vg = (ViewGroup) p; 11403 vg.damageInParent(); 11404 } 11405 } 11406 } 11407 11408 /** 11409 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11410 * set any flags or handle all of the cases handled by the default invalidation methods. 11411 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11412 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11413 * walk up the hierarchy, transforming the dirty rect as necessary. 11414 * 11415 * The method also handles normal invalidation logic if display list properties are not 11416 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11417 * backup approach, to handle these cases used in the various property-setting methods. 11418 * 11419 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11420 * are not being used in this view 11421 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11422 * list properties are not being used in this view 11423 */ 11424 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11425 if (!isHardwareAccelerated() 11426 || !mRenderNode.isValid() 11427 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11428 if (invalidateParent) { 11429 invalidateParentCaches(); 11430 } 11431 if (forceRedraw) { 11432 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11433 } 11434 invalidate(false); 11435 } else { 11436 damageInParent(); 11437 } 11438 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 11439 damageShadowReceiver(); 11440 } 11441 } 11442 11443 /** 11444 * Tells the parent view to damage this view's bounds. 11445 * 11446 * @hide 11447 */ 11448 protected void damageInParent() { 11449 final AttachInfo ai = mAttachInfo; 11450 final ViewParent p = mParent; 11451 if (p != null && ai != null) { 11452 final Rect r = ai.mTmpInvalRect; 11453 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11454 if (mParent instanceof ViewGroup) { 11455 ((ViewGroup) mParent).damageChild(this, r); 11456 } else { 11457 mParent.invalidateChild(this, r); 11458 } 11459 } 11460 } 11461 11462 /** 11463 * Utility method to transform a given Rect by the current matrix of this view. 11464 */ 11465 void transformRect(final Rect rect) { 11466 if (!getMatrix().isIdentity()) { 11467 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11468 boundingRect.set(rect); 11469 getMatrix().mapRect(boundingRect); 11470 rect.set((int) Math.floor(boundingRect.left), 11471 (int) Math.floor(boundingRect.top), 11472 (int) Math.ceil(boundingRect.right), 11473 (int) Math.ceil(boundingRect.bottom)); 11474 } 11475 } 11476 11477 /** 11478 * Used to indicate that the parent of this view should clear its caches. This functionality 11479 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11480 * which is necessary when various parent-managed properties of the view change, such as 11481 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11482 * clears the parent caches and does not causes an invalidate event. 11483 * 11484 * @hide 11485 */ 11486 protected void invalidateParentCaches() { 11487 if (mParent instanceof View) { 11488 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11489 } 11490 } 11491 11492 /** 11493 * Used to indicate that the parent of this view should be invalidated. This functionality 11494 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11495 * which is necessary when various parent-managed properties of the view change, such as 11496 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11497 * an invalidation event to the parent. 11498 * 11499 * @hide 11500 */ 11501 protected void invalidateParentIfNeeded() { 11502 if (isHardwareAccelerated() && mParent instanceof View) { 11503 ((View) mParent).invalidate(true); 11504 } 11505 } 11506 11507 /** 11508 * @hide 11509 */ 11510 protected void invalidateParentIfNeededAndWasQuickRejected() { 11511 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 11512 // View was rejected last time it was drawn by its parent; this may have changed 11513 invalidateParentIfNeeded(); 11514 } 11515 } 11516 11517 /** 11518 * Indicates whether this View is opaque. An opaque View guarantees that it will 11519 * draw all the pixels overlapping its bounds using a fully opaque color. 11520 * 11521 * Subclasses of View should override this method whenever possible to indicate 11522 * whether an instance is opaque. Opaque Views are treated in a special way by 11523 * the View hierarchy, possibly allowing it to perform optimizations during 11524 * invalidate/draw passes. 11525 * 11526 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11527 */ 11528 @ViewDebug.ExportedProperty(category = "drawing") 11529 public boolean isOpaque() { 11530 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11531 getFinalAlpha() >= 1.0f; 11532 } 11533 11534 /** 11535 * @hide 11536 */ 11537 protected void computeOpaqueFlags() { 11538 // Opaque if: 11539 // - Has a background 11540 // - Background is opaque 11541 // - Doesn't have scrollbars or scrollbars overlay 11542 11543 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11544 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11545 } else { 11546 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11547 } 11548 11549 final int flags = mViewFlags; 11550 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11551 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11552 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11553 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11554 } else { 11555 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11556 } 11557 } 11558 11559 /** 11560 * @hide 11561 */ 11562 protected boolean hasOpaqueScrollbars() { 11563 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11564 } 11565 11566 /** 11567 * @return A handler associated with the thread running the View. This 11568 * handler can be used to pump events in the UI events queue. 11569 */ 11570 public Handler getHandler() { 11571 final AttachInfo attachInfo = mAttachInfo; 11572 if (attachInfo != null) { 11573 return attachInfo.mHandler; 11574 } 11575 return null; 11576 } 11577 11578 /** 11579 * Gets the view root associated with the View. 11580 * @return The view root, or null if none. 11581 * @hide 11582 */ 11583 public ViewRootImpl getViewRootImpl() { 11584 if (mAttachInfo != null) { 11585 return mAttachInfo.mViewRootImpl; 11586 } 11587 return null; 11588 } 11589 11590 /** 11591 * @hide 11592 */ 11593 public HardwareRenderer getHardwareRenderer() { 11594 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 11595 } 11596 11597 /** 11598 * <p>Causes the Runnable to be added to the message queue. 11599 * The runnable will be run on the user interface thread.</p> 11600 * 11601 * @param action The Runnable that will be executed. 11602 * 11603 * @return Returns 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. 11606 * 11607 * @see #postDelayed 11608 * @see #removeCallbacks 11609 */ 11610 public boolean post(Runnable action) { 11611 final AttachInfo attachInfo = mAttachInfo; 11612 if (attachInfo != null) { 11613 return attachInfo.mHandler.post(action); 11614 } 11615 // Assume that post will succeed later 11616 ViewRootImpl.getRunQueue().post(action); 11617 return true; 11618 } 11619 11620 /** 11621 * <p>Causes the Runnable to be added to the message queue, to be run 11622 * after the specified amount of time elapses. 11623 * The runnable will be run on the user interface thread.</p> 11624 * 11625 * @param action The Runnable that will be executed. 11626 * @param delayMillis The delay (in milliseconds) until the Runnable 11627 * will be executed. 11628 * 11629 * @return true if the Runnable was successfully placed in to the 11630 * message queue. Returns false on failure, usually because the 11631 * looper processing the message queue is exiting. Note that a 11632 * result of true does not mean the Runnable will be processed -- 11633 * if the looper is quit before the delivery time of the message 11634 * occurs then the message will be dropped. 11635 * 11636 * @see #post 11637 * @see #removeCallbacks 11638 */ 11639 public boolean postDelayed(Runnable action, long delayMillis) { 11640 final AttachInfo attachInfo = mAttachInfo; 11641 if (attachInfo != null) { 11642 return attachInfo.mHandler.postDelayed(action, delayMillis); 11643 } 11644 // Assume that post will succeed later 11645 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11646 return true; 11647 } 11648 11649 /** 11650 * <p>Causes the Runnable to execute on the next animation time step. 11651 * The runnable will be run on the user interface thread.</p> 11652 * 11653 * @param action The Runnable that will be executed. 11654 * 11655 * @see #postOnAnimationDelayed 11656 * @see #removeCallbacks 11657 */ 11658 public void postOnAnimation(Runnable action) { 11659 final AttachInfo attachInfo = mAttachInfo; 11660 if (attachInfo != null) { 11661 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11662 Choreographer.CALLBACK_ANIMATION, action, null); 11663 } else { 11664 // Assume that post will succeed later 11665 ViewRootImpl.getRunQueue().post(action); 11666 } 11667 } 11668 11669 /** 11670 * <p>Causes the Runnable to execute on the next animation time step, 11671 * after the specified amount of time elapses. 11672 * The runnable will be run on the user interface thread.</p> 11673 * 11674 * @param action The Runnable that will be executed. 11675 * @param delayMillis The delay (in milliseconds) until the Runnable 11676 * will be executed. 11677 * 11678 * @see #postOnAnimation 11679 * @see #removeCallbacks 11680 */ 11681 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11682 final AttachInfo attachInfo = mAttachInfo; 11683 if (attachInfo != null) { 11684 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11685 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11686 } else { 11687 // Assume that post will succeed later 11688 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11689 } 11690 } 11691 11692 /** 11693 * <p>Removes the specified Runnable from the message queue.</p> 11694 * 11695 * @param action The Runnable to remove from the message handling queue 11696 * 11697 * @return true if this view could ask the Handler to remove the Runnable, 11698 * false otherwise. When the returned value is true, the Runnable 11699 * may or may not have been actually removed from the message queue 11700 * (for instance, if the Runnable was not in the queue already.) 11701 * 11702 * @see #post 11703 * @see #postDelayed 11704 * @see #postOnAnimation 11705 * @see #postOnAnimationDelayed 11706 */ 11707 public boolean removeCallbacks(Runnable action) { 11708 if (action != null) { 11709 final AttachInfo attachInfo = mAttachInfo; 11710 if (attachInfo != null) { 11711 attachInfo.mHandler.removeCallbacks(action); 11712 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11713 Choreographer.CALLBACK_ANIMATION, action, null); 11714 } 11715 // Assume that post will succeed later 11716 ViewRootImpl.getRunQueue().removeCallbacks(action); 11717 } 11718 return true; 11719 } 11720 11721 /** 11722 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11723 * Use this to invalidate the View from a non-UI thread.</p> 11724 * 11725 * <p>This method can be invoked from outside of the UI thread 11726 * only when this View is attached to a window.</p> 11727 * 11728 * @see #invalidate() 11729 * @see #postInvalidateDelayed(long) 11730 */ 11731 public void postInvalidate() { 11732 postInvalidateDelayed(0); 11733 } 11734 11735 /** 11736 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11737 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11738 * 11739 * <p>This method can be invoked from outside of the UI thread 11740 * only when this View is attached to a window.</p> 11741 * 11742 * @param left The left coordinate of the rectangle to invalidate. 11743 * @param top The top coordinate of the rectangle to invalidate. 11744 * @param right The right coordinate of the rectangle to invalidate. 11745 * @param bottom The bottom coordinate of the rectangle to invalidate. 11746 * 11747 * @see #invalidate(int, int, int, int) 11748 * @see #invalidate(Rect) 11749 * @see #postInvalidateDelayed(long, int, int, int, int) 11750 */ 11751 public void postInvalidate(int left, int top, int right, int bottom) { 11752 postInvalidateDelayed(0, left, top, right, bottom); 11753 } 11754 11755 /** 11756 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11757 * loop. Waits for the specified amount of time.</p> 11758 * 11759 * <p>This method can be invoked from outside of the UI thread 11760 * only when this View is attached to a window.</p> 11761 * 11762 * @param delayMilliseconds the duration in milliseconds to delay the 11763 * invalidation by 11764 * 11765 * @see #invalidate() 11766 * @see #postInvalidate() 11767 */ 11768 public void postInvalidateDelayed(long delayMilliseconds) { 11769 // We try only with the AttachInfo because there's no point in invalidating 11770 // if we are not attached to our window 11771 final AttachInfo attachInfo = mAttachInfo; 11772 if (attachInfo != null) { 11773 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11774 } 11775 } 11776 11777 /** 11778 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11779 * through the event loop. Waits for the specified amount of time.</p> 11780 * 11781 * <p>This method can be invoked from outside of the UI thread 11782 * only when this View is attached to a window.</p> 11783 * 11784 * @param delayMilliseconds the duration in milliseconds to delay the 11785 * invalidation by 11786 * @param left The left coordinate of the rectangle to invalidate. 11787 * @param top The top coordinate of the rectangle to invalidate. 11788 * @param right The right coordinate of the rectangle to invalidate. 11789 * @param bottom The bottom coordinate of the rectangle to invalidate. 11790 * 11791 * @see #invalidate(int, int, int, int) 11792 * @see #invalidate(Rect) 11793 * @see #postInvalidate(int, int, int, int) 11794 */ 11795 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11796 int right, int bottom) { 11797 11798 // We try only with the AttachInfo because there's no point in invalidating 11799 // if we are not attached to our window 11800 final AttachInfo attachInfo = mAttachInfo; 11801 if (attachInfo != null) { 11802 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11803 info.target = this; 11804 info.left = left; 11805 info.top = top; 11806 info.right = right; 11807 info.bottom = bottom; 11808 11809 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11810 } 11811 } 11812 11813 /** 11814 * <p>Cause an invalidate to happen on the next animation time step, typically the 11815 * next display frame.</p> 11816 * 11817 * <p>This method can be invoked from outside of the UI thread 11818 * only when this View is attached to a window.</p> 11819 * 11820 * @see #invalidate() 11821 */ 11822 public void postInvalidateOnAnimation() { 11823 // We try only with the AttachInfo because there's no point in invalidating 11824 // if we are not attached to our window 11825 final AttachInfo attachInfo = mAttachInfo; 11826 if (attachInfo != null) { 11827 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11828 } 11829 } 11830 11831 /** 11832 * <p>Cause an invalidate of the specified area to happen on the next animation 11833 * time step, typically the next display frame.</p> 11834 * 11835 * <p>This method can be invoked from outside of the UI thread 11836 * only when this View is attached to a window.</p> 11837 * 11838 * @param left The left coordinate of the rectangle to invalidate. 11839 * @param top The top coordinate of the rectangle to invalidate. 11840 * @param right The right coordinate of the rectangle to invalidate. 11841 * @param bottom The bottom coordinate of the rectangle to invalidate. 11842 * 11843 * @see #invalidate(int, int, int, int) 11844 * @see #invalidate(Rect) 11845 */ 11846 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11847 // We try only with the AttachInfo because there's no point in invalidating 11848 // if we are not attached to our window 11849 final AttachInfo attachInfo = mAttachInfo; 11850 if (attachInfo != null) { 11851 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11852 info.target = this; 11853 info.left = left; 11854 info.top = top; 11855 info.right = right; 11856 info.bottom = bottom; 11857 11858 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11859 } 11860 } 11861 11862 /** 11863 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11864 * This event is sent at most once every 11865 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11866 */ 11867 private void postSendViewScrolledAccessibilityEventCallback() { 11868 if (mSendViewScrolledAccessibilityEvent == null) { 11869 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11870 } 11871 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11872 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11873 postDelayed(mSendViewScrolledAccessibilityEvent, 11874 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11875 } 11876 } 11877 11878 /** 11879 * Called by a parent to request that a child update its values for mScrollX 11880 * and mScrollY if necessary. This will typically be done if the child is 11881 * animating a scroll using a {@link android.widget.Scroller Scroller} 11882 * object. 11883 */ 11884 public void computeScroll() { 11885 } 11886 11887 /** 11888 * <p>Indicate whether the horizontal edges are faded when the view is 11889 * scrolled horizontally.</p> 11890 * 11891 * @return true if the horizontal edges should are faded on scroll, false 11892 * otherwise 11893 * 11894 * @see #setHorizontalFadingEdgeEnabled(boolean) 11895 * 11896 * @attr ref android.R.styleable#View_requiresFadingEdge 11897 */ 11898 public boolean isHorizontalFadingEdgeEnabled() { 11899 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11900 } 11901 11902 /** 11903 * <p>Define whether the horizontal edges should be faded when this view 11904 * is scrolled horizontally.</p> 11905 * 11906 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11907 * be faded when the view is scrolled 11908 * horizontally 11909 * 11910 * @see #isHorizontalFadingEdgeEnabled() 11911 * 11912 * @attr ref android.R.styleable#View_requiresFadingEdge 11913 */ 11914 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11915 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11916 if (horizontalFadingEdgeEnabled) { 11917 initScrollCache(); 11918 } 11919 11920 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11921 } 11922 } 11923 11924 /** 11925 * <p>Indicate whether the vertical edges are faded when the view is 11926 * scrolled horizontally.</p> 11927 * 11928 * @return true if the vertical edges should are faded on scroll, false 11929 * otherwise 11930 * 11931 * @see #setVerticalFadingEdgeEnabled(boolean) 11932 * 11933 * @attr ref android.R.styleable#View_requiresFadingEdge 11934 */ 11935 public boolean isVerticalFadingEdgeEnabled() { 11936 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 11937 } 11938 11939 /** 11940 * <p>Define whether the vertical edges should be faded when this view 11941 * is scrolled vertically.</p> 11942 * 11943 * @param verticalFadingEdgeEnabled true if the vertical edges should 11944 * be faded when the view is scrolled 11945 * vertically 11946 * 11947 * @see #isVerticalFadingEdgeEnabled() 11948 * 11949 * @attr ref android.R.styleable#View_requiresFadingEdge 11950 */ 11951 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 11952 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 11953 if (verticalFadingEdgeEnabled) { 11954 initScrollCache(); 11955 } 11956 11957 mViewFlags ^= FADING_EDGE_VERTICAL; 11958 } 11959 } 11960 11961 /** 11962 * Returns the strength, or intensity, of the top faded edge. The strength is 11963 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11964 * returns 0.0 or 1.0 but no value in between. 11965 * 11966 * Subclasses should override this method to provide a smoother fade transition 11967 * when scrolling occurs. 11968 * 11969 * @return the intensity of the top fade as a float between 0.0f and 1.0f 11970 */ 11971 protected float getTopFadingEdgeStrength() { 11972 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 11973 } 11974 11975 /** 11976 * Returns the strength, or intensity, of the bottom faded edge. The strength is 11977 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11978 * returns 0.0 or 1.0 but no value in between. 11979 * 11980 * Subclasses should override this method to provide a smoother fade transition 11981 * when scrolling occurs. 11982 * 11983 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 11984 */ 11985 protected float getBottomFadingEdgeStrength() { 11986 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 11987 computeVerticalScrollRange() ? 1.0f : 0.0f; 11988 } 11989 11990 /** 11991 * Returns the strength, or intensity, of the left faded edge. The strength is 11992 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11993 * returns 0.0 or 1.0 but no value in between. 11994 * 11995 * Subclasses should override this method to provide a smoother fade transition 11996 * when scrolling occurs. 11997 * 11998 * @return the intensity of the left fade as a float between 0.0f and 1.0f 11999 */ 12000 protected float getLeftFadingEdgeStrength() { 12001 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 12002 } 12003 12004 /** 12005 * Returns the strength, or intensity, of the right faded edge. The strength is 12006 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12007 * returns 0.0 or 1.0 but no value in between. 12008 * 12009 * Subclasses should override this method to provide a smoother fade transition 12010 * when scrolling occurs. 12011 * 12012 * @return the intensity of the right fade as a float between 0.0f and 1.0f 12013 */ 12014 protected float getRightFadingEdgeStrength() { 12015 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 12016 computeHorizontalScrollRange() ? 1.0f : 0.0f; 12017 } 12018 12019 /** 12020 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 12021 * scrollbar is not drawn by default.</p> 12022 * 12023 * @return true if the horizontal scrollbar should be painted, false 12024 * otherwise 12025 * 12026 * @see #setHorizontalScrollBarEnabled(boolean) 12027 */ 12028 public boolean isHorizontalScrollBarEnabled() { 12029 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12030 } 12031 12032 /** 12033 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12034 * scrollbar is not drawn by default.</p> 12035 * 12036 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12037 * be painted 12038 * 12039 * @see #isHorizontalScrollBarEnabled() 12040 */ 12041 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12042 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12043 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12044 computeOpaqueFlags(); 12045 resolvePadding(); 12046 } 12047 } 12048 12049 /** 12050 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12051 * scrollbar is not drawn by default.</p> 12052 * 12053 * @return true if the vertical scrollbar should be painted, false 12054 * otherwise 12055 * 12056 * @see #setVerticalScrollBarEnabled(boolean) 12057 */ 12058 public boolean isVerticalScrollBarEnabled() { 12059 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12060 } 12061 12062 /** 12063 * <p>Define whether the vertical scrollbar should be drawn or not. The 12064 * scrollbar is not drawn by default.</p> 12065 * 12066 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12067 * be painted 12068 * 12069 * @see #isVerticalScrollBarEnabled() 12070 */ 12071 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12072 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12073 mViewFlags ^= SCROLLBARS_VERTICAL; 12074 computeOpaqueFlags(); 12075 resolvePadding(); 12076 } 12077 } 12078 12079 /** 12080 * @hide 12081 */ 12082 protected void recomputePadding() { 12083 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12084 } 12085 12086 /** 12087 * Define whether scrollbars will fade when the view is not scrolling. 12088 * 12089 * @param fadeScrollbars wheter to enable fading 12090 * 12091 * @attr ref android.R.styleable#View_fadeScrollbars 12092 */ 12093 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12094 initScrollCache(); 12095 final ScrollabilityCache scrollabilityCache = mScrollCache; 12096 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12097 if (fadeScrollbars) { 12098 scrollabilityCache.state = ScrollabilityCache.OFF; 12099 } else { 12100 scrollabilityCache.state = ScrollabilityCache.ON; 12101 } 12102 } 12103 12104 /** 12105 * 12106 * Returns true if scrollbars will fade when this view is not scrolling 12107 * 12108 * @return true if scrollbar fading is enabled 12109 * 12110 * @attr ref android.R.styleable#View_fadeScrollbars 12111 */ 12112 public boolean isScrollbarFadingEnabled() { 12113 return mScrollCache != null && mScrollCache.fadeScrollBars; 12114 } 12115 12116 /** 12117 * 12118 * Returns the delay before scrollbars fade. 12119 * 12120 * @return the delay before scrollbars fade 12121 * 12122 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12123 */ 12124 public int getScrollBarDefaultDelayBeforeFade() { 12125 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12126 mScrollCache.scrollBarDefaultDelayBeforeFade; 12127 } 12128 12129 /** 12130 * Define the delay before scrollbars fade. 12131 * 12132 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12133 * 12134 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12135 */ 12136 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12137 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12138 } 12139 12140 /** 12141 * 12142 * Returns the scrollbar fade duration. 12143 * 12144 * @return the scrollbar fade duration 12145 * 12146 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12147 */ 12148 public int getScrollBarFadeDuration() { 12149 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12150 mScrollCache.scrollBarFadeDuration; 12151 } 12152 12153 /** 12154 * Define the scrollbar fade duration. 12155 * 12156 * @param scrollBarFadeDuration - the scrollbar fade duration 12157 * 12158 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12159 */ 12160 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12161 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12162 } 12163 12164 /** 12165 * 12166 * Returns the scrollbar size. 12167 * 12168 * @return the scrollbar size 12169 * 12170 * @attr ref android.R.styleable#View_scrollbarSize 12171 */ 12172 public int getScrollBarSize() { 12173 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12174 mScrollCache.scrollBarSize; 12175 } 12176 12177 /** 12178 * Define the scrollbar size. 12179 * 12180 * @param scrollBarSize - the scrollbar size 12181 * 12182 * @attr ref android.R.styleable#View_scrollbarSize 12183 */ 12184 public void setScrollBarSize(int scrollBarSize) { 12185 getScrollCache().scrollBarSize = scrollBarSize; 12186 } 12187 12188 /** 12189 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12190 * inset. When inset, they add to the padding of the view. And the scrollbars 12191 * can be drawn inside the padding area or on the edge of the view. For example, 12192 * if a view has a background drawable and you want to draw the scrollbars 12193 * inside the padding specified by the drawable, you can use 12194 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12195 * appear at the edge of the view, ignoring the padding, then you can use 12196 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12197 * @param style the style of the scrollbars. Should be one of 12198 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12199 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12200 * @see #SCROLLBARS_INSIDE_OVERLAY 12201 * @see #SCROLLBARS_INSIDE_INSET 12202 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12203 * @see #SCROLLBARS_OUTSIDE_INSET 12204 * 12205 * @attr ref android.R.styleable#View_scrollbarStyle 12206 */ 12207 public void setScrollBarStyle(@ScrollBarStyle int style) { 12208 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12209 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12210 computeOpaqueFlags(); 12211 resolvePadding(); 12212 } 12213 } 12214 12215 /** 12216 * <p>Returns the current scrollbar style.</p> 12217 * @return the current scrollbar style 12218 * @see #SCROLLBARS_INSIDE_OVERLAY 12219 * @see #SCROLLBARS_INSIDE_INSET 12220 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12221 * @see #SCROLLBARS_OUTSIDE_INSET 12222 * 12223 * @attr ref android.R.styleable#View_scrollbarStyle 12224 */ 12225 @ViewDebug.ExportedProperty(mapping = { 12226 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12227 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12228 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12229 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12230 }) 12231 @ScrollBarStyle 12232 public int getScrollBarStyle() { 12233 return mViewFlags & SCROLLBARS_STYLE_MASK; 12234 } 12235 12236 /** 12237 * <p>Compute the horizontal range that the horizontal scrollbar 12238 * represents.</p> 12239 * 12240 * <p>The range is expressed in arbitrary units that must be the same as the 12241 * units used by {@link #computeHorizontalScrollExtent()} and 12242 * {@link #computeHorizontalScrollOffset()}.</p> 12243 * 12244 * <p>The default range is the drawing width of this view.</p> 12245 * 12246 * @return the total horizontal range represented by the horizontal 12247 * scrollbar 12248 * 12249 * @see #computeHorizontalScrollExtent() 12250 * @see #computeHorizontalScrollOffset() 12251 * @see android.widget.ScrollBarDrawable 12252 */ 12253 protected int computeHorizontalScrollRange() { 12254 return getWidth(); 12255 } 12256 12257 /** 12258 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12259 * within the horizontal range. This value is used to compute the position 12260 * of the thumb within the scrollbar's track.</p> 12261 * 12262 * <p>The range is expressed in arbitrary units that must be the same as the 12263 * units used by {@link #computeHorizontalScrollRange()} and 12264 * {@link #computeHorizontalScrollExtent()}.</p> 12265 * 12266 * <p>The default offset is the scroll offset of this view.</p> 12267 * 12268 * @return the horizontal offset of the scrollbar's thumb 12269 * 12270 * @see #computeHorizontalScrollRange() 12271 * @see #computeHorizontalScrollExtent() 12272 * @see android.widget.ScrollBarDrawable 12273 */ 12274 protected int computeHorizontalScrollOffset() { 12275 return mScrollX; 12276 } 12277 12278 /** 12279 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12280 * within the horizontal range. This value is used to compute the length 12281 * of the thumb within the scrollbar's track.</p> 12282 * 12283 * <p>The range is expressed in arbitrary units that must be the same as the 12284 * units used by {@link #computeHorizontalScrollRange()} and 12285 * {@link #computeHorizontalScrollOffset()}.</p> 12286 * 12287 * <p>The default extent is the drawing width of this view.</p> 12288 * 12289 * @return the horizontal extent of the scrollbar's thumb 12290 * 12291 * @see #computeHorizontalScrollRange() 12292 * @see #computeHorizontalScrollOffset() 12293 * @see android.widget.ScrollBarDrawable 12294 */ 12295 protected int computeHorizontalScrollExtent() { 12296 return getWidth(); 12297 } 12298 12299 /** 12300 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12301 * 12302 * <p>The range is expressed in arbitrary units that must be the same as the 12303 * units used by {@link #computeVerticalScrollExtent()} and 12304 * {@link #computeVerticalScrollOffset()}.</p> 12305 * 12306 * @return the total vertical range represented by the vertical scrollbar 12307 * 12308 * <p>The default range is the drawing height of this view.</p> 12309 * 12310 * @see #computeVerticalScrollExtent() 12311 * @see #computeVerticalScrollOffset() 12312 * @see android.widget.ScrollBarDrawable 12313 */ 12314 protected int computeVerticalScrollRange() { 12315 return getHeight(); 12316 } 12317 12318 /** 12319 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12320 * within the horizontal range. This value is used to compute the position 12321 * of the thumb within the scrollbar's track.</p> 12322 * 12323 * <p>The range is expressed in arbitrary units that must be the same as the 12324 * units used by {@link #computeVerticalScrollRange()} and 12325 * {@link #computeVerticalScrollExtent()}.</p> 12326 * 12327 * <p>The default offset is the scroll offset of this view.</p> 12328 * 12329 * @return the vertical offset of the scrollbar's thumb 12330 * 12331 * @see #computeVerticalScrollRange() 12332 * @see #computeVerticalScrollExtent() 12333 * @see android.widget.ScrollBarDrawable 12334 */ 12335 protected int computeVerticalScrollOffset() { 12336 return mScrollY; 12337 } 12338 12339 /** 12340 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12341 * within the vertical range. This value is used to compute the length 12342 * of the thumb within the scrollbar's track.</p> 12343 * 12344 * <p>The range is expressed in arbitrary units that must be the same as the 12345 * units used by {@link #computeVerticalScrollRange()} and 12346 * {@link #computeVerticalScrollOffset()}.</p> 12347 * 12348 * <p>The default extent is the drawing height of this view.</p> 12349 * 12350 * @return the vertical extent of the scrollbar's thumb 12351 * 12352 * @see #computeVerticalScrollRange() 12353 * @see #computeVerticalScrollOffset() 12354 * @see android.widget.ScrollBarDrawable 12355 */ 12356 protected int computeVerticalScrollExtent() { 12357 return getHeight(); 12358 } 12359 12360 /** 12361 * Check if this view can be scrolled horizontally in a certain direction. 12362 * 12363 * @param direction Negative to check scrolling left, positive to check scrolling right. 12364 * @return true if this view can be scrolled in the specified direction, false otherwise. 12365 */ 12366 public boolean canScrollHorizontally(int direction) { 12367 final int offset = computeHorizontalScrollOffset(); 12368 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12369 if (range == 0) return false; 12370 if (direction < 0) { 12371 return offset > 0; 12372 } else { 12373 return offset < range - 1; 12374 } 12375 } 12376 12377 /** 12378 * Check if this view can be scrolled vertically in a certain direction. 12379 * 12380 * @param direction Negative to check scrolling up, positive to check scrolling down. 12381 * @return true if this view can be scrolled in the specified direction, false otherwise. 12382 */ 12383 public boolean canScrollVertically(int direction) { 12384 final int offset = computeVerticalScrollOffset(); 12385 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12386 if (range == 0) return false; 12387 if (direction < 0) { 12388 return offset > 0; 12389 } else { 12390 return offset < range - 1; 12391 } 12392 } 12393 12394 /** 12395 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12396 * scrollbars are painted only if they have been awakened first.</p> 12397 * 12398 * @param canvas the canvas on which to draw the scrollbars 12399 * 12400 * @see #awakenScrollBars(int) 12401 */ 12402 protected final void onDrawScrollBars(Canvas canvas) { 12403 // scrollbars are drawn only when the animation is running 12404 final ScrollabilityCache cache = mScrollCache; 12405 if (cache != null) { 12406 12407 int state = cache.state; 12408 12409 if (state == ScrollabilityCache.OFF) { 12410 return; 12411 } 12412 12413 boolean invalidate = false; 12414 12415 if (state == ScrollabilityCache.FADING) { 12416 // We're fading -- get our fade interpolation 12417 if (cache.interpolatorValues == null) { 12418 cache.interpolatorValues = new float[1]; 12419 } 12420 12421 float[] values = cache.interpolatorValues; 12422 12423 // Stops the animation if we're done 12424 if (cache.scrollBarInterpolator.timeToValues(values) == 12425 Interpolator.Result.FREEZE_END) { 12426 cache.state = ScrollabilityCache.OFF; 12427 } else { 12428 cache.scrollBar.setAlpha(Math.round(values[0])); 12429 } 12430 12431 // This will make the scroll bars inval themselves after 12432 // drawing. We only want this when we're fading so that 12433 // we prevent excessive redraws 12434 invalidate = true; 12435 } else { 12436 // We're just on -- but we may have been fading before so 12437 // reset alpha 12438 cache.scrollBar.setAlpha(255); 12439 } 12440 12441 12442 final int viewFlags = mViewFlags; 12443 12444 final boolean drawHorizontalScrollBar = 12445 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12446 final boolean drawVerticalScrollBar = 12447 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12448 && !isVerticalScrollBarHidden(); 12449 12450 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12451 final int width = mRight - mLeft; 12452 final int height = mBottom - mTop; 12453 12454 final ScrollBarDrawable scrollBar = cache.scrollBar; 12455 12456 final int scrollX = mScrollX; 12457 final int scrollY = mScrollY; 12458 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12459 12460 int left; 12461 int top; 12462 int right; 12463 int bottom; 12464 12465 if (drawHorizontalScrollBar) { 12466 int size = scrollBar.getSize(false); 12467 if (size <= 0) { 12468 size = cache.scrollBarSize; 12469 } 12470 12471 scrollBar.setParameters(computeHorizontalScrollRange(), 12472 computeHorizontalScrollOffset(), 12473 computeHorizontalScrollExtent(), false); 12474 final int verticalScrollBarGap = drawVerticalScrollBar ? 12475 getVerticalScrollbarWidth() : 0; 12476 top = scrollY + height - size - (mUserPaddingBottom & inside); 12477 left = scrollX + (mPaddingLeft & inside); 12478 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12479 bottom = top + size; 12480 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12481 if (invalidate) { 12482 invalidate(left, top, right, bottom); 12483 } 12484 } 12485 12486 if (drawVerticalScrollBar) { 12487 int size = scrollBar.getSize(true); 12488 if (size <= 0) { 12489 size = cache.scrollBarSize; 12490 } 12491 12492 scrollBar.setParameters(computeVerticalScrollRange(), 12493 computeVerticalScrollOffset(), 12494 computeVerticalScrollExtent(), true); 12495 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12496 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12497 verticalScrollbarPosition = isLayoutRtl() ? 12498 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12499 } 12500 switch (verticalScrollbarPosition) { 12501 default: 12502 case SCROLLBAR_POSITION_RIGHT: 12503 left = scrollX + width - size - (mUserPaddingRight & inside); 12504 break; 12505 case SCROLLBAR_POSITION_LEFT: 12506 left = scrollX + (mUserPaddingLeft & inside); 12507 break; 12508 } 12509 top = scrollY + (mPaddingTop & inside); 12510 right = left + size; 12511 bottom = scrollY + height - (mUserPaddingBottom & inside); 12512 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12513 if (invalidate) { 12514 invalidate(left, top, right, bottom); 12515 } 12516 } 12517 } 12518 } 12519 } 12520 12521 /** 12522 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12523 * FastScroller is visible. 12524 * @return whether to temporarily hide the vertical scrollbar 12525 * @hide 12526 */ 12527 protected boolean isVerticalScrollBarHidden() { 12528 return false; 12529 } 12530 12531 /** 12532 * <p>Draw the horizontal scrollbar if 12533 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12534 * 12535 * @param canvas the canvas on which to draw the scrollbar 12536 * @param scrollBar the scrollbar's drawable 12537 * 12538 * @see #isHorizontalScrollBarEnabled() 12539 * @see #computeHorizontalScrollRange() 12540 * @see #computeHorizontalScrollExtent() 12541 * @see #computeHorizontalScrollOffset() 12542 * @see android.widget.ScrollBarDrawable 12543 * @hide 12544 */ 12545 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12546 int l, int t, int r, int b) { 12547 scrollBar.setBounds(l, t, r, b); 12548 scrollBar.draw(canvas); 12549 } 12550 12551 /** 12552 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12553 * returns true.</p> 12554 * 12555 * @param canvas the canvas on which to draw the scrollbar 12556 * @param scrollBar the scrollbar's drawable 12557 * 12558 * @see #isVerticalScrollBarEnabled() 12559 * @see #computeVerticalScrollRange() 12560 * @see #computeVerticalScrollExtent() 12561 * @see #computeVerticalScrollOffset() 12562 * @see android.widget.ScrollBarDrawable 12563 * @hide 12564 */ 12565 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12566 int l, int t, int r, int b) { 12567 scrollBar.setBounds(l, t, r, b); 12568 scrollBar.draw(canvas); 12569 } 12570 12571 /** 12572 * Implement this to do your drawing. 12573 * 12574 * @param canvas the canvas on which the background will be drawn 12575 */ 12576 protected void onDraw(Canvas canvas) { 12577 } 12578 12579 /* 12580 * Caller is responsible for calling requestLayout if necessary. 12581 * (This allows addViewInLayout to not request a new layout.) 12582 */ 12583 void assignParent(ViewParent parent) { 12584 if (mParent == null) { 12585 mParent = parent; 12586 } else if (parent == null) { 12587 mParent = null; 12588 } else { 12589 throw new RuntimeException("view " + this + " being added, but" 12590 + " it already has a parent"); 12591 } 12592 } 12593 12594 /** 12595 * This is called when the view is attached to a window. At this point it 12596 * has a Surface and will start drawing. Note that this function is 12597 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12598 * however it may be called any time before the first onDraw -- including 12599 * before or after {@link #onMeasure(int, int)}. 12600 * 12601 * @see #onDetachedFromWindow() 12602 */ 12603 protected void onAttachedToWindow() { 12604 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12605 mParent.requestTransparentRegion(this); 12606 } 12607 12608 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12609 initialAwakenScrollBars(); 12610 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12611 } 12612 12613 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12614 12615 jumpDrawablesToCurrentState(); 12616 12617 resetSubtreeAccessibilityStateChanged(); 12618 12619 if (isFocused()) { 12620 InputMethodManager imm = InputMethodManager.peekInstance(); 12621 imm.focusIn(this); 12622 } 12623 } 12624 12625 /** 12626 * Resolve all RTL related properties. 12627 * 12628 * @return true if resolution of RTL properties has been done 12629 * 12630 * @hide 12631 */ 12632 public boolean resolveRtlPropertiesIfNeeded() { 12633 if (!needRtlPropertiesResolution()) return false; 12634 12635 // Order is important here: LayoutDirection MUST be resolved first 12636 if (!isLayoutDirectionResolved()) { 12637 resolveLayoutDirection(); 12638 resolveLayoutParams(); 12639 } 12640 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12641 if (!isTextDirectionResolved()) { 12642 resolveTextDirection(); 12643 } 12644 if (!isTextAlignmentResolved()) { 12645 resolveTextAlignment(); 12646 } 12647 // Should resolve Drawables before Padding because we need the layout direction of the 12648 // Drawable to correctly resolve Padding. 12649 if (!isDrawablesResolved()) { 12650 resolveDrawables(); 12651 } 12652 if (!isPaddingResolved()) { 12653 resolvePadding(); 12654 } 12655 onRtlPropertiesChanged(getLayoutDirection()); 12656 return true; 12657 } 12658 12659 /** 12660 * Reset resolution of all RTL related properties. 12661 * 12662 * @hide 12663 */ 12664 public void resetRtlProperties() { 12665 resetResolvedLayoutDirection(); 12666 resetResolvedTextDirection(); 12667 resetResolvedTextAlignment(); 12668 resetResolvedPadding(); 12669 resetResolvedDrawables(); 12670 } 12671 12672 /** 12673 * @see #onScreenStateChanged(int) 12674 */ 12675 void dispatchScreenStateChanged(int screenState) { 12676 onScreenStateChanged(screenState); 12677 } 12678 12679 /** 12680 * This method is called whenever the state of the screen this view is 12681 * attached to changes. A state change will usually occurs when the screen 12682 * turns on or off (whether it happens automatically or the user does it 12683 * manually.) 12684 * 12685 * @param screenState The new state of the screen. Can be either 12686 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12687 */ 12688 public void onScreenStateChanged(int screenState) { 12689 } 12690 12691 /** 12692 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12693 */ 12694 private boolean hasRtlSupport() { 12695 return mContext.getApplicationInfo().hasRtlSupport(); 12696 } 12697 12698 /** 12699 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12700 * RTL not supported) 12701 */ 12702 private boolean isRtlCompatibilityMode() { 12703 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12704 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12705 } 12706 12707 /** 12708 * @return true if RTL properties need resolution. 12709 * 12710 */ 12711 private boolean needRtlPropertiesResolution() { 12712 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12713 } 12714 12715 /** 12716 * Called when any RTL property (layout direction or text direction or text alignment) has 12717 * been changed. 12718 * 12719 * Subclasses need to override this method to take care of cached information that depends on the 12720 * resolved layout direction, or to inform child views that inherit their layout direction. 12721 * 12722 * The default implementation does nothing. 12723 * 12724 * @param layoutDirection the direction of the layout 12725 * 12726 * @see #LAYOUT_DIRECTION_LTR 12727 * @see #LAYOUT_DIRECTION_RTL 12728 */ 12729 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 12730 } 12731 12732 /** 12733 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12734 * that the parent directionality can and will be resolved before its children. 12735 * 12736 * @return true if resolution has been done, false otherwise. 12737 * 12738 * @hide 12739 */ 12740 public boolean resolveLayoutDirection() { 12741 // Clear any previous layout direction resolution 12742 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12743 12744 if (hasRtlSupport()) { 12745 // Set resolved depending on layout direction 12746 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12747 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12748 case LAYOUT_DIRECTION_INHERIT: 12749 // We cannot resolve yet. LTR is by default and let the resolution happen again 12750 // later to get the correct resolved value 12751 if (!canResolveLayoutDirection()) return false; 12752 12753 // Parent has not yet resolved, LTR is still the default 12754 try { 12755 if (!mParent.isLayoutDirectionResolved()) return false; 12756 12757 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12758 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12759 } 12760 } catch (AbstractMethodError e) { 12761 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12762 " does not fully implement ViewParent", e); 12763 } 12764 break; 12765 case LAYOUT_DIRECTION_RTL: 12766 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12767 break; 12768 case LAYOUT_DIRECTION_LOCALE: 12769 if((LAYOUT_DIRECTION_RTL == 12770 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12771 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12772 } 12773 break; 12774 default: 12775 // Nothing to do, LTR by default 12776 } 12777 } 12778 12779 // Set to resolved 12780 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12781 return true; 12782 } 12783 12784 /** 12785 * Check if layout direction resolution can be done. 12786 * 12787 * @return true if layout direction resolution can be done otherwise return false. 12788 */ 12789 public boolean canResolveLayoutDirection() { 12790 switch (getRawLayoutDirection()) { 12791 case LAYOUT_DIRECTION_INHERIT: 12792 if (mParent != null) { 12793 try { 12794 return mParent.canResolveLayoutDirection(); 12795 } catch (AbstractMethodError e) { 12796 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12797 " does not fully implement ViewParent", e); 12798 } 12799 } 12800 return false; 12801 12802 default: 12803 return true; 12804 } 12805 } 12806 12807 /** 12808 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12809 * {@link #onMeasure(int, int)}. 12810 * 12811 * @hide 12812 */ 12813 public void resetResolvedLayoutDirection() { 12814 // Reset the current resolved bits 12815 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12816 } 12817 12818 /** 12819 * @return true if the layout direction is inherited. 12820 * 12821 * @hide 12822 */ 12823 public boolean isLayoutDirectionInherited() { 12824 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12825 } 12826 12827 /** 12828 * @return true if layout direction has been resolved. 12829 */ 12830 public boolean isLayoutDirectionResolved() { 12831 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12832 } 12833 12834 /** 12835 * Return if padding has been resolved 12836 * 12837 * @hide 12838 */ 12839 boolean isPaddingResolved() { 12840 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12841 } 12842 12843 /** 12844 * Resolves padding depending on layout direction, if applicable, and 12845 * recomputes internal padding values to adjust for scroll bars. 12846 * 12847 * @hide 12848 */ 12849 public void resolvePadding() { 12850 final int resolvedLayoutDirection = getLayoutDirection(); 12851 12852 if (!isRtlCompatibilityMode()) { 12853 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12854 // If start / end padding are defined, they will be resolved (hence overriding) to 12855 // left / right or right / left depending on the resolved layout direction. 12856 // If start / end padding are not defined, use the left / right ones. 12857 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 12858 Rect padding = sThreadLocal.get(); 12859 if (padding == null) { 12860 padding = new Rect(); 12861 sThreadLocal.set(padding); 12862 } 12863 mBackground.getPadding(padding); 12864 if (!mLeftPaddingDefined) { 12865 mUserPaddingLeftInitial = padding.left; 12866 } 12867 if (!mRightPaddingDefined) { 12868 mUserPaddingRightInitial = padding.right; 12869 } 12870 } 12871 switch (resolvedLayoutDirection) { 12872 case LAYOUT_DIRECTION_RTL: 12873 if (mUserPaddingStart != UNDEFINED_PADDING) { 12874 mUserPaddingRight = mUserPaddingStart; 12875 } else { 12876 mUserPaddingRight = mUserPaddingRightInitial; 12877 } 12878 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12879 mUserPaddingLeft = mUserPaddingEnd; 12880 } else { 12881 mUserPaddingLeft = mUserPaddingLeftInitial; 12882 } 12883 break; 12884 case LAYOUT_DIRECTION_LTR: 12885 default: 12886 if (mUserPaddingStart != UNDEFINED_PADDING) { 12887 mUserPaddingLeft = mUserPaddingStart; 12888 } else { 12889 mUserPaddingLeft = mUserPaddingLeftInitial; 12890 } 12891 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12892 mUserPaddingRight = mUserPaddingEnd; 12893 } else { 12894 mUserPaddingRight = mUserPaddingRightInitial; 12895 } 12896 } 12897 12898 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12899 } 12900 12901 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12902 onRtlPropertiesChanged(resolvedLayoutDirection); 12903 12904 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12905 } 12906 12907 /** 12908 * Reset the resolved layout direction. 12909 * 12910 * @hide 12911 */ 12912 public void resetResolvedPadding() { 12913 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12914 } 12915 12916 /** 12917 * This is called when the view is detached from a window. At this point it 12918 * no longer has a surface for drawing. 12919 * 12920 * @see #onAttachedToWindow() 12921 */ 12922 protected void onDetachedFromWindow() { 12923 } 12924 12925 /** 12926 * This is a framework-internal mirror of onDetachedFromWindow() that's called 12927 * after onDetachedFromWindow(). 12928 * 12929 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 12930 * The super method should be called at the end of the overriden method to ensure 12931 * subclasses are destroyed first 12932 * 12933 * @hide 12934 */ 12935 protected void onDetachedFromWindowInternal() { 12936 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 12937 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12938 12939 removeUnsetPressCallback(); 12940 removeLongPressCallback(); 12941 removePerformClickCallback(); 12942 removeSendViewScrolledAccessibilityEventCallback(); 12943 stopNestedScroll(); 12944 12945 destroyDrawingCache(); 12946 destroyLayer(false); 12947 12948 cleanupDraw(); 12949 mCurrentAnimation = null; 12950 } 12951 12952 private void cleanupDraw() { 12953 resetDisplayList(); 12954 if (mAttachInfo != null) { 12955 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 12956 } 12957 } 12958 12959 /** 12960 * This method ensures the hardware renderer is in a valid state 12961 * before executing the specified action. 12962 * 12963 * This method will attempt to set a valid state even if the window 12964 * the renderer is attached to was destroyed. 12965 * 12966 * This method is not guaranteed to work. If the hardware renderer 12967 * does not exist or cannot be put in a valid state, this method 12968 * will not executed the specified action. 12969 * 12970 * The specified action is executed synchronously. 12971 * 12972 * @param action The action to execute after the renderer is in a valid state 12973 * 12974 * @return True if the specified Runnable was executed, false otherwise 12975 * 12976 * @hide 12977 */ 12978 public boolean executeHardwareAction(Runnable action) { 12979 //noinspection SimplifiableIfStatement 12980 if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) { 12981 return mAttachInfo.mHardwareRenderer.safelyRun(action); 12982 } 12983 return false; 12984 } 12985 12986 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 12987 } 12988 12989 /** 12990 * @return The number of times this view has been attached to a window 12991 */ 12992 protected int getWindowAttachCount() { 12993 return mWindowAttachCount; 12994 } 12995 12996 /** 12997 * Retrieve a unique token identifying the window this view is attached to. 12998 * @return Return the window's token for use in 12999 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 13000 */ 13001 public IBinder getWindowToken() { 13002 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 13003 } 13004 13005 /** 13006 * Retrieve the {@link WindowId} for the window this view is 13007 * currently attached to. 13008 */ 13009 public WindowId getWindowId() { 13010 if (mAttachInfo == null) { 13011 return null; 13012 } 13013 if (mAttachInfo.mWindowId == null) { 13014 try { 13015 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 13016 mAttachInfo.mWindowToken); 13017 mAttachInfo.mWindowId = new WindowId( 13018 mAttachInfo.mIWindowId); 13019 } catch (RemoteException e) { 13020 } 13021 } 13022 return mAttachInfo.mWindowId; 13023 } 13024 13025 /** 13026 * Retrieve a unique token identifying the top-level "real" window of 13027 * the window that this view is attached to. That is, this is like 13028 * {@link #getWindowToken}, except if the window this view in is a panel 13029 * window (attached to another containing window), then the token of 13030 * the containing window is returned instead. 13031 * 13032 * @return Returns the associated window token, either 13033 * {@link #getWindowToken()} or the containing window's token. 13034 */ 13035 public IBinder getApplicationWindowToken() { 13036 AttachInfo ai = mAttachInfo; 13037 if (ai != null) { 13038 IBinder appWindowToken = ai.mPanelParentWindowToken; 13039 if (appWindowToken == null) { 13040 appWindowToken = ai.mWindowToken; 13041 } 13042 return appWindowToken; 13043 } 13044 return null; 13045 } 13046 13047 /** 13048 * Gets the logical display to which the view's window has been attached. 13049 * 13050 * @return The logical display, or null if the view is not currently attached to a window. 13051 */ 13052 public Display getDisplay() { 13053 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13054 } 13055 13056 /** 13057 * Retrieve private session object this view hierarchy is using to 13058 * communicate with the window manager. 13059 * @return the session object to communicate with the window manager 13060 */ 13061 /*package*/ IWindowSession getWindowSession() { 13062 return mAttachInfo != null ? mAttachInfo.mSession : null; 13063 } 13064 13065 /** 13066 * @param info the {@link android.view.View.AttachInfo} to associated with 13067 * this view 13068 */ 13069 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13070 //System.out.println("Attached! " + this); 13071 mAttachInfo = info; 13072 if (mOverlay != null) { 13073 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13074 } 13075 mWindowAttachCount++; 13076 // We will need to evaluate the drawable state at least once. 13077 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13078 if (mFloatingTreeObserver != null) { 13079 info.mTreeObserver.merge(mFloatingTreeObserver); 13080 mFloatingTreeObserver = null; 13081 } 13082 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13083 mAttachInfo.mScrollContainers.add(this); 13084 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13085 } 13086 performCollectViewAttributes(mAttachInfo, visibility); 13087 onAttachedToWindow(); 13088 13089 ListenerInfo li = mListenerInfo; 13090 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13091 li != null ? li.mOnAttachStateChangeListeners : null; 13092 if (listeners != null && listeners.size() > 0) { 13093 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13094 // perform the dispatching. The iterator is a safe guard against listeners that 13095 // could mutate the list by calling the various add/remove methods. This prevents 13096 // the array from being modified while we iterate it. 13097 for (OnAttachStateChangeListener listener : listeners) { 13098 listener.onViewAttachedToWindow(this); 13099 } 13100 } 13101 13102 int vis = info.mWindowVisibility; 13103 if (vis != GONE) { 13104 onWindowVisibilityChanged(vis); 13105 } 13106 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13107 // If nobody has evaluated the drawable state yet, then do it now. 13108 refreshDrawableState(); 13109 } 13110 needGlobalAttributesUpdate(false); 13111 } 13112 13113 void dispatchDetachedFromWindow() { 13114 AttachInfo info = mAttachInfo; 13115 if (info != null) { 13116 int vis = info.mWindowVisibility; 13117 if (vis != GONE) { 13118 onWindowVisibilityChanged(GONE); 13119 } 13120 } 13121 13122 onDetachedFromWindow(); 13123 onDetachedFromWindowInternal(); 13124 13125 ListenerInfo li = mListenerInfo; 13126 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13127 li != null ? li.mOnAttachStateChangeListeners : null; 13128 if (listeners != null && listeners.size() > 0) { 13129 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13130 // perform the dispatching. The iterator is a safe guard against listeners that 13131 // could mutate the list by calling the various add/remove methods. This prevents 13132 // the array from being modified while we iterate it. 13133 for (OnAttachStateChangeListener listener : listeners) { 13134 listener.onViewDetachedFromWindow(this); 13135 } 13136 } 13137 13138 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13139 mAttachInfo.mScrollContainers.remove(this); 13140 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13141 } 13142 13143 mAttachInfo = null; 13144 if (mOverlay != null) { 13145 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13146 } 13147 } 13148 13149 /** 13150 * Cancel any deferred high-level input events that were previously posted to the event queue. 13151 * 13152 * <p>Many views post high-level events such as click handlers to the event queue 13153 * to run deferred in order to preserve a desired user experience - clearing visible 13154 * pressed states before executing, etc. This method will abort any events of this nature 13155 * that are currently in flight.</p> 13156 * 13157 * <p>Custom views that generate their own high-level deferred input events should override 13158 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13159 * 13160 * <p>This will also cancel pending input events for any child views.</p> 13161 * 13162 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13163 * This will not impact newer events posted after this call that may occur as a result of 13164 * lower-level input events still waiting in the queue. If you are trying to prevent 13165 * double-submitted events for the duration of some sort of asynchronous transaction 13166 * you should also take other steps to protect against unexpected double inputs e.g. calling 13167 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13168 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13169 */ 13170 public final void cancelPendingInputEvents() { 13171 dispatchCancelPendingInputEvents(); 13172 } 13173 13174 /** 13175 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13176 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13177 */ 13178 void dispatchCancelPendingInputEvents() { 13179 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13180 onCancelPendingInputEvents(); 13181 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13182 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13183 " did not call through to super.onCancelPendingInputEvents()"); 13184 } 13185 } 13186 13187 /** 13188 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13189 * a parent view. 13190 * 13191 * <p>This method is responsible for removing any pending high-level input events that were 13192 * posted to the event queue to run later. Custom view classes that post their own deferred 13193 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13194 * {@link android.os.Handler} should override this method, call 13195 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13196 * </p> 13197 */ 13198 public void onCancelPendingInputEvents() { 13199 removePerformClickCallback(); 13200 cancelLongPress(); 13201 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13202 } 13203 13204 /** 13205 * Store this view hierarchy's frozen state into the given container. 13206 * 13207 * @param container The SparseArray in which to save the view's state. 13208 * 13209 * @see #restoreHierarchyState(android.util.SparseArray) 13210 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13211 * @see #onSaveInstanceState() 13212 */ 13213 public void saveHierarchyState(SparseArray<Parcelable> container) { 13214 dispatchSaveInstanceState(container); 13215 } 13216 13217 /** 13218 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13219 * this view and its children. May be overridden to modify how freezing happens to a 13220 * view's children; for example, some views may want to not store state for their children. 13221 * 13222 * @param container The SparseArray in which to save the view's state. 13223 * 13224 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13225 * @see #saveHierarchyState(android.util.SparseArray) 13226 * @see #onSaveInstanceState() 13227 */ 13228 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13229 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13230 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13231 Parcelable state = onSaveInstanceState(); 13232 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13233 throw new IllegalStateException( 13234 "Derived class did not call super.onSaveInstanceState()"); 13235 } 13236 if (state != null) { 13237 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13238 // + ": " + state); 13239 container.put(mID, state); 13240 } 13241 } 13242 } 13243 13244 /** 13245 * Hook allowing a view to generate a representation of its internal state 13246 * that can later be used to create a new instance with that same state. 13247 * This state should only contain information that is not persistent or can 13248 * not be reconstructed later. For example, you will never store your 13249 * current position on screen because that will be computed again when a 13250 * new instance of the view is placed in its view hierarchy. 13251 * <p> 13252 * Some examples of things you may store here: the current cursor position 13253 * in a text view (but usually not the text itself since that is stored in a 13254 * content provider or other persistent storage), the currently selected 13255 * item in a list view. 13256 * 13257 * @return Returns a Parcelable object containing the view's current dynamic 13258 * state, or null if there is nothing interesting to save. The 13259 * default implementation returns null. 13260 * @see #onRestoreInstanceState(android.os.Parcelable) 13261 * @see #saveHierarchyState(android.util.SparseArray) 13262 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13263 * @see #setSaveEnabled(boolean) 13264 */ 13265 protected Parcelable onSaveInstanceState() { 13266 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13267 return BaseSavedState.EMPTY_STATE; 13268 } 13269 13270 /** 13271 * Restore this view hierarchy's frozen state from the given container. 13272 * 13273 * @param container The SparseArray which holds previously frozen states. 13274 * 13275 * @see #saveHierarchyState(android.util.SparseArray) 13276 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13277 * @see #onRestoreInstanceState(android.os.Parcelable) 13278 */ 13279 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13280 dispatchRestoreInstanceState(container); 13281 } 13282 13283 /** 13284 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13285 * state for this view and its children. May be overridden to modify how restoring 13286 * happens to a view's children; for example, some views may want to not store state 13287 * for their children. 13288 * 13289 * @param container The SparseArray which holds previously saved state. 13290 * 13291 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13292 * @see #restoreHierarchyState(android.util.SparseArray) 13293 * @see #onRestoreInstanceState(android.os.Parcelable) 13294 */ 13295 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13296 if (mID != NO_ID) { 13297 Parcelable state = container.get(mID); 13298 if (state != null) { 13299 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13300 // + ": " + state); 13301 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13302 onRestoreInstanceState(state); 13303 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13304 throw new IllegalStateException( 13305 "Derived class did not call super.onRestoreInstanceState()"); 13306 } 13307 } 13308 } 13309 } 13310 13311 /** 13312 * Hook allowing a view to re-apply a representation of its internal state that had previously 13313 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13314 * null state. 13315 * 13316 * @param state The frozen state that had previously been returned by 13317 * {@link #onSaveInstanceState}. 13318 * 13319 * @see #onSaveInstanceState() 13320 * @see #restoreHierarchyState(android.util.SparseArray) 13321 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13322 */ 13323 protected void onRestoreInstanceState(Parcelable state) { 13324 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13325 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13326 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13327 + "received " + state.getClass().toString() + " instead. This usually happens " 13328 + "when two views of different type have the same id in the same hierarchy. " 13329 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13330 + "other views do not use the same id."); 13331 } 13332 } 13333 13334 /** 13335 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13336 * 13337 * @return the drawing start time in milliseconds 13338 */ 13339 public long getDrawingTime() { 13340 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13341 } 13342 13343 /** 13344 * <p>Enables or disables the duplication of the parent's state into this view. When 13345 * duplication is enabled, this view gets its drawable state from its parent rather 13346 * than from its own internal properties.</p> 13347 * 13348 * <p>Note: in the current implementation, setting this property to true after the 13349 * view was added to a ViewGroup might have no effect at all. This property should 13350 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13351 * 13352 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13353 * property is enabled, an exception will be thrown.</p> 13354 * 13355 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13356 * parent, these states should not be affected by this method.</p> 13357 * 13358 * @param enabled True to enable duplication of the parent's drawable state, false 13359 * to disable it. 13360 * 13361 * @see #getDrawableState() 13362 * @see #isDuplicateParentStateEnabled() 13363 */ 13364 public void setDuplicateParentStateEnabled(boolean enabled) { 13365 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13366 } 13367 13368 /** 13369 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13370 * 13371 * @return True if this view's drawable state is duplicated from the parent, 13372 * false otherwise 13373 * 13374 * @see #getDrawableState() 13375 * @see #setDuplicateParentStateEnabled(boolean) 13376 */ 13377 public boolean isDuplicateParentStateEnabled() { 13378 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13379 } 13380 13381 /** 13382 * <p>Specifies the type of layer backing this view. The layer can be 13383 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13384 * {@link #LAYER_TYPE_HARDWARE}.</p> 13385 * 13386 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13387 * instance that controls how the layer is composed on screen. The following 13388 * properties of the paint are taken into account when composing the layer:</p> 13389 * <ul> 13390 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13391 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13392 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13393 * </ul> 13394 * 13395 * <p>If this view has an alpha value set to < 1.0 by calling 13396 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13397 * by this view's alpha value.</p> 13398 * 13399 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13400 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13401 * for more information on when and how to use layers.</p> 13402 * 13403 * @param layerType The type of layer to use with this view, must be one of 13404 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13405 * {@link #LAYER_TYPE_HARDWARE} 13406 * @param paint The paint used to compose the layer. This argument is optional 13407 * and can be null. It is ignored when the layer type is 13408 * {@link #LAYER_TYPE_NONE} 13409 * 13410 * @see #getLayerType() 13411 * @see #LAYER_TYPE_NONE 13412 * @see #LAYER_TYPE_SOFTWARE 13413 * @see #LAYER_TYPE_HARDWARE 13414 * @see #setAlpha(float) 13415 * 13416 * @attr ref android.R.styleable#View_layerType 13417 */ 13418 public void setLayerType(int layerType, Paint paint) { 13419 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13420 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13421 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13422 } 13423 13424 if (layerType == mLayerType) { 13425 setLayerPaint(paint); 13426 return; 13427 } 13428 13429 // Destroy any previous software drawing cache if needed 13430 switch (mLayerType) { 13431 case LAYER_TYPE_HARDWARE: 13432 destroyLayer(false); 13433 // fall through - non-accelerated views may use software layer mechanism instead 13434 case LAYER_TYPE_SOFTWARE: 13435 destroyDrawingCache(); 13436 break; 13437 default: 13438 break; 13439 } 13440 13441 mLayerType = layerType; 13442 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 13443 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13444 mLocalDirtyRect = layerDisabled ? null : new Rect(); 13445 13446 invalidateParentCaches(); 13447 invalidate(true); 13448 } 13449 13450 /** 13451 * Updates the {@link Paint} object used with the current layer (used only if the current 13452 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13453 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13454 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13455 * ensure that the view gets redrawn immediately. 13456 * 13457 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13458 * instance that controls how the layer is composed on screen. The following 13459 * properties of the paint are taken into account when composing the layer:</p> 13460 * <ul> 13461 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13462 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13463 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13464 * </ul> 13465 * 13466 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13467 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13468 * 13469 * @param paint The paint used to compose the layer. This argument is optional 13470 * and can be null. It is ignored when the layer type is 13471 * {@link #LAYER_TYPE_NONE} 13472 * 13473 * @see #setLayerType(int, android.graphics.Paint) 13474 */ 13475 public void setLayerPaint(Paint paint) { 13476 int layerType = getLayerType(); 13477 if (layerType != LAYER_TYPE_NONE) { 13478 mLayerPaint = paint == null ? new Paint() : paint; 13479 if (layerType == LAYER_TYPE_HARDWARE) { 13480 HardwareLayer layer = getHardwareLayer(); 13481 if (layer != null) { 13482 layer.setLayerPaint(mLayerPaint); 13483 } 13484 invalidateViewProperty(false, false); 13485 } else { 13486 invalidate(); 13487 } 13488 } 13489 } 13490 13491 /** 13492 * Indicates whether this view has a static layer. A view with layer type 13493 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13494 * dynamic. 13495 */ 13496 boolean hasStaticLayer() { 13497 return true; 13498 } 13499 13500 /** 13501 * Indicates what type of layer is currently associated with this view. By default 13502 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13503 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13504 * for more information on the different types of layers. 13505 * 13506 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13507 * {@link #LAYER_TYPE_HARDWARE} 13508 * 13509 * @see #setLayerType(int, android.graphics.Paint) 13510 * @see #buildLayer() 13511 * @see #LAYER_TYPE_NONE 13512 * @see #LAYER_TYPE_SOFTWARE 13513 * @see #LAYER_TYPE_HARDWARE 13514 */ 13515 public int getLayerType() { 13516 return mLayerType; 13517 } 13518 13519 /** 13520 * Forces this view's layer to be created and this view to be rendered 13521 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13522 * invoking this method will have no effect. 13523 * 13524 * This method can for instance be used to render a view into its layer before 13525 * starting an animation. If this view is complex, rendering into the layer 13526 * before starting the animation will avoid skipping frames. 13527 * 13528 * @throws IllegalStateException If this view is not attached to a window 13529 * 13530 * @see #setLayerType(int, android.graphics.Paint) 13531 */ 13532 public void buildLayer() { 13533 if (mLayerType == LAYER_TYPE_NONE) return; 13534 13535 final AttachInfo attachInfo = mAttachInfo; 13536 if (attachInfo == null) { 13537 throw new IllegalStateException("This view must be attached to a window first"); 13538 } 13539 13540 switch (mLayerType) { 13541 case LAYER_TYPE_HARDWARE: 13542 getHardwareLayer(); 13543 // TODO: We need a better way to handle this case 13544 // If views have registered pre-draw listeners they need 13545 // to be notified before we build the layer. Those listeners 13546 // may however rely on other events to happen first so we 13547 // cannot just invoke them here until they don't cancel the 13548 // current frame 13549 if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) { 13550 attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates(); 13551 } 13552 break; 13553 case LAYER_TYPE_SOFTWARE: 13554 buildDrawingCache(true); 13555 break; 13556 } 13557 } 13558 13559 /** 13560 * <p>Returns a hardware layer that can be used to draw this view again 13561 * without executing its draw method.</p> 13562 * 13563 * @return A HardwareLayer ready to render, or null if an error occurred. 13564 */ 13565 HardwareLayer getHardwareLayer() { 13566 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 13567 !mAttachInfo.mHardwareRenderer.isEnabled()) { 13568 return null; 13569 } 13570 13571 final int width = mRight - mLeft; 13572 final int height = mBottom - mTop; 13573 13574 if (width == 0 || height == 0) { 13575 return null; 13576 } 13577 13578 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 13579 if (mHardwareLayer == null) { 13580 mHardwareLayer = mAttachInfo.mHardwareRenderer.createDisplayListLayer( 13581 width, height); 13582 mLocalDirtyRect.set(0, 0, width, height); 13583 } else if (mHardwareLayer.isValid()) { 13584 // This should not be necessary but applications that change 13585 // the parameters of their background drawable without calling 13586 // this.setBackground(Drawable) can leave the view in a bad state 13587 // (for instance isOpaque() returns true, but the background is 13588 // not opaque.) 13589 computeOpaqueFlags(); 13590 13591 if (mHardwareLayer.prepare(width, height, isOpaque())) { 13592 mLocalDirtyRect.set(0, 0, width, height); 13593 } 13594 } 13595 13596 mHardwareLayer.setLayerPaint(mLayerPaint); 13597 RenderNode displayList = mHardwareLayer.startRecording(); 13598 updateDisplayListIfDirty(displayList, true); 13599 mHardwareLayer.endRecording(mLocalDirtyRect); 13600 mLocalDirtyRect.setEmpty(); 13601 } 13602 13603 return mHardwareLayer; 13604 } 13605 13606 /** 13607 * Destroys this View's hardware layer if possible. 13608 * 13609 * @return True if the layer was destroyed, false otherwise. 13610 * 13611 * @see #setLayerType(int, android.graphics.Paint) 13612 * @see #LAYER_TYPE_HARDWARE 13613 */ 13614 boolean destroyLayer(boolean valid) { 13615 if (mHardwareLayer != null) { 13616 mHardwareLayer.destroy(); 13617 mHardwareLayer = null; 13618 13619 invalidate(true); 13620 invalidateParentCaches(); 13621 return true; 13622 } 13623 return false; 13624 } 13625 13626 /** 13627 * Destroys all hardware rendering resources. This method is invoked 13628 * when the system needs to reclaim resources. Upon execution of this 13629 * method, you should free any OpenGL resources created by the view. 13630 * 13631 * Note: you <strong>must</strong> call 13632 * <code>super.destroyHardwareResources()</code> when overriding 13633 * this method. 13634 * 13635 * @hide 13636 */ 13637 protected void destroyHardwareResources() { 13638 resetDisplayList(); 13639 destroyLayer(true); 13640 } 13641 13642 /** 13643 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13644 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13645 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13646 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13647 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13648 * null.</p> 13649 * 13650 * <p>Enabling the drawing cache is similar to 13651 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13652 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13653 * drawing cache has no effect on rendering because the system uses a different mechanism 13654 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13655 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13656 * for information on how to enable software and hardware layers.</p> 13657 * 13658 * <p>This API can be used to manually generate 13659 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13660 * {@link #getDrawingCache()}.</p> 13661 * 13662 * @param enabled true to enable the drawing cache, false otherwise 13663 * 13664 * @see #isDrawingCacheEnabled() 13665 * @see #getDrawingCache() 13666 * @see #buildDrawingCache() 13667 * @see #setLayerType(int, android.graphics.Paint) 13668 */ 13669 public void setDrawingCacheEnabled(boolean enabled) { 13670 mCachingFailed = false; 13671 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13672 } 13673 13674 /** 13675 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13676 * 13677 * @return true if the drawing cache is enabled 13678 * 13679 * @see #setDrawingCacheEnabled(boolean) 13680 * @see #getDrawingCache() 13681 */ 13682 @ViewDebug.ExportedProperty(category = "drawing") 13683 public boolean isDrawingCacheEnabled() { 13684 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13685 } 13686 13687 /** 13688 * Debugging utility which recursively outputs the dirty state of a view and its 13689 * descendants. 13690 * 13691 * @hide 13692 */ 13693 @SuppressWarnings({"UnusedDeclaration"}) 13694 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13695 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13696 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13697 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13698 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13699 if (clear) { 13700 mPrivateFlags &= clearMask; 13701 } 13702 if (this instanceof ViewGroup) { 13703 ViewGroup parent = (ViewGroup) this; 13704 final int count = parent.getChildCount(); 13705 for (int i = 0; i < count; i++) { 13706 final View child = parent.getChildAt(i); 13707 child.outputDirtyFlags(indent + " ", clear, clearMask); 13708 } 13709 } 13710 } 13711 13712 /** 13713 * This method is used by ViewGroup to cause its children to restore or recreate their 13714 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13715 * to recreate its own display list, which would happen if it went through the normal 13716 * draw/dispatchDraw mechanisms. 13717 * 13718 * @hide 13719 */ 13720 protected void dispatchGetDisplayList() {} 13721 13722 /** 13723 * A view that is not attached or hardware accelerated cannot create a display list. 13724 * This method checks these conditions and returns the appropriate result. 13725 * 13726 * @return true if view has the ability to create a display list, false otherwise. 13727 * 13728 * @hide 13729 */ 13730 public boolean canHaveDisplayList() { 13731 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13732 } 13733 13734 /** 13735 * Returns a DisplayList. If the incoming displayList is null, one will be created. 13736 * Otherwise, the same display list will be returned (after having been rendered into 13737 * along the way, depending on the invalidation state of the view). 13738 * 13739 * @param renderNode The previous version of this displayList, could be null. 13740 * @param isLayer Whether the requester of the display list is a layer. If so, 13741 * the view will avoid creating a layer inside the resulting display list. 13742 * @return A new or reused DisplayList object. 13743 */ 13744 private void updateDisplayListIfDirty(@NonNull RenderNode renderNode, boolean isLayer) { 13745 if (renderNode == null) { 13746 throw new IllegalArgumentException("RenderNode must not be null"); 13747 } 13748 if (!canHaveDisplayList()) { 13749 // can't populate RenderNode, don't try 13750 return; 13751 } 13752 13753 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 13754 || !renderNode.isValid() 13755 || (!isLayer && mRecreateDisplayList)) { 13756 // Don't need to recreate the display list, just need to tell our 13757 // children to restore/recreate theirs 13758 if (renderNode.isValid() 13759 && !isLayer 13760 && !mRecreateDisplayList) { 13761 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13762 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13763 dispatchGetDisplayList(); 13764 13765 return; // no work needed 13766 } 13767 13768 if (!isLayer) { 13769 // If we got here, we're recreating it. Mark it as such to ensure that 13770 // we copy in child display lists into ours in drawChild() 13771 mRecreateDisplayList = true; 13772 } 13773 13774 boolean caching = false; 13775 int width = mRight - mLeft; 13776 int height = mBottom - mTop; 13777 int layerType = getLayerType(); 13778 13779 final HardwareCanvas canvas = renderNode.start(width, height); 13780 13781 try { 13782 if (!isLayer && layerType != LAYER_TYPE_NONE) { 13783 if (layerType == LAYER_TYPE_HARDWARE) { 13784 final HardwareLayer layer = getHardwareLayer(); 13785 if (layer != null && layer.isValid()) { 13786 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13787 } else { 13788 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 13789 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 13790 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13791 } 13792 caching = true; 13793 } else { 13794 buildDrawingCache(true); 13795 Bitmap cache = getDrawingCache(true); 13796 if (cache != null) { 13797 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13798 caching = true; 13799 } 13800 } 13801 } else { 13802 13803 computeScroll(); 13804 13805 canvas.translate(-mScrollX, -mScrollY); 13806 if (!isLayer) { 13807 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13808 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13809 } 13810 13811 // Fast path for layouts with no backgrounds 13812 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13813 dispatchDraw(canvas); 13814 if (mOverlay != null && !mOverlay.isEmpty()) { 13815 mOverlay.getOverlayView().draw(canvas); 13816 } 13817 } else { 13818 draw(canvas); 13819 } 13820 } 13821 } finally { 13822 renderNode.end(canvas); 13823 renderNode.setCaching(caching); 13824 if (isLayer) { 13825 renderNode.setLeftTopRightBottom(0, 0, width, height); 13826 } else { 13827 setDisplayListProperties(renderNode); 13828 } 13829 } 13830 } else if (!isLayer) { 13831 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13832 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13833 } 13834 } 13835 13836 /** 13837 * Returns a RenderNode with View draw content recorded, which can be 13838 * used to draw this view again without executing its draw method. 13839 * 13840 * @return A RenderNode ready to replay, or null if caching is not enabled. 13841 * 13842 * @hide 13843 */ 13844 public RenderNode getDisplayList() { 13845 updateDisplayListIfDirty(mRenderNode, false); 13846 return mRenderNode; 13847 } 13848 13849 private void resetDisplayList() { 13850 if (mRenderNode.isValid()) { 13851 mRenderNode.destroyDisplayListData(); 13852 } 13853 13854 if (mBackgroundDisplayList != null && mBackgroundDisplayList.isValid()) { 13855 mBackgroundDisplayList.destroyDisplayListData(); 13856 } 13857 } 13858 13859 /** 13860 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13861 * 13862 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13863 * 13864 * @see #getDrawingCache(boolean) 13865 */ 13866 public Bitmap getDrawingCache() { 13867 return getDrawingCache(false); 13868 } 13869 13870 /** 13871 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13872 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13873 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13874 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13875 * request the drawing cache by calling this method and draw it on screen if the 13876 * returned bitmap is not null.</p> 13877 * 13878 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13879 * this method will create a bitmap of the same size as this view. Because this bitmap 13880 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13881 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13882 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13883 * size than the view. This implies that your application must be able to handle this 13884 * size.</p> 13885 * 13886 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13887 * the current density of the screen when the application is in compatibility 13888 * mode. 13889 * 13890 * @return A bitmap representing this view or null if cache is disabled. 13891 * 13892 * @see #setDrawingCacheEnabled(boolean) 13893 * @see #isDrawingCacheEnabled() 13894 * @see #buildDrawingCache(boolean) 13895 * @see #destroyDrawingCache() 13896 */ 13897 public Bitmap getDrawingCache(boolean autoScale) { 13898 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13899 return null; 13900 } 13901 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13902 buildDrawingCache(autoScale); 13903 } 13904 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13905 } 13906 13907 /** 13908 * <p>Frees the resources used by the drawing cache. If you call 13909 * {@link #buildDrawingCache()} manually without calling 13910 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13911 * should cleanup the cache with this method afterwards.</p> 13912 * 13913 * @see #setDrawingCacheEnabled(boolean) 13914 * @see #buildDrawingCache() 13915 * @see #getDrawingCache() 13916 */ 13917 public void destroyDrawingCache() { 13918 if (mDrawingCache != null) { 13919 mDrawingCache.recycle(); 13920 mDrawingCache = null; 13921 } 13922 if (mUnscaledDrawingCache != null) { 13923 mUnscaledDrawingCache.recycle(); 13924 mUnscaledDrawingCache = null; 13925 } 13926 } 13927 13928 /** 13929 * Setting a solid background color for the drawing cache's bitmaps will improve 13930 * performance and memory usage. Note, though that this should only be used if this 13931 * view will always be drawn on top of a solid color. 13932 * 13933 * @param color The background color to use for the drawing cache's bitmap 13934 * 13935 * @see #setDrawingCacheEnabled(boolean) 13936 * @see #buildDrawingCache() 13937 * @see #getDrawingCache() 13938 */ 13939 public void setDrawingCacheBackgroundColor(int color) { 13940 if (color != mDrawingCacheBackgroundColor) { 13941 mDrawingCacheBackgroundColor = color; 13942 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13943 } 13944 } 13945 13946 /** 13947 * @see #setDrawingCacheBackgroundColor(int) 13948 * 13949 * @return The background color to used for the drawing cache's bitmap 13950 */ 13951 public int getDrawingCacheBackgroundColor() { 13952 return mDrawingCacheBackgroundColor; 13953 } 13954 13955 /** 13956 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13957 * 13958 * @see #buildDrawingCache(boolean) 13959 */ 13960 public void buildDrawingCache() { 13961 buildDrawingCache(false); 13962 } 13963 13964 /** 13965 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13966 * 13967 * <p>If you call {@link #buildDrawingCache()} manually without calling 13968 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13969 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13970 * 13971 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13972 * this method will create a bitmap of the same size as this view. Because this bitmap 13973 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13974 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13975 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13976 * size than the view. This implies that your application must be able to handle this 13977 * size.</p> 13978 * 13979 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13980 * you do not need the drawing cache bitmap, calling this method will increase memory 13981 * usage and cause the view to be rendered in software once, thus negatively impacting 13982 * performance.</p> 13983 * 13984 * @see #getDrawingCache() 13985 * @see #destroyDrawingCache() 13986 */ 13987 public void buildDrawingCache(boolean autoScale) { 13988 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13989 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13990 mCachingFailed = false; 13991 13992 int width = mRight - mLeft; 13993 int height = mBottom - mTop; 13994 13995 final AttachInfo attachInfo = mAttachInfo; 13996 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13997 13998 if (autoScale && scalingRequired) { 13999 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 14000 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 14001 } 14002 14003 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 14004 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 14005 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 14006 14007 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 14008 final long drawingCacheSize = 14009 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 14010 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 14011 if (width > 0 && height > 0) { 14012 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 14013 + projectedBitmapSize + " bytes, only " 14014 + drawingCacheSize + " available"); 14015 } 14016 destroyDrawingCache(); 14017 mCachingFailed = true; 14018 return; 14019 } 14020 14021 boolean clear = true; 14022 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 14023 14024 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 14025 Bitmap.Config quality; 14026 if (!opaque) { 14027 // Never pick ARGB_4444 because it looks awful 14028 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 14029 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 14030 case DRAWING_CACHE_QUALITY_AUTO: 14031 case DRAWING_CACHE_QUALITY_LOW: 14032 case DRAWING_CACHE_QUALITY_HIGH: 14033 default: 14034 quality = Bitmap.Config.ARGB_8888; 14035 break; 14036 } 14037 } else { 14038 // Optimization for translucent windows 14039 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 14040 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 14041 } 14042 14043 // Try to cleanup memory 14044 if (bitmap != null) bitmap.recycle(); 14045 14046 try { 14047 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14048 width, height, quality); 14049 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 14050 if (autoScale) { 14051 mDrawingCache = bitmap; 14052 } else { 14053 mUnscaledDrawingCache = bitmap; 14054 } 14055 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 14056 } catch (OutOfMemoryError e) { 14057 // If there is not enough memory to create the bitmap cache, just 14058 // ignore the issue as bitmap caches are not required to draw the 14059 // view hierarchy 14060 if (autoScale) { 14061 mDrawingCache = null; 14062 } else { 14063 mUnscaledDrawingCache = null; 14064 } 14065 mCachingFailed = true; 14066 return; 14067 } 14068 14069 clear = drawingCacheBackgroundColor != 0; 14070 } 14071 14072 Canvas canvas; 14073 if (attachInfo != null) { 14074 canvas = attachInfo.mCanvas; 14075 if (canvas == null) { 14076 canvas = new Canvas(); 14077 } 14078 canvas.setBitmap(bitmap); 14079 // Temporarily clobber the cached Canvas in case one of our children 14080 // is also using a drawing cache. Without this, the children would 14081 // steal the canvas by attaching their own bitmap to it and bad, bad 14082 // thing would happen (invisible views, corrupted drawings, etc.) 14083 attachInfo.mCanvas = null; 14084 } else { 14085 // This case should hopefully never or seldom happen 14086 canvas = new Canvas(bitmap); 14087 } 14088 14089 if (clear) { 14090 bitmap.eraseColor(drawingCacheBackgroundColor); 14091 } 14092 14093 computeScroll(); 14094 final int restoreCount = canvas.save(); 14095 14096 if (autoScale && scalingRequired) { 14097 final float scale = attachInfo.mApplicationScale; 14098 canvas.scale(scale, scale); 14099 } 14100 14101 canvas.translate(-mScrollX, -mScrollY); 14102 14103 mPrivateFlags |= PFLAG_DRAWN; 14104 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 14105 mLayerType != LAYER_TYPE_NONE) { 14106 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 14107 } 14108 14109 // Fast path for layouts with no backgrounds 14110 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14111 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14112 dispatchDraw(canvas); 14113 if (mOverlay != null && !mOverlay.isEmpty()) { 14114 mOverlay.getOverlayView().draw(canvas); 14115 } 14116 } else { 14117 draw(canvas); 14118 } 14119 14120 canvas.restoreToCount(restoreCount); 14121 canvas.setBitmap(null); 14122 14123 if (attachInfo != null) { 14124 // Restore the cached Canvas for our siblings 14125 attachInfo.mCanvas = canvas; 14126 } 14127 } 14128 } 14129 14130 /** 14131 * Create a snapshot of the view into a bitmap. We should probably make 14132 * some form of this public, but should think about the API. 14133 */ 14134 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14135 int width = mRight - mLeft; 14136 int height = mBottom - mTop; 14137 14138 final AttachInfo attachInfo = mAttachInfo; 14139 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14140 width = (int) ((width * scale) + 0.5f); 14141 height = (int) ((height * scale) + 0.5f); 14142 14143 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14144 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14145 if (bitmap == null) { 14146 throw new OutOfMemoryError(); 14147 } 14148 14149 Resources resources = getResources(); 14150 if (resources != null) { 14151 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14152 } 14153 14154 Canvas canvas; 14155 if (attachInfo != null) { 14156 canvas = attachInfo.mCanvas; 14157 if (canvas == null) { 14158 canvas = new Canvas(); 14159 } 14160 canvas.setBitmap(bitmap); 14161 // Temporarily clobber the cached Canvas in case one of our children 14162 // is also using a drawing cache. Without this, the children would 14163 // steal the canvas by attaching their own bitmap to it and bad, bad 14164 // things would happen (invisible views, corrupted drawings, etc.) 14165 attachInfo.mCanvas = null; 14166 } else { 14167 // This case should hopefully never or seldom happen 14168 canvas = new Canvas(bitmap); 14169 } 14170 14171 if ((backgroundColor & 0xff000000) != 0) { 14172 bitmap.eraseColor(backgroundColor); 14173 } 14174 14175 computeScroll(); 14176 final int restoreCount = canvas.save(); 14177 canvas.scale(scale, scale); 14178 canvas.translate(-mScrollX, -mScrollY); 14179 14180 // Temporarily remove the dirty mask 14181 int flags = mPrivateFlags; 14182 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14183 14184 // Fast path for layouts with no backgrounds 14185 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14186 dispatchDraw(canvas); 14187 if (mOverlay != null && !mOverlay.isEmpty()) { 14188 mOverlay.getOverlayView().draw(canvas); 14189 } 14190 } else { 14191 draw(canvas); 14192 } 14193 14194 mPrivateFlags = flags; 14195 14196 canvas.restoreToCount(restoreCount); 14197 canvas.setBitmap(null); 14198 14199 if (attachInfo != null) { 14200 // Restore the cached Canvas for our siblings 14201 attachInfo.mCanvas = canvas; 14202 } 14203 14204 return bitmap; 14205 } 14206 14207 /** 14208 * Indicates whether this View is currently in edit mode. A View is usually 14209 * in edit mode when displayed within a developer tool. For instance, if 14210 * this View is being drawn by a visual user interface builder, this method 14211 * should return true. 14212 * 14213 * Subclasses should check the return value of this method to provide 14214 * different behaviors if their normal behavior might interfere with the 14215 * host environment. For instance: the class spawns a thread in its 14216 * constructor, the drawing code relies on device-specific features, etc. 14217 * 14218 * This method is usually checked in the drawing code of custom widgets. 14219 * 14220 * @return True if this View is in edit mode, false otherwise. 14221 */ 14222 public boolean isInEditMode() { 14223 return false; 14224 } 14225 14226 /** 14227 * If the View draws content inside its padding and enables fading edges, 14228 * it needs to support padding offsets. Padding offsets are added to the 14229 * fading edges to extend the length of the fade so that it covers pixels 14230 * drawn inside the padding. 14231 * 14232 * Subclasses of this class should override this method if they need 14233 * to draw content inside the padding. 14234 * 14235 * @return True if padding offset must be applied, false otherwise. 14236 * 14237 * @see #getLeftPaddingOffset() 14238 * @see #getRightPaddingOffset() 14239 * @see #getTopPaddingOffset() 14240 * @see #getBottomPaddingOffset() 14241 * 14242 * @since CURRENT 14243 */ 14244 protected boolean isPaddingOffsetRequired() { 14245 return false; 14246 } 14247 14248 /** 14249 * Amount by which to extend the left fading region. Called only when 14250 * {@link #isPaddingOffsetRequired()} returns true. 14251 * 14252 * @return The left padding offset in pixels. 14253 * 14254 * @see #isPaddingOffsetRequired() 14255 * 14256 * @since CURRENT 14257 */ 14258 protected int getLeftPaddingOffset() { 14259 return 0; 14260 } 14261 14262 /** 14263 * Amount by which to extend the right fading region. Called only when 14264 * {@link #isPaddingOffsetRequired()} returns true. 14265 * 14266 * @return The right padding offset in pixels. 14267 * 14268 * @see #isPaddingOffsetRequired() 14269 * 14270 * @since CURRENT 14271 */ 14272 protected int getRightPaddingOffset() { 14273 return 0; 14274 } 14275 14276 /** 14277 * Amount by which to extend the top fading region. Called only when 14278 * {@link #isPaddingOffsetRequired()} returns true. 14279 * 14280 * @return The top padding offset in pixels. 14281 * 14282 * @see #isPaddingOffsetRequired() 14283 * 14284 * @since CURRENT 14285 */ 14286 protected int getTopPaddingOffset() { 14287 return 0; 14288 } 14289 14290 /** 14291 * Amount by which to extend the bottom fading region. Called only when 14292 * {@link #isPaddingOffsetRequired()} returns true. 14293 * 14294 * @return The bottom padding offset in pixels. 14295 * 14296 * @see #isPaddingOffsetRequired() 14297 * 14298 * @since CURRENT 14299 */ 14300 protected int getBottomPaddingOffset() { 14301 return 0; 14302 } 14303 14304 /** 14305 * @hide 14306 * @param offsetRequired 14307 */ 14308 protected int getFadeTop(boolean offsetRequired) { 14309 int top = mPaddingTop; 14310 if (offsetRequired) top += getTopPaddingOffset(); 14311 return top; 14312 } 14313 14314 /** 14315 * @hide 14316 * @param offsetRequired 14317 */ 14318 protected int getFadeHeight(boolean offsetRequired) { 14319 int padding = mPaddingTop; 14320 if (offsetRequired) padding += getTopPaddingOffset(); 14321 return mBottom - mTop - mPaddingBottom - padding; 14322 } 14323 14324 /** 14325 * <p>Indicates whether this view is attached to a hardware accelerated 14326 * window or not.</p> 14327 * 14328 * <p>Even if this method returns true, it does not mean that every call 14329 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14330 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14331 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14332 * window is hardware accelerated, 14333 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14334 * return false, and this method will return true.</p> 14335 * 14336 * @return True if the view is attached to a window and the window is 14337 * hardware accelerated; false in any other case. 14338 */ 14339 public boolean isHardwareAccelerated() { 14340 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14341 } 14342 14343 /** 14344 * Sets a rectangular area on this view to which the view will be clipped 14345 * when it is drawn. Setting the value to null will remove the clip bounds 14346 * and the view will draw normally, using its full bounds. 14347 * 14348 * @param clipBounds The rectangular area, in the local coordinates of 14349 * this view, to which future drawing operations will be clipped. 14350 */ 14351 public void setClipBounds(Rect clipBounds) { 14352 if (clipBounds != null) { 14353 if (clipBounds.equals(mClipBounds)) { 14354 return; 14355 } 14356 if (mClipBounds == null) { 14357 invalidate(); 14358 mClipBounds = new Rect(clipBounds); 14359 } else { 14360 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14361 Math.min(mClipBounds.top, clipBounds.top), 14362 Math.max(mClipBounds.right, clipBounds.right), 14363 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14364 mClipBounds.set(clipBounds); 14365 } 14366 } else { 14367 if (mClipBounds != null) { 14368 invalidate(); 14369 mClipBounds = null; 14370 } 14371 } 14372 } 14373 14374 /** 14375 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14376 * 14377 * @return A copy of the current clip bounds if clip bounds are set, 14378 * otherwise null. 14379 */ 14380 public Rect getClipBounds() { 14381 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14382 } 14383 14384 /** 14385 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14386 * case of an active Animation being run on the view. 14387 */ 14388 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14389 Animation a, boolean scalingRequired) { 14390 Transformation invalidationTransform; 14391 final int flags = parent.mGroupFlags; 14392 final boolean initialized = a.isInitialized(); 14393 if (!initialized) { 14394 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14395 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14396 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14397 onAnimationStart(); 14398 } 14399 14400 final Transformation t = parent.getChildTransformation(); 14401 boolean more = a.getTransformation(drawingTime, t, 1f); 14402 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14403 if (parent.mInvalidationTransformation == null) { 14404 parent.mInvalidationTransformation = new Transformation(); 14405 } 14406 invalidationTransform = parent.mInvalidationTransformation; 14407 a.getTransformation(drawingTime, invalidationTransform, 1f); 14408 } else { 14409 invalidationTransform = t; 14410 } 14411 14412 if (more) { 14413 if (!a.willChangeBounds()) { 14414 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14415 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14416 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14417 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14418 // The child need to draw an animation, potentially offscreen, so 14419 // make sure we do not cancel invalidate requests 14420 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14421 parent.invalidate(mLeft, mTop, mRight, mBottom); 14422 } 14423 } else { 14424 if (parent.mInvalidateRegion == null) { 14425 parent.mInvalidateRegion = new RectF(); 14426 } 14427 final RectF region = parent.mInvalidateRegion; 14428 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14429 invalidationTransform); 14430 14431 // The child need to draw an animation, potentially offscreen, so 14432 // make sure we do not cancel invalidate requests 14433 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14434 14435 final int left = mLeft + (int) region.left; 14436 final int top = mTop + (int) region.top; 14437 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14438 top + (int) (region.height() + .5f)); 14439 } 14440 } 14441 return more; 14442 } 14443 14444 /** 14445 * This method is called by getDisplayList() when a display list is recorded for a View. 14446 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14447 */ 14448 void setDisplayListProperties(RenderNode renderNode) { 14449 if (renderNode != null) { 14450 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14451 if (mParent instanceof ViewGroup) { 14452 renderNode.setClipToBounds( 14453 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14454 } 14455 float alpha = 1; 14456 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14457 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14458 ViewGroup parentVG = (ViewGroup) mParent; 14459 final Transformation t = parentVG.getChildTransformation(); 14460 if (parentVG.getChildStaticTransformation(this, t)) { 14461 final int transformType = t.getTransformationType(); 14462 if (transformType != Transformation.TYPE_IDENTITY) { 14463 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14464 alpha = t.getAlpha(); 14465 } 14466 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14467 renderNode.setStaticMatrix(t.getMatrix()); 14468 } 14469 } 14470 } 14471 } 14472 if (mTransformationInfo != null) { 14473 alpha *= getFinalAlpha(); 14474 if (alpha < 1) { 14475 final int multipliedAlpha = (int) (255 * alpha); 14476 if (onSetAlpha(multipliedAlpha)) { 14477 alpha = 1; 14478 } 14479 } 14480 renderNode.setAlpha(alpha); 14481 } else if (alpha < 1) { 14482 renderNode.setAlpha(alpha); 14483 } 14484 } 14485 } 14486 14487 /** 14488 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14489 * This draw() method is an implementation detail and is not intended to be overridden or 14490 * to be called from anywhere else other than ViewGroup.drawChild(). 14491 */ 14492 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14493 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14494 boolean more = false; 14495 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14496 final int flags = parent.mGroupFlags; 14497 14498 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14499 parent.getChildTransformation().clear(); 14500 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14501 } 14502 14503 Transformation transformToApply = null; 14504 boolean concatMatrix = false; 14505 14506 boolean scalingRequired = false; 14507 boolean caching; 14508 int layerType = getLayerType(); 14509 14510 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14511 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14512 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14513 caching = true; 14514 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14515 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14516 } else { 14517 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14518 } 14519 14520 final Animation a = getAnimation(); 14521 if (a != null) { 14522 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14523 concatMatrix = a.willChangeTransformationMatrix(); 14524 if (concatMatrix) { 14525 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14526 } 14527 transformToApply = parent.getChildTransformation(); 14528 } else { 14529 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14530 // No longer animating: clear out old animation matrix 14531 mRenderNode.setAnimationMatrix(null); 14532 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14533 } 14534 if (!useDisplayListProperties && 14535 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14536 final Transformation t = parent.getChildTransformation(); 14537 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14538 if (hasTransform) { 14539 final int transformType = t.getTransformationType(); 14540 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14541 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14542 } 14543 } 14544 } 14545 14546 concatMatrix |= !childHasIdentityMatrix; 14547 14548 // Sets the flag as early as possible to allow draw() implementations 14549 // to call invalidate() successfully when doing animations 14550 mPrivateFlags |= PFLAG_DRAWN; 14551 14552 if (!concatMatrix && 14553 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14554 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14555 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14556 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14557 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14558 return more; 14559 } 14560 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14561 14562 if (hardwareAccelerated) { 14563 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14564 // retain the flag's value temporarily in the mRecreateDisplayList flag 14565 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14566 mPrivateFlags &= ~PFLAG_INVALIDATED; 14567 } 14568 14569 RenderNode displayList = null; 14570 Bitmap cache = null; 14571 boolean hasDisplayList = false; 14572 if (caching) { 14573 if (!hardwareAccelerated) { 14574 if (layerType != LAYER_TYPE_NONE) { 14575 layerType = LAYER_TYPE_SOFTWARE; 14576 buildDrawingCache(true); 14577 } 14578 cache = getDrawingCache(true); 14579 } else { 14580 switch (layerType) { 14581 case LAYER_TYPE_SOFTWARE: 14582 if (useDisplayListProperties) { 14583 hasDisplayList = canHaveDisplayList(); 14584 } else { 14585 buildDrawingCache(true); 14586 cache = getDrawingCache(true); 14587 } 14588 break; 14589 case LAYER_TYPE_HARDWARE: 14590 if (useDisplayListProperties) { 14591 hasDisplayList = canHaveDisplayList(); 14592 } 14593 break; 14594 case LAYER_TYPE_NONE: 14595 // Delay getting the display list until animation-driven alpha values are 14596 // set up and possibly passed on to the view 14597 hasDisplayList = canHaveDisplayList(); 14598 break; 14599 } 14600 } 14601 } 14602 useDisplayListProperties &= hasDisplayList; 14603 if (useDisplayListProperties) { 14604 displayList = getDisplayList(); 14605 if (!displayList.isValid()) { 14606 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14607 // to getDisplayList(), the display list will be marked invalid and we should not 14608 // try to use it again. 14609 displayList = null; 14610 hasDisplayList = false; 14611 useDisplayListProperties = false; 14612 } 14613 } 14614 14615 int sx = 0; 14616 int sy = 0; 14617 if (!hasDisplayList) { 14618 computeScroll(); 14619 sx = mScrollX; 14620 sy = mScrollY; 14621 } 14622 14623 final boolean hasNoCache = cache == null || hasDisplayList; 14624 final boolean offsetForScroll = cache == null && !hasDisplayList && 14625 layerType != LAYER_TYPE_HARDWARE; 14626 14627 int restoreTo = -1; 14628 if (!useDisplayListProperties || transformToApply != null) { 14629 restoreTo = canvas.save(); 14630 } 14631 if (offsetForScroll) { 14632 canvas.translate(mLeft - sx, mTop - sy); 14633 } else { 14634 if (!useDisplayListProperties) { 14635 canvas.translate(mLeft, mTop); 14636 } 14637 if (scalingRequired) { 14638 if (useDisplayListProperties) { 14639 // TODO: Might not need this if we put everything inside the DL 14640 restoreTo = canvas.save(); 14641 } 14642 // mAttachInfo cannot be null, otherwise scalingRequired == false 14643 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14644 canvas.scale(scale, scale); 14645 } 14646 } 14647 14648 float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14649 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14650 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14651 if (transformToApply != null || !childHasIdentityMatrix) { 14652 int transX = 0; 14653 int transY = 0; 14654 14655 if (offsetForScroll) { 14656 transX = -sx; 14657 transY = -sy; 14658 } 14659 14660 if (transformToApply != null) { 14661 if (concatMatrix) { 14662 if (useDisplayListProperties) { 14663 displayList.setAnimationMatrix(transformToApply.getMatrix()); 14664 } else { 14665 // Undo the scroll translation, apply the transformation matrix, 14666 // then redo the scroll translate to get the correct result. 14667 canvas.translate(-transX, -transY); 14668 canvas.concat(transformToApply.getMatrix()); 14669 canvas.translate(transX, transY); 14670 } 14671 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14672 } 14673 14674 float transformAlpha = transformToApply.getAlpha(); 14675 if (transformAlpha < 1) { 14676 alpha *= transformAlpha; 14677 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14678 } 14679 } 14680 14681 if (!childHasIdentityMatrix && !useDisplayListProperties) { 14682 canvas.translate(-transX, -transY); 14683 canvas.concat(getMatrix()); 14684 canvas.translate(transX, transY); 14685 } 14686 } 14687 14688 // Deal with alpha if it is or used to be <1 14689 if (alpha < 1 || 14690 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14691 if (alpha < 1) { 14692 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14693 } else { 14694 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14695 } 14696 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14697 if (hasNoCache) { 14698 final int multipliedAlpha = (int) (255 * alpha); 14699 if (!onSetAlpha(multipliedAlpha)) { 14700 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14701 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14702 layerType != LAYER_TYPE_NONE) { 14703 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14704 } 14705 if (useDisplayListProperties) { 14706 displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14707 } else if (layerType == LAYER_TYPE_NONE) { 14708 final int scrollX = hasDisplayList ? 0 : sx; 14709 final int scrollY = hasDisplayList ? 0 : sy; 14710 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 14711 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 14712 } 14713 } else { 14714 // Alpha is handled by the child directly, clobber the layer's alpha 14715 mPrivateFlags |= PFLAG_ALPHA_SET; 14716 } 14717 } 14718 } 14719 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14720 onSetAlpha(255); 14721 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14722 } 14723 14724 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 14725 !useDisplayListProperties && cache == null) { 14726 if (offsetForScroll) { 14727 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14728 } else { 14729 if (!scalingRequired || cache == null) { 14730 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14731 } else { 14732 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14733 } 14734 } 14735 } 14736 14737 if (!useDisplayListProperties && hasDisplayList) { 14738 displayList = getDisplayList(); 14739 if (!displayList.isValid()) { 14740 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14741 // to getDisplayList(), the display list will be marked invalid and we should not 14742 // try to use it again. 14743 displayList = null; 14744 hasDisplayList = false; 14745 } 14746 } 14747 14748 if (hasNoCache) { 14749 boolean layerRendered = false; 14750 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 14751 final HardwareLayer layer = getHardwareLayer(); 14752 if (layer != null && layer.isValid()) { 14753 mLayerPaint.setAlpha((int) (alpha * 255)); 14754 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14755 layerRendered = true; 14756 } else { 14757 final int scrollX = hasDisplayList ? 0 : sx; 14758 final int scrollY = hasDisplayList ? 0 : sy; 14759 canvas.saveLayer(scrollX, scrollY, 14760 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14761 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14762 } 14763 } 14764 14765 if (!layerRendered) { 14766 if (!hasDisplayList) { 14767 // Fast path for layouts with no backgrounds 14768 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14769 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14770 dispatchDraw(canvas); 14771 } else { 14772 draw(canvas); 14773 } 14774 } else { 14775 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14776 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 14777 } 14778 } 14779 } else if (cache != null) { 14780 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14781 Paint cachePaint; 14782 14783 if (layerType == LAYER_TYPE_NONE) { 14784 cachePaint = parent.mCachePaint; 14785 if (cachePaint == null) { 14786 cachePaint = new Paint(); 14787 cachePaint.setDither(false); 14788 parent.mCachePaint = cachePaint; 14789 } 14790 if (alpha < 1) { 14791 cachePaint.setAlpha((int) (alpha * 255)); 14792 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14793 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14794 cachePaint.setAlpha(255); 14795 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14796 } 14797 } else { 14798 cachePaint = mLayerPaint; 14799 cachePaint.setAlpha((int) (alpha * 255)); 14800 } 14801 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14802 } 14803 14804 if (restoreTo >= 0) { 14805 canvas.restoreToCount(restoreTo); 14806 } 14807 14808 if (a != null && !more) { 14809 if (!hardwareAccelerated && !a.getFillAfter()) { 14810 onSetAlpha(255); 14811 } 14812 parent.finishAnimatingView(this, a); 14813 } 14814 14815 if (more && hardwareAccelerated) { 14816 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14817 // alpha animations should cause the child to recreate its display list 14818 invalidate(true); 14819 } 14820 } 14821 14822 mRecreateDisplayList = false; 14823 14824 return more; 14825 } 14826 14827 /** 14828 * Manually render this view (and all of its children) to the given Canvas. 14829 * The view must have already done a full layout before this function is 14830 * called. When implementing a view, implement 14831 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14832 * If you do need to override this method, call the superclass version. 14833 * 14834 * @param canvas The Canvas to which the View is rendered. 14835 */ 14836 public void draw(Canvas canvas) { 14837 if (mClipBounds != null) { 14838 canvas.clipRect(mClipBounds); 14839 } 14840 final int privateFlags = mPrivateFlags; 14841 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14842 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14843 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14844 14845 /* 14846 * Draw traversal performs several drawing steps which must be executed 14847 * in the appropriate order: 14848 * 14849 * 1. Draw the background 14850 * 2. If necessary, save the canvas' layers to prepare for fading 14851 * 3. Draw view's content 14852 * 4. Draw children 14853 * 5. If necessary, draw the fading edges and restore layers 14854 * 6. Draw decorations (scrollbars for instance) 14855 */ 14856 14857 // Step 1, draw the background, if needed 14858 int saveCount; 14859 14860 if (!dirtyOpaque) { 14861 drawBackground(canvas); 14862 } 14863 14864 // skip step 2 & 5 if possible (common case) 14865 final int viewFlags = mViewFlags; 14866 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14867 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14868 if (!verticalEdges && !horizontalEdges) { 14869 // Step 3, draw the content 14870 if (!dirtyOpaque) onDraw(canvas); 14871 14872 // Step 4, draw the children 14873 dispatchDraw(canvas); 14874 14875 // Step 6, draw decorations (scrollbars) 14876 onDrawScrollBars(canvas); 14877 14878 if (mOverlay != null && !mOverlay.isEmpty()) { 14879 mOverlay.getOverlayView().dispatchDraw(canvas); 14880 } 14881 14882 // we're done... 14883 return; 14884 } 14885 14886 /* 14887 * Here we do the full fledged routine... 14888 * (this is an uncommon case where speed matters less, 14889 * this is why we repeat some of the tests that have been 14890 * done above) 14891 */ 14892 14893 boolean drawTop = false; 14894 boolean drawBottom = false; 14895 boolean drawLeft = false; 14896 boolean drawRight = false; 14897 14898 float topFadeStrength = 0.0f; 14899 float bottomFadeStrength = 0.0f; 14900 float leftFadeStrength = 0.0f; 14901 float rightFadeStrength = 0.0f; 14902 14903 // Step 2, save the canvas' layers 14904 int paddingLeft = mPaddingLeft; 14905 14906 final boolean offsetRequired = isPaddingOffsetRequired(); 14907 if (offsetRequired) { 14908 paddingLeft += getLeftPaddingOffset(); 14909 } 14910 14911 int left = mScrollX + paddingLeft; 14912 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14913 int top = mScrollY + getFadeTop(offsetRequired); 14914 int bottom = top + getFadeHeight(offsetRequired); 14915 14916 if (offsetRequired) { 14917 right += getRightPaddingOffset(); 14918 bottom += getBottomPaddingOffset(); 14919 } 14920 14921 final ScrollabilityCache scrollabilityCache = mScrollCache; 14922 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14923 int length = (int) fadeHeight; 14924 14925 // clip the fade length if top and bottom fades overlap 14926 // overlapping fades produce odd-looking artifacts 14927 if (verticalEdges && (top + length > bottom - length)) { 14928 length = (bottom - top) / 2; 14929 } 14930 14931 // also clip horizontal fades if necessary 14932 if (horizontalEdges && (left + length > right - length)) { 14933 length = (right - left) / 2; 14934 } 14935 14936 if (verticalEdges) { 14937 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14938 drawTop = topFadeStrength * fadeHeight > 1.0f; 14939 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14940 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14941 } 14942 14943 if (horizontalEdges) { 14944 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14945 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14946 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14947 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14948 } 14949 14950 saveCount = canvas.getSaveCount(); 14951 14952 int solidColor = getSolidColor(); 14953 if (solidColor == 0) { 14954 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14955 14956 if (drawTop) { 14957 canvas.saveLayer(left, top, right, top + length, null, flags); 14958 } 14959 14960 if (drawBottom) { 14961 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14962 } 14963 14964 if (drawLeft) { 14965 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14966 } 14967 14968 if (drawRight) { 14969 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14970 } 14971 } else { 14972 scrollabilityCache.setFadeColor(solidColor); 14973 } 14974 14975 // Step 3, draw the content 14976 if (!dirtyOpaque) onDraw(canvas); 14977 14978 // Step 4, draw the children 14979 dispatchDraw(canvas); 14980 14981 // Step 5, draw the fade effect and restore layers 14982 final Paint p = scrollabilityCache.paint; 14983 final Matrix matrix = scrollabilityCache.matrix; 14984 final Shader fade = scrollabilityCache.shader; 14985 14986 if (drawTop) { 14987 matrix.setScale(1, fadeHeight * topFadeStrength); 14988 matrix.postTranslate(left, top); 14989 fade.setLocalMatrix(matrix); 14990 canvas.drawRect(left, top, right, top + length, p); 14991 } 14992 14993 if (drawBottom) { 14994 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14995 matrix.postRotate(180); 14996 matrix.postTranslate(left, bottom); 14997 fade.setLocalMatrix(matrix); 14998 canvas.drawRect(left, bottom - length, right, bottom, p); 14999 } 15000 15001 if (drawLeft) { 15002 matrix.setScale(1, fadeHeight * leftFadeStrength); 15003 matrix.postRotate(-90); 15004 matrix.postTranslate(left, top); 15005 fade.setLocalMatrix(matrix); 15006 canvas.drawRect(left, top, left + length, bottom, p); 15007 } 15008 15009 if (drawRight) { 15010 matrix.setScale(1, fadeHeight * rightFadeStrength); 15011 matrix.postRotate(90); 15012 matrix.postTranslate(right, top); 15013 fade.setLocalMatrix(matrix); 15014 canvas.drawRect(right - length, top, right, bottom, p); 15015 } 15016 15017 canvas.restoreToCount(saveCount); 15018 15019 // Step 6, draw decorations (scrollbars) 15020 onDrawScrollBars(canvas); 15021 15022 if (mOverlay != null && !mOverlay.isEmpty()) { 15023 mOverlay.getOverlayView().dispatchDraw(canvas); 15024 } 15025 } 15026 15027 /** 15028 * Draws the background onto the specified canvas. 15029 * 15030 * @param canvas Canvas on which to draw the background 15031 */ 15032 private void drawBackground(Canvas canvas) { 15033 final Drawable background = mBackground; 15034 if (background == null) { 15035 return; 15036 } 15037 15038 if (mBackgroundSizeChanged) { 15039 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 15040 mBackgroundSizeChanged = false; 15041 queryOutlineFromBackgroundIfUndefined(); 15042 } 15043 15044 // Attempt to use a display list if requested. 15045 if (canvas.isHardwareAccelerated() && mAttachInfo != null 15046 && mAttachInfo.mHardwareRenderer != null) { 15047 mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList); 15048 15049 final RenderNode displayList = mBackgroundDisplayList; 15050 if (displayList != null && displayList.isValid()) { 15051 setBackgroundDisplayListProperties(displayList); 15052 ((HardwareCanvas) canvas).drawDisplayList(displayList); 15053 return; 15054 } 15055 } 15056 15057 final int scrollX = mScrollX; 15058 final int scrollY = mScrollY; 15059 if ((scrollX | scrollY) == 0) { 15060 background.draw(canvas); 15061 } else { 15062 canvas.translate(scrollX, scrollY); 15063 background.draw(canvas); 15064 canvas.translate(-scrollX, -scrollY); 15065 } 15066 } 15067 15068 /** 15069 * Set up background drawable display list properties. 15070 * 15071 * @param displayList Valid display list for the background drawable 15072 */ 15073 private void setBackgroundDisplayListProperties(RenderNode displayList) { 15074 displayList.setTranslationX(mScrollX); 15075 displayList.setTranslationY(mScrollY); 15076 } 15077 15078 /** 15079 * Creates a new display list or updates the existing display list for the 15080 * specified Drawable. 15081 * 15082 * @param drawable Drawable for which to create a display list 15083 * @param displayList Existing display list, or {@code null} 15084 * @return A valid display list for the specified drawable 15085 */ 15086 private RenderNode getDrawableDisplayList(Drawable drawable, RenderNode displayList) { 15087 if (displayList == null) { 15088 displayList = RenderNode.create(drawable.getClass().getName()); 15089 } 15090 15091 final Rect bounds = drawable.getBounds(); 15092 final int width = bounds.width(); 15093 final int height = bounds.height(); 15094 final HardwareCanvas canvas = displayList.start(width, height); 15095 try { 15096 drawable.draw(canvas); 15097 } finally { 15098 displayList.end(canvas); 15099 } 15100 15101 // Set up drawable properties that are view-independent. 15102 displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15103 displayList.setProjectBackwards(drawable.isProjected()); 15104 displayList.setProjectionReceiver(true); 15105 displayList.setClipToBounds(false); 15106 return displayList; 15107 } 15108 15109 /** 15110 * Returns the overlay for this view, creating it if it does not yet exist. 15111 * Adding drawables to the overlay will cause them to be displayed whenever 15112 * the view itself is redrawn. Objects in the overlay should be actively 15113 * managed: remove them when they should not be displayed anymore. The 15114 * overlay will always have the same size as its host view. 15115 * 15116 * <p>Note: Overlays do not currently work correctly with {@link 15117 * SurfaceView} or {@link TextureView}; contents in overlays for these 15118 * types of views may not display correctly.</p> 15119 * 15120 * @return The ViewOverlay object for this view. 15121 * @see ViewOverlay 15122 */ 15123 public ViewOverlay getOverlay() { 15124 if (mOverlay == null) { 15125 mOverlay = new ViewOverlay(mContext, this); 15126 } 15127 return mOverlay; 15128 } 15129 15130 /** 15131 * Override this if your view is known to always be drawn on top of a solid color background, 15132 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15133 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15134 * should be set to 0xFF. 15135 * 15136 * @see #setVerticalFadingEdgeEnabled(boolean) 15137 * @see #setHorizontalFadingEdgeEnabled(boolean) 15138 * 15139 * @return The known solid color background for this view, or 0 if the color may vary 15140 */ 15141 @ViewDebug.ExportedProperty(category = "drawing") 15142 public int getSolidColor() { 15143 return 0; 15144 } 15145 15146 /** 15147 * Build a human readable string representation of the specified view flags. 15148 * 15149 * @param flags the view flags to convert to a string 15150 * @return a String representing the supplied flags 15151 */ 15152 private static String printFlags(int flags) { 15153 String output = ""; 15154 int numFlags = 0; 15155 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15156 output += "TAKES_FOCUS"; 15157 numFlags++; 15158 } 15159 15160 switch (flags & VISIBILITY_MASK) { 15161 case INVISIBLE: 15162 if (numFlags > 0) { 15163 output += " "; 15164 } 15165 output += "INVISIBLE"; 15166 // USELESS HERE numFlags++; 15167 break; 15168 case GONE: 15169 if (numFlags > 0) { 15170 output += " "; 15171 } 15172 output += "GONE"; 15173 // USELESS HERE numFlags++; 15174 break; 15175 default: 15176 break; 15177 } 15178 return output; 15179 } 15180 15181 /** 15182 * Build a human readable string representation of the specified private 15183 * view flags. 15184 * 15185 * @param privateFlags the private view flags to convert to a string 15186 * @return a String representing the supplied flags 15187 */ 15188 private static String printPrivateFlags(int privateFlags) { 15189 String output = ""; 15190 int numFlags = 0; 15191 15192 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15193 output += "WANTS_FOCUS"; 15194 numFlags++; 15195 } 15196 15197 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15198 if (numFlags > 0) { 15199 output += " "; 15200 } 15201 output += "FOCUSED"; 15202 numFlags++; 15203 } 15204 15205 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15206 if (numFlags > 0) { 15207 output += " "; 15208 } 15209 output += "SELECTED"; 15210 numFlags++; 15211 } 15212 15213 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15214 if (numFlags > 0) { 15215 output += " "; 15216 } 15217 output += "IS_ROOT_NAMESPACE"; 15218 numFlags++; 15219 } 15220 15221 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15222 if (numFlags > 0) { 15223 output += " "; 15224 } 15225 output += "HAS_BOUNDS"; 15226 numFlags++; 15227 } 15228 15229 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15230 if (numFlags > 0) { 15231 output += " "; 15232 } 15233 output += "DRAWN"; 15234 // USELESS HERE numFlags++; 15235 } 15236 return output; 15237 } 15238 15239 /** 15240 * <p>Indicates whether or not this view's layout will be requested during 15241 * the next hierarchy layout pass.</p> 15242 * 15243 * @return true if the layout will be forced during next layout pass 15244 */ 15245 public boolean isLayoutRequested() { 15246 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15247 } 15248 15249 /** 15250 * Return true if o is a ViewGroup that is laying out using optical bounds. 15251 * @hide 15252 */ 15253 public static boolean isLayoutModeOptical(Object o) { 15254 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15255 } 15256 15257 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15258 Insets parentInsets = mParent instanceof View ? 15259 ((View) mParent).getOpticalInsets() : Insets.NONE; 15260 Insets childInsets = getOpticalInsets(); 15261 return setFrame( 15262 left + parentInsets.left - childInsets.left, 15263 top + parentInsets.top - childInsets.top, 15264 right + parentInsets.left + childInsets.right, 15265 bottom + parentInsets.top + childInsets.bottom); 15266 } 15267 15268 /** 15269 * Assign a size and position to a view and all of its 15270 * descendants 15271 * 15272 * <p>This is the second phase of the layout mechanism. 15273 * (The first is measuring). In this phase, each parent calls 15274 * layout on all of its children to position them. 15275 * This is typically done using the child measurements 15276 * that were stored in the measure pass().</p> 15277 * 15278 * <p>Derived classes should not override this method. 15279 * Derived classes with children should override 15280 * onLayout. In that method, they should 15281 * call layout on each of their children.</p> 15282 * 15283 * @param l Left position, relative to parent 15284 * @param t Top position, relative to parent 15285 * @param r Right position, relative to parent 15286 * @param b Bottom position, relative to parent 15287 */ 15288 @SuppressWarnings({"unchecked"}) 15289 public void layout(int l, int t, int r, int b) { 15290 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15291 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15292 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15293 } 15294 15295 int oldL = mLeft; 15296 int oldT = mTop; 15297 int oldB = mBottom; 15298 int oldR = mRight; 15299 15300 boolean changed = isLayoutModeOptical(mParent) ? 15301 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15302 15303 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15304 onLayout(changed, l, t, r, b); 15305 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15306 15307 ListenerInfo li = mListenerInfo; 15308 if (li != null && li.mOnLayoutChangeListeners != null) { 15309 ArrayList<OnLayoutChangeListener> listenersCopy = 15310 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15311 int numListeners = listenersCopy.size(); 15312 for (int i = 0; i < numListeners; ++i) { 15313 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15314 } 15315 } 15316 } 15317 15318 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15319 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15320 } 15321 15322 /** 15323 * Called from layout when this view should 15324 * assign a size and position to each of its children. 15325 * 15326 * Derived classes with children should override 15327 * this method and call layout on each of 15328 * their children. 15329 * @param changed This is a new size or position for this view 15330 * @param left Left position, relative to parent 15331 * @param top Top position, relative to parent 15332 * @param right Right position, relative to parent 15333 * @param bottom Bottom position, relative to parent 15334 */ 15335 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15336 } 15337 15338 /** 15339 * Assign a size and position to this view. 15340 * 15341 * This is called from layout. 15342 * 15343 * @param left Left position, relative to parent 15344 * @param top Top position, relative to parent 15345 * @param right Right position, relative to parent 15346 * @param bottom Bottom position, relative to parent 15347 * @return true if the new size and position are different than the 15348 * previous ones 15349 * {@hide} 15350 */ 15351 protected boolean setFrame(int left, int top, int right, int bottom) { 15352 boolean changed = false; 15353 15354 if (DBG) { 15355 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15356 + right + "," + bottom + ")"); 15357 } 15358 15359 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15360 changed = true; 15361 15362 // Remember our drawn bit 15363 int drawn = mPrivateFlags & PFLAG_DRAWN; 15364 15365 int oldWidth = mRight - mLeft; 15366 int oldHeight = mBottom - mTop; 15367 int newWidth = right - left; 15368 int newHeight = bottom - top; 15369 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15370 15371 // Invalidate our old position 15372 invalidate(sizeChanged); 15373 15374 mLeft = left; 15375 mTop = top; 15376 mRight = right; 15377 mBottom = bottom; 15378 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15379 15380 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15381 15382 15383 if (sizeChanged) { 15384 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15385 } 15386 15387 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 15388 // If we are visible, force the DRAWN bit to on so that 15389 // this invalidate will go through (at least to our parent). 15390 // This is because someone may have invalidated this view 15391 // before this call to setFrame came in, thereby clearing 15392 // the DRAWN bit. 15393 mPrivateFlags |= PFLAG_DRAWN; 15394 invalidate(sizeChanged); 15395 // parent display list may need to be recreated based on a change in the bounds 15396 // of any child 15397 invalidateParentCaches(); 15398 } 15399 15400 // Reset drawn bit to original value (invalidate turns it off) 15401 mPrivateFlags |= drawn; 15402 15403 mBackgroundSizeChanged = true; 15404 15405 notifySubtreeAccessibilityStateChangedIfNeeded(); 15406 } 15407 return changed; 15408 } 15409 15410 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15411 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15412 if (mOverlay != null) { 15413 mOverlay.getOverlayView().setRight(newWidth); 15414 mOverlay.getOverlayView().setBottom(newHeight); 15415 } 15416 } 15417 15418 /** 15419 * Finalize inflating a view from XML. This is called as the last phase 15420 * of inflation, after all child views have been added. 15421 * 15422 * <p>Even if the subclass overrides onFinishInflate, they should always be 15423 * sure to call the super method, so that we get called. 15424 */ 15425 protected void onFinishInflate() { 15426 } 15427 15428 /** 15429 * Returns the resources associated with this view. 15430 * 15431 * @return Resources object. 15432 */ 15433 public Resources getResources() { 15434 return mResources; 15435 } 15436 15437 /** 15438 * Invalidates the specified Drawable. 15439 * 15440 * @param drawable the drawable to invalidate 15441 */ 15442 @Override 15443 public void invalidateDrawable(@NonNull Drawable drawable) { 15444 if (verifyDrawable(drawable)) { 15445 final Rect dirty = drawable.getDirtyBounds(); 15446 final int scrollX = mScrollX; 15447 final int scrollY = mScrollY; 15448 15449 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15450 dirty.right + scrollX, dirty.bottom + scrollY); 15451 15452 if (drawable == mBackground) { 15453 queryOutlineFromBackgroundIfUndefined(); 15454 } 15455 } 15456 } 15457 15458 /** 15459 * Schedules an action on a drawable to occur at a specified time. 15460 * 15461 * @param who the recipient of the action 15462 * @param what the action to run on the drawable 15463 * @param when the time at which the action must occur. Uses the 15464 * {@link SystemClock#uptimeMillis} timebase. 15465 */ 15466 @Override 15467 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15468 if (verifyDrawable(who) && what != null) { 15469 final long delay = when - SystemClock.uptimeMillis(); 15470 if (mAttachInfo != null) { 15471 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15472 Choreographer.CALLBACK_ANIMATION, what, who, 15473 Choreographer.subtractFrameDelay(delay)); 15474 } else { 15475 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15476 } 15477 } 15478 } 15479 15480 /** 15481 * Cancels a scheduled action on a drawable. 15482 * 15483 * @param who the recipient of the action 15484 * @param what the action to cancel 15485 */ 15486 @Override 15487 public void unscheduleDrawable(Drawable who, Runnable what) { 15488 if (verifyDrawable(who) && what != null) { 15489 if (mAttachInfo != null) { 15490 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15491 Choreographer.CALLBACK_ANIMATION, what, who); 15492 } 15493 ViewRootImpl.getRunQueue().removeCallbacks(what); 15494 } 15495 } 15496 15497 /** 15498 * Unschedule any events associated with the given Drawable. This can be 15499 * used when selecting a new Drawable into a view, so that the previous 15500 * one is completely unscheduled. 15501 * 15502 * @param who The Drawable to unschedule. 15503 * 15504 * @see #drawableStateChanged 15505 */ 15506 public void unscheduleDrawable(Drawable who) { 15507 if (mAttachInfo != null && who != null) { 15508 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15509 Choreographer.CALLBACK_ANIMATION, null, who); 15510 } 15511 } 15512 15513 /** 15514 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15515 * that the View directionality can and will be resolved before its Drawables. 15516 * 15517 * Will call {@link View#onResolveDrawables} when resolution is done. 15518 * 15519 * @hide 15520 */ 15521 protected void resolveDrawables() { 15522 // Drawables resolution may need to happen before resolving the layout direction (which is 15523 // done only during the measure() call). 15524 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15525 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15526 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15527 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15528 // direction to be resolved as its resolved value will be the same as its raw value. 15529 if (!isLayoutDirectionResolved() && 15530 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15531 return; 15532 } 15533 15534 final int layoutDirection = isLayoutDirectionResolved() ? 15535 getLayoutDirection() : getRawLayoutDirection(); 15536 15537 if (mBackground != null) { 15538 mBackground.setLayoutDirection(layoutDirection); 15539 } 15540 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15541 onResolveDrawables(layoutDirection); 15542 } 15543 15544 /** 15545 * Called when layout direction has been resolved. 15546 * 15547 * The default implementation does nothing. 15548 * 15549 * @param layoutDirection The resolved layout direction. 15550 * 15551 * @see #LAYOUT_DIRECTION_LTR 15552 * @see #LAYOUT_DIRECTION_RTL 15553 * 15554 * @hide 15555 */ 15556 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15557 } 15558 15559 /** 15560 * @hide 15561 */ 15562 protected void resetResolvedDrawables() { 15563 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15564 } 15565 15566 private boolean isDrawablesResolved() { 15567 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15568 } 15569 15570 /** 15571 * If your view subclass is displaying its own Drawable objects, it should 15572 * override this function and return true for any Drawable it is 15573 * displaying. This allows animations for those drawables to be 15574 * scheduled. 15575 * 15576 * <p>Be sure to call through to the super class when overriding this 15577 * function. 15578 * 15579 * @param who The Drawable to verify. Return true if it is one you are 15580 * displaying, else return the result of calling through to the 15581 * super class. 15582 * 15583 * @return boolean If true than the Drawable is being displayed in the 15584 * view; else false and it is not allowed to animate. 15585 * 15586 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15587 * @see #drawableStateChanged() 15588 */ 15589 protected boolean verifyDrawable(Drawable who) { 15590 return who == mBackground; 15591 } 15592 15593 /** 15594 * This function is called whenever the state of the view changes in such 15595 * a way that it impacts the state of drawables being shown. 15596 * <p> 15597 * If the View has a StateListAnimator, it will also be called to run necessary state 15598 * change animations. 15599 * <p> 15600 * Be sure to call through to the superclass when overriding this function. 15601 * 15602 * @see Drawable#setState(int[]) 15603 */ 15604 protected void drawableStateChanged() { 15605 final Drawable d = mBackground; 15606 if (d != null && d.isStateful()) { 15607 d.setState(getDrawableState()); 15608 } 15609 15610 if (mStateListAnimator != null) { 15611 mStateListAnimator.setState(getDrawableState()); 15612 } 15613 } 15614 15615 /** 15616 * Call this to force a view to update its drawable state. This will cause 15617 * drawableStateChanged to be called on this view. Views that are interested 15618 * in the new state should call getDrawableState. 15619 * 15620 * @see #drawableStateChanged 15621 * @see #getDrawableState 15622 */ 15623 public void refreshDrawableState() { 15624 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15625 drawableStateChanged(); 15626 15627 ViewParent parent = mParent; 15628 if (parent != null) { 15629 parent.childDrawableStateChanged(this); 15630 } 15631 } 15632 15633 /** 15634 * Return an array of resource IDs of the drawable states representing the 15635 * current state of the view. 15636 * 15637 * @return The current drawable state 15638 * 15639 * @see Drawable#setState(int[]) 15640 * @see #drawableStateChanged() 15641 * @see #onCreateDrawableState(int) 15642 */ 15643 public final int[] getDrawableState() { 15644 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15645 return mDrawableState; 15646 } else { 15647 mDrawableState = onCreateDrawableState(0); 15648 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15649 return mDrawableState; 15650 } 15651 } 15652 15653 /** 15654 * Generate the new {@link android.graphics.drawable.Drawable} state for 15655 * this view. This is called by the view 15656 * system when the cached Drawable state is determined to be invalid. To 15657 * retrieve the current state, you should use {@link #getDrawableState}. 15658 * 15659 * @param extraSpace if non-zero, this is the number of extra entries you 15660 * would like in the returned array in which you can place your own 15661 * states. 15662 * 15663 * @return Returns an array holding the current {@link Drawable} state of 15664 * the view. 15665 * 15666 * @see #mergeDrawableStates(int[], int[]) 15667 */ 15668 protected int[] onCreateDrawableState(int extraSpace) { 15669 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15670 mParent instanceof View) { 15671 return ((View) mParent).onCreateDrawableState(extraSpace); 15672 } 15673 15674 int[] drawableState; 15675 15676 int privateFlags = mPrivateFlags; 15677 15678 int viewStateIndex = 0; 15679 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15680 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15681 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15682 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15683 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15684 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15685 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15686 HardwareRenderer.isAvailable()) { 15687 // This is set if HW acceleration is requested, even if the current 15688 // process doesn't allow it. This is just to allow app preview 15689 // windows to better match their app. 15690 viewStateIndex |= VIEW_STATE_ACCELERATED; 15691 } 15692 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15693 15694 final int privateFlags2 = mPrivateFlags2; 15695 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15696 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15697 15698 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15699 15700 //noinspection ConstantIfStatement 15701 if (false) { 15702 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15703 Log.i("View", toString() 15704 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15705 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15706 + " fo=" + hasFocus() 15707 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15708 + " wf=" + hasWindowFocus() 15709 + ": " + Arrays.toString(drawableState)); 15710 } 15711 15712 if (extraSpace == 0) { 15713 return drawableState; 15714 } 15715 15716 final int[] fullState; 15717 if (drawableState != null) { 15718 fullState = new int[drawableState.length + extraSpace]; 15719 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15720 } else { 15721 fullState = new int[extraSpace]; 15722 } 15723 15724 return fullState; 15725 } 15726 15727 /** 15728 * Merge your own state values in <var>additionalState</var> into the base 15729 * state values <var>baseState</var> that were returned by 15730 * {@link #onCreateDrawableState(int)}. 15731 * 15732 * @param baseState The base state values returned by 15733 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15734 * own additional state values. 15735 * 15736 * @param additionalState The additional state values you would like 15737 * added to <var>baseState</var>; this array is not modified. 15738 * 15739 * @return As a convenience, the <var>baseState</var> array you originally 15740 * passed into the function is returned. 15741 * 15742 * @see #onCreateDrawableState(int) 15743 */ 15744 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15745 final int N = baseState.length; 15746 int i = N - 1; 15747 while (i >= 0 && baseState[i] == 0) { 15748 i--; 15749 } 15750 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15751 return baseState; 15752 } 15753 15754 /** 15755 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15756 * on all Drawable objects associated with this view. 15757 * <p> 15758 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 15759 * attached to this view. 15760 */ 15761 public void jumpDrawablesToCurrentState() { 15762 if (mBackground != null) { 15763 mBackground.jumpToCurrentState(); 15764 } 15765 if (mStateListAnimator != null) { 15766 mStateListAnimator.jumpToCurrentState(); 15767 } 15768 } 15769 15770 /** 15771 * Sets the background color for this view. 15772 * @param color the color of the background 15773 */ 15774 @RemotableViewMethod 15775 public void setBackgroundColor(int color) { 15776 if (mBackground instanceof ColorDrawable) { 15777 ((ColorDrawable) mBackground.mutate()).setColor(color); 15778 computeOpaqueFlags(); 15779 mBackgroundResource = 0; 15780 } else { 15781 setBackground(new ColorDrawable(color)); 15782 } 15783 } 15784 15785 /** 15786 * Set the background to a given resource. The resource should refer to 15787 * a Drawable object or 0 to remove the background. 15788 * @param resid The identifier of the resource. 15789 * 15790 * @attr ref android.R.styleable#View_background 15791 */ 15792 @RemotableViewMethod 15793 public void setBackgroundResource(int resid) { 15794 if (resid != 0 && resid == mBackgroundResource) { 15795 return; 15796 } 15797 15798 Drawable d= null; 15799 if (resid != 0) { 15800 d = mContext.getDrawable(resid); 15801 } 15802 setBackground(d); 15803 15804 mBackgroundResource = resid; 15805 } 15806 15807 /** 15808 * Set the background to a given Drawable, or remove the background. If the 15809 * background has padding, this View's padding is set to the background's 15810 * padding. However, when a background is removed, this View's padding isn't 15811 * touched. If setting the padding is desired, please use 15812 * {@link #setPadding(int, int, int, int)}. 15813 * 15814 * @param background The Drawable to use as the background, or null to remove the 15815 * background 15816 */ 15817 public void setBackground(Drawable background) { 15818 //noinspection deprecation 15819 setBackgroundDrawable(background); 15820 } 15821 15822 /** 15823 * @deprecated use {@link #setBackground(Drawable)} instead 15824 */ 15825 @Deprecated 15826 public void setBackgroundDrawable(Drawable background) { 15827 computeOpaqueFlags(); 15828 15829 if (background == mBackground) { 15830 return; 15831 } 15832 15833 boolean requestLayout = false; 15834 15835 mBackgroundResource = 0; 15836 15837 /* 15838 * Regardless of whether we're setting a new background or not, we want 15839 * to clear the previous drawable. 15840 */ 15841 if (mBackground != null) { 15842 mBackground.setCallback(null); 15843 unscheduleDrawable(mBackground); 15844 } 15845 15846 if (background != null) { 15847 Rect padding = sThreadLocal.get(); 15848 if (padding == null) { 15849 padding = new Rect(); 15850 sThreadLocal.set(padding); 15851 } 15852 resetResolvedDrawables(); 15853 background.setLayoutDirection(getLayoutDirection()); 15854 if (background.getPadding(padding)) { 15855 resetResolvedPadding(); 15856 switch (background.getLayoutDirection()) { 15857 case LAYOUT_DIRECTION_RTL: 15858 mUserPaddingLeftInitial = padding.right; 15859 mUserPaddingRightInitial = padding.left; 15860 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15861 break; 15862 case LAYOUT_DIRECTION_LTR: 15863 default: 15864 mUserPaddingLeftInitial = padding.left; 15865 mUserPaddingRightInitial = padding.right; 15866 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15867 } 15868 mLeftPaddingDefined = false; 15869 mRightPaddingDefined = false; 15870 } 15871 15872 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15873 // if it has a different minimum size, we should layout again 15874 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 15875 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15876 requestLayout = true; 15877 } 15878 15879 background.setCallback(this); 15880 if (background.isStateful()) { 15881 background.setState(getDrawableState()); 15882 } 15883 background.setVisible(getVisibility() == VISIBLE, false); 15884 mBackground = background; 15885 15886 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15887 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15888 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15889 requestLayout = true; 15890 } 15891 } else { 15892 /* Remove the background */ 15893 mBackground = null; 15894 15895 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15896 /* 15897 * This view ONLY drew the background before and we're removing 15898 * the background, so now it won't draw anything 15899 * (hence we SKIP_DRAW) 15900 */ 15901 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15902 mPrivateFlags |= PFLAG_SKIP_DRAW; 15903 } 15904 15905 /* 15906 * When the background is set, we try to apply its padding to this 15907 * View. When the background is removed, we don't touch this View's 15908 * padding. This is noted in the Javadocs. Hence, we don't need to 15909 * requestLayout(), the invalidate() below is sufficient. 15910 */ 15911 15912 // The old background's minimum size could have affected this 15913 // View's layout, so let's requestLayout 15914 requestLayout = true; 15915 } 15916 15917 computeOpaqueFlags(); 15918 15919 if (requestLayout) { 15920 requestLayout(); 15921 } 15922 15923 mBackgroundSizeChanged = true; 15924 invalidate(true); 15925 } 15926 15927 /** 15928 * Gets the background drawable 15929 * 15930 * @return The drawable used as the background for this view, if any. 15931 * 15932 * @see #setBackground(Drawable) 15933 * 15934 * @attr ref android.R.styleable#View_background 15935 */ 15936 public Drawable getBackground() { 15937 return mBackground; 15938 } 15939 15940 /** 15941 * Sets the padding. The view may add on the space required to display 15942 * the scrollbars, depending on the style and visibility of the scrollbars. 15943 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15944 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 15945 * from the values set in this call. 15946 * 15947 * @attr ref android.R.styleable#View_padding 15948 * @attr ref android.R.styleable#View_paddingBottom 15949 * @attr ref android.R.styleable#View_paddingLeft 15950 * @attr ref android.R.styleable#View_paddingRight 15951 * @attr ref android.R.styleable#View_paddingTop 15952 * @param left the left padding in pixels 15953 * @param top the top padding in pixels 15954 * @param right the right padding in pixels 15955 * @param bottom the bottom padding in pixels 15956 */ 15957 public void setPadding(int left, int top, int right, int bottom) { 15958 resetResolvedPadding(); 15959 15960 mUserPaddingStart = UNDEFINED_PADDING; 15961 mUserPaddingEnd = UNDEFINED_PADDING; 15962 15963 mUserPaddingLeftInitial = left; 15964 mUserPaddingRightInitial = right; 15965 15966 mLeftPaddingDefined = true; 15967 mRightPaddingDefined = true; 15968 15969 internalSetPadding(left, top, right, bottom); 15970 } 15971 15972 /** 15973 * @hide 15974 */ 15975 protected void internalSetPadding(int left, int top, int right, int bottom) { 15976 mUserPaddingLeft = left; 15977 mUserPaddingRight = right; 15978 mUserPaddingBottom = bottom; 15979 15980 final int viewFlags = mViewFlags; 15981 boolean changed = false; 15982 15983 // Common case is there are no scroll bars. 15984 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 15985 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 15986 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 15987 ? 0 : getVerticalScrollbarWidth(); 15988 switch (mVerticalScrollbarPosition) { 15989 case SCROLLBAR_POSITION_DEFAULT: 15990 if (isLayoutRtl()) { 15991 left += offset; 15992 } else { 15993 right += offset; 15994 } 15995 break; 15996 case SCROLLBAR_POSITION_RIGHT: 15997 right += offset; 15998 break; 15999 case SCROLLBAR_POSITION_LEFT: 16000 left += offset; 16001 break; 16002 } 16003 } 16004 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 16005 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 16006 ? 0 : getHorizontalScrollbarHeight(); 16007 } 16008 } 16009 16010 if (mPaddingLeft != left) { 16011 changed = true; 16012 mPaddingLeft = left; 16013 } 16014 if (mPaddingTop != top) { 16015 changed = true; 16016 mPaddingTop = top; 16017 } 16018 if (mPaddingRight != right) { 16019 changed = true; 16020 mPaddingRight = right; 16021 } 16022 if (mPaddingBottom != bottom) { 16023 changed = true; 16024 mPaddingBottom = bottom; 16025 } 16026 16027 if (changed) { 16028 requestLayout(); 16029 } 16030 } 16031 16032 /** 16033 * Sets the relative padding. The view may add on the space required to display 16034 * the scrollbars, depending on the style and visibility of the scrollbars. 16035 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16036 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16037 * from the values set in this call. 16038 * 16039 * @attr ref android.R.styleable#View_padding 16040 * @attr ref android.R.styleable#View_paddingBottom 16041 * @attr ref android.R.styleable#View_paddingStart 16042 * @attr ref android.R.styleable#View_paddingEnd 16043 * @attr ref android.R.styleable#View_paddingTop 16044 * @param start the start padding in pixels 16045 * @param top the top padding in pixels 16046 * @param end the end padding in pixels 16047 * @param bottom the bottom padding in pixels 16048 */ 16049 public void setPaddingRelative(int start, int top, int end, int bottom) { 16050 resetResolvedPadding(); 16051 16052 mUserPaddingStart = start; 16053 mUserPaddingEnd = end; 16054 mLeftPaddingDefined = true; 16055 mRightPaddingDefined = true; 16056 16057 switch(getLayoutDirection()) { 16058 case LAYOUT_DIRECTION_RTL: 16059 mUserPaddingLeftInitial = end; 16060 mUserPaddingRightInitial = start; 16061 internalSetPadding(end, top, start, bottom); 16062 break; 16063 case LAYOUT_DIRECTION_LTR: 16064 default: 16065 mUserPaddingLeftInitial = start; 16066 mUserPaddingRightInitial = end; 16067 internalSetPadding(start, top, end, bottom); 16068 } 16069 } 16070 16071 /** 16072 * Returns the top padding of this view. 16073 * 16074 * @return the top padding in pixels 16075 */ 16076 public int getPaddingTop() { 16077 return mPaddingTop; 16078 } 16079 16080 /** 16081 * Returns the bottom padding of this view. If there are inset and enabled 16082 * scrollbars, this value may include the space required to display the 16083 * scrollbars as well. 16084 * 16085 * @return the bottom padding in pixels 16086 */ 16087 public int getPaddingBottom() { 16088 return mPaddingBottom; 16089 } 16090 16091 /** 16092 * Returns the left padding of this view. If there are inset and enabled 16093 * scrollbars, this value may include the space required to display the 16094 * scrollbars as well. 16095 * 16096 * @return the left padding in pixels 16097 */ 16098 public int getPaddingLeft() { 16099 if (!isPaddingResolved()) { 16100 resolvePadding(); 16101 } 16102 return mPaddingLeft; 16103 } 16104 16105 /** 16106 * Returns the start padding of this view depending on its resolved layout direction. 16107 * If there are inset and enabled scrollbars, this value may include the space 16108 * required to display the scrollbars as well. 16109 * 16110 * @return the start padding in pixels 16111 */ 16112 public int getPaddingStart() { 16113 if (!isPaddingResolved()) { 16114 resolvePadding(); 16115 } 16116 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16117 mPaddingRight : mPaddingLeft; 16118 } 16119 16120 /** 16121 * Returns the right padding of this view. If there are inset and enabled 16122 * scrollbars, this value may include the space required to display the 16123 * scrollbars as well. 16124 * 16125 * @return the right padding in pixels 16126 */ 16127 public int getPaddingRight() { 16128 if (!isPaddingResolved()) { 16129 resolvePadding(); 16130 } 16131 return mPaddingRight; 16132 } 16133 16134 /** 16135 * Returns the end padding of this view depending on its resolved layout direction. 16136 * If there are inset and enabled scrollbars, this value may include the space 16137 * required to display the scrollbars as well. 16138 * 16139 * @return the end padding in pixels 16140 */ 16141 public int getPaddingEnd() { 16142 if (!isPaddingResolved()) { 16143 resolvePadding(); 16144 } 16145 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16146 mPaddingLeft : mPaddingRight; 16147 } 16148 16149 /** 16150 * Return if the padding as been set thru relative values 16151 * {@link #setPaddingRelative(int, int, int, int)} or thru 16152 * @attr ref android.R.styleable#View_paddingStart or 16153 * @attr ref android.R.styleable#View_paddingEnd 16154 * 16155 * @return true if the padding is relative or false if it is not. 16156 */ 16157 public boolean isPaddingRelative() { 16158 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16159 } 16160 16161 Insets computeOpticalInsets() { 16162 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16163 } 16164 16165 /** 16166 * @hide 16167 */ 16168 public void resetPaddingToInitialValues() { 16169 if (isRtlCompatibilityMode()) { 16170 mPaddingLeft = mUserPaddingLeftInitial; 16171 mPaddingRight = mUserPaddingRightInitial; 16172 return; 16173 } 16174 if (isLayoutRtl()) { 16175 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16176 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16177 } else { 16178 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16179 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16180 } 16181 } 16182 16183 /** 16184 * @hide 16185 */ 16186 public Insets getOpticalInsets() { 16187 if (mLayoutInsets == null) { 16188 mLayoutInsets = computeOpticalInsets(); 16189 } 16190 return mLayoutInsets; 16191 } 16192 16193 /** 16194 * Changes the selection state of this view. A view can be selected or not. 16195 * Note that selection is not the same as focus. Views are typically 16196 * selected in the context of an AdapterView like ListView or GridView; 16197 * the selected view is the view that is highlighted. 16198 * 16199 * @param selected true if the view must be selected, false otherwise 16200 */ 16201 public void setSelected(boolean selected) { 16202 //noinspection DoubleNegation 16203 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16204 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16205 if (!selected) resetPressedState(); 16206 invalidate(true); 16207 refreshDrawableState(); 16208 dispatchSetSelected(selected); 16209 notifyViewAccessibilityStateChangedIfNeeded( 16210 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16211 } 16212 } 16213 16214 /** 16215 * Dispatch setSelected to all of this View's children. 16216 * 16217 * @see #setSelected(boolean) 16218 * 16219 * @param selected The new selected state 16220 */ 16221 protected void dispatchSetSelected(boolean selected) { 16222 } 16223 16224 /** 16225 * Indicates the selection state of this view. 16226 * 16227 * @return true if the view is selected, false otherwise 16228 */ 16229 @ViewDebug.ExportedProperty 16230 public boolean isSelected() { 16231 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16232 } 16233 16234 /** 16235 * Changes the activated state of this view. A view can be activated or not. 16236 * Note that activation is not the same as selection. Selection is 16237 * a transient property, representing the view (hierarchy) the user is 16238 * currently interacting with. Activation is a longer-term state that the 16239 * user can move views in and out of. For example, in a list view with 16240 * single or multiple selection enabled, the views in the current selection 16241 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16242 * here.) The activated state is propagated down to children of the view it 16243 * is set on. 16244 * 16245 * @param activated true if the view must be activated, false otherwise 16246 */ 16247 public void setActivated(boolean activated) { 16248 //noinspection DoubleNegation 16249 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16250 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16251 invalidate(true); 16252 refreshDrawableState(); 16253 dispatchSetActivated(activated); 16254 } 16255 } 16256 16257 /** 16258 * Dispatch setActivated to all of this View's children. 16259 * 16260 * @see #setActivated(boolean) 16261 * 16262 * @param activated The new activated state 16263 */ 16264 protected void dispatchSetActivated(boolean activated) { 16265 } 16266 16267 /** 16268 * Indicates the activation state of this view. 16269 * 16270 * @return true if the view is activated, false otherwise 16271 */ 16272 @ViewDebug.ExportedProperty 16273 public boolean isActivated() { 16274 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16275 } 16276 16277 /** 16278 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16279 * observer can be used to get notifications when global events, like 16280 * layout, happen. 16281 * 16282 * The returned ViewTreeObserver observer is not guaranteed to remain 16283 * valid for the lifetime of this View. If the caller of this method keeps 16284 * a long-lived reference to ViewTreeObserver, it should always check for 16285 * the return value of {@link ViewTreeObserver#isAlive()}. 16286 * 16287 * @return The ViewTreeObserver for this view's hierarchy. 16288 */ 16289 public ViewTreeObserver getViewTreeObserver() { 16290 if (mAttachInfo != null) { 16291 return mAttachInfo.mTreeObserver; 16292 } 16293 if (mFloatingTreeObserver == null) { 16294 mFloatingTreeObserver = new ViewTreeObserver(); 16295 } 16296 return mFloatingTreeObserver; 16297 } 16298 16299 /** 16300 * <p>Finds the topmost view in the current view hierarchy.</p> 16301 * 16302 * @return the topmost view containing this view 16303 */ 16304 public View getRootView() { 16305 if (mAttachInfo != null) { 16306 final View v = mAttachInfo.mRootView; 16307 if (v != null) { 16308 return v; 16309 } 16310 } 16311 16312 View parent = this; 16313 16314 while (parent.mParent != null && parent.mParent instanceof View) { 16315 parent = (View) parent.mParent; 16316 } 16317 16318 return parent; 16319 } 16320 16321 /** 16322 * Transforms a motion event from view-local coordinates to on-screen 16323 * coordinates. 16324 * 16325 * @param ev the view-local motion event 16326 * @return false if the transformation could not be applied 16327 * @hide 16328 */ 16329 public boolean toGlobalMotionEvent(MotionEvent ev) { 16330 final AttachInfo info = mAttachInfo; 16331 if (info == null) { 16332 return false; 16333 } 16334 16335 final Matrix m = info.mTmpMatrix; 16336 m.set(Matrix.IDENTITY_MATRIX); 16337 transformMatrixToGlobal(m); 16338 ev.transform(m); 16339 return true; 16340 } 16341 16342 /** 16343 * Transforms a motion event from on-screen coordinates to view-local 16344 * coordinates. 16345 * 16346 * @param ev the on-screen motion event 16347 * @return false if the transformation could not be applied 16348 * @hide 16349 */ 16350 public boolean toLocalMotionEvent(MotionEvent ev) { 16351 final AttachInfo info = mAttachInfo; 16352 if (info == null) { 16353 return false; 16354 } 16355 16356 final Matrix m = info.mTmpMatrix; 16357 m.set(Matrix.IDENTITY_MATRIX); 16358 transformMatrixToLocal(m); 16359 ev.transform(m); 16360 return true; 16361 } 16362 16363 /** 16364 * Modifies the input matrix such that it maps view-local coordinates to 16365 * on-screen coordinates. 16366 * 16367 * @param m input matrix to modify 16368 */ 16369 void transformMatrixToGlobal(Matrix m) { 16370 final ViewParent parent = mParent; 16371 if (parent instanceof View) { 16372 final View vp = (View) parent; 16373 vp.transformMatrixToGlobal(m); 16374 m.postTranslate(-vp.mScrollX, -vp.mScrollY); 16375 } else if (parent instanceof ViewRootImpl) { 16376 final ViewRootImpl vr = (ViewRootImpl) parent; 16377 vr.transformMatrixToGlobal(m); 16378 m.postTranslate(0, -vr.mCurScrollY); 16379 } 16380 16381 m.postTranslate(mLeft, mTop); 16382 16383 if (!hasIdentityMatrix()) { 16384 m.postConcat(getMatrix()); 16385 } 16386 } 16387 16388 /** 16389 * Modifies the input matrix such that it maps on-screen coordinates to 16390 * view-local coordinates. 16391 * 16392 * @param m input matrix to modify 16393 */ 16394 void transformMatrixToLocal(Matrix m) { 16395 final ViewParent parent = mParent; 16396 if (parent instanceof View) { 16397 final View vp = (View) parent; 16398 vp.transformMatrixToLocal(m); 16399 m.preTranslate(vp.mScrollX, vp.mScrollY); 16400 } else if (parent instanceof ViewRootImpl) { 16401 final ViewRootImpl vr = (ViewRootImpl) parent; 16402 vr.transformMatrixToLocal(m); 16403 m.preTranslate(0, vr.mCurScrollY); 16404 } 16405 16406 m.preTranslate(-mLeft, -mTop); 16407 16408 if (!hasIdentityMatrix()) { 16409 m.preConcat(getInverseMatrix()); 16410 } 16411 } 16412 16413 /** 16414 * <p>Computes the coordinates of this view on the screen. The argument 16415 * must be an array of two integers. After the method returns, the array 16416 * contains the x and y location in that order.</p> 16417 * 16418 * @param location an array of two integers in which to hold the coordinates 16419 */ 16420 public void getLocationOnScreen(int[] location) { 16421 getLocationInWindow(location); 16422 16423 final AttachInfo info = mAttachInfo; 16424 if (info != null) { 16425 location[0] += info.mWindowLeft; 16426 location[1] += info.mWindowTop; 16427 } 16428 } 16429 16430 /** 16431 * <p>Computes the coordinates of this view in its window. The argument 16432 * must be an array of two integers. After the method returns, the array 16433 * contains the x and y location in that order.</p> 16434 * 16435 * @param location an array of two integers in which to hold the coordinates 16436 */ 16437 public void getLocationInWindow(int[] location) { 16438 if (location == null || location.length < 2) { 16439 throw new IllegalArgumentException("location must be an array of two integers"); 16440 } 16441 16442 if (mAttachInfo == null) { 16443 // When the view is not attached to a window, this method does not make sense 16444 location[0] = location[1] = 0; 16445 return; 16446 } 16447 16448 float[] position = mAttachInfo.mTmpTransformLocation; 16449 position[0] = position[1] = 0.0f; 16450 16451 if (!hasIdentityMatrix()) { 16452 getMatrix().mapPoints(position); 16453 } 16454 16455 position[0] += mLeft; 16456 position[1] += mTop; 16457 16458 ViewParent viewParent = mParent; 16459 while (viewParent instanceof View) { 16460 final View view = (View) viewParent; 16461 16462 position[0] -= view.mScrollX; 16463 position[1] -= view.mScrollY; 16464 16465 if (!view.hasIdentityMatrix()) { 16466 view.getMatrix().mapPoints(position); 16467 } 16468 16469 position[0] += view.mLeft; 16470 position[1] += view.mTop; 16471 16472 viewParent = view.mParent; 16473 } 16474 16475 if (viewParent instanceof ViewRootImpl) { 16476 // *cough* 16477 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16478 position[1] -= vr.mCurScrollY; 16479 } 16480 16481 location[0] = (int) (position[0] + 0.5f); 16482 location[1] = (int) (position[1] + 0.5f); 16483 } 16484 16485 /** 16486 * {@hide} 16487 * @param id the id of the view to be found 16488 * @return the view of the specified id, null if cannot be found 16489 */ 16490 protected View findViewTraversal(int id) { 16491 if (id == mID) { 16492 return this; 16493 } 16494 return null; 16495 } 16496 16497 /** 16498 * {@hide} 16499 * @param tag the tag of the view to be found 16500 * @return the view of specified tag, null if cannot be found 16501 */ 16502 protected View findViewWithTagTraversal(Object tag) { 16503 if (tag != null && tag.equals(mTag)) { 16504 return this; 16505 } 16506 return null; 16507 } 16508 16509 /** 16510 * {@hide} 16511 * @param predicate The predicate to evaluate. 16512 * @param childToSkip If not null, ignores this child during the recursive traversal. 16513 * @return The first view that matches the predicate or null. 16514 */ 16515 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16516 if (predicate.apply(this)) { 16517 return this; 16518 } 16519 return null; 16520 } 16521 16522 /** 16523 * Look for a child view with the given id. If this view has the given 16524 * id, return this view. 16525 * 16526 * @param id The id to search for. 16527 * @return The view that has the given id in the hierarchy or null 16528 */ 16529 public final View findViewById(int id) { 16530 if (id < 0) { 16531 return null; 16532 } 16533 return findViewTraversal(id); 16534 } 16535 16536 /** 16537 * Finds a view by its unuque and stable accessibility id. 16538 * 16539 * @param accessibilityId The searched accessibility id. 16540 * @return The found view. 16541 */ 16542 final View findViewByAccessibilityId(int accessibilityId) { 16543 if (accessibilityId < 0) { 16544 return null; 16545 } 16546 return findViewByAccessibilityIdTraversal(accessibilityId); 16547 } 16548 16549 /** 16550 * Performs the traversal to find a view by its unuque and stable accessibility id. 16551 * 16552 * <strong>Note:</strong>This method does not stop at the root namespace 16553 * boundary since the user can touch the screen at an arbitrary location 16554 * potentially crossing the root namespace bounday which will send an 16555 * accessibility event to accessibility services and they should be able 16556 * to obtain the event source. Also accessibility ids are guaranteed to be 16557 * unique in the window. 16558 * 16559 * @param accessibilityId The accessibility id. 16560 * @return The found view. 16561 * 16562 * @hide 16563 */ 16564 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16565 if (getAccessibilityViewId() == accessibilityId) { 16566 return this; 16567 } 16568 return null; 16569 } 16570 16571 /** 16572 * Look for a child view with the given tag. If this view has the given 16573 * tag, return this view. 16574 * 16575 * @param tag The tag to search for, using "tag.equals(getTag())". 16576 * @return The View that has the given tag in the hierarchy or null 16577 */ 16578 public final View findViewWithTag(Object tag) { 16579 if (tag == null) { 16580 return null; 16581 } 16582 return findViewWithTagTraversal(tag); 16583 } 16584 16585 /** 16586 * {@hide} 16587 * Look for a child view that matches the specified predicate. 16588 * If this view matches the predicate, return this view. 16589 * 16590 * @param predicate The predicate to evaluate. 16591 * @return The first view that matches the predicate or null. 16592 */ 16593 public final View findViewByPredicate(Predicate<View> predicate) { 16594 return findViewByPredicateTraversal(predicate, null); 16595 } 16596 16597 /** 16598 * {@hide} 16599 * Look for a child view that matches the specified predicate, 16600 * starting with the specified view and its descendents and then 16601 * recusively searching the ancestors and siblings of that view 16602 * until this view is reached. 16603 * 16604 * This method is useful in cases where the predicate does not match 16605 * a single unique view (perhaps multiple views use the same id) 16606 * and we are trying to find the view that is "closest" in scope to the 16607 * starting view. 16608 * 16609 * @param start The view to start from. 16610 * @param predicate The predicate to evaluate. 16611 * @return The first view that matches the predicate or null. 16612 */ 16613 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16614 View childToSkip = null; 16615 for (;;) { 16616 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16617 if (view != null || start == this) { 16618 return view; 16619 } 16620 16621 ViewParent parent = start.getParent(); 16622 if (parent == null || !(parent instanceof View)) { 16623 return null; 16624 } 16625 16626 childToSkip = start; 16627 start = (View) parent; 16628 } 16629 } 16630 16631 /** 16632 * Sets the identifier for this view. The identifier does not have to be 16633 * unique in this view's hierarchy. The identifier should be a positive 16634 * number. 16635 * 16636 * @see #NO_ID 16637 * @see #getId() 16638 * @see #findViewById(int) 16639 * 16640 * @param id a number used to identify the view 16641 * 16642 * @attr ref android.R.styleable#View_id 16643 */ 16644 public void setId(int id) { 16645 mID = id; 16646 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 16647 mID = generateViewId(); 16648 } 16649 } 16650 16651 /** 16652 * {@hide} 16653 * 16654 * @param isRoot true if the view belongs to the root namespace, false 16655 * otherwise 16656 */ 16657 public void setIsRootNamespace(boolean isRoot) { 16658 if (isRoot) { 16659 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 16660 } else { 16661 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 16662 } 16663 } 16664 16665 /** 16666 * {@hide} 16667 * 16668 * @return true if the view belongs to the root namespace, false otherwise 16669 */ 16670 public boolean isRootNamespace() { 16671 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 16672 } 16673 16674 /** 16675 * Returns this view's identifier. 16676 * 16677 * @return a positive integer used to identify the view or {@link #NO_ID} 16678 * if the view has no ID 16679 * 16680 * @see #setId(int) 16681 * @see #findViewById(int) 16682 * @attr ref android.R.styleable#View_id 16683 */ 16684 @ViewDebug.CapturedViewProperty 16685 public int getId() { 16686 return mID; 16687 } 16688 16689 /** 16690 * Returns this view's tag. 16691 * 16692 * @return the Object stored in this view as a tag, or {@code null} if not 16693 * set 16694 * 16695 * @see #setTag(Object) 16696 * @see #getTag(int) 16697 */ 16698 @ViewDebug.ExportedProperty 16699 public Object getTag() { 16700 return mTag; 16701 } 16702 16703 /** 16704 * Sets the tag associated with this view. A tag can be used to mark 16705 * a view in its hierarchy and does not have to be unique within the 16706 * hierarchy. Tags can also be used to store data within a view without 16707 * resorting to another data structure. 16708 * 16709 * @param tag an Object to tag the view with 16710 * 16711 * @see #getTag() 16712 * @see #setTag(int, Object) 16713 */ 16714 public void setTag(final Object tag) { 16715 mTag = tag; 16716 } 16717 16718 /** 16719 * Returns the tag associated with this view and the specified key. 16720 * 16721 * @param key The key identifying the tag 16722 * 16723 * @return the Object stored in this view as a tag, or {@code null} if not 16724 * set 16725 * 16726 * @see #setTag(int, Object) 16727 * @see #getTag() 16728 */ 16729 public Object getTag(int key) { 16730 if (mKeyedTags != null) return mKeyedTags.get(key); 16731 return null; 16732 } 16733 16734 /** 16735 * Sets a tag associated with this view and a key. A tag can be used 16736 * to mark a view in its hierarchy and does not have to be unique within 16737 * the hierarchy. Tags can also be used to store data within a view 16738 * without resorting to another data structure. 16739 * 16740 * The specified key should be an id declared in the resources of the 16741 * application to ensure it is unique (see the <a 16742 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 16743 * Keys identified as belonging to 16744 * the Android framework or not associated with any package will cause 16745 * an {@link IllegalArgumentException} to be thrown. 16746 * 16747 * @param key The key identifying the tag 16748 * @param tag An Object to tag the view with 16749 * 16750 * @throws IllegalArgumentException If they specified key is not valid 16751 * 16752 * @see #setTag(Object) 16753 * @see #getTag(int) 16754 */ 16755 public void setTag(int key, final Object tag) { 16756 // If the package id is 0x00 or 0x01, it's either an undefined package 16757 // or a framework id 16758 if ((key >>> 24) < 2) { 16759 throw new IllegalArgumentException("The key must be an application-specific " 16760 + "resource id."); 16761 } 16762 16763 setKeyedTag(key, tag); 16764 } 16765 16766 /** 16767 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16768 * framework id. 16769 * 16770 * @hide 16771 */ 16772 public void setTagInternal(int key, Object tag) { 16773 if ((key >>> 24) != 0x1) { 16774 throw new IllegalArgumentException("The key must be a framework-specific " 16775 + "resource id."); 16776 } 16777 16778 setKeyedTag(key, tag); 16779 } 16780 16781 private void setKeyedTag(int key, Object tag) { 16782 if (mKeyedTags == null) { 16783 mKeyedTags = new SparseArray<Object>(2); 16784 } 16785 16786 mKeyedTags.put(key, tag); 16787 } 16788 16789 /** 16790 * Prints information about this view in the log output, with the tag 16791 * {@link #VIEW_LOG_TAG}. 16792 * 16793 * @hide 16794 */ 16795 public void debug() { 16796 debug(0); 16797 } 16798 16799 /** 16800 * Prints information about this view in the log output, with the tag 16801 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16802 * indentation defined by the <code>depth</code>. 16803 * 16804 * @param depth the indentation level 16805 * 16806 * @hide 16807 */ 16808 protected void debug(int depth) { 16809 String output = debugIndent(depth - 1); 16810 16811 output += "+ " + this; 16812 int id = getId(); 16813 if (id != -1) { 16814 output += " (id=" + id + ")"; 16815 } 16816 Object tag = getTag(); 16817 if (tag != null) { 16818 output += " (tag=" + tag + ")"; 16819 } 16820 Log.d(VIEW_LOG_TAG, output); 16821 16822 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16823 output = debugIndent(depth) + " FOCUSED"; 16824 Log.d(VIEW_LOG_TAG, output); 16825 } 16826 16827 output = debugIndent(depth); 16828 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16829 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16830 + "} "; 16831 Log.d(VIEW_LOG_TAG, output); 16832 16833 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16834 || mPaddingBottom != 0) { 16835 output = debugIndent(depth); 16836 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16837 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16838 Log.d(VIEW_LOG_TAG, output); 16839 } 16840 16841 output = debugIndent(depth); 16842 output += "mMeasureWidth=" + mMeasuredWidth + 16843 " mMeasureHeight=" + mMeasuredHeight; 16844 Log.d(VIEW_LOG_TAG, output); 16845 16846 output = debugIndent(depth); 16847 if (mLayoutParams == null) { 16848 output += "BAD! no layout params"; 16849 } else { 16850 output = mLayoutParams.debug(output); 16851 } 16852 Log.d(VIEW_LOG_TAG, output); 16853 16854 output = debugIndent(depth); 16855 output += "flags={"; 16856 output += View.printFlags(mViewFlags); 16857 output += "}"; 16858 Log.d(VIEW_LOG_TAG, output); 16859 16860 output = debugIndent(depth); 16861 output += "privateFlags={"; 16862 output += View.printPrivateFlags(mPrivateFlags); 16863 output += "}"; 16864 Log.d(VIEW_LOG_TAG, output); 16865 } 16866 16867 /** 16868 * Creates a string of whitespaces used for indentation. 16869 * 16870 * @param depth the indentation level 16871 * @return a String containing (depth * 2 + 3) * 2 white spaces 16872 * 16873 * @hide 16874 */ 16875 protected static String debugIndent(int depth) { 16876 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16877 for (int i = 0; i < (depth * 2) + 3; i++) { 16878 spaces.append(' ').append(' '); 16879 } 16880 return spaces.toString(); 16881 } 16882 16883 /** 16884 * <p>Return the offset of the widget's text baseline from the widget's top 16885 * boundary. If this widget does not support baseline alignment, this 16886 * method returns -1. </p> 16887 * 16888 * @return the offset of the baseline within the widget's bounds or -1 16889 * if baseline alignment is not supported 16890 */ 16891 @ViewDebug.ExportedProperty(category = "layout") 16892 public int getBaseline() { 16893 return -1; 16894 } 16895 16896 /** 16897 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16898 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16899 * a layout pass. 16900 * 16901 * @return whether the view hierarchy is currently undergoing a layout pass 16902 */ 16903 public boolean isInLayout() { 16904 ViewRootImpl viewRoot = getViewRootImpl(); 16905 return (viewRoot != null && viewRoot.isInLayout()); 16906 } 16907 16908 /** 16909 * Call this when something has changed which has invalidated the 16910 * layout of this view. This will schedule a layout pass of the view 16911 * tree. This should not be called while the view hierarchy is currently in a layout 16912 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16913 * end of the current layout pass (and then layout will run again) or after the current 16914 * frame is drawn and the next layout occurs. 16915 * 16916 * <p>Subclasses which override this method should call the superclass method to 16917 * handle possible request-during-layout errors correctly.</p> 16918 */ 16919 public void requestLayout() { 16920 if (mMeasureCache != null) mMeasureCache.clear(); 16921 16922 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16923 // Only trigger request-during-layout logic if this is the view requesting it, 16924 // not the views in its parent hierarchy 16925 ViewRootImpl viewRoot = getViewRootImpl(); 16926 if (viewRoot != null && viewRoot.isInLayout()) { 16927 if (!viewRoot.requestLayoutDuringLayout(this)) { 16928 return; 16929 } 16930 } 16931 mAttachInfo.mViewRequestingLayout = this; 16932 } 16933 16934 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16935 mPrivateFlags |= PFLAG_INVALIDATED; 16936 16937 if (mParent != null && !mParent.isLayoutRequested()) { 16938 mParent.requestLayout(); 16939 } 16940 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 16941 mAttachInfo.mViewRequestingLayout = null; 16942 } 16943 } 16944 16945 /** 16946 * Forces this view to be laid out during the next layout pass. 16947 * This method does not call requestLayout() or forceLayout() 16948 * on the parent. 16949 */ 16950 public void forceLayout() { 16951 if (mMeasureCache != null) mMeasureCache.clear(); 16952 16953 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16954 mPrivateFlags |= PFLAG_INVALIDATED; 16955 } 16956 16957 /** 16958 * <p> 16959 * This is called to find out how big a view should be. The parent 16960 * supplies constraint information in the width and height parameters. 16961 * </p> 16962 * 16963 * <p> 16964 * The actual measurement work of a view is performed in 16965 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 16966 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 16967 * </p> 16968 * 16969 * 16970 * @param widthMeasureSpec Horizontal space requirements as imposed by the 16971 * parent 16972 * @param heightMeasureSpec Vertical space requirements as imposed by the 16973 * parent 16974 * 16975 * @see #onMeasure(int, int) 16976 */ 16977 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 16978 boolean optical = isLayoutModeOptical(this); 16979 if (optical != isLayoutModeOptical(mParent)) { 16980 Insets insets = getOpticalInsets(); 16981 int oWidth = insets.left + insets.right; 16982 int oHeight = insets.top + insets.bottom; 16983 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 16984 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 16985 } 16986 16987 // Suppress sign extension for the low bytes 16988 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 16989 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 16990 16991 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 16992 widthMeasureSpec != mOldWidthMeasureSpec || 16993 heightMeasureSpec != mOldHeightMeasureSpec) { 16994 16995 // first clears the measured dimension flag 16996 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 16997 16998 resolveRtlPropertiesIfNeeded(); 16999 17000 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 17001 mMeasureCache.indexOfKey(key); 17002 if (cacheIndex < 0 || sIgnoreMeasureCache) { 17003 // measure ourselves, this should set the measured dimension flag back 17004 onMeasure(widthMeasureSpec, heightMeasureSpec); 17005 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17006 } else { 17007 long value = mMeasureCache.valueAt(cacheIndex); 17008 // Casting a long to int drops the high 32 bits, no mask needed 17009 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 17010 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17011 } 17012 17013 // flag not set, setMeasuredDimension() was not invoked, we raise 17014 // an exception to warn the developer 17015 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 17016 throw new IllegalStateException("onMeasure() did not set the" 17017 + " measured dimension by calling" 17018 + " setMeasuredDimension()"); 17019 } 17020 17021 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17022 } 17023 17024 mOldWidthMeasureSpec = widthMeasureSpec; 17025 mOldHeightMeasureSpec = heightMeasureSpec; 17026 17027 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17028 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17029 } 17030 17031 /** 17032 * <p> 17033 * Measure the view and its content to determine the measured width and the 17034 * measured height. This method is invoked by {@link #measure(int, int)} and 17035 * should be overriden by subclasses to provide accurate and efficient 17036 * measurement of their contents. 17037 * </p> 17038 * 17039 * <p> 17040 * <strong>CONTRACT:</strong> When overriding this method, you 17041 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17042 * measured width and height of this view. Failure to do so will trigger an 17043 * <code>IllegalStateException</code>, thrown by 17044 * {@link #measure(int, int)}. Calling the superclass' 17045 * {@link #onMeasure(int, int)} is a valid use. 17046 * </p> 17047 * 17048 * <p> 17049 * The base class implementation of measure defaults to the background size, 17050 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17051 * override {@link #onMeasure(int, int)} to provide better measurements of 17052 * their content. 17053 * </p> 17054 * 17055 * <p> 17056 * If this method is overridden, it is the subclass's responsibility to make 17057 * sure the measured height and width are at least the view's minimum height 17058 * and width ({@link #getSuggestedMinimumHeight()} and 17059 * {@link #getSuggestedMinimumWidth()}). 17060 * </p> 17061 * 17062 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17063 * The requirements are encoded with 17064 * {@link android.view.View.MeasureSpec}. 17065 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17066 * The requirements are encoded with 17067 * {@link android.view.View.MeasureSpec}. 17068 * 17069 * @see #getMeasuredWidth() 17070 * @see #getMeasuredHeight() 17071 * @see #setMeasuredDimension(int, int) 17072 * @see #getSuggestedMinimumHeight() 17073 * @see #getSuggestedMinimumWidth() 17074 * @see android.view.View.MeasureSpec#getMode(int) 17075 * @see android.view.View.MeasureSpec#getSize(int) 17076 */ 17077 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17078 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17079 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17080 } 17081 17082 /** 17083 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17084 * measured width and measured height. Failing to do so will trigger an 17085 * exception at measurement time.</p> 17086 * 17087 * @param measuredWidth The measured width of this view. May be a complex 17088 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17089 * {@link #MEASURED_STATE_TOO_SMALL}. 17090 * @param measuredHeight The measured height of this view. May be a complex 17091 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17092 * {@link #MEASURED_STATE_TOO_SMALL}. 17093 */ 17094 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17095 boolean optical = isLayoutModeOptical(this); 17096 if (optical != isLayoutModeOptical(mParent)) { 17097 Insets insets = getOpticalInsets(); 17098 int opticalWidth = insets.left + insets.right; 17099 int opticalHeight = insets.top + insets.bottom; 17100 17101 measuredWidth += optical ? opticalWidth : -opticalWidth; 17102 measuredHeight += optical ? opticalHeight : -opticalHeight; 17103 } 17104 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17105 } 17106 17107 /** 17108 * Sets the measured dimension without extra processing for things like optical bounds. 17109 * Useful for reapplying consistent values that have already been cooked with adjustments 17110 * for optical bounds, etc. such as those from the measurement cache. 17111 * 17112 * @param measuredWidth The measured width of this view. May be a complex 17113 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17114 * {@link #MEASURED_STATE_TOO_SMALL}. 17115 * @param measuredHeight The measured height of this view. May be a complex 17116 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17117 * {@link #MEASURED_STATE_TOO_SMALL}. 17118 */ 17119 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17120 mMeasuredWidth = measuredWidth; 17121 mMeasuredHeight = measuredHeight; 17122 17123 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17124 } 17125 17126 /** 17127 * Merge two states as returned by {@link #getMeasuredState()}. 17128 * @param curState The current state as returned from a view or the result 17129 * of combining multiple views. 17130 * @param newState The new view state to combine. 17131 * @return Returns a new integer reflecting the combination of the two 17132 * states. 17133 */ 17134 public static int combineMeasuredStates(int curState, int newState) { 17135 return curState | newState; 17136 } 17137 17138 /** 17139 * Version of {@link #resolveSizeAndState(int, int, int)} 17140 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17141 */ 17142 public static int resolveSize(int size, int measureSpec) { 17143 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17144 } 17145 17146 /** 17147 * Utility to reconcile a desired size and state, with constraints imposed 17148 * by a MeasureSpec. Will take the desired size, unless a different size 17149 * is imposed by the constraints. The returned value is a compound integer, 17150 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17151 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17152 * size is smaller than the size the view wants to be. 17153 * 17154 * @param size How big the view wants to be 17155 * @param measureSpec Constraints imposed by the parent 17156 * @return Size information bit mask as defined by 17157 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17158 */ 17159 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17160 int result = size; 17161 int specMode = MeasureSpec.getMode(measureSpec); 17162 int specSize = MeasureSpec.getSize(measureSpec); 17163 switch (specMode) { 17164 case MeasureSpec.UNSPECIFIED: 17165 result = size; 17166 break; 17167 case MeasureSpec.AT_MOST: 17168 if (specSize < size) { 17169 result = specSize | MEASURED_STATE_TOO_SMALL; 17170 } else { 17171 result = size; 17172 } 17173 break; 17174 case MeasureSpec.EXACTLY: 17175 result = specSize; 17176 break; 17177 } 17178 return result | (childMeasuredState&MEASURED_STATE_MASK); 17179 } 17180 17181 /** 17182 * Utility to return a default size. Uses the supplied size if the 17183 * MeasureSpec imposed no constraints. Will get larger if allowed 17184 * by the MeasureSpec. 17185 * 17186 * @param size Default size for this view 17187 * @param measureSpec Constraints imposed by the parent 17188 * @return The size this view should be. 17189 */ 17190 public static int getDefaultSize(int size, int measureSpec) { 17191 int result = size; 17192 int specMode = MeasureSpec.getMode(measureSpec); 17193 int specSize = MeasureSpec.getSize(measureSpec); 17194 17195 switch (specMode) { 17196 case MeasureSpec.UNSPECIFIED: 17197 result = size; 17198 break; 17199 case MeasureSpec.AT_MOST: 17200 case MeasureSpec.EXACTLY: 17201 result = specSize; 17202 break; 17203 } 17204 return result; 17205 } 17206 17207 /** 17208 * Returns the suggested minimum height that the view should use. This 17209 * returns the maximum of the view's minimum height 17210 * and the background's minimum height 17211 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17212 * <p> 17213 * When being used in {@link #onMeasure(int, int)}, the caller should still 17214 * ensure the returned height is within the requirements of the parent. 17215 * 17216 * @return The suggested minimum height of the view. 17217 */ 17218 protected int getSuggestedMinimumHeight() { 17219 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17220 17221 } 17222 17223 /** 17224 * Returns the suggested minimum width that the view should use. This 17225 * returns the maximum of the view's minimum width) 17226 * and the background's minimum width 17227 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17228 * <p> 17229 * When being used in {@link #onMeasure(int, int)}, the caller should still 17230 * ensure the returned width is within the requirements of the parent. 17231 * 17232 * @return The suggested minimum width of the view. 17233 */ 17234 protected int getSuggestedMinimumWidth() { 17235 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17236 } 17237 17238 /** 17239 * Returns the minimum height of the view. 17240 * 17241 * @return the minimum height the view will try to be. 17242 * 17243 * @see #setMinimumHeight(int) 17244 * 17245 * @attr ref android.R.styleable#View_minHeight 17246 */ 17247 public int getMinimumHeight() { 17248 return mMinHeight; 17249 } 17250 17251 /** 17252 * Sets the minimum height of the view. It is not guaranteed the view will 17253 * be able to achieve this minimum height (for example, if its parent layout 17254 * constrains it with less available height). 17255 * 17256 * @param minHeight The minimum height the view will try to be. 17257 * 17258 * @see #getMinimumHeight() 17259 * 17260 * @attr ref android.R.styleable#View_minHeight 17261 */ 17262 public void setMinimumHeight(int minHeight) { 17263 mMinHeight = minHeight; 17264 requestLayout(); 17265 } 17266 17267 /** 17268 * Returns the minimum width of the view. 17269 * 17270 * @return the minimum width the view will try to be. 17271 * 17272 * @see #setMinimumWidth(int) 17273 * 17274 * @attr ref android.R.styleable#View_minWidth 17275 */ 17276 public int getMinimumWidth() { 17277 return mMinWidth; 17278 } 17279 17280 /** 17281 * Sets the minimum width of the view. It is not guaranteed the view will 17282 * be able to achieve this minimum width (for example, if its parent layout 17283 * constrains it with less available width). 17284 * 17285 * @param minWidth The minimum width the view will try to be. 17286 * 17287 * @see #getMinimumWidth() 17288 * 17289 * @attr ref android.R.styleable#View_minWidth 17290 */ 17291 public void setMinimumWidth(int minWidth) { 17292 mMinWidth = minWidth; 17293 requestLayout(); 17294 17295 } 17296 17297 /** 17298 * Get the animation currently associated with this view. 17299 * 17300 * @return The animation that is currently playing or 17301 * scheduled to play for this view. 17302 */ 17303 public Animation getAnimation() { 17304 return mCurrentAnimation; 17305 } 17306 17307 /** 17308 * Start the specified animation now. 17309 * 17310 * @param animation the animation to start now 17311 */ 17312 public void startAnimation(Animation animation) { 17313 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17314 setAnimation(animation); 17315 invalidateParentCaches(); 17316 invalidate(true); 17317 } 17318 17319 /** 17320 * Cancels any animations for this view. 17321 */ 17322 public void clearAnimation() { 17323 if (mCurrentAnimation != null) { 17324 mCurrentAnimation.detach(); 17325 } 17326 mCurrentAnimation = null; 17327 invalidateParentIfNeeded(); 17328 } 17329 17330 /** 17331 * Sets the next animation to play for this view. 17332 * If you want the animation to play immediately, use 17333 * {@link #startAnimation(android.view.animation.Animation)} instead. 17334 * This method provides allows fine-grained 17335 * control over the start time and invalidation, but you 17336 * must make sure that 1) the animation has a start time set, and 17337 * 2) the view's parent (which controls animations on its children) 17338 * will be invalidated when the animation is supposed to 17339 * start. 17340 * 17341 * @param animation The next animation, or null. 17342 */ 17343 public void setAnimation(Animation animation) { 17344 mCurrentAnimation = animation; 17345 17346 if (animation != null) { 17347 // If the screen is off assume the animation start time is now instead of 17348 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17349 // would cause the animation to start when the screen turns back on 17350 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 17351 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17352 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17353 } 17354 animation.reset(); 17355 } 17356 } 17357 17358 /** 17359 * Invoked by a parent ViewGroup to notify the start of the animation 17360 * currently associated with this view. If you override this method, 17361 * always call super.onAnimationStart(); 17362 * 17363 * @see #setAnimation(android.view.animation.Animation) 17364 * @see #getAnimation() 17365 */ 17366 protected void onAnimationStart() { 17367 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17368 } 17369 17370 /** 17371 * Invoked by a parent ViewGroup to notify the end of the animation 17372 * currently associated with this view. If you override this method, 17373 * always call super.onAnimationEnd(); 17374 * 17375 * @see #setAnimation(android.view.animation.Animation) 17376 * @see #getAnimation() 17377 */ 17378 protected void onAnimationEnd() { 17379 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17380 } 17381 17382 /** 17383 * Invoked if there is a Transform that involves alpha. Subclass that can 17384 * draw themselves with the specified alpha should return true, and then 17385 * respect that alpha when their onDraw() is called. If this returns false 17386 * then the view may be redirected to draw into an offscreen buffer to 17387 * fulfill the request, which will look fine, but may be slower than if the 17388 * subclass handles it internally. The default implementation returns false. 17389 * 17390 * @param alpha The alpha (0..255) to apply to the view's drawing 17391 * @return true if the view can draw with the specified alpha. 17392 */ 17393 protected boolean onSetAlpha(int alpha) { 17394 return false; 17395 } 17396 17397 /** 17398 * This is used by the RootView to perform an optimization when 17399 * the view hierarchy contains one or several SurfaceView. 17400 * SurfaceView is always considered transparent, but its children are not, 17401 * therefore all View objects remove themselves from the global transparent 17402 * region (passed as a parameter to this function). 17403 * 17404 * @param region The transparent region for this ViewAncestor (window). 17405 * 17406 * @return Returns true if the effective visibility of the view at this 17407 * point is opaque, regardless of the transparent region; returns false 17408 * if it is possible for underlying windows to be seen behind the view. 17409 * 17410 * {@hide} 17411 */ 17412 public boolean gatherTransparentRegion(Region region) { 17413 final AttachInfo attachInfo = mAttachInfo; 17414 if (region != null && attachInfo != null) { 17415 final int pflags = mPrivateFlags; 17416 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 17417 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 17418 // remove it from the transparent region. 17419 final int[] location = attachInfo.mTransparentLocation; 17420 getLocationInWindow(location); 17421 region.op(location[0], location[1], location[0] + mRight - mLeft, 17422 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 17423 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 17424 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 17425 // exists, so we remove the background drawable's non-transparent 17426 // parts from this transparent region. 17427 applyDrawableToTransparentRegion(mBackground, region); 17428 } 17429 } 17430 return true; 17431 } 17432 17433 /** 17434 * Play a sound effect for this view. 17435 * 17436 * <p>The framework will play sound effects for some built in actions, such as 17437 * clicking, but you may wish to play these effects in your widget, 17438 * for instance, for internal navigation. 17439 * 17440 * <p>The sound effect will only be played if sound effects are enabled by the user, and 17441 * {@link #isSoundEffectsEnabled()} is true. 17442 * 17443 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 17444 */ 17445 public void playSoundEffect(int soundConstant) { 17446 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 17447 return; 17448 } 17449 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 17450 } 17451 17452 /** 17453 * BZZZTT!!1! 17454 * 17455 * <p>Provide haptic feedback to the user for this view. 17456 * 17457 * <p>The framework will provide haptic feedback for some built in actions, 17458 * such as long presses, but you may wish to provide feedback for your 17459 * own widget. 17460 * 17461 * <p>The feedback will only be performed if 17462 * {@link #isHapticFeedbackEnabled()} is true. 17463 * 17464 * @param feedbackConstant One of the constants defined in 17465 * {@link HapticFeedbackConstants} 17466 */ 17467 public boolean performHapticFeedback(int feedbackConstant) { 17468 return performHapticFeedback(feedbackConstant, 0); 17469 } 17470 17471 /** 17472 * BZZZTT!!1! 17473 * 17474 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17475 * 17476 * @param feedbackConstant One of the constants defined in 17477 * {@link HapticFeedbackConstants} 17478 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17479 */ 17480 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17481 if (mAttachInfo == null) { 17482 return false; 17483 } 17484 //noinspection SimplifiableIfStatement 17485 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17486 && !isHapticFeedbackEnabled()) { 17487 return false; 17488 } 17489 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17490 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17491 } 17492 17493 /** 17494 * Request that the visibility of the status bar or other screen/window 17495 * decorations be changed. 17496 * 17497 * <p>This method is used to put the over device UI into temporary modes 17498 * where the user's attention is focused more on the application content, 17499 * by dimming or hiding surrounding system affordances. This is typically 17500 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17501 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17502 * to be placed behind the action bar (and with these flags other system 17503 * affordances) so that smooth transitions between hiding and showing them 17504 * can be done. 17505 * 17506 * <p>Two representative examples of the use of system UI visibility is 17507 * implementing a content browsing application (like a magazine reader) 17508 * and a video playing application. 17509 * 17510 * <p>The first code shows a typical implementation of a View in a content 17511 * browsing application. In this implementation, the application goes 17512 * into a content-oriented mode by hiding the status bar and action bar, 17513 * and putting the navigation elements into lights out mode. The user can 17514 * then interact with content while in this mode. Such an application should 17515 * provide an easy way for the user to toggle out of the mode (such as to 17516 * check information in the status bar or access notifications). In the 17517 * implementation here, this is done simply by tapping on the content. 17518 * 17519 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17520 * content} 17521 * 17522 * <p>This second code sample shows a typical implementation of a View 17523 * in a video playing application. In this situation, while the video is 17524 * playing the application would like to go into a complete full-screen mode, 17525 * to use as much of the display as possible for the video. When in this state 17526 * the user can not interact with the application; the system intercepts 17527 * touching on the screen to pop the UI out of full screen mode. See 17528 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17529 * 17530 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17531 * content} 17532 * 17533 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17534 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17535 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17536 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17537 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17538 */ 17539 public void setSystemUiVisibility(int visibility) { 17540 if (visibility != mSystemUiVisibility) { 17541 mSystemUiVisibility = visibility; 17542 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17543 mParent.recomputeViewAttributes(this); 17544 } 17545 } 17546 } 17547 17548 /** 17549 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17550 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17551 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17552 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17553 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17554 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17555 */ 17556 public int getSystemUiVisibility() { 17557 return mSystemUiVisibility; 17558 } 17559 17560 /** 17561 * Returns the current system UI visibility that is currently set for 17562 * the entire window. This is the combination of the 17563 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17564 * views in the window. 17565 */ 17566 public int getWindowSystemUiVisibility() { 17567 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17568 } 17569 17570 /** 17571 * Override to find out when the window's requested system UI visibility 17572 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17573 * This is different from the callbacks received through 17574 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17575 * in that this is only telling you about the local request of the window, 17576 * not the actual values applied by the system. 17577 */ 17578 public void onWindowSystemUiVisibilityChanged(int visible) { 17579 } 17580 17581 /** 17582 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17583 * the view hierarchy. 17584 */ 17585 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17586 onWindowSystemUiVisibilityChanged(visible); 17587 } 17588 17589 /** 17590 * Set a listener to receive callbacks when the visibility of the system bar changes. 17591 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17592 */ 17593 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17594 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17595 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17596 mParent.recomputeViewAttributes(this); 17597 } 17598 } 17599 17600 /** 17601 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17602 * the view hierarchy. 17603 */ 17604 public void dispatchSystemUiVisibilityChanged(int visibility) { 17605 ListenerInfo li = mListenerInfo; 17606 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17607 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17608 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17609 } 17610 } 17611 17612 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17613 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17614 if (val != mSystemUiVisibility) { 17615 setSystemUiVisibility(val); 17616 return true; 17617 } 17618 return false; 17619 } 17620 17621 /** @hide */ 17622 public void setDisabledSystemUiVisibility(int flags) { 17623 if (mAttachInfo != null) { 17624 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17625 mAttachInfo.mDisabledSystemUiVisibility = flags; 17626 if (mParent != null) { 17627 mParent.recomputeViewAttributes(this); 17628 } 17629 } 17630 } 17631 } 17632 17633 /** 17634 * Creates an image that the system displays during the drag and drop 17635 * operation. This is called a "drag shadow". The default implementation 17636 * for a DragShadowBuilder based on a View returns an image that has exactly the same 17637 * appearance as the given View. The default also positions the center of the drag shadow 17638 * directly under the touch point. If no View is provided (the constructor with no parameters 17639 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 17640 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 17641 * default is an invisible drag shadow. 17642 * <p> 17643 * You are not required to use the View you provide to the constructor as the basis of the 17644 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 17645 * anything you want as the drag shadow. 17646 * </p> 17647 * <p> 17648 * You pass a DragShadowBuilder object to the system when you start the drag. The system 17649 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 17650 * size and position of the drag shadow. It uses this data to construct a 17651 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 17652 * so that your application can draw the shadow image in the Canvas. 17653 * </p> 17654 * 17655 * <div class="special reference"> 17656 * <h3>Developer Guides</h3> 17657 * <p>For a guide to implementing drag and drop features, read the 17658 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17659 * </div> 17660 */ 17661 public static class DragShadowBuilder { 17662 private final WeakReference<View> mView; 17663 17664 /** 17665 * Constructs a shadow image builder based on a View. By default, the resulting drag 17666 * shadow will have the same appearance and dimensions as the View, with the touch point 17667 * over the center of the View. 17668 * @param view A View. Any View in scope can be used. 17669 */ 17670 public DragShadowBuilder(View view) { 17671 mView = new WeakReference<View>(view); 17672 } 17673 17674 /** 17675 * Construct a shadow builder object with no associated View. This 17676 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 17677 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 17678 * to supply the drag shadow's dimensions and appearance without 17679 * reference to any View object. If they are not overridden, then the result is an 17680 * invisible drag shadow. 17681 */ 17682 public DragShadowBuilder() { 17683 mView = new WeakReference<View>(null); 17684 } 17685 17686 /** 17687 * Returns the View object that had been passed to the 17688 * {@link #View.DragShadowBuilder(View)} 17689 * constructor. If that View parameter was {@code null} or if the 17690 * {@link #View.DragShadowBuilder()} 17691 * constructor was used to instantiate the builder object, this method will return 17692 * null. 17693 * 17694 * @return The View object associate with this builder object. 17695 */ 17696 @SuppressWarnings({"JavadocReference"}) 17697 final public View getView() { 17698 return mView.get(); 17699 } 17700 17701 /** 17702 * Provides the metrics for the shadow image. These include the dimensions of 17703 * the shadow image, and the point within that shadow that should 17704 * be centered under the touch location while dragging. 17705 * <p> 17706 * The default implementation sets the dimensions of the shadow to be the 17707 * same as the dimensions of the View itself and centers the shadow under 17708 * the touch point. 17709 * </p> 17710 * 17711 * @param shadowSize A {@link android.graphics.Point} containing the width and height 17712 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 17713 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 17714 * image. 17715 * 17716 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 17717 * shadow image that should be underneath the touch point during the drag and drop 17718 * operation. Your application must set {@link android.graphics.Point#x} to the 17719 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 17720 */ 17721 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 17722 final View view = mView.get(); 17723 if (view != null) { 17724 shadowSize.set(view.getWidth(), view.getHeight()); 17725 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 17726 } else { 17727 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 17728 } 17729 } 17730 17731 /** 17732 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 17733 * based on the dimensions it received from the 17734 * {@link #onProvideShadowMetrics(Point, Point)} callback. 17735 * 17736 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 17737 */ 17738 public void onDrawShadow(Canvas canvas) { 17739 final View view = mView.get(); 17740 if (view != null) { 17741 view.draw(canvas); 17742 } else { 17743 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 17744 } 17745 } 17746 } 17747 17748 /** 17749 * Starts a drag and drop operation. When your application calls this method, it passes a 17750 * {@link android.view.View.DragShadowBuilder} object to the system. The 17751 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 17752 * to get metrics for the drag shadow, and then calls the object's 17753 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 17754 * <p> 17755 * Once the system has the drag shadow, it begins the drag and drop operation by sending 17756 * drag events to all the View objects in your application that are currently visible. It does 17757 * this either by calling the View object's drag listener (an implementation of 17758 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 17759 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17760 * Both are passed a {@link android.view.DragEvent} object that has a 17761 * {@link android.view.DragEvent#getAction()} value of 17762 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17763 * </p> 17764 * <p> 17765 * Your application can invoke startDrag() on any attached View object. The View object does not 17766 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17767 * be related to the View the user selected for dragging. 17768 * </p> 17769 * @param data A {@link android.content.ClipData} object pointing to the data to be 17770 * transferred by the drag and drop operation. 17771 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17772 * drag shadow. 17773 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17774 * drop operation. This Object is put into every DragEvent object sent by the system during the 17775 * current drag. 17776 * <p> 17777 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17778 * to the target Views. For example, it can contain flags that differentiate between a 17779 * a copy operation and a move operation. 17780 * </p> 17781 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17782 * so the parameter should be set to 0. 17783 * @return {@code true} if the method completes successfully, or 17784 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17785 * do a drag, and so no drag operation is in progress. 17786 */ 17787 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17788 Object myLocalState, int flags) { 17789 if (ViewDebug.DEBUG_DRAG) { 17790 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17791 } 17792 boolean okay = false; 17793 17794 Point shadowSize = new Point(); 17795 Point shadowTouchPoint = new Point(); 17796 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17797 17798 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17799 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17800 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17801 } 17802 17803 if (ViewDebug.DEBUG_DRAG) { 17804 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17805 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17806 } 17807 Surface surface = new Surface(); 17808 try { 17809 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17810 flags, shadowSize.x, shadowSize.y, surface); 17811 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17812 + " surface=" + surface); 17813 if (token != null) { 17814 Canvas canvas = surface.lockCanvas(null); 17815 try { 17816 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17817 shadowBuilder.onDrawShadow(canvas); 17818 } finally { 17819 surface.unlockCanvasAndPost(canvas); 17820 } 17821 17822 final ViewRootImpl root = getViewRootImpl(); 17823 17824 // Cache the local state object for delivery with DragEvents 17825 root.setLocalDragState(myLocalState); 17826 17827 // repurpose 'shadowSize' for the last touch point 17828 root.getLastTouchPoint(shadowSize); 17829 17830 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17831 shadowSize.x, shadowSize.y, 17832 shadowTouchPoint.x, shadowTouchPoint.y, data); 17833 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17834 17835 // Off and running! Release our local surface instance; the drag 17836 // shadow surface is now managed by the system process. 17837 surface.release(); 17838 } 17839 } catch (Exception e) { 17840 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17841 surface.destroy(); 17842 } 17843 17844 return okay; 17845 } 17846 17847 /** 17848 * Handles drag events sent by the system following a call to 17849 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17850 *<p> 17851 * When the system calls this method, it passes a 17852 * {@link android.view.DragEvent} object. A call to 17853 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17854 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17855 * operation. 17856 * @param event The {@link android.view.DragEvent} sent by the system. 17857 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17858 * in DragEvent, indicating the type of drag event represented by this object. 17859 * @return {@code true} if the method was successful, otherwise {@code false}. 17860 * <p> 17861 * The method should return {@code true} in response to an action type of 17862 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17863 * operation. 17864 * </p> 17865 * <p> 17866 * The method should also return {@code true} in response to an action type of 17867 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17868 * {@code false} if it didn't. 17869 * </p> 17870 */ 17871 public boolean onDragEvent(DragEvent event) { 17872 return false; 17873 } 17874 17875 /** 17876 * Detects if this View is enabled and has a drag event listener. 17877 * If both are true, then it calls the drag event listener with the 17878 * {@link android.view.DragEvent} it received. If the drag event listener returns 17879 * {@code true}, then dispatchDragEvent() returns {@code true}. 17880 * <p> 17881 * For all other cases, the method calls the 17882 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17883 * method and returns its result. 17884 * </p> 17885 * <p> 17886 * This ensures that a drag event is always consumed, even if the View does not have a drag 17887 * event listener. However, if the View has a listener and the listener returns true, then 17888 * onDragEvent() is not called. 17889 * </p> 17890 */ 17891 public boolean dispatchDragEvent(DragEvent event) { 17892 ListenerInfo li = mListenerInfo; 17893 //noinspection SimplifiableIfStatement 17894 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17895 && li.mOnDragListener.onDrag(this, event)) { 17896 return true; 17897 } 17898 return onDragEvent(event); 17899 } 17900 17901 boolean canAcceptDrag() { 17902 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17903 } 17904 17905 /** 17906 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17907 * it is ever exposed at all. 17908 * @hide 17909 */ 17910 public void onCloseSystemDialogs(String reason) { 17911 } 17912 17913 /** 17914 * Given a Drawable whose bounds have been set to draw into this view, 17915 * update a Region being computed for 17916 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17917 * that any non-transparent parts of the Drawable are removed from the 17918 * given transparent region. 17919 * 17920 * @param dr The Drawable whose transparency is to be applied to the region. 17921 * @param region A Region holding the current transparency information, 17922 * where any parts of the region that are set are considered to be 17923 * transparent. On return, this region will be modified to have the 17924 * transparency information reduced by the corresponding parts of the 17925 * Drawable that are not transparent. 17926 * {@hide} 17927 */ 17928 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17929 if (DBG) { 17930 Log.i("View", "Getting transparent region for: " + this); 17931 } 17932 final Region r = dr.getTransparentRegion(); 17933 final Rect db = dr.getBounds(); 17934 final AttachInfo attachInfo = mAttachInfo; 17935 if (r != null && attachInfo != null) { 17936 final int w = getRight()-getLeft(); 17937 final int h = getBottom()-getTop(); 17938 if (db.left > 0) { 17939 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 17940 r.op(0, 0, db.left, h, Region.Op.UNION); 17941 } 17942 if (db.right < w) { 17943 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 17944 r.op(db.right, 0, w, h, Region.Op.UNION); 17945 } 17946 if (db.top > 0) { 17947 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 17948 r.op(0, 0, w, db.top, Region.Op.UNION); 17949 } 17950 if (db.bottom < h) { 17951 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 17952 r.op(0, db.bottom, w, h, Region.Op.UNION); 17953 } 17954 final int[] location = attachInfo.mTransparentLocation; 17955 getLocationInWindow(location); 17956 r.translate(location[0], location[1]); 17957 region.op(r, Region.Op.INTERSECT); 17958 } else { 17959 region.op(db, Region.Op.DIFFERENCE); 17960 } 17961 } 17962 17963 private void checkForLongClick(int delayOffset) { 17964 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 17965 mHasPerformedLongPress = false; 17966 17967 if (mPendingCheckForLongPress == null) { 17968 mPendingCheckForLongPress = new CheckForLongPress(); 17969 } 17970 mPendingCheckForLongPress.rememberWindowAttachCount(); 17971 postDelayed(mPendingCheckForLongPress, 17972 ViewConfiguration.getLongPressTimeout() - delayOffset); 17973 } 17974 } 17975 17976 /** 17977 * Inflate a view from an XML resource. This convenience method wraps the {@link 17978 * LayoutInflater} class, which provides a full range of options for view inflation. 17979 * 17980 * @param context The Context object for your activity or application. 17981 * @param resource The resource ID to inflate 17982 * @param root A view group that will be the parent. Used to properly inflate the 17983 * layout_* parameters. 17984 * @see LayoutInflater 17985 */ 17986 public static View inflate(Context context, int resource, ViewGroup root) { 17987 LayoutInflater factory = LayoutInflater.from(context); 17988 return factory.inflate(resource, root); 17989 } 17990 17991 /** 17992 * Scroll the view with standard behavior for scrolling beyond the normal 17993 * content boundaries. Views that call this method should override 17994 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 17995 * results of an over-scroll operation. 17996 * 17997 * Views can use this method to handle any touch or fling-based scrolling. 17998 * 17999 * @param deltaX Change in X in pixels 18000 * @param deltaY Change in Y in pixels 18001 * @param scrollX Current X scroll value in pixels before applying deltaX 18002 * @param scrollY Current Y scroll value in pixels before applying deltaY 18003 * @param scrollRangeX Maximum content scroll range along the X axis 18004 * @param scrollRangeY Maximum content scroll range along the Y axis 18005 * @param maxOverScrollX Number of pixels to overscroll by in either direction 18006 * along the X axis. 18007 * @param maxOverScrollY Number of pixels to overscroll by in either direction 18008 * along the Y axis. 18009 * @param isTouchEvent true if this scroll operation is the result of a touch event. 18010 * @return true if scrolling was clamped to an over-scroll boundary along either 18011 * axis, false otherwise. 18012 */ 18013 @SuppressWarnings({"UnusedParameters"}) 18014 protected boolean overScrollBy(int deltaX, int deltaY, 18015 int scrollX, int scrollY, 18016 int scrollRangeX, int scrollRangeY, 18017 int maxOverScrollX, int maxOverScrollY, 18018 boolean isTouchEvent) { 18019 final int overScrollMode = mOverScrollMode; 18020 final boolean canScrollHorizontal = 18021 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18022 final boolean canScrollVertical = 18023 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18024 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18025 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18026 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18027 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18028 18029 int newScrollX = scrollX + deltaX; 18030 if (!overScrollHorizontal) { 18031 maxOverScrollX = 0; 18032 } 18033 18034 int newScrollY = scrollY + deltaY; 18035 if (!overScrollVertical) { 18036 maxOverScrollY = 0; 18037 } 18038 18039 // Clamp values if at the limits and record 18040 final int left = -maxOverScrollX; 18041 final int right = maxOverScrollX + scrollRangeX; 18042 final int top = -maxOverScrollY; 18043 final int bottom = maxOverScrollY + scrollRangeY; 18044 18045 boolean clampedX = false; 18046 if (newScrollX > right) { 18047 newScrollX = right; 18048 clampedX = true; 18049 } else if (newScrollX < left) { 18050 newScrollX = left; 18051 clampedX = true; 18052 } 18053 18054 boolean clampedY = false; 18055 if (newScrollY > bottom) { 18056 newScrollY = bottom; 18057 clampedY = true; 18058 } else if (newScrollY < top) { 18059 newScrollY = top; 18060 clampedY = true; 18061 } 18062 18063 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18064 18065 return clampedX || clampedY; 18066 } 18067 18068 /** 18069 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18070 * respond to the results of an over-scroll operation. 18071 * 18072 * @param scrollX New X scroll value in pixels 18073 * @param scrollY New Y scroll value in pixels 18074 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18075 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18076 */ 18077 protected void onOverScrolled(int scrollX, int scrollY, 18078 boolean clampedX, boolean clampedY) { 18079 // Intentionally empty. 18080 } 18081 18082 /** 18083 * Returns the over-scroll mode for this view. The result will be 18084 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18085 * (allow over-scrolling only if the view content is larger than the container), 18086 * or {@link #OVER_SCROLL_NEVER}. 18087 * 18088 * @return This view's over-scroll mode. 18089 */ 18090 public int getOverScrollMode() { 18091 return mOverScrollMode; 18092 } 18093 18094 /** 18095 * Set the over-scroll mode for this view. Valid over-scroll modes are 18096 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18097 * (allow over-scrolling only if the view content is larger than the container), 18098 * or {@link #OVER_SCROLL_NEVER}. 18099 * 18100 * Setting the over-scroll mode of a view will have an effect only if the 18101 * view is capable of scrolling. 18102 * 18103 * @param overScrollMode The new over-scroll mode for this view. 18104 */ 18105 public void setOverScrollMode(int overScrollMode) { 18106 if (overScrollMode != OVER_SCROLL_ALWAYS && 18107 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18108 overScrollMode != OVER_SCROLL_NEVER) { 18109 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18110 } 18111 mOverScrollMode = overScrollMode; 18112 } 18113 18114 /** 18115 * Enable or disable nested scrolling for this view. 18116 * 18117 * <p>If this property is set to true the view will be permitted to initiate nested 18118 * scrolling operations with a compatible parent view in the current hierarchy. If this 18119 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 18120 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 18121 * the nested scroll.</p> 18122 * 18123 * @param enabled true to enable nested scrolling, false to disable 18124 * 18125 * @see #isNestedScrollingEnabled() 18126 */ 18127 public void setNestedScrollingEnabled(boolean enabled) { 18128 if (enabled) { 18129 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18130 } else { 18131 stopNestedScroll(); 18132 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18133 } 18134 } 18135 18136 /** 18137 * Returns true if nested scrolling is enabled for this view. 18138 * 18139 * <p>If nested scrolling is enabled and this View class implementation supports it, 18140 * this view will act as a nested scrolling child view when applicable, forwarding data 18141 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18142 * parent.</p> 18143 * 18144 * @return true if nested scrolling is enabled 18145 * 18146 * @see #setNestedScrollingEnabled(boolean) 18147 */ 18148 public boolean isNestedScrollingEnabled() { 18149 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18150 PFLAG3_NESTED_SCROLLING_ENABLED; 18151 } 18152 18153 /** 18154 * Begin a nestable scroll operation along the given axes. 18155 * 18156 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18157 * 18158 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18159 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18160 * In the case of touch scrolling the nested scroll will be terminated automatically in 18161 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18162 * In the event of programmatic scrolling the caller must explicitly call 18163 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18164 * 18165 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18166 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18167 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18168 * 18169 * <p>At each incremental step of the scroll the caller should invoke 18170 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18171 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18172 * parent at least partially consumed the scroll and the caller should adjust the amount it 18173 * scrolls by.</p> 18174 * 18175 * <p>After applying the remainder of the scroll delta the caller should invoke 18176 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18177 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18178 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18179 * </p> 18180 * 18181 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18182 * {@link #SCROLL_AXIS_VERTICAL}. 18183 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18184 * the current gesture. 18185 * 18186 * @see #stopNestedScroll() 18187 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18188 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18189 */ 18190 public boolean startNestedScroll(int axes) { 18191 if (hasNestedScrollingParent()) { 18192 // Already in progress 18193 return true; 18194 } 18195 if (isNestedScrollingEnabled()) { 18196 ViewParent p = getParent(); 18197 View child = this; 18198 while (p != null) { 18199 try { 18200 if (p.onStartNestedScroll(child, this, axes)) { 18201 mNestedScrollingParent = p; 18202 p.onNestedScrollAccepted(child, this, axes); 18203 return true; 18204 } 18205 } catch (AbstractMethodError e) { 18206 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18207 "method onStartNestedScroll", e); 18208 // Allow the search upward to continue 18209 } 18210 if (p instanceof View) { 18211 child = (View) p; 18212 } 18213 p = p.getParent(); 18214 } 18215 } 18216 return false; 18217 } 18218 18219 /** 18220 * Stop a nested scroll in progress. 18221 * 18222 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18223 * 18224 * @see #startNestedScroll(int) 18225 */ 18226 public void stopNestedScroll() { 18227 if (mNestedScrollingParent != null) { 18228 mNestedScrollingParent.onStopNestedScroll(this); 18229 mNestedScrollingParent = null; 18230 } 18231 } 18232 18233 /** 18234 * Returns true if this view has a nested scrolling parent. 18235 * 18236 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18237 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18238 * 18239 * @return whether this view has a nested scrolling parent 18240 */ 18241 public boolean hasNestedScrollingParent() { 18242 return mNestedScrollingParent != null; 18243 } 18244 18245 /** 18246 * Dispatch one step of a nested scroll in progress. 18247 * 18248 * <p>Implementations of views that support nested scrolling should call this to report 18249 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18250 * is not currently in progress or nested scrolling is not 18251 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18252 * 18253 * <p>Compatible View implementations should also call 18254 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18255 * consuming a component of the scroll event themselves.</p> 18256 * 18257 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18258 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18259 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18260 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18261 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18262 * in local view coordinates of this view from before this operation 18263 * to after it completes. View implementations may use this to adjust 18264 * expected input coordinate tracking. 18265 * @return true if the event was dispatched, false if it could not be dispatched. 18266 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18267 */ 18268 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18269 int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { 18270 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18271 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18272 int startX = 0; 18273 int startY = 0; 18274 if (offsetInWindow != null) { 18275 getLocationInWindow(offsetInWindow); 18276 startX = offsetInWindow[0]; 18277 startY = offsetInWindow[1]; 18278 } 18279 18280 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18281 dxUnconsumed, dyUnconsumed); 18282 18283 if (offsetInWindow != null) { 18284 getLocationInWindow(offsetInWindow); 18285 offsetInWindow[0] -= startX; 18286 offsetInWindow[1] -= startY; 18287 } 18288 return true; 18289 } else if (offsetInWindow != null) { 18290 // No motion, no dispatch. Keep offsetInWindow up to date. 18291 offsetInWindow[0] = 0; 18292 offsetInWindow[1] = 0; 18293 } 18294 } 18295 return false; 18296 } 18297 18298 /** 18299 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18300 * 18301 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18302 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18303 * scrolling operation to consume some or all of the scroll operation before the child view 18304 * consumes it.</p> 18305 * 18306 * @param dx Horizontal scroll distance in pixels 18307 * @param dy Vertical scroll distance in pixels 18308 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18309 * and consumed[1] the consumed dy. 18310 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18311 * in local view coordinates of this view from before this operation 18312 * to after it completes. View implementations may use this to adjust 18313 * expected input coordinate tracking. 18314 * @return true if the parent consumed some or all of the scroll delta 18315 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18316 */ 18317 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 18318 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18319 if (dx != 0 || dy != 0) { 18320 int startX = 0; 18321 int startY = 0; 18322 if (offsetInWindow != null) { 18323 getLocationInWindow(offsetInWindow); 18324 startX = offsetInWindow[0]; 18325 startY = offsetInWindow[1]; 18326 } 18327 18328 if (consumed == null) { 18329 if (mTempNestedScrollConsumed == null) { 18330 mTempNestedScrollConsumed = new int[2]; 18331 } 18332 consumed = mTempNestedScrollConsumed; 18333 } 18334 consumed[0] = 0; 18335 consumed[1] = 0; 18336 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 18337 18338 if (offsetInWindow != null) { 18339 getLocationInWindow(offsetInWindow); 18340 offsetInWindow[0] -= startX; 18341 offsetInWindow[1] -= startY; 18342 } 18343 return consumed[0] != 0 || consumed[1] != 0; 18344 } else if (offsetInWindow != null) { 18345 offsetInWindow[0] = 0; 18346 offsetInWindow[1] = 0; 18347 } 18348 } 18349 return false; 18350 } 18351 18352 /** 18353 * Dispatch a fling to a nested scrolling parent. 18354 * 18355 * <p>This method should be used to indicate that a nested scrolling child has detected 18356 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 18357 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 18358 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 18359 * along a scrollable axis.</p> 18360 * 18361 * <p>If a nested scrolling child view would normally fling but it is at the edge of 18362 * its own content, it can use this method to delegate the fling to its nested scrolling 18363 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 18364 * 18365 * @param velocityX Horizontal fling velocity in pixels per second 18366 * @param velocityY Vertical fling velocity in pixels per second 18367 * @param consumed true if the child consumed the fling, false otherwise 18368 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 18369 */ 18370 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 18371 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18372 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 18373 } 18374 return false; 18375 } 18376 18377 /** 18378 * Gets a scale factor that determines the distance the view should scroll 18379 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 18380 * @return The vertical scroll scale factor. 18381 * @hide 18382 */ 18383 protected float getVerticalScrollFactor() { 18384 if (mVerticalScrollFactor == 0) { 18385 TypedValue outValue = new TypedValue(); 18386 if (!mContext.getTheme().resolveAttribute( 18387 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 18388 throw new IllegalStateException( 18389 "Expected theme to define listPreferredItemHeight."); 18390 } 18391 mVerticalScrollFactor = outValue.getDimension( 18392 mContext.getResources().getDisplayMetrics()); 18393 } 18394 return mVerticalScrollFactor; 18395 } 18396 18397 /** 18398 * Gets a scale factor that determines the distance the view should scroll 18399 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 18400 * @return The horizontal scroll scale factor. 18401 * @hide 18402 */ 18403 protected float getHorizontalScrollFactor() { 18404 // TODO: Should use something else. 18405 return getVerticalScrollFactor(); 18406 } 18407 18408 /** 18409 * Return the value specifying the text direction or policy that was set with 18410 * {@link #setTextDirection(int)}. 18411 * 18412 * @return the defined text direction. It can be one of: 18413 * 18414 * {@link #TEXT_DIRECTION_INHERIT}, 18415 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18416 * {@link #TEXT_DIRECTION_ANY_RTL}, 18417 * {@link #TEXT_DIRECTION_LTR}, 18418 * {@link #TEXT_DIRECTION_RTL}, 18419 * {@link #TEXT_DIRECTION_LOCALE} 18420 * 18421 * @attr ref android.R.styleable#View_textDirection 18422 * 18423 * @hide 18424 */ 18425 @ViewDebug.ExportedProperty(category = "text", mapping = { 18426 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18427 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18428 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18429 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18430 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18431 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18432 }) 18433 public int getRawTextDirection() { 18434 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 18435 } 18436 18437 /** 18438 * Set the text direction. 18439 * 18440 * @param textDirection the direction to set. Should be one of: 18441 * 18442 * {@link #TEXT_DIRECTION_INHERIT}, 18443 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18444 * {@link #TEXT_DIRECTION_ANY_RTL}, 18445 * {@link #TEXT_DIRECTION_LTR}, 18446 * {@link #TEXT_DIRECTION_RTL}, 18447 * {@link #TEXT_DIRECTION_LOCALE} 18448 * 18449 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 18450 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 18451 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 18452 * 18453 * @attr ref android.R.styleable#View_textDirection 18454 */ 18455 public void setTextDirection(int textDirection) { 18456 if (getRawTextDirection() != textDirection) { 18457 // Reset the current text direction and the resolved one 18458 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 18459 resetResolvedTextDirection(); 18460 // Set the new text direction 18461 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 18462 // Do resolution 18463 resolveTextDirection(); 18464 // Notify change 18465 onRtlPropertiesChanged(getLayoutDirection()); 18466 // Refresh 18467 requestLayout(); 18468 invalidate(true); 18469 } 18470 } 18471 18472 /** 18473 * Return the resolved text direction. 18474 * 18475 * @return the resolved text direction. Returns one of: 18476 * 18477 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18478 * {@link #TEXT_DIRECTION_ANY_RTL}, 18479 * {@link #TEXT_DIRECTION_LTR}, 18480 * {@link #TEXT_DIRECTION_RTL}, 18481 * {@link #TEXT_DIRECTION_LOCALE} 18482 * 18483 * @attr ref android.R.styleable#View_textDirection 18484 */ 18485 @ViewDebug.ExportedProperty(category = "text", mapping = { 18486 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18487 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18488 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18489 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18490 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18491 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18492 }) 18493 public int getTextDirection() { 18494 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 18495 } 18496 18497 /** 18498 * Resolve the text direction. 18499 * 18500 * @return true if resolution has been done, false otherwise. 18501 * 18502 * @hide 18503 */ 18504 public boolean resolveTextDirection() { 18505 // Reset any previous text direction resolution 18506 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18507 18508 if (hasRtlSupport()) { 18509 // Set resolved text direction flag depending on text direction flag 18510 final int textDirection = getRawTextDirection(); 18511 switch(textDirection) { 18512 case TEXT_DIRECTION_INHERIT: 18513 if (!canResolveTextDirection()) { 18514 // We cannot do the resolution if there is no parent, so use the default one 18515 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18516 // Resolution will need to happen again later 18517 return false; 18518 } 18519 18520 // Parent has not yet resolved, so we still return the default 18521 try { 18522 if (!mParent.isTextDirectionResolved()) { 18523 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18524 // Resolution will need to happen again later 18525 return false; 18526 } 18527 } catch (AbstractMethodError e) { 18528 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18529 " does not fully implement ViewParent", e); 18530 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 18531 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18532 return true; 18533 } 18534 18535 // Set current resolved direction to the same value as the parent's one 18536 int parentResolvedDirection; 18537 try { 18538 parentResolvedDirection = mParent.getTextDirection(); 18539 } catch (AbstractMethodError e) { 18540 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18541 " does not fully implement ViewParent", e); 18542 parentResolvedDirection = TEXT_DIRECTION_LTR; 18543 } 18544 switch (parentResolvedDirection) { 18545 case TEXT_DIRECTION_FIRST_STRONG: 18546 case TEXT_DIRECTION_ANY_RTL: 18547 case TEXT_DIRECTION_LTR: 18548 case TEXT_DIRECTION_RTL: 18549 case TEXT_DIRECTION_LOCALE: 18550 mPrivateFlags2 |= 18551 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18552 break; 18553 default: 18554 // Default resolved direction is "first strong" heuristic 18555 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18556 } 18557 break; 18558 case TEXT_DIRECTION_FIRST_STRONG: 18559 case TEXT_DIRECTION_ANY_RTL: 18560 case TEXT_DIRECTION_LTR: 18561 case TEXT_DIRECTION_RTL: 18562 case TEXT_DIRECTION_LOCALE: 18563 // Resolved direction is the same as text direction 18564 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18565 break; 18566 default: 18567 // Default resolved direction is "first strong" heuristic 18568 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18569 } 18570 } else { 18571 // Default resolved direction is "first strong" heuristic 18572 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18573 } 18574 18575 // Set to resolved 18576 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 18577 return true; 18578 } 18579 18580 /** 18581 * Check if text direction resolution can be done. 18582 * 18583 * @return true if text direction resolution can be done otherwise return false. 18584 */ 18585 public boolean canResolveTextDirection() { 18586 switch (getRawTextDirection()) { 18587 case TEXT_DIRECTION_INHERIT: 18588 if (mParent != null) { 18589 try { 18590 return mParent.canResolveTextDirection(); 18591 } catch (AbstractMethodError e) { 18592 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18593 " does not fully implement ViewParent", e); 18594 } 18595 } 18596 return false; 18597 18598 default: 18599 return true; 18600 } 18601 } 18602 18603 /** 18604 * Reset resolved text direction. Text direction will be resolved during a call to 18605 * {@link #onMeasure(int, int)}. 18606 * 18607 * @hide 18608 */ 18609 public void resetResolvedTextDirection() { 18610 // Reset any previous text direction resolution 18611 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18612 // Set to default value 18613 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18614 } 18615 18616 /** 18617 * @return true if text direction is inherited. 18618 * 18619 * @hide 18620 */ 18621 public boolean isTextDirectionInherited() { 18622 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 18623 } 18624 18625 /** 18626 * @return true if text direction is resolved. 18627 */ 18628 public boolean isTextDirectionResolved() { 18629 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 18630 } 18631 18632 /** 18633 * Return the value specifying the text alignment or policy that was set with 18634 * {@link #setTextAlignment(int)}. 18635 * 18636 * @return the defined text alignment. It can be one of: 18637 * 18638 * {@link #TEXT_ALIGNMENT_INHERIT}, 18639 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18640 * {@link #TEXT_ALIGNMENT_CENTER}, 18641 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18642 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18643 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18644 * {@link #TEXT_ALIGNMENT_VIEW_END} 18645 * 18646 * @attr ref android.R.styleable#View_textAlignment 18647 * 18648 * @hide 18649 */ 18650 @ViewDebug.ExportedProperty(category = "text", mapping = { 18651 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18652 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18653 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18654 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18655 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18656 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18657 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18658 }) 18659 @TextAlignment 18660 public int getRawTextAlignment() { 18661 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 18662 } 18663 18664 /** 18665 * Set the text alignment. 18666 * 18667 * @param textAlignment The text alignment to set. Should be one of 18668 * 18669 * {@link #TEXT_ALIGNMENT_INHERIT}, 18670 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18671 * {@link #TEXT_ALIGNMENT_CENTER}, 18672 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18673 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18674 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18675 * {@link #TEXT_ALIGNMENT_VIEW_END} 18676 * 18677 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 18678 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 18679 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 18680 * 18681 * @attr ref android.R.styleable#View_textAlignment 18682 */ 18683 public void setTextAlignment(@TextAlignment int textAlignment) { 18684 if (textAlignment != getRawTextAlignment()) { 18685 // Reset the current and resolved text alignment 18686 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 18687 resetResolvedTextAlignment(); 18688 // Set the new text alignment 18689 mPrivateFlags2 |= 18690 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 18691 // Do resolution 18692 resolveTextAlignment(); 18693 // Notify change 18694 onRtlPropertiesChanged(getLayoutDirection()); 18695 // Refresh 18696 requestLayout(); 18697 invalidate(true); 18698 } 18699 } 18700 18701 /** 18702 * Return the resolved text alignment. 18703 * 18704 * @return the resolved text alignment. Returns one of: 18705 * 18706 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18707 * {@link #TEXT_ALIGNMENT_CENTER}, 18708 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18709 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18710 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18711 * {@link #TEXT_ALIGNMENT_VIEW_END} 18712 * 18713 * @attr ref android.R.styleable#View_textAlignment 18714 */ 18715 @ViewDebug.ExportedProperty(category = "text", mapping = { 18716 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18717 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18718 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18719 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18720 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18721 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18722 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18723 }) 18724 @TextAlignment 18725 public int getTextAlignment() { 18726 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 18727 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 18728 } 18729 18730 /** 18731 * Resolve the text alignment. 18732 * 18733 * @return true if resolution has been done, false otherwise. 18734 * 18735 * @hide 18736 */ 18737 public boolean resolveTextAlignment() { 18738 // Reset any previous text alignment resolution 18739 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18740 18741 if (hasRtlSupport()) { 18742 // Set resolved text alignment flag depending on text alignment flag 18743 final int textAlignment = getRawTextAlignment(); 18744 switch (textAlignment) { 18745 case TEXT_ALIGNMENT_INHERIT: 18746 // Check if we can resolve the text alignment 18747 if (!canResolveTextAlignment()) { 18748 // We cannot do the resolution if there is no parent so use the default 18749 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18750 // Resolution will need to happen again later 18751 return false; 18752 } 18753 18754 // Parent has not yet resolved, so we still return the default 18755 try { 18756 if (!mParent.isTextAlignmentResolved()) { 18757 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18758 // Resolution will need to happen again later 18759 return false; 18760 } 18761 } catch (AbstractMethodError e) { 18762 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18763 " does not fully implement ViewParent", e); 18764 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 18765 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18766 return true; 18767 } 18768 18769 int parentResolvedTextAlignment; 18770 try { 18771 parentResolvedTextAlignment = mParent.getTextAlignment(); 18772 } catch (AbstractMethodError e) { 18773 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18774 " does not fully implement ViewParent", e); 18775 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 18776 } 18777 switch (parentResolvedTextAlignment) { 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 the parent resolved 18785 // text alignment 18786 mPrivateFlags2 |= 18787 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18788 break; 18789 default: 18790 // Use default resolved text alignment 18791 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18792 } 18793 break; 18794 case TEXT_ALIGNMENT_GRAVITY: 18795 case TEXT_ALIGNMENT_TEXT_START: 18796 case TEXT_ALIGNMENT_TEXT_END: 18797 case TEXT_ALIGNMENT_CENTER: 18798 case TEXT_ALIGNMENT_VIEW_START: 18799 case TEXT_ALIGNMENT_VIEW_END: 18800 // Resolved text alignment is the same as text alignment 18801 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18802 break; 18803 default: 18804 // Use default resolved text alignment 18805 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18806 } 18807 } else { 18808 // Use default resolved text alignment 18809 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18810 } 18811 18812 // Set the resolved 18813 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18814 return true; 18815 } 18816 18817 /** 18818 * Check if text alignment resolution can be done. 18819 * 18820 * @return true if text alignment resolution can be done otherwise return false. 18821 */ 18822 public boolean canResolveTextAlignment() { 18823 switch (getRawTextAlignment()) { 18824 case TEXT_DIRECTION_INHERIT: 18825 if (mParent != null) { 18826 try { 18827 return mParent.canResolveTextAlignment(); 18828 } catch (AbstractMethodError e) { 18829 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18830 " does not fully implement ViewParent", e); 18831 } 18832 } 18833 return false; 18834 18835 default: 18836 return true; 18837 } 18838 } 18839 18840 /** 18841 * Reset resolved text alignment. Text alignment will be resolved during a call to 18842 * {@link #onMeasure(int, int)}. 18843 * 18844 * @hide 18845 */ 18846 public void resetResolvedTextAlignment() { 18847 // Reset any previous text alignment resolution 18848 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18849 // Set to default 18850 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18851 } 18852 18853 /** 18854 * @return true if text alignment is inherited. 18855 * 18856 * @hide 18857 */ 18858 public boolean isTextAlignmentInherited() { 18859 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 18860 } 18861 18862 /** 18863 * @return true if text alignment is resolved. 18864 */ 18865 public boolean isTextAlignmentResolved() { 18866 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18867 } 18868 18869 /** 18870 * Generate a value suitable for use in {@link #setId(int)}. 18871 * This value will not collide with ID values generated at build time by aapt for R.id. 18872 * 18873 * @return a generated ID value 18874 */ 18875 public static int generateViewId() { 18876 for (;;) { 18877 final int result = sNextGeneratedId.get(); 18878 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 18879 int newValue = result + 1; 18880 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 18881 if (sNextGeneratedId.compareAndSet(result, newValue)) { 18882 return result; 18883 } 18884 } 18885 } 18886 18887 /** 18888 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 18889 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 18890 * a normal View or a ViewGroup with 18891 * {@link android.view.ViewGroup#isTransitionGroup()} true. 18892 * @hide 18893 */ 18894 public void captureTransitioningViews(List<View> transitioningViews) { 18895 if (getVisibility() == View.VISIBLE) { 18896 transitioningViews.add(this); 18897 } 18898 } 18899 18900 /** 18901 * Adds all Views that have {@link #getViewName()} non-null to namedElements. 18902 * @param namedElements Will contain all Views in the hierarchy having a view name. 18903 * @hide 18904 */ 18905 public void findNamedViews(Map<String, View> namedElements) { 18906 if (getVisibility() == VISIBLE) { 18907 String viewName = getViewName(); 18908 if (viewName != null) { 18909 namedElements.put(viewName, this); 18910 } 18911 } 18912 } 18913 18914 // 18915 // Properties 18916 // 18917 /** 18918 * A Property wrapper around the <code>alpha</code> functionality handled by the 18919 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 18920 */ 18921 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 18922 @Override 18923 public void setValue(View object, float value) { 18924 object.setAlpha(value); 18925 } 18926 18927 @Override 18928 public Float get(View object) { 18929 return object.getAlpha(); 18930 } 18931 }; 18932 18933 /** 18934 * A Property wrapper around the <code>translationX</code> functionality handled by the 18935 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 18936 */ 18937 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 18938 @Override 18939 public void setValue(View object, float value) { 18940 object.setTranslationX(value); 18941 } 18942 18943 @Override 18944 public Float get(View object) { 18945 return object.getTranslationX(); 18946 } 18947 }; 18948 18949 /** 18950 * A Property wrapper around the <code>translationY</code> functionality handled by the 18951 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 18952 */ 18953 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 18954 @Override 18955 public void setValue(View object, float value) { 18956 object.setTranslationY(value); 18957 } 18958 18959 @Override 18960 public Float get(View object) { 18961 return object.getTranslationY(); 18962 } 18963 }; 18964 18965 /** 18966 * A Property wrapper around the <code>translationZ</code> functionality handled by the 18967 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 18968 */ 18969 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 18970 @Override 18971 public void setValue(View object, float value) { 18972 object.setTranslationZ(value); 18973 } 18974 18975 @Override 18976 public Float get(View object) { 18977 return object.getTranslationZ(); 18978 } 18979 }; 18980 18981 /** 18982 * A Property wrapper around the <code>x</code> functionality handled by the 18983 * {@link View#setX(float)} and {@link View#getX()} methods. 18984 */ 18985 public static final Property<View, Float> X = new FloatProperty<View>("x") { 18986 @Override 18987 public void setValue(View object, float value) { 18988 object.setX(value); 18989 } 18990 18991 @Override 18992 public Float get(View object) { 18993 return object.getX(); 18994 } 18995 }; 18996 18997 /** 18998 * A Property wrapper around the <code>y</code> functionality handled by the 18999 * {@link View#setY(float)} and {@link View#getY()} methods. 19000 */ 19001 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 19002 @Override 19003 public void setValue(View object, float value) { 19004 object.setY(value); 19005 } 19006 19007 @Override 19008 public Float get(View object) { 19009 return object.getY(); 19010 } 19011 }; 19012 19013 /** 19014 * A Property wrapper around the <code>z</code> functionality handled by the 19015 * {@link View#setZ(float)} and {@link View#getZ()} methods. 19016 */ 19017 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 19018 @Override 19019 public void setValue(View object, float value) { 19020 object.setZ(value); 19021 } 19022 19023 @Override 19024 public Float get(View object) { 19025 return object.getZ(); 19026 } 19027 }; 19028 19029 /** 19030 * A Property wrapper around the <code>rotation</code> functionality handled by the 19031 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 19032 */ 19033 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 19034 @Override 19035 public void setValue(View object, float value) { 19036 object.setRotation(value); 19037 } 19038 19039 @Override 19040 public Float get(View object) { 19041 return object.getRotation(); 19042 } 19043 }; 19044 19045 /** 19046 * A Property wrapper around the <code>rotationX</code> functionality handled by the 19047 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 19048 */ 19049 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 19050 @Override 19051 public void setValue(View object, float value) { 19052 object.setRotationX(value); 19053 } 19054 19055 @Override 19056 public Float get(View object) { 19057 return object.getRotationX(); 19058 } 19059 }; 19060 19061 /** 19062 * A Property wrapper around the <code>rotationY</code> functionality handled by the 19063 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 19064 */ 19065 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 19066 @Override 19067 public void setValue(View object, float value) { 19068 object.setRotationY(value); 19069 } 19070 19071 @Override 19072 public Float get(View object) { 19073 return object.getRotationY(); 19074 } 19075 }; 19076 19077 /** 19078 * A Property wrapper around the <code>scaleX</code> functionality handled by the 19079 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 19080 */ 19081 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 19082 @Override 19083 public void setValue(View object, float value) { 19084 object.setScaleX(value); 19085 } 19086 19087 @Override 19088 public Float get(View object) { 19089 return object.getScaleX(); 19090 } 19091 }; 19092 19093 /** 19094 * A Property wrapper around the <code>scaleY</code> functionality handled by the 19095 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 19096 */ 19097 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 19098 @Override 19099 public void setValue(View object, float value) { 19100 object.setScaleY(value); 19101 } 19102 19103 @Override 19104 public Float get(View object) { 19105 return object.getScaleY(); 19106 } 19107 }; 19108 19109 /** 19110 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 19111 * Each MeasureSpec represents a requirement for either the width or the height. 19112 * A MeasureSpec is comprised of a size and a mode. There are three possible 19113 * modes: 19114 * <dl> 19115 * <dt>UNSPECIFIED</dt> 19116 * <dd> 19117 * The parent has not imposed any constraint on the child. It can be whatever size 19118 * it wants. 19119 * </dd> 19120 * 19121 * <dt>EXACTLY</dt> 19122 * <dd> 19123 * The parent has determined an exact size for the child. The child is going to be 19124 * given those bounds regardless of how big it wants to be. 19125 * </dd> 19126 * 19127 * <dt>AT_MOST</dt> 19128 * <dd> 19129 * The child can be as large as it wants up to the specified size. 19130 * </dd> 19131 * </dl> 19132 * 19133 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19134 * is provided to pack and unpack the <size, mode> tuple into the int. 19135 */ 19136 public static class MeasureSpec { 19137 private static final int MODE_SHIFT = 30; 19138 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19139 19140 /** 19141 * Measure specification mode: The parent has not imposed any constraint 19142 * on the child. It can be whatever size it wants. 19143 */ 19144 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19145 19146 /** 19147 * Measure specification mode: The parent has determined an exact size 19148 * for the child. The child is going to be given those bounds regardless 19149 * of how big it wants to be. 19150 */ 19151 public static final int EXACTLY = 1 << MODE_SHIFT; 19152 19153 /** 19154 * Measure specification mode: The child can be as large as it wants up 19155 * to the specified size. 19156 */ 19157 public static final int AT_MOST = 2 << MODE_SHIFT; 19158 19159 /** 19160 * Creates a measure specification based on the supplied size and mode. 19161 * 19162 * The mode must always be one of the following: 19163 * <ul> 19164 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19165 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19166 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19167 * </ul> 19168 * 19169 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19170 * implementation was such that the order of arguments did not matter 19171 * and overflow in either value could impact the resulting MeasureSpec. 19172 * {@link android.widget.RelativeLayout} was affected by this bug. 19173 * Apps targeting API levels greater than 17 will get the fixed, more strict 19174 * behavior.</p> 19175 * 19176 * @param size the size of the measure specification 19177 * @param mode the mode of the measure specification 19178 * @return the measure specification based on size and mode 19179 */ 19180 public static int makeMeasureSpec(int size, int mode) { 19181 if (sUseBrokenMakeMeasureSpec) { 19182 return size + mode; 19183 } else { 19184 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19185 } 19186 } 19187 19188 /** 19189 * Extracts the mode from the supplied measure specification. 19190 * 19191 * @param measureSpec the measure specification to extract the mode from 19192 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19193 * {@link android.view.View.MeasureSpec#AT_MOST} or 19194 * {@link android.view.View.MeasureSpec#EXACTLY} 19195 */ 19196 public static int getMode(int measureSpec) { 19197 return (measureSpec & MODE_MASK); 19198 } 19199 19200 /** 19201 * Extracts the size from the supplied measure specification. 19202 * 19203 * @param measureSpec the measure specification to extract the size from 19204 * @return the size in pixels defined in the supplied measure specification 19205 */ 19206 public static int getSize(int measureSpec) { 19207 return (measureSpec & ~MODE_MASK); 19208 } 19209 19210 static int adjust(int measureSpec, int delta) { 19211 final int mode = getMode(measureSpec); 19212 if (mode == UNSPECIFIED) { 19213 // No need to adjust size for UNSPECIFIED mode. 19214 return makeMeasureSpec(0, UNSPECIFIED); 19215 } 19216 int size = getSize(measureSpec) + delta; 19217 if (size < 0) { 19218 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19219 ") spec: " + toString(measureSpec) + " delta: " + delta); 19220 size = 0; 19221 } 19222 return makeMeasureSpec(size, mode); 19223 } 19224 19225 /** 19226 * Returns a String representation of the specified measure 19227 * specification. 19228 * 19229 * @param measureSpec the measure specification to convert to a String 19230 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19231 */ 19232 public static String toString(int measureSpec) { 19233 int mode = getMode(measureSpec); 19234 int size = getSize(measureSpec); 19235 19236 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19237 19238 if (mode == UNSPECIFIED) 19239 sb.append("UNSPECIFIED "); 19240 else if (mode == EXACTLY) 19241 sb.append("EXACTLY "); 19242 else if (mode == AT_MOST) 19243 sb.append("AT_MOST "); 19244 else 19245 sb.append(mode).append(" "); 19246 19247 sb.append(size); 19248 return sb.toString(); 19249 } 19250 } 19251 19252 private final class CheckForLongPress implements Runnable { 19253 private int mOriginalWindowAttachCount; 19254 19255 @Override 19256 public void run() { 19257 if (isPressed() && (mParent != null) 19258 && mOriginalWindowAttachCount == mWindowAttachCount) { 19259 if (performLongClick()) { 19260 mHasPerformedLongPress = true; 19261 } 19262 } 19263 } 19264 19265 public void rememberWindowAttachCount() { 19266 mOriginalWindowAttachCount = mWindowAttachCount; 19267 } 19268 } 19269 19270 private final class CheckForTap implements Runnable { 19271 public float x; 19272 public float y; 19273 19274 @Override 19275 public void run() { 19276 mPrivateFlags &= ~PFLAG_PREPRESSED; 19277 setPressed(true, x, y); 19278 checkForLongClick(ViewConfiguration.getTapTimeout()); 19279 } 19280 } 19281 19282 private final class PerformClick implements Runnable { 19283 @Override 19284 public void run() { 19285 performClick(); 19286 } 19287 } 19288 19289 /** @hide */ 19290 public void hackTurnOffWindowResizeAnim(boolean off) { 19291 mAttachInfo.mTurnOffWindowResizeAnim = off; 19292 } 19293 19294 /** 19295 * This method returns a ViewPropertyAnimator object, which can be used to animate 19296 * specific properties on this View. 19297 * 19298 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19299 */ 19300 public ViewPropertyAnimator animate() { 19301 if (mAnimator == null) { 19302 mAnimator = new ViewPropertyAnimator(this); 19303 } 19304 return mAnimator; 19305 } 19306 19307 /** 19308 * Sets the name of the View to be used to identify Views in Transitions. 19309 * Names should be unique in the View hierarchy. 19310 * 19311 * @param viewName The name of the View to uniquely identify it for Transitions. 19312 */ 19313 public final void setViewName(String viewName) { 19314 mViewName = viewName; 19315 } 19316 19317 /** 19318 * Returns the name of the View to be used to identify Views in Transitions. 19319 * Names should be unique in the View hierarchy. 19320 * 19321 * <p>This returns null if the View has not been given a name.</p> 19322 * 19323 * @return The name used of the View to be used to identify Views in Transitions or null 19324 * if no name has been given. 19325 */ 19326 public String getViewName() { 19327 return mViewName; 19328 } 19329 19330 /** 19331 * Interface definition for a callback to be invoked when a hardware key event is 19332 * dispatched to this view. The callback will be invoked before the key event is 19333 * given to the view. This is only useful for hardware keyboards; a software input 19334 * method has no obligation to trigger this listener. 19335 */ 19336 public interface OnKeyListener { 19337 /** 19338 * Called when a hardware key is dispatched to a view. This allows listeners to 19339 * get a chance to respond before the target view. 19340 * <p>Key presses in software keyboards will generally NOT trigger this method, 19341 * although some may elect to do so in some situations. Do not assume a 19342 * software input method has to be key-based; even if it is, it may use key presses 19343 * in a different way than you expect, so there is no way to reliably catch soft 19344 * input key presses. 19345 * 19346 * @param v The view the key has been dispatched to. 19347 * @param keyCode The code for the physical key that was pressed 19348 * @param event The KeyEvent object containing full information about 19349 * the event. 19350 * @return True if the listener has consumed the event, false otherwise. 19351 */ 19352 boolean onKey(View v, int keyCode, KeyEvent event); 19353 } 19354 19355 /** 19356 * Interface definition for a callback to be invoked when a touch event is 19357 * dispatched to this view. The callback will be invoked before the touch 19358 * event is given to the view. 19359 */ 19360 public interface OnTouchListener { 19361 /** 19362 * Called when a touch event is dispatched to a view. This allows listeners to 19363 * get a chance to respond before the target view. 19364 * 19365 * @param v The view the touch event has been dispatched to. 19366 * @param event The MotionEvent object containing full information about 19367 * the event. 19368 * @return True if the listener has consumed the event, false otherwise. 19369 */ 19370 boolean onTouch(View v, MotionEvent event); 19371 } 19372 19373 /** 19374 * Interface definition for a callback to be invoked when a hover event is 19375 * dispatched to this view. The callback will be invoked before the hover 19376 * event is given to the view. 19377 */ 19378 public interface OnHoverListener { 19379 /** 19380 * Called when a hover event is dispatched to a view. This allows listeners to 19381 * get a chance to respond before the target view. 19382 * 19383 * @param v The view the hover event has been dispatched to. 19384 * @param event The MotionEvent object containing full information about 19385 * the event. 19386 * @return True if the listener has consumed the event, false otherwise. 19387 */ 19388 boolean onHover(View v, MotionEvent event); 19389 } 19390 19391 /** 19392 * Interface definition for a callback to be invoked when a generic motion event is 19393 * dispatched to this view. The callback will be invoked before the generic motion 19394 * event is given to the view. 19395 */ 19396 public interface OnGenericMotionListener { 19397 /** 19398 * Called when a generic motion event is dispatched to a view. This allows listeners to 19399 * get a chance to respond before the target view. 19400 * 19401 * @param v The view the generic motion event has been dispatched to. 19402 * @param event The MotionEvent object containing full information about 19403 * the event. 19404 * @return True if the listener has consumed the event, false otherwise. 19405 */ 19406 boolean onGenericMotion(View v, MotionEvent event); 19407 } 19408 19409 /** 19410 * Interface definition for a callback to be invoked when a view has been clicked and held. 19411 */ 19412 public interface OnLongClickListener { 19413 /** 19414 * Called when a view has been clicked and held. 19415 * 19416 * @param v The view that was clicked and held. 19417 * 19418 * @return true if the callback consumed the long click, false otherwise. 19419 */ 19420 boolean onLongClick(View v); 19421 } 19422 19423 /** 19424 * Interface definition for a callback to be invoked when a drag is being dispatched 19425 * to this view. The callback will be invoked before the hosting view's own 19426 * onDrag(event) method. If the listener wants to fall back to the hosting view's 19427 * onDrag(event) behavior, it should return 'false' from this callback. 19428 * 19429 * <div class="special reference"> 19430 * <h3>Developer Guides</h3> 19431 * <p>For a guide to implementing drag and drop features, read the 19432 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 19433 * </div> 19434 */ 19435 public interface OnDragListener { 19436 /** 19437 * Called when a drag event is dispatched to a view. This allows listeners 19438 * to get a chance to override base View behavior. 19439 * 19440 * @param v The View that received the drag event. 19441 * @param event The {@link android.view.DragEvent} object for the drag event. 19442 * @return {@code true} if the drag event was handled successfully, or {@code false} 19443 * if the drag event was not handled. Note that {@code false} will trigger the View 19444 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 19445 */ 19446 boolean onDrag(View v, DragEvent event); 19447 } 19448 19449 /** 19450 * Interface definition for a callback to be invoked when the focus state of 19451 * a view changed. 19452 */ 19453 public interface OnFocusChangeListener { 19454 /** 19455 * Called when the focus state of a view has changed. 19456 * 19457 * @param v The view whose state has changed. 19458 * @param hasFocus The new focus state of v. 19459 */ 19460 void onFocusChange(View v, boolean hasFocus); 19461 } 19462 19463 /** 19464 * Interface definition for a callback to be invoked when a view is clicked. 19465 */ 19466 public interface OnClickListener { 19467 /** 19468 * Called when a view has been clicked. 19469 * 19470 * @param v The view that was clicked. 19471 */ 19472 void onClick(View v); 19473 } 19474 19475 /** 19476 * Interface definition for a callback to be invoked when the context menu 19477 * for this view is being built. 19478 */ 19479 public interface OnCreateContextMenuListener { 19480 /** 19481 * Called when the context menu for this view is being built. It is not 19482 * safe to hold onto the menu after this method returns. 19483 * 19484 * @param menu The context menu that is being built 19485 * @param v The view for which the context menu is being built 19486 * @param menuInfo Extra information about the item for which the 19487 * context menu should be shown. This information will vary 19488 * depending on the class of v. 19489 */ 19490 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 19491 } 19492 19493 /** 19494 * Interface definition for a callback to be invoked when the status bar changes 19495 * visibility. This reports <strong>global</strong> changes to the system UI 19496 * state, not what the application is requesting. 19497 * 19498 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 19499 */ 19500 public interface OnSystemUiVisibilityChangeListener { 19501 /** 19502 * Called when the status bar changes visibility because of a call to 19503 * {@link View#setSystemUiVisibility(int)}. 19504 * 19505 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19506 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 19507 * This tells you the <strong>global</strong> state of these UI visibility 19508 * flags, not what your app is currently applying. 19509 */ 19510 public void onSystemUiVisibilityChange(int visibility); 19511 } 19512 19513 /** 19514 * Interface definition for a callback to be invoked when this view is attached 19515 * or detached from its window. 19516 */ 19517 public interface OnAttachStateChangeListener { 19518 /** 19519 * Called when the view is attached to a window. 19520 * @param v The view that was attached 19521 */ 19522 public void onViewAttachedToWindow(View v); 19523 /** 19524 * Called when the view is detached from a window. 19525 * @param v The view that was detached 19526 */ 19527 public void onViewDetachedFromWindow(View v); 19528 } 19529 19530 /** 19531 * Listener for applying window insets on a view in a custom way. 19532 * 19533 * <p>Apps may choose to implement this interface if they want to apply custom policy 19534 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 19535 * is set, its 19536 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 19537 * method will be called instead of the View's own 19538 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 19539 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 19540 * the View's normal behavior as part of its own.</p> 19541 */ 19542 public interface OnApplyWindowInsetsListener { 19543 /** 19544 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 19545 * on a View, this listener method will be called instead of the view's own 19546 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 19547 * 19548 * @param v The view applying window insets 19549 * @param insets The insets to apply 19550 * @return The insets supplied, minus any insets that were consumed 19551 */ 19552 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 19553 } 19554 19555 private final class UnsetPressedState implements Runnable { 19556 @Override 19557 public void run() { 19558 setPressed(false); 19559 } 19560 } 19561 19562 /** 19563 * Base class for derived classes that want to save and restore their own 19564 * state in {@link android.view.View#onSaveInstanceState()}. 19565 */ 19566 public static class BaseSavedState extends AbsSavedState { 19567 /** 19568 * Constructor used when reading from a parcel. Reads the state of the superclass. 19569 * 19570 * @param source 19571 */ 19572 public BaseSavedState(Parcel source) { 19573 super(source); 19574 } 19575 19576 /** 19577 * Constructor called by derived classes when creating their SavedState objects 19578 * 19579 * @param superState The state of the superclass of this view 19580 */ 19581 public BaseSavedState(Parcelable superState) { 19582 super(superState); 19583 } 19584 19585 public static final Parcelable.Creator<BaseSavedState> CREATOR = 19586 new Parcelable.Creator<BaseSavedState>() { 19587 public BaseSavedState createFromParcel(Parcel in) { 19588 return new BaseSavedState(in); 19589 } 19590 19591 public BaseSavedState[] newArray(int size) { 19592 return new BaseSavedState[size]; 19593 } 19594 }; 19595 } 19596 19597 /** 19598 * A set of information given to a view when it is attached to its parent 19599 * window. 19600 */ 19601 final static class AttachInfo { 19602 interface Callbacks { 19603 void playSoundEffect(int effectId); 19604 boolean performHapticFeedback(int effectId, boolean always); 19605 } 19606 19607 /** 19608 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 19609 * to a Handler. This class contains the target (View) to invalidate and 19610 * the coordinates of the dirty rectangle. 19611 * 19612 * For performance purposes, this class also implements a pool of up to 19613 * POOL_LIMIT objects that get reused. This reduces memory allocations 19614 * whenever possible. 19615 */ 19616 static class InvalidateInfo { 19617 private static final int POOL_LIMIT = 10; 19618 19619 private static final SynchronizedPool<InvalidateInfo> sPool = 19620 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 19621 19622 View target; 19623 19624 int left; 19625 int top; 19626 int right; 19627 int bottom; 19628 19629 public static InvalidateInfo obtain() { 19630 InvalidateInfo instance = sPool.acquire(); 19631 return (instance != null) ? instance : new InvalidateInfo(); 19632 } 19633 19634 public void recycle() { 19635 target = null; 19636 sPool.release(this); 19637 } 19638 } 19639 19640 final IWindowSession mSession; 19641 19642 final IWindow mWindow; 19643 19644 final IBinder mWindowToken; 19645 19646 final Display mDisplay; 19647 19648 final Callbacks mRootCallbacks; 19649 19650 IWindowId mIWindowId; 19651 WindowId mWindowId; 19652 19653 /** 19654 * The top view of the hierarchy. 19655 */ 19656 View mRootView; 19657 19658 IBinder mPanelParentWindowToken; 19659 19660 boolean mHardwareAccelerated; 19661 boolean mHardwareAccelerationRequested; 19662 HardwareRenderer mHardwareRenderer; 19663 19664 /** 19665 * The state of the display to which the window is attached, as reported 19666 * by {@link Display#getState()}. Note that the display state constants 19667 * declared by {@link Display} do not exactly line up with the screen state 19668 * constants declared by {@link View} (there are more display states than 19669 * screen states). 19670 */ 19671 int mDisplayState = Display.STATE_UNKNOWN; 19672 19673 /** 19674 * Scale factor used by the compatibility mode 19675 */ 19676 float mApplicationScale; 19677 19678 /** 19679 * Indicates whether the application is in compatibility mode 19680 */ 19681 boolean mScalingRequired; 19682 19683 /** 19684 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 19685 */ 19686 boolean mTurnOffWindowResizeAnim; 19687 19688 /** 19689 * Left position of this view's window 19690 */ 19691 int mWindowLeft; 19692 19693 /** 19694 * Top position of this view's window 19695 */ 19696 int mWindowTop; 19697 19698 /** 19699 * Indicates whether views need to use 32-bit drawing caches 19700 */ 19701 boolean mUse32BitDrawingCache; 19702 19703 /** 19704 * For windows that are full-screen but using insets to layout inside 19705 * of the screen areas, these are the current insets to appear inside 19706 * the overscan area of the display. 19707 */ 19708 final Rect mOverscanInsets = new Rect(); 19709 19710 /** 19711 * For windows that are full-screen but using insets to layout inside 19712 * of the screen decorations, these are the current insets for the 19713 * content of the window. 19714 */ 19715 final Rect mContentInsets = new Rect(); 19716 19717 /** 19718 * For windows that are full-screen but using insets to layout inside 19719 * of the screen decorations, these are the current insets for the 19720 * actual visible parts of the window. 19721 */ 19722 final Rect mVisibleInsets = new Rect(); 19723 19724 /** 19725 * The internal insets given by this window. This value is 19726 * supplied by the client (through 19727 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 19728 * be given to the window manager when changed to be used in laying 19729 * out windows behind it. 19730 */ 19731 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 19732 = new ViewTreeObserver.InternalInsetsInfo(); 19733 19734 /** 19735 * Set to true when mGivenInternalInsets is non-empty. 19736 */ 19737 boolean mHasNonEmptyGivenInternalInsets; 19738 19739 /** 19740 * All views in the window's hierarchy that serve as scroll containers, 19741 * used to determine if the window can be resized or must be panned 19742 * to adjust for a soft input area. 19743 */ 19744 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 19745 19746 final KeyEvent.DispatcherState mKeyDispatchState 19747 = new KeyEvent.DispatcherState(); 19748 19749 /** 19750 * Indicates whether the view's window currently has the focus. 19751 */ 19752 boolean mHasWindowFocus; 19753 19754 /** 19755 * The current visibility of the window. 19756 */ 19757 int mWindowVisibility; 19758 19759 /** 19760 * Indicates the time at which drawing started to occur. 19761 */ 19762 long mDrawingTime; 19763 19764 /** 19765 * Indicates whether or not ignoring the DIRTY_MASK flags. 19766 */ 19767 boolean mIgnoreDirtyState; 19768 19769 /** 19770 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 19771 * to avoid clearing that flag prematurely. 19772 */ 19773 boolean mSetIgnoreDirtyState = false; 19774 19775 /** 19776 * Indicates whether the view's window is currently in touch mode. 19777 */ 19778 boolean mInTouchMode; 19779 19780 /** 19781 * Indicates whether the view has requested unbuffered input dispatching for the current 19782 * event stream. 19783 */ 19784 boolean mUnbufferedDispatchRequested; 19785 19786 /** 19787 * Indicates that ViewAncestor should trigger a global layout change 19788 * the next time it performs a traversal 19789 */ 19790 boolean mRecomputeGlobalAttributes; 19791 19792 /** 19793 * Always report new attributes at next traversal. 19794 */ 19795 boolean mForceReportNewAttributes; 19796 19797 /** 19798 * Set during a traveral if any views want to keep the screen on. 19799 */ 19800 boolean mKeepScreenOn; 19801 19802 /** 19803 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 19804 */ 19805 int mSystemUiVisibility; 19806 19807 /** 19808 * Hack to force certain system UI visibility flags to be cleared. 19809 */ 19810 int mDisabledSystemUiVisibility; 19811 19812 /** 19813 * Last global system UI visibility reported by the window manager. 19814 */ 19815 int mGlobalSystemUiVisibility; 19816 19817 /** 19818 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 19819 * attached. 19820 */ 19821 boolean mHasSystemUiListeners; 19822 19823 /** 19824 * Set if the window has requested to extend into the overscan region 19825 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 19826 */ 19827 boolean mOverscanRequested; 19828 19829 /** 19830 * Set if the visibility of any views has changed. 19831 */ 19832 boolean mViewVisibilityChanged; 19833 19834 /** 19835 * Set to true if a view has been scrolled. 19836 */ 19837 boolean mViewScrollChanged; 19838 19839 /** 19840 * Global to the view hierarchy used as a temporary for dealing with 19841 * x/y points in the transparent region computations. 19842 */ 19843 final int[] mTransparentLocation = new int[2]; 19844 19845 /** 19846 * Global to the view hierarchy used as a temporary for dealing with 19847 * x/y points in the ViewGroup.invalidateChild implementation. 19848 */ 19849 final int[] mInvalidateChildLocation = new int[2]; 19850 19851 19852 /** 19853 * Global to the view hierarchy used as a temporary for dealing with 19854 * x/y location when view is transformed. 19855 */ 19856 final float[] mTmpTransformLocation = new float[2]; 19857 19858 /** 19859 * The view tree observer used to dispatch global events like 19860 * layout, pre-draw, touch mode change, etc. 19861 */ 19862 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 19863 19864 /** 19865 * A Canvas used by the view hierarchy to perform bitmap caching. 19866 */ 19867 Canvas mCanvas; 19868 19869 /** 19870 * The view root impl. 19871 */ 19872 final ViewRootImpl mViewRootImpl; 19873 19874 /** 19875 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 19876 * handler can be used to pump events in the UI events queue. 19877 */ 19878 final Handler mHandler; 19879 19880 /** 19881 * Temporary for use in computing invalidate rectangles while 19882 * calling up the hierarchy. 19883 */ 19884 final Rect mTmpInvalRect = new Rect(); 19885 19886 /** 19887 * Temporary for use in computing hit areas with transformed views 19888 */ 19889 final RectF mTmpTransformRect = new RectF(); 19890 19891 /** 19892 * Temporary for use in transforming invalidation rect 19893 */ 19894 final Matrix mTmpMatrix = new Matrix(); 19895 19896 /** 19897 * Temporary for use in transforming invalidation rect 19898 */ 19899 final Transformation mTmpTransformation = new Transformation(); 19900 19901 /** 19902 * Temporary list for use in collecting focusable descendents of a view. 19903 */ 19904 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 19905 19906 /** 19907 * The id of the window for accessibility purposes. 19908 */ 19909 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 19910 19911 /** 19912 * Flags related to accessibility processing. 19913 * 19914 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 19915 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 19916 */ 19917 int mAccessibilityFetchFlags; 19918 19919 /** 19920 * The drawable for highlighting accessibility focus. 19921 */ 19922 Drawable mAccessibilityFocusDrawable; 19923 19924 /** 19925 * Show where the margins, bounds and layout bounds are for each view. 19926 */ 19927 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 19928 19929 /** 19930 * Point used to compute visible regions. 19931 */ 19932 final Point mPoint = new Point(); 19933 19934 /** 19935 * Used to track which View originated a requestLayout() call, used when 19936 * requestLayout() is called during layout. 19937 */ 19938 View mViewRequestingLayout; 19939 19940 /** 19941 * Creates a new set of attachment information with the specified 19942 * events handler and thread. 19943 * 19944 * @param handler the events handler the view must use 19945 */ 19946 AttachInfo(IWindowSession session, IWindow window, Display display, 19947 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 19948 mSession = session; 19949 mWindow = window; 19950 mWindowToken = window.asBinder(); 19951 mDisplay = display; 19952 mViewRootImpl = viewRootImpl; 19953 mHandler = handler; 19954 mRootCallbacks = effectPlayer; 19955 } 19956 } 19957 19958 /** 19959 * <p>ScrollabilityCache holds various fields used by a View when scrolling 19960 * is supported. This avoids keeping too many unused fields in most 19961 * instances of View.</p> 19962 */ 19963 private static class ScrollabilityCache implements Runnable { 19964 19965 /** 19966 * Scrollbars are not visible 19967 */ 19968 public static final int OFF = 0; 19969 19970 /** 19971 * Scrollbars are visible 19972 */ 19973 public static final int ON = 1; 19974 19975 /** 19976 * Scrollbars are fading away 19977 */ 19978 public static final int FADING = 2; 19979 19980 public boolean fadeScrollBars; 19981 19982 public int fadingEdgeLength; 19983 public int scrollBarDefaultDelayBeforeFade; 19984 public int scrollBarFadeDuration; 19985 19986 public int scrollBarSize; 19987 public ScrollBarDrawable scrollBar; 19988 public float[] interpolatorValues; 19989 public View host; 19990 19991 public final Paint paint; 19992 public final Matrix matrix; 19993 public Shader shader; 19994 19995 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 19996 19997 private static final float[] OPAQUE = { 255 }; 19998 private static final float[] TRANSPARENT = { 0.0f }; 19999 20000 /** 20001 * When fading should start. This time moves into the future every time 20002 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 20003 */ 20004 public long fadeStartTime; 20005 20006 20007 /** 20008 * The current state of the scrollbars: ON, OFF, or FADING 20009 */ 20010 public int state = OFF; 20011 20012 private int mLastColor; 20013 20014 public ScrollabilityCache(ViewConfiguration configuration, View host) { 20015 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 20016 scrollBarSize = configuration.getScaledScrollBarSize(); 20017 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 20018 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 20019 20020 paint = new Paint(); 20021 matrix = new Matrix(); 20022 // use use a height of 1, and then wack the matrix each time we 20023 // actually use it. 20024 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20025 paint.setShader(shader); 20026 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20027 20028 this.host = host; 20029 } 20030 20031 public void setFadeColor(int color) { 20032 if (color != mLastColor) { 20033 mLastColor = color; 20034 20035 if (color != 0) { 20036 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 20037 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 20038 paint.setShader(shader); 20039 // Restore the default transfer mode (src_over) 20040 paint.setXfermode(null); 20041 } else { 20042 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20043 paint.setShader(shader); 20044 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20045 } 20046 } 20047 } 20048 20049 public void run() { 20050 long now = AnimationUtils.currentAnimationTimeMillis(); 20051 if (now >= fadeStartTime) { 20052 20053 // the animation fades the scrollbars out by changing 20054 // the opacity (alpha) from fully opaque to fully 20055 // transparent 20056 int nextFrame = (int) now; 20057 int framesCount = 0; 20058 20059 Interpolator interpolator = scrollBarInterpolator; 20060 20061 // Start opaque 20062 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 20063 20064 // End transparent 20065 nextFrame += scrollBarFadeDuration; 20066 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 20067 20068 state = FADING; 20069 20070 // Kick off the fade animation 20071 host.invalidate(true); 20072 } 20073 } 20074 } 20075 20076 /** 20077 * Resuable callback for sending 20078 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 20079 */ 20080 private class SendViewScrolledAccessibilityEvent implements Runnable { 20081 public volatile boolean mIsPending; 20082 20083 public void run() { 20084 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 20085 mIsPending = false; 20086 } 20087 } 20088 20089 /** 20090 * <p> 20091 * This class represents a delegate that can be registered in a {@link View} 20092 * to enhance accessibility support via composition rather via inheritance. 20093 * It is specifically targeted to widget developers that extend basic View 20094 * classes i.e. classes in package android.view, that would like their 20095 * applications to be backwards compatible. 20096 * </p> 20097 * <div class="special reference"> 20098 * <h3>Developer Guides</h3> 20099 * <p>For more information about making applications accessible, read the 20100 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 20101 * developer guide.</p> 20102 * </div> 20103 * <p> 20104 * A scenario in which a developer would like to use an accessibility delegate 20105 * is overriding a method introduced in a later API version then the minimal API 20106 * version supported by the application. For example, the method 20107 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 20108 * in API version 4 when the accessibility APIs were first introduced. If a 20109 * developer would like his application to run on API version 4 devices (assuming 20110 * all other APIs used by the application are version 4 or lower) and take advantage 20111 * of this method, instead of overriding the method which would break the application's 20112 * backwards compatibility, he can override the corresponding method in this 20113 * delegate and register the delegate in the target View if the API version of 20114 * the system is high enough i.e. the API version is same or higher to the API 20115 * version that introduced 20116 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 20117 * </p> 20118 * <p> 20119 * Here is an example implementation: 20120 * </p> 20121 * <code><pre><p> 20122 * if (Build.VERSION.SDK_INT >= 14) { 20123 * // If the API version is equal of higher than the version in 20124 * // which onInitializeAccessibilityNodeInfo was introduced we 20125 * // register a delegate with a customized implementation. 20126 * View view = findViewById(R.id.view_id); 20127 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20128 * public void onInitializeAccessibilityNodeInfo(View host, 20129 * AccessibilityNodeInfo info) { 20130 * // Let the default implementation populate the info. 20131 * super.onInitializeAccessibilityNodeInfo(host, info); 20132 * // Set some other information. 20133 * info.setEnabled(host.isEnabled()); 20134 * } 20135 * }); 20136 * } 20137 * </code></pre></p> 20138 * <p> 20139 * This delegate contains methods that correspond to the accessibility methods 20140 * in View. If a delegate has been specified the implementation in View hands 20141 * off handling to the corresponding method in this delegate. The default 20142 * implementation the delegate methods behaves exactly as the corresponding 20143 * method in View for the case of no accessibility delegate been set. Hence, 20144 * to customize the behavior of a View method, clients can override only the 20145 * corresponding delegate method without altering the behavior of the rest 20146 * accessibility related methods of the host view. 20147 * </p> 20148 */ 20149 public static class AccessibilityDelegate { 20150 20151 /** 20152 * Sends an accessibility event of the given type. If accessibility is not 20153 * enabled this method has no effect. 20154 * <p> 20155 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20156 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20157 * been set. 20158 * </p> 20159 * 20160 * @param host The View hosting the delegate. 20161 * @param eventType The type of the event to send. 20162 * 20163 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20164 */ 20165 public void sendAccessibilityEvent(View host, int eventType) { 20166 host.sendAccessibilityEventInternal(eventType); 20167 } 20168 20169 /** 20170 * Performs the specified accessibility action on the view. For 20171 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20172 * <p> 20173 * The default implementation behaves as 20174 * {@link View#performAccessibilityAction(int, Bundle) 20175 * View#performAccessibilityAction(int, Bundle)} for the case of 20176 * no accessibility delegate been set. 20177 * </p> 20178 * 20179 * @param action The action to perform. 20180 * @return Whether the action was performed. 20181 * 20182 * @see View#performAccessibilityAction(int, Bundle) 20183 * View#performAccessibilityAction(int, Bundle) 20184 */ 20185 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20186 return host.performAccessibilityActionInternal(action, args); 20187 } 20188 20189 /** 20190 * Sends an accessibility event. This method behaves exactly as 20191 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20192 * empty {@link AccessibilityEvent} and does not perform a check whether 20193 * accessibility is enabled. 20194 * <p> 20195 * The default implementation behaves as 20196 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20197 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20198 * the case of no accessibility delegate been set. 20199 * </p> 20200 * 20201 * @param host The View hosting the delegate. 20202 * @param event The event to send. 20203 * 20204 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20205 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20206 */ 20207 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20208 host.sendAccessibilityEventUncheckedInternal(event); 20209 } 20210 20211 /** 20212 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20213 * to its children for adding their text content to the event. 20214 * <p> 20215 * The default implementation behaves as 20216 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20217 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20218 * the case of no accessibility delegate been set. 20219 * </p> 20220 * 20221 * @param host The View hosting the delegate. 20222 * @param event The event. 20223 * @return True if the event population was completed. 20224 * 20225 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20226 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20227 */ 20228 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20229 return host.dispatchPopulateAccessibilityEventInternal(event); 20230 } 20231 20232 /** 20233 * Gives a chance to the host View to populate the accessibility event with its 20234 * text content. 20235 * <p> 20236 * The default implementation behaves as 20237 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20238 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20239 * the case of no accessibility delegate been set. 20240 * </p> 20241 * 20242 * @param host The View hosting the delegate. 20243 * @param event The accessibility event which to populate. 20244 * 20245 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20246 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20247 */ 20248 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20249 host.onPopulateAccessibilityEventInternal(event); 20250 } 20251 20252 /** 20253 * Initializes an {@link AccessibilityEvent} with information about the 20254 * the host View which is the event source. 20255 * <p> 20256 * The default implementation behaves as 20257 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20258 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20259 * the case of no accessibility delegate been set. 20260 * </p> 20261 * 20262 * @param host The View hosting the delegate. 20263 * @param event The event to initialize. 20264 * 20265 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 20266 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 20267 */ 20268 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 20269 host.onInitializeAccessibilityEventInternal(event); 20270 } 20271 20272 /** 20273 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 20274 * <p> 20275 * The default implementation behaves as 20276 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20277 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 20278 * the case of no accessibility delegate been set. 20279 * </p> 20280 * 20281 * @param host The View hosting the delegate. 20282 * @param info The instance to initialize. 20283 * 20284 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20285 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20286 */ 20287 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 20288 host.onInitializeAccessibilityNodeInfoInternal(info); 20289 } 20290 20291 /** 20292 * Called when a child of the host View has requested sending an 20293 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 20294 * to augment the event. 20295 * <p> 20296 * The default implementation behaves as 20297 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20298 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 20299 * the case of no accessibility delegate been set. 20300 * </p> 20301 * 20302 * @param host The View hosting the delegate. 20303 * @param child The child which requests sending the event. 20304 * @param event The event to be sent. 20305 * @return True if the event should be sent 20306 * 20307 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20308 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20309 */ 20310 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 20311 AccessibilityEvent event) { 20312 return host.onRequestSendAccessibilityEventInternal(child, event); 20313 } 20314 20315 /** 20316 * Gets the provider for managing a virtual view hierarchy rooted at this View 20317 * and reported to {@link android.accessibilityservice.AccessibilityService}s 20318 * that explore the window content. 20319 * <p> 20320 * The default implementation behaves as 20321 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 20322 * the case of no accessibility delegate been set. 20323 * </p> 20324 * 20325 * @return The provider. 20326 * 20327 * @see AccessibilityNodeProvider 20328 */ 20329 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 20330 return null; 20331 } 20332 20333 /** 20334 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 20335 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 20336 * This method is responsible for obtaining an accessibility node info from a 20337 * pool of reusable instances and calling 20338 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 20339 * view to initialize the former. 20340 * <p> 20341 * <strong>Note:</strong> The client is responsible for recycling the obtained 20342 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 20343 * creation. 20344 * </p> 20345 * <p> 20346 * The default implementation behaves as 20347 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 20348 * the case of no accessibility delegate been set. 20349 * </p> 20350 * @return A populated {@link AccessibilityNodeInfo}. 20351 * 20352 * @see AccessibilityNodeInfo 20353 * 20354 * @hide 20355 */ 20356 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 20357 return host.createAccessibilityNodeInfoInternal(); 20358 } 20359 } 20360 20361 private class MatchIdPredicate implements Predicate<View> { 20362 public int mId; 20363 20364 @Override 20365 public boolean apply(View view) { 20366 return (view.mID == mId); 20367 } 20368 } 20369 20370 private class MatchLabelForPredicate implements Predicate<View> { 20371 private int mLabeledId; 20372 20373 @Override 20374 public boolean apply(View view) { 20375 return (view.mLabelForId == mLabeledId); 20376 } 20377 } 20378 20379 private class SendViewStateChangedAccessibilityEvent implements Runnable { 20380 private int mChangeTypes = 0; 20381 private boolean mPosted; 20382 private boolean mPostedWithDelay; 20383 private long mLastEventTimeMillis; 20384 20385 @Override 20386 public void run() { 20387 mPosted = false; 20388 mPostedWithDelay = false; 20389 mLastEventTimeMillis = SystemClock.uptimeMillis(); 20390 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 20391 final AccessibilityEvent event = AccessibilityEvent.obtain(); 20392 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 20393 event.setContentChangeTypes(mChangeTypes); 20394 sendAccessibilityEventUnchecked(event); 20395 } 20396 mChangeTypes = 0; 20397 } 20398 20399 public void runOrPost(int changeType) { 20400 mChangeTypes |= changeType; 20401 20402 // If this is a live region or the child of a live region, collect 20403 // all events from this frame and send them on the next frame. 20404 if (inLiveRegion()) { 20405 // If we're already posted with a delay, remove that. 20406 if (mPostedWithDelay) { 20407 removeCallbacks(this); 20408 mPostedWithDelay = false; 20409 } 20410 // Only post if we're not already posted. 20411 if (!mPosted) { 20412 post(this); 20413 mPosted = true; 20414 } 20415 return; 20416 } 20417 20418 if (mPosted) { 20419 return; 20420 } 20421 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 20422 final long minEventIntevalMillis = 20423 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 20424 if (timeSinceLastMillis >= minEventIntevalMillis) { 20425 removeCallbacks(this); 20426 run(); 20427 } else { 20428 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 20429 mPosted = true; 20430 mPostedWithDelay = true; 20431 } 20432 } 20433 } 20434 20435 private boolean inLiveRegion() { 20436 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20437 return true; 20438 } 20439 20440 ViewParent parent = getParent(); 20441 while (parent instanceof View) { 20442 if (((View) parent).getAccessibilityLiveRegion() 20443 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20444 return true; 20445 } 20446 parent = parent.getParent(); 20447 } 20448 20449 return false; 20450 } 20451 20452 /** 20453 * Dump all private flags in readable format, useful for documentation and 20454 * sanity checking. 20455 */ 20456 private static void dumpFlags() { 20457 final HashMap<String, String> found = Maps.newHashMap(); 20458 try { 20459 for (Field field : View.class.getDeclaredFields()) { 20460 final int modifiers = field.getModifiers(); 20461 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 20462 if (field.getType().equals(int.class)) { 20463 final int value = field.getInt(null); 20464 dumpFlag(found, field.getName(), value); 20465 } else if (field.getType().equals(int[].class)) { 20466 final int[] values = (int[]) field.get(null); 20467 for (int i = 0; i < values.length; i++) { 20468 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 20469 } 20470 } 20471 } 20472 } 20473 } catch (IllegalAccessException e) { 20474 throw new RuntimeException(e); 20475 } 20476 20477 final ArrayList<String> keys = Lists.newArrayList(); 20478 keys.addAll(found.keySet()); 20479 Collections.sort(keys); 20480 for (String key : keys) { 20481 Log.d(VIEW_LOG_TAG, found.get(key)); 20482 } 20483 } 20484 20485 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 20486 // Sort flags by prefix, then by bits, always keeping unique keys 20487 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 20488 final int prefix = name.indexOf('_'); 20489 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 20490 final String output = bits + " " + name; 20491 found.put(key, output); 20492 } 20493} 20494