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 17 package android.view; 18 19 import android.content.ClipData; 20 import android.content.Context; 21 import android.content.pm.ApplicationInfo; 22 import android.content.res.Configuration; 23 import android.content.res.Resources; 24 import android.content.res.TypedArray; 25 import android.graphics.Bitmap; 26 import android.graphics.Camera; 27 import android.graphics.Canvas; 28 import android.graphics.Insets; 29 import android.graphics.Interpolator; 30 import android.graphics.LinearGradient; 31 import android.graphics.Matrix; 32 import android.graphics.Paint; 33 import android.graphics.PixelFormat; 34 import android.graphics.Point; 35 import android.graphics.PorterDuff; 36 import android.graphics.PorterDuffXfermode; 37 import android.graphics.Rect; 38 import android.graphics.RectF; 39 import android.graphics.Region; 40 import android.graphics.Shader; 41 import android.graphics.drawable.ColorDrawable; 42 import android.graphics.drawable.Drawable; 43 import android.hardware.display.DisplayManagerGlobal; 44 import android.os.Bundle; 45 import android.os.Handler; 46 import android.os.IBinder; 47 import android.os.Parcel; 48 import android.os.Parcelable; 49 import android.os.RemoteException; 50 import android.os.SystemClock; 51 import android.os.SystemProperties; 52 import android.text.TextUtils; 53 import android.util.AttributeSet; 54 import android.util.FloatProperty; 55 import android.util.LayoutDirection; 56 import android.util.Log; 57 import android.util.LongSparseLongArray; 58 import android.util.Pools.SynchronizedPool; 59 import android.util.Property; 60 import android.util.SparseArray; 61 import android.util.SuperNotCalledException; 62 import android.util.TypedValue; 63 import android.view.ContextMenu.ContextMenuInfo; 64 import android.view.AccessibilityIterators.TextSegmentIterator; 65 import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 66 import android.view.AccessibilityIterators.WordTextSegmentIterator; 67 import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 68 import android.view.accessibility.AccessibilityEvent; 69 import android.view.accessibility.AccessibilityEventSource; 70 import android.view.accessibility.AccessibilityManager; 71 import android.view.accessibility.AccessibilityNodeInfo; 72 import android.view.accessibility.AccessibilityNodeProvider; 73 import android.view.animation.Animation; 74 import android.view.animation.AnimationUtils; 75 import android.view.animation.Transformation; 76 import android.view.inputmethod.EditorInfo; 77 import android.view.inputmethod.InputConnection; 78 import android.view.inputmethod.InputMethodManager; 79 import android.widget.ScrollBarDrawable; 80 81 import static android.os.Build.VERSION_CODES.*; 82 import static java.lang.Math.max; 83 84 import com.android.internal.R; 85 import com.android.internal.util.Predicate; 86 import com.android.internal.view.menu.MenuBuilder; 87 import com.google.android.collect.Lists; 88 import com.google.android.collect.Maps; 89 90 import java.lang.ref.WeakReference; 91 import java.lang.reflect.Field; 92 import java.lang.reflect.InvocationTargetException; 93 import java.lang.reflect.Method; 94 import java.lang.reflect.Modifier; 95 import java.util.ArrayList; 96 import java.util.Arrays; 97 import java.util.Collections; 98 import java.util.HashMap; 99 import java.util.Locale; 100 import java.util.concurrent.CopyOnWriteArrayList; 101 import java.util.concurrent.atomic.AtomicInteger; 102 103 /** 104 * <p> 105 * This class represents the basic building block for user interface components. A View 106 * occupies a rectangular area on the screen and is responsible for drawing and 107 * event handling. View is the base class for <em>widgets</em>, which are 108 * used to create interactive UI components (buttons, text fields, etc.). The 109 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 110 * are invisible containers that hold other Views (or other ViewGroups) and define 111 * their layout properties. 112 * </p> 113 * 114 * <div class="special reference"> 115 * <h3>Developer Guides</h3> 116 * <p>For information about using this class to develop your application's user interface, 117 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 118 * </div> 119 * 120 * <a name="Using"></a> 121 * <h3>Using Views</h3> 122 * <p> 123 * All of the views in a window are arranged in a single tree. You can add views 124 * either from code or by specifying a tree of views in one or more XML layout 125 * files. There are many specialized subclasses of views that act as controls or 126 * are capable of displaying text, images, or other content. 127 * </p> 128 * <p> 129 * Once you have created a tree of views, there are typically a few types of 130 * common operations you may wish to perform: 131 * <ul> 132 * <li><strong>Set properties:</strong> for example setting the text of a 133 * {@link android.widget.TextView}. The available properties and the methods 134 * that set them will vary among the different subclasses of views. Note that 135 * properties that are known at build time can be set in the XML layout 136 * files.</li> 137 * <li><strong>Set focus:</strong> The framework will handled moving focus in 138 * response to user input. To force focus to a specific view, call 139 * {@link #requestFocus}.</li> 140 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 141 * that will be notified when something interesting happens to the view. For 142 * example, all views will let you set a listener to be notified when the view 143 * gains or loses focus. You can register such a listener using 144 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 145 * Other view subclasses offer more specialized listeners. For example, a Button 146 * exposes a listener to notify clients when the button is clicked.</li> 147 * <li><strong>Set visibility:</strong> You can hide or show views using 148 * {@link #setVisibility(int)}.</li> 149 * </ul> 150 * </p> 151 * <p><em> 152 * Note: The Android framework is responsible for measuring, laying out and 153 * drawing views. You should not call methods that perform these actions on 154 * views yourself unless you are actually implementing a 155 * {@link android.view.ViewGroup}. 156 * </em></p> 157 * 158 * <a name="Lifecycle"></a> 159 * <h3>Implementing a Custom View</h3> 160 * 161 * <p> 162 * To implement a custom view, you will usually begin by providing overrides for 163 * some of the standard methods that the framework calls on all views. You do 164 * not need to override all of these methods. In fact, you can start by just 165 * overriding {@link #onDraw(android.graphics.Canvas)}. 166 * <table border="2" width="85%" align="center" cellpadding="5"> 167 * <thead> 168 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 169 * </thead> 170 * 171 * <tbody> 172 * <tr> 173 * <td rowspan="2">Creation</td> 174 * <td>Constructors</td> 175 * <td>There is a form of the constructor that are called when the view 176 * is created from code and a form that is called when the view is 177 * inflated from a layout file. The second form should parse and apply 178 * any attributes defined in the layout file. 179 * </td> 180 * </tr> 181 * <tr> 182 * <td><code>{@link #onFinishInflate()}</code></td> 183 * <td>Called after a view and all of its children has been inflated 184 * from XML.</td> 185 * </tr> 186 * 187 * <tr> 188 * <td rowspan="3">Layout</td> 189 * <td><code>{@link #onMeasure(int, int)}</code></td> 190 * <td>Called to determine the size requirements for this view and all 191 * of its children. 192 * </td> 193 * </tr> 194 * <tr> 195 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 196 * <td>Called when this view should assign a size and position to all 197 * of its children. 198 * </td> 199 * </tr> 200 * <tr> 201 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 202 * <td>Called when the size of this view has changed. 203 * </td> 204 * </tr> 205 * 206 * <tr> 207 * <td>Drawing</td> 208 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 209 * <td>Called when the view should render its content. 210 * </td> 211 * </tr> 212 * 213 * <tr> 214 * <td rowspan="4">Event processing</td> 215 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 216 * <td>Called when a new hardware key event occurs. 217 * </td> 218 * </tr> 219 * <tr> 220 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 221 * <td>Called when a hardware key up event occurs. 222 * </td> 223 * </tr> 224 * <tr> 225 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 226 * <td>Called when a trackball motion event occurs. 227 * </td> 228 * </tr> 229 * <tr> 230 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 231 * <td>Called when a touch screen motion event occurs. 232 * </td> 233 * </tr> 234 * 235 * <tr> 236 * <td rowspan="2">Focus</td> 237 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 238 * <td>Called when the view gains or loses focus. 239 * </td> 240 * </tr> 241 * 242 * <tr> 243 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 244 * <td>Called when the window containing the view gains or loses focus. 245 * </td> 246 * </tr> 247 * 248 * <tr> 249 * <td rowspan="3">Attaching</td> 250 * <td><code>{@link #onAttachedToWindow()}</code></td> 251 * <td>Called when the view is attached to a window. 252 * </td> 253 * </tr> 254 * 255 * <tr> 256 * <td><code>{@link #onDetachedFromWindow}</code></td> 257 * <td>Called when the view is detached from its window. 258 * </td> 259 * </tr> 260 * 261 * <tr> 262 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 263 * <td>Called when the visibility of the window containing the view 264 * has changed. 265 * </td> 266 * </tr> 267 * </tbody> 268 * 269 * </table> 270 * </p> 271 * 272 * <a name="IDs"></a> 273 * <h3>IDs</h3> 274 * Views may have an integer id associated with them. These ids are typically 275 * assigned in the layout XML files, and are used to find specific views within 276 * the view tree. A common pattern is to: 277 * <ul> 278 * <li>Define a Button in the layout file and assign it a unique ID. 279 * <pre> 280 * <Button 281 * android:id="@+id/my_button" 282 * android:layout_width="wrap_content" 283 * android:layout_height="wrap_content" 284 * android:text="@string/my_button_text"/> 285 * </pre></li> 286 * <li>From the onCreate method of an Activity, find the Button 287 * <pre class="prettyprint"> 288 * Button myButton = (Button) findViewById(R.id.my_button); 289 * </pre></li> 290 * </ul> 291 * <p> 292 * View IDs need not be unique throughout the tree, but it is good practice to 293 * ensure that they are at least unique within the part of the tree you are 294 * searching. 295 * </p> 296 * 297 * <a name="Position"></a> 298 * <h3>Position</h3> 299 * <p> 300 * The geometry of a view is that of a rectangle. A view has a location, 301 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 302 * two dimensions, expressed as a width and a height. The unit for location 303 * and dimensions is the pixel. 304 * </p> 305 * 306 * <p> 307 * It is possible to retrieve the location of a view by invoking the methods 308 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 309 * coordinate of the rectangle representing the view. The latter returns the 310 * top, or Y, coordinate of the rectangle representing the view. These methods 311 * both return the location of the view relative to its parent. For instance, 312 * when getLeft() returns 20, that means the view is located 20 pixels to the 313 * right of the left edge of its direct parent. 314 * </p> 315 * 316 * <p> 317 * In addition, several convenience methods are offered to avoid unnecessary 318 * computations, namely {@link #getRight()} and {@link #getBottom()}. 319 * These methods return the coordinates of the right and bottom edges of the 320 * rectangle representing the view. For instance, calling {@link #getRight()} 321 * is similar to the following computation: <code>getLeft() + getWidth()</code> 322 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 323 * </p> 324 * 325 * <a name="SizePaddingMargins"></a> 326 * <h3>Size, padding and margins</h3> 327 * <p> 328 * The size of a view is expressed with a width and a height. A view actually 329 * possess two pairs of width and height values. 330 * </p> 331 * 332 * <p> 333 * The first pair is known as <em>measured width</em> and 334 * <em>measured height</em>. These dimensions define how big a view wants to be 335 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 336 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 337 * and {@link #getMeasuredHeight()}. 338 * </p> 339 * 340 * <p> 341 * The second pair is simply known as <em>width</em> and <em>height</em>, or 342 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 343 * dimensions define the actual size of the view on screen, at drawing time and 344 * after layout. These values may, but do not have to, be different from the 345 * measured width and height. The width and height can be obtained by calling 346 * {@link #getWidth()} and {@link #getHeight()}. 347 * </p> 348 * 349 * <p> 350 * To measure its dimensions, a view takes into account its padding. The padding 351 * is expressed in pixels for the left, top, right and bottom parts of the view. 352 * Padding can be used to offset the content of the view by a specific amount of 353 * pixels. For instance, a left padding of 2 will push the view's content by 354 * 2 pixels to the right of the left edge. Padding can be set using the 355 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 356 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 357 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 358 * {@link #getPaddingEnd()}. 359 * </p> 360 * 361 * <p> 362 * Even though a view can define a padding, it does not provide any support for 363 * margins. However, view groups provide such a support. Refer to 364 * {@link android.view.ViewGroup} and 365 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 366 * </p> 367 * 368 * <a name="Layout"></a> 369 * <h3>Layout</h3> 370 * <p> 371 * Layout is a two pass process: a measure pass and a layout pass. The measuring 372 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 373 * of the view tree. Each view pushes dimension specifications down the tree 374 * during the recursion. At the end of the measure pass, every view has stored 375 * its measurements. The second pass happens in 376 * {@link #layout(int,int,int,int)} and is also top-down. During 377 * this pass each parent is responsible for positioning all of its children 378 * using the sizes computed in the measure pass. 379 * </p> 380 * 381 * <p> 382 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 383 * {@link #getMeasuredHeight()} values must be set, along with those for all of 384 * that view's descendants. A view's measured width and measured height values 385 * must respect the constraints imposed by the view's parents. This guarantees 386 * that at the end of the measure pass, all parents accept all of their 387 * children's measurements. A parent view may call measure() more than once on 388 * its children. For example, the parent may measure each child once with 389 * unspecified dimensions to find out how big they want to be, then call 390 * measure() on them again with actual numbers if the sum of all the children's 391 * unconstrained sizes is too big or too small. 392 * </p> 393 * 394 * <p> 395 * The measure pass uses two classes to communicate dimensions. The 396 * {@link MeasureSpec} class is used by views to tell their parents how they 397 * want to be measured and positioned. The base LayoutParams class just 398 * describes how big the view wants to be for both width and height. For each 399 * dimension, it can specify one of: 400 * <ul> 401 * <li> an exact number 402 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 403 * (minus padding) 404 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 405 * enclose its content (plus padding). 406 * </ul> 407 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 408 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 409 * an X and Y value. 410 * </p> 411 * 412 * <p> 413 * MeasureSpecs are used to push requirements down the tree from parent to 414 * child. A MeasureSpec can be in one of three modes: 415 * <ul> 416 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 417 * of a child view. For example, a LinearLayout may call measure() on its child 418 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 419 * tall the child view wants to be given a width of 240 pixels. 420 * <li>EXACTLY: This is used by the parent to impose an exact size on the 421 * child. The child must use this size, and guarantee that all of its 422 * descendants will fit within this size. 423 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 424 * child. The child must gurantee that it and all of its descendants will fit 425 * within this size. 426 * </ul> 427 * </p> 428 * 429 * <p> 430 * To intiate a layout, call {@link #requestLayout}. This method is typically 431 * called by a view on itself when it believes that is can no longer fit within 432 * its current bounds. 433 * </p> 434 * 435 * <a name="Drawing"></a> 436 * <h3>Drawing</h3> 437 * <p> 438 * Drawing is handled by walking the tree and rendering each view that 439 * intersects the invalid region. Because the tree is traversed in-order, 440 * this means that parents will draw before (i.e., behind) their children, with 441 * siblings drawn in the order they appear in the tree. 442 * If you set a background drawable for a View, then the View will draw it for you 443 * before calling back to its <code>onDraw()</code> method. 444 * </p> 445 * 446 * <p> 447 * Note that the framework will not draw views that are not in the invalid region. 448 * </p> 449 * 450 * <p> 451 * To force a view to draw, call {@link #invalidate()}. 452 * </p> 453 * 454 * <a name="EventHandlingThreading"></a> 455 * <h3>Event Handling and Threading</h3> 456 * <p> 457 * The basic cycle of a view is as follows: 458 * <ol> 459 * <li>An event comes in and is dispatched to the appropriate view. The view 460 * handles the event and notifies any listeners.</li> 461 * <li>If in the course of processing the event, the view's bounds may need 462 * to be changed, the view will call {@link #requestLayout()}.</li> 463 * <li>Similarly, if in the course of processing the event the view's appearance 464 * may need to be changed, the view will call {@link #invalidate()}.</li> 465 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 466 * the framework will take care of measuring, laying out, and drawing the tree 467 * as appropriate.</li> 468 * </ol> 469 * </p> 470 * 471 * <p><em>Note: The entire view tree is single threaded. You must always be on 472 * the UI thread when calling any method on any view.</em> 473 * If you are doing work on other threads and want to update the state of a view 474 * from that thread, you should use a {@link Handler}. 475 * </p> 476 * 477 * <a name="FocusHandling"></a> 478 * <h3>Focus Handling</h3> 479 * <p> 480 * The framework will handle routine focus movement in response to user input. 481 * This includes changing the focus as views are removed or hidden, or as new 482 * views become available. Views indicate their willingness to take focus 483 * through the {@link #isFocusable} method. To change whether a view can take 484 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 485 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 486 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 487 * </p> 488 * <p> 489 * Focus movement is based on an algorithm which finds the nearest neighbor in a 490 * given direction. In rare cases, the default algorithm may not match the 491 * intended behavior of the developer. In these situations, you can provide 492 * explicit overrides by using these XML attributes in the layout file: 493 * <pre> 494 * nextFocusDown 495 * nextFocusLeft 496 * nextFocusRight 497 * nextFocusUp 498 * </pre> 499 * </p> 500 * 501 * 502 * <p> 503 * To get a particular view to take focus, call {@link #requestFocus()}. 504 * </p> 505 * 506 * <a name="TouchMode"></a> 507 * <h3>Touch Mode</h3> 508 * <p> 509 * When a user is navigating a user interface via directional keys such as a D-pad, it is 510 * necessary to give focus to actionable items such as buttons so the user can see 511 * what will take input. If the device has touch capabilities, however, and the user 512 * begins interacting with the interface by touching it, it is no longer necessary to 513 * always highlight, or give focus to, a particular view. This motivates a mode 514 * for interaction named 'touch mode'. 515 * </p> 516 * <p> 517 * For a touch capable device, once the user touches the screen, the device 518 * will enter touch mode. From this point onward, only views for which 519 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 520 * Other views that are touchable, like buttons, will not take focus when touched; they will 521 * only fire the on click listeners. 522 * </p> 523 * <p> 524 * Any time a user hits a directional key, such as a D-pad direction, the view device will 525 * exit touch mode, and find a view to take focus, so that the user may resume interacting 526 * with the user interface without touching the screen again. 527 * </p> 528 * <p> 529 * The touch mode state is maintained across {@link android.app.Activity}s. Call 530 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 531 * </p> 532 * 533 * <a name="Scrolling"></a> 534 * <h3>Scrolling</h3> 535 * <p> 536 * The framework provides basic support for views that wish to internally 537 * scroll their content. This includes keeping track of the X and Y scroll 538 * offset as well as mechanisms for drawing scrollbars. See 539 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 540 * {@link #awakenScrollBars()} for more details. 541 * </p> 542 * 543 * <a name="Tags"></a> 544 * <h3>Tags</h3> 545 * <p> 546 * Unlike IDs, tags are not used to identify views. Tags are essentially an 547 * extra piece of information that can be associated with a view. They are most 548 * often used as a convenience to store data related to views in the views 549 * themselves rather than by putting them in a separate structure. 550 * </p> 551 * 552 * <a name="Properties"></a> 553 * <h3>Properties</h3> 554 * <p> 555 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 556 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 557 * available both in the {@link Property} form as well as in similarly-named setter/getter 558 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 559 * be used to set persistent state associated with these rendering-related properties on the view. 560 * The properties and methods can also be used in conjunction with 561 * {@link android.animation.Animator Animator}-based animations, described more in the 562 * <a href="#Animation">Animation</a> section. 563 * </p> 564 * 565 * <a name="Animation"></a> 566 * <h3>Animation</h3> 567 * <p> 568 * Starting with Android 3.0, the preferred way of animating views is to use the 569 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 570 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 571 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 572 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 573 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 574 * makes animating these View properties particularly easy and efficient. 575 * </p> 576 * <p> 577 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 578 * You can attach an {@link Animation} object to a view using 579 * {@link #setAnimation(Animation)} or 580 * {@link #startAnimation(Animation)}. The animation can alter the scale, 581 * rotation, translation and alpha of a view over time. If the animation is 582 * attached to a view that has children, the animation will affect the entire 583 * subtree rooted by that node. When an animation is started, the framework will 584 * take care of redrawing the appropriate views until the animation completes. 585 * </p> 586 * 587 * <a name="Security"></a> 588 * <h3>Security</h3> 589 * <p> 590 * Sometimes it is essential that an application be able to verify that an action 591 * is being performed with the full knowledge and consent of the user, such as 592 * granting a permission request, making a purchase or clicking on an advertisement. 593 * Unfortunately, a malicious application could try to spoof the user into 594 * performing these actions, unaware, by concealing the intended purpose of the view. 595 * As a remedy, the framework offers a touch filtering mechanism that can be used to 596 * improve the security of views that provide access to sensitive functionality. 597 * </p><p> 598 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 599 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 600 * will discard touches that are received whenever the view's window is obscured by 601 * another visible window. As a result, the view will not receive touches whenever a 602 * toast, dialog or other window appears above the view's window. 603 * </p><p> 604 * For more fine-grained control over security, consider overriding the 605 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 606 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 607 * </p> 608 * 609 * @attr ref android.R.styleable#View_alpha 610 * @attr ref android.R.styleable#View_background 611 * @attr ref android.R.styleable#View_clickable 612 * @attr ref android.R.styleable#View_contentDescription 613 * @attr ref android.R.styleable#View_drawingCacheQuality 614 * @attr ref android.R.styleable#View_duplicateParentState 615 * @attr ref android.R.styleable#View_id 616 * @attr ref android.R.styleable#View_requiresFadingEdge 617 * @attr ref android.R.styleable#View_fadeScrollbars 618 * @attr ref android.R.styleable#View_fadingEdgeLength 619 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 620 * @attr ref android.R.styleable#View_fitsSystemWindows 621 * @attr ref android.R.styleable#View_isScrollContainer 622 * @attr ref android.R.styleable#View_focusable 623 * @attr ref android.R.styleable#View_focusableInTouchMode 624 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 625 * @attr ref android.R.styleable#View_keepScreenOn 626 * @attr ref android.R.styleable#View_layerType 627 * @attr ref android.R.styleable#View_layoutDirection 628 * @attr ref android.R.styleable#View_longClickable 629 * @attr ref android.R.styleable#View_minHeight 630 * @attr ref android.R.styleable#View_minWidth 631 * @attr ref android.R.styleable#View_nextFocusDown 632 * @attr ref android.R.styleable#View_nextFocusLeft 633 * @attr ref android.R.styleable#View_nextFocusRight 634 * @attr ref android.R.styleable#View_nextFocusUp 635 * @attr ref android.R.styleable#View_onClick 636 * @attr ref android.R.styleable#View_padding 637 * @attr ref android.R.styleable#View_paddingBottom 638 * @attr ref android.R.styleable#View_paddingLeft 639 * @attr ref android.R.styleable#View_paddingRight 640 * @attr ref android.R.styleable#View_paddingTop 641 * @attr ref android.R.styleable#View_paddingStart 642 * @attr ref android.R.styleable#View_paddingEnd 643 * @attr ref android.R.styleable#View_saveEnabled 644 * @attr ref android.R.styleable#View_rotation 645 * @attr ref android.R.styleable#View_rotationX 646 * @attr ref android.R.styleable#View_rotationY 647 * @attr ref android.R.styleable#View_scaleX 648 * @attr ref android.R.styleable#View_scaleY 649 * @attr ref android.R.styleable#View_scrollX 650 * @attr ref android.R.styleable#View_scrollY 651 * @attr ref android.R.styleable#View_scrollbarSize 652 * @attr ref android.R.styleable#View_scrollbarStyle 653 * @attr ref android.R.styleable#View_scrollbars 654 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 655 * @attr ref android.R.styleable#View_scrollbarFadeDuration 656 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 657 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 658 * @attr ref android.R.styleable#View_scrollbarThumbVertical 659 * @attr ref android.R.styleable#View_scrollbarTrackVertical 660 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 661 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 662 * @attr ref android.R.styleable#View_soundEffectsEnabled 663 * @attr ref android.R.styleable#View_tag 664 * @attr ref android.R.styleable#View_textAlignment 665 * @attr ref android.R.styleable#View_textDirection 666 * @attr ref android.R.styleable#View_transformPivotX 667 * @attr ref android.R.styleable#View_transformPivotY 668 * @attr ref android.R.styleable#View_translationX 669 * @attr ref android.R.styleable#View_translationY 670 * @attr ref android.R.styleable#View_visibility 671 * 672 * @see android.view.ViewGroup 673 */ 674 public class View implements Drawable.Callback, KeyEvent.Callback, 675 AccessibilityEventSource { 676 private static final boolean DBG = false; 677 678 /** 679 * The logging tag used by this class with android.util.Log. 680 */ 681 protected static final String VIEW_LOG_TAG = "View"; 682 683 /** 684 * When set to true, apps will draw debugging information about their layouts. 685 * 686 * @hide 687 */ 688 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 689 690 /** 691 * Used to mark a View that has no ID. 692 */ 693 public static final int NO_ID = -1; 694 695 /** 696 * Signals that compatibility booleans have been initialized according to 697 * target SDK versions. 698 */ 699 private static boolean sCompatibilityDone = false; 700 701 /** 702 * Use the old (broken) way of building MeasureSpecs. 703 */ 704 private static boolean sUseBrokenMakeMeasureSpec = false; 705 706 /** 707 * Ignore any optimizations using the measure cache. 708 */ 709 private static boolean sIgnoreMeasureCache = false; 710 711 /** 712 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 713 * calling setFlags. 714 */ 715 private static final int NOT_FOCUSABLE = 0x00000000; 716 717 /** 718 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 719 * setFlags. 720 */ 721 private static final int FOCUSABLE = 0x00000001; 722 723 /** 724 * Mask for use with setFlags indicating bits used for focus. 725 */ 726 private static final int FOCUSABLE_MASK = 0x00000001; 727 728 /** 729 * This view will adjust its padding to fit sytem windows (e.g. status bar) 730 */ 731 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 732 733 /** 734 * This view is visible. 735 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 736 * android:visibility}. 737 */ 738 public static final int VISIBLE = 0x00000000; 739 740 /** 741 * This view is invisible, but it still takes up space for layout purposes. 742 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 743 * android:visibility}. 744 */ 745 public static final int INVISIBLE = 0x00000004; 746 747 /** 748 * This view is invisible, and it doesn't take any space for layout 749 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 750 * android:visibility}. 751 */ 752 public static final int GONE = 0x00000008; 753 754 /** 755 * Mask for use with setFlags indicating bits used for visibility. 756 * {@hide} 757 */ 758 static final int VISIBILITY_MASK = 0x0000000C; 759 760 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 761 762 /** 763 * This view is enabled. Interpretation varies by subclass. 764 * Use with ENABLED_MASK when calling setFlags. 765 * {@hide} 766 */ 767 static final int ENABLED = 0x00000000; 768 769 /** 770 * This view is disabled. Interpretation varies by subclass. 771 * Use with ENABLED_MASK when calling setFlags. 772 * {@hide} 773 */ 774 static final int DISABLED = 0x00000020; 775 776 /** 777 * Mask for use with setFlags indicating bits used for indicating whether 778 * this view is enabled 779 * {@hide} 780 */ 781 static final int ENABLED_MASK = 0x00000020; 782 783 /** 784 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 785 * called and further optimizations will be performed. It is okay to have 786 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 787 * {@hide} 788 */ 789 static final int WILL_NOT_DRAW = 0x00000080; 790 791 /** 792 * Mask for use with setFlags indicating bits used for indicating whether 793 * this view is will draw 794 * {@hide} 795 */ 796 static final int DRAW_MASK = 0x00000080; 797 798 /** 799 * <p>This view doesn't show scrollbars.</p> 800 * {@hide} 801 */ 802 static final int SCROLLBARS_NONE = 0x00000000; 803 804 /** 805 * <p>This view shows horizontal scrollbars.</p> 806 * {@hide} 807 */ 808 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 809 810 /** 811 * <p>This view shows vertical scrollbars.</p> 812 * {@hide} 813 */ 814 static final int SCROLLBARS_VERTICAL = 0x00000200; 815 816 /** 817 * <p>Mask for use with setFlags indicating bits used for indicating which 818 * scrollbars are enabled.</p> 819 * {@hide} 820 */ 821 static final int SCROLLBARS_MASK = 0x00000300; 822 823 /** 824 * Indicates that the view should filter touches when its window is obscured. 825 * Refer to the class comments for more information about this security feature. 826 * {@hide} 827 */ 828 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 829 830 /** 831 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 832 * that they are optional and should be skipped if the window has 833 * requested system UI flags that ignore those insets for layout. 834 */ 835 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 836 837 /** 838 * <p>This view doesn't show fading edges.</p> 839 * {@hide} 840 */ 841 static final int FADING_EDGE_NONE = 0x00000000; 842 843 /** 844 * <p>This view shows horizontal fading edges.</p> 845 * {@hide} 846 */ 847 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 848 849 /** 850 * <p>This view shows vertical fading edges.</p> 851 * {@hide} 852 */ 853 static final int FADING_EDGE_VERTICAL = 0x00002000; 854 855 /** 856 * <p>Mask for use with setFlags indicating bits used for indicating which 857 * fading edges are enabled.</p> 858 * {@hide} 859 */ 860 static final int FADING_EDGE_MASK = 0x00003000; 861 862 /** 863 * <p>Indicates this view can be clicked. When clickable, a View reacts 864 * to clicks by notifying the OnClickListener.<p> 865 * {@hide} 866 */ 867 static final int CLICKABLE = 0x00004000; 868 869 /** 870 * <p>Indicates this view is caching its drawing into a bitmap.</p> 871 * {@hide} 872 */ 873 static final int DRAWING_CACHE_ENABLED = 0x00008000; 874 875 /** 876 * <p>Indicates that no icicle should be saved for this view.<p> 877 * {@hide} 878 */ 879 static final int SAVE_DISABLED = 0x000010000; 880 881 /** 882 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 883 * property.</p> 884 * {@hide} 885 */ 886 static final int SAVE_DISABLED_MASK = 0x000010000; 887 888 /** 889 * <p>Indicates that no drawing cache should ever be created for this view.<p> 890 * {@hide} 891 */ 892 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 893 894 /** 895 * <p>Indicates this view can take / keep focus when int touch mode.</p> 896 * {@hide} 897 */ 898 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 899 900 /** 901 * <p>Enables low quality mode for the drawing cache.</p> 902 */ 903 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 904 905 /** 906 * <p>Enables high quality mode for the drawing cache.</p> 907 */ 908 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 909 910 /** 911 * <p>Enables automatic quality mode for the drawing cache.</p> 912 */ 913 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 914 915 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 916 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 917 }; 918 919 /** 920 * <p>Mask for use with setFlags indicating bits used for the cache 921 * quality property.</p> 922 * {@hide} 923 */ 924 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 925 926 /** 927 * <p> 928 * Indicates this view can be long clicked. When long clickable, a View 929 * reacts to long clicks by notifying the OnLongClickListener or showing a 930 * context menu. 931 * </p> 932 * {@hide} 933 */ 934 static final int LONG_CLICKABLE = 0x00200000; 935 936 /** 937 * <p>Indicates that this view gets its drawable states from its direct parent 938 * and ignores its original internal states.</p> 939 * 940 * @hide 941 */ 942 static final int DUPLICATE_PARENT_STATE = 0x00400000; 943 944 /** 945 * The scrollbar style to display the scrollbars inside the content area, 946 * without increasing the padding. The scrollbars will be overlaid with 947 * translucency on the view's content. 948 */ 949 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 950 951 /** 952 * The scrollbar style to display the scrollbars inside the padded area, 953 * increasing the padding of the view. The scrollbars will not overlap the 954 * content area of the view. 955 */ 956 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 957 958 /** 959 * The scrollbar style to display the scrollbars at the edge of the view, 960 * without increasing the padding. The scrollbars will be overlaid with 961 * translucency. 962 */ 963 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 964 965 /** 966 * The scrollbar style to display the scrollbars at the edge of the view, 967 * increasing the padding of the view. The scrollbars will only overlap the 968 * background, if any. 969 */ 970 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 971 972 /** 973 * Mask to check if the scrollbar style is overlay or inset. 974 * {@hide} 975 */ 976 static final int SCROLLBARS_INSET_MASK = 0x01000000; 977 978 /** 979 * Mask to check if the scrollbar style is inside or outside. 980 * {@hide} 981 */ 982 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 983 984 /** 985 * Mask for scrollbar style. 986 * {@hide} 987 */ 988 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 989 990 /** 991 * View flag indicating that the screen should remain on while the 992 * window containing this view is visible to the user. This effectively 993 * takes care of automatically setting the WindowManager's 994 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 995 */ 996 public static final int KEEP_SCREEN_ON = 0x04000000; 997 998 /** 999 * View flag indicating whether this view should have sound effects enabled 1000 * for events such as clicking and touching. 1001 */ 1002 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1003 1004 /** 1005 * View flag indicating whether this view should have haptic feedback 1006 * enabled for events such as long presses. 1007 */ 1008 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1009 1010 /** 1011 * <p>Indicates that the view hierarchy should stop saving state when 1012 * it reaches this view. If state saving is initiated immediately at 1013 * the view, it will be allowed. 1014 * {@hide} 1015 */ 1016 static final int PARENT_SAVE_DISABLED = 0x20000000; 1017 1018 /** 1019 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1020 * {@hide} 1021 */ 1022 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1023 1024 /** 1025 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1026 * should add all focusable Views regardless if they are focusable in touch mode. 1027 */ 1028 public static final int FOCUSABLES_ALL = 0x00000000; 1029 1030 /** 1031 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1032 * should add only Views focusable in touch mode. 1033 */ 1034 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1035 1036 /** 1037 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1038 * item. 1039 */ 1040 public static final int FOCUS_BACKWARD = 0x00000001; 1041 1042 /** 1043 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1044 * item. 1045 */ 1046 public static final int FOCUS_FORWARD = 0x00000002; 1047 1048 /** 1049 * Use with {@link #focusSearch(int)}. Move focus to the left. 1050 */ 1051 public static final int FOCUS_LEFT = 0x00000011; 1052 1053 /** 1054 * Use with {@link #focusSearch(int)}. Move focus up. 1055 */ 1056 public static final int FOCUS_UP = 0x00000021; 1057 1058 /** 1059 * Use with {@link #focusSearch(int)}. Move focus to the right. 1060 */ 1061 public static final int FOCUS_RIGHT = 0x00000042; 1062 1063 /** 1064 * Use with {@link #focusSearch(int)}. Move focus down. 1065 */ 1066 public static final int FOCUS_DOWN = 0x00000082; 1067 1068 /** 1069 * Bits of {@link #getMeasuredWidthAndState()} and 1070 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1071 */ 1072 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1073 1074 /** 1075 * Bits of {@link #getMeasuredWidthAndState()} and 1076 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1077 */ 1078 public static final int MEASURED_STATE_MASK = 0xff000000; 1079 1080 /** 1081 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1082 * for functions that combine both width and height into a single int, 1083 * such as {@link #getMeasuredState()} and the childState argument of 1084 * {@link #resolveSizeAndState(int, int, int)}. 1085 */ 1086 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1087 1088 /** 1089 * Bit of {@link #getMeasuredWidthAndState()} and 1090 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1091 * is smaller that the space the view would like to have. 1092 */ 1093 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1094 1095 /** 1096 * Base View state sets 1097 */ 1098 // Singles 1099 /** 1100 * Indicates the view has no states set. States are used with 1101 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1102 * view depending on its state. 1103 * 1104 * @see android.graphics.drawable.Drawable 1105 * @see #getDrawableState() 1106 */ 1107 protected static final int[] EMPTY_STATE_SET; 1108 /** 1109 * Indicates the view is enabled. States are used with 1110 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1111 * view depending on its state. 1112 * 1113 * @see android.graphics.drawable.Drawable 1114 * @see #getDrawableState() 1115 */ 1116 protected static final int[] ENABLED_STATE_SET; 1117 /** 1118 * Indicates the view is focused. States are used with 1119 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1120 * view depending on its state. 1121 * 1122 * @see android.graphics.drawable.Drawable 1123 * @see #getDrawableState() 1124 */ 1125 protected static final int[] FOCUSED_STATE_SET; 1126 /** 1127 * Indicates the view is selected. States are used with 1128 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1129 * view depending on its state. 1130 * 1131 * @see android.graphics.drawable.Drawable 1132 * @see #getDrawableState() 1133 */ 1134 protected static final int[] SELECTED_STATE_SET; 1135 /** 1136 * Indicates the view is pressed. States are used with 1137 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1138 * view depending on its state. 1139 * 1140 * @see android.graphics.drawable.Drawable 1141 * @see #getDrawableState() 1142 */ 1143 protected static final int[] PRESSED_STATE_SET; 1144 /** 1145 * Indicates the view's window has focus. States are used with 1146 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1147 * view depending on its state. 1148 * 1149 * @see android.graphics.drawable.Drawable 1150 * @see #getDrawableState() 1151 */ 1152 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1153 // Doubles 1154 /** 1155 * Indicates the view is enabled and has the focus. 1156 * 1157 * @see #ENABLED_STATE_SET 1158 * @see #FOCUSED_STATE_SET 1159 */ 1160 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1161 /** 1162 * Indicates the view is enabled and selected. 1163 * 1164 * @see #ENABLED_STATE_SET 1165 * @see #SELECTED_STATE_SET 1166 */ 1167 protected static final int[] ENABLED_SELECTED_STATE_SET; 1168 /** 1169 * Indicates the view is enabled and that its window has focus. 1170 * 1171 * @see #ENABLED_STATE_SET 1172 * @see #WINDOW_FOCUSED_STATE_SET 1173 */ 1174 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1175 /** 1176 * Indicates the view is focused and selected. 1177 * 1178 * @see #FOCUSED_STATE_SET 1179 * @see #SELECTED_STATE_SET 1180 */ 1181 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1182 /** 1183 * Indicates the view has the focus and that its window has the focus. 1184 * 1185 * @see #FOCUSED_STATE_SET 1186 * @see #WINDOW_FOCUSED_STATE_SET 1187 */ 1188 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1189 /** 1190 * Indicates the view is selected and that its window has the focus. 1191 * 1192 * @see #SELECTED_STATE_SET 1193 * @see #WINDOW_FOCUSED_STATE_SET 1194 */ 1195 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1196 // Triples 1197 /** 1198 * Indicates the view is enabled, focused and selected. 1199 * 1200 * @see #ENABLED_STATE_SET 1201 * @see #FOCUSED_STATE_SET 1202 * @see #SELECTED_STATE_SET 1203 */ 1204 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1205 /** 1206 * Indicates the view is enabled, focused and its window has the focus. 1207 * 1208 * @see #ENABLED_STATE_SET 1209 * @see #FOCUSED_STATE_SET 1210 * @see #WINDOW_FOCUSED_STATE_SET 1211 */ 1212 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1213 /** 1214 * Indicates the view is enabled, selected and its window has the focus. 1215 * 1216 * @see #ENABLED_STATE_SET 1217 * @see #SELECTED_STATE_SET 1218 * @see #WINDOW_FOCUSED_STATE_SET 1219 */ 1220 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1221 /** 1222 * Indicates the view is focused, selected and its window has the focus. 1223 * 1224 * @see #FOCUSED_STATE_SET 1225 * @see #SELECTED_STATE_SET 1226 * @see #WINDOW_FOCUSED_STATE_SET 1227 */ 1228 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1229 /** 1230 * Indicates the view is enabled, focused, selected and its window 1231 * has the focus. 1232 * 1233 * @see #ENABLED_STATE_SET 1234 * @see #FOCUSED_STATE_SET 1235 * @see #SELECTED_STATE_SET 1236 * @see #WINDOW_FOCUSED_STATE_SET 1237 */ 1238 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1239 /** 1240 * Indicates the view is pressed and its window has the focus. 1241 * 1242 * @see #PRESSED_STATE_SET 1243 * @see #WINDOW_FOCUSED_STATE_SET 1244 */ 1245 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1246 /** 1247 * Indicates the view is pressed and selected. 1248 * 1249 * @see #PRESSED_STATE_SET 1250 * @see #SELECTED_STATE_SET 1251 */ 1252 protected static final int[] PRESSED_SELECTED_STATE_SET; 1253 /** 1254 * Indicates the view is pressed, selected and its window has the focus. 1255 * 1256 * @see #PRESSED_STATE_SET 1257 * @see #SELECTED_STATE_SET 1258 * @see #WINDOW_FOCUSED_STATE_SET 1259 */ 1260 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1261 /** 1262 * Indicates the view is pressed and focused. 1263 * 1264 * @see #PRESSED_STATE_SET 1265 * @see #FOCUSED_STATE_SET 1266 */ 1267 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1268 /** 1269 * Indicates the view is pressed, focused and its window has the focus. 1270 * 1271 * @see #PRESSED_STATE_SET 1272 * @see #FOCUSED_STATE_SET 1273 * @see #WINDOW_FOCUSED_STATE_SET 1274 */ 1275 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1276 /** 1277 * Indicates the view is pressed, focused and selected. 1278 * 1279 * @see #PRESSED_STATE_SET 1280 * @see #SELECTED_STATE_SET 1281 * @see #FOCUSED_STATE_SET 1282 */ 1283 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1284 /** 1285 * Indicates the view is pressed, focused, selected and its window has the focus. 1286 * 1287 * @see #PRESSED_STATE_SET 1288 * @see #FOCUSED_STATE_SET 1289 * @see #SELECTED_STATE_SET 1290 * @see #WINDOW_FOCUSED_STATE_SET 1291 */ 1292 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1293 /** 1294 * Indicates the view is pressed and enabled. 1295 * 1296 * @see #PRESSED_STATE_SET 1297 * @see #ENABLED_STATE_SET 1298 */ 1299 protected static final int[] PRESSED_ENABLED_STATE_SET; 1300 /** 1301 * Indicates the view is pressed, enabled and its window has the focus. 1302 * 1303 * @see #PRESSED_STATE_SET 1304 * @see #ENABLED_STATE_SET 1305 * @see #WINDOW_FOCUSED_STATE_SET 1306 */ 1307 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1308 /** 1309 * Indicates the view is pressed, enabled and selected. 1310 * 1311 * @see #PRESSED_STATE_SET 1312 * @see #ENABLED_STATE_SET 1313 * @see #SELECTED_STATE_SET 1314 */ 1315 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1316 /** 1317 * Indicates the view is pressed, enabled, selected and its window has the 1318 * focus. 1319 * 1320 * @see #PRESSED_STATE_SET 1321 * @see #ENABLED_STATE_SET 1322 * @see #SELECTED_STATE_SET 1323 * @see #WINDOW_FOCUSED_STATE_SET 1324 */ 1325 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1326 /** 1327 * Indicates the view is pressed, enabled and focused. 1328 * 1329 * @see #PRESSED_STATE_SET 1330 * @see #ENABLED_STATE_SET 1331 * @see #FOCUSED_STATE_SET 1332 */ 1333 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1334 /** 1335 * Indicates the view is pressed, enabled, focused and its window has the 1336 * focus. 1337 * 1338 * @see #PRESSED_STATE_SET 1339 * @see #ENABLED_STATE_SET 1340 * @see #FOCUSED_STATE_SET 1341 * @see #WINDOW_FOCUSED_STATE_SET 1342 */ 1343 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1344 /** 1345 * Indicates the view is pressed, enabled, focused and selected. 1346 * 1347 * @see #PRESSED_STATE_SET 1348 * @see #ENABLED_STATE_SET 1349 * @see #SELECTED_STATE_SET 1350 * @see #FOCUSED_STATE_SET 1351 */ 1352 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1353 /** 1354 * Indicates the view is pressed, enabled, focused, selected and its window 1355 * has the focus. 1356 * 1357 * @see #PRESSED_STATE_SET 1358 * @see #ENABLED_STATE_SET 1359 * @see #SELECTED_STATE_SET 1360 * @see #FOCUSED_STATE_SET 1361 * @see #WINDOW_FOCUSED_STATE_SET 1362 */ 1363 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1364 1365 /** 1366 * The order here is very important to {@link #getDrawableState()} 1367 */ 1368 private static final int[][] VIEW_STATE_SETS; 1369 1370 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1371 static final int VIEW_STATE_SELECTED = 1 << 1; 1372 static final int VIEW_STATE_FOCUSED = 1 << 2; 1373 static final int VIEW_STATE_ENABLED = 1 << 3; 1374 static final int VIEW_STATE_PRESSED = 1 << 4; 1375 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1376 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1377 static final int VIEW_STATE_HOVERED = 1 << 7; 1378 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1379 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1380 1381 static final int[] VIEW_STATE_IDS = new int[] { 1382 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1383 R.attr.state_selected, VIEW_STATE_SELECTED, 1384 R.attr.state_focused, VIEW_STATE_FOCUSED, 1385 R.attr.state_enabled, VIEW_STATE_ENABLED, 1386 R.attr.state_pressed, VIEW_STATE_PRESSED, 1387 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1388 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1389 R.attr.state_hovered, VIEW_STATE_HOVERED, 1390 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1391 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1392 }; 1393 1394 static { 1395 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1396 throw new IllegalStateException( 1397 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1398 } 1399 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1400 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1401 int viewState = R.styleable.ViewDrawableStates[i]; 1402 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1403 if (VIEW_STATE_IDS[j] == viewState) { 1404 orderedIds[i * 2] = viewState; 1405 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1406 } 1407 } 1408 } 1409 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1410 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1411 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1412 int numBits = Integer.bitCount(i); 1413 int[] set = new int[numBits]; 1414 int pos = 0; 1415 for (int j = 0; j < orderedIds.length; j += 2) { 1416 if ((i & orderedIds[j+1]) != 0) { 1417 set[pos++] = orderedIds[j]; 1418 } 1419 } 1420 VIEW_STATE_SETS[i] = set; 1421 } 1422 1423 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1424 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1425 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1426 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1427 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1428 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1429 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1430 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1431 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1432 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1433 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1434 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1435 | VIEW_STATE_FOCUSED]; 1436 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1437 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1438 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1439 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1440 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1441 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1442 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1443 | VIEW_STATE_ENABLED]; 1444 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1445 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1446 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1447 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1448 | VIEW_STATE_ENABLED]; 1449 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1450 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1451 | VIEW_STATE_ENABLED]; 1452 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1453 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1454 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1455 1456 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1457 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1458 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1459 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1460 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1461 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1462 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1463 | VIEW_STATE_PRESSED]; 1464 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1465 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1466 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1467 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1468 | VIEW_STATE_PRESSED]; 1469 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1470 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1471 | VIEW_STATE_PRESSED]; 1472 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1473 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1474 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1475 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1476 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1477 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1478 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1479 | VIEW_STATE_PRESSED]; 1480 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1481 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1482 | VIEW_STATE_PRESSED]; 1483 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1484 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1485 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1486 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1487 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1488 | VIEW_STATE_PRESSED]; 1489 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1490 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1491 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1492 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1493 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1494 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1495 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1496 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1497 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1498 | VIEW_STATE_PRESSED]; 1499 } 1500 1501 /** 1502 * Accessibility event types that are dispatched for text population. 1503 */ 1504 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1505 AccessibilityEvent.TYPE_VIEW_CLICKED 1506 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1507 | AccessibilityEvent.TYPE_VIEW_SELECTED 1508 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1509 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1510 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1511 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1512 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1513 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1514 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1515 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1516 1517 /** 1518 * Temporary Rect currently for use in setBackground(). This will probably 1519 * be extended in the future to hold our own class with more than just 1520 * a Rect. :) 1521 */ 1522 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1523 1524 /** 1525 * Map used to store views' tags. 1526 */ 1527 private SparseArray<Object> mKeyedTags; 1528 1529 /** 1530 * The next available accessibility id. 1531 */ 1532 private static int sNextAccessibilityViewId; 1533 1534 /** 1535 * The animation currently associated with this view. 1536 * @hide 1537 */ 1538 protected Animation mCurrentAnimation = null; 1539 1540 /** 1541 * Width as measured during measure pass. 1542 * {@hide} 1543 */ 1544 @ViewDebug.ExportedProperty(category = "measurement") 1545 int mMeasuredWidth; 1546 1547 /** 1548 * Height as measured during measure pass. 1549 * {@hide} 1550 */ 1551 @ViewDebug.ExportedProperty(category = "measurement") 1552 int mMeasuredHeight; 1553 1554 /** 1555 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1556 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1557 * its display list. This flag, used only when hw accelerated, allows us to clear the 1558 * flag while retaining this information until it's needed (at getDisplayList() time and 1559 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1560 * 1561 * {@hide} 1562 */ 1563 boolean mRecreateDisplayList = false; 1564 1565 /** 1566 * The view's identifier. 1567 * {@hide} 1568 * 1569 * @see #setId(int) 1570 * @see #getId() 1571 */ 1572 @ViewDebug.ExportedProperty(resolveId = true) 1573 int mID = NO_ID; 1574 1575 /** 1576 * The stable ID of this view for accessibility purposes. 1577 */ 1578 int mAccessibilityViewId = NO_ID; 1579 1580 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1581 1582 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1583 1584 /** 1585 * The view's tag. 1586 * {@hide} 1587 * 1588 * @see #setTag(Object) 1589 * @see #getTag() 1590 */ 1591 protected Object mTag; 1592 1593 // for mPrivateFlags: 1594 /** {@hide} */ 1595 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1596 /** {@hide} */ 1597 static final int PFLAG_FOCUSED = 0x00000002; 1598 /** {@hide} */ 1599 static final int PFLAG_SELECTED = 0x00000004; 1600 /** {@hide} */ 1601 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1602 /** {@hide} */ 1603 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1604 /** {@hide} */ 1605 static final int PFLAG_DRAWN = 0x00000020; 1606 /** 1607 * When this flag is set, this view is running an animation on behalf of its 1608 * children and should therefore not cancel invalidate requests, even if they 1609 * lie outside of this view's bounds. 1610 * 1611 * {@hide} 1612 */ 1613 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1614 /** {@hide} */ 1615 static final int PFLAG_SKIP_DRAW = 0x00000080; 1616 /** {@hide} */ 1617 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1618 /** {@hide} */ 1619 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1620 /** {@hide} */ 1621 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1622 /** {@hide} */ 1623 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1624 /** {@hide} */ 1625 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1626 /** {@hide} */ 1627 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1628 1629 private static final int PFLAG_PRESSED = 0x00004000; 1630 1631 /** {@hide} */ 1632 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1633 /** 1634 * Flag used to indicate that this view should be drawn once more (and only once 1635 * more) after its animation has completed. 1636 * {@hide} 1637 */ 1638 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1639 1640 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1641 1642 /** 1643 * Indicates that the View returned true when onSetAlpha() was called and that 1644 * the alpha must be restored. 1645 * {@hide} 1646 */ 1647 static final int PFLAG_ALPHA_SET = 0x00040000; 1648 1649 /** 1650 * Set by {@link #setScrollContainer(boolean)}. 1651 */ 1652 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1653 1654 /** 1655 * Set by {@link #setScrollContainer(boolean)}. 1656 */ 1657 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1658 1659 /** 1660 * View flag indicating whether this view was invalidated (fully or partially.) 1661 * 1662 * @hide 1663 */ 1664 static final int PFLAG_DIRTY = 0x00200000; 1665 1666 /** 1667 * View flag indicating whether this view was invalidated by an opaque 1668 * invalidate request. 1669 * 1670 * @hide 1671 */ 1672 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1673 1674 /** 1675 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1676 * 1677 * @hide 1678 */ 1679 static final int PFLAG_DIRTY_MASK = 0x00600000; 1680 1681 /** 1682 * Indicates whether the background is opaque. 1683 * 1684 * @hide 1685 */ 1686 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1687 1688 /** 1689 * Indicates whether the scrollbars are opaque. 1690 * 1691 * @hide 1692 */ 1693 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1694 1695 /** 1696 * Indicates whether the view is opaque. 1697 * 1698 * @hide 1699 */ 1700 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1701 1702 /** 1703 * Indicates a prepressed state; 1704 * the short time between ACTION_DOWN and recognizing 1705 * a 'real' press. Prepressed is used to recognize quick taps 1706 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1707 * 1708 * @hide 1709 */ 1710 private static final int PFLAG_PREPRESSED = 0x02000000; 1711 1712 /** 1713 * Indicates whether the view is temporarily detached. 1714 * 1715 * @hide 1716 */ 1717 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1718 1719 /** 1720 * Indicates that we should awaken scroll bars once attached 1721 * 1722 * @hide 1723 */ 1724 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1725 1726 /** 1727 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1728 * @hide 1729 */ 1730 private static final int PFLAG_HOVERED = 0x10000000; 1731 1732 /** 1733 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1734 * for transform operations 1735 * 1736 * @hide 1737 */ 1738 private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000; 1739 1740 /** {@hide} */ 1741 static final int PFLAG_ACTIVATED = 0x40000000; 1742 1743 /** 1744 * Indicates that this view was specifically invalidated, not just dirtied because some 1745 * child view was invalidated. The flag is used to determine when we need to recreate 1746 * a view's display list (as opposed to just returning a reference to its existing 1747 * display list). 1748 * 1749 * @hide 1750 */ 1751 static final int PFLAG_INVALIDATED = 0x80000000; 1752 1753 /** 1754 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1755 * 1756 * |-------|-------|-------|-------| 1757 * 1 PFLAG2_DRAG_CAN_ACCEPT 1758 * 1 PFLAG2_DRAG_HOVERED 1759 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1760 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1761 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1762 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1763 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1764 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1765 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1766 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1767 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1768 * 111 PFLAG2_TEXT_DIRECTION_MASK 1769 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1770 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1771 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1772 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1773 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1774 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1775 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1776 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1777 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1778 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1779 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1780 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1781 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1782 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1783 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1784 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1785 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1786 * 1 PFLAG2_VIEW_QUICK_REJECTED 1787 * 1 PFLAG2_PADDING_RESOLVED 1788 * 1 PFLAG2_DRAWABLE_RESOLVED 1789 * 1 PFLAG2_HAS_TRANSIENT_STATE 1790 * |-------|-------|-------|-------| 1791 */ 1792 1793 /** 1794 * Indicates that this view has reported that it can accept the current drag's content. 1795 * Cleared when the drag operation concludes. 1796 * @hide 1797 */ 1798 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1799 1800 /** 1801 * Indicates that this view is currently directly under the drag location in a 1802 * drag-and-drop operation involving content that it can accept. Cleared when 1803 * the drag exits the view, or when the drag operation concludes. 1804 * @hide 1805 */ 1806 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1807 1808 /** 1809 * Horizontal layout direction of this view is from Left to Right. 1810 * Use with {@link #setLayoutDirection}. 1811 */ 1812 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1813 1814 /** 1815 * Horizontal layout direction of this view is from Right to Left. 1816 * Use with {@link #setLayoutDirection}. 1817 */ 1818 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1819 1820 /** 1821 * Horizontal layout direction of this view is inherited from its parent. 1822 * Use with {@link #setLayoutDirection}. 1823 */ 1824 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1825 1826 /** 1827 * Horizontal layout direction of this view is from deduced from the default language 1828 * script for the locale. Use with {@link #setLayoutDirection}. 1829 */ 1830 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1831 1832 /** 1833 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1834 * @hide 1835 */ 1836 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1837 1838 /** 1839 * Mask for use with private flags indicating bits used for horizontal layout direction. 1840 * @hide 1841 */ 1842 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1843 1844 /** 1845 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1846 * right-to-left direction. 1847 * @hide 1848 */ 1849 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1850 1851 /** 1852 * Indicates whether the view horizontal layout direction has been resolved. 1853 * @hide 1854 */ 1855 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1856 1857 /** 1858 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1859 * @hide 1860 */ 1861 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1862 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1863 1864 /* 1865 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1866 * flag value. 1867 * @hide 1868 */ 1869 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1870 LAYOUT_DIRECTION_LTR, 1871 LAYOUT_DIRECTION_RTL, 1872 LAYOUT_DIRECTION_INHERIT, 1873 LAYOUT_DIRECTION_LOCALE 1874 }; 1875 1876 /** 1877 * Default horizontal layout direction. 1878 */ 1879 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1880 1881 /** 1882 * Default horizontal layout direction. 1883 * @hide 1884 */ 1885 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1886 1887 /** 1888 * Text direction is inherited thru {@link ViewGroup} 1889 */ 1890 public static final int TEXT_DIRECTION_INHERIT = 0; 1891 1892 /** 1893 * Text direction is using "first strong algorithm". The first strong directional character 1894 * determines the paragraph direction. If there is no strong directional character, the 1895 * paragraph direction is the view's resolved layout direction. 1896 */ 1897 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1898 1899 /** 1900 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1901 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1902 * If there are neither, the paragraph direction is the view's resolved layout direction. 1903 */ 1904 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1905 1906 /** 1907 * Text direction is forced to LTR. 1908 */ 1909 public static final int TEXT_DIRECTION_LTR = 3; 1910 1911 /** 1912 * Text direction is forced to RTL. 1913 */ 1914 public static final int TEXT_DIRECTION_RTL = 4; 1915 1916 /** 1917 * Text direction is coming from the system Locale. 1918 */ 1919 public static final int TEXT_DIRECTION_LOCALE = 5; 1920 1921 /** 1922 * Default text direction is inherited 1923 */ 1924 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 1925 1926 /** 1927 * Default resolved text direction 1928 * @hide 1929 */ 1930 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 1931 1932 /** 1933 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 1934 * @hide 1935 */ 1936 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 1937 1938 /** 1939 * Mask for use with private flags indicating bits used for text direction. 1940 * @hide 1941 */ 1942 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 1943 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1944 1945 /** 1946 * Array of text direction flags for mapping attribute "textDirection" to correct 1947 * flag value. 1948 * @hide 1949 */ 1950 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 1951 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1952 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1953 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1954 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1955 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1956 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 1957 }; 1958 1959 /** 1960 * Indicates whether the view text direction has been resolved. 1961 * @hide 1962 */ 1963 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 1964 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1965 1966 /** 1967 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1968 * @hide 1969 */ 1970 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 1971 1972 /** 1973 * Mask for use with private flags indicating bits used for resolved text direction. 1974 * @hide 1975 */ 1976 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 1977 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1978 1979 /** 1980 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 1981 * @hide 1982 */ 1983 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 1984 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1985 1986 /* 1987 * Default text alignment. The text alignment of this View is inherited from its parent. 1988 * Use with {@link #setTextAlignment(int)} 1989 */ 1990 public static final int TEXT_ALIGNMENT_INHERIT = 0; 1991 1992 /** 1993 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 1994 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraphs text direction. 1995 * 1996 * Use with {@link #setTextAlignment(int)} 1997 */ 1998 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 1999 2000 /** 2001 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2002 * 2003 * Use with {@link #setTextAlignment(int)} 2004 */ 2005 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2006 2007 /** 2008 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2009 * 2010 * Use with {@link #setTextAlignment(int)} 2011 */ 2012 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2013 2014 /** 2015 * Center the paragraph, e.g. ALIGN_CENTER. 2016 * 2017 * Use with {@link #setTextAlignment(int)} 2018 */ 2019 public static final int TEXT_ALIGNMENT_CENTER = 4; 2020 2021 /** 2022 * Align to the start of the view, which is ALIGN_LEFT if the views resolved 2023 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2024 * 2025 * Use with {@link #setTextAlignment(int)} 2026 */ 2027 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2028 2029 /** 2030 * Align to the end of the view, which is ALIGN_RIGHT if the views resolved 2031 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2032 * 2033 * Use with {@link #setTextAlignment(int)} 2034 */ 2035 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2036 2037 /** 2038 * Default text alignment is inherited 2039 */ 2040 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2041 2042 /** 2043 * Default resolved text alignment 2044 * @hide 2045 */ 2046 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2047 2048 /** 2049 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2050 * @hide 2051 */ 2052 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2053 2054 /** 2055 * Mask for use with private flags indicating bits used for text alignment. 2056 * @hide 2057 */ 2058 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2059 2060 /** 2061 * Array of text direction flags for mapping attribute "textAlignment" to correct 2062 * flag value. 2063 * @hide 2064 */ 2065 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2066 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2067 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2068 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2069 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2070 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2071 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2072 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2073 }; 2074 2075 /** 2076 * Indicates whether the view text alignment has been resolved. 2077 * @hide 2078 */ 2079 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2080 2081 /** 2082 * Bit shift to get the resolved text alignment. 2083 * @hide 2084 */ 2085 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2086 2087 /** 2088 * Mask for use with private flags indicating bits used for text alignment. 2089 * @hide 2090 */ 2091 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2092 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2093 2094 /** 2095 * Indicates whether if the view text alignment has been resolved to gravity 2096 */ 2097 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2098 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2099 2100 // Accessiblity constants for mPrivateFlags2 2101 2102 /** 2103 * Shift for the bits in {@link #mPrivateFlags2} related to the 2104 * "importantForAccessibility" attribute. 2105 */ 2106 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2107 2108 /** 2109 * Automatically determine whether a view is important for accessibility. 2110 */ 2111 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2112 2113 /** 2114 * The view is important for accessibility. 2115 */ 2116 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2117 2118 /** 2119 * The view is not important for accessibility. 2120 */ 2121 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2122 2123 /** 2124 * The view is not important for accessibility, nor are any of its 2125 * descendant views. 2126 */ 2127 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2128 2129 /** 2130 * The default whether the view is important for accessibility. 2131 */ 2132 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2133 2134 /** 2135 * Mask for obtainig the bits which specify how to determine 2136 * whether a view is important for accessibility. 2137 */ 2138 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2139 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2140 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2141 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2142 2143 /** 2144 * Shift for the bits in {@link #mPrivateFlags2} related to the 2145 * "accessibilityLiveRegion" attribute. 2146 */ 2147 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2148 2149 /** 2150 * Live region mode specifying that accessibility services should not 2151 * automatically announce changes to this view. This is the default live 2152 * region mode for most views. 2153 * <p> 2154 * Use with {@link #setAccessibilityLiveRegion(int)}. 2155 */ 2156 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2157 2158 /** 2159 * Live region mode specifying that accessibility services should announce 2160 * changes to this view. 2161 * <p> 2162 * Use with {@link #setAccessibilityLiveRegion(int)}. 2163 */ 2164 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2165 2166 /** 2167 * Live region mode specifying that accessibility services should interrupt 2168 * ongoing speech to immediately announce changes to this view. 2169 * <p> 2170 * Use with {@link #setAccessibilityLiveRegion(int)}. 2171 */ 2172 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2173 2174 /** 2175 * The default whether the view is important for accessibility. 2176 */ 2177 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2178 2179 /** 2180 * Mask for obtaining the bits which specify a view's accessibility live 2181 * region mode. 2182 */ 2183 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2184 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2185 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2186 2187 /** 2188 * Flag indicating whether a view has accessibility focus. 2189 */ 2190 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2191 2192 /** 2193 * Flag whether the accessibility state of the subtree rooted at this view changed. 2194 */ 2195 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2196 2197 /** 2198 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2199 * is used to check whether later changes to the view's transform should invalidate the 2200 * view to force the quickReject test to run again. 2201 */ 2202 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2203 2204 /** 2205 * Flag indicating that start/end padding has been resolved into left/right padding 2206 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2207 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2208 * during measurement. In some special cases this is required such as when an adapter-based 2209 * view measures prospective children without attaching them to a window. 2210 */ 2211 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2212 2213 /** 2214 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2215 */ 2216 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2217 2218 /** 2219 * Indicates that the view is tracking some sort of transient state 2220 * that the app should not need to be aware of, but that the framework 2221 * should take special care to preserve. 2222 */ 2223 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2224 2225 /** 2226 * Group of bits indicating that RTL properties resolution is done. 2227 */ 2228 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2229 PFLAG2_TEXT_DIRECTION_RESOLVED | 2230 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2231 PFLAG2_PADDING_RESOLVED | 2232 PFLAG2_DRAWABLE_RESOLVED; 2233 2234 // There are a couple of flags left in mPrivateFlags2 2235 2236 /* End of masks for mPrivateFlags2 */ 2237 2238 /* Masks for mPrivateFlags3 */ 2239 2240 /** 2241 * Flag indicating that view has a transform animation set on it. This is used to track whether 2242 * an animation is cleared between successive frames, in order to tell the associated 2243 * DisplayList to clear its animation matrix. 2244 */ 2245 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2246 2247 /** 2248 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2249 * animation is cleared between successive frames, in order to tell the associated 2250 * DisplayList to restore its alpha value. 2251 */ 2252 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2253 2254 /** 2255 * Flag indicating that the view has been through at least one layout since it 2256 * was last attached to a window. 2257 */ 2258 static final int PFLAG3_IS_LAID_OUT = 0x4; 2259 2260 /** 2261 * Flag indicating that a call to measure() was skipped and should be done 2262 * instead when layout() is invoked. 2263 */ 2264 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2265 2266 /** 2267 * Flag indicating that an overridden method correctly called down to 2268 * the superclass implementation as required by the API spec. 2269 */ 2270 static final int PFLAG3_CALLED_SUPER = 0x10; 2271 2272 2273 /* End of masks for mPrivateFlags3 */ 2274 2275 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2276 2277 /** 2278 * Always allow a user to over-scroll this view, provided it is a 2279 * view that can scroll. 2280 * 2281 * @see #getOverScrollMode() 2282 * @see #setOverScrollMode(int) 2283 */ 2284 public static final int OVER_SCROLL_ALWAYS = 0; 2285 2286 /** 2287 * Allow a user to over-scroll this view only if the content is large 2288 * enough to meaningfully scroll, provided it is a view that can scroll. 2289 * 2290 * @see #getOverScrollMode() 2291 * @see #setOverScrollMode(int) 2292 */ 2293 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2294 2295 /** 2296 * Never allow a user to over-scroll this view. 2297 * 2298 * @see #getOverScrollMode() 2299 * @see #setOverScrollMode(int) 2300 */ 2301 public static final int OVER_SCROLL_NEVER = 2; 2302 2303 /** 2304 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2305 * requested the system UI (status bar) to be visible (the default). 2306 * 2307 * @see #setSystemUiVisibility(int) 2308 */ 2309 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2310 2311 /** 2312 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2313 * system UI to enter an unobtrusive "low profile" mode. 2314 * 2315 * <p>This is for use in games, book readers, video players, or any other 2316 * "immersive" application where the usual system chrome is deemed too distracting. 2317 * 2318 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2319 * 2320 * @see #setSystemUiVisibility(int) 2321 */ 2322 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2323 2324 /** 2325 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2326 * system navigation be temporarily hidden. 2327 * 2328 * <p>This is an even less obtrusive state than that called for by 2329 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2330 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2331 * those to disappear. This is useful (in conjunction with the 2332 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2333 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2334 * window flags) for displaying content using every last pixel on the display. 2335 * 2336 * <p>There is a limitation: because navigation controls are so important, the least user 2337 * interaction will cause them to reappear immediately. When this happens, both 2338 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2339 * so that both elements reappear at the same time. 2340 * 2341 * @see #setSystemUiVisibility(int) 2342 */ 2343 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2344 2345 /** 2346 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2347 * into the normal fullscreen mode so that its content can take over the screen 2348 * while still allowing the user to interact with the application. 2349 * 2350 * <p>This has the same visual effect as 2351 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2352 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2353 * meaning that non-critical screen decorations (such as the status bar) will be 2354 * hidden while the user is in the View's window, focusing the experience on 2355 * that content. Unlike the window flag, if you are using ActionBar in 2356 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2357 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2358 * hide the action bar. 2359 * 2360 * <p>This approach to going fullscreen is best used over the window flag when 2361 * it is a transient state -- that is, the application does this at certain 2362 * points in its user interaction where it wants to allow the user to focus 2363 * on content, but not as a continuous state. For situations where the application 2364 * would like to simply stay full screen the entire time (such as a game that 2365 * wants to take over the screen), the 2366 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2367 * is usually a better approach. The state set here will be removed by the system 2368 * in various situations (such as the user moving to another application) like 2369 * the other system UI states. 2370 * 2371 * <p>When using this flag, the application should provide some easy facility 2372 * for the user to go out of it. A common example would be in an e-book 2373 * reader, where tapping on the screen brings back whatever screen and UI 2374 * decorations that had been hidden while the user was immersed in reading 2375 * the book. 2376 * 2377 * @see #setSystemUiVisibility(int) 2378 */ 2379 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2380 2381 /** 2382 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2383 * flags, we would like a stable view of the content insets given to 2384 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2385 * will always represent the worst case that the application can expect 2386 * as a continuous state. In the stock Android UI this is the space for 2387 * the system bar, nav bar, and status bar, but not more transient elements 2388 * such as an input method. 2389 * 2390 * The stable layout your UI sees is based on the system UI modes you can 2391 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2392 * then you will get a stable layout for changes of the 2393 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2394 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2395 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2396 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2397 * with a stable layout. (Note that you should avoid using 2398 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2399 * 2400 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2401 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2402 * then a hidden status bar will be considered a "stable" state for purposes 2403 * here. This allows your UI to continually hide the status bar, while still 2404 * using the system UI flags to hide the action bar while still retaining 2405 * a stable layout. Note that changing the window fullscreen flag will never 2406 * provide a stable layout for a clean transition. 2407 * 2408 * <p>If you are using ActionBar in 2409 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2410 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2411 * insets it adds to those given to the application. 2412 */ 2413 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2414 2415 /** 2416 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2417 * to be layed out as if it has requested 2418 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2419 * allows it to avoid artifacts when switching in and out of that mode, at 2420 * the expense that some of its user interface may be covered by screen 2421 * decorations when they are shown. You can perform layout of your inner 2422 * UI elements to account for the navigation system UI through the 2423 * {@link #fitSystemWindows(Rect)} method. 2424 */ 2425 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2426 2427 /** 2428 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2429 * to be layed out as if it has requested 2430 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2431 * allows it to avoid artifacts when switching in and out of that mode, at 2432 * the expense that some of its user interface may be covered by screen 2433 * decorations when they are shown. You can perform layout of your inner 2434 * UI elements to account for non-fullscreen system UI through the 2435 * {@link #fitSystemWindows(Rect)} method. 2436 */ 2437 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2438 2439 /** 2440 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2441 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2442 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2443 * user interaction. 2444 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2445 * has an effect when used in combination with that flag.</p> 2446 */ 2447 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2448 2449 /** 2450 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2451 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2452 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2453 * experience while also hiding the system bars. If this flag is not set, 2454 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2455 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2456 * if the user swipes from the top of the screen. 2457 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2458 * system gestures, such as swiping from the top of the screen. These transient system bars 2459 * will overlay apps content, may have some degree of transparency, and will automatically 2460 * hide after a short timeout. 2461 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2462 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2463 * with one or both of those flags.</p> 2464 */ 2465 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2466 2467 /** 2468 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2469 */ 2470 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2471 2472 /** 2473 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2474 */ 2475 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2476 2477 /** 2478 * @hide 2479 * 2480 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2481 * out of the public fields to keep the undefined bits out of the developer's way. 2482 * 2483 * Flag to make the status bar not expandable. Unless you also 2484 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2485 */ 2486 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2487 2488 /** 2489 * @hide 2490 * 2491 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2492 * out of the public fields to keep the undefined bits out of the developer's way. 2493 * 2494 * Flag to hide notification icons and scrolling ticker text. 2495 */ 2496 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2497 2498 /** 2499 * @hide 2500 * 2501 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2502 * out of the public fields to keep the undefined bits out of the developer's way. 2503 * 2504 * Flag to disable incoming notification alerts. This will not block 2505 * icons, but it will block sound, vibrating and other visual or aural notifications. 2506 */ 2507 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2508 2509 /** 2510 * @hide 2511 * 2512 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2513 * out of the public fields to keep the undefined bits out of the developer's way. 2514 * 2515 * Flag to hide only the scrolling ticker. Note that 2516 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2517 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2518 */ 2519 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2520 2521 /** 2522 * @hide 2523 * 2524 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2525 * out of the public fields to keep the undefined bits out of the developer's way. 2526 * 2527 * Flag to hide the center system info area. 2528 */ 2529 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2530 2531 /** 2532 * @hide 2533 * 2534 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2535 * out of the public fields to keep the undefined bits out of the developer's way. 2536 * 2537 * Flag to hide only the home button. Don't use this 2538 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2539 */ 2540 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2541 2542 /** 2543 * @hide 2544 * 2545 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2546 * out of the public fields to keep the undefined bits out of the developer's way. 2547 * 2548 * Flag to hide only the back button. Don't use this 2549 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2550 */ 2551 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2552 2553 /** 2554 * @hide 2555 * 2556 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2557 * out of the public fields to keep the undefined bits out of the developer's way. 2558 * 2559 * Flag to hide only the clock. You might use this if your activity has 2560 * its own clock making the status bar's clock redundant. 2561 */ 2562 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2563 2564 /** 2565 * @hide 2566 * 2567 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2568 * out of the public fields to keep the undefined bits out of the developer's way. 2569 * 2570 * Flag to hide only the recent apps button. Don't use this 2571 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2572 */ 2573 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2574 2575 /** 2576 * @hide 2577 * 2578 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2579 * out of the public fields to keep the undefined bits out of the developer's way. 2580 * 2581 * Flag to disable the global search gesture. Don't use this 2582 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2583 */ 2584 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2585 2586 /** 2587 * @hide 2588 * 2589 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2590 * out of the public fields to keep the undefined bits out of the developer's way. 2591 * 2592 * Flag to specify that the status bar is displayed in transient mode. 2593 */ 2594 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2595 2596 /** 2597 * @hide 2598 * 2599 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2600 * out of the public fields to keep the undefined bits out of the developer's way. 2601 * 2602 * Flag to specify that the navigation bar is displayed in transient mode. 2603 */ 2604 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 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 specify that the hidden status bar would like to be shown. 2613 */ 2614 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2615 2616 /** 2617 * @hide 2618 * 2619 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2620 * out of the public fields to keep the undefined bits out of the developer's way. 2621 * 2622 * Flag to specify that the hidden navigation bar would like to be shown. 2623 */ 2624 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2625 2626 /** 2627 * @hide 2628 * 2629 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2630 * out of the public fields to keep the undefined bits out of the developer's way. 2631 * 2632 * Flag to specify that the status bar is displayed in translucent mode. 2633 */ 2634 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2635 2636 /** 2637 * @hide 2638 * 2639 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2640 * out of the public fields to keep the undefined bits out of the developer's way. 2641 * 2642 * Flag to specify that the navigation bar is displayed in translucent mode. 2643 */ 2644 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2645 2646 /** 2647 * @hide 2648 */ 2649 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2650 2651 /** 2652 * These are the system UI flags that can be cleared by events outside 2653 * of an application. Currently this is just the ability to tap on the 2654 * screen while hiding the navigation bar to have it return. 2655 * @hide 2656 */ 2657 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2658 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2659 | SYSTEM_UI_FLAG_FULLSCREEN; 2660 2661 /** 2662 * Flags that can impact the layout in relation to system UI. 2663 */ 2664 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2665 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2666 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2667 2668 /** 2669 * Find views that render the specified text. 2670 * 2671 * @see #findViewsWithText(ArrayList, CharSequence, int) 2672 */ 2673 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2674 2675 /** 2676 * Find find views that contain the specified content description. 2677 * 2678 * @see #findViewsWithText(ArrayList, CharSequence, int) 2679 */ 2680 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2681 2682 /** 2683 * Find views that contain {@link AccessibilityNodeProvider}. Such 2684 * a View is a root of virtual view hierarchy and may contain the searched 2685 * text. If this flag is set Views with providers are automatically 2686 * added and it is a responsibility of the client to call the APIs of 2687 * the provider to determine whether the virtual tree rooted at this View 2688 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2689 * represeting the virtual views with this text. 2690 * 2691 * @see #findViewsWithText(ArrayList, CharSequence, int) 2692 * 2693 * @hide 2694 */ 2695 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2696 2697 /** 2698 * The undefined cursor position. 2699 * 2700 * @hide 2701 */ 2702 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2703 2704 /** 2705 * Indicates that the screen has changed state and is now off. 2706 * 2707 * @see #onScreenStateChanged(int) 2708 */ 2709 public static final int SCREEN_STATE_OFF = 0x0; 2710 2711 /** 2712 * Indicates that the screen has changed state and is now on. 2713 * 2714 * @see #onScreenStateChanged(int) 2715 */ 2716 public static final int SCREEN_STATE_ON = 0x1; 2717 2718 /** 2719 * Controls the over-scroll mode for this view. 2720 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2721 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2722 * and {@link #OVER_SCROLL_NEVER}. 2723 */ 2724 private int mOverScrollMode; 2725 2726 /** 2727 * The parent this view is attached to. 2728 * {@hide} 2729 * 2730 * @see #getParent() 2731 */ 2732 protected ViewParent mParent; 2733 2734 /** 2735 * {@hide} 2736 */ 2737 AttachInfo mAttachInfo; 2738 2739 /** 2740 * {@hide} 2741 */ 2742 @ViewDebug.ExportedProperty(flagMapping = { 2743 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2744 name = "FORCE_LAYOUT"), 2745 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2746 name = "LAYOUT_REQUIRED"), 2747 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2748 name = "DRAWING_CACHE_INVALID", outputIf = false), 2749 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2750 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2751 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2752 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2753 }) 2754 int mPrivateFlags; 2755 int mPrivateFlags2; 2756 int mPrivateFlags3; 2757 2758 /** 2759 * This view's request for the visibility of the status bar. 2760 * @hide 2761 */ 2762 @ViewDebug.ExportedProperty(flagMapping = { 2763 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2764 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2765 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2766 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2767 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2768 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2769 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2770 equals = SYSTEM_UI_FLAG_VISIBLE, 2771 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2772 }) 2773 int mSystemUiVisibility; 2774 2775 /** 2776 * Reference count for transient state. 2777 * @see #setHasTransientState(boolean) 2778 */ 2779 int mTransientStateCount = 0; 2780 2781 /** 2782 * Count of how many windows this view has been attached to. 2783 */ 2784 int mWindowAttachCount; 2785 2786 /** 2787 * The layout parameters associated with this view and used by the parent 2788 * {@link android.view.ViewGroup} to determine how this view should be 2789 * laid out. 2790 * {@hide} 2791 */ 2792 protected ViewGroup.LayoutParams mLayoutParams; 2793 2794 /** 2795 * The view flags hold various views states. 2796 * {@hide} 2797 */ 2798 @ViewDebug.ExportedProperty 2799 int mViewFlags; 2800 2801 static class TransformationInfo { 2802 /** 2803 * The transform matrix for the View. This transform is calculated internally 2804 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2805 * is used by default. Do *not* use this variable directly; instead call 2806 * getMatrix(), which will automatically recalculate the matrix if necessary 2807 * to get the correct matrix based on the latest rotation and scale properties. 2808 */ 2809 private final Matrix mMatrix = new Matrix(); 2810 2811 /** 2812 * The transform matrix for the View. This transform is calculated internally 2813 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2814 * is used by default. Do *not* use this variable directly; instead call 2815 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2816 * to get the correct matrix based on the latest rotation and scale properties. 2817 */ 2818 private Matrix mInverseMatrix; 2819 2820 /** 2821 * An internal variable that tracks whether we need to recalculate the 2822 * transform matrix, based on whether the rotation or scaleX/Y properties 2823 * have changed since the matrix was last calculated. 2824 */ 2825 boolean mMatrixDirty = false; 2826 2827 /** 2828 * An internal variable that tracks whether we need to recalculate the 2829 * transform matrix, based on whether the rotation or scaleX/Y properties 2830 * have changed since the matrix was last calculated. 2831 */ 2832 private boolean mInverseMatrixDirty = true; 2833 2834 /** 2835 * A variable that tracks whether we need to recalculate the 2836 * transform matrix, based on whether the rotation or scaleX/Y properties 2837 * have changed since the matrix was last calculated. This variable 2838 * is only valid after a call to updateMatrix() or to a function that 2839 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2840 */ 2841 private boolean mMatrixIsIdentity = true; 2842 2843 /** 2844 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2845 */ 2846 private Camera mCamera = null; 2847 2848 /** 2849 * This matrix is used when computing the matrix for 3D rotations. 2850 */ 2851 private Matrix matrix3D = null; 2852 2853 /** 2854 * These prev values are used to recalculate a centered pivot point when necessary. The 2855 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2856 * set), so thes values are only used then as well. 2857 */ 2858 private int mPrevWidth = -1; 2859 private int mPrevHeight = -1; 2860 2861 /** 2862 * The degrees rotation around the vertical axis through the pivot point. 2863 */ 2864 @ViewDebug.ExportedProperty 2865 float mRotationY = 0f; 2866 2867 /** 2868 * The degrees rotation around the horizontal axis through the pivot point. 2869 */ 2870 @ViewDebug.ExportedProperty 2871 float mRotationX = 0f; 2872 2873 /** 2874 * The degrees rotation around the pivot point. 2875 */ 2876 @ViewDebug.ExportedProperty 2877 float mRotation = 0f; 2878 2879 /** 2880 * The amount of translation of the object away from its left property (post-layout). 2881 */ 2882 @ViewDebug.ExportedProperty 2883 float mTranslationX = 0f; 2884 2885 /** 2886 * The amount of translation of the object away from its top property (post-layout). 2887 */ 2888 @ViewDebug.ExportedProperty 2889 float mTranslationY = 0f; 2890 2891 /** 2892 * The amount of scale in the x direction around the pivot point. A 2893 * value of 1 means no scaling is applied. 2894 */ 2895 @ViewDebug.ExportedProperty 2896 float mScaleX = 1f; 2897 2898 /** 2899 * The amount of scale in the y direction around the pivot point. A 2900 * value of 1 means no scaling is applied. 2901 */ 2902 @ViewDebug.ExportedProperty 2903 float mScaleY = 1f; 2904 2905 /** 2906 * The x location of the point around which the view is rotated and scaled. 2907 */ 2908 @ViewDebug.ExportedProperty 2909 float mPivotX = 0f; 2910 2911 /** 2912 * The y location of the point around which the view is rotated and scaled. 2913 */ 2914 @ViewDebug.ExportedProperty 2915 float mPivotY = 0f; 2916 2917 /** 2918 * The opacity of the View. This is a value from 0 to 1, where 0 means 2919 * completely transparent and 1 means completely opaque. 2920 */ 2921 @ViewDebug.ExportedProperty 2922 float mAlpha = 1f; 2923 2924 /** 2925 * The opacity of the view as manipulated by the Fade transition. This is a hidden 2926 * property only used by transitions, which is composited with the other alpha 2927 * values to calculate the final visual alpha value. 2928 */ 2929 float mTransitionAlpha = 1f; 2930 } 2931 2932 TransformationInfo mTransformationInfo; 2933 2934 /** 2935 * Current clip bounds. to which all drawing of this view are constrained. 2936 */ 2937 private Rect mClipBounds = null; 2938 2939 private boolean mLastIsOpaque; 2940 2941 /** 2942 * Convenience value to check for float values that are close enough to zero to be considered 2943 * zero. 2944 */ 2945 private static final float NONZERO_EPSILON = .001f; 2946 2947 /** 2948 * The distance in pixels from the left edge of this view's parent 2949 * to the left edge of this view. 2950 * {@hide} 2951 */ 2952 @ViewDebug.ExportedProperty(category = "layout") 2953 protected int mLeft; 2954 /** 2955 * The distance in pixels from the left edge of this view's parent 2956 * to the right edge of this view. 2957 * {@hide} 2958 */ 2959 @ViewDebug.ExportedProperty(category = "layout") 2960 protected int mRight; 2961 /** 2962 * The distance in pixels from the top edge of this view's parent 2963 * to the top edge of this view. 2964 * {@hide} 2965 */ 2966 @ViewDebug.ExportedProperty(category = "layout") 2967 protected int mTop; 2968 /** 2969 * The distance in pixels from the top edge of this view's parent 2970 * to the bottom edge of this view. 2971 * {@hide} 2972 */ 2973 @ViewDebug.ExportedProperty(category = "layout") 2974 protected int mBottom; 2975 2976 /** 2977 * The offset, in pixels, by which the content of this view is scrolled 2978 * horizontally. 2979 * {@hide} 2980 */ 2981 @ViewDebug.ExportedProperty(category = "scrolling") 2982 protected int mScrollX; 2983 /** 2984 * The offset, in pixels, by which the content of this view is scrolled 2985 * vertically. 2986 * {@hide} 2987 */ 2988 @ViewDebug.ExportedProperty(category = "scrolling") 2989 protected int mScrollY; 2990 2991 /** 2992 * The left padding in pixels, that is the distance in pixels between the 2993 * left edge of this view and the left edge of its content. 2994 * {@hide} 2995 */ 2996 @ViewDebug.ExportedProperty(category = "padding") 2997 protected int mPaddingLeft = 0; 2998 /** 2999 * The right padding in pixels, that is the distance in pixels between the 3000 * right edge of this view and the right edge of its content. 3001 * {@hide} 3002 */ 3003 @ViewDebug.ExportedProperty(category = "padding") 3004 protected int mPaddingRight = 0; 3005 /** 3006 * The top padding in pixels, that is the distance in pixels between the 3007 * top edge of this view and the top edge of its content. 3008 * {@hide} 3009 */ 3010 @ViewDebug.ExportedProperty(category = "padding") 3011 protected int mPaddingTop; 3012 /** 3013 * The bottom padding in pixels, that is the distance in pixels between the 3014 * bottom edge of this view and the bottom edge of its content. 3015 * {@hide} 3016 */ 3017 @ViewDebug.ExportedProperty(category = "padding") 3018 protected int mPaddingBottom; 3019 3020 /** 3021 * The layout insets in pixels, that is the distance in pixels between the 3022 * visible edges of this view its bounds. 3023 */ 3024 private Insets mLayoutInsets; 3025 3026 /** 3027 * Briefly describes the view and is primarily used for accessibility support. 3028 */ 3029 private CharSequence mContentDescription; 3030 3031 /** 3032 * Specifies the id of a view for which this view serves as a label for 3033 * accessibility purposes. 3034 */ 3035 private int mLabelForId = View.NO_ID; 3036 3037 /** 3038 * Predicate for matching labeled view id with its label for 3039 * accessibility purposes. 3040 */ 3041 private MatchLabelForPredicate mMatchLabelForPredicate; 3042 3043 /** 3044 * Predicate for matching a view by its id. 3045 */ 3046 private MatchIdPredicate mMatchIdPredicate; 3047 3048 /** 3049 * Cache the paddingRight set by the user to append to the scrollbar's size. 3050 * 3051 * @hide 3052 */ 3053 @ViewDebug.ExportedProperty(category = "padding") 3054 protected int mUserPaddingRight; 3055 3056 /** 3057 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3058 * 3059 * @hide 3060 */ 3061 @ViewDebug.ExportedProperty(category = "padding") 3062 protected int mUserPaddingBottom; 3063 3064 /** 3065 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3066 * 3067 * @hide 3068 */ 3069 @ViewDebug.ExportedProperty(category = "padding") 3070 protected int mUserPaddingLeft; 3071 3072 /** 3073 * Cache the paddingStart set by the user to append to the scrollbar's size. 3074 * 3075 */ 3076 @ViewDebug.ExportedProperty(category = "padding") 3077 int mUserPaddingStart; 3078 3079 /** 3080 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3081 * 3082 */ 3083 @ViewDebug.ExportedProperty(category = "padding") 3084 int mUserPaddingEnd; 3085 3086 /** 3087 * Cache initial left padding. 3088 * 3089 * @hide 3090 */ 3091 int mUserPaddingLeftInitial; 3092 3093 /** 3094 * Cache initial right padding. 3095 * 3096 * @hide 3097 */ 3098 int mUserPaddingRightInitial; 3099 3100 /** 3101 * Default undefined padding 3102 */ 3103 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3104 3105 /** 3106 * @hide 3107 */ 3108 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3109 /** 3110 * @hide 3111 */ 3112 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3113 3114 private LongSparseLongArray mMeasureCache; 3115 3116 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3117 private Drawable mBackground; 3118 3119 private int mBackgroundResource; 3120 private boolean mBackgroundSizeChanged; 3121 3122 static class ListenerInfo { 3123 /** 3124 * Listener used to dispatch focus change events. 3125 * This field should be made private, so it is hidden from the SDK. 3126 * {@hide} 3127 */ 3128 protected OnFocusChangeListener mOnFocusChangeListener; 3129 3130 /** 3131 * Listeners for layout change events. 3132 */ 3133 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3134 3135 /** 3136 * Listeners for attach events. 3137 */ 3138 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3139 3140 /** 3141 * Listener used to dispatch click events. 3142 * This field should be made private, so it is hidden from the SDK. 3143 * {@hide} 3144 */ 3145 public OnClickListener mOnClickListener; 3146 3147 /** 3148 * Listener used to dispatch long click events. 3149 * This field should be made private, so it is hidden from the SDK. 3150 * {@hide} 3151 */ 3152 protected OnLongClickListener mOnLongClickListener; 3153 3154 /** 3155 * Listener used to build the context menu. 3156 * This field should be made private, so it is hidden from the SDK. 3157 * {@hide} 3158 */ 3159 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3160 3161 private OnKeyListener mOnKeyListener; 3162 3163 private OnTouchListener mOnTouchListener; 3164 3165 private OnHoverListener mOnHoverListener; 3166 3167 private OnGenericMotionListener mOnGenericMotionListener; 3168 3169 private OnDragListener mOnDragListener; 3170 3171 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3172 } 3173 3174 ListenerInfo mListenerInfo; 3175 3176 /** 3177 * The application environment this view lives in. 3178 * This field should be made private, so it is hidden from the SDK. 3179 * {@hide} 3180 */ 3181 protected Context mContext; 3182 3183 private final Resources mResources; 3184 3185 private ScrollabilityCache mScrollCache; 3186 3187 private int[] mDrawableState = null; 3188 3189 /** 3190 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3191 * the user may specify which view to go to next. 3192 */ 3193 private int mNextFocusLeftId = View.NO_ID; 3194 3195 /** 3196 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3197 * the user may specify which view to go to next. 3198 */ 3199 private int mNextFocusRightId = View.NO_ID; 3200 3201 /** 3202 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3203 * the user may specify which view to go to next. 3204 */ 3205 private int mNextFocusUpId = View.NO_ID; 3206 3207 /** 3208 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3209 * the user may specify which view to go to next. 3210 */ 3211 private int mNextFocusDownId = View.NO_ID; 3212 3213 /** 3214 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3215 * the user may specify which view to go to next. 3216 */ 3217 int mNextFocusForwardId = View.NO_ID; 3218 3219 private CheckForLongPress mPendingCheckForLongPress; 3220 private CheckForTap mPendingCheckForTap = null; 3221 private PerformClick mPerformClick; 3222 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3223 3224 private UnsetPressedState mUnsetPressedState; 3225 3226 /** 3227 * Whether the long press's action has been invoked. The tap's action is invoked on the 3228 * up event while a long press is invoked as soon as the long press duration is reached, so 3229 * a long press could be performed before the tap is checked, in which case the tap's action 3230 * should not be invoked. 3231 */ 3232 private boolean mHasPerformedLongPress; 3233 3234 /** 3235 * The minimum height of the view. We'll try our best to have the height 3236 * of this view to at least this amount. 3237 */ 3238 @ViewDebug.ExportedProperty(category = "measurement") 3239 private int mMinHeight; 3240 3241 /** 3242 * The minimum width of the view. We'll try our best to have the width 3243 * of this view to at least this amount. 3244 */ 3245 @ViewDebug.ExportedProperty(category = "measurement") 3246 private int mMinWidth; 3247 3248 /** 3249 * The delegate to handle touch events that are physically in this view 3250 * but should be handled by another view. 3251 */ 3252 private TouchDelegate mTouchDelegate = null; 3253 3254 /** 3255 * Solid color to use as a background when creating the drawing cache. Enables 3256 * the cache to use 16 bit bitmaps instead of 32 bit. 3257 */ 3258 private int mDrawingCacheBackgroundColor = 0; 3259 3260 /** 3261 * Special tree observer used when mAttachInfo is null. 3262 */ 3263 private ViewTreeObserver mFloatingTreeObserver; 3264 3265 /** 3266 * Cache the touch slop from the context that created the view. 3267 */ 3268 private int mTouchSlop; 3269 3270 /** 3271 * Object that handles automatic animation of view properties. 3272 */ 3273 private ViewPropertyAnimator mAnimator = null; 3274 3275 /** 3276 * Flag indicating that a drag can cross window boundaries. When 3277 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3278 * with this flag set, all visible applications will be able to participate 3279 * in the drag operation and receive the dragged content. 3280 * 3281 * @hide 3282 */ 3283 public static final int DRAG_FLAG_GLOBAL = 1; 3284 3285 /** 3286 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3287 */ 3288 private float mVerticalScrollFactor; 3289 3290 /** 3291 * Position of the vertical scroll bar. 3292 */ 3293 private int mVerticalScrollbarPosition; 3294 3295 /** 3296 * Position the scroll bar at the default position as determined by the system. 3297 */ 3298 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3299 3300 /** 3301 * Position the scroll bar along the left edge. 3302 */ 3303 public static final int SCROLLBAR_POSITION_LEFT = 1; 3304 3305 /** 3306 * Position the scroll bar along the right edge. 3307 */ 3308 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3309 3310 /** 3311 * Indicates that the view does not have a layer. 3312 * 3313 * @see #getLayerType() 3314 * @see #setLayerType(int, android.graphics.Paint) 3315 * @see #LAYER_TYPE_SOFTWARE 3316 * @see #LAYER_TYPE_HARDWARE 3317 */ 3318 public static final int LAYER_TYPE_NONE = 0; 3319 3320 /** 3321 * <p>Indicates that the view has a software layer. A software layer is backed 3322 * by a bitmap and causes the view to be rendered using Android's software 3323 * rendering pipeline, even if hardware acceleration is enabled.</p> 3324 * 3325 * <p>Software layers have various usages:</p> 3326 * <p>When the application is not using hardware acceleration, a software layer 3327 * is useful to apply a specific color filter and/or blending mode and/or 3328 * translucency to a view and all its children.</p> 3329 * <p>When the application is using hardware acceleration, a software layer 3330 * is useful to render drawing primitives not supported by the hardware 3331 * accelerated pipeline. It can also be used to cache a complex view tree 3332 * into a texture and reduce the complexity of drawing operations. For instance, 3333 * when animating a complex view tree with a translation, a software layer can 3334 * be used to render the view tree only once.</p> 3335 * <p>Software layers should be avoided when the affected view tree updates 3336 * often. Every update will require to re-render the software layer, which can 3337 * potentially be slow (particularly when hardware acceleration is turned on 3338 * since the layer will have to be uploaded into a hardware texture after every 3339 * update.)</p> 3340 * 3341 * @see #getLayerType() 3342 * @see #setLayerType(int, android.graphics.Paint) 3343 * @see #LAYER_TYPE_NONE 3344 * @see #LAYER_TYPE_HARDWARE 3345 */ 3346 public static final int LAYER_TYPE_SOFTWARE = 1; 3347 3348 /** 3349 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3350 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3351 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3352 * rendering pipeline, but only if hardware acceleration is turned on for the 3353 * view hierarchy. When hardware acceleration is turned off, hardware layers 3354 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3355 * 3356 * <p>A hardware layer is useful to apply a specific color filter and/or 3357 * blending mode and/or translucency to a view and all its children.</p> 3358 * <p>A hardware layer can be used to cache a complex view tree into a 3359 * texture and reduce the complexity of drawing operations. For instance, 3360 * when animating a complex view tree with a translation, a hardware layer can 3361 * be used to render the view tree only once.</p> 3362 * <p>A hardware layer can also be used to increase the rendering quality when 3363 * rotation transformations are applied on a view. It can also be used to 3364 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3365 * 3366 * @see #getLayerType() 3367 * @see #setLayerType(int, android.graphics.Paint) 3368 * @see #LAYER_TYPE_NONE 3369 * @see #LAYER_TYPE_SOFTWARE 3370 */ 3371 public static final int LAYER_TYPE_HARDWARE = 2; 3372 3373 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3374 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3375 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3376 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3377 }) 3378 int mLayerType = LAYER_TYPE_NONE; 3379 Paint mLayerPaint; 3380 Rect mLocalDirtyRect; 3381 private HardwareLayer mHardwareLayer; 3382 3383 /** 3384 * Set to true when drawing cache is enabled and cannot be created. 3385 * 3386 * @hide 3387 */ 3388 public boolean mCachingFailed; 3389 private Bitmap mDrawingCache; 3390 private Bitmap mUnscaledDrawingCache; 3391 3392 DisplayList mDisplayList; 3393 3394 /** 3395 * Set to true when the view is sending hover accessibility events because it 3396 * is the innermost hovered view. 3397 */ 3398 private boolean mSendingHoverAccessibilityEvents; 3399 3400 /** 3401 * Delegate for injecting accessibility functionality. 3402 */ 3403 AccessibilityDelegate mAccessibilityDelegate; 3404 3405 /** 3406 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3407 * and add/remove objects to/from the overlay directly through the Overlay methods. 3408 */ 3409 ViewOverlay mOverlay; 3410 3411 /** 3412 * Consistency verifier for debugging purposes. 3413 * @hide 3414 */ 3415 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3416 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3417 new InputEventConsistencyVerifier(this, 0) : null; 3418 3419 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3420 3421 /** 3422 * Simple constructor to use when creating a view from code. 3423 * 3424 * @param context The Context the view is running in, through which it can 3425 * access the current theme, resources, etc. 3426 */ 3427 public View(Context context) { 3428 mContext = context; 3429 mResources = context != null ? context.getResources() : null; 3430 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3431 // Set some flags defaults 3432 mPrivateFlags2 = 3433 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3434 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3435 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3436 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3437 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3438 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3439 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3440 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3441 mUserPaddingStart = UNDEFINED_PADDING; 3442 mUserPaddingEnd = UNDEFINED_PADDING; 3443 3444 if (!sCompatibilityDone && context != null) { 3445 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3446 3447 // Older apps may need this compatibility hack for measurement. 3448 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3449 3450 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3451 // of whether a layout was requested on that View. 3452 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3453 3454 sCompatibilityDone = true; 3455 } 3456 } 3457 3458 /** 3459 * Constructor that is called when inflating a view from XML. This is called 3460 * when a view is being constructed from an XML file, supplying attributes 3461 * that were specified in the XML file. This version uses a default style of 3462 * 0, so the only attribute values applied are those in the Context's Theme 3463 * and the given AttributeSet. 3464 * 3465 * <p> 3466 * The method onFinishInflate() will be called after all children have been 3467 * added. 3468 * 3469 * @param context The Context the view is running in, through which it can 3470 * access the current theme, resources, etc. 3471 * @param attrs The attributes of the XML tag that is inflating the view. 3472 * @see #View(Context, AttributeSet, int) 3473 */ 3474 public View(Context context, AttributeSet attrs) { 3475 this(context, attrs, 0); 3476 } 3477 3478 /** 3479 * Perform inflation from XML and apply a class-specific base style. This 3480 * constructor of View allows subclasses to use their own base style when 3481 * they are inflating. For example, a Button class's constructor would call 3482 * this version of the super class constructor and supply 3483 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 3484 * the theme's button style to modify all of the base view attributes (in 3485 * particular its background) as well as the Button class's attributes. 3486 * 3487 * @param context The Context the view is running in, through which it can 3488 * access the current theme, resources, etc. 3489 * @param attrs The attributes of the XML tag that is inflating the view. 3490 * @param defStyleAttr An attribute in the current theme that contains a 3491 * reference to a style resource to apply to this view. If 0, no 3492 * default style will be applied. 3493 * @see #View(Context, AttributeSet) 3494 */ 3495 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3496 this(context); 3497 3498 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 3499 defStyleAttr, 0); 3500 3501 Drawable background = null; 3502 3503 int leftPadding = -1; 3504 int topPadding = -1; 3505 int rightPadding = -1; 3506 int bottomPadding = -1; 3507 int startPadding = UNDEFINED_PADDING; 3508 int endPadding = UNDEFINED_PADDING; 3509 3510 int padding = -1; 3511 3512 int viewFlagValues = 0; 3513 int viewFlagMasks = 0; 3514 3515 boolean setScrollContainer = false; 3516 3517 int x = 0; 3518 int y = 0; 3519 3520 float tx = 0; 3521 float ty = 0; 3522 float rotation = 0; 3523 float rotationX = 0; 3524 float rotationY = 0; 3525 float sx = 1f; 3526 float sy = 1f; 3527 boolean transformSet = false; 3528 3529 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3530 int overScrollMode = mOverScrollMode; 3531 boolean initializeScrollbars = false; 3532 3533 boolean leftPaddingDefined = false; 3534 boolean rightPaddingDefined = false; 3535 boolean startPaddingDefined = false; 3536 boolean endPaddingDefined = false; 3537 3538 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3539 3540 final int N = a.getIndexCount(); 3541 for (int i = 0; i < N; i++) { 3542 int attr = a.getIndex(i); 3543 switch (attr) { 3544 case com.android.internal.R.styleable.View_background: 3545 background = a.getDrawable(attr); 3546 break; 3547 case com.android.internal.R.styleable.View_padding: 3548 padding = a.getDimensionPixelSize(attr, -1); 3549 mUserPaddingLeftInitial = padding; 3550 mUserPaddingRightInitial = padding; 3551 leftPaddingDefined = true; 3552 rightPaddingDefined = true; 3553 break; 3554 case com.android.internal.R.styleable.View_paddingLeft: 3555 leftPadding = a.getDimensionPixelSize(attr, -1); 3556 mUserPaddingLeftInitial = leftPadding; 3557 leftPaddingDefined = true; 3558 break; 3559 case com.android.internal.R.styleable.View_paddingTop: 3560 topPadding = a.getDimensionPixelSize(attr, -1); 3561 break; 3562 case com.android.internal.R.styleable.View_paddingRight: 3563 rightPadding = a.getDimensionPixelSize(attr, -1); 3564 mUserPaddingRightInitial = rightPadding; 3565 rightPaddingDefined = true; 3566 break; 3567 case com.android.internal.R.styleable.View_paddingBottom: 3568 bottomPadding = a.getDimensionPixelSize(attr, -1); 3569 break; 3570 case com.android.internal.R.styleable.View_paddingStart: 3571 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3572 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3573 break; 3574 case com.android.internal.R.styleable.View_paddingEnd: 3575 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3576 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3577 break; 3578 case com.android.internal.R.styleable.View_scrollX: 3579 x = a.getDimensionPixelOffset(attr, 0); 3580 break; 3581 case com.android.internal.R.styleable.View_scrollY: 3582 y = a.getDimensionPixelOffset(attr, 0); 3583 break; 3584 case com.android.internal.R.styleable.View_alpha: 3585 setAlpha(a.getFloat(attr, 1f)); 3586 break; 3587 case com.android.internal.R.styleable.View_transformPivotX: 3588 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3589 break; 3590 case com.android.internal.R.styleable.View_transformPivotY: 3591 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3592 break; 3593 case com.android.internal.R.styleable.View_translationX: 3594 tx = a.getDimensionPixelOffset(attr, 0); 3595 transformSet = true; 3596 break; 3597 case com.android.internal.R.styleable.View_translationY: 3598 ty = a.getDimensionPixelOffset(attr, 0); 3599 transformSet = true; 3600 break; 3601 case com.android.internal.R.styleable.View_rotation: 3602 rotation = a.getFloat(attr, 0); 3603 transformSet = true; 3604 break; 3605 case com.android.internal.R.styleable.View_rotationX: 3606 rotationX = a.getFloat(attr, 0); 3607 transformSet = true; 3608 break; 3609 case com.android.internal.R.styleable.View_rotationY: 3610 rotationY = a.getFloat(attr, 0); 3611 transformSet = true; 3612 break; 3613 case com.android.internal.R.styleable.View_scaleX: 3614 sx = a.getFloat(attr, 1f); 3615 transformSet = true; 3616 break; 3617 case com.android.internal.R.styleable.View_scaleY: 3618 sy = a.getFloat(attr, 1f); 3619 transformSet = true; 3620 break; 3621 case com.android.internal.R.styleable.View_id: 3622 mID = a.getResourceId(attr, NO_ID); 3623 break; 3624 case com.android.internal.R.styleable.View_tag: 3625 mTag = a.getText(attr); 3626 break; 3627 case com.android.internal.R.styleable.View_fitsSystemWindows: 3628 if (a.getBoolean(attr, false)) { 3629 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3630 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3631 } 3632 break; 3633 case com.android.internal.R.styleable.View_focusable: 3634 if (a.getBoolean(attr, false)) { 3635 viewFlagValues |= FOCUSABLE; 3636 viewFlagMasks |= FOCUSABLE_MASK; 3637 } 3638 break; 3639 case com.android.internal.R.styleable.View_focusableInTouchMode: 3640 if (a.getBoolean(attr, false)) { 3641 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3642 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3643 } 3644 break; 3645 case com.android.internal.R.styleable.View_clickable: 3646 if (a.getBoolean(attr, false)) { 3647 viewFlagValues |= CLICKABLE; 3648 viewFlagMasks |= CLICKABLE; 3649 } 3650 break; 3651 case com.android.internal.R.styleable.View_longClickable: 3652 if (a.getBoolean(attr, false)) { 3653 viewFlagValues |= LONG_CLICKABLE; 3654 viewFlagMasks |= LONG_CLICKABLE; 3655 } 3656 break; 3657 case com.android.internal.R.styleable.View_saveEnabled: 3658 if (!a.getBoolean(attr, true)) { 3659 viewFlagValues |= SAVE_DISABLED; 3660 viewFlagMasks |= SAVE_DISABLED_MASK; 3661 } 3662 break; 3663 case com.android.internal.R.styleable.View_duplicateParentState: 3664 if (a.getBoolean(attr, false)) { 3665 viewFlagValues |= DUPLICATE_PARENT_STATE; 3666 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3667 } 3668 break; 3669 case com.android.internal.R.styleable.View_visibility: 3670 final int visibility = a.getInt(attr, 0); 3671 if (visibility != 0) { 3672 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3673 viewFlagMasks |= VISIBILITY_MASK; 3674 } 3675 break; 3676 case com.android.internal.R.styleable.View_layoutDirection: 3677 // Clear any layout direction flags (included resolved bits) already set 3678 mPrivateFlags2 &= 3679 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3680 // Set the layout direction flags depending on the value of the attribute 3681 final int layoutDirection = a.getInt(attr, -1); 3682 final int value = (layoutDirection != -1) ? 3683 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3684 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3685 break; 3686 case com.android.internal.R.styleable.View_drawingCacheQuality: 3687 final int cacheQuality = a.getInt(attr, 0); 3688 if (cacheQuality != 0) { 3689 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3690 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3691 } 3692 break; 3693 case com.android.internal.R.styleable.View_contentDescription: 3694 setContentDescription(a.getString(attr)); 3695 break; 3696 case com.android.internal.R.styleable.View_labelFor: 3697 setLabelFor(a.getResourceId(attr, NO_ID)); 3698 break; 3699 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3700 if (!a.getBoolean(attr, true)) { 3701 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3702 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3703 } 3704 break; 3705 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3706 if (!a.getBoolean(attr, true)) { 3707 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3708 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3709 } 3710 break; 3711 case R.styleable.View_scrollbars: 3712 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3713 if (scrollbars != SCROLLBARS_NONE) { 3714 viewFlagValues |= scrollbars; 3715 viewFlagMasks |= SCROLLBARS_MASK; 3716 initializeScrollbars = true; 3717 } 3718 break; 3719 //noinspection deprecation 3720 case R.styleable.View_fadingEdge: 3721 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3722 // Ignore the attribute starting with ICS 3723 break; 3724 } 3725 // With builds < ICS, fall through and apply fading edges 3726 case R.styleable.View_requiresFadingEdge: 3727 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3728 if (fadingEdge != FADING_EDGE_NONE) { 3729 viewFlagValues |= fadingEdge; 3730 viewFlagMasks |= FADING_EDGE_MASK; 3731 initializeFadingEdge(a); 3732 } 3733 break; 3734 case R.styleable.View_scrollbarStyle: 3735 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3736 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3737 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3738 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3739 } 3740 break; 3741 case R.styleable.View_isScrollContainer: 3742 setScrollContainer = true; 3743 if (a.getBoolean(attr, false)) { 3744 setScrollContainer(true); 3745 } 3746 break; 3747 case com.android.internal.R.styleable.View_keepScreenOn: 3748 if (a.getBoolean(attr, false)) { 3749 viewFlagValues |= KEEP_SCREEN_ON; 3750 viewFlagMasks |= KEEP_SCREEN_ON; 3751 } 3752 break; 3753 case R.styleable.View_filterTouchesWhenObscured: 3754 if (a.getBoolean(attr, false)) { 3755 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3756 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3757 } 3758 break; 3759 case R.styleable.View_nextFocusLeft: 3760 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3761 break; 3762 case R.styleable.View_nextFocusRight: 3763 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3764 break; 3765 case R.styleable.View_nextFocusUp: 3766 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3767 break; 3768 case R.styleable.View_nextFocusDown: 3769 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3770 break; 3771 case R.styleable.View_nextFocusForward: 3772 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3773 break; 3774 case R.styleable.View_minWidth: 3775 mMinWidth = a.getDimensionPixelSize(attr, 0); 3776 break; 3777 case R.styleable.View_minHeight: 3778 mMinHeight = a.getDimensionPixelSize(attr, 0); 3779 break; 3780 case R.styleable.View_onClick: 3781 if (context.isRestricted()) { 3782 throw new IllegalStateException("The android:onClick attribute cannot " 3783 + "be used within a restricted context"); 3784 } 3785 3786 final String handlerName = a.getString(attr); 3787 if (handlerName != null) { 3788 setOnClickListener(new OnClickListener() { 3789 private Method mHandler; 3790 3791 public void onClick(View v) { 3792 if (mHandler == null) { 3793 try { 3794 mHandler = getContext().getClass().getMethod(handlerName, 3795 View.class); 3796 } catch (NoSuchMethodException e) { 3797 int id = getId(); 3798 String idText = id == NO_ID ? "" : " with id '" 3799 + getContext().getResources().getResourceEntryName( 3800 id) + "'"; 3801 throw new IllegalStateException("Could not find a method " + 3802 handlerName + "(View) in the activity " 3803 + getContext().getClass() + " for onClick handler" 3804 + " on view " + View.this.getClass() + idText, e); 3805 } 3806 } 3807 3808 try { 3809 mHandler.invoke(getContext(), View.this); 3810 } catch (IllegalAccessException e) { 3811 throw new IllegalStateException("Could not execute non " 3812 + "public method of the activity", e); 3813 } catch (InvocationTargetException e) { 3814 throw new IllegalStateException("Could not execute " 3815 + "method of the activity", e); 3816 } 3817 } 3818 }); 3819 } 3820 break; 3821 case R.styleable.View_overScrollMode: 3822 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3823 break; 3824 case R.styleable.View_verticalScrollbarPosition: 3825 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3826 break; 3827 case R.styleable.View_layerType: 3828 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3829 break; 3830 case R.styleable.View_textDirection: 3831 // Clear any text direction flag already set 3832 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3833 // Set the text direction flags depending on the value of the attribute 3834 final int textDirection = a.getInt(attr, -1); 3835 if (textDirection != -1) { 3836 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3837 } 3838 break; 3839 case R.styleable.View_textAlignment: 3840 // Clear any text alignment flag already set 3841 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3842 // Set the text alignment flag depending on the value of the attribute 3843 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 3844 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 3845 break; 3846 case R.styleable.View_importantForAccessibility: 3847 setImportantForAccessibility(a.getInt(attr, 3848 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 3849 break; 3850 case R.styleable.View_accessibilityLiveRegion: 3851 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 3852 break; 3853 } 3854 } 3855 3856 setOverScrollMode(overScrollMode); 3857 3858 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 3859 // the resolved layout direction). Those cached values will be used later during padding 3860 // resolution. 3861 mUserPaddingStart = startPadding; 3862 mUserPaddingEnd = endPadding; 3863 3864 if (background != null) { 3865 setBackground(background); 3866 } 3867 3868 if (padding >= 0) { 3869 leftPadding = padding; 3870 topPadding = padding; 3871 rightPadding = padding; 3872 bottomPadding = padding; 3873 mUserPaddingLeftInitial = padding; 3874 mUserPaddingRightInitial = padding; 3875 } 3876 3877 if (isRtlCompatibilityMode()) { 3878 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 3879 // left / right padding are used if defined (meaning here nothing to do). If they are not 3880 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 3881 // start / end and resolve them as left / right (layout direction is not taken into account). 3882 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 3883 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 3884 // defined. 3885 if (!leftPaddingDefined && startPaddingDefined) { 3886 leftPadding = startPadding; 3887 } 3888 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 3889 if (!rightPaddingDefined && endPaddingDefined) { 3890 rightPadding = endPadding; 3891 } 3892 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 3893 } else { 3894 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 3895 // values defined. Otherwise, left /right values are used. 3896 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 3897 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 3898 // defined. 3899 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 3900 3901 if (leftPaddingDefined && !hasRelativePadding) { 3902 mUserPaddingLeftInitial = leftPadding; 3903 } 3904 if (rightPaddingDefined && !hasRelativePadding) { 3905 mUserPaddingRightInitial = rightPadding; 3906 } 3907 } 3908 3909 internalSetPadding( 3910 mUserPaddingLeftInitial, 3911 topPadding >= 0 ? topPadding : mPaddingTop, 3912 mUserPaddingRightInitial, 3913 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3914 3915 if (viewFlagMasks != 0) { 3916 setFlags(viewFlagValues, viewFlagMasks); 3917 } 3918 3919 if (initializeScrollbars) { 3920 initializeScrollbars(a); 3921 } 3922 3923 a.recycle(); 3924 3925 // Needs to be called after mViewFlags is set 3926 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3927 recomputePadding(); 3928 } 3929 3930 if (x != 0 || y != 0) { 3931 scrollTo(x, y); 3932 } 3933 3934 if (transformSet) { 3935 setTranslationX(tx); 3936 setTranslationY(ty); 3937 setRotation(rotation); 3938 setRotationX(rotationX); 3939 setRotationY(rotationY); 3940 setScaleX(sx); 3941 setScaleY(sy); 3942 } 3943 3944 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3945 setScrollContainer(true); 3946 } 3947 3948 computeOpaqueFlags(); 3949 } 3950 3951 /** 3952 * Non-public constructor for use in testing 3953 */ 3954 View() { 3955 mResources = null; 3956 } 3957 3958 public String toString() { 3959 StringBuilder out = new StringBuilder(128); 3960 out.append(getClass().getName()); 3961 out.append('{'); 3962 out.append(Integer.toHexString(System.identityHashCode(this))); 3963 out.append(' '); 3964 switch (mViewFlags&VISIBILITY_MASK) { 3965 case VISIBLE: out.append('V'); break; 3966 case INVISIBLE: out.append('I'); break; 3967 case GONE: out.append('G'); break; 3968 default: out.append('.'); break; 3969 } 3970 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 3971 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 3972 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 3973 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 3974 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 3975 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 3976 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 3977 out.append(' '); 3978 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 3979 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 3980 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 3981 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 3982 out.append('p'); 3983 } else { 3984 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 3985 } 3986 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 3987 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 3988 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 3989 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 3990 out.append(' '); 3991 out.append(mLeft); 3992 out.append(','); 3993 out.append(mTop); 3994 out.append('-'); 3995 out.append(mRight); 3996 out.append(','); 3997 out.append(mBottom); 3998 final int id = getId(); 3999 if (id != NO_ID) { 4000 out.append(" #"); 4001 out.append(Integer.toHexString(id)); 4002 final Resources r = mResources; 4003 if (id != 0 && r != null) { 4004 try { 4005 String pkgname; 4006 switch (id&0xff000000) { 4007 case 0x7f000000: 4008 pkgname="app"; 4009 break; 4010 case 0x01000000: 4011 pkgname="android"; 4012 break; 4013 default: 4014 pkgname = r.getResourcePackageName(id); 4015 break; 4016 } 4017 String typename = r.getResourceTypeName(id); 4018 String entryname = r.getResourceEntryName(id); 4019 out.append(" "); 4020 out.append(pkgname); 4021 out.append(":"); 4022 out.append(typename); 4023 out.append("/"); 4024 out.append(entryname); 4025 } catch (Resources.NotFoundException e) { 4026 } 4027 } 4028 } 4029 out.append("}"); 4030 return out.toString(); 4031 } 4032 4033 /** 4034 * <p> 4035 * Initializes the fading edges from a given set of styled attributes. This 4036 * method should be called by subclasses that need fading edges and when an 4037 * instance of these subclasses is created programmatically rather than 4038 * being inflated from XML. This method is automatically called when the XML 4039 * is inflated. 4040 * </p> 4041 * 4042 * @param a the styled attributes set to initialize the fading edges from 4043 */ 4044 protected void initializeFadingEdge(TypedArray a) { 4045 initScrollCache(); 4046 4047 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4048 R.styleable.View_fadingEdgeLength, 4049 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4050 } 4051 4052 /** 4053 * Returns the size of the vertical faded edges used to indicate that more 4054 * content in this view is visible. 4055 * 4056 * @return The size in pixels of the vertical faded edge or 0 if vertical 4057 * faded edges are not enabled for this view. 4058 * @attr ref android.R.styleable#View_fadingEdgeLength 4059 */ 4060 public int getVerticalFadingEdgeLength() { 4061 if (isVerticalFadingEdgeEnabled()) { 4062 ScrollabilityCache cache = mScrollCache; 4063 if (cache != null) { 4064 return cache.fadingEdgeLength; 4065 } 4066 } 4067 return 0; 4068 } 4069 4070 /** 4071 * Set the size of the faded edge used to indicate that more content in this 4072 * view is available. Will not change whether the fading edge is enabled; use 4073 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4074 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4075 * for the vertical or horizontal fading edges. 4076 * 4077 * @param length The size in pixels of the faded edge used to indicate that more 4078 * content in this view is visible. 4079 */ 4080 public void setFadingEdgeLength(int length) { 4081 initScrollCache(); 4082 mScrollCache.fadingEdgeLength = length; 4083 } 4084 4085 /** 4086 * Returns the size of the horizontal faded edges used to indicate that more 4087 * content in this view is visible. 4088 * 4089 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4090 * faded edges are not enabled for this view. 4091 * @attr ref android.R.styleable#View_fadingEdgeLength 4092 */ 4093 public int getHorizontalFadingEdgeLength() { 4094 if (isHorizontalFadingEdgeEnabled()) { 4095 ScrollabilityCache cache = mScrollCache; 4096 if (cache != null) { 4097 return cache.fadingEdgeLength; 4098 } 4099 } 4100 return 0; 4101 } 4102 4103 /** 4104 * Returns the width of the vertical scrollbar. 4105 * 4106 * @return The width in pixels of the vertical scrollbar or 0 if there 4107 * is no vertical scrollbar. 4108 */ 4109 public int getVerticalScrollbarWidth() { 4110 ScrollabilityCache cache = mScrollCache; 4111 if (cache != null) { 4112 ScrollBarDrawable scrollBar = cache.scrollBar; 4113 if (scrollBar != null) { 4114 int size = scrollBar.getSize(true); 4115 if (size <= 0) { 4116 size = cache.scrollBarSize; 4117 } 4118 return size; 4119 } 4120 return 0; 4121 } 4122 return 0; 4123 } 4124 4125 /** 4126 * Returns the height of the horizontal scrollbar. 4127 * 4128 * @return The height in pixels of the horizontal scrollbar or 0 if 4129 * there is no horizontal scrollbar. 4130 */ 4131 protected int getHorizontalScrollbarHeight() { 4132 ScrollabilityCache cache = mScrollCache; 4133 if (cache != null) { 4134 ScrollBarDrawable scrollBar = cache.scrollBar; 4135 if (scrollBar != null) { 4136 int size = scrollBar.getSize(false); 4137 if (size <= 0) { 4138 size = cache.scrollBarSize; 4139 } 4140 return size; 4141 } 4142 return 0; 4143 } 4144 return 0; 4145 } 4146 4147 /** 4148 * <p> 4149 * Initializes the scrollbars from a given set of styled attributes. This 4150 * method should be called by subclasses that need scrollbars and when an 4151 * instance of these subclasses is created programmatically rather than 4152 * being inflated from XML. This method is automatically called when the XML 4153 * is inflated. 4154 * </p> 4155 * 4156 * @param a the styled attributes set to initialize the scrollbars from 4157 */ 4158 protected void initializeScrollbars(TypedArray a) { 4159 initScrollCache(); 4160 4161 final ScrollabilityCache scrollabilityCache = mScrollCache; 4162 4163 if (scrollabilityCache.scrollBar == null) { 4164 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4165 } 4166 4167 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4168 4169 if (!fadeScrollbars) { 4170 scrollabilityCache.state = ScrollabilityCache.ON; 4171 } 4172 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4173 4174 4175 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4176 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4177 .getScrollBarFadeDuration()); 4178 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4179 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4180 ViewConfiguration.getScrollDefaultDelay()); 4181 4182 4183 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4184 com.android.internal.R.styleable.View_scrollbarSize, 4185 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4186 4187 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4188 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4189 4190 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4191 if (thumb != null) { 4192 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4193 } 4194 4195 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4196 false); 4197 if (alwaysDraw) { 4198 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4199 } 4200 4201 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4202 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4203 4204 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4205 if (thumb != null) { 4206 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4207 } 4208 4209 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4210 false); 4211 if (alwaysDraw) { 4212 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4213 } 4214 4215 // Apply layout direction to the new Drawables if needed 4216 final int layoutDirection = getLayoutDirection(); 4217 if (track != null) { 4218 track.setLayoutDirection(layoutDirection); 4219 } 4220 if (thumb != null) { 4221 thumb.setLayoutDirection(layoutDirection); 4222 } 4223 4224 // Re-apply user/background padding so that scrollbar(s) get added 4225 resolvePadding(); 4226 } 4227 4228 /** 4229 * <p> 4230 * Initalizes the scrollability cache if necessary. 4231 * </p> 4232 */ 4233 private void initScrollCache() { 4234 if (mScrollCache == null) { 4235 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4236 } 4237 } 4238 4239 private ScrollabilityCache getScrollCache() { 4240 initScrollCache(); 4241 return mScrollCache; 4242 } 4243 4244 /** 4245 * Set the position of the vertical scroll bar. Should be one of 4246 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4247 * {@link #SCROLLBAR_POSITION_RIGHT}. 4248 * 4249 * @param position Where the vertical scroll bar should be positioned. 4250 */ 4251 public void setVerticalScrollbarPosition(int position) { 4252 if (mVerticalScrollbarPosition != position) { 4253 mVerticalScrollbarPosition = position; 4254 computeOpaqueFlags(); 4255 resolvePadding(); 4256 } 4257 } 4258 4259 /** 4260 * @return The position where the vertical scroll bar will show, if applicable. 4261 * @see #setVerticalScrollbarPosition(int) 4262 */ 4263 public int getVerticalScrollbarPosition() { 4264 return mVerticalScrollbarPosition; 4265 } 4266 4267 ListenerInfo getListenerInfo() { 4268 if (mListenerInfo != null) { 4269 return mListenerInfo; 4270 } 4271 mListenerInfo = new ListenerInfo(); 4272 return mListenerInfo; 4273 } 4274 4275 /** 4276 * Register a callback to be invoked when focus of this view changed. 4277 * 4278 * @param l The callback that will run. 4279 */ 4280 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4281 getListenerInfo().mOnFocusChangeListener = l; 4282 } 4283 4284 /** 4285 * Add a listener that will be called when the bounds of the view change due to 4286 * layout processing. 4287 * 4288 * @param listener The listener that will be called when layout bounds change. 4289 */ 4290 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4291 ListenerInfo li = getListenerInfo(); 4292 if (li.mOnLayoutChangeListeners == null) { 4293 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4294 } 4295 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4296 li.mOnLayoutChangeListeners.add(listener); 4297 } 4298 } 4299 4300 /** 4301 * Remove a listener for layout changes. 4302 * 4303 * @param listener The listener for layout bounds change. 4304 */ 4305 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4306 ListenerInfo li = mListenerInfo; 4307 if (li == null || li.mOnLayoutChangeListeners == null) { 4308 return; 4309 } 4310 li.mOnLayoutChangeListeners.remove(listener); 4311 } 4312 4313 /** 4314 * Add a listener for attach state changes. 4315 * 4316 * This listener will be called whenever this view is attached or detached 4317 * from a window. Remove the listener using 4318 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4319 * 4320 * @param listener Listener to attach 4321 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4322 */ 4323 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4324 ListenerInfo li = getListenerInfo(); 4325 if (li.mOnAttachStateChangeListeners == null) { 4326 li.mOnAttachStateChangeListeners 4327 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4328 } 4329 li.mOnAttachStateChangeListeners.add(listener); 4330 } 4331 4332 /** 4333 * Remove a listener for attach state changes. The listener will receive no further 4334 * notification of window attach/detach events. 4335 * 4336 * @param listener Listener to remove 4337 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4338 */ 4339 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4340 ListenerInfo li = mListenerInfo; 4341 if (li == null || li.mOnAttachStateChangeListeners == null) { 4342 return; 4343 } 4344 li.mOnAttachStateChangeListeners.remove(listener); 4345 } 4346 4347 /** 4348 * Returns the focus-change callback registered for this view. 4349 * 4350 * @return The callback, or null if one is not registered. 4351 */ 4352 public OnFocusChangeListener getOnFocusChangeListener() { 4353 ListenerInfo li = mListenerInfo; 4354 return li != null ? li.mOnFocusChangeListener : null; 4355 } 4356 4357 /** 4358 * Register a callback to be invoked when this view is clicked. If this view is not 4359 * clickable, it becomes clickable. 4360 * 4361 * @param l The callback that will run 4362 * 4363 * @see #setClickable(boolean) 4364 */ 4365 public void setOnClickListener(OnClickListener l) { 4366 if (!isClickable()) { 4367 setClickable(true); 4368 } 4369 getListenerInfo().mOnClickListener = l; 4370 } 4371 4372 /** 4373 * Return whether this view has an attached OnClickListener. Returns 4374 * true if there is a listener, false if there is none. 4375 */ 4376 public boolean hasOnClickListeners() { 4377 ListenerInfo li = mListenerInfo; 4378 return (li != null && li.mOnClickListener != null); 4379 } 4380 4381 /** 4382 * Register a callback to be invoked when this view is clicked and held. If this view is not 4383 * long clickable, it becomes long clickable. 4384 * 4385 * @param l The callback that will run 4386 * 4387 * @see #setLongClickable(boolean) 4388 */ 4389 public void setOnLongClickListener(OnLongClickListener l) { 4390 if (!isLongClickable()) { 4391 setLongClickable(true); 4392 } 4393 getListenerInfo().mOnLongClickListener = l; 4394 } 4395 4396 /** 4397 * Register a callback to be invoked when the context menu for this view is 4398 * being built. If this view is not long clickable, it becomes long clickable. 4399 * 4400 * @param l The callback that will run 4401 * 4402 */ 4403 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4404 if (!isLongClickable()) { 4405 setLongClickable(true); 4406 } 4407 getListenerInfo().mOnCreateContextMenuListener = l; 4408 } 4409 4410 /** 4411 * Call this view's OnClickListener, if it is defined. Performs all normal 4412 * actions associated with clicking: reporting accessibility event, playing 4413 * a sound, etc. 4414 * 4415 * @return True there was an assigned OnClickListener that was called, false 4416 * otherwise is returned. 4417 */ 4418 public boolean performClick() { 4419 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4420 4421 ListenerInfo li = mListenerInfo; 4422 if (li != null && li.mOnClickListener != null) { 4423 playSoundEffect(SoundEffectConstants.CLICK); 4424 li.mOnClickListener.onClick(this); 4425 return true; 4426 } 4427 4428 return false; 4429 } 4430 4431 /** 4432 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4433 * this only calls the listener, and does not do any associated clicking 4434 * actions like reporting an accessibility event. 4435 * 4436 * @return True there was an assigned OnClickListener that was called, false 4437 * otherwise is returned. 4438 */ 4439 public boolean callOnClick() { 4440 ListenerInfo li = mListenerInfo; 4441 if (li != null && li.mOnClickListener != null) { 4442 li.mOnClickListener.onClick(this); 4443 return true; 4444 } 4445 return false; 4446 } 4447 4448 /** 4449 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4450 * OnLongClickListener did not consume the event. 4451 * 4452 * @return True if one of the above receivers consumed the event, false otherwise. 4453 */ 4454 public boolean performLongClick() { 4455 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4456 4457 boolean handled = false; 4458 ListenerInfo li = mListenerInfo; 4459 if (li != null && li.mOnLongClickListener != null) { 4460 handled = li.mOnLongClickListener.onLongClick(View.this); 4461 } 4462 if (!handled) { 4463 handled = showContextMenu(); 4464 } 4465 if (handled) { 4466 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4467 } 4468 return handled; 4469 } 4470 4471 /** 4472 * Performs button-related actions during a touch down event. 4473 * 4474 * @param event The event. 4475 * @return True if the down was consumed. 4476 * 4477 * @hide 4478 */ 4479 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4480 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4481 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4482 return true; 4483 } 4484 } 4485 return false; 4486 } 4487 4488 /** 4489 * Bring up the context menu for this view. 4490 * 4491 * @return Whether a context menu was displayed. 4492 */ 4493 public boolean showContextMenu() { 4494 return getParent().showContextMenuForChild(this); 4495 } 4496 4497 /** 4498 * Bring up the context menu for this view, referring to the item under the specified point. 4499 * 4500 * @param x The referenced x coordinate. 4501 * @param y The referenced y coordinate. 4502 * @param metaState The keyboard modifiers that were pressed. 4503 * @return Whether a context menu was displayed. 4504 * 4505 * @hide 4506 */ 4507 public boolean showContextMenu(float x, float y, int metaState) { 4508 return showContextMenu(); 4509 } 4510 4511 /** 4512 * Start an action mode. 4513 * 4514 * @param callback Callback that will control the lifecycle of the action mode 4515 * @return The new action mode if it is started, null otherwise 4516 * 4517 * @see ActionMode 4518 */ 4519 public ActionMode startActionMode(ActionMode.Callback callback) { 4520 ViewParent parent = getParent(); 4521 if (parent == null) return null; 4522 return parent.startActionModeForChild(this, callback); 4523 } 4524 4525 /** 4526 * Register a callback to be invoked when a hardware key is pressed in this view. 4527 * Key presses in software input methods will generally not trigger the methods of 4528 * this listener. 4529 * @param l the key listener to attach to this view 4530 */ 4531 public void setOnKeyListener(OnKeyListener l) { 4532 getListenerInfo().mOnKeyListener = l; 4533 } 4534 4535 /** 4536 * Register a callback to be invoked when a touch event is sent to this view. 4537 * @param l the touch listener to attach to this view 4538 */ 4539 public void setOnTouchListener(OnTouchListener l) { 4540 getListenerInfo().mOnTouchListener = l; 4541 } 4542 4543 /** 4544 * Register a callback to be invoked when a generic motion event is sent to this view. 4545 * @param l the generic motion listener to attach to this view 4546 */ 4547 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4548 getListenerInfo().mOnGenericMotionListener = l; 4549 } 4550 4551 /** 4552 * Register a callback to be invoked when a hover event is sent to this view. 4553 * @param l the hover listener to attach to this view 4554 */ 4555 public void setOnHoverListener(OnHoverListener l) { 4556 getListenerInfo().mOnHoverListener = l; 4557 } 4558 4559 /** 4560 * Register a drag event listener callback object for this View. The parameter is 4561 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4562 * View, the system calls the 4563 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4564 * @param l An implementation of {@link android.view.View.OnDragListener}. 4565 */ 4566 public void setOnDragListener(OnDragListener l) { 4567 getListenerInfo().mOnDragListener = l; 4568 } 4569 4570 /** 4571 * Give this view focus. This will cause 4572 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4573 * 4574 * Note: this does not check whether this {@link View} should get focus, it just 4575 * gives it focus no matter what. It should only be called internally by framework 4576 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4577 * 4578 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4579 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4580 * focus moved when requestFocus() is called. It may not always 4581 * apply, in which case use the default View.FOCUS_DOWN. 4582 * @param previouslyFocusedRect The rectangle of the view that had focus 4583 * prior in this View's coordinate system. 4584 */ 4585 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 4586 if (DBG) { 4587 System.out.println(this + " requestFocus()"); 4588 } 4589 4590 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4591 mPrivateFlags |= PFLAG_FOCUSED; 4592 4593 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4594 4595 if (mParent != null) { 4596 mParent.requestChildFocus(this, this); 4597 } 4598 4599 if (mAttachInfo != null) { 4600 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4601 } 4602 4603 onFocusChanged(true, direction, previouslyFocusedRect); 4604 refreshDrawableState(); 4605 } 4606 } 4607 4608 /** 4609 * Request that a rectangle of this view be visible on the screen, 4610 * scrolling if necessary just enough. 4611 * 4612 * <p>A View should call this if it maintains some notion of which part 4613 * of its content is interesting. For example, a text editing view 4614 * should call this when its cursor moves. 4615 * 4616 * @param rectangle The rectangle. 4617 * @return Whether any parent scrolled. 4618 */ 4619 public boolean requestRectangleOnScreen(Rect rectangle) { 4620 return requestRectangleOnScreen(rectangle, false); 4621 } 4622 4623 /** 4624 * Request that a rectangle of this view be visible on the screen, 4625 * scrolling if necessary just enough. 4626 * 4627 * <p>A View should call this if it maintains some notion of which part 4628 * of its content is interesting. For example, a text editing view 4629 * should call this when its cursor moves. 4630 * 4631 * <p>When <code>immediate</code> is set to true, scrolling will not be 4632 * animated. 4633 * 4634 * @param rectangle The rectangle. 4635 * @param immediate True to forbid animated scrolling, false otherwise 4636 * @return Whether any parent scrolled. 4637 */ 4638 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4639 if (mParent == null) { 4640 return false; 4641 } 4642 4643 View child = this; 4644 4645 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4646 position.set(rectangle); 4647 4648 ViewParent parent = mParent; 4649 boolean scrolled = false; 4650 while (parent != null) { 4651 rectangle.set((int) position.left, (int) position.top, 4652 (int) position.right, (int) position.bottom); 4653 4654 scrolled |= parent.requestChildRectangleOnScreen(child, 4655 rectangle, immediate); 4656 4657 if (!child.hasIdentityMatrix()) { 4658 child.getMatrix().mapRect(position); 4659 } 4660 4661 position.offset(child.mLeft, child.mTop); 4662 4663 if (!(parent instanceof View)) { 4664 break; 4665 } 4666 4667 View parentView = (View) parent; 4668 4669 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4670 4671 child = parentView; 4672 parent = child.getParent(); 4673 } 4674 4675 return scrolled; 4676 } 4677 4678 /** 4679 * Called when this view wants to give up focus. If focus is cleared 4680 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4681 * <p> 4682 * <strong>Note:</strong> When a View clears focus the framework is trying 4683 * to give focus to the first focusable View from the top. Hence, if this 4684 * View is the first from the top that can take focus, then all callbacks 4685 * related to clearing focus will be invoked after wich the framework will 4686 * give focus to this view. 4687 * </p> 4688 */ 4689 public void clearFocus() { 4690 if (DBG) { 4691 System.out.println(this + " clearFocus()"); 4692 } 4693 4694 clearFocusInternal(true, true); 4695 } 4696 4697 /** 4698 * Clears focus from the view, optionally propagating the change up through 4699 * the parent hierarchy and requesting that the root view place new focus. 4700 * 4701 * @param propagate whether to propagate the change up through the parent 4702 * hierarchy 4703 * @param refocus when propagate is true, specifies whether to request the 4704 * root view place new focus 4705 */ 4706 void clearFocusInternal(boolean propagate, boolean refocus) { 4707 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4708 mPrivateFlags &= ~PFLAG_FOCUSED; 4709 4710 if (propagate && mParent != null) { 4711 mParent.clearChildFocus(this); 4712 } 4713 4714 onFocusChanged(false, 0, null); 4715 4716 refreshDrawableState(); 4717 4718 if (propagate && (!refocus || !rootViewRequestFocus())) { 4719 notifyGlobalFocusCleared(this); 4720 } 4721 } 4722 } 4723 4724 void notifyGlobalFocusCleared(View oldFocus) { 4725 if (oldFocus != null && mAttachInfo != null) { 4726 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 4727 } 4728 } 4729 4730 boolean rootViewRequestFocus() { 4731 final View root = getRootView(); 4732 return root != null && root.requestFocus(); 4733 } 4734 4735 /** 4736 * Called internally by the view system when a new view is getting focus. 4737 * This is what clears the old focus. 4738 * <p> 4739 * <b>NOTE:</b> The parent view's focused child must be updated manually 4740 * after calling this method. Otherwise, the view hierarchy may be left in 4741 * an inconstent state. 4742 */ 4743 void unFocus() { 4744 if (DBG) { 4745 System.out.println(this + " unFocus()"); 4746 } 4747 4748 clearFocusInternal(false, false); 4749 } 4750 4751 /** 4752 * Returns true if this view has focus iteself, or is the ancestor of the 4753 * view that has focus. 4754 * 4755 * @return True if this view has or contains focus, false otherwise. 4756 */ 4757 @ViewDebug.ExportedProperty(category = "focus") 4758 public boolean hasFocus() { 4759 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4760 } 4761 4762 /** 4763 * Returns true if this view is focusable or if it contains a reachable View 4764 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4765 * is a View whose parents do not block descendants focus. 4766 * 4767 * Only {@link #VISIBLE} views are considered focusable. 4768 * 4769 * @return True if the view is focusable or if the view contains a focusable 4770 * View, false otherwise. 4771 * 4772 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4773 */ 4774 public boolean hasFocusable() { 4775 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4776 } 4777 4778 /** 4779 * Called by the view system when the focus state of this view changes. 4780 * When the focus change event is caused by directional navigation, direction 4781 * and previouslyFocusedRect provide insight into where the focus is coming from. 4782 * When overriding, be sure to call up through to the super class so that 4783 * the standard focus handling will occur. 4784 * 4785 * @param gainFocus True if the View has focus; false otherwise. 4786 * @param direction The direction focus has moved when requestFocus() 4787 * is called to give this view focus. Values are 4788 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4789 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4790 * It may not always apply, in which case use the default. 4791 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4792 * system, of the previously focused view. If applicable, this will be 4793 * passed in as finer grained information about where the focus is coming 4794 * from (in addition to direction). Will be <code>null</code> otherwise. 4795 */ 4796 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 4797 if (gainFocus) { 4798 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 4799 } else { 4800 notifyViewAccessibilityStateChangedIfNeeded( 4801 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 4802 } 4803 4804 InputMethodManager imm = InputMethodManager.peekInstance(); 4805 if (!gainFocus) { 4806 if (isPressed()) { 4807 setPressed(false); 4808 } 4809 if (imm != null && mAttachInfo != null 4810 && mAttachInfo.mHasWindowFocus) { 4811 imm.focusOut(this); 4812 } 4813 onFocusLost(); 4814 } else if (imm != null && mAttachInfo != null 4815 && mAttachInfo.mHasWindowFocus) { 4816 imm.focusIn(this); 4817 } 4818 4819 invalidate(true); 4820 ListenerInfo li = mListenerInfo; 4821 if (li != null && li.mOnFocusChangeListener != null) { 4822 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 4823 } 4824 4825 if (mAttachInfo != null) { 4826 mAttachInfo.mKeyDispatchState.reset(this); 4827 } 4828 } 4829 4830 /** 4831 * Sends an accessibility event of the given type. If accessibility is 4832 * not enabled this method has no effect. The default implementation calls 4833 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 4834 * to populate information about the event source (this View), then calls 4835 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 4836 * populate the text content of the event source including its descendants, 4837 * and last calls 4838 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 4839 * on its parent to resuest sending of the event to interested parties. 4840 * <p> 4841 * If an {@link AccessibilityDelegate} has been specified via calling 4842 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4843 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 4844 * responsible for handling this call. 4845 * </p> 4846 * 4847 * @param eventType The type of the event to send, as defined by several types from 4848 * {@link android.view.accessibility.AccessibilityEvent}, such as 4849 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 4850 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 4851 * 4852 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4853 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4854 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 4855 * @see AccessibilityDelegate 4856 */ 4857 public void sendAccessibilityEvent(int eventType) { 4858 // Excluded views do not send accessibility events. 4859 if (!includeForAccessibility()) { 4860 return; 4861 } 4862 if (mAccessibilityDelegate != null) { 4863 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 4864 } else { 4865 sendAccessibilityEventInternal(eventType); 4866 } 4867 } 4868 4869 /** 4870 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 4871 * {@link AccessibilityEvent} to make an announcement which is related to some 4872 * sort of a context change for which none of the events representing UI transitions 4873 * is a good fit. For example, announcing a new page in a book. If accessibility 4874 * is not enabled this method does nothing. 4875 * 4876 * @param text The announcement text. 4877 */ 4878 public void announceForAccessibility(CharSequence text) { 4879 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 4880 AccessibilityEvent event = AccessibilityEvent.obtain( 4881 AccessibilityEvent.TYPE_ANNOUNCEMENT); 4882 onInitializeAccessibilityEvent(event); 4883 event.getText().add(text); 4884 event.setContentDescription(null); 4885 mParent.requestSendAccessibilityEvent(this, event); 4886 } 4887 } 4888 4889 /** 4890 * @see #sendAccessibilityEvent(int) 4891 * 4892 * Note: Called from the default {@link AccessibilityDelegate}. 4893 */ 4894 void sendAccessibilityEventInternal(int eventType) { 4895 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4896 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 4897 } 4898 } 4899 4900 /** 4901 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 4902 * takes as an argument an empty {@link AccessibilityEvent} and does not 4903 * perform a check whether accessibility is enabled. 4904 * <p> 4905 * If an {@link AccessibilityDelegate} has been specified via calling 4906 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4907 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 4908 * is responsible for handling this call. 4909 * </p> 4910 * 4911 * @param event The event to send. 4912 * 4913 * @see #sendAccessibilityEvent(int) 4914 */ 4915 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 4916 if (mAccessibilityDelegate != null) { 4917 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 4918 } else { 4919 sendAccessibilityEventUncheckedInternal(event); 4920 } 4921 } 4922 4923 /** 4924 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 4925 * 4926 * Note: Called from the default {@link AccessibilityDelegate}. 4927 */ 4928 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 4929 if (!isShown()) { 4930 return; 4931 } 4932 onInitializeAccessibilityEvent(event); 4933 // Only a subset of accessibility events populates text content. 4934 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 4935 dispatchPopulateAccessibilityEvent(event); 4936 } 4937 // In the beginning we called #isShown(), so we know that getParent() is not null. 4938 getParent().requestSendAccessibilityEvent(this, event); 4939 } 4940 4941 /** 4942 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 4943 * to its children for adding their text content to the event. Note that the 4944 * event text is populated in a separate dispatch path since we add to the 4945 * event not only the text of the source but also the text of all its descendants. 4946 * A typical implementation will call 4947 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 4948 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4949 * on each child. Override this method if custom population of the event text 4950 * content is required. 4951 * <p> 4952 * If an {@link AccessibilityDelegate} has been specified via calling 4953 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4954 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 4955 * is responsible for handling this call. 4956 * </p> 4957 * <p> 4958 * <em>Note:</em> Accessibility events of certain types are not dispatched for 4959 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 4960 * </p> 4961 * 4962 * @param event The event. 4963 * 4964 * @return True if the event population was completed. 4965 */ 4966 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 4967 if (mAccessibilityDelegate != null) { 4968 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 4969 } else { 4970 return dispatchPopulateAccessibilityEventInternal(event); 4971 } 4972 } 4973 4974 /** 4975 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4976 * 4977 * Note: Called from the default {@link AccessibilityDelegate}. 4978 */ 4979 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4980 onPopulateAccessibilityEvent(event); 4981 return false; 4982 } 4983 4984 /** 4985 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4986 * giving a chance to this View to populate the accessibility event with its 4987 * text content. While this method is free to modify event 4988 * attributes other than text content, doing so should normally be performed in 4989 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 4990 * <p> 4991 * Example: Adding formatted date string to an accessibility event in addition 4992 * to the text added by the super implementation: 4993 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4994 * super.onPopulateAccessibilityEvent(event); 4995 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 4996 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 4997 * mCurrentDate.getTimeInMillis(), flags); 4998 * event.getText().add(selectedDateUtterance); 4999 * }</pre> 5000 * <p> 5001 * If an {@link AccessibilityDelegate} has been specified via calling 5002 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5003 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5004 * is responsible for handling this call. 5005 * </p> 5006 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5007 * information to the event, in case the default implementation has basic information to add. 5008 * </p> 5009 * 5010 * @param event The accessibility event which to populate. 5011 * 5012 * @see #sendAccessibilityEvent(int) 5013 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5014 */ 5015 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5016 if (mAccessibilityDelegate != null) { 5017 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5018 } else { 5019 onPopulateAccessibilityEventInternal(event); 5020 } 5021 } 5022 5023 /** 5024 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5025 * 5026 * Note: Called from the default {@link AccessibilityDelegate}. 5027 */ 5028 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5029 } 5030 5031 /** 5032 * Initializes an {@link AccessibilityEvent} with information about 5033 * this View which is the event source. In other words, the source of 5034 * an accessibility event is the view whose state change triggered firing 5035 * the event. 5036 * <p> 5037 * Example: Setting the password property of an event in addition 5038 * to properties set by the super implementation: 5039 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5040 * super.onInitializeAccessibilityEvent(event); 5041 * event.setPassword(true); 5042 * }</pre> 5043 * <p> 5044 * If an {@link AccessibilityDelegate} has been specified via calling 5045 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5046 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5047 * is responsible for handling this call. 5048 * </p> 5049 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5050 * information to the event, in case the default implementation has basic information to add. 5051 * </p> 5052 * @param event The event to initialize. 5053 * 5054 * @see #sendAccessibilityEvent(int) 5055 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5056 */ 5057 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5058 if (mAccessibilityDelegate != null) { 5059 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5060 } else { 5061 onInitializeAccessibilityEventInternal(event); 5062 } 5063 } 5064 5065 /** 5066 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5067 * 5068 * Note: Called from the default {@link AccessibilityDelegate}. 5069 */ 5070 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5071 event.setSource(this); 5072 event.setClassName(View.class.getName()); 5073 event.setPackageName(getContext().getPackageName()); 5074 event.setEnabled(isEnabled()); 5075 event.setContentDescription(mContentDescription); 5076 5077 switch (event.getEventType()) { 5078 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5079 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5080 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5081 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5082 event.setItemCount(focusablesTempList.size()); 5083 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5084 if (mAttachInfo != null) { 5085 focusablesTempList.clear(); 5086 } 5087 } break; 5088 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5089 CharSequence text = getIterableTextForAccessibility(); 5090 if (text != null && text.length() > 0) { 5091 event.setFromIndex(getAccessibilitySelectionStart()); 5092 event.setToIndex(getAccessibilitySelectionEnd()); 5093 event.setItemCount(text.length()); 5094 } 5095 } break; 5096 } 5097 } 5098 5099 /** 5100 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5101 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5102 * This method is responsible for obtaining an accessibility node info from a 5103 * pool of reusable instances and calling 5104 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5105 * initialize the former. 5106 * <p> 5107 * Note: The client is responsible for recycling the obtained instance by calling 5108 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5109 * </p> 5110 * 5111 * @return A populated {@link AccessibilityNodeInfo}. 5112 * 5113 * @see AccessibilityNodeInfo 5114 */ 5115 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5116 if (mAccessibilityDelegate != null) { 5117 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5118 } else { 5119 return createAccessibilityNodeInfoInternal(); 5120 } 5121 } 5122 5123 /** 5124 * @see #createAccessibilityNodeInfo() 5125 */ 5126 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5127 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5128 if (provider != null) { 5129 return provider.createAccessibilityNodeInfo(View.NO_ID); 5130 } else { 5131 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5132 onInitializeAccessibilityNodeInfo(info); 5133 return info; 5134 } 5135 } 5136 5137 /** 5138 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5139 * The base implementation sets: 5140 * <ul> 5141 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5142 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5143 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5144 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5145 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5146 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5147 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5148 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5149 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5150 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5151 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5152 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5153 * </ul> 5154 * <p> 5155 * Subclasses should override this method, call the super implementation, 5156 * and set additional attributes. 5157 * </p> 5158 * <p> 5159 * If an {@link AccessibilityDelegate} has been specified via calling 5160 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5161 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5162 * is responsible for handling this call. 5163 * </p> 5164 * 5165 * @param info The instance to initialize. 5166 */ 5167 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5168 if (mAccessibilityDelegate != null) { 5169 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5170 } else { 5171 onInitializeAccessibilityNodeInfoInternal(info); 5172 } 5173 } 5174 5175 /** 5176 * Gets the location of this view in screen coordintates. 5177 * 5178 * @param outRect The output location 5179 */ 5180 void getBoundsOnScreen(Rect outRect) { 5181 if (mAttachInfo == null) { 5182 return; 5183 } 5184 5185 RectF position = mAttachInfo.mTmpTransformRect; 5186 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5187 5188 if (!hasIdentityMatrix()) { 5189 getMatrix().mapRect(position); 5190 } 5191 5192 position.offset(mLeft, mTop); 5193 5194 ViewParent parent = mParent; 5195 while (parent instanceof View) { 5196 View parentView = (View) parent; 5197 5198 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5199 5200 if (!parentView.hasIdentityMatrix()) { 5201 parentView.getMatrix().mapRect(position); 5202 } 5203 5204 position.offset(parentView.mLeft, parentView.mTop); 5205 5206 parent = parentView.mParent; 5207 } 5208 5209 if (parent instanceof ViewRootImpl) { 5210 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5211 position.offset(0, -viewRootImpl.mCurScrollY); 5212 } 5213 5214 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5215 5216 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5217 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5218 } 5219 5220 /** 5221 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5222 * 5223 * Note: Called from the default {@link AccessibilityDelegate}. 5224 */ 5225 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5226 Rect bounds = mAttachInfo.mTmpInvalRect; 5227 5228 getDrawingRect(bounds); 5229 info.setBoundsInParent(bounds); 5230 5231 getBoundsOnScreen(bounds); 5232 info.setBoundsInScreen(bounds); 5233 5234 ViewParent parent = getParentForAccessibility(); 5235 if (parent instanceof View) { 5236 info.setParent((View) parent); 5237 } 5238 5239 if (mID != View.NO_ID) { 5240 View rootView = getRootView(); 5241 if (rootView == null) { 5242 rootView = this; 5243 } 5244 View label = rootView.findLabelForView(this, mID); 5245 if (label != null) { 5246 info.setLabeledBy(label); 5247 } 5248 5249 if ((mAttachInfo.mAccessibilityFetchFlags 5250 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5251 && Resources.resourceHasPackage(mID)) { 5252 try { 5253 String viewId = getResources().getResourceName(mID); 5254 info.setViewIdResourceName(viewId); 5255 } catch (Resources.NotFoundException nfe) { 5256 /* ignore */ 5257 } 5258 } 5259 } 5260 5261 if (mLabelForId != View.NO_ID) { 5262 View rootView = getRootView(); 5263 if (rootView == null) { 5264 rootView = this; 5265 } 5266 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5267 if (labeled != null) { 5268 info.setLabelFor(labeled); 5269 } 5270 } 5271 5272 info.setVisibleToUser(isVisibleToUser()); 5273 5274 info.setPackageName(mContext.getPackageName()); 5275 info.setClassName(View.class.getName()); 5276 info.setContentDescription(getContentDescription()); 5277 5278 info.setEnabled(isEnabled()); 5279 info.setClickable(isClickable()); 5280 info.setFocusable(isFocusable()); 5281 info.setFocused(isFocused()); 5282 info.setAccessibilityFocused(isAccessibilityFocused()); 5283 info.setSelected(isSelected()); 5284 info.setLongClickable(isLongClickable()); 5285 info.setLiveRegion(getAccessibilityLiveRegion()); 5286 5287 // TODO: These make sense only if we are in an AdapterView but all 5288 // views can be selected. Maybe from accessibility perspective 5289 // we should report as selectable view in an AdapterView. 5290 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5291 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5292 5293 if (isFocusable()) { 5294 if (isFocused()) { 5295 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5296 } else { 5297 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5298 } 5299 } 5300 5301 if (!isAccessibilityFocused()) { 5302 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5303 } else { 5304 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5305 } 5306 5307 if (isClickable() && isEnabled()) { 5308 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5309 } 5310 5311 if (isLongClickable() && isEnabled()) { 5312 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5313 } 5314 5315 CharSequence text = getIterableTextForAccessibility(); 5316 if (text != null && text.length() > 0) { 5317 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5318 5319 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5320 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5321 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5322 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5323 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5324 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5325 } 5326 } 5327 5328 private View findLabelForView(View view, int labeledId) { 5329 if (mMatchLabelForPredicate == null) { 5330 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5331 } 5332 mMatchLabelForPredicate.mLabeledId = labeledId; 5333 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5334 } 5335 5336 /** 5337 * Computes whether this view is visible to the user. Such a view is 5338 * attached, visible, all its predecessors are visible, it is not clipped 5339 * entirely by its predecessors, and has an alpha greater than zero. 5340 * 5341 * @return Whether the view is visible on the screen. 5342 * 5343 * @hide 5344 */ 5345 protected boolean isVisibleToUser() { 5346 return isVisibleToUser(null); 5347 } 5348 5349 /** 5350 * Computes whether the given portion of this view is visible to the user. 5351 * Such a view is attached, visible, all its predecessors are visible, 5352 * has an alpha greater than zero, and the specified portion is not 5353 * clipped entirely by its predecessors. 5354 * 5355 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5356 * <code>null</code>, and the entire view will be tested in this case. 5357 * When <code>true</code> is returned by the function, the actual visible 5358 * region will be stored in this parameter; that is, if boundInView is fully 5359 * contained within the view, no modification will be made, otherwise regions 5360 * outside of the visible area of the view will be clipped. 5361 * 5362 * @return Whether the specified portion of the view is visible on the screen. 5363 * 5364 * @hide 5365 */ 5366 protected boolean isVisibleToUser(Rect boundInView) { 5367 if (mAttachInfo != null) { 5368 // Attached to invisible window means this view is not visible. 5369 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5370 return false; 5371 } 5372 // An invisible predecessor or one with alpha zero means 5373 // that this view is not visible to the user. 5374 Object current = this; 5375 while (current instanceof View) { 5376 View view = (View) current; 5377 // We have attach info so this view is attached and there is no 5378 // need to check whether we reach to ViewRootImpl on the way up. 5379 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5380 view.getVisibility() != VISIBLE) { 5381 return false; 5382 } 5383 current = view.mParent; 5384 } 5385 // Check if the view is entirely covered by its predecessors. 5386 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5387 Point offset = mAttachInfo.mPoint; 5388 if (!getGlobalVisibleRect(visibleRect, offset)) { 5389 return false; 5390 } 5391 // Check if the visible portion intersects the rectangle of interest. 5392 if (boundInView != null) { 5393 visibleRect.offset(-offset.x, -offset.y); 5394 return boundInView.intersect(visibleRect); 5395 } 5396 return true; 5397 } 5398 return false; 5399 } 5400 5401 /** 5402 * Returns the delegate for implementing accessibility support via 5403 * composition. For more details see {@link AccessibilityDelegate}. 5404 * 5405 * @return The delegate, or null if none set. 5406 * 5407 * @hide 5408 */ 5409 public AccessibilityDelegate getAccessibilityDelegate() { 5410 return mAccessibilityDelegate; 5411 } 5412 5413 /** 5414 * Sets a delegate for implementing accessibility support via composition as 5415 * opposed to inheritance. The delegate's primary use is for implementing 5416 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5417 * 5418 * @param delegate The delegate instance. 5419 * 5420 * @see AccessibilityDelegate 5421 */ 5422 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5423 mAccessibilityDelegate = delegate; 5424 } 5425 5426 /** 5427 * Gets the provider for managing a virtual view hierarchy rooted at this View 5428 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5429 * that explore the window content. 5430 * <p> 5431 * If this method returns an instance, this instance is responsible for managing 5432 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5433 * View including the one representing the View itself. Similarly the returned 5434 * instance is responsible for performing accessibility actions on any virtual 5435 * view or the root view itself. 5436 * </p> 5437 * <p> 5438 * If an {@link AccessibilityDelegate} has been specified via calling 5439 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5440 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5441 * is responsible for handling this call. 5442 * </p> 5443 * 5444 * @return The provider. 5445 * 5446 * @see AccessibilityNodeProvider 5447 */ 5448 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5449 if (mAccessibilityDelegate != null) { 5450 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5451 } else { 5452 return null; 5453 } 5454 } 5455 5456 /** 5457 * Gets the unique identifier of this view on the screen for accessibility purposes. 5458 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5459 * 5460 * @return The view accessibility id. 5461 * 5462 * @hide 5463 */ 5464 public int getAccessibilityViewId() { 5465 if (mAccessibilityViewId == NO_ID) { 5466 mAccessibilityViewId = sNextAccessibilityViewId++; 5467 } 5468 return mAccessibilityViewId; 5469 } 5470 5471 /** 5472 * Gets the unique identifier of the window in which this View reseides. 5473 * 5474 * @return The window accessibility id. 5475 * 5476 * @hide 5477 */ 5478 public int getAccessibilityWindowId() { 5479 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 5480 } 5481 5482 /** 5483 * Gets the {@link View} description. It briefly describes the view and is 5484 * primarily used for accessibility support. Set this property to enable 5485 * better accessibility support for your application. This is especially 5486 * true for views that do not have textual representation (For example, 5487 * ImageButton). 5488 * 5489 * @return The content description. 5490 * 5491 * @attr ref android.R.styleable#View_contentDescription 5492 */ 5493 @ViewDebug.ExportedProperty(category = "accessibility") 5494 public CharSequence getContentDescription() { 5495 return mContentDescription; 5496 } 5497 5498 /** 5499 * Sets the {@link View} description. It briefly describes the view and is 5500 * primarily used for accessibility support. Set this property to enable 5501 * better accessibility support for your application. This is especially 5502 * true for views that do not have textual representation (For example, 5503 * ImageButton). 5504 * 5505 * @param contentDescription The content description. 5506 * 5507 * @attr ref android.R.styleable#View_contentDescription 5508 */ 5509 @RemotableViewMethod 5510 public void setContentDescription(CharSequence contentDescription) { 5511 if (mContentDescription == null) { 5512 if (contentDescription == null) { 5513 return; 5514 } 5515 } else if (mContentDescription.equals(contentDescription)) { 5516 return; 5517 } 5518 mContentDescription = contentDescription; 5519 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5520 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5521 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5522 notifySubtreeAccessibilityStateChangedIfNeeded(); 5523 } else { 5524 notifyViewAccessibilityStateChangedIfNeeded( 5525 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5526 } 5527 } 5528 5529 /** 5530 * Gets the id of a view for which this view serves as a label for 5531 * accessibility purposes. 5532 * 5533 * @return The labeled view id. 5534 */ 5535 @ViewDebug.ExportedProperty(category = "accessibility") 5536 public int getLabelFor() { 5537 return mLabelForId; 5538 } 5539 5540 /** 5541 * Sets the id of a view for which this view serves as a label for 5542 * accessibility purposes. 5543 * 5544 * @param id The labeled view id. 5545 */ 5546 @RemotableViewMethod 5547 public void setLabelFor(int id) { 5548 mLabelForId = id; 5549 if (mLabelForId != View.NO_ID 5550 && mID == View.NO_ID) { 5551 mID = generateViewId(); 5552 } 5553 } 5554 5555 /** 5556 * Invoked whenever this view loses focus, either by losing window focus or by losing 5557 * focus within its window. This method can be used to clear any state tied to the 5558 * focus. For instance, if a button is held pressed with the trackball and the window 5559 * loses focus, this method can be used to cancel the press. 5560 * 5561 * Subclasses of View overriding this method should always call super.onFocusLost(). 5562 * 5563 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5564 * @see #onWindowFocusChanged(boolean) 5565 * 5566 * @hide pending API council approval 5567 */ 5568 protected void onFocusLost() { 5569 resetPressedState(); 5570 } 5571 5572 private void resetPressedState() { 5573 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5574 return; 5575 } 5576 5577 if (isPressed()) { 5578 setPressed(false); 5579 5580 if (!mHasPerformedLongPress) { 5581 removeLongPressCallback(); 5582 } 5583 } 5584 } 5585 5586 /** 5587 * Returns true if this view has focus 5588 * 5589 * @return True if this view has focus, false otherwise. 5590 */ 5591 @ViewDebug.ExportedProperty(category = "focus") 5592 public boolean isFocused() { 5593 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5594 } 5595 5596 /** 5597 * Find the view in the hierarchy rooted at this view that currently has 5598 * focus. 5599 * 5600 * @return The view that currently has focus, or null if no focused view can 5601 * be found. 5602 */ 5603 public View findFocus() { 5604 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5605 } 5606 5607 /** 5608 * Indicates whether this view is one of the set of scrollable containers in 5609 * its window. 5610 * 5611 * @return whether this view is one of the set of scrollable containers in 5612 * its window 5613 * 5614 * @attr ref android.R.styleable#View_isScrollContainer 5615 */ 5616 public boolean isScrollContainer() { 5617 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5618 } 5619 5620 /** 5621 * Change whether this view is one of the set of scrollable containers in 5622 * its window. This will be used to determine whether the window can 5623 * resize or must pan when a soft input area is open -- scrollable 5624 * containers allow the window to use resize mode since the container 5625 * will appropriately shrink. 5626 * 5627 * @attr ref android.R.styleable#View_isScrollContainer 5628 */ 5629 public void setScrollContainer(boolean isScrollContainer) { 5630 if (isScrollContainer) { 5631 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5632 mAttachInfo.mScrollContainers.add(this); 5633 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5634 } 5635 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5636 } else { 5637 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5638 mAttachInfo.mScrollContainers.remove(this); 5639 } 5640 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5641 } 5642 } 5643 5644 /** 5645 * Returns the quality of the drawing cache. 5646 * 5647 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5648 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5649 * 5650 * @see #setDrawingCacheQuality(int) 5651 * @see #setDrawingCacheEnabled(boolean) 5652 * @see #isDrawingCacheEnabled() 5653 * 5654 * @attr ref android.R.styleable#View_drawingCacheQuality 5655 */ 5656 public int getDrawingCacheQuality() { 5657 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5658 } 5659 5660 /** 5661 * Set the drawing cache quality of this view. This value is used only when the 5662 * drawing cache is enabled 5663 * 5664 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5665 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5666 * 5667 * @see #getDrawingCacheQuality() 5668 * @see #setDrawingCacheEnabled(boolean) 5669 * @see #isDrawingCacheEnabled() 5670 * 5671 * @attr ref android.R.styleable#View_drawingCacheQuality 5672 */ 5673 public void setDrawingCacheQuality(int quality) { 5674 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5675 } 5676 5677 /** 5678 * Returns whether the screen should remain on, corresponding to the current 5679 * value of {@link #KEEP_SCREEN_ON}. 5680 * 5681 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5682 * 5683 * @see #setKeepScreenOn(boolean) 5684 * 5685 * @attr ref android.R.styleable#View_keepScreenOn 5686 */ 5687 public boolean getKeepScreenOn() { 5688 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5689 } 5690 5691 /** 5692 * Controls whether the screen should remain on, modifying the 5693 * value of {@link #KEEP_SCREEN_ON}. 5694 * 5695 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5696 * 5697 * @see #getKeepScreenOn() 5698 * 5699 * @attr ref android.R.styleable#View_keepScreenOn 5700 */ 5701 public void setKeepScreenOn(boolean keepScreenOn) { 5702 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5703 } 5704 5705 /** 5706 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5707 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5708 * 5709 * @attr ref android.R.styleable#View_nextFocusLeft 5710 */ 5711 public int getNextFocusLeftId() { 5712 return mNextFocusLeftId; 5713 } 5714 5715 /** 5716 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5717 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5718 * decide automatically. 5719 * 5720 * @attr ref android.R.styleable#View_nextFocusLeft 5721 */ 5722 public void setNextFocusLeftId(int nextFocusLeftId) { 5723 mNextFocusLeftId = nextFocusLeftId; 5724 } 5725 5726 /** 5727 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5728 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5729 * 5730 * @attr ref android.R.styleable#View_nextFocusRight 5731 */ 5732 public int getNextFocusRightId() { 5733 return mNextFocusRightId; 5734 } 5735 5736 /** 5737 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5738 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5739 * decide automatically. 5740 * 5741 * @attr ref android.R.styleable#View_nextFocusRight 5742 */ 5743 public void setNextFocusRightId(int nextFocusRightId) { 5744 mNextFocusRightId = nextFocusRightId; 5745 } 5746 5747 /** 5748 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5749 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5750 * 5751 * @attr ref android.R.styleable#View_nextFocusUp 5752 */ 5753 public int getNextFocusUpId() { 5754 return mNextFocusUpId; 5755 } 5756 5757 /** 5758 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5759 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5760 * decide automatically. 5761 * 5762 * @attr ref android.R.styleable#View_nextFocusUp 5763 */ 5764 public void setNextFocusUpId(int nextFocusUpId) { 5765 mNextFocusUpId = nextFocusUpId; 5766 } 5767 5768 /** 5769 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5770 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5771 * 5772 * @attr ref android.R.styleable#View_nextFocusDown 5773 */ 5774 public int getNextFocusDownId() { 5775 return mNextFocusDownId; 5776 } 5777 5778 /** 5779 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5780 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 5781 * decide automatically. 5782 * 5783 * @attr ref android.R.styleable#View_nextFocusDown 5784 */ 5785 public void setNextFocusDownId(int nextFocusDownId) { 5786 mNextFocusDownId = nextFocusDownId; 5787 } 5788 5789 /** 5790 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5791 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5792 * 5793 * @attr ref android.R.styleable#View_nextFocusForward 5794 */ 5795 public int getNextFocusForwardId() { 5796 return mNextFocusForwardId; 5797 } 5798 5799 /** 5800 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5801 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 5802 * decide automatically. 5803 * 5804 * @attr ref android.R.styleable#View_nextFocusForward 5805 */ 5806 public void setNextFocusForwardId(int nextFocusForwardId) { 5807 mNextFocusForwardId = nextFocusForwardId; 5808 } 5809 5810 /** 5811 * Returns the visibility of this view and all of its ancestors 5812 * 5813 * @return True if this view and all of its ancestors are {@link #VISIBLE} 5814 */ 5815 public boolean isShown() { 5816 View current = this; 5817 //noinspection ConstantConditions 5818 do { 5819 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5820 return false; 5821 } 5822 ViewParent parent = current.mParent; 5823 if (parent == null) { 5824 return false; // We are not attached to the view root 5825 } 5826 if (!(parent instanceof View)) { 5827 return true; 5828 } 5829 current = (View) parent; 5830 } while (current != null); 5831 5832 return false; 5833 } 5834 5835 /** 5836 * Called by the view hierarchy when the content insets for a window have 5837 * changed, to allow it to adjust its content to fit within those windows. 5838 * The content insets tell you the space that the status bar, input method, 5839 * and other system windows infringe on the application's window. 5840 * 5841 * <p>You do not normally need to deal with this function, since the default 5842 * window decoration given to applications takes care of applying it to the 5843 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 5844 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 5845 * and your content can be placed under those system elements. You can then 5846 * use this method within your view hierarchy if you have parts of your UI 5847 * which you would like to ensure are not being covered. 5848 * 5849 * <p>The default implementation of this method simply applies the content 5850 * insets to the view's padding, consuming that content (modifying the 5851 * insets to be 0), and returning true. This behavior is off by default, but can 5852 * be enabled through {@link #setFitsSystemWindows(boolean)}. 5853 * 5854 * <p>This function's traversal down the hierarchy is depth-first. The same content 5855 * insets object is propagated down the hierarchy, so any changes made to it will 5856 * be seen by all following views (including potentially ones above in 5857 * the hierarchy since this is a depth-first traversal). The first view 5858 * that returns true will abort the entire traversal. 5859 * 5860 * <p>The default implementation works well for a situation where it is 5861 * used with a container that covers the entire window, allowing it to 5862 * apply the appropriate insets to its content on all edges. If you need 5863 * a more complicated layout (such as two different views fitting system 5864 * windows, one on the top of the window, and one on the bottom), 5865 * you can override the method and handle the insets however you would like. 5866 * Note that the insets provided by the framework are always relative to the 5867 * far edges of the window, not accounting for the location of the called view 5868 * within that window. (In fact when this method is called you do not yet know 5869 * where the layout will place the view, as it is done before layout happens.) 5870 * 5871 * <p>Note: unlike many View methods, there is no dispatch phase to this 5872 * call. If you are overriding it in a ViewGroup and want to allow the 5873 * call to continue to your children, you must be sure to call the super 5874 * implementation. 5875 * 5876 * <p>Here is a sample layout that makes use of fitting system windows 5877 * to have controls for a video view placed inside of the window decorations 5878 * that it hides and shows. This can be used with code like the second 5879 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 5880 * 5881 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 5882 * 5883 * @param insets Current content insets of the window. Prior to 5884 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 5885 * the insets or else you and Android will be unhappy. 5886 * 5887 * @return {@code true} if this view applied the insets and it should not 5888 * continue propagating further down the hierarchy, {@code false} otherwise. 5889 * @see #getFitsSystemWindows() 5890 * @see #setFitsSystemWindows(boolean) 5891 * @see #setSystemUiVisibility(int) 5892 */ 5893 protected boolean fitSystemWindows(Rect insets) { 5894 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 5895 mUserPaddingStart = UNDEFINED_PADDING; 5896 mUserPaddingEnd = UNDEFINED_PADDING; 5897 Rect localInsets = sThreadLocal.get(); 5898 if (localInsets == null) { 5899 localInsets = new Rect(); 5900 sThreadLocal.set(localInsets); 5901 } 5902 boolean res = computeFitSystemWindows(insets, localInsets); 5903 internalSetPadding(localInsets.left, localInsets.top, 5904 localInsets.right, localInsets.bottom); 5905 return res; 5906 } 5907 return false; 5908 } 5909 5910 /** 5911 * @hide Compute the insets that should be consumed by this view and the ones 5912 * that should propagate to those under it. 5913 */ 5914 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 5915 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 5916 || mAttachInfo == null 5917 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 5918 && !mAttachInfo.mOverscanRequested)) { 5919 outLocalInsets.set(inoutInsets); 5920 inoutInsets.set(0, 0, 0, 0); 5921 return true; 5922 } else { 5923 // The application wants to take care of fitting system window for 5924 // the content... however we still need to take care of any overscan here. 5925 final Rect overscan = mAttachInfo.mOverscanInsets; 5926 outLocalInsets.set(overscan); 5927 inoutInsets.left -= overscan.left; 5928 inoutInsets.top -= overscan.top; 5929 inoutInsets.right -= overscan.right; 5930 inoutInsets.bottom -= overscan.bottom; 5931 return false; 5932 } 5933 } 5934 5935 /** 5936 * Sets whether or not this view should account for system screen decorations 5937 * such as the status bar and inset its content; that is, controlling whether 5938 * the default implementation of {@link #fitSystemWindows(Rect)} will be 5939 * executed. See that method for more details. 5940 * 5941 * <p>Note that if you are providing your own implementation of 5942 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 5943 * flag to true -- your implementation will be overriding the default 5944 * implementation that checks this flag. 5945 * 5946 * @param fitSystemWindows If true, then the default implementation of 5947 * {@link #fitSystemWindows(Rect)} will be executed. 5948 * 5949 * @attr ref android.R.styleable#View_fitsSystemWindows 5950 * @see #getFitsSystemWindows() 5951 * @see #fitSystemWindows(Rect) 5952 * @see #setSystemUiVisibility(int) 5953 */ 5954 public void setFitsSystemWindows(boolean fitSystemWindows) { 5955 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 5956 } 5957 5958 /** 5959 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 5960 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 5961 * will be executed. 5962 * 5963 * @return {@code true} if the default implementation of 5964 * {@link #fitSystemWindows(Rect)} will be executed. 5965 * 5966 * @attr ref android.R.styleable#View_fitsSystemWindows 5967 * @see #setFitsSystemWindows(boolean) 5968 * @see #fitSystemWindows(Rect) 5969 * @see #setSystemUiVisibility(int) 5970 */ 5971 public boolean getFitsSystemWindows() { 5972 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 5973 } 5974 5975 /** @hide */ 5976 public boolean fitsSystemWindows() { 5977 return getFitsSystemWindows(); 5978 } 5979 5980 /** 5981 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 5982 */ 5983 public void requestFitSystemWindows() { 5984 if (mParent != null) { 5985 mParent.requestFitSystemWindows(); 5986 } 5987 } 5988 5989 /** 5990 * For use by PhoneWindow to make its own system window fitting optional. 5991 * @hide 5992 */ 5993 public void makeOptionalFitsSystemWindows() { 5994 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 5995 } 5996 5997 /** 5998 * Returns the visibility status for this view. 5999 * 6000 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6001 * @attr ref android.R.styleable#View_visibility 6002 */ 6003 @ViewDebug.ExportedProperty(mapping = { 6004 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6005 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6006 @ViewDebug.IntToString(from = GONE, to = "GONE") 6007 }) 6008 public int getVisibility() { 6009 return mViewFlags & VISIBILITY_MASK; 6010 } 6011 6012 /** 6013 * Set the enabled state of this view. 6014 * 6015 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6016 * @attr ref android.R.styleable#View_visibility 6017 */ 6018 @RemotableViewMethod 6019 public void setVisibility(int visibility) { 6020 setFlags(visibility, VISIBILITY_MASK); 6021 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6022 } 6023 6024 /** 6025 * Returns the enabled status for this view. The interpretation of the 6026 * enabled state varies by subclass. 6027 * 6028 * @return True if this view is enabled, false otherwise. 6029 */ 6030 @ViewDebug.ExportedProperty 6031 public boolean isEnabled() { 6032 return (mViewFlags & ENABLED_MASK) == ENABLED; 6033 } 6034 6035 /** 6036 * Set the enabled state of this view. The interpretation of the enabled 6037 * state varies by subclass. 6038 * 6039 * @param enabled True if this view is enabled, false otherwise. 6040 */ 6041 @RemotableViewMethod 6042 public void setEnabled(boolean enabled) { 6043 if (enabled == isEnabled()) return; 6044 6045 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6046 6047 /* 6048 * The View most likely has to change its appearance, so refresh 6049 * the drawable state. 6050 */ 6051 refreshDrawableState(); 6052 6053 // Invalidate too, since the default behavior for views is to be 6054 // be drawn at 50% alpha rather than to change the drawable. 6055 invalidate(true); 6056 6057 if (!enabled) { 6058 cancelPendingInputEvents(); 6059 } 6060 } 6061 6062 /** 6063 * Set whether this view can receive the focus. 6064 * 6065 * Setting this to false will also ensure that this view is not focusable 6066 * in touch mode. 6067 * 6068 * @param focusable If true, this view can receive the focus. 6069 * 6070 * @see #setFocusableInTouchMode(boolean) 6071 * @attr ref android.R.styleable#View_focusable 6072 */ 6073 public void setFocusable(boolean focusable) { 6074 if (!focusable) { 6075 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6076 } 6077 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6078 } 6079 6080 /** 6081 * Set whether this view can receive focus while in touch mode. 6082 * 6083 * Setting this to true will also ensure that this view is focusable. 6084 * 6085 * @param focusableInTouchMode If true, this view can receive the focus while 6086 * in touch mode. 6087 * 6088 * @see #setFocusable(boolean) 6089 * @attr ref android.R.styleable#View_focusableInTouchMode 6090 */ 6091 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6092 // Focusable in touch mode should always be set before the focusable flag 6093 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6094 // which, in touch mode, will not successfully request focus on this view 6095 // because the focusable in touch mode flag is not set 6096 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6097 if (focusableInTouchMode) { 6098 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6099 } 6100 } 6101 6102 /** 6103 * Set whether this view should have sound effects enabled for events such as 6104 * clicking and touching. 6105 * 6106 * <p>You may wish to disable sound effects for a view if you already play sounds, 6107 * for instance, a dial key that plays dtmf tones. 6108 * 6109 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6110 * @see #isSoundEffectsEnabled() 6111 * @see #playSoundEffect(int) 6112 * @attr ref android.R.styleable#View_soundEffectsEnabled 6113 */ 6114 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6115 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6116 } 6117 6118 /** 6119 * @return whether this view should have sound effects enabled for events such as 6120 * clicking and touching. 6121 * 6122 * @see #setSoundEffectsEnabled(boolean) 6123 * @see #playSoundEffect(int) 6124 * @attr ref android.R.styleable#View_soundEffectsEnabled 6125 */ 6126 @ViewDebug.ExportedProperty 6127 public boolean isSoundEffectsEnabled() { 6128 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6129 } 6130 6131 /** 6132 * Set whether this view should have haptic feedback for events such as 6133 * long presses. 6134 * 6135 * <p>You may wish to disable haptic feedback if your view already controls 6136 * its own haptic feedback. 6137 * 6138 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6139 * @see #isHapticFeedbackEnabled() 6140 * @see #performHapticFeedback(int) 6141 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6142 */ 6143 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6144 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6145 } 6146 6147 /** 6148 * @return whether this view should have haptic feedback enabled for events 6149 * long presses. 6150 * 6151 * @see #setHapticFeedbackEnabled(boolean) 6152 * @see #performHapticFeedback(int) 6153 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6154 */ 6155 @ViewDebug.ExportedProperty 6156 public boolean isHapticFeedbackEnabled() { 6157 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6158 } 6159 6160 /** 6161 * Returns the layout direction for this view. 6162 * 6163 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6164 * {@link #LAYOUT_DIRECTION_RTL}, 6165 * {@link #LAYOUT_DIRECTION_INHERIT} or 6166 * {@link #LAYOUT_DIRECTION_LOCALE}. 6167 * 6168 * @attr ref android.R.styleable#View_layoutDirection 6169 * 6170 * @hide 6171 */ 6172 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6173 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6174 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6175 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6176 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6177 }) 6178 public int getRawLayoutDirection() { 6179 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6180 } 6181 6182 /** 6183 * Set the layout direction for this view. This will propagate a reset of layout direction 6184 * resolution to the view's children and resolve layout direction for this view. 6185 * 6186 * @param layoutDirection the layout direction to set. Should be one of: 6187 * 6188 * {@link #LAYOUT_DIRECTION_LTR}, 6189 * {@link #LAYOUT_DIRECTION_RTL}, 6190 * {@link #LAYOUT_DIRECTION_INHERIT}, 6191 * {@link #LAYOUT_DIRECTION_LOCALE}. 6192 * 6193 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6194 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6195 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6196 * 6197 * @attr ref android.R.styleable#View_layoutDirection 6198 */ 6199 @RemotableViewMethod 6200 public void setLayoutDirection(int layoutDirection) { 6201 if (getRawLayoutDirection() != layoutDirection) { 6202 // Reset the current layout direction and the resolved one 6203 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6204 resetRtlProperties(); 6205 // Set the new layout direction (filtered) 6206 mPrivateFlags2 |= 6207 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6208 // We need to resolve all RTL properties as they all depend on layout direction 6209 resolveRtlPropertiesIfNeeded(); 6210 requestLayout(); 6211 invalidate(true); 6212 } 6213 } 6214 6215 /** 6216 * Returns the resolved layout direction for this view. 6217 * 6218 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6219 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6220 * 6221 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6222 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6223 * 6224 * @attr ref android.R.styleable#View_layoutDirection 6225 */ 6226 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6227 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6228 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6229 }) 6230 public int getLayoutDirection() { 6231 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6232 if (targetSdkVersion < JELLY_BEAN_MR1) { 6233 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6234 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6235 } 6236 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6237 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6238 } 6239 6240 /** 6241 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6242 * layout attribute and/or the inherited value from the parent 6243 * 6244 * @return true if the layout is right-to-left. 6245 * 6246 * @hide 6247 */ 6248 @ViewDebug.ExportedProperty(category = "layout") 6249 public boolean isLayoutRtl() { 6250 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6251 } 6252 6253 /** 6254 * Indicates whether the view is currently tracking transient state that the 6255 * app should not need to concern itself with saving and restoring, but that 6256 * the framework should take special note to preserve when possible. 6257 * 6258 * <p>A view with transient state cannot be trivially rebound from an external 6259 * data source, such as an adapter binding item views in a list. This may be 6260 * because the view is performing an animation, tracking user selection 6261 * of content, or similar.</p> 6262 * 6263 * @return true if the view has transient state 6264 */ 6265 @ViewDebug.ExportedProperty(category = "layout") 6266 public boolean hasTransientState() { 6267 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6268 } 6269 6270 /** 6271 * Set whether this view is currently tracking transient state that the 6272 * framework should attempt to preserve when possible. This flag is reference counted, 6273 * so every call to setHasTransientState(true) should be paired with a later call 6274 * to setHasTransientState(false). 6275 * 6276 * <p>A view with transient state cannot be trivially rebound from an external 6277 * data source, such as an adapter binding item views in a list. This may be 6278 * because the view is performing an animation, tracking user selection 6279 * of content, or similar.</p> 6280 * 6281 * @param hasTransientState true if this view has transient state 6282 */ 6283 public void setHasTransientState(boolean hasTransientState) { 6284 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6285 mTransientStateCount - 1; 6286 if (mTransientStateCount < 0) { 6287 mTransientStateCount = 0; 6288 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6289 "unmatched pair of setHasTransientState calls"); 6290 } else if ((hasTransientState && mTransientStateCount == 1) || 6291 (!hasTransientState && mTransientStateCount == 0)) { 6292 // update flag if we've just incremented up from 0 or decremented down to 0 6293 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6294 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6295 if (mParent != null) { 6296 try { 6297 mParent.childHasTransientStateChanged(this, hasTransientState); 6298 } catch (AbstractMethodError e) { 6299 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6300 " does not fully implement ViewParent", e); 6301 } 6302 } 6303 } 6304 } 6305 6306 /** 6307 * Returns true if this view is currently attached to a window. 6308 */ 6309 public boolean isAttachedToWindow() { 6310 return mAttachInfo != null; 6311 } 6312 6313 /** 6314 * Returns true if this view has been through at least one layout since it 6315 * was last attached to or detached from a window. 6316 */ 6317 public boolean isLaidOut() { 6318 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6319 } 6320 6321 /** 6322 * If this view doesn't do any drawing on its own, set this flag to 6323 * allow further optimizations. By default, this flag is not set on 6324 * View, but could be set on some View subclasses such as ViewGroup. 6325 * 6326 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6327 * you should clear this flag. 6328 * 6329 * @param willNotDraw whether or not this View draw on its own 6330 */ 6331 public void setWillNotDraw(boolean willNotDraw) { 6332 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6333 } 6334 6335 /** 6336 * Returns whether or not this View draws on its own. 6337 * 6338 * @return true if this view has nothing to draw, false otherwise 6339 */ 6340 @ViewDebug.ExportedProperty(category = "drawing") 6341 public boolean willNotDraw() { 6342 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6343 } 6344 6345 /** 6346 * When a View's drawing cache is enabled, drawing is redirected to an 6347 * offscreen bitmap. Some views, like an ImageView, must be able to 6348 * bypass this mechanism if they already draw a single bitmap, to avoid 6349 * unnecessary usage of the memory. 6350 * 6351 * @param willNotCacheDrawing true if this view does not cache its 6352 * drawing, false otherwise 6353 */ 6354 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6355 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6356 } 6357 6358 /** 6359 * Returns whether or not this View can cache its drawing or not. 6360 * 6361 * @return true if this view does not cache its drawing, false otherwise 6362 */ 6363 @ViewDebug.ExportedProperty(category = "drawing") 6364 public boolean willNotCacheDrawing() { 6365 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6366 } 6367 6368 /** 6369 * Indicates whether this view reacts to click events or not. 6370 * 6371 * @return true if the view is clickable, false otherwise 6372 * 6373 * @see #setClickable(boolean) 6374 * @attr ref android.R.styleable#View_clickable 6375 */ 6376 @ViewDebug.ExportedProperty 6377 public boolean isClickable() { 6378 return (mViewFlags & CLICKABLE) == CLICKABLE; 6379 } 6380 6381 /** 6382 * Enables or disables click events for this view. When a view 6383 * is clickable it will change its state to "pressed" on every click. 6384 * Subclasses should set the view clickable to visually react to 6385 * user's clicks. 6386 * 6387 * @param clickable true to make the view clickable, false otherwise 6388 * 6389 * @see #isClickable() 6390 * @attr ref android.R.styleable#View_clickable 6391 */ 6392 public void setClickable(boolean clickable) { 6393 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6394 } 6395 6396 /** 6397 * Indicates whether this view reacts to long click events or not. 6398 * 6399 * @return true if the view is long clickable, false otherwise 6400 * 6401 * @see #setLongClickable(boolean) 6402 * @attr ref android.R.styleable#View_longClickable 6403 */ 6404 public boolean isLongClickable() { 6405 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6406 } 6407 6408 /** 6409 * Enables or disables long click events for this view. When a view is long 6410 * clickable it reacts to the user holding down the button for a longer 6411 * duration than a tap. This event can either launch the listener or a 6412 * context menu. 6413 * 6414 * @param longClickable true to make the view long clickable, false otherwise 6415 * @see #isLongClickable() 6416 * @attr ref android.R.styleable#View_longClickable 6417 */ 6418 public void setLongClickable(boolean longClickable) { 6419 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6420 } 6421 6422 /** 6423 * Sets the pressed state for this view. 6424 * 6425 * @see #isClickable() 6426 * @see #setClickable(boolean) 6427 * 6428 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6429 * the View's internal state from a previously set "pressed" state. 6430 */ 6431 public void setPressed(boolean pressed) { 6432 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6433 6434 if (pressed) { 6435 mPrivateFlags |= PFLAG_PRESSED; 6436 } else { 6437 mPrivateFlags &= ~PFLAG_PRESSED; 6438 } 6439 6440 if (needsRefresh) { 6441 refreshDrawableState(); 6442 } 6443 dispatchSetPressed(pressed); 6444 } 6445 6446 /** 6447 * Dispatch setPressed to all of this View's children. 6448 * 6449 * @see #setPressed(boolean) 6450 * 6451 * @param pressed The new pressed state 6452 */ 6453 protected void dispatchSetPressed(boolean pressed) { 6454 } 6455 6456 /** 6457 * Indicates whether the view is currently in pressed state. Unless 6458 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6459 * the pressed state. 6460 * 6461 * @see #setPressed(boolean) 6462 * @see #isClickable() 6463 * @see #setClickable(boolean) 6464 * 6465 * @return true if the view is currently pressed, false otherwise 6466 */ 6467 public boolean isPressed() { 6468 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6469 } 6470 6471 /** 6472 * Indicates whether this view will save its state (that is, 6473 * whether its {@link #onSaveInstanceState} method will be called). 6474 * 6475 * @return Returns true if the view state saving is enabled, else false. 6476 * 6477 * @see #setSaveEnabled(boolean) 6478 * @attr ref android.R.styleable#View_saveEnabled 6479 */ 6480 public boolean isSaveEnabled() { 6481 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6482 } 6483 6484 /** 6485 * Controls whether the saving of this view's state is 6486 * enabled (that is, whether its {@link #onSaveInstanceState} method 6487 * will be called). Note that even if freezing is enabled, the 6488 * view still must have an id assigned to it (via {@link #setId(int)}) 6489 * for its state to be saved. This flag can only disable the 6490 * saving of this view; any child views may still have their state saved. 6491 * 6492 * @param enabled Set to false to <em>disable</em> state saving, or true 6493 * (the default) to allow it. 6494 * 6495 * @see #isSaveEnabled() 6496 * @see #setId(int) 6497 * @see #onSaveInstanceState() 6498 * @attr ref android.R.styleable#View_saveEnabled 6499 */ 6500 public void setSaveEnabled(boolean enabled) { 6501 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6502 } 6503 6504 /** 6505 * Gets whether the framework should discard touches when the view's 6506 * window is obscured by another visible window. 6507 * Refer to the {@link View} security documentation for more details. 6508 * 6509 * @return True if touch filtering is enabled. 6510 * 6511 * @see #setFilterTouchesWhenObscured(boolean) 6512 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6513 */ 6514 @ViewDebug.ExportedProperty 6515 public boolean getFilterTouchesWhenObscured() { 6516 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6517 } 6518 6519 /** 6520 * Sets whether the framework should discard touches when the view's 6521 * window is obscured by another visible window. 6522 * Refer to the {@link View} security documentation for more details. 6523 * 6524 * @param enabled True if touch filtering should be enabled. 6525 * 6526 * @see #getFilterTouchesWhenObscured 6527 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6528 */ 6529 public void setFilterTouchesWhenObscured(boolean enabled) { 6530 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 6531 FILTER_TOUCHES_WHEN_OBSCURED); 6532 } 6533 6534 /** 6535 * Indicates whether the entire hierarchy under this view will save its 6536 * state when a state saving traversal occurs from its parent. The default 6537 * is true; if false, these views will not be saved unless 6538 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6539 * 6540 * @return Returns true if the view state saving from parent is enabled, else false. 6541 * 6542 * @see #setSaveFromParentEnabled(boolean) 6543 */ 6544 public boolean isSaveFromParentEnabled() { 6545 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6546 } 6547 6548 /** 6549 * Controls whether the entire hierarchy under this view will save its 6550 * state when a state saving traversal occurs from its parent. The default 6551 * is true; if false, these views will not be saved unless 6552 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6553 * 6554 * @param enabled Set to false to <em>disable</em> state saving, or true 6555 * (the default) to allow it. 6556 * 6557 * @see #isSaveFromParentEnabled() 6558 * @see #setId(int) 6559 * @see #onSaveInstanceState() 6560 */ 6561 public void setSaveFromParentEnabled(boolean enabled) { 6562 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6563 } 6564 6565 6566 /** 6567 * Returns whether this View is able to take focus. 6568 * 6569 * @return True if this view can take focus, or false otherwise. 6570 * @attr ref android.R.styleable#View_focusable 6571 */ 6572 @ViewDebug.ExportedProperty(category = "focus") 6573 public final boolean isFocusable() { 6574 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6575 } 6576 6577 /** 6578 * When a view is focusable, it may not want to take focus when in touch mode. 6579 * For example, a button would like focus when the user is navigating via a D-pad 6580 * so that the user can click on it, but once the user starts touching the screen, 6581 * the button shouldn't take focus 6582 * @return Whether the view is focusable in touch mode. 6583 * @attr ref android.R.styleable#View_focusableInTouchMode 6584 */ 6585 @ViewDebug.ExportedProperty 6586 public final boolean isFocusableInTouchMode() { 6587 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6588 } 6589 6590 /** 6591 * Find the nearest view in the specified direction that can take focus. 6592 * This does not actually give focus to that view. 6593 * 6594 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6595 * 6596 * @return The nearest focusable in the specified direction, or null if none 6597 * can be found. 6598 */ 6599 public View focusSearch(int direction) { 6600 if (mParent != null) { 6601 return mParent.focusSearch(this, direction); 6602 } else { 6603 return null; 6604 } 6605 } 6606 6607 /** 6608 * This method is the last chance for the focused view and its ancestors to 6609 * respond to an arrow key. This is called when the focused view did not 6610 * consume the key internally, nor could the view system find a new view in 6611 * the requested direction to give focus to. 6612 * 6613 * @param focused The currently focused view. 6614 * @param direction The direction focus wants to move. One of FOCUS_UP, 6615 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6616 * @return True if the this view consumed this unhandled move. 6617 */ 6618 public boolean dispatchUnhandledMove(View focused, int direction) { 6619 return false; 6620 } 6621 6622 /** 6623 * If a user manually specified the next view id for a particular direction, 6624 * use the root to look up the view. 6625 * @param root The root view of the hierarchy containing this view. 6626 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6627 * or FOCUS_BACKWARD. 6628 * @return The user specified next view, or null if there is none. 6629 */ 6630 View findUserSetNextFocus(View root, int direction) { 6631 switch (direction) { 6632 case FOCUS_LEFT: 6633 if (mNextFocusLeftId == View.NO_ID) return null; 6634 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6635 case FOCUS_RIGHT: 6636 if (mNextFocusRightId == View.NO_ID) return null; 6637 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6638 case FOCUS_UP: 6639 if (mNextFocusUpId == View.NO_ID) return null; 6640 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6641 case FOCUS_DOWN: 6642 if (mNextFocusDownId == View.NO_ID) return null; 6643 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6644 case FOCUS_FORWARD: 6645 if (mNextFocusForwardId == View.NO_ID) return null; 6646 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6647 case FOCUS_BACKWARD: { 6648 if (mID == View.NO_ID) return null; 6649 final int id = mID; 6650 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6651 @Override 6652 public boolean apply(View t) { 6653 return t.mNextFocusForwardId == id; 6654 } 6655 }); 6656 } 6657 } 6658 return null; 6659 } 6660 6661 private View findViewInsideOutShouldExist(View root, int id) { 6662 if (mMatchIdPredicate == null) { 6663 mMatchIdPredicate = new MatchIdPredicate(); 6664 } 6665 mMatchIdPredicate.mId = id; 6666 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 6667 if (result == null) { 6668 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 6669 } 6670 return result; 6671 } 6672 6673 /** 6674 * Find and return all focusable views that are descendants of this view, 6675 * possibly including this view if it is focusable itself. 6676 * 6677 * @param direction The direction of the focus 6678 * @return A list of focusable views 6679 */ 6680 public ArrayList<View> getFocusables(int direction) { 6681 ArrayList<View> result = new ArrayList<View>(24); 6682 addFocusables(result, direction); 6683 return result; 6684 } 6685 6686 /** 6687 * Add any focusable views that are descendants of this view (possibly 6688 * including this view if it is focusable itself) to views. If we are in touch mode, 6689 * only add views that are also focusable in touch mode. 6690 * 6691 * @param views Focusable views found so far 6692 * @param direction The direction of the focus 6693 */ 6694 public void addFocusables(ArrayList<View> views, int direction) { 6695 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 6696 } 6697 6698 /** 6699 * Adds any focusable views that are descendants of this view (possibly 6700 * including this view if it is focusable itself) to views. This method 6701 * adds all focusable views regardless if we are in touch mode or 6702 * only views focusable in touch mode if we are in touch mode or 6703 * only views that can take accessibility focus if accessibility is enabeld 6704 * depending on the focusable mode paramater. 6705 * 6706 * @param views Focusable views found so far or null if all we are interested is 6707 * the number of focusables. 6708 * @param direction The direction of the focus. 6709 * @param focusableMode The type of focusables to be added. 6710 * 6711 * @see #FOCUSABLES_ALL 6712 * @see #FOCUSABLES_TOUCH_MODE 6713 */ 6714 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 6715 if (views == null) { 6716 return; 6717 } 6718 if (!isFocusable()) { 6719 return; 6720 } 6721 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 6722 && isInTouchMode() && !isFocusableInTouchMode()) { 6723 return; 6724 } 6725 views.add(this); 6726 } 6727 6728 /** 6729 * Finds the Views that contain given text. The containment is case insensitive. 6730 * The search is performed by either the text that the View renders or the content 6731 * description that describes the view for accessibility purposes and the view does 6732 * not render or both. Clients can specify how the search is to be performed via 6733 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 6734 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 6735 * 6736 * @param outViews The output list of matching Views. 6737 * @param searched The text to match against. 6738 * 6739 * @see #FIND_VIEWS_WITH_TEXT 6740 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 6741 * @see #setContentDescription(CharSequence) 6742 */ 6743 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 6744 if (getAccessibilityNodeProvider() != null) { 6745 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 6746 outViews.add(this); 6747 } 6748 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 6749 && (searched != null && searched.length() > 0) 6750 && (mContentDescription != null && mContentDescription.length() > 0)) { 6751 String searchedLowerCase = searched.toString().toLowerCase(); 6752 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 6753 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 6754 outViews.add(this); 6755 } 6756 } 6757 } 6758 6759 /** 6760 * Find and return all touchable views that are descendants of this view, 6761 * possibly including this view if it is touchable itself. 6762 * 6763 * @return A list of touchable views 6764 */ 6765 public ArrayList<View> getTouchables() { 6766 ArrayList<View> result = new ArrayList<View>(); 6767 addTouchables(result); 6768 return result; 6769 } 6770 6771 /** 6772 * Add any touchable views that are descendants of this view (possibly 6773 * including this view if it is touchable itself) to views. 6774 * 6775 * @param views Touchable views found so far 6776 */ 6777 public void addTouchables(ArrayList<View> views) { 6778 final int viewFlags = mViewFlags; 6779 6780 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 6781 && (viewFlags & ENABLED_MASK) == ENABLED) { 6782 views.add(this); 6783 } 6784 } 6785 6786 /** 6787 * Returns whether this View is accessibility focused. 6788 * 6789 * @return True if this View is accessibility focused. 6790 * @hide 6791 */ 6792 public boolean isAccessibilityFocused() { 6793 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 6794 } 6795 6796 /** 6797 * Call this to try to give accessibility focus to this view. 6798 * 6799 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 6800 * returns false or the view is no visible or the view already has accessibility 6801 * focus. 6802 * 6803 * See also {@link #focusSearch(int)}, which is what you call to say that you 6804 * have focus, and you want your parent to look for the next one. 6805 * 6806 * @return Whether this view actually took accessibility focus. 6807 * 6808 * @hide 6809 */ 6810 public boolean requestAccessibilityFocus() { 6811 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 6812 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 6813 return false; 6814 } 6815 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6816 return false; 6817 } 6818 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 6819 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 6820 ViewRootImpl viewRootImpl = getViewRootImpl(); 6821 if (viewRootImpl != null) { 6822 viewRootImpl.setAccessibilityFocus(this, null); 6823 } 6824 invalidate(); 6825 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 6826 return true; 6827 } 6828 return false; 6829 } 6830 6831 /** 6832 * Call this to try to clear accessibility focus of this view. 6833 * 6834 * See also {@link #focusSearch(int)}, which is what you call to say that you 6835 * have focus, and you want your parent to look for the next one. 6836 * 6837 * @hide 6838 */ 6839 public void clearAccessibilityFocus() { 6840 clearAccessibilityFocusNoCallbacks(); 6841 // Clear the global reference of accessibility focus if this 6842 // view or any of its descendants had accessibility focus. 6843 ViewRootImpl viewRootImpl = getViewRootImpl(); 6844 if (viewRootImpl != null) { 6845 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 6846 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 6847 viewRootImpl.setAccessibilityFocus(null, null); 6848 } 6849 } 6850 } 6851 6852 private void sendAccessibilityHoverEvent(int eventType) { 6853 // Since we are not delivering to a client accessibility events from not 6854 // important views (unless the clinet request that) we need to fire the 6855 // event from the deepest view exposed to the client. As a consequence if 6856 // the user crosses a not exposed view the client will see enter and exit 6857 // of the exposed predecessor followed by and enter and exit of that same 6858 // predecessor when entering and exiting the not exposed descendant. This 6859 // is fine since the client has a clear idea which view is hovered at the 6860 // price of a couple more events being sent. This is a simple and 6861 // working solution. 6862 View source = this; 6863 while (true) { 6864 if (source.includeForAccessibility()) { 6865 source.sendAccessibilityEvent(eventType); 6866 return; 6867 } 6868 ViewParent parent = source.getParent(); 6869 if (parent instanceof View) { 6870 source = (View) parent; 6871 } else { 6872 return; 6873 } 6874 } 6875 } 6876 6877 /** 6878 * Clears accessibility focus without calling any callback methods 6879 * normally invoked in {@link #clearAccessibilityFocus()}. This method 6880 * is used for clearing accessibility focus when giving this focus to 6881 * another view. 6882 */ 6883 void clearAccessibilityFocusNoCallbacks() { 6884 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 6885 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 6886 invalidate(); 6887 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 6888 } 6889 } 6890 6891 /** 6892 * Call this to try to give focus to a specific view or to one of its 6893 * descendants. 6894 * 6895 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6896 * false), or if it is focusable and it is not focusable in touch mode 6897 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6898 * 6899 * See also {@link #focusSearch(int)}, which is what you call to say that you 6900 * have focus, and you want your parent to look for the next one. 6901 * 6902 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 6903 * {@link #FOCUS_DOWN} and <code>null</code>. 6904 * 6905 * @return Whether this view or one of its descendants actually took focus. 6906 */ 6907 public final boolean requestFocus() { 6908 return requestFocus(View.FOCUS_DOWN); 6909 } 6910 6911 /** 6912 * Call this to try to give focus to a specific view or to one of its 6913 * descendants and give it a hint about what direction focus is heading. 6914 * 6915 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6916 * false), or if it is focusable and it is not focusable in touch mode 6917 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6918 * 6919 * See also {@link #focusSearch(int)}, which is what you call to say that you 6920 * have focus, and you want your parent to look for the next one. 6921 * 6922 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 6923 * <code>null</code> set for the previously focused rectangle. 6924 * 6925 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6926 * @return Whether this view or one of its descendants actually took focus. 6927 */ 6928 public final boolean requestFocus(int direction) { 6929 return requestFocus(direction, null); 6930 } 6931 6932 /** 6933 * Call this to try to give focus to a specific view or to one of its descendants 6934 * and give it hints about the direction and a specific rectangle that the focus 6935 * is coming from. The rectangle can help give larger views a finer grained hint 6936 * about where focus is coming from, and therefore, where to show selection, or 6937 * forward focus change internally. 6938 * 6939 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6940 * false), or if it is focusable and it is not focusable in touch mode 6941 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6942 * 6943 * A View will not take focus if it is not visible. 6944 * 6945 * A View will not take focus if one of its parents has 6946 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 6947 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 6948 * 6949 * See also {@link #focusSearch(int)}, which is what you call to say that you 6950 * have focus, and you want your parent to look for the next one. 6951 * 6952 * You may wish to override this method if your custom {@link View} has an internal 6953 * {@link View} that it wishes to forward the request to. 6954 * 6955 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6956 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 6957 * to give a finer grained hint about where focus is coming from. May be null 6958 * if there is no hint. 6959 * @return Whether this view or one of its descendants actually took focus. 6960 */ 6961 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 6962 return requestFocusNoSearch(direction, previouslyFocusedRect); 6963 } 6964 6965 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 6966 // need to be focusable 6967 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 6968 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6969 return false; 6970 } 6971 6972 // need to be focusable in touch mode if in touch mode 6973 if (isInTouchMode() && 6974 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 6975 return false; 6976 } 6977 6978 // need to not have any parents blocking us 6979 if (hasAncestorThatBlocksDescendantFocus()) { 6980 return false; 6981 } 6982 6983 handleFocusGainInternal(direction, previouslyFocusedRect); 6984 return true; 6985 } 6986 6987 /** 6988 * Call this to try to give focus to a specific view or to one of its descendants. This is a 6989 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 6990 * touch mode to request focus when they are touched. 6991 * 6992 * @return Whether this view or one of its descendants actually took focus. 6993 * 6994 * @see #isInTouchMode() 6995 * 6996 */ 6997 public final boolean requestFocusFromTouch() { 6998 // Leave touch mode if we need to 6999 if (isInTouchMode()) { 7000 ViewRootImpl viewRoot = getViewRootImpl(); 7001 if (viewRoot != null) { 7002 viewRoot.ensureTouchMode(false); 7003 } 7004 } 7005 return requestFocus(View.FOCUS_DOWN); 7006 } 7007 7008 /** 7009 * @return Whether any ancestor of this view blocks descendant focus. 7010 */ 7011 private boolean hasAncestorThatBlocksDescendantFocus() { 7012 ViewParent ancestor = mParent; 7013 while (ancestor instanceof ViewGroup) { 7014 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7015 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 7016 return true; 7017 } else { 7018 ancestor = vgAncestor.getParent(); 7019 } 7020 } 7021 return false; 7022 } 7023 7024 /** 7025 * Gets the mode for determining whether this View is important for accessibility 7026 * which is if it fires accessibility events and if it is reported to 7027 * accessibility services that query the screen. 7028 * 7029 * @return The mode for determining whether a View is important for accessibility. 7030 * 7031 * @attr ref android.R.styleable#View_importantForAccessibility 7032 * 7033 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7034 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7035 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7036 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7037 */ 7038 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7039 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7040 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7041 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7042 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7043 to = "noHideDescendants") 7044 }) 7045 public int getImportantForAccessibility() { 7046 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7047 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7048 } 7049 7050 /** 7051 * Sets the live region mode for this view. This indicates to accessibility 7052 * services whether they should automatically notify the user about changes 7053 * to the view's content description or text, or to the content descriptions 7054 * or text of the view's children (where applicable). 7055 * <p> 7056 * For example, in a login screen with a TextView that displays an "incorrect 7057 * password" notification, that view should be marked as a live region with 7058 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7059 * <p> 7060 * To disable change notifications for this view, use 7061 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7062 * mode for most views. 7063 * <p> 7064 * To indicate that the user should be notified of changes, use 7065 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7066 * <p> 7067 * If the view's changes should interrupt ongoing speech and notify the user 7068 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7069 * 7070 * @param mode The live region mode for this view, one of: 7071 * <ul> 7072 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7073 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7074 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7075 * </ul> 7076 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7077 */ 7078 public void setAccessibilityLiveRegion(int mode) { 7079 if (mode != getAccessibilityLiveRegion()) { 7080 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7081 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7082 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7083 notifyViewAccessibilityStateChangedIfNeeded( 7084 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7085 } 7086 } 7087 7088 /** 7089 * Gets the live region mode for this View. 7090 * 7091 * @return The live region mode for the view. 7092 * 7093 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7094 * 7095 * @see #setAccessibilityLiveRegion(int) 7096 */ 7097 public int getAccessibilityLiveRegion() { 7098 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7099 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7100 } 7101 7102 /** 7103 * Sets how to determine whether this view is important for accessibility 7104 * which is if it fires accessibility events and if it is reported to 7105 * accessibility services that query the screen. 7106 * 7107 * @param mode How to determine whether this view is important for accessibility. 7108 * 7109 * @attr ref android.R.styleable#View_importantForAccessibility 7110 * 7111 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7112 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7113 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7114 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7115 */ 7116 public void setImportantForAccessibility(int mode) { 7117 final int oldMode = getImportantForAccessibility(); 7118 if (mode != oldMode) { 7119 // If we're moving between AUTO and another state, we might not need 7120 // to send a subtree changed notification. We'll store the computed 7121 // importance, since we'll need to check it later to make sure. 7122 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7123 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7124 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7125 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7126 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7127 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7128 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7129 notifySubtreeAccessibilityStateChangedIfNeeded(); 7130 } else { 7131 notifyViewAccessibilityStateChangedIfNeeded( 7132 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7133 } 7134 } 7135 } 7136 7137 /** 7138 * Gets whether this view should be exposed for accessibility. 7139 * 7140 * @return Whether the view is exposed for accessibility. 7141 * 7142 * @hide 7143 */ 7144 public boolean isImportantForAccessibility() { 7145 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7146 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7147 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7148 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7149 return false; 7150 } 7151 7152 // Check parent mode to ensure we're not hidden. 7153 ViewParent parent = mParent; 7154 while (parent instanceof View) { 7155 if (((View) parent).getImportantForAccessibility() 7156 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7157 return false; 7158 } 7159 parent = parent.getParent(); 7160 } 7161 7162 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7163 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7164 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7165 } 7166 7167 /** 7168 * Gets the parent for accessibility purposes. Note that the parent for 7169 * accessibility is not necessary the immediate parent. It is the first 7170 * predecessor that is important for accessibility. 7171 * 7172 * @return The parent for accessibility purposes. 7173 */ 7174 public ViewParent getParentForAccessibility() { 7175 if (mParent instanceof View) { 7176 View parentView = (View) mParent; 7177 if (parentView.includeForAccessibility()) { 7178 return mParent; 7179 } else { 7180 return mParent.getParentForAccessibility(); 7181 } 7182 } 7183 return null; 7184 } 7185 7186 /** 7187 * Adds the children of a given View for accessibility. Since some Views are 7188 * not important for accessibility the children for accessibility are not 7189 * necessarily direct children of the view, rather they are the first level of 7190 * descendants important for accessibility. 7191 * 7192 * @param children The list of children for accessibility. 7193 */ 7194 public void addChildrenForAccessibility(ArrayList<View> children) { 7195 if (includeForAccessibility()) { 7196 children.add(this); 7197 } 7198 } 7199 7200 /** 7201 * Whether to regard this view for accessibility. A view is regarded for 7202 * accessibility if it is important for accessibility or the querying 7203 * accessibility service has explicitly requested that view not 7204 * important for accessibility are regarded. 7205 * 7206 * @return Whether to regard the view for accessibility. 7207 * 7208 * @hide 7209 */ 7210 public boolean includeForAccessibility() { 7211 //noinspection SimplifiableIfStatement 7212 if (mAttachInfo != null) { 7213 return (mAttachInfo.mAccessibilityFetchFlags 7214 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7215 || isImportantForAccessibility(); 7216 } 7217 return false; 7218 } 7219 7220 /** 7221 * Returns whether the View is considered actionable from 7222 * accessibility perspective. Such view are important for 7223 * accessibility. 7224 * 7225 * @return True if the view is actionable for accessibility. 7226 * 7227 * @hide 7228 */ 7229 public boolean isActionableForAccessibility() { 7230 return (isClickable() || isLongClickable() || isFocusable()); 7231 } 7232 7233 /** 7234 * Returns whether the View has registered callbacks wich makes it 7235 * important for accessibility. 7236 * 7237 * @return True if the view is actionable for accessibility. 7238 */ 7239 private boolean hasListenersForAccessibility() { 7240 ListenerInfo info = getListenerInfo(); 7241 return mTouchDelegate != null || info.mOnKeyListener != null 7242 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7243 || info.mOnHoverListener != null || info.mOnDragListener != null; 7244 } 7245 7246 /** 7247 * Notifies that the accessibility state of this view changed. The change 7248 * is local to this view and does not represent structural changes such 7249 * as children and parent. For example, the view became focusable. The 7250 * notification is at at most once every 7251 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7252 * to avoid unnecessary load to the system. Also once a view has a pending 7253 * notifucation this method is a NOP until the notification has been sent. 7254 * 7255 * @hide 7256 */ 7257 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7258 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7259 return; 7260 } 7261 if (mSendViewStateChangedAccessibilityEvent == null) { 7262 mSendViewStateChangedAccessibilityEvent = 7263 new SendViewStateChangedAccessibilityEvent(); 7264 } 7265 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7266 } 7267 7268 /** 7269 * Notifies that the accessibility state of this view changed. The change 7270 * is *not* local to this view and does represent structural changes such 7271 * as children and parent. For example, the view size changed. The 7272 * notification is at at most once every 7273 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7274 * to avoid unnecessary load to the system. Also once a view has a pending 7275 * notifucation this method is a NOP until the notification has been sent. 7276 * 7277 * @hide 7278 */ 7279 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7280 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7281 return; 7282 } 7283 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7284 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7285 if (mParent != null) { 7286 try { 7287 mParent.notifySubtreeAccessibilityStateChanged( 7288 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7289 } catch (AbstractMethodError e) { 7290 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7291 " does not fully implement ViewParent", e); 7292 } 7293 } 7294 } 7295 } 7296 7297 /** 7298 * Reset the flag indicating the accessibility state of the subtree rooted 7299 * at this view changed. 7300 */ 7301 void resetSubtreeAccessibilityStateChanged() { 7302 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7303 } 7304 7305 /** 7306 * Performs the specified accessibility action on the view. For 7307 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7308 * <p> 7309 * If an {@link AccessibilityDelegate} has been specified via calling 7310 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7311 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7312 * is responsible for handling this call. 7313 * </p> 7314 * 7315 * @param action The action to perform. 7316 * @param arguments Optional action arguments. 7317 * @return Whether the action was performed. 7318 */ 7319 public boolean performAccessibilityAction(int action, Bundle arguments) { 7320 if (mAccessibilityDelegate != null) { 7321 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7322 } else { 7323 return performAccessibilityActionInternal(action, arguments); 7324 } 7325 } 7326 7327 /** 7328 * @see #performAccessibilityAction(int, Bundle) 7329 * 7330 * Note: Called from the default {@link AccessibilityDelegate}. 7331 */ 7332 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7333 switch (action) { 7334 case AccessibilityNodeInfo.ACTION_CLICK: { 7335 if (isClickable()) { 7336 performClick(); 7337 return true; 7338 } 7339 } break; 7340 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7341 if (isLongClickable()) { 7342 performLongClick(); 7343 return true; 7344 } 7345 } break; 7346 case AccessibilityNodeInfo.ACTION_FOCUS: { 7347 if (!hasFocus()) { 7348 // Get out of touch mode since accessibility 7349 // wants to move focus around. 7350 getViewRootImpl().ensureTouchMode(false); 7351 return requestFocus(); 7352 } 7353 } break; 7354 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7355 if (hasFocus()) { 7356 clearFocus(); 7357 return !isFocused(); 7358 } 7359 } break; 7360 case AccessibilityNodeInfo.ACTION_SELECT: { 7361 if (!isSelected()) { 7362 setSelected(true); 7363 return isSelected(); 7364 } 7365 } break; 7366 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7367 if (isSelected()) { 7368 setSelected(false); 7369 return !isSelected(); 7370 } 7371 } break; 7372 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7373 if (!isAccessibilityFocused()) { 7374 return requestAccessibilityFocus(); 7375 } 7376 } break; 7377 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7378 if (isAccessibilityFocused()) { 7379 clearAccessibilityFocus(); 7380 return true; 7381 } 7382 } break; 7383 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7384 if (arguments != null) { 7385 final int granularity = arguments.getInt( 7386 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7387 final boolean extendSelection = arguments.getBoolean( 7388 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7389 return traverseAtGranularity(granularity, true, extendSelection); 7390 } 7391 } break; 7392 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7393 if (arguments != null) { 7394 final int granularity = arguments.getInt( 7395 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7396 final boolean extendSelection = arguments.getBoolean( 7397 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7398 return traverseAtGranularity(granularity, false, extendSelection); 7399 } 7400 } break; 7401 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7402 CharSequence text = getIterableTextForAccessibility(); 7403 if (text == null) { 7404 return false; 7405 } 7406 final int start = (arguments != null) ? arguments.getInt( 7407 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7408 final int end = (arguments != null) ? arguments.getInt( 7409 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7410 // Only cursor position can be specified (selection length == 0) 7411 if ((getAccessibilitySelectionStart() != start 7412 || getAccessibilitySelectionEnd() != end) 7413 && (start == end)) { 7414 setAccessibilitySelection(start, end); 7415 notifyViewAccessibilityStateChangedIfNeeded( 7416 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7417 return true; 7418 } 7419 } break; 7420 } 7421 return false; 7422 } 7423 7424 private boolean traverseAtGranularity(int granularity, boolean forward, 7425 boolean extendSelection) { 7426 CharSequence text = getIterableTextForAccessibility(); 7427 if (text == null || text.length() == 0) { 7428 return false; 7429 } 7430 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7431 if (iterator == null) { 7432 return false; 7433 } 7434 int current = getAccessibilitySelectionEnd(); 7435 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7436 current = forward ? 0 : text.length(); 7437 } 7438 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7439 if (range == null) { 7440 return false; 7441 } 7442 final int segmentStart = range[0]; 7443 final int segmentEnd = range[1]; 7444 int selectionStart; 7445 int selectionEnd; 7446 if (extendSelection && isAccessibilitySelectionExtendable()) { 7447 selectionStart = getAccessibilitySelectionStart(); 7448 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7449 selectionStart = forward ? segmentStart : segmentEnd; 7450 } 7451 selectionEnd = forward ? segmentEnd : segmentStart; 7452 } else { 7453 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7454 } 7455 setAccessibilitySelection(selectionStart, selectionEnd); 7456 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7457 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7458 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7459 return true; 7460 } 7461 7462 /** 7463 * Gets the text reported for accessibility purposes. 7464 * 7465 * @return The accessibility text. 7466 * 7467 * @hide 7468 */ 7469 public CharSequence getIterableTextForAccessibility() { 7470 return getContentDescription(); 7471 } 7472 7473 /** 7474 * Gets whether accessibility selection can be extended. 7475 * 7476 * @return If selection is extensible. 7477 * 7478 * @hide 7479 */ 7480 public boolean isAccessibilitySelectionExtendable() { 7481 return false; 7482 } 7483 7484 /** 7485 * @hide 7486 */ 7487 public int getAccessibilitySelectionStart() { 7488 return mAccessibilityCursorPosition; 7489 } 7490 7491 /** 7492 * @hide 7493 */ 7494 public int getAccessibilitySelectionEnd() { 7495 return getAccessibilitySelectionStart(); 7496 } 7497 7498 /** 7499 * @hide 7500 */ 7501 public void setAccessibilitySelection(int start, int end) { 7502 if (start == end && end == mAccessibilityCursorPosition) { 7503 return; 7504 } 7505 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7506 mAccessibilityCursorPosition = start; 7507 } else { 7508 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7509 } 7510 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7511 } 7512 7513 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7514 int fromIndex, int toIndex) { 7515 if (mParent == null) { 7516 return; 7517 } 7518 AccessibilityEvent event = AccessibilityEvent.obtain( 7519 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7520 onInitializeAccessibilityEvent(event); 7521 onPopulateAccessibilityEvent(event); 7522 event.setFromIndex(fromIndex); 7523 event.setToIndex(toIndex); 7524 event.setAction(action); 7525 event.setMovementGranularity(granularity); 7526 mParent.requestSendAccessibilityEvent(this, event); 7527 } 7528 7529 /** 7530 * @hide 7531 */ 7532 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7533 switch (granularity) { 7534 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7535 CharSequence text = getIterableTextForAccessibility(); 7536 if (text != null && text.length() > 0) { 7537 CharacterTextSegmentIterator iterator = 7538 CharacterTextSegmentIterator.getInstance( 7539 mContext.getResources().getConfiguration().locale); 7540 iterator.initialize(text.toString()); 7541 return iterator; 7542 } 7543 } break; 7544 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7545 CharSequence text = getIterableTextForAccessibility(); 7546 if (text != null && text.length() > 0) { 7547 WordTextSegmentIterator iterator = 7548 WordTextSegmentIterator.getInstance( 7549 mContext.getResources().getConfiguration().locale); 7550 iterator.initialize(text.toString()); 7551 return iterator; 7552 } 7553 } break; 7554 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7555 CharSequence text = getIterableTextForAccessibility(); 7556 if (text != null && text.length() > 0) { 7557 ParagraphTextSegmentIterator iterator = 7558 ParagraphTextSegmentIterator.getInstance(); 7559 iterator.initialize(text.toString()); 7560 return iterator; 7561 } 7562 } break; 7563 } 7564 return null; 7565 } 7566 7567 /** 7568 * @hide 7569 */ 7570 public void dispatchStartTemporaryDetach() { 7571 clearDisplayList(); 7572 7573 onStartTemporaryDetach(); 7574 } 7575 7576 /** 7577 * This is called when a container is going to temporarily detach a child, with 7578 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7579 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7580 * {@link #onDetachedFromWindow()} when the container is done. 7581 */ 7582 public void onStartTemporaryDetach() { 7583 removeUnsetPressCallback(); 7584 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7585 } 7586 7587 /** 7588 * @hide 7589 */ 7590 public void dispatchFinishTemporaryDetach() { 7591 onFinishTemporaryDetach(); 7592 } 7593 7594 /** 7595 * Called after {@link #onStartTemporaryDetach} when the container is done 7596 * changing the view. 7597 */ 7598 public void onFinishTemporaryDetach() { 7599 } 7600 7601 /** 7602 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7603 * for this view's window. Returns null if the view is not currently attached 7604 * to the window. Normally you will not need to use this directly, but 7605 * just use the standard high-level event callbacks like 7606 * {@link #onKeyDown(int, KeyEvent)}. 7607 */ 7608 public KeyEvent.DispatcherState getKeyDispatcherState() { 7609 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7610 } 7611 7612 /** 7613 * Dispatch a key event before it is processed by any input method 7614 * associated with the view hierarchy. This can be used to intercept 7615 * key events in special situations before the IME consumes them; a 7616 * typical example would be handling the BACK key to update the application's 7617 * UI instead of allowing the IME to see it and close itself. 7618 * 7619 * @param event The key event to be dispatched. 7620 * @return True if the event was handled, false otherwise. 7621 */ 7622 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7623 return onKeyPreIme(event.getKeyCode(), event); 7624 } 7625 7626 /** 7627 * Dispatch a key event to the next view on the focus path. This path runs 7628 * from the top of the view tree down to the currently focused view. If this 7629 * view has focus, it will dispatch to itself. Otherwise it will dispatch 7630 * the next node down the focus path. This method also fires any key 7631 * listeners. 7632 * 7633 * @param event The key event to be dispatched. 7634 * @return True if the event was handled, false otherwise. 7635 */ 7636 public boolean dispatchKeyEvent(KeyEvent event) { 7637 if (mInputEventConsistencyVerifier != null) { 7638 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 7639 } 7640 7641 // Give any attached key listener a first crack at the event. 7642 //noinspection SimplifiableIfStatement 7643 ListenerInfo li = mListenerInfo; 7644 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7645 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 7646 return true; 7647 } 7648 7649 if (event.dispatch(this, mAttachInfo != null 7650 ? mAttachInfo.mKeyDispatchState : null, this)) { 7651 return true; 7652 } 7653 7654 if (mInputEventConsistencyVerifier != null) { 7655 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7656 } 7657 return false; 7658 } 7659 7660 /** 7661 * Dispatches a key shortcut event. 7662 * 7663 * @param event The key event to be dispatched. 7664 * @return True if the event was handled by the view, false otherwise. 7665 */ 7666 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 7667 return onKeyShortcut(event.getKeyCode(), event); 7668 } 7669 7670 /** 7671 * Pass the touch screen motion event down to the target view, or this 7672 * view if it is the target. 7673 * 7674 * @param event The motion event to be dispatched. 7675 * @return True if the event was handled by the view, false otherwise. 7676 */ 7677 public boolean dispatchTouchEvent(MotionEvent event) { 7678 if (mInputEventConsistencyVerifier != null) { 7679 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 7680 } 7681 7682 if (onFilterTouchEventForSecurity(event)) { 7683 //noinspection SimplifiableIfStatement 7684 ListenerInfo li = mListenerInfo; 7685 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7686 && li.mOnTouchListener.onTouch(this, event)) { 7687 return true; 7688 } 7689 7690 if (onTouchEvent(event)) { 7691 return true; 7692 } 7693 } 7694 7695 if (mInputEventConsistencyVerifier != null) { 7696 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7697 } 7698 return false; 7699 } 7700 7701 /** 7702 * Filter the touch event to apply security policies. 7703 * 7704 * @param event The motion event to be filtered. 7705 * @return True if the event should be dispatched, false if the event should be dropped. 7706 * 7707 * @see #getFilterTouchesWhenObscured 7708 */ 7709 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 7710 //noinspection RedundantIfStatement 7711 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 7712 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 7713 // Window is obscured, drop this touch. 7714 return false; 7715 } 7716 return true; 7717 } 7718 7719 /** 7720 * Pass a trackball motion event down to the focused view. 7721 * 7722 * @param event The motion event to be dispatched. 7723 * @return True if the event was handled by the view, false otherwise. 7724 */ 7725 public boolean dispatchTrackballEvent(MotionEvent event) { 7726 if (mInputEventConsistencyVerifier != null) { 7727 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 7728 } 7729 7730 return onTrackballEvent(event); 7731 } 7732 7733 /** 7734 * Dispatch a generic motion event. 7735 * <p> 7736 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 7737 * are delivered to the view under the pointer. All other generic motion events are 7738 * delivered to the focused view. Hover events are handled specially and are delivered 7739 * to {@link #onHoverEvent(MotionEvent)}. 7740 * </p> 7741 * 7742 * @param event The motion event to be dispatched. 7743 * @return True if the event was handled by the view, false otherwise. 7744 */ 7745 public boolean dispatchGenericMotionEvent(MotionEvent event) { 7746 if (mInputEventConsistencyVerifier != null) { 7747 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 7748 } 7749 7750 final int source = event.getSource(); 7751 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 7752 final int action = event.getAction(); 7753 if (action == MotionEvent.ACTION_HOVER_ENTER 7754 || action == MotionEvent.ACTION_HOVER_MOVE 7755 || action == MotionEvent.ACTION_HOVER_EXIT) { 7756 if (dispatchHoverEvent(event)) { 7757 return true; 7758 } 7759 } else if (dispatchGenericPointerEvent(event)) { 7760 return true; 7761 } 7762 } else if (dispatchGenericFocusedEvent(event)) { 7763 return true; 7764 } 7765 7766 if (dispatchGenericMotionEventInternal(event)) { 7767 return true; 7768 } 7769 7770 if (mInputEventConsistencyVerifier != null) { 7771 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7772 } 7773 return false; 7774 } 7775 7776 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 7777 //noinspection SimplifiableIfStatement 7778 ListenerInfo li = mListenerInfo; 7779 if (li != null && li.mOnGenericMotionListener != null 7780 && (mViewFlags & ENABLED_MASK) == ENABLED 7781 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 7782 return true; 7783 } 7784 7785 if (onGenericMotionEvent(event)) { 7786 return true; 7787 } 7788 7789 if (mInputEventConsistencyVerifier != null) { 7790 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7791 } 7792 return false; 7793 } 7794 7795 /** 7796 * Dispatch a hover event. 7797 * <p> 7798 * Do not call this method directly. 7799 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7800 * </p> 7801 * 7802 * @param event The motion event to be dispatched. 7803 * @return True if the event was handled by the view, false otherwise. 7804 */ 7805 protected boolean dispatchHoverEvent(MotionEvent event) { 7806 ListenerInfo li = mListenerInfo; 7807 //noinspection SimplifiableIfStatement 7808 if (li != null && li.mOnHoverListener != null 7809 && (mViewFlags & ENABLED_MASK) == ENABLED 7810 && li.mOnHoverListener.onHover(this, event)) { 7811 return true; 7812 } 7813 7814 return onHoverEvent(event); 7815 } 7816 7817 /** 7818 * Returns true if the view has a child to which it has recently sent 7819 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 7820 * it does not have a hovered child, then it must be the innermost hovered view. 7821 * @hide 7822 */ 7823 protected boolean hasHoveredChild() { 7824 return false; 7825 } 7826 7827 /** 7828 * Dispatch a generic motion event to the view under the first pointer. 7829 * <p> 7830 * Do not call this method directly. 7831 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7832 * </p> 7833 * 7834 * @param event The motion event to be dispatched. 7835 * @return True if the event was handled by the view, false otherwise. 7836 */ 7837 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 7838 return false; 7839 } 7840 7841 /** 7842 * Dispatch a generic motion event to the currently focused view. 7843 * <p> 7844 * Do not call this method directly. 7845 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7846 * </p> 7847 * 7848 * @param event The motion event to be dispatched. 7849 * @return True if the event was handled by the view, false otherwise. 7850 */ 7851 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 7852 return false; 7853 } 7854 7855 /** 7856 * Dispatch a pointer event. 7857 * <p> 7858 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 7859 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 7860 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 7861 * and should not be expected to handle other pointing device features. 7862 * </p> 7863 * 7864 * @param event The motion event to be dispatched. 7865 * @return True if the event was handled by the view, false otherwise. 7866 * @hide 7867 */ 7868 public final boolean dispatchPointerEvent(MotionEvent event) { 7869 if (event.isTouchEvent()) { 7870 return dispatchTouchEvent(event); 7871 } else { 7872 return dispatchGenericMotionEvent(event); 7873 } 7874 } 7875 7876 /** 7877 * Called when the window containing this view gains or loses window focus. 7878 * ViewGroups should override to route to their children. 7879 * 7880 * @param hasFocus True if the window containing this view now has focus, 7881 * false otherwise. 7882 */ 7883 public void dispatchWindowFocusChanged(boolean hasFocus) { 7884 onWindowFocusChanged(hasFocus); 7885 } 7886 7887 /** 7888 * Called when the window containing this view gains or loses focus. Note 7889 * that this is separate from view focus: to receive key events, both 7890 * your view and its window must have focus. If a window is displayed 7891 * on top of yours that takes input focus, then your own window will lose 7892 * focus but the view focus will remain unchanged. 7893 * 7894 * @param hasWindowFocus True if the window containing this view now has 7895 * focus, false otherwise. 7896 */ 7897 public void onWindowFocusChanged(boolean hasWindowFocus) { 7898 InputMethodManager imm = InputMethodManager.peekInstance(); 7899 if (!hasWindowFocus) { 7900 if (isPressed()) { 7901 setPressed(false); 7902 } 7903 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7904 imm.focusOut(this); 7905 } 7906 removeLongPressCallback(); 7907 removeTapCallback(); 7908 onFocusLost(); 7909 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7910 imm.focusIn(this); 7911 } 7912 refreshDrawableState(); 7913 } 7914 7915 /** 7916 * Returns true if this view is in a window that currently has window focus. 7917 * Note that this is not the same as the view itself having focus. 7918 * 7919 * @return True if this view is in a window that currently has window focus. 7920 */ 7921 public boolean hasWindowFocus() { 7922 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 7923 } 7924 7925 /** 7926 * Dispatch a view visibility change down the view hierarchy. 7927 * ViewGroups should override to route to their children. 7928 * @param changedView The view whose visibility changed. Could be 'this' or 7929 * an ancestor view. 7930 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7931 * {@link #INVISIBLE} or {@link #GONE}. 7932 */ 7933 protected void dispatchVisibilityChanged(View changedView, int visibility) { 7934 onVisibilityChanged(changedView, visibility); 7935 } 7936 7937 /** 7938 * Called when the visibility of the view or an ancestor of the view is changed. 7939 * @param changedView The view whose visibility changed. Could be 'this' or 7940 * an ancestor view. 7941 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7942 * {@link #INVISIBLE} or {@link #GONE}. 7943 */ 7944 protected void onVisibilityChanged(View changedView, int visibility) { 7945 if (visibility == VISIBLE) { 7946 if (mAttachInfo != null) { 7947 initialAwakenScrollBars(); 7948 } else { 7949 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 7950 } 7951 } 7952 } 7953 7954 /** 7955 * Dispatch a hint about whether this view is displayed. For instance, when 7956 * a View moves out of the screen, it might receives a display hint indicating 7957 * the view is not displayed. Applications should not <em>rely</em> on this hint 7958 * as there is no guarantee that they will receive one. 7959 * 7960 * @param hint A hint about whether or not this view is displayed: 7961 * {@link #VISIBLE} or {@link #INVISIBLE}. 7962 */ 7963 public void dispatchDisplayHint(int hint) { 7964 onDisplayHint(hint); 7965 } 7966 7967 /** 7968 * Gives this view a hint about whether is displayed or not. For instance, when 7969 * a View moves out of the screen, it might receives a display hint indicating 7970 * the view is not displayed. Applications should not <em>rely</em> on this hint 7971 * as there is no guarantee that they will receive one. 7972 * 7973 * @param hint A hint about whether or not this view is displayed: 7974 * {@link #VISIBLE} or {@link #INVISIBLE}. 7975 */ 7976 protected void onDisplayHint(int hint) { 7977 } 7978 7979 /** 7980 * Dispatch a window visibility change down the view hierarchy. 7981 * ViewGroups should override to route to their children. 7982 * 7983 * @param visibility The new visibility of the window. 7984 * 7985 * @see #onWindowVisibilityChanged(int) 7986 */ 7987 public void dispatchWindowVisibilityChanged(int visibility) { 7988 onWindowVisibilityChanged(visibility); 7989 } 7990 7991 /** 7992 * Called when the window containing has change its visibility 7993 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 7994 * that this tells you whether or not your window is being made visible 7995 * to the window manager; this does <em>not</em> tell you whether or not 7996 * your window is obscured by other windows on the screen, even if it 7997 * is itself visible. 7998 * 7999 * @param visibility The new visibility of the window. 8000 */ 8001 protected void onWindowVisibilityChanged(int visibility) { 8002 if (visibility == VISIBLE) { 8003 initialAwakenScrollBars(); 8004 } 8005 } 8006 8007 /** 8008 * Returns the current visibility of the window this view is attached to 8009 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8010 * 8011 * @return Returns the current visibility of the view's window. 8012 */ 8013 public int getWindowVisibility() { 8014 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8015 } 8016 8017 /** 8018 * Retrieve the overall visible display size in which the window this view is 8019 * attached to has been positioned in. This takes into account screen 8020 * decorations above the window, for both cases where the window itself 8021 * is being position inside of them or the window is being placed under 8022 * then and covered insets are used for the window to position its content 8023 * inside. In effect, this tells you the available area where content can 8024 * be placed and remain visible to users. 8025 * 8026 * <p>This function requires an IPC back to the window manager to retrieve 8027 * the requested information, so should not be used in performance critical 8028 * code like drawing. 8029 * 8030 * @param outRect Filled in with the visible display frame. If the view 8031 * is not attached to a window, this is simply the raw display size. 8032 */ 8033 public void getWindowVisibleDisplayFrame(Rect outRect) { 8034 if (mAttachInfo != null) { 8035 try { 8036 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8037 } catch (RemoteException e) { 8038 return; 8039 } 8040 // XXX This is really broken, and probably all needs to be done 8041 // in the window manager, and we need to know more about whether 8042 // we want the area behind or in front of the IME. 8043 final Rect insets = mAttachInfo.mVisibleInsets; 8044 outRect.left += insets.left; 8045 outRect.top += insets.top; 8046 outRect.right -= insets.right; 8047 outRect.bottom -= insets.bottom; 8048 return; 8049 } 8050 // The view is not attached to a display so we don't have a context. 8051 // Make a best guess about the display size. 8052 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8053 d.getRectSize(outRect); 8054 } 8055 8056 /** 8057 * Dispatch a notification about a resource configuration change down 8058 * the view hierarchy. 8059 * ViewGroups should override to route to their children. 8060 * 8061 * @param newConfig The new resource configuration. 8062 * 8063 * @see #onConfigurationChanged(android.content.res.Configuration) 8064 */ 8065 public void dispatchConfigurationChanged(Configuration newConfig) { 8066 onConfigurationChanged(newConfig); 8067 } 8068 8069 /** 8070 * Called when the current configuration of the resources being used 8071 * by the application have changed. You can use this to decide when 8072 * to reload resources that can changed based on orientation and other 8073 * configuration characterstics. You only need to use this if you are 8074 * not relying on the normal {@link android.app.Activity} mechanism of 8075 * recreating the activity instance upon a configuration change. 8076 * 8077 * @param newConfig The new resource configuration. 8078 */ 8079 protected void onConfigurationChanged(Configuration newConfig) { 8080 } 8081 8082 /** 8083 * Private function to aggregate all per-view attributes in to the view 8084 * root. 8085 */ 8086 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8087 performCollectViewAttributes(attachInfo, visibility); 8088 } 8089 8090 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8091 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8092 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8093 attachInfo.mKeepScreenOn = true; 8094 } 8095 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8096 ListenerInfo li = mListenerInfo; 8097 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8098 attachInfo.mHasSystemUiListeners = true; 8099 } 8100 } 8101 } 8102 8103 void needGlobalAttributesUpdate(boolean force) { 8104 final AttachInfo ai = mAttachInfo; 8105 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8106 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8107 || ai.mHasSystemUiListeners) { 8108 ai.mRecomputeGlobalAttributes = true; 8109 } 8110 } 8111 } 8112 8113 /** 8114 * Returns whether the device is currently in touch mode. Touch mode is entered 8115 * once the user begins interacting with the device by touch, and affects various 8116 * things like whether focus is always visible to the user. 8117 * 8118 * @return Whether the device is in touch mode. 8119 */ 8120 @ViewDebug.ExportedProperty 8121 public boolean isInTouchMode() { 8122 if (mAttachInfo != null) { 8123 return mAttachInfo.mInTouchMode; 8124 } else { 8125 return ViewRootImpl.isInTouchMode(); 8126 } 8127 } 8128 8129 /** 8130 * Returns the context the view is running in, through which it can 8131 * access the current theme, resources, etc. 8132 * 8133 * @return The view's Context. 8134 */ 8135 @ViewDebug.CapturedViewProperty 8136 public final Context getContext() { 8137 return mContext; 8138 } 8139 8140 /** 8141 * Handle a key event before it is processed by any input method 8142 * associated with the view hierarchy. This can be used to intercept 8143 * key events in special situations before the IME consumes them; a 8144 * typical example would be handling the BACK key to update the application's 8145 * UI instead of allowing the IME to see it and close itself. 8146 * 8147 * @param keyCode The value in event.getKeyCode(). 8148 * @param event Description of the key event. 8149 * @return If you handled the event, return true. If you want to allow the 8150 * event to be handled by the next receiver, return false. 8151 */ 8152 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8153 return false; 8154 } 8155 8156 /** 8157 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8158 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8159 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8160 * is released, if the view is enabled and clickable. 8161 * 8162 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8163 * although some may elect to do so in some situations. Do not rely on this to 8164 * catch software key presses. 8165 * 8166 * @param keyCode A key code that represents the button pressed, from 8167 * {@link android.view.KeyEvent}. 8168 * @param event The KeyEvent object that defines the button action. 8169 */ 8170 public boolean onKeyDown(int keyCode, KeyEvent event) { 8171 boolean result = false; 8172 8173 if (KeyEvent.isConfirmKey(keyCode)) { 8174 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8175 return true; 8176 } 8177 // Long clickable items don't necessarily have to be clickable 8178 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8179 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8180 (event.getRepeatCount() == 0)) { 8181 setPressed(true); 8182 checkForLongClick(0); 8183 return true; 8184 } 8185 } 8186 return result; 8187 } 8188 8189 /** 8190 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8191 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8192 * the event). 8193 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8194 * although some may elect to do so in some situations. Do not rely on this to 8195 * catch software key presses. 8196 */ 8197 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8198 return false; 8199 } 8200 8201 /** 8202 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8203 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8204 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8205 * {@link KeyEvent#KEYCODE_ENTER} is released. 8206 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8207 * although some may elect to do so in some situations. Do not rely on this to 8208 * catch software key presses. 8209 * 8210 * @param keyCode A key code that represents the button pressed, from 8211 * {@link android.view.KeyEvent}. 8212 * @param event The KeyEvent object that defines the button action. 8213 */ 8214 public boolean onKeyUp(int keyCode, KeyEvent event) { 8215 if (KeyEvent.isConfirmKey(keyCode)) { 8216 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8217 return true; 8218 } 8219 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8220 setPressed(false); 8221 8222 if (!mHasPerformedLongPress) { 8223 // This is a tap, so remove the longpress check 8224 removeLongPressCallback(); 8225 return performClick(); 8226 } 8227 } 8228 } 8229 return false; 8230 } 8231 8232 /** 8233 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8234 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8235 * the event). 8236 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8237 * although some may elect to do so in some situations. Do not rely on this to 8238 * catch software key presses. 8239 * 8240 * @param keyCode A key code that represents the button pressed, from 8241 * {@link android.view.KeyEvent}. 8242 * @param repeatCount The number of times the action was made. 8243 * @param event The KeyEvent object that defines the button action. 8244 */ 8245 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8246 return false; 8247 } 8248 8249 /** 8250 * Called on the focused view when a key shortcut event is not handled. 8251 * Override this method to implement local key shortcuts for the View. 8252 * Key shortcuts can also be implemented by setting the 8253 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8254 * 8255 * @param keyCode The value in event.getKeyCode(). 8256 * @param event Description of the key event. 8257 * @return If you handled the event, return true. If you want to allow the 8258 * event to be handled by the next receiver, return false. 8259 */ 8260 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8261 return false; 8262 } 8263 8264 /** 8265 * Check whether the called view is a text editor, in which case it 8266 * would make sense to automatically display a soft input window for 8267 * it. Subclasses should override this if they implement 8268 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8269 * a call on that method would return a non-null InputConnection, and 8270 * they are really a first-class editor that the user would normally 8271 * start typing on when the go into a window containing your view. 8272 * 8273 * <p>The default implementation always returns false. This does 8274 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8275 * will not be called or the user can not otherwise perform edits on your 8276 * view; it is just a hint to the system that this is not the primary 8277 * purpose of this view. 8278 * 8279 * @return Returns true if this view is a text editor, else false. 8280 */ 8281 public boolean onCheckIsTextEditor() { 8282 return false; 8283 } 8284 8285 /** 8286 * Create a new InputConnection for an InputMethod to interact 8287 * with the view. The default implementation returns null, since it doesn't 8288 * support input methods. You can override this to implement such support. 8289 * This is only needed for views that take focus and text input. 8290 * 8291 * <p>When implementing this, you probably also want to implement 8292 * {@link #onCheckIsTextEditor()} to indicate you will return a 8293 * non-null InputConnection. 8294 * 8295 * @param outAttrs Fill in with attribute information about the connection. 8296 */ 8297 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8298 return null; 8299 } 8300 8301 /** 8302 * Called by the {@link android.view.inputmethod.InputMethodManager} 8303 * when a view who is not the current 8304 * input connection target is trying to make a call on the manager. The 8305 * default implementation returns false; you can override this to return 8306 * true for certain views if you are performing InputConnection proxying 8307 * to them. 8308 * @param view The View that is making the InputMethodManager call. 8309 * @return Return true to allow the call, false to reject. 8310 */ 8311 public boolean checkInputConnectionProxy(View view) { 8312 return false; 8313 } 8314 8315 /** 8316 * Show the context menu for this view. It is not safe to hold on to the 8317 * menu after returning from this method. 8318 * 8319 * You should normally not overload this method. Overload 8320 * {@link #onCreateContextMenu(ContextMenu)} or define an 8321 * {@link OnCreateContextMenuListener} to add items to the context menu. 8322 * 8323 * @param menu The context menu to populate 8324 */ 8325 public void createContextMenu(ContextMenu menu) { 8326 ContextMenuInfo menuInfo = getContextMenuInfo(); 8327 8328 // Sets the current menu info so all items added to menu will have 8329 // my extra info set. 8330 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8331 8332 onCreateContextMenu(menu); 8333 ListenerInfo li = mListenerInfo; 8334 if (li != null && li.mOnCreateContextMenuListener != null) { 8335 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8336 } 8337 8338 // Clear the extra information so subsequent items that aren't mine don't 8339 // have my extra info. 8340 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8341 8342 if (mParent != null) { 8343 mParent.createContextMenu(menu); 8344 } 8345 } 8346 8347 /** 8348 * Views should implement this if they have extra information to associate 8349 * with the context menu. The return result is supplied as a parameter to 8350 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8351 * callback. 8352 * 8353 * @return Extra information about the item for which the context menu 8354 * should be shown. This information will vary across different 8355 * subclasses of View. 8356 */ 8357 protected ContextMenuInfo getContextMenuInfo() { 8358 return null; 8359 } 8360 8361 /** 8362 * Views should implement this if the view itself is going to add items to 8363 * the context menu. 8364 * 8365 * @param menu the context menu to populate 8366 */ 8367 protected void onCreateContextMenu(ContextMenu menu) { 8368 } 8369 8370 /** 8371 * Implement this method to handle trackball motion events. The 8372 * <em>relative</em> movement of the trackball since the last event 8373 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8374 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8375 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8376 * they will often be fractional values, representing the more fine-grained 8377 * movement information available from a trackball). 8378 * 8379 * @param event The motion event. 8380 * @return True if the event was handled, false otherwise. 8381 */ 8382 public boolean onTrackballEvent(MotionEvent event) { 8383 return false; 8384 } 8385 8386 /** 8387 * Implement this method to handle generic motion events. 8388 * <p> 8389 * Generic motion events describe joystick movements, mouse hovers, track pad 8390 * touches, scroll wheel movements and other input events. The 8391 * {@link MotionEvent#getSource() source} of the motion event specifies 8392 * the class of input that was received. Implementations of this method 8393 * must examine the bits in the source before processing the event. 8394 * The following code example shows how this is done. 8395 * </p><p> 8396 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8397 * are delivered to the view under the pointer. All other generic motion events are 8398 * delivered to the focused view. 8399 * </p> 8400 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8401 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8402 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8403 * // process the joystick movement... 8404 * return true; 8405 * } 8406 * } 8407 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8408 * switch (event.getAction()) { 8409 * case MotionEvent.ACTION_HOVER_MOVE: 8410 * // process the mouse hover movement... 8411 * return true; 8412 * case MotionEvent.ACTION_SCROLL: 8413 * // process the scroll wheel movement... 8414 * return true; 8415 * } 8416 * } 8417 * return super.onGenericMotionEvent(event); 8418 * }</pre> 8419 * 8420 * @param event The generic motion event being processed. 8421 * @return True if the event was handled, false otherwise. 8422 */ 8423 public boolean onGenericMotionEvent(MotionEvent event) { 8424 return false; 8425 } 8426 8427 /** 8428 * Implement this method to handle hover events. 8429 * <p> 8430 * This method is called whenever a pointer is hovering into, over, or out of the 8431 * bounds of a view and the view is not currently being touched. 8432 * Hover events are represented as pointer events with action 8433 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8434 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8435 * </p> 8436 * <ul> 8437 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8438 * when the pointer enters the bounds of the view.</li> 8439 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8440 * when the pointer has already entered the bounds of the view and has moved.</li> 8441 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8442 * when the pointer has exited the bounds of the view or when the pointer is 8443 * about to go down due to a button click, tap, or similar user action that 8444 * causes the view to be touched.</li> 8445 * </ul> 8446 * <p> 8447 * The view should implement this method to return true to indicate that it is 8448 * handling the hover event, such as by changing its drawable state. 8449 * </p><p> 8450 * The default implementation calls {@link #setHovered} to update the hovered state 8451 * of the view when a hover enter or hover exit event is received, if the view 8452 * is enabled and is clickable. The default implementation also sends hover 8453 * accessibility events. 8454 * </p> 8455 * 8456 * @param event The motion event that describes the hover. 8457 * @return True if the view handled the hover event. 8458 * 8459 * @see #isHovered 8460 * @see #setHovered 8461 * @see #onHoverChanged 8462 */ 8463 public boolean onHoverEvent(MotionEvent event) { 8464 // The root view may receive hover (or touch) events that are outside the bounds of 8465 // the window. This code ensures that we only send accessibility events for 8466 // hovers that are actually within the bounds of the root view. 8467 final int action = event.getActionMasked(); 8468 if (!mSendingHoverAccessibilityEvents) { 8469 if ((action == MotionEvent.ACTION_HOVER_ENTER 8470 || action == MotionEvent.ACTION_HOVER_MOVE) 8471 && !hasHoveredChild() 8472 && pointInView(event.getX(), event.getY())) { 8473 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8474 mSendingHoverAccessibilityEvents = true; 8475 } 8476 } else { 8477 if (action == MotionEvent.ACTION_HOVER_EXIT 8478 || (action == MotionEvent.ACTION_MOVE 8479 && !pointInView(event.getX(), event.getY()))) { 8480 mSendingHoverAccessibilityEvents = false; 8481 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8482 // If the window does not have input focus we take away accessibility 8483 // focus as soon as the user stop hovering over the view. 8484 if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) { 8485 getViewRootImpl().setAccessibilityFocus(null, null); 8486 } 8487 } 8488 } 8489 8490 if (isHoverable()) { 8491 switch (action) { 8492 case MotionEvent.ACTION_HOVER_ENTER: 8493 setHovered(true); 8494 break; 8495 case MotionEvent.ACTION_HOVER_EXIT: 8496 setHovered(false); 8497 break; 8498 } 8499 8500 // Dispatch the event to onGenericMotionEvent before returning true. 8501 // This is to provide compatibility with existing applications that 8502 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8503 // break because of the new default handling for hoverable views 8504 // in onHoverEvent. 8505 // Note that onGenericMotionEvent will be called by default when 8506 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8507 dispatchGenericMotionEventInternal(event); 8508 // The event was already handled by calling setHovered(), so always 8509 // return true. 8510 return true; 8511 } 8512 8513 return false; 8514 } 8515 8516 /** 8517 * Returns true if the view should handle {@link #onHoverEvent} 8518 * by calling {@link #setHovered} to change its hovered state. 8519 * 8520 * @return True if the view is hoverable. 8521 */ 8522 private boolean isHoverable() { 8523 final int viewFlags = mViewFlags; 8524 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8525 return false; 8526 } 8527 8528 return (viewFlags & CLICKABLE) == CLICKABLE 8529 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8530 } 8531 8532 /** 8533 * Returns true if the view is currently hovered. 8534 * 8535 * @return True if the view is currently hovered. 8536 * 8537 * @see #setHovered 8538 * @see #onHoverChanged 8539 */ 8540 @ViewDebug.ExportedProperty 8541 public boolean isHovered() { 8542 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8543 } 8544 8545 /** 8546 * Sets whether the view is currently hovered. 8547 * <p> 8548 * Calling this method also changes the drawable state of the view. This 8549 * enables the view to react to hover by using different drawable resources 8550 * to change its appearance. 8551 * </p><p> 8552 * The {@link #onHoverChanged} method is called when the hovered state changes. 8553 * </p> 8554 * 8555 * @param hovered True if the view is hovered. 8556 * 8557 * @see #isHovered 8558 * @see #onHoverChanged 8559 */ 8560 public void setHovered(boolean hovered) { 8561 if (hovered) { 8562 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8563 mPrivateFlags |= PFLAG_HOVERED; 8564 refreshDrawableState(); 8565 onHoverChanged(true); 8566 } 8567 } else { 8568 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8569 mPrivateFlags &= ~PFLAG_HOVERED; 8570 refreshDrawableState(); 8571 onHoverChanged(false); 8572 } 8573 } 8574 } 8575 8576 /** 8577 * Implement this method to handle hover state changes. 8578 * <p> 8579 * This method is called whenever the hover state changes as a result of a 8580 * call to {@link #setHovered}. 8581 * </p> 8582 * 8583 * @param hovered The current hover state, as returned by {@link #isHovered}. 8584 * 8585 * @see #isHovered 8586 * @see #setHovered 8587 */ 8588 public void onHoverChanged(boolean hovered) { 8589 } 8590 8591 /** 8592 * Implement this method to handle touch screen motion events. 8593 * <p> 8594 * If this method is used to detect click actions, it is recommended that 8595 * the actions be performed by implementing and calling 8596 * {@link #performClick()}. This will ensure consistent system behavior, 8597 * including: 8598 * <ul> 8599 * <li>obeying click sound preferences 8600 * <li>dispatching OnClickListener calls 8601 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 8602 * accessibility features are enabled 8603 * </ul> 8604 * 8605 * @param event The motion event. 8606 * @return True if the event was handled, false otherwise. 8607 */ 8608 public boolean onTouchEvent(MotionEvent event) { 8609 final int viewFlags = mViewFlags; 8610 8611 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8612 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 8613 setPressed(false); 8614 } 8615 // A disabled view that is clickable still consumes the touch 8616 // events, it just doesn't respond to them. 8617 return (((viewFlags & CLICKABLE) == CLICKABLE || 8618 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 8619 } 8620 8621 if (mTouchDelegate != null) { 8622 if (mTouchDelegate.onTouchEvent(event)) { 8623 return true; 8624 } 8625 } 8626 8627 if (((viewFlags & CLICKABLE) == CLICKABLE || 8628 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 8629 switch (event.getAction()) { 8630 case MotionEvent.ACTION_UP: 8631 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 8632 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 8633 // take focus if we don't have it already and we should in 8634 // touch mode. 8635 boolean focusTaken = false; 8636 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 8637 focusTaken = requestFocus(); 8638 } 8639 8640 if (prepressed) { 8641 // The button is being released before we actually 8642 // showed it as pressed. Make it show the pressed 8643 // state now (before scheduling the click) to ensure 8644 // the user sees it. 8645 setPressed(true); 8646 } 8647 8648 if (!mHasPerformedLongPress) { 8649 // This is a tap, so remove the longpress check 8650 removeLongPressCallback(); 8651 8652 // Only perform take click actions if we were in the pressed state 8653 if (!focusTaken) { 8654 // Use a Runnable and post this rather than calling 8655 // performClick directly. This lets other visual state 8656 // of the view update before click actions start. 8657 if (mPerformClick == null) { 8658 mPerformClick = new PerformClick(); 8659 } 8660 if (!post(mPerformClick)) { 8661 performClick(); 8662 } 8663 } 8664 } 8665 8666 if (mUnsetPressedState == null) { 8667 mUnsetPressedState = new UnsetPressedState(); 8668 } 8669 8670 if (prepressed) { 8671 postDelayed(mUnsetPressedState, 8672 ViewConfiguration.getPressedStateDuration()); 8673 } else if (!post(mUnsetPressedState)) { 8674 // If the post failed, unpress right now 8675 mUnsetPressedState.run(); 8676 } 8677 removeTapCallback(); 8678 } 8679 break; 8680 8681 case MotionEvent.ACTION_DOWN: 8682 mHasPerformedLongPress = false; 8683 8684 if (performButtonActionOnTouchDown(event)) { 8685 break; 8686 } 8687 8688 // Walk up the hierarchy to determine if we're inside a scrolling container. 8689 boolean isInScrollingContainer = isInScrollingContainer(); 8690 8691 // For views inside a scrolling container, delay the pressed feedback for 8692 // a short period in case this is a scroll. 8693 if (isInScrollingContainer) { 8694 mPrivateFlags |= PFLAG_PREPRESSED; 8695 if (mPendingCheckForTap == null) { 8696 mPendingCheckForTap = new CheckForTap(); 8697 } 8698 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 8699 } else { 8700 // Not inside a scrolling container, so show the feedback right away 8701 setPressed(true); 8702 checkForLongClick(0); 8703 } 8704 break; 8705 8706 case MotionEvent.ACTION_CANCEL: 8707 setPressed(false); 8708 removeTapCallback(); 8709 removeLongPressCallback(); 8710 break; 8711 8712 case MotionEvent.ACTION_MOVE: 8713 final int x = (int) event.getX(); 8714 final int y = (int) event.getY(); 8715 8716 // Be lenient about moving outside of buttons 8717 if (!pointInView(x, y, mTouchSlop)) { 8718 // Outside button 8719 removeTapCallback(); 8720 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 8721 // Remove any future long press/tap checks 8722 removeLongPressCallback(); 8723 8724 setPressed(false); 8725 } 8726 } 8727 break; 8728 } 8729 return true; 8730 } 8731 8732 return false; 8733 } 8734 8735 /** 8736 * @hide 8737 */ 8738 public boolean isInScrollingContainer() { 8739 ViewParent p = getParent(); 8740 while (p != null && p instanceof ViewGroup) { 8741 if (((ViewGroup) p).shouldDelayChildPressedState()) { 8742 return true; 8743 } 8744 p = p.getParent(); 8745 } 8746 return false; 8747 } 8748 8749 /** 8750 * Remove the longpress detection timer. 8751 */ 8752 private void removeLongPressCallback() { 8753 if (mPendingCheckForLongPress != null) { 8754 removeCallbacks(mPendingCheckForLongPress); 8755 } 8756 } 8757 8758 /** 8759 * Remove the pending click action 8760 */ 8761 private void removePerformClickCallback() { 8762 if (mPerformClick != null) { 8763 removeCallbacks(mPerformClick); 8764 } 8765 } 8766 8767 /** 8768 * Remove the prepress detection timer. 8769 */ 8770 private void removeUnsetPressCallback() { 8771 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 8772 setPressed(false); 8773 removeCallbacks(mUnsetPressedState); 8774 } 8775 } 8776 8777 /** 8778 * Remove the tap detection timer. 8779 */ 8780 private void removeTapCallback() { 8781 if (mPendingCheckForTap != null) { 8782 mPrivateFlags &= ~PFLAG_PREPRESSED; 8783 removeCallbacks(mPendingCheckForTap); 8784 } 8785 } 8786 8787 /** 8788 * Cancels a pending long press. Your subclass can use this if you 8789 * want the context menu to come up if the user presses and holds 8790 * at the same place, but you don't want it to come up if they press 8791 * and then move around enough to cause scrolling. 8792 */ 8793 public void cancelLongPress() { 8794 removeLongPressCallback(); 8795 8796 /* 8797 * The prepressed state handled by the tap callback is a display 8798 * construct, but the tap callback will post a long press callback 8799 * less its own timeout. Remove it here. 8800 */ 8801 removeTapCallback(); 8802 } 8803 8804 /** 8805 * Remove the pending callback for sending a 8806 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 8807 */ 8808 private void removeSendViewScrolledAccessibilityEventCallback() { 8809 if (mSendViewScrolledAccessibilityEvent != null) { 8810 removeCallbacks(mSendViewScrolledAccessibilityEvent); 8811 mSendViewScrolledAccessibilityEvent.mIsPending = false; 8812 } 8813 } 8814 8815 /** 8816 * Sets the TouchDelegate for this View. 8817 */ 8818 public void setTouchDelegate(TouchDelegate delegate) { 8819 mTouchDelegate = delegate; 8820 } 8821 8822 /** 8823 * Gets the TouchDelegate for this View. 8824 */ 8825 public TouchDelegate getTouchDelegate() { 8826 return mTouchDelegate; 8827 } 8828 8829 /** 8830 * Set flags controlling behavior of this view. 8831 * 8832 * @param flags Constant indicating the value which should be set 8833 * @param mask Constant indicating the bit range that should be changed 8834 */ 8835 void setFlags(int flags, int mask) { 8836 final boolean accessibilityEnabled = 8837 AccessibilityManager.getInstance(mContext).isEnabled(); 8838 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 8839 8840 int old = mViewFlags; 8841 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 8842 8843 int changed = mViewFlags ^ old; 8844 if (changed == 0) { 8845 return; 8846 } 8847 int privateFlags = mPrivateFlags; 8848 8849 /* Check if the FOCUSABLE bit has changed */ 8850 if (((changed & FOCUSABLE_MASK) != 0) && 8851 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 8852 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 8853 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 8854 /* Give up focus if we are no longer focusable */ 8855 clearFocus(); 8856 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 8857 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 8858 /* 8859 * Tell the view system that we are now available to take focus 8860 * if no one else already has it. 8861 */ 8862 if (mParent != null) mParent.focusableViewAvailable(this); 8863 } 8864 } 8865 8866 final int newVisibility = flags & VISIBILITY_MASK; 8867 if (newVisibility == VISIBLE) { 8868 if ((changed & VISIBILITY_MASK) != 0) { 8869 /* 8870 * If this view is becoming visible, invalidate it in case it changed while 8871 * it was not visible. Marking it drawn ensures that the invalidation will 8872 * go through. 8873 */ 8874 mPrivateFlags |= PFLAG_DRAWN; 8875 invalidate(true); 8876 8877 needGlobalAttributesUpdate(true); 8878 8879 // a view becoming visible is worth notifying the parent 8880 // about in case nothing has focus. even if this specific view 8881 // isn't focusable, it may contain something that is, so let 8882 // the root view try to give this focus if nothing else does. 8883 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 8884 mParent.focusableViewAvailable(this); 8885 } 8886 } 8887 } 8888 8889 /* Check if the GONE bit has changed */ 8890 if ((changed & GONE) != 0) { 8891 needGlobalAttributesUpdate(false); 8892 requestLayout(); 8893 8894 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 8895 if (hasFocus()) clearFocus(); 8896 clearAccessibilityFocus(); 8897 destroyDrawingCache(); 8898 if (mParent instanceof View) { 8899 // GONE views noop invalidation, so invalidate the parent 8900 ((View) mParent).invalidate(true); 8901 } 8902 // Mark the view drawn to ensure that it gets invalidated properly the next 8903 // time it is visible and gets invalidated 8904 mPrivateFlags |= PFLAG_DRAWN; 8905 } 8906 if (mAttachInfo != null) { 8907 mAttachInfo.mViewVisibilityChanged = true; 8908 } 8909 } 8910 8911 /* Check if the VISIBLE bit has changed */ 8912 if ((changed & INVISIBLE) != 0) { 8913 needGlobalAttributesUpdate(false); 8914 /* 8915 * If this view is becoming invisible, set the DRAWN flag so that 8916 * the next invalidate() will not be skipped. 8917 */ 8918 mPrivateFlags |= PFLAG_DRAWN; 8919 8920 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 8921 // root view becoming invisible shouldn't clear focus and accessibility focus 8922 if (getRootView() != this) { 8923 if (hasFocus()) clearFocus(); 8924 clearAccessibilityFocus(); 8925 } 8926 } 8927 if (mAttachInfo != null) { 8928 mAttachInfo.mViewVisibilityChanged = true; 8929 } 8930 } 8931 8932 if ((changed & VISIBILITY_MASK) != 0) { 8933 // If the view is invisible, cleanup its display list to free up resources 8934 if (newVisibility != VISIBLE) { 8935 cleanupDraw(); 8936 } 8937 8938 if (mParent instanceof ViewGroup) { 8939 ((ViewGroup) mParent).onChildVisibilityChanged(this, 8940 (changed & VISIBILITY_MASK), newVisibility); 8941 ((View) mParent).invalidate(true); 8942 } else if (mParent != null) { 8943 mParent.invalidateChild(this, null); 8944 } 8945 dispatchVisibilityChanged(this, newVisibility); 8946 } 8947 8948 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 8949 destroyDrawingCache(); 8950 } 8951 8952 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 8953 destroyDrawingCache(); 8954 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8955 invalidateParentCaches(); 8956 } 8957 8958 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 8959 destroyDrawingCache(); 8960 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8961 } 8962 8963 if ((changed & DRAW_MASK) != 0) { 8964 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 8965 if (mBackground != null) { 8966 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8967 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 8968 } else { 8969 mPrivateFlags |= PFLAG_SKIP_DRAW; 8970 } 8971 } else { 8972 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8973 } 8974 requestLayout(); 8975 invalidate(true); 8976 } 8977 8978 if ((changed & KEEP_SCREEN_ON) != 0) { 8979 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 8980 mParent.recomputeViewAttributes(this); 8981 } 8982 } 8983 8984 if (accessibilityEnabled) { 8985 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 8986 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 8987 if (oldIncludeForAccessibility != includeForAccessibility()) { 8988 notifySubtreeAccessibilityStateChangedIfNeeded(); 8989 } else { 8990 notifyViewAccessibilityStateChangedIfNeeded( 8991 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8992 } 8993 } else if ((changed & ENABLED_MASK) != 0) { 8994 notifyViewAccessibilityStateChangedIfNeeded( 8995 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8996 } 8997 } 8998 } 8999 9000 /** 9001 * Change the view's z order in the tree, so it's on top of other sibling 9002 * views. This ordering change may affect layout, if the parent container 9003 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9004 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9005 * method should be followed by calls to {@link #requestLayout()} and 9006 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9007 * with the new child ordering. 9008 * 9009 * @see ViewGroup#bringChildToFront(View) 9010 */ 9011 public void bringToFront() { 9012 if (mParent != null) { 9013 mParent.bringChildToFront(this); 9014 } 9015 } 9016 9017 /** 9018 * This is called in response to an internal scroll in this view (i.e., the 9019 * view scrolled its own contents). This is typically as a result of 9020 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9021 * called. 9022 * 9023 * @param l Current horizontal scroll origin. 9024 * @param t Current vertical scroll origin. 9025 * @param oldl Previous horizontal scroll origin. 9026 * @param oldt Previous vertical scroll origin. 9027 */ 9028 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9029 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9030 postSendViewScrolledAccessibilityEventCallback(); 9031 } 9032 9033 mBackgroundSizeChanged = true; 9034 9035 final AttachInfo ai = mAttachInfo; 9036 if (ai != null) { 9037 ai.mViewScrollChanged = true; 9038 } 9039 } 9040 9041 /** 9042 * Interface definition for a callback to be invoked when the layout bounds of a view 9043 * changes due to layout processing. 9044 */ 9045 public interface OnLayoutChangeListener { 9046 /** 9047 * Called when the focus state of a view has changed. 9048 * 9049 * @param v The view whose state has changed. 9050 * @param left The new value of the view's left property. 9051 * @param top The new value of the view's top property. 9052 * @param right The new value of the view's right property. 9053 * @param bottom The new value of the view's bottom property. 9054 * @param oldLeft The previous value of the view's left property. 9055 * @param oldTop The previous value of the view's top property. 9056 * @param oldRight The previous value of the view's right property. 9057 * @param oldBottom The previous value of the view's bottom property. 9058 */ 9059 void onLayoutChange(View v, int left, int top, int right, int bottom, 9060 int oldLeft, int oldTop, int oldRight, int oldBottom); 9061 } 9062 9063 /** 9064 * This is called during layout when the size of this view has changed. If 9065 * you were just added to the view hierarchy, you're called with the old 9066 * values of 0. 9067 * 9068 * @param w Current width of this view. 9069 * @param h Current height of this view. 9070 * @param oldw Old width of this view. 9071 * @param oldh Old height of this view. 9072 */ 9073 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9074 } 9075 9076 /** 9077 * Called by draw to draw the child views. This may be overridden 9078 * by derived classes to gain control just before its children are drawn 9079 * (but after its own view has been drawn). 9080 * @param canvas the canvas on which to draw the view 9081 */ 9082 protected void dispatchDraw(Canvas canvas) { 9083 9084 } 9085 9086 /** 9087 * Gets the parent of this view. Note that the parent is a 9088 * ViewParent and not necessarily a View. 9089 * 9090 * @return Parent of this view. 9091 */ 9092 public final ViewParent getParent() { 9093 return mParent; 9094 } 9095 9096 /** 9097 * Set the horizontal scrolled position of your view. This will cause a call to 9098 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9099 * invalidated. 9100 * @param value the x position to scroll to 9101 */ 9102 public void setScrollX(int value) { 9103 scrollTo(value, mScrollY); 9104 } 9105 9106 /** 9107 * Set the vertical scrolled position of your view. This will cause a call to 9108 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9109 * invalidated. 9110 * @param value the y position to scroll to 9111 */ 9112 public void setScrollY(int value) { 9113 scrollTo(mScrollX, value); 9114 } 9115 9116 /** 9117 * Return the scrolled left position of this view. This is the left edge of 9118 * the displayed part of your view. You do not need to draw any pixels 9119 * farther left, since those are outside of the frame of your view on 9120 * screen. 9121 * 9122 * @return The left edge of the displayed part of your view, in pixels. 9123 */ 9124 public final int getScrollX() { 9125 return mScrollX; 9126 } 9127 9128 /** 9129 * Return the scrolled top position of this view. This is the top edge of 9130 * the displayed part of your view. You do not need to draw any pixels above 9131 * it, since those are outside of the frame of your view on screen. 9132 * 9133 * @return The top edge of the displayed part of your view, in pixels. 9134 */ 9135 public final int getScrollY() { 9136 return mScrollY; 9137 } 9138 9139 /** 9140 * Return the width of the your view. 9141 * 9142 * @return The width of your view, in pixels. 9143 */ 9144 @ViewDebug.ExportedProperty(category = "layout") 9145 public final int getWidth() { 9146 return mRight - mLeft; 9147 } 9148 9149 /** 9150 * Return the height of your view. 9151 * 9152 * @return The height of your view, in pixels. 9153 */ 9154 @ViewDebug.ExportedProperty(category = "layout") 9155 public final int getHeight() { 9156 return mBottom - mTop; 9157 } 9158 9159 /** 9160 * Return the visible drawing bounds of your view. Fills in the output 9161 * rectangle with the values from getScrollX(), getScrollY(), 9162 * getWidth(), and getHeight(). These bounds do not account for any 9163 * transformation properties currently set on the view, such as 9164 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9165 * 9166 * @param outRect The (scrolled) drawing bounds of the view. 9167 */ 9168 public void getDrawingRect(Rect outRect) { 9169 outRect.left = mScrollX; 9170 outRect.top = mScrollY; 9171 outRect.right = mScrollX + (mRight - mLeft); 9172 outRect.bottom = mScrollY + (mBottom - mTop); 9173 } 9174 9175 /** 9176 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9177 * raw width component (that is the result is masked by 9178 * {@link #MEASURED_SIZE_MASK}). 9179 * 9180 * @return The raw measured width of this view. 9181 */ 9182 public final int getMeasuredWidth() { 9183 return mMeasuredWidth & MEASURED_SIZE_MASK; 9184 } 9185 9186 /** 9187 * Return the full width measurement information for this view as computed 9188 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9189 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9190 * This should be used during measurement and layout calculations only. Use 9191 * {@link #getWidth()} to see how wide a view is after layout. 9192 * 9193 * @return The measured width of this view as a bit mask. 9194 */ 9195 public final int getMeasuredWidthAndState() { 9196 return mMeasuredWidth; 9197 } 9198 9199 /** 9200 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9201 * raw width component (that is the result is masked by 9202 * {@link #MEASURED_SIZE_MASK}). 9203 * 9204 * @return The raw measured height of this view. 9205 */ 9206 public final int getMeasuredHeight() { 9207 return mMeasuredHeight & MEASURED_SIZE_MASK; 9208 } 9209 9210 /** 9211 * Return the full height measurement information for this view as computed 9212 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9213 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9214 * This should be used during measurement and layout calculations only. Use 9215 * {@link #getHeight()} to see how wide a view is after layout. 9216 * 9217 * @return The measured width of this view as a bit mask. 9218 */ 9219 public final int getMeasuredHeightAndState() { 9220 return mMeasuredHeight; 9221 } 9222 9223 /** 9224 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9225 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9226 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9227 * and the height component is at the shifted bits 9228 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9229 */ 9230 public final int getMeasuredState() { 9231 return (mMeasuredWidth&MEASURED_STATE_MASK) 9232 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9233 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9234 } 9235 9236 /** 9237 * The transform matrix of this view, which is calculated based on the current 9238 * roation, scale, and pivot properties. 9239 * 9240 * @see #getRotation() 9241 * @see #getScaleX() 9242 * @see #getScaleY() 9243 * @see #getPivotX() 9244 * @see #getPivotY() 9245 * @return The current transform matrix for the view 9246 */ 9247 public Matrix getMatrix() { 9248 if (mTransformationInfo != null) { 9249 updateMatrix(); 9250 return mTransformationInfo.mMatrix; 9251 } 9252 return Matrix.IDENTITY_MATRIX; 9253 } 9254 9255 /** 9256 * Utility function to determine if the value is far enough away from zero to be 9257 * considered non-zero. 9258 * @param value A floating point value to check for zero-ness 9259 * @return whether the passed-in value is far enough away from zero to be considered non-zero 9260 */ 9261 private static boolean nonzero(float value) { 9262 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 9263 } 9264 9265 /** 9266 * Returns true if the transform matrix is the identity matrix. 9267 * Recomputes the matrix if necessary. 9268 * 9269 * @return True if the transform matrix is the identity matrix, false otherwise. 9270 */ 9271 final boolean hasIdentityMatrix() { 9272 if (mTransformationInfo != null) { 9273 updateMatrix(); 9274 return mTransformationInfo.mMatrixIsIdentity; 9275 } 9276 return true; 9277 } 9278 9279 void ensureTransformationInfo() { 9280 if (mTransformationInfo == null) { 9281 mTransformationInfo = new TransformationInfo(); 9282 } 9283 } 9284 9285 /** 9286 * Recomputes the transform matrix if necessary. 9287 */ 9288 private void updateMatrix() { 9289 final TransformationInfo info = mTransformationInfo; 9290 if (info == null) { 9291 return; 9292 } 9293 if (info.mMatrixDirty) { 9294 // transform-related properties have changed since the last time someone 9295 // asked for the matrix; recalculate it with the current values 9296 9297 // Figure out if we need to update the pivot point 9298 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9299 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 9300 info.mPrevWidth = mRight - mLeft; 9301 info.mPrevHeight = mBottom - mTop; 9302 info.mPivotX = info.mPrevWidth / 2f; 9303 info.mPivotY = info.mPrevHeight / 2f; 9304 } 9305 } 9306 info.mMatrix.reset(); 9307 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 9308 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 9309 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 9310 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 9311 } else { 9312 if (info.mCamera == null) { 9313 info.mCamera = new Camera(); 9314 info.matrix3D = new Matrix(); 9315 } 9316 info.mCamera.save(); 9317 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 9318 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 9319 info.mCamera.getMatrix(info.matrix3D); 9320 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 9321 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 9322 info.mPivotY + info.mTranslationY); 9323 info.mMatrix.postConcat(info.matrix3D); 9324 info.mCamera.restore(); 9325 } 9326 info.mMatrixDirty = false; 9327 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 9328 info.mInverseMatrixDirty = true; 9329 } 9330 } 9331 9332 /** 9333 * Utility method to retrieve the inverse of the current mMatrix property. 9334 * We cache the matrix to avoid recalculating it when transform properties 9335 * have not changed. 9336 * 9337 * @return The inverse of the current matrix of this view. 9338 */ 9339 final Matrix getInverseMatrix() { 9340 final TransformationInfo info = mTransformationInfo; 9341 if (info != null) { 9342 updateMatrix(); 9343 if (info.mInverseMatrixDirty) { 9344 if (info.mInverseMatrix == null) { 9345 info.mInverseMatrix = new Matrix(); 9346 } 9347 info.mMatrix.invert(info.mInverseMatrix); 9348 info.mInverseMatrixDirty = false; 9349 } 9350 return info.mInverseMatrix; 9351 } 9352 return Matrix.IDENTITY_MATRIX; 9353 } 9354 9355 /** 9356 * Gets the distance along the Z axis from the camera to this view. 9357 * 9358 * @see #setCameraDistance(float) 9359 * 9360 * @return The distance along the Z axis. 9361 */ 9362 public float getCameraDistance() { 9363 ensureTransformationInfo(); 9364 final float dpi = mResources.getDisplayMetrics().densityDpi; 9365 final TransformationInfo info = mTransformationInfo; 9366 if (info.mCamera == null) { 9367 info.mCamera = new Camera(); 9368 info.matrix3D = new Matrix(); 9369 } 9370 return -(info.mCamera.getLocationZ() * dpi); 9371 } 9372 9373 /** 9374 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9375 * views are drawn) from the camera to this view. The camera's distance 9376 * affects 3D transformations, for instance rotations around the X and Y 9377 * axis. If the rotationX or rotationY properties are changed and this view is 9378 * large (more than half the size of the screen), it is recommended to always 9379 * use a camera distance that's greater than the height (X axis rotation) or 9380 * the width (Y axis rotation) of this view.</p> 9381 * 9382 * <p>The distance of the camera from the view plane can have an affect on the 9383 * perspective distortion of the view when it is rotated around the x or y axis. 9384 * For example, a large distance will result in a large viewing angle, and there 9385 * will not be much perspective distortion of the view as it rotates. A short 9386 * distance may cause much more perspective distortion upon rotation, and can 9387 * also result in some drawing artifacts if the rotated view ends up partially 9388 * behind the camera (which is why the recommendation is to use a distance at 9389 * least as far as the size of the view, if the view is to be rotated.)</p> 9390 * 9391 * <p>The distance is expressed in "depth pixels." The default distance depends 9392 * on the screen density. For instance, on a medium density display, the 9393 * default distance is 1280. On a high density display, the default distance 9394 * is 1920.</p> 9395 * 9396 * <p>If you want to specify a distance that leads to visually consistent 9397 * results across various densities, use the following formula:</p> 9398 * <pre> 9399 * float scale = context.getResources().getDisplayMetrics().density; 9400 * view.setCameraDistance(distance * scale); 9401 * </pre> 9402 * 9403 * <p>The density scale factor of a high density display is 1.5, 9404 * and 1920 = 1280 * 1.5.</p> 9405 * 9406 * @param distance The distance in "depth pixels", if negative the opposite 9407 * value is used 9408 * 9409 * @see #setRotationX(float) 9410 * @see #setRotationY(float) 9411 */ 9412 public void setCameraDistance(float distance) { 9413 invalidateViewProperty(true, false); 9414 9415 ensureTransformationInfo(); 9416 final float dpi = mResources.getDisplayMetrics().densityDpi; 9417 final TransformationInfo info = mTransformationInfo; 9418 if (info.mCamera == null) { 9419 info.mCamera = new Camera(); 9420 info.matrix3D = new Matrix(); 9421 } 9422 9423 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 9424 info.mMatrixDirty = true; 9425 9426 invalidateViewProperty(false, false); 9427 if (mDisplayList != null) { 9428 mDisplayList.setCameraDistance(-Math.abs(distance) / dpi); 9429 } 9430 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9431 // View was rejected last time it was drawn by its parent; this may have changed 9432 invalidateParentIfNeeded(); 9433 } 9434 } 9435 9436 /** 9437 * The degrees that the view is rotated around the pivot point. 9438 * 9439 * @see #setRotation(float) 9440 * @see #getPivotX() 9441 * @see #getPivotY() 9442 * 9443 * @return The degrees of rotation. 9444 */ 9445 @ViewDebug.ExportedProperty(category = "drawing") 9446 public float getRotation() { 9447 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 9448 } 9449 9450 /** 9451 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9452 * result in clockwise rotation. 9453 * 9454 * @param rotation The degrees of rotation. 9455 * 9456 * @see #getRotation() 9457 * @see #getPivotX() 9458 * @see #getPivotY() 9459 * @see #setRotationX(float) 9460 * @see #setRotationY(float) 9461 * 9462 * @attr ref android.R.styleable#View_rotation 9463 */ 9464 public void setRotation(float rotation) { 9465 ensureTransformationInfo(); 9466 final TransformationInfo info = mTransformationInfo; 9467 if (info.mRotation != rotation) { 9468 // Double-invalidation is necessary to capture view's old and new areas 9469 invalidateViewProperty(true, false); 9470 info.mRotation = rotation; 9471 info.mMatrixDirty = true; 9472 invalidateViewProperty(false, true); 9473 if (mDisplayList != null) { 9474 mDisplayList.setRotation(rotation); 9475 } 9476 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9477 // View was rejected last time it was drawn by its parent; this may have changed 9478 invalidateParentIfNeeded(); 9479 } 9480 } 9481 } 9482 9483 /** 9484 * The degrees that the view is rotated around the vertical axis through the pivot point. 9485 * 9486 * @see #getPivotX() 9487 * @see #getPivotY() 9488 * @see #setRotationY(float) 9489 * 9490 * @return The degrees of Y rotation. 9491 */ 9492 @ViewDebug.ExportedProperty(category = "drawing") 9493 public float getRotationY() { 9494 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 9495 } 9496 9497 /** 9498 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9499 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9500 * down the y axis. 9501 * 9502 * When rotating large views, it is recommended to adjust the camera distance 9503 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9504 * 9505 * @param rotationY The degrees of Y rotation. 9506 * 9507 * @see #getRotationY() 9508 * @see #getPivotX() 9509 * @see #getPivotY() 9510 * @see #setRotation(float) 9511 * @see #setRotationX(float) 9512 * @see #setCameraDistance(float) 9513 * 9514 * @attr ref android.R.styleable#View_rotationY 9515 */ 9516 public void setRotationY(float rotationY) { 9517 ensureTransformationInfo(); 9518 final TransformationInfo info = mTransformationInfo; 9519 if (info.mRotationY != rotationY) { 9520 invalidateViewProperty(true, false); 9521 info.mRotationY = rotationY; 9522 info.mMatrixDirty = true; 9523 invalidateViewProperty(false, true); 9524 if (mDisplayList != null) { 9525 mDisplayList.setRotationY(rotationY); 9526 } 9527 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9528 // View was rejected last time it was drawn by its parent; this may have changed 9529 invalidateParentIfNeeded(); 9530 } 9531 } 9532 } 9533 9534 /** 9535 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9536 * 9537 * @see #getPivotX() 9538 * @see #getPivotY() 9539 * @see #setRotationX(float) 9540 * 9541 * @return The degrees of X rotation. 9542 */ 9543 @ViewDebug.ExportedProperty(category = "drawing") 9544 public float getRotationX() { 9545 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 9546 } 9547 9548 /** 9549 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9550 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9551 * x axis. 9552 * 9553 * When rotating large views, it is recommended to adjust the camera distance 9554 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9555 * 9556 * @param rotationX The degrees of X rotation. 9557 * 9558 * @see #getRotationX() 9559 * @see #getPivotX() 9560 * @see #getPivotY() 9561 * @see #setRotation(float) 9562 * @see #setRotationY(float) 9563 * @see #setCameraDistance(float) 9564 * 9565 * @attr ref android.R.styleable#View_rotationX 9566 */ 9567 public void setRotationX(float rotationX) { 9568 ensureTransformationInfo(); 9569 final TransformationInfo info = mTransformationInfo; 9570 if (info.mRotationX != rotationX) { 9571 invalidateViewProperty(true, false); 9572 info.mRotationX = rotationX; 9573 info.mMatrixDirty = true; 9574 invalidateViewProperty(false, true); 9575 if (mDisplayList != null) { 9576 mDisplayList.setRotationX(rotationX); 9577 } 9578 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9579 // View was rejected last time it was drawn by its parent; this may have changed 9580 invalidateParentIfNeeded(); 9581 } 9582 } 9583 } 9584 9585 /** 9586 * The amount that the view is scaled in x around the pivot point, as a proportion of 9587 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9588 * 9589 * <p>By default, this is 1.0f. 9590 * 9591 * @see #getPivotX() 9592 * @see #getPivotY() 9593 * @return The scaling factor. 9594 */ 9595 @ViewDebug.ExportedProperty(category = "drawing") 9596 public float getScaleX() { 9597 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 9598 } 9599 9600 /** 9601 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9602 * the view's unscaled width. A value of 1 means that no scaling is applied. 9603 * 9604 * @param scaleX The scaling factor. 9605 * @see #getPivotX() 9606 * @see #getPivotY() 9607 * 9608 * @attr ref android.R.styleable#View_scaleX 9609 */ 9610 public void setScaleX(float scaleX) { 9611 ensureTransformationInfo(); 9612 final TransformationInfo info = mTransformationInfo; 9613 if (info.mScaleX != scaleX) { 9614 invalidateViewProperty(true, false); 9615 info.mScaleX = scaleX; 9616 info.mMatrixDirty = true; 9617 invalidateViewProperty(false, true); 9618 if (mDisplayList != null) { 9619 mDisplayList.setScaleX(scaleX); 9620 } 9621 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9622 // View was rejected last time it was drawn by its parent; this may have changed 9623 invalidateParentIfNeeded(); 9624 } 9625 } 9626 } 9627 9628 /** 9629 * The amount that the view is scaled in y around the pivot point, as a proportion of 9630 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9631 * 9632 * <p>By default, this is 1.0f. 9633 * 9634 * @see #getPivotX() 9635 * @see #getPivotY() 9636 * @return The scaling factor. 9637 */ 9638 @ViewDebug.ExportedProperty(category = "drawing") 9639 public float getScaleY() { 9640 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 9641 } 9642 9643 /** 9644 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9645 * the view's unscaled width. A value of 1 means that no scaling is applied. 9646 * 9647 * @param scaleY The scaling factor. 9648 * @see #getPivotX() 9649 * @see #getPivotY() 9650 * 9651 * @attr ref android.R.styleable#View_scaleY 9652 */ 9653 public void setScaleY(float scaleY) { 9654 ensureTransformationInfo(); 9655 final TransformationInfo info = mTransformationInfo; 9656 if (info.mScaleY != scaleY) { 9657 invalidateViewProperty(true, false); 9658 info.mScaleY = scaleY; 9659 info.mMatrixDirty = true; 9660 invalidateViewProperty(false, true); 9661 if (mDisplayList != null) { 9662 mDisplayList.setScaleY(scaleY); 9663 } 9664 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9665 // View was rejected last time it was drawn by its parent; this may have changed 9666 invalidateParentIfNeeded(); 9667 } 9668 } 9669 } 9670 9671 /** 9672 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9673 * and {@link #setScaleX(float) scaled}. 9674 * 9675 * @see #getRotation() 9676 * @see #getScaleX() 9677 * @see #getScaleY() 9678 * @see #getPivotY() 9679 * @return The x location of the pivot point. 9680 * 9681 * @attr ref android.R.styleable#View_transformPivotX 9682 */ 9683 @ViewDebug.ExportedProperty(category = "drawing") 9684 public float getPivotX() { 9685 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 9686 } 9687 9688 /** 9689 * Sets the x location of the point around which the view is 9690 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 9691 * By default, the pivot point is centered on the object. 9692 * Setting this property disables this behavior and causes the view to use only the 9693 * explicitly set pivotX and pivotY values. 9694 * 9695 * @param pivotX The x location of the pivot point. 9696 * @see #getRotation() 9697 * @see #getScaleX() 9698 * @see #getScaleY() 9699 * @see #getPivotY() 9700 * 9701 * @attr ref android.R.styleable#View_transformPivotX 9702 */ 9703 public void setPivotX(float pivotX) { 9704 ensureTransformationInfo(); 9705 final TransformationInfo info = mTransformationInfo; 9706 boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 9707 PFLAG_PIVOT_EXPLICITLY_SET; 9708 if (info.mPivotX != pivotX || !pivotSet) { 9709 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9710 invalidateViewProperty(true, false); 9711 info.mPivotX = pivotX; 9712 info.mMatrixDirty = true; 9713 invalidateViewProperty(false, true); 9714 if (mDisplayList != null) { 9715 mDisplayList.setPivotX(pivotX); 9716 } 9717 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9718 // View was rejected last time it was drawn by its parent; this may have changed 9719 invalidateParentIfNeeded(); 9720 } 9721 } 9722 } 9723 9724 /** 9725 * The y location of the point around which the view is {@link #setRotation(float) rotated} 9726 * and {@link #setScaleY(float) scaled}. 9727 * 9728 * @see #getRotation() 9729 * @see #getScaleX() 9730 * @see #getScaleY() 9731 * @see #getPivotY() 9732 * @return The y location of the pivot point. 9733 * 9734 * @attr ref android.R.styleable#View_transformPivotY 9735 */ 9736 @ViewDebug.ExportedProperty(category = "drawing") 9737 public float getPivotY() { 9738 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 9739 } 9740 9741 /** 9742 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 9743 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 9744 * Setting this property disables this behavior and causes the view to use only the 9745 * explicitly set pivotX and pivotY values. 9746 * 9747 * @param pivotY The y location of the pivot point. 9748 * @see #getRotation() 9749 * @see #getScaleX() 9750 * @see #getScaleY() 9751 * @see #getPivotY() 9752 * 9753 * @attr ref android.R.styleable#View_transformPivotY 9754 */ 9755 public void setPivotY(float pivotY) { 9756 ensureTransformationInfo(); 9757 final TransformationInfo info = mTransformationInfo; 9758 boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 9759 PFLAG_PIVOT_EXPLICITLY_SET; 9760 if (info.mPivotY != pivotY || !pivotSet) { 9761 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9762 invalidateViewProperty(true, false); 9763 info.mPivotY = pivotY; 9764 info.mMatrixDirty = true; 9765 invalidateViewProperty(false, true); 9766 if (mDisplayList != null) { 9767 mDisplayList.setPivotY(pivotY); 9768 } 9769 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9770 // View was rejected last time it was drawn by its parent; this may have changed 9771 invalidateParentIfNeeded(); 9772 } 9773 } 9774 } 9775 9776 /** 9777 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 9778 * completely transparent and 1 means the view is completely opaque. 9779 * 9780 * <p>By default this is 1.0f. 9781 * @return The opacity of the view. 9782 */ 9783 @ViewDebug.ExportedProperty(category = "drawing") 9784 public float getAlpha() { 9785 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 9786 } 9787 9788 /** 9789 * Returns whether this View has content which overlaps. 9790 * 9791 * <p>This function, intended to be overridden by specific View types, is an optimization when 9792 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 9793 * an offscreen buffer and then composited into place, which can be expensive. If the view has 9794 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 9795 * directly. An example of overlapping rendering is a TextView with a background image, such as 9796 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 9797 * ImageView with only the foreground image. The default implementation returns true; subclasses 9798 * should override if they have cases which can be optimized.</p> 9799 * 9800 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 9801 * necessitates that a View return true if it uses the methods internally without passing the 9802 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 9803 * 9804 * @return true if the content in this view might overlap, false otherwise. 9805 */ 9806 public boolean hasOverlappingRendering() { 9807 return true; 9808 } 9809 9810 /** 9811 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 9812 * completely transparent and 1 means the view is completely opaque.</p> 9813 * 9814 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 9815 * performance implications, especially for large views. It is best to use the alpha property 9816 * sparingly and transiently, as in the case of fading animations.</p> 9817 * 9818 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 9819 * strongly recommended for performance reasons to either override 9820 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 9821 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 9822 * 9823 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 9824 * responsible for applying the opacity itself.</p> 9825 * 9826 * <p>Note that if the view is backed by a 9827 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 9828 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 9829 * 1.0 will supercede the alpha of the layer paint.</p> 9830 * 9831 * @param alpha The opacity of the view. 9832 * 9833 * @see #hasOverlappingRendering() 9834 * @see #setLayerType(int, android.graphics.Paint) 9835 * 9836 * @attr ref android.R.styleable#View_alpha 9837 */ 9838 public void setAlpha(float alpha) { 9839 ensureTransformationInfo(); 9840 if (mTransformationInfo.mAlpha != alpha) { 9841 mTransformationInfo.mAlpha = alpha; 9842 if (onSetAlpha((int) (alpha * 255))) { 9843 mPrivateFlags |= PFLAG_ALPHA_SET; 9844 // subclass is handling alpha - don't optimize rendering cache invalidation 9845 invalidateParentCaches(); 9846 invalidate(true); 9847 } else { 9848 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9849 invalidateViewProperty(true, false); 9850 if (mDisplayList != null) { 9851 mDisplayList.setAlpha(getFinalAlpha()); 9852 } 9853 } 9854 } 9855 } 9856 9857 /** 9858 * Faster version of setAlpha() which performs the same steps except there are 9859 * no calls to invalidate(). The caller of this function should perform proper invalidation 9860 * on the parent and this object. The return value indicates whether the subclass handles 9861 * alpha (the return value for onSetAlpha()). 9862 * 9863 * @param alpha The new value for the alpha property 9864 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 9865 * the new value for the alpha property is different from the old value 9866 */ 9867 boolean setAlphaNoInvalidation(float alpha) { 9868 ensureTransformationInfo(); 9869 if (mTransformationInfo.mAlpha != alpha) { 9870 mTransformationInfo.mAlpha = alpha; 9871 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 9872 if (subclassHandlesAlpha) { 9873 mPrivateFlags |= PFLAG_ALPHA_SET; 9874 return true; 9875 } else { 9876 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9877 if (mDisplayList != null) { 9878 mDisplayList.setAlpha(getFinalAlpha()); 9879 } 9880 } 9881 } 9882 return false; 9883 } 9884 9885 /** 9886 * This property is hidden and intended only for use by the Fade transition, which 9887 * animates it to produce a visual translucency that does not side-effect (or get 9888 * affected by) the real alpha property. This value is composited with the other 9889 * alpha value (and the AlphaAnimation value, when that is present) to produce 9890 * a final visual translucency result, which is what is passed into the DisplayList. 9891 * 9892 * @hide 9893 */ 9894 public void setTransitionAlpha(float alpha) { 9895 ensureTransformationInfo(); 9896 if (mTransformationInfo.mTransitionAlpha != alpha) { 9897 mTransformationInfo.mTransitionAlpha = alpha; 9898 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9899 invalidateViewProperty(true, false); 9900 if (mDisplayList != null) { 9901 mDisplayList.setAlpha(getFinalAlpha()); 9902 } 9903 } 9904 } 9905 9906 /** 9907 * Calculates the visual alpha of this view, which is a combination of the actual 9908 * alpha value and the transitionAlpha value (if set). 9909 */ 9910 private float getFinalAlpha() { 9911 if (mTransformationInfo != null) { 9912 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 9913 } 9914 return 1; 9915 } 9916 9917 /** 9918 * This property is hidden and intended only for use by the Fade transition, which 9919 * animates it to produce a visual translucency that does not side-effect (or get 9920 * affected by) the real alpha property. This value is composited with the other 9921 * alpha value (and the AlphaAnimation value, when that is present) to produce 9922 * a final visual translucency result, which is what is passed into the DisplayList. 9923 * 9924 * @hide 9925 */ 9926 public float getTransitionAlpha() { 9927 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 9928 } 9929 9930 /** 9931 * Top position of this view relative to its parent. 9932 * 9933 * @return The top of this view, in pixels. 9934 */ 9935 @ViewDebug.CapturedViewProperty 9936 public final int getTop() { 9937 return mTop; 9938 } 9939 9940 /** 9941 * Sets the top position of this view relative to its parent. This method is meant to be called 9942 * by the layout system and should not generally be called otherwise, because the property 9943 * may be changed at any time by the layout. 9944 * 9945 * @param top The top of this view, in pixels. 9946 */ 9947 public final void setTop(int top) { 9948 if (top != mTop) { 9949 updateMatrix(); 9950 final boolean matrixIsIdentity = mTransformationInfo == null 9951 || mTransformationInfo.mMatrixIsIdentity; 9952 if (matrixIsIdentity) { 9953 if (mAttachInfo != null) { 9954 int minTop; 9955 int yLoc; 9956 if (top < mTop) { 9957 minTop = top; 9958 yLoc = top - mTop; 9959 } else { 9960 minTop = mTop; 9961 yLoc = 0; 9962 } 9963 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 9964 } 9965 } else { 9966 // Double-invalidation is necessary to capture view's old and new areas 9967 invalidate(true); 9968 } 9969 9970 int width = mRight - mLeft; 9971 int oldHeight = mBottom - mTop; 9972 9973 mTop = top; 9974 if (mDisplayList != null) { 9975 mDisplayList.setTop(mTop); 9976 } 9977 9978 sizeChange(width, mBottom - mTop, width, oldHeight); 9979 9980 if (!matrixIsIdentity) { 9981 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9982 // A change in dimension means an auto-centered pivot point changes, too 9983 mTransformationInfo.mMatrixDirty = true; 9984 } 9985 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9986 invalidate(true); 9987 } 9988 mBackgroundSizeChanged = true; 9989 invalidateParentIfNeeded(); 9990 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9991 // View was rejected last time it was drawn by its parent; this may have changed 9992 invalidateParentIfNeeded(); 9993 } 9994 } 9995 } 9996 9997 /** 9998 * Bottom position of this view relative to its parent. 9999 * 10000 * @return The bottom of this view, in pixels. 10001 */ 10002 @ViewDebug.CapturedViewProperty 10003 public final int getBottom() { 10004 return mBottom; 10005 } 10006 10007 /** 10008 * True if this view has changed since the last time being drawn. 10009 * 10010 * @return The dirty state of this view. 10011 */ 10012 public boolean isDirty() { 10013 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10014 } 10015 10016 /** 10017 * Sets the bottom position of this view relative to its parent. This method is meant to be 10018 * called by the layout system and should not generally be called otherwise, because the 10019 * property may be changed at any time by the layout. 10020 * 10021 * @param bottom The bottom of this view, in pixels. 10022 */ 10023 public final void setBottom(int bottom) { 10024 if (bottom != mBottom) { 10025 updateMatrix(); 10026 final boolean matrixIsIdentity = mTransformationInfo == null 10027 || mTransformationInfo.mMatrixIsIdentity; 10028 if (matrixIsIdentity) { 10029 if (mAttachInfo != null) { 10030 int maxBottom; 10031 if (bottom < mBottom) { 10032 maxBottom = mBottom; 10033 } else { 10034 maxBottom = bottom; 10035 } 10036 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10037 } 10038 } else { 10039 // Double-invalidation is necessary to capture view's old and new areas 10040 invalidate(true); 10041 } 10042 10043 int width = mRight - mLeft; 10044 int oldHeight = mBottom - mTop; 10045 10046 mBottom = bottom; 10047 if (mDisplayList != null) { 10048 mDisplayList.setBottom(mBottom); 10049 } 10050 10051 sizeChange(width, mBottom - mTop, width, oldHeight); 10052 10053 if (!matrixIsIdentity) { 10054 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10055 // A change in dimension means an auto-centered pivot point changes, too 10056 mTransformationInfo.mMatrixDirty = true; 10057 } 10058 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10059 invalidate(true); 10060 } 10061 mBackgroundSizeChanged = true; 10062 invalidateParentIfNeeded(); 10063 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10064 // View was rejected last time it was drawn by its parent; this may have changed 10065 invalidateParentIfNeeded(); 10066 } 10067 } 10068 } 10069 10070 /** 10071 * Left position of this view relative to its parent. 10072 * 10073 * @return The left edge of this view, in pixels. 10074 */ 10075 @ViewDebug.CapturedViewProperty 10076 public final int getLeft() { 10077 return mLeft; 10078 } 10079 10080 /** 10081 * Sets the left position of this view relative to its parent. This method is meant to be called 10082 * by the layout system and should not generally be called otherwise, because the property 10083 * may be changed at any time by the layout. 10084 * 10085 * @param left The bottom of this view, in pixels. 10086 */ 10087 public final void setLeft(int left) { 10088 if (left != mLeft) { 10089 updateMatrix(); 10090 final boolean matrixIsIdentity = mTransformationInfo == null 10091 || mTransformationInfo.mMatrixIsIdentity; 10092 if (matrixIsIdentity) { 10093 if (mAttachInfo != null) { 10094 int minLeft; 10095 int xLoc; 10096 if (left < mLeft) { 10097 minLeft = left; 10098 xLoc = left - mLeft; 10099 } else { 10100 minLeft = mLeft; 10101 xLoc = 0; 10102 } 10103 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10104 } 10105 } else { 10106 // Double-invalidation is necessary to capture view's old and new areas 10107 invalidate(true); 10108 } 10109 10110 int oldWidth = mRight - mLeft; 10111 int height = mBottom - mTop; 10112 10113 mLeft = left; 10114 if (mDisplayList != null) { 10115 mDisplayList.setLeft(left); 10116 } 10117 10118 sizeChange(mRight - mLeft, height, oldWidth, height); 10119 10120 if (!matrixIsIdentity) { 10121 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10122 // A change in dimension means an auto-centered pivot point changes, too 10123 mTransformationInfo.mMatrixDirty = true; 10124 } 10125 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10126 invalidate(true); 10127 } 10128 mBackgroundSizeChanged = true; 10129 invalidateParentIfNeeded(); 10130 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10131 // View was rejected last time it was drawn by its parent; this may have changed 10132 invalidateParentIfNeeded(); 10133 } 10134 } 10135 } 10136 10137 /** 10138 * Right position of this view relative to its parent. 10139 * 10140 * @return The right edge of this view, in pixels. 10141 */ 10142 @ViewDebug.CapturedViewProperty 10143 public final int getRight() { 10144 return mRight; 10145 } 10146 10147 /** 10148 * Sets the right position of this view relative to its parent. This method is meant to be called 10149 * by the layout system and should not generally be called otherwise, because the property 10150 * may be changed at any time by the layout. 10151 * 10152 * @param right The bottom of this view, in pixels. 10153 */ 10154 public final void setRight(int right) { 10155 if (right != mRight) { 10156 updateMatrix(); 10157 final boolean matrixIsIdentity = mTransformationInfo == null 10158 || mTransformationInfo.mMatrixIsIdentity; 10159 if (matrixIsIdentity) { 10160 if (mAttachInfo != null) { 10161 int maxRight; 10162 if (right < mRight) { 10163 maxRight = mRight; 10164 } else { 10165 maxRight = right; 10166 } 10167 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10168 } 10169 } else { 10170 // Double-invalidation is necessary to capture view's old and new areas 10171 invalidate(true); 10172 } 10173 10174 int oldWidth = mRight - mLeft; 10175 int height = mBottom - mTop; 10176 10177 mRight = right; 10178 if (mDisplayList != null) { 10179 mDisplayList.setRight(mRight); 10180 } 10181 10182 sizeChange(mRight - mLeft, height, oldWidth, height); 10183 10184 if (!matrixIsIdentity) { 10185 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10186 // A change in dimension means an auto-centered pivot point changes, too 10187 mTransformationInfo.mMatrixDirty = true; 10188 } 10189 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10190 invalidate(true); 10191 } 10192 mBackgroundSizeChanged = true; 10193 invalidateParentIfNeeded(); 10194 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10195 // View was rejected last time it was drawn by its parent; this may have changed 10196 invalidateParentIfNeeded(); 10197 } 10198 } 10199 } 10200 10201 /** 10202 * The visual x position of this view, in pixels. This is equivalent to the 10203 * {@link #setTranslationX(float) translationX} property plus the current 10204 * {@link #getLeft() left} property. 10205 * 10206 * @return The visual x position of this view, in pixels. 10207 */ 10208 @ViewDebug.ExportedProperty(category = "drawing") 10209 public float getX() { 10210 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 10211 } 10212 10213 /** 10214 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10215 * {@link #setTranslationX(float) translationX} property to be the difference between 10216 * the x value passed in and the current {@link #getLeft() left} property. 10217 * 10218 * @param x The visual x position of this view, in pixels. 10219 */ 10220 public void setX(float x) { 10221 setTranslationX(x - mLeft); 10222 } 10223 10224 /** 10225 * The visual y position of this view, in pixels. This is equivalent to the 10226 * {@link #setTranslationY(float) translationY} property plus the current 10227 * {@link #getTop() top} property. 10228 * 10229 * @return The visual y position of this view, in pixels. 10230 */ 10231 @ViewDebug.ExportedProperty(category = "drawing") 10232 public float getY() { 10233 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 10234 } 10235 10236 /** 10237 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10238 * {@link #setTranslationY(float) translationY} property to be the difference between 10239 * the y value passed in and the current {@link #getTop() top} property. 10240 * 10241 * @param y The visual y position of this view, in pixels. 10242 */ 10243 public void setY(float y) { 10244 setTranslationY(y - mTop); 10245 } 10246 10247 10248 /** 10249 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10250 * This position is post-layout, in addition to wherever the object's 10251 * layout placed it. 10252 * 10253 * @return The horizontal position of this view relative to its left position, in pixels. 10254 */ 10255 @ViewDebug.ExportedProperty(category = "drawing") 10256 public float getTranslationX() { 10257 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 10258 } 10259 10260 /** 10261 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10262 * This effectively positions the object post-layout, in addition to wherever the object's 10263 * layout placed it. 10264 * 10265 * @param translationX The horizontal position of this view relative to its left position, 10266 * in pixels. 10267 * 10268 * @attr ref android.R.styleable#View_translationX 10269 */ 10270 public void setTranslationX(float translationX) { 10271 ensureTransformationInfo(); 10272 final TransformationInfo info = mTransformationInfo; 10273 if (info.mTranslationX != translationX) { 10274 // Double-invalidation is necessary to capture view's old and new areas 10275 invalidateViewProperty(true, false); 10276 info.mTranslationX = translationX; 10277 info.mMatrixDirty = true; 10278 invalidateViewProperty(false, true); 10279 if (mDisplayList != null) { 10280 mDisplayList.setTranslationX(translationX); 10281 } 10282 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10283 // View was rejected last time it was drawn by its parent; this may have changed 10284 invalidateParentIfNeeded(); 10285 } 10286 } 10287 } 10288 10289 /** 10290 * The horizontal location of this view relative to its {@link #getTop() top} position. 10291 * This position is post-layout, in addition to wherever the object's 10292 * layout placed it. 10293 * 10294 * @return The vertical position of this view relative to its top position, 10295 * in pixels. 10296 */ 10297 @ViewDebug.ExportedProperty(category = "drawing") 10298 public float getTranslationY() { 10299 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 10300 } 10301 10302 /** 10303 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10304 * This effectively positions the object post-layout, in addition to wherever the object's 10305 * layout placed it. 10306 * 10307 * @param translationY The vertical position of this view relative to its top position, 10308 * in pixels. 10309 * 10310 * @attr ref android.R.styleable#View_translationY 10311 */ 10312 public void setTranslationY(float translationY) { 10313 ensureTransformationInfo(); 10314 final TransformationInfo info = mTransformationInfo; 10315 if (info.mTranslationY != translationY) { 10316 invalidateViewProperty(true, false); 10317 info.mTranslationY = translationY; 10318 info.mMatrixDirty = true; 10319 invalidateViewProperty(false, true); 10320 if (mDisplayList != null) { 10321 mDisplayList.setTranslationY(translationY); 10322 } 10323 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10324 // View was rejected last time it was drawn by its parent; this may have changed 10325 invalidateParentIfNeeded(); 10326 } 10327 } 10328 } 10329 10330 /** 10331 * Hit rectangle in parent's coordinates 10332 * 10333 * @param outRect The hit rectangle of the view. 10334 */ 10335 public void getHitRect(Rect outRect) { 10336 updateMatrix(); 10337 final TransformationInfo info = mTransformationInfo; 10338 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 10339 outRect.set(mLeft, mTop, mRight, mBottom); 10340 } else { 10341 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10342 tmpRect.set(0, 0, getWidth(), getHeight()); 10343 info.mMatrix.mapRect(tmpRect); 10344 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10345 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10346 } 10347 } 10348 10349 /** 10350 * Determines whether the given point, in local coordinates is inside the view. 10351 */ 10352 /*package*/ final boolean pointInView(float localX, float localY) { 10353 return localX >= 0 && localX < (mRight - mLeft) 10354 && localY >= 0 && localY < (mBottom - mTop); 10355 } 10356 10357 /** 10358 * Utility method to determine whether the given point, in local coordinates, 10359 * is inside the view, where the area of the view is expanded by the slop factor. 10360 * This method is called while processing touch-move events to determine if the event 10361 * is still within the view. 10362 * 10363 * @hide 10364 */ 10365 public boolean pointInView(float localX, float localY, float slop) { 10366 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10367 localY < ((mBottom - mTop) + slop); 10368 } 10369 10370 /** 10371 * When a view has focus and the user navigates away from it, the next view is searched for 10372 * starting from the rectangle filled in by this method. 10373 * 10374 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10375 * of the view. However, if your view maintains some idea of internal selection, 10376 * such as a cursor, or a selected row or column, you should override this method and 10377 * fill in a more specific rectangle. 10378 * 10379 * @param r The rectangle to fill in, in this view's coordinates. 10380 */ 10381 public void getFocusedRect(Rect r) { 10382 getDrawingRect(r); 10383 } 10384 10385 /** 10386 * If some part of this view is not clipped by any of its parents, then 10387 * return that area in r in global (root) coordinates. To convert r to local 10388 * coordinates (without taking possible View rotations into account), offset 10389 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10390 * If the view is completely clipped or translated out, return false. 10391 * 10392 * @param r If true is returned, r holds the global coordinates of the 10393 * visible portion of this view. 10394 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10395 * between this view and its root. globalOffet may be null. 10396 * @return true if r is non-empty (i.e. part of the view is visible at the 10397 * root level. 10398 */ 10399 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10400 int width = mRight - mLeft; 10401 int height = mBottom - mTop; 10402 if (width > 0 && height > 0) { 10403 r.set(0, 0, width, height); 10404 if (globalOffset != null) { 10405 globalOffset.set(-mScrollX, -mScrollY); 10406 } 10407 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10408 } 10409 return false; 10410 } 10411 10412 public final boolean getGlobalVisibleRect(Rect r) { 10413 return getGlobalVisibleRect(r, null); 10414 } 10415 10416 public final boolean getLocalVisibleRect(Rect r) { 10417 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10418 if (getGlobalVisibleRect(r, offset)) { 10419 r.offset(-offset.x, -offset.y); // make r local 10420 return true; 10421 } 10422 return false; 10423 } 10424 10425 /** 10426 * Offset this view's vertical location by the specified number of pixels. 10427 * 10428 * @param offset the number of pixels to offset the view by 10429 */ 10430 public void offsetTopAndBottom(int offset) { 10431 if (offset != 0) { 10432 updateMatrix(); 10433 final boolean matrixIsIdentity = mTransformationInfo == null 10434 || mTransformationInfo.mMatrixIsIdentity; 10435 if (matrixIsIdentity) { 10436 if (mDisplayList != null) { 10437 invalidateViewProperty(false, false); 10438 } else { 10439 final ViewParent p = mParent; 10440 if (p != null && mAttachInfo != null) { 10441 final Rect r = mAttachInfo.mTmpInvalRect; 10442 int minTop; 10443 int maxBottom; 10444 int yLoc; 10445 if (offset < 0) { 10446 minTop = mTop + offset; 10447 maxBottom = mBottom; 10448 yLoc = offset; 10449 } else { 10450 minTop = mTop; 10451 maxBottom = mBottom + offset; 10452 yLoc = 0; 10453 } 10454 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10455 p.invalidateChild(this, r); 10456 } 10457 } 10458 } else { 10459 invalidateViewProperty(false, false); 10460 } 10461 10462 mTop += offset; 10463 mBottom += offset; 10464 if (mDisplayList != null) { 10465 mDisplayList.offsetTopAndBottom(offset); 10466 invalidateViewProperty(false, false); 10467 } else { 10468 if (!matrixIsIdentity) { 10469 invalidateViewProperty(false, true); 10470 } 10471 invalidateParentIfNeeded(); 10472 } 10473 } 10474 } 10475 10476 /** 10477 * Offset this view's horizontal location by the specified amount of pixels. 10478 * 10479 * @param offset the number of pixels to offset the view by 10480 */ 10481 public void offsetLeftAndRight(int offset) { 10482 if (offset != 0) { 10483 updateMatrix(); 10484 final boolean matrixIsIdentity = mTransformationInfo == null 10485 || mTransformationInfo.mMatrixIsIdentity; 10486 if (matrixIsIdentity) { 10487 if (mDisplayList != null) { 10488 invalidateViewProperty(false, false); 10489 } else { 10490 final ViewParent p = mParent; 10491 if (p != null && mAttachInfo != null) { 10492 final Rect r = mAttachInfo.mTmpInvalRect; 10493 int minLeft; 10494 int maxRight; 10495 if (offset < 0) { 10496 minLeft = mLeft + offset; 10497 maxRight = mRight; 10498 } else { 10499 minLeft = mLeft; 10500 maxRight = mRight + offset; 10501 } 10502 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 10503 p.invalidateChild(this, r); 10504 } 10505 } 10506 } else { 10507 invalidateViewProperty(false, false); 10508 } 10509 10510 mLeft += offset; 10511 mRight += offset; 10512 if (mDisplayList != null) { 10513 mDisplayList.offsetLeftAndRight(offset); 10514 invalidateViewProperty(false, false); 10515 } else { 10516 if (!matrixIsIdentity) { 10517 invalidateViewProperty(false, true); 10518 } 10519 invalidateParentIfNeeded(); 10520 } 10521 } 10522 } 10523 10524 /** 10525 * Get the LayoutParams associated with this view. All views should have 10526 * layout parameters. These supply parameters to the <i>parent</i> of this 10527 * view specifying how it should be arranged. There are many subclasses of 10528 * ViewGroup.LayoutParams, and these correspond to the different subclasses 10529 * of ViewGroup that are responsible for arranging their children. 10530 * 10531 * This method may return null if this View is not attached to a parent 10532 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 10533 * was not invoked successfully. When a View is attached to a parent 10534 * ViewGroup, this method must not return null. 10535 * 10536 * @return The LayoutParams associated with this view, or null if no 10537 * parameters have been set yet 10538 */ 10539 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 10540 public ViewGroup.LayoutParams getLayoutParams() { 10541 return mLayoutParams; 10542 } 10543 10544 /** 10545 * Set the layout parameters associated with this view. These supply 10546 * parameters to the <i>parent</i> of this view specifying how it should be 10547 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 10548 * correspond to the different subclasses of ViewGroup that are responsible 10549 * for arranging their children. 10550 * 10551 * @param params The layout parameters for this view, cannot be null 10552 */ 10553 public void setLayoutParams(ViewGroup.LayoutParams params) { 10554 if (params == null) { 10555 throw new NullPointerException("Layout parameters cannot be null"); 10556 } 10557 mLayoutParams = params; 10558 resolveLayoutParams(); 10559 if (mParent instanceof ViewGroup) { 10560 ((ViewGroup) mParent).onSetLayoutParams(this, params); 10561 } 10562 requestLayout(); 10563 } 10564 10565 /** 10566 * Resolve the layout parameters depending on the resolved layout direction 10567 * 10568 * @hide 10569 */ 10570 public void resolveLayoutParams() { 10571 if (mLayoutParams != null) { 10572 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 10573 } 10574 } 10575 10576 /** 10577 * Set the scrolled position of your view. This will cause a call to 10578 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10579 * invalidated. 10580 * @param x the x position to scroll to 10581 * @param y the y position to scroll to 10582 */ 10583 public void scrollTo(int x, int y) { 10584 if (mScrollX != x || mScrollY != y) { 10585 int oldX = mScrollX; 10586 int oldY = mScrollY; 10587 mScrollX = x; 10588 mScrollY = y; 10589 invalidateParentCaches(); 10590 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 10591 if (!awakenScrollBars()) { 10592 postInvalidateOnAnimation(); 10593 } 10594 } 10595 } 10596 10597 /** 10598 * Move the scrolled position of your view. This will cause a call to 10599 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10600 * invalidated. 10601 * @param x the amount of pixels to scroll by horizontally 10602 * @param y the amount of pixels to scroll by vertically 10603 */ 10604 public void scrollBy(int x, int y) { 10605 scrollTo(mScrollX + x, mScrollY + y); 10606 } 10607 10608 /** 10609 * <p>Trigger the scrollbars to draw. When invoked this method starts an 10610 * animation to fade the scrollbars out after a default delay. If a subclass 10611 * provides animated scrolling, the start delay should equal the duration 10612 * of the scrolling animation.</p> 10613 * 10614 * <p>The animation starts only if at least one of the scrollbars is 10615 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 10616 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10617 * this method returns true, and false otherwise. If the animation is 10618 * started, this method calls {@link #invalidate()}; in that case the 10619 * caller should not call {@link #invalidate()}.</p> 10620 * 10621 * <p>This method should be invoked every time a subclass directly updates 10622 * the scroll parameters.</p> 10623 * 10624 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 10625 * and {@link #scrollTo(int, int)}.</p> 10626 * 10627 * @return true if the animation is played, false otherwise 10628 * 10629 * @see #awakenScrollBars(int) 10630 * @see #scrollBy(int, int) 10631 * @see #scrollTo(int, int) 10632 * @see #isHorizontalScrollBarEnabled() 10633 * @see #isVerticalScrollBarEnabled() 10634 * @see #setHorizontalScrollBarEnabled(boolean) 10635 * @see #setVerticalScrollBarEnabled(boolean) 10636 */ 10637 protected boolean awakenScrollBars() { 10638 return mScrollCache != null && 10639 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 10640 } 10641 10642 /** 10643 * Trigger the scrollbars to draw. 10644 * This method differs from awakenScrollBars() only in its default duration. 10645 * initialAwakenScrollBars() will show the scroll bars for longer than 10646 * usual to give the user more of a chance to notice them. 10647 * 10648 * @return true if the animation is played, false otherwise. 10649 */ 10650 private boolean initialAwakenScrollBars() { 10651 return mScrollCache != null && 10652 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 10653 } 10654 10655 /** 10656 * <p> 10657 * Trigger the scrollbars to draw. When invoked this method starts an 10658 * animation to fade the scrollbars out after a fixed delay. If a subclass 10659 * provides animated scrolling, the start delay should equal the duration of 10660 * the scrolling animation. 10661 * </p> 10662 * 10663 * <p> 10664 * The animation starts only if at least one of the scrollbars is enabled, 10665 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10666 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10667 * this method returns true, and false otherwise. If the animation is 10668 * started, this method calls {@link #invalidate()}; in that case the caller 10669 * should not call {@link #invalidate()}. 10670 * </p> 10671 * 10672 * <p> 10673 * This method should be invoked everytime a subclass directly updates the 10674 * scroll parameters. 10675 * </p> 10676 * 10677 * @param startDelay the delay, in milliseconds, after which the animation 10678 * should start; when the delay is 0, the animation starts 10679 * immediately 10680 * @return true if the animation is played, false otherwise 10681 * 10682 * @see #scrollBy(int, int) 10683 * @see #scrollTo(int, int) 10684 * @see #isHorizontalScrollBarEnabled() 10685 * @see #isVerticalScrollBarEnabled() 10686 * @see #setHorizontalScrollBarEnabled(boolean) 10687 * @see #setVerticalScrollBarEnabled(boolean) 10688 */ 10689 protected boolean awakenScrollBars(int startDelay) { 10690 return awakenScrollBars(startDelay, true); 10691 } 10692 10693 /** 10694 * <p> 10695 * Trigger the scrollbars to draw. When invoked this method starts an 10696 * animation to fade the scrollbars out after a fixed delay. If a subclass 10697 * provides animated scrolling, the start delay should equal the duration of 10698 * the scrolling animation. 10699 * </p> 10700 * 10701 * <p> 10702 * The animation starts only if at least one of the scrollbars is enabled, 10703 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10704 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10705 * this method returns true, and false otherwise. If the animation is 10706 * started, this method calls {@link #invalidate()} if the invalidate parameter 10707 * is set to true; in that case the caller 10708 * should not call {@link #invalidate()}. 10709 * </p> 10710 * 10711 * <p> 10712 * This method should be invoked everytime a subclass directly updates the 10713 * scroll parameters. 10714 * </p> 10715 * 10716 * @param startDelay the delay, in milliseconds, after which the animation 10717 * should start; when the delay is 0, the animation starts 10718 * immediately 10719 * 10720 * @param invalidate Wheter this method should call invalidate 10721 * 10722 * @return true if the animation is played, false otherwise 10723 * 10724 * @see #scrollBy(int, int) 10725 * @see #scrollTo(int, int) 10726 * @see #isHorizontalScrollBarEnabled() 10727 * @see #isVerticalScrollBarEnabled() 10728 * @see #setHorizontalScrollBarEnabled(boolean) 10729 * @see #setVerticalScrollBarEnabled(boolean) 10730 */ 10731 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 10732 final ScrollabilityCache scrollCache = mScrollCache; 10733 10734 if (scrollCache == null || !scrollCache.fadeScrollBars) { 10735 return false; 10736 } 10737 10738 if (scrollCache.scrollBar == null) { 10739 scrollCache.scrollBar = new ScrollBarDrawable(); 10740 } 10741 10742 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 10743 10744 if (invalidate) { 10745 // Invalidate to show the scrollbars 10746 postInvalidateOnAnimation(); 10747 } 10748 10749 if (scrollCache.state == ScrollabilityCache.OFF) { 10750 // FIXME: this is copied from WindowManagerService. 10751 // We should get this value from the system when it 10752 // is possible to do so. 10753 final int KEY_REPEAT_FIRST_DELAY = 750; 10754 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 10755 } 10756 10757 // Tell mScrollCache when we should start fading. This may 10758 // extend the fade start time if one was already scheduled 10759 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 10760 scrollCache.fadeStartTime = fadeStartTime; 10761 scrollCache.state = ScrollabilityCache.ON; 10762 10763 // Schedule our fader to run, unscheduling any old ones first 10764 if (mAttachInfo != null) { 10765 mAttachInfo.mHandler.removeCallbacks(scrollCache); 10766 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 10767 } 10768 10769 return true; 10770 } 10771 10772 return false; 10773 } 10774 10775 /** 10776 * Do not invalidate views which are not visible and which are not running an animation. They 10777 * will not get drawn and they should not set dirty flags as if they will be drawn 10778 */ 10779 private boolean skipInvalidate() { 10780 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 10781 (!(mParent instanceof ViewGroup) || 10782 !((ViewGroup) mParent).isViewTransitioning(this)); 10783 } 10784 /** 10785 * Mark the area defined by dirty as needing to be drawn. If the view is 10786 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 10787 * in the future. This must be called from a UI thread. To call from a non-UI 10788 * thread, call {@link #postInvalidate()}. 10789 * 10790 * WARNING: This method is destructive to dirty. 10791 * @param dirty the rectangle representing the bounds of the dirty region 10792 */ 10793 public void invalidate(Rect dirty) { 10794 if (skipInvalidate()) { 10795 return; 10796 } 10797 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10798 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10799 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10800 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10801 mPrivateFlags |= PFLAG_INVALIDATED; 10802 mPrivateFlags |= PFLAG_DIRTY; 10803 final ViewParent p = mParent; 10804 final AttachInfo ai = mAttachInfo; 10805 //noinspection PointlessBooleanExpression,ConstantConditions 10806 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10807 if (p != null && ai != null && ai.mHardwareAccelerated) { 10808 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10809 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10810 p.invalidateChild(this, null); 10811 return; 10812 } 10813 } 10814 if (p != null && ai != null) { 10815 final int scrollX = mScrollX; 10816 final int scrollY = mScrollY; 10817 final Rect r = ai.mTmpInvalRect; 10818 r.set(dirty.left - scrollX, dirty.top - scrollY, 10819 dirty.right - scrollX, dirty.bottom - scrollY); 10820 mParent.invalidateChild(this, r); 10821 } 10822 } 10823 } 10824 10825 /** 10826 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 10827 * The coordinates of the dirty rect are relative to the view. 10828 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 10829 * will be called at some point in the future. This must be called from 10830 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 10831 * @param l the left position of the dirty region 10832 * @param t the top position of the dirty region 10833 * @param r the right position of the dirty region 10834 * @param b the bottom position of the dirty region 10835 */ 10836 public void invalidate(int l, int t, int r, int b) { 10837 if (skipInvalidate()) { 10838 return; 10839 } 10840 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10841 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10842 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10843 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10844 mPrivateFlags |= PFLAG_INVALIDATED; 10845 mPrivateFlags |= PFLAG_DIRTY; 10846 final ViewParent p = mParent; 10847 final AttachInfo ai = mAttachInfo; 10848 //noinspection PointlessBooleanExpression,ConstantConditions 10849 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10850 if (p != null && ai != null && ai.mHardwareAccelerated) { 10851 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10852 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10853 p.invalidateChild(this, null); 10854 return; 10855 } 10856 } 10857 if (p != null && ai != null && l < r && t < b) { 10858 final int scrollX = mScrollX; 10859 final int scrollY = mScrollY; 10860 final Rect tmpr = ai.mTmpInvalRect; 10861 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 10862 p.invalidateChild(this, tmpr); 10863 } 10864 } 10865 } 10866 10867 /** 10868 * Invalidate the whole view. If the view is visible, 10869 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 10870 * the future. This must be called from a UI thread. To call from a non-UI thread, 10871 * call {@link #postInvalidate()}. 10872 */ 10873 public void invalidate() { 10874 invalidate(true); 10875 } 10876 10877 /** 10878 * This is where the invalidate() work actually happens. A full invalidate() 10879 * causes the drawing cache to be invalidated, but this function can be called with 10880 * invalidateCache set to false to skip that invalidation step for cases that do not 10881 * need it (for example, a component that remains at the same dimensions with the same 10882 * content). 10883 * 10884 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 10885 * well. This is usually true for a full invalidate, but may be set to false if the 10886 * View's contents or dimensions have not changed. 10887 */ 10888 void invalidate(boolean invalidateCache) { 10889 if (skipInvalidate()) { 10890 return; 10891 } 10892 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10893 (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) || 10894 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) { 10895 mLastIsOpaque = isOpaque(); 10896 mPrivateFlags &= ~PFLAG_DRAWN; 10897 mPrivateFlags |= PFLAG_DIRTY; 10898 if (invalidateCache) { 10899 mPrivateFlags |= PFLAG_INVALIDATED; 10900 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10901 } 10902 final AttachInfo ai = mAttachInfo; 10903 final ViewParent p = mParent; 10904 //noinspection PointlessBooleanExpression,ConstantConditions 10905 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10906 if (p != null && ai != null && ai.mHardwareAccelerated) { 10907 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10908 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10909 p.invalidateChild(this, null); 10910 return; 10911 } 10912 } 10913 10914 if (p != null && ai != null) { 10915 final Rect r = ai.mTmpInvalRect; 10916 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10917 // Don't call invalidate -- we don't want to internally scroll 10918 // our own bounds 10919 p.invalidateChild(this, r); 10920 } 10921 } 10922 } 10923 10924 /** 10925 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 10926 * set any flags or handle all of the cases handled by the default invalidation methods. 10927 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 10928 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 10929 * walk up the hierarchy, transforming the dirty rect as necessary. 10930 * 10931 * The method also handles normal invalidation logic if display list properties are not 10932 * being used in this view. The invalidateParent and forceRedraw flags are used by that 10933 * backup approach, to handle these cases used in the various property-setting methods. 10934 * 10935 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 10936 * are not being used in this view 10937 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 10938 * list properties are not being used in this view 10939 */ 10940 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 10941 if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) { 10942 if (invalidateParent) { 10943 invalidateParentCaches(); 10944 } 10945 if (forceRedraw) { 10946 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10947 } 10948 invalidate(false); 10949 } else { 10950 final AttachInfo ai = mAttachInfo; 10951 final ViewParent p = mParent; 10952 if (p != null && ai != null) { 10953 final Rect r = ai.mTmpInvalRect; 10954 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10955 if (mParent instanceof ViewGroup) { 10956 ((ViewGroup) mParent).invalidateChildFast(this, r); 10957 } else { 10958 mParent.invalidateChild(this, r); 10959 } 10960 } 10961 } 10962 } 10963 10964 /** 10965 * Utility method to transform a given Rect by the current matrix of this view. 10966 */ 10967 void transformRect(final Rect rect) { 10968 if (!getMatrix().isIdentity()) { 10969 RectF boundingRect = mAttachInfo.mTmpTransformRect; 10970 boundingRect.set(rect); 10971 getMatrix().mapRect(boundingRect); 10972 rect.set((int) Math.floor(boundingRect.left), 10973 (int) Math.floor(boundingRect.top), 10974 (int) Math.ceil(boundingRect.right), 10975 (int) Math.ceil(boundingRect.bottom)); 10976 } 10977 } 10978 10979 /** 10980 * Used to indicate that the parent of this view should clear its caches. This functionality 10981 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10982 * which is necessary when various parent-managed properties of the view change, such as 10983 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 10984 * clears the parent caches and does not causes an invalidate event. 10985 * 10986 * @hide 10987 */ 10988 protected void invalidateParentCaches() { 10989 if (mParent instanceof View) { 10990 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 10991 } 10992 } 10993 10994 /** 10995 * Used to indicate that the parent of this view should be invalidated. This functionality 10996 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10997 * which is necessary when various parent-managed properties of the view change, such as 10998 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 10999 * an invalidation event to the parent. 11000 * 11001 * @hide 11002 */ 11003 protected void invalidateParentIfNeeded() { 11004 if (isHardwareAccelerated() && mParent instanceof View) { 11005 ((View) mParent).invalidate(true); 11006 } 11007 } 11008 11009 /** 11010 * Indicates whether this View is opaque. An opaque View guarantees that it will 11011 * draw all the pixels overlapping its bounds using a fully opaque color. 11012 * 11013 * Subclasses of View should override this method whenever possible to indicate 11014 * whether an instance is opaque. Opaque Views are treated in a special way by 11015 * the View hierarchy, possibly allowing it to perform optimizations during 11016 * invalidate/draw passes. 11017 * 11018 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11019 */ 11020 @ViewDebug.ExportedProperty(category = "drawing") 11021 public boolean isOpaque() { 11022 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11023 getFinalAlpha() >= 1.0f; 11024 } 11025 11026 /** 11027 * @hide 11028 */ 11029 protected void computeOpaqueFlags() { 11030 // Opaque if: 11031 // - Has a background 11032 // - Background is opaque 11033 // - Doesn't have scrollbars or scrollbars overlay 11034 11035 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11036 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11037 } else { 11038 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11039 } 11040 11041 final int flags = mViewFlags; 11042 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11043 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11044 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11045 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11046 } else { 11047 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11048 } 11049 } 11050 11051 /** 11052 * @hide 11053 */ 11054 protected boolean hasOpaqueScrollbars() { 11055 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11056 } 11057 11058 /** 11059 * @return A handler associated with the thread running the View. This 11060 * handler can be used to pump events in the UI events queue. 11061 */ 11062 public Handler getHandler() { 11063 final AttachInfo attachInfo = mAttachInfo; 11064 if (attachInfo != null) { 11065 return attachInfo.mHandler; 11066 } 11067 return null; 11068 } 11069 11070 /** 11071 * Gets the view root associated with the View. 11072 * @return The view root, or null if none. 11073 * @hide 11074 */ 11075 public ViewRootImpl getViewRootImpl() { 11076 if (mAttachInfo != null) { 11077 return mAttachInfo.mViewRootImpl; 11078 } 11079 return null; 11080 } 11081 11082 /** 11083 * <p>Causes the Runnable to be added to the message queue. 11084 * The runnable will be run on the user interface thread.</p> 11085 * 11086 * @param action The Runnable that will be executed. 11087 * 11088 * @return Returns true if the Runnable was successfully placed in to the 11089 * message queue. Returns false on failure, usually because the 11090 * looper processing the message queue is exiting. 11091 * 11092 * @see #postDelayed 11093 * @see #removeCallbacks 11094 */ 11095 public boolean post(Runnable action) { 11096 final AttachInfo attachInfo = mAttachInfo; 11097 if (attachInfo != null) { 11098 return attachInfo.mHandler.post(action); 11099 } 11100 // Assume that post will succeed later 11101 ViewRootImpl.getRunQueue().post(action); 11102 return true; 11103 } 11104 11105 /** 11106 * <p>Causes the Runnable to be added to the message queue, to be run 11107 * after the specified amount of time elapses. 11108 * The runnable will be run on the user interface thread.</p> 11109 * 11110 * @param action The Runnable that will be executed. 11111 * @param delayMillis The delay (in milliseconds) until the Runnable 11112 * will be executed. 11113 * 11114 * @return true if the Runnable was successfully placed in to the 11115 * message queue. Returns false on failure, usually because the 11116 * looper processing the message queue is exiting. Note that a 11117 * result of true does not mean the Runnable will be processed -- 11118 * if the looper is quit before the delivery time of the message 11119 * occurs then the message will be dropped. 11120 * 11121 * @see #post 11122 * @see #removeCallbacks 11123 */ 11124 public boolean postDelayed(Runnable action, long delayMillis) { 11125 final AttachInfo attachInfo = mAttachInfo; 11126 if (attachInfo != null) { 11127 return attachInfo.mHandler.postDelayed(action, delayMillis); 11128 } 11129 // Assume that post will succeed later 11130 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11131 return true; 11132 } 11133 11134 /** 11135 * <p>Causes the Runnable to execute on the next animation time step. 11136 * The runnable will be run on the user interface thread.</p> 11137 * 11138 * @param action The Runnable that will be executed. 11139 * 11140 * @see #postOnAnimationDelayed 11141 * @see #removeCallbacks 11142 */ 11143 public void postOnAnimation(Runnable action) { 11144 final AttachInfo attachInfo = mAttachInfo; 11145 if (attachInfo != null) { 11146 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11147 Choreographer.CALLBACK_ANIMATION, action, null); 11148 } else { 11149 // Assume that post will succeed later 11150 ViewRootImpl.getRunQueue().post(action); 11151 } 11152 } 11153 11154 /** 11155 * <p>Causes the Runnable to execute on the next animation time step, 11156 * after the specified amount of time elapses. 11157 * The runnable will be run on the user interface thread.</p> 11158 * 11159 * @param action The Runnable that will be executed. 11160 * @param delayMillis The delay (in milliseconds) until the Runnable 11161 * will be executed. 11162 * 11163 * @see #postOnAnimation 11164 * @see #removeCallbacks 11165 */ 11166 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11167 final AttachInfo attachInfo = mAttachInfo; 11168 if (attachInfo != null) { 11169 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11170 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11171 } else { 11172 // Assume that post will succeed later 11173 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11174 } 11175 } 11176 11177 /** 11178 * <p>Removes the specified Runnable from the message queue.</p> 11179 * 11180 * @param action The Runnable to remove from the message handling queue 11181 * 11182 * @return true if this view could ask the Handler to remove the Runnable, 11183 * false otherwise. When the returned value is true, the Runnable 11184 * may or may not have been actually removed from the message queue 11185 * (for instance, if the Runnable was not in the queue already.) 11186 * 11187 * @see #post 11188 * @see #postDelayed 11189 * @see #postOnAnimation 11190 * @see #postOnAnimationDelayed 11191 */ 11192 public boolean removeCallbacks(Runnable action) { 11193 if (action != null) { 11194 final AttachInfo attachInfo = mAttachInfo; 11195 if (attachInfo != null) { 11196 attachInfo.mHandler.removeCallbacks(action); 11197 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11198 Choreographer.CALLBACK_ANIMATION, action, null); 11199 } else { 11200 // Assume that post will succeed later 11201 ViewRootImpl.getRunQueue().removeCallbacks(action); 11202 } 11203 } 11204 return true; 11205 } 11206 11207 /** 11208 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11209 * Use this to invalidate the View from a non-UI thread.</p> 11210 * 11211 * <p>This method can be invoked from outside of the UI thread 11212 * only when this View is attached to a window.</p> 11213 * 11214 * @see #invalidate() 11215 * @see #postInvalidateDelayed(long) 11216 */ 11217 public void postInvalidate() { 11218 postInvalidateDelayed(0); 11219 } 11220 11221 /** 11222 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11223 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11224 * 11225 * <p>This method can be invoked from outside of the UI thread 11226 * only when this View is attached to a window.</p> 11227 * 11228 * @param left The left coordinate of the rectangle to invalidate. 11229 * @param top The top coordinate of the rectangle to invalidate. 11230 * @param right The right coordinate of the rectangle to invalidate. 11231 * @param bottom The bottom coordinate of the rectangle to invalidate. 11232 * 11233 * @see #invalidate(int, int, int, int) 11234 * @see #invalidate(Rect) 11235 * @see #postInvalidateDelayed(long, int, int, int, int) 11236 */ 11237 public void postInvalidate(int left, int top, int right, int bottom) { 11238 postInvalidateDelayed(0, left, top, right, bottom); 11239 } 11240 11241 /** 11242 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11243 * loop. Waits for the specified amount of time.</p> 11244 * 11245 * <p>This method can be invoked from outside of the UI thread 11246 * only when this View is attached to a window.</p> 11247 * 11248 * @param delayMilliseconds the duration in milliseconds to delay the 11249 * invalidation by 11250 * 11251 * @see #invalidate() 11252 * @see #postInvalidate() 11253 */ 11254 public void postInvalidateDelayed(long delayMilliseconds) { 11255 // We try only with the AttachInfo because there's no point in invalidating 11256 // if we are not attached to our window 11257 final AttachInfo attachInfo = mAttachInfo; 11258 if (attachInfo != null) { 11259 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11260 } 11261 } 11262 11263 /** 11264 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11265 * through the event loop. Waits for the specified amount of time.</p> 11266 * 11267 * <p>This method can be invoked from outside of the UI thread 11268 * only when this View is attached to a window.</p> 11269 * 11270 * @param delayMilliseconds the duration in milliseconds to delay the 11271 * invalidation by 11272 * @param left The left coordinate of the rectangle to invalidate. 11273 * @param top The top coordinate of the rectangle to invalidate. 11274 * @param right The right coordinate of the rectangle to invalidate. 11275 * @param bottom The bottom coordinate of the rectangle to invalidate. 11276 * 11277 * @see #invalidate(int, int, int, int) 11278 * @see #invalidate(Rect) 11279 * @see #postInvalidate(int, int, int, int) 11280 */ 11281 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11282 int right, int bottom) { 11283 11284 // We try only with the AttachInfo because there's no point in invalidating 11285 // if we are not attached to our window 11286 final AttachInfo attachInfo = mAttachInfo; 11287 if (attachInfo != null) { 11288 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11289 info.target = this; 11290 info.left = left; 11291 info.top = top; 11292 info.right = right; 11293 info.bottom = bottom; 11294 11295 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11296 } 11297 } 11298 11299 /** 11300 * <p>Cause an invalidate to happen on the next animation time step, typically the 11301 * next display frame.</p> 11302 * 11303 * <p>This method can be invoked from outside of the UI thread 11304 * only when this View is attached to a window.</p> 11305 * 11306 * @see #invalidate() 11307 */ 11308 public void postInvalidateOnAnimation() { 11309 // We try only with the AttachInfo because there's no point in invalidating 11310 // if we are not attached to our window 11311 final AttachInfo attachInfo = mAttachInfo; 11312 if (attachInfo != null) { 11313 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11314 } 11315 } 11316 11317 /** 11318 * <p>Cause an invalidate of the specified area to happen on the next animation 11319 * time step, typically the next display frame.</p> 11320 * 11321 * <p>This method can be invoked from outside of the UI thread 11322 * only when this View is attached to a window.</p> 11323 * 11324 * @param left The left coordinate of the rectangle to invalidate. 11325 * @param top The top coordinate of the rectangle to invalidate. 11326 * @param right The right coordinate of the rectangle to invalidate. 11327 * @param bottom The bottom coordinate of the rectangle to invalidate. 11328 * 11329 * @see #invalidate(int, int, int, int) 11330 * @see #invalidate(Rect) 11331 */ 11332 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11333 // We try only with the AttachInfo because there's no point in invalidating 11334 // if we are not attached to our window 11335 final AttachInfo attachInfo = mAttachInfo; 11336 if (attachInfo != null) { 11337 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11338 info.target = this; 11339 info.left = left; 11340 info.top = top; 11341 info.right = right; 11342 info.bottom = bottom; 11343 11344 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11345 } 11346 } 11347 11348 /** 11349 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11350 * This event is sent at most once every 11351 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11352 */ 11353 private void postSendViewScrolledAccessibilityEventCallback() { 11354 if (mSendViewScrolledAccessibilityEvent == null) { 11355 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11356 } 11357 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11358 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11359 postDelayed(mSendViewScrolledAccessibilityEvent, 11360 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11361 } 11362 } 11363 11364 /** 11365 * Called by a parent to request that a child update its values for mScrollX 11366 * and mScrollY if necessary. This will typically be done if the child is 11367 * animating a scroll using a {@link android.widget.Scroller Scroller} 11368 * object. 11369 */ 11370 public void computeScroll() { 11371 } 11372 11373 /** 11374 * <p>Indicate whether the horizontal edges are faded when the view is 11375 * scrolled horizontally.</p> 11376 * 11377 * @return true if the horizontal edges should are faded on scroll, false 11378 * otherwise 11379 * 11380 * @see #setHorizontalFadingEdgeEnabled(boolean) 11381 * 11382 * @attr ref android.R.styleable#View_requiresFadingEdge 11383 */ 11384 public boolean isHorizontalFadingEdgeEnabled() { 11385 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11386 } 11387 11388 /** 11389 * <p>Define whether the horizontal edges should be faded when this view 11390 * is scrolled horizontally.</p> 11391 * 11392 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11393 * be faded when the view is scrolled 11394 * horizontally 11395 * 11396 * @see #isHorizontalFadingEdgeEnabled() 11397 * 11398 * @attr ref android.R.styleable#View_requiresFadingEdge 11399 */ 11400 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11401 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11402 if (horizontalFadingEdgeEnabled) { 11403 initScrollCache(); 11404 } 11405 11406 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11407 } 11408 } 11409 11410 /** 11411 * <p>Indicate whether the vertical edges are faded when the view is 11412 * scrolled horizontally.</p> 11413 * 11414 * @return true if the vertical edges should are faded on scroll, false 11415 * otherwise 11416 * 11417 * @see #setVerticalFadingEdgeEnabled(boolean) 11418 * 11419 * @attr ref android.R.styleable#View_requiresFadingEdge 11420 */ 11421 public boolean isVerticalFadingEdgeEnabled() { 11422 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 11423 } 11424 11425 /** 11426 * <p>Define whether the vertical edges should be faded when this view 11427 * is scrolled vertically.</p> 11428 * 11429 * @param verticalFadingEdgeEnabled true if the vertical edges should 11430 * be faded when the view is scrolled 11431 * vertically 11432 * 11433 * @see #isVerticalFadingEdgeEnabled() 11434 * 11435 * @attr ref android.R.styleable#View_requiresFadingEdge 11436 */ 11437 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 11438 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 11439 if (verticalFadingEdgeEnabled) { 11440 initScrollCache(); 11441 } 11442 11443 mViewFlags ^= FADING_EDGE_VERTICAL; 11444 } 11445 } 11446 11447 /** 11448 * Returns the strength, or intensity, of the top faded edge. The strength is 11449 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11450 * returns 0.0 or 1.0 but no value in between. 11451 * 11452 * Subclasses should override this method to provide a smoother fade transition 11453 * when scrolling occurs. 11454 * 11455 * @return the intensity of the top fade as a float between 0.0f and 1.0f 11456 */ 11457 protected float getTopFadingEdgeStrength() { 11458 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 11459 } 11460 11461 /** 11462 * Returns the strength, or intensity, of the bottom faded edge. The strength is 11463 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11464 * returns 0.0 or 1.0 but no value in between. 11465 * 11466 * Subclasses should override this method to provide a smoother fade transition 11467 * when scrolling occurs. 11468 * 11469 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 11470 */ 11471 protected float getBottomFadingEdgeStrength() { 11472 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 11473 computeVerticalScrollRange() ? 1.0f : 0.0f; 11474 } 11475 11476 /** 11477 * Returns the strength, or intensity, of the left faded edge. The strength is 11478 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11479 * returns 0.0 or 1.0 but no value in between. 11480 * 11481 * Subclasses should override this method to provide a smoother fade transition 11482 * when scrolling occurs. 11483 * 11484 * @return the intensity of the left fade as a float between 0.0f and 1.0f 11485 */ 11486 protected float getLeftFadingEdgeStrength() { 11487 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 11488 } 11489 11490 /** 11491 * Returns the strength, or intensity, of the right faded edge. The strength is 11492 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11493 * returns 0.0 or 1.0 but no value in between. 11494 * 11495 * Subclasses should override this method to provide a smoother fade transition 11496 * when scrolling occurs. 11497 * 11498 * @return the intensity of the right fade as a float between 0.0f and 1.0f 11499 */ 11500 protected float getRightFadingEdgeStrength() { 11501 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 11502 computeHorizontalScrollRange() ? 1.0f : 0.0f; 11503 } 11504 11505 /** 11506 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 11507 * scrollbar is not drawn by default.</p> 11508 * 11509 * @return true if the horizontal scrollbar should be painted, false 11510 * otherwise 11511 * 11512 * @see #setHorizontalScrollBarEnabled(boolean) 11513 */ 11514 public boolean isHorizontalScrollBarEnabled() { 11515 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11516 } 11517 11518 /** 11519 * <p>Define whether the horizontal scrollbar should be drawn or not. The 11520 * scrollbar is not drawn by default.</p> 11521 * 11522 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 11523 * be painted 11524 * 11525 * @see #isHorizontalScrollBarEnabled() 11526 */ 11527 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 11528 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 11529 mViewFlags ^= SCROLLBARS_HORIZONTAL; 11530 computeOpaqueFlags(); 11531 resolvePadding(); 11532 } 11533 } 11534 11535 /** 11536 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 11537 * scrollbar is not drawn by default.</p> 11538 * 11539 * @return true if the vertical scrollbar should be painted, false 11540 * otherwise 11541 * 11542 * @see #setVerticalScrollBarEnabled(boolean) 11543 */ 11544 public boolean isVerticalScrollBarEnabled() { 11545 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 11546 } 11547 11548 /** 11549 * <p>Define whether the vertical scrollbar should be drawn or not. The 11550 * scrollbar is not drawn by default.</p> 11551 * 11552 * @param verticalScrollBarEnabled true if the vertical scrollbar should 11553 * be painted 11554 * 11555 * @see #isVerticalScrollBarEnabled() 11556 */ 11557 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 11558 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 11559 mViewFlags ^= SCROLLBARS_VERTICAL; 11560 computeOpaqueFlags(); 11561 resolvePadding(); 11562 } 11563 } 11564 11565 /** 11566 * @hide 11567 */ 11568 protected void recomputePadding() { 11569 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 11570 } 11571 11572 /** 11573 * Define whether scrollbars will fade when the view is not scrolling. 11574 * 11575 * @param fadeScrollbars wheter to enable fading 11576 * 11577 * @attr ref android.R.styleable#View_fadeScrollbars 11578 */ 11579 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 11580 initScrollCache(); 11581 final ScrollabilityCache scrollabilityCache = mScrollCache; 11582 scrollabilityCache.fadeScrollBars = fadeScrollbars; 11583 if (fadeScrollbars) { 11584 scrollabilityCache.state = ScrollabilityCache.OFF; 11585 } else { 11586 scrollabilityCache.state = ScrollabilityCache.ON; 11587 } 11588 } 11589 11590 /** 11591 * 11592 * Returns true if scrollbars will fade when this view is not scrolling 11593 * 11594 * @return true if scrollbar fading is enabled 11595 * 11596 * @attr ref android.R.styleable#View_fadeScrollbars 11597 */ 11598 public boolean isScrollbarFadingEnabled() { 11599 return mScrollCache != null && mScrollCache.fadeScrollBars; 11600 } 11601 11602 /** 11603 * 11604 * Returns the delay before scrollbars fade. 11605 * 11606 * @return the delay before scrollbars fade 11607 * 11608 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11609 */ 11610 public int getScrollBarDefaultDelayBeforeFade() { 11611 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 11612 mScrollCache.scrollBarDefaultDelayBeforeFade; 11613 } 11614 11615 /** 11616 * Define the delay before scrollbars fade. 11617 * 11618 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 11619 * 11620 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11621 */ 11622 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 11623 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 11624 } 11625 11626 /** 11627 * 11628 * Returns the scrollbar fade duration. 11629 * 11630 * @return the scrollbar fade duration 11631 * 11632 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11633 */ 11634 public int getScrollBarFadeDuration() { 11635 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 11636 mScrollCache.scrollBarFadeDuration; 11637 } 11638 11639 /** 11640 * Define the scrollbar fade duration. 11641 * 11642 * @param scrollBarFadeDuration - the scrollbar fade duration 11643 * 11644 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11645 */ 11646 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 11647 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 11648 } 11649 11650 /** 11651 * 11652 * Returns the scrollbar size. 11653 * 11654 * @return the scrollbar size 11655 * 11656 * @attr ref android.R.styleable#View_scrollbarSize 11657 */ 11658 public int getScrollBarSize() { 11659 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 11660 mScrollCache.scrollBarSize; 11661 } 11662 11663 /** 11664 * Define the scrollbar size. 11665 * 11666 * @param scrollBarSize - the scrollbar size 11667 * 11668 * @attr ref android.R.styleable#View_scrollbarSize 11669 */ 11670 public void setScrollBarSize(int scrollBarSize) { 11671 getScrollCache().scrollBarSize = scrollBarSize; 11672 } 11673 11674 /** 11675 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 11676 * inset. When inset, they add to the padding of the view. And the scrollbars 11677 * can be drawn inside the padding area or on the edge of the view. For example, 11678 * if a view has a background drawable and you want to draw the scrollbars 11679 * inside the padding specified by the drawable, you can use 11680 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 11681 * appear at the edge of the view, ignoring the padding, then you can use 11682 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 11683 * @param style the style of the scrollbars. Should be one of 11684 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 11685 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 11686 * @see #SCROLLBARS_INSIDE_OVERLAY 11687 * @see #SCROLLBARS_INSIDE_INSET 11688 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11689 * @see #SCROLLBARS_OUTSIDE_INSET 11690 * 11691 * @attr ref android.R.styleable#View_scrollbarStyle 11692 */ 11693 public void setScrollBarStyle(int style) { 11694 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 11695 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 11696 computeOpaqueFlags(); 11697 resolvePadding(); 11698 } 11699 } 11700 11701 /** 11702 * <p>Returns the current scrollbar style.</p> 11703 * @return the current scrollbar style 11704 * @see #SCROLLBARS_INSIDE_OVERLAY 11705 * @see #SCROLLBARS_INSIDE_INSET 11706 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11707 * @see #SCROLLBARS_OUTSIDE_INSET 11708 * 11709 * @attr ref android.R.styleable#View_scrollbarStyle 11710 */ 11711 @ViewDebug.ExportedProperty(mapping = { 11712 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 11713 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 11714 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 11715 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 11716 }) 11717 public int getScrollBarStyle() { 11718 return mViewFlags & SCROLLBARS_STYLE_MASK; 11719 } 11720 11721 /** 11722 * <p>Compute the horizontal range that the horizontal scrollbar 11723 * represents.</p> 11724 * 11725 * <p>The range is expressed in arbitrary units that must be the same as the 11726 * units used by {@link #computeHorizontalScrollExtent()} and 11727 * {@link #computeHorizontalScrollOffset()}.</p> 11728 * 11729 * <p>The default range is the drawing width of this view.</p> 11730 * 11731 * @return the total horizontal range represented by the horizontal 11732 * scrollbar 11733 * 11734 * @see #computeHorizontalScrollExtent() 11735 * @see #computeHorizontalScrollOffset() 11736 * @see android.widget.ScrollBarDrawable 11737 */ 11738 protected int computeHorizontalScrollRange() { 11739 return getWidth(); 11740 } 11741 11742 /** 11743 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 11744 * within the horizontal range. This value is used to compute the position 11745 * of the thumb within the scrollbar's track.</p> 11746 * 11747 * <p>The range is expressed in arbitrary units that must be the same as the 11748 * units used by {@link #computeHorizontalScrollRange()} and 11749 * {@link #computeHorizontalScrollExtent()}.</p> 11750 * 11751 * <p>The default offset is the scroll offset of this view.</p> 11752 * 11753 * @return the horizontal offset of the scrollbar's thumb 11754 * 11755 * @see #computeHorizontalScrollRange() 11756 * @see #computeHorizontalScrollExtent() 11757 * @see android.widget.ScrollBarDrawable 11758 */ 11759 protected int computeHorizontalScrollOffset() { 11760 return mScrollX; 11761 } 11762 11763 /** 11764 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 11765 * within the horizontal range. This value is used to compute the length 11766 * of the thumb within the scrollbar's track.</p> 11767 * 11768 * <p>The range is expressed in arbitrary units that must be the same as the 11769 * units used by {@link #computeHorizontalScrollRange()} and 11770 * {@link #computeHorizontalScrollOffset()}.</p> 11771 * 11772 * <p>The default extent is the drawing width of this view.</p> 11773 * 11774 * @return the horizontal extent of the scrollbar's thumb 11775 * 11776 * @see #computeHorizontalScrollRange() 11777 * @see #computeHorizontalScrollOffset() 11778 * @see android.widget.ScrollBarDrawable 11779 */ 11780 protected int computeHorizontalScrollExtent() { 11781 return getWidth(); 11782 } 11783 11784 /** 11785 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 11786 * 11787 * <p>The range is expressed in arbitrary units that must be the same as the 11788 * units used by {@link #computeVerticalScrollExtent()} and 11789 * {@link #computeVerticalScrollOffset()}.</p> 11790 * 11791 * @return the total vertical range represented by the vertical scrollbar 11792 * 11793 * <p>The default range is the drawing height of this view.</p> 11794 * 11795 * @see #computeVerticalScrollExtent() 11796 * @see #computeVerticalScrollOffset() 11797 * @see android.widget.ScrollBarDrawable 11798 */ 11799 protected int computeVerticalScrollRange() { 11800 return getHeight(); 11801 } 11802 11803 /** 11804 * <p>Compute the vertical offset of the vertical scrollbar's thumb 11805 * within the horizontal range. This value is used to compute the position 11806 * of the thumb within the scrollbar's track.</p> 11807 * 11808 * <p>The range is expressed in arbitrary units that must be the same as the 11809 * units used by {@link #computeVerticalScrollRange()} and 11810 * {@link #computeVerticalScrollExtent()}.</p> 11811 * 11812 * <p>The default offset is the scroll offset of this view.</p> 11813 * 11814 * @return the vertical offset of the scrollbar's thumb 11815 * 11816 * @see #computeVerticalScrollRange() 11817 * @see #computeVerticalScrollExtent() 11818 * @see android.widget.ScrollBarDrawable 11819 */ 11820 protected int computeVerticalScrollOffset() { 11821 return mScrollY; 11822 } 11823 11824 /** 11825 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 11826 * within the vertical range. This value is used to compute the length 11827 * of the thumb within the scrollbar's track.</p> 11828 * 11829 * <p>The range is expressed in arbitrary units that must be the same as the 11830 * units used by {@link #computeVerticalScrollRange()} and 11831 * {@link #computeVerticalScrollOffset()}.</p> 11832 * 11833 * <p>The default extent is the drawing height of this view.</p> 11834 * 11835 * @return the vertical extent of the scrollbar's thumb 11836 * 11837 * @see #computeVerticalScrollRange() 11838 * @see #computeVerticalScrollOffset() 11839 * @see android.widget.ScrollBarDrawable 11840 */ 11841 protected int computeVerticalScrollExtent() { 11842 return getHeight(); 11843 } 11844 11845 /** 11846 * Check if this view can be scrolled horizontally in a certain direction. 11847 * 11848 * @param direction Negative to check scrolling left, positive to check scrolling right. 11849 * @return true if this view can be scrolled in the specified direction, false otherwise. 11850 */ 11851 public boolean canScrollHorizontally(int direction) { 11852 final int offset = computeHorizontalScrollOffset(); 11853 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 11854 if (range == 0) return false; 11855 if (direction < 0) { 11856 return offset > 0; 11857 } else { 11858 return offset < range - 1; 11859 } 11860 } 11861 11862 /** 11863 * Check if this view can be scrolled vertically in a certain direction. 11864 * 11865 * @param direction Negative to check scrolling up, positive to check scrolling down. 11866 * @return true if this view can be scrolled in the specified direction, false otherwise. 11867 */ 11868 public boolean canScrollVertically(int direction) { 11869 final int offset = computeVerticalScrollOffset(); 11870 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 11871 if (range == 0) return false; 11872 if (direction < 0) { 11873 return offset > 0; 11874 } else { 11875 return offset < range - 1; 11876 } 11877 } 11878 11879 /** 11880 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 11881 * scrollbars are painted only if they have been awakened first.</p> 11882 * 11883 * @param canvas the canvas on which to draw the scrollbars 11884 * 11885 * @see #awakenScrollBars(int) 11886 */ 11887 protected final void onDrawScrollBars(Canvas canvas) { 11888 // scrollbars are drawn only when the animation is running 11889 final ScrollabilityCache cache = mScrollCache; 11890 if (cache != null) { 11891 11892 int state = cache.state; 11893 11894 if (state == ScrollabilityCache.OFF) { 11895 return; 11896 } 11897 11898 boolean invalidate = false; 11899 11900 if (state == ScrollabilityCache.FADING) { 11901 // We're fading -- get our fade interpolation 11902 if (cache.interpolatorValues == null) { 11903 cache.interpolatorValues = new float[1]; 11904 } 11905 11906 float[] values = cache.interpolatorValues; 11907 11908 // Stops the animation if we're done 11909 if (cache.scrollBarInterpolator.timeToValues(values) == 11910 Interpolator.Result.FREEZE_END) { 11911 cache.state = ScrollabilityCache.OFF; 11912 } else { 11913 cache.scrollBar.setAlpha(Math.round(values[0])); 11914 } 11915 11916 // This will make the scroll bars inval themselves after 11917 // drawing. We only want this when we're fading so that 11918 // we prevent excessive redraws 11919 invalidate = true; 11920 } else { 11921 // We're just on -- but we may have been fading before so 11922 // reset alpha 11923 cache.scrollBar.setAlpha(255); 11924 } 11925 11926 11927 final int viewFlags = mViewFlags; 11928 11929 final boolean drawHorizontalScrollBar = 11930 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11931 final boolean drawVerticalScrollBar = 11932 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 11933 && !isVerticalScrollBarHidden(); 11934 11935 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 11936 final int width = mRight - mLeft; 11937 final int height = mBottom - mTop; 11938 11939 final ScrollBarDrawable scrollBar = cache.scrollBar; 11940 11941 final int scrollX = mScrollX; 11942 final int scrollY = mScrollY; 11943 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 11944 11945 int left; 11946 int top; 11947 int right; 11948 int bottom; 11949 11950 if (drawHorizontalScrollBar) { 11951 int size = scrollBar.getSize(false); 11952 if (size <= 0) { 11953 size = cache.scrollBarSize; 11954 } 11955 11956 scrollBar.setParameters(computeHorizontalScrollRange(), 11957 computeHorizontalScrollOffset(), 11958 computeHorizontalScrollExtent(), false); 11959 final int verticalScrollBarGap = drawVerticalScrollBar ? 11960 getVerticalScrollbarWidth() : 0; 11961 top = scrollY + height - size - (mUserPaddingBottom & inside); 11962 left = scrollX + (mPaddingLeft & inside); 11963 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 11964 bottom = top + size; 11965 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 11966 if (invalidate) { 11967 invalidate(left, top, right, bottom); 11968 } 11969 } 11970 11971 if (drawVerticalScrollBar) { 11972 int size = scrollBar.getSize(true); 11973 if (size <= 0) { 11974 size = cache.scrollBarSize; 11975 } 11976 11977 scrollBar.setParameters(computeVerticalScrollRange(), 11978 computeVerticalScrollOffset(), 11979 computeVerticalScrollExtent(), true); 11980 int verticalScrollbarPosition = mVerticalScrollbarPosition; 11981 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 11982 verticalScrollbarPosition = isLayoutRtl() ? 11983 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 11984 } 11985 switch (verticalScrollbarPosition) { 11986 default: 11987 case SCROLLBAR_POSITION_RIGHT: 11988 left = scrollX + width - size - (mUserPaddingRight & inside); 11989 break; 11990 case SCROLLBAR_POSITION_LEFT: 11991 left = scrollX + (mUserPaddingLeft & inside); 11992 break; 11993 } 11994 top = scrollY + (mPaddingTop & inside); 11995 right = left + size; 11996 bottom = scrollY + height - (mUserPaddingBottom & inside); 11997 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 11998 if (invalidate) { 11999 invalidate(left, top, right, bottom); 12000 } 12001 } 12002 } 12003 } 12004 } 12005 12006 /** 12007 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12008 * FastScroller is visible. 12009 * @return whether to temporarily hide the vertical scrollbar 12010 * @hide 12011 */ 12012 protected boolean isVerticalScrollBarHidden() { 12013 return false; 12014 } 12015 12016 /** 12017 * <p>Draw the horizontal scrollbar if 12018 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12019 * 12020 * @param canvas the canvas on which to draw the scrollbar 12021 * @param scrollBar the scrollbar's drawable 12022 * 12023 * @see #isHorizontalScrollBarEnabled() 12024 * @see #computeHorizontalScrollRange() 12025 * @see #computeHorizontalScrollExtent() 12026 * @see #computeHorizontalScrollOffset() 12027 * @see android.widget.ScrollBarDrawable 12028 * @hide 12029 */ 12030 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12031 int l, int t, int r, int b) { 12032 scrollBar.setBounds(l, t, r, b); 12033 scrollBar.draw(canvas); 12034 } 12035 12036 /** 12037 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12038 * returns true.</p> 12039 * 12040 * @param canvas the canvas on which to draw the scrollbar 12041 * @param scrollBar the scrollbar's drawable 12042 * 12043 * @see #isVerticalScrollBarEnabled() 12044 * @see #computeVerticalScrollRange() 12045 * @see #computeVerticalScrollExtent() 12046 * @see #computeVerticalScrollOffset() 12047 * @see android.widget.ScrollBarDrawable 12048 * @hide 12049 */ 12050 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12051 int l, int t, int r, int b) { 12052 scrollBar.setBounds(l, t, r, b); 12053 scrollBar.draw(canvas); 12054 } 12055 12056 /** 12057 * Implement this to do your drawing. 12058 * 12059 * @param canvas the canvas on which the background will be drawn 12060 */ 12061 protected void onDraw(Canvas canvas) { 12062 } 12063 12064 /* 12065 * Caller is responsible for calling requestLayout if necessary. 12066 * (This allows addViewInLayout to not request a new layout.) 12067 */ 12068 void assignParent(ViewParent parent) { 12069 if (mParent == null) { 12070 mParent = parent; 12071 } else if (parent == null) { 12072 mParent = null; 12073 } else { 12074 throw new RuntimeException("view " + this + " being added, but" 12075 + " it already has a parent"); 12076 } 12077 } 12078 12079 /** 12080 * This is called when the view is attached to a window. At this point it 12081 * has a Surface and will start drawing. Note that this function is 12082 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12083 * however it may be called any time before the first onDraw -- including 12084 * before or after {@link #onMeasure(int, int)}. 12085 * 12086 * @see #onDetachedFromWindow() 12087 */ 12088 protected void onAttachedToWindow() { 12089 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12090 mParent.requestTransparentRegion(this); 12091 } 12092 12093 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12094 initialAwakenScrollBars(); 12095 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12096 } 12097 12098 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12099 12100 jumpDrawablesToCurrentState(); 12101 12102 resetSubtreeAccessibilityStateChanged(); 12103 12104 if (isFocused()) { 12105 InputMethodManager imm = InputMethodManager.peekInstance(); 12106 imm.focusIn(this); 12107 } 12108 12109 if (mDisplayList != null) { 12110 mDisplayList.clearDirty(); 12111 } 12112 } 12113 12114 /** 12115 * Resolve all RTL related properties. 12116 * 12117 * @return true if resolution of RTL properties has been done 12118 * 12119 * @hide 12120 */ 12121 public boolean resolveRtlPropertiesIfNeeded() { 12122 if (!needRtlPropertiesResolution()) return false; 12123 12124 // Order is important here: LayoutDirection MUST be resolved first 12125 if (!isLayoutDirectionResolved()) { 12126 resolveLayoutDirection(); 12127 resolveLayoutParams(); 12128 } 12129 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12130 if (!isTextDirectionResolved()) { 12131 resolveTextDirection(); 12132 } 12133 if (!isTextAlignmentResolved()) { 12134 resolveTextAlignment(); 12135 } 12136 if (!isPaddingResolved()) { 12137 resolvePadding(); 12138 } 12139 if (!isDrawablesResolved()) { 12140 resolveDrawables(); 12141 } 12142 onRtlPropertiesChanged(getLayoutDirection()); 12143 return true; 12144 } 12145 12146 /** 12147 * Reset resolution of all RTL related properties. 12148 * 12149 * @hide 12150 */ 12151 public void resetRtlProperties() { 12152 resetResolvedLayoutDirection(); 12153 resetResolvedTextDirection(); 12154 resetResolvedTextAlignment(); 12155 resetResolvedPadding(); 12156 resetResolvedDrawables(); 12157 } 12158 12159 /** 12160 * @see #onScreenStateChanged(int) 12161 */ 12162 void dispatchScreenStateChanged(int screenState) { 12163 onScreenStateChanged(screenState); 12164 } 12165 12166 /** 12167 * This method is called whenever the state of the screen this view is 12168 * attached to changes. A state change will usually occurs when the screen 12169 * turns on or off (whether it happens automatically or the user does it 12170 * manually.) 12171 * 12172 * @param screenState The new state of the screen. Can be either 12173 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12174 */ 12175 public void onScreenStateChanged(int screenState) { 12176 } 12177 12178 /** 12179 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12180 */ 12181 private boolean hasRtlSupport() { 12182 return mContext.getApplicationInfo().hasRtlSupport(); 12183 } 12184 12185 /** 12186 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12187 * RTL not supported) 12188 */ 12189 private boolean isRtlCompatibilityMode() { 12190 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12191 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12192 } 12193 12194 /** 12195 * @return true if RTL properties need resolution. 12196 * 12197 */ 12198 private boolean needRtlPropertiesResolution() { 12199 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12200 } 12201 12202 /** 12203 * Called when any RTL property (layout direction or text direction or text alignment) has 12204 * been changed. 12205 * 12206 * Subclasses need to override this method to take care of cached information that depends on the 12207 * resolved layout direction, or to inform child views that inherit their layout direction. 12208 * 12209 * The default implementation does nothing. 12210 * 12211 * @param layoutDirection the direction of the layout 12212 * 12213 * @see #LAYOUT_DIRECTION_LTR 12214 * @see #LAYOUT_DIRECTION_RTL 12215 */ 12216 public void onRtlPropertiesChanged(int layoutDirection) { 12217 } 12218 12219 /** 12220 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12221 * that the parent directionality can and will be resolved before its children. 12222 * 12223 * @return true if resolution has been done, false otherwise. 12224 * 12225 * @hide 12226 */ 12227 public boolean resolveLayoutDirection() { 12228 // Clear any previous layout direction resolution 12229 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12230 12231 if (hasRtlSupport()) { 12232 // Set resolved depending on layout direction 12233 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12234 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12235 case LAYOUT_DIRECTION_INHERIT: 12236 // We cannot resolve yet. LTR is by default and let the resolution happen again 12237 // later to get the correct resolved value 12238 if (!canResolveLayoutDirection()) return false; 12239 12240 // Parent has not yet resolved, LTR is still the default 12241 try { 12242 if (!mParent.isLayoutDirectionResolved()) return false; 12243 12244 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12245 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12246 } 12247 } catch (AbstractMethodError e) { 12248 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12249 " does not fully implement ViewParent", e); 12250 } 12251 break; 12252 case LAYOUT_DIRECTION_RTL: 12253 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12254 break; 12255 case LAYOUT_DIRECTION_LOCALE: 12256 if((LAYOUT_DIRECTION_RTL == 12257 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12258 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12259 } 12260 break; 12261 default: 12262 // Nothing to do, LTR by default 12263 } 12264 } 12265 12266 // Set to resolved 12267 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12268 return true; 12269 } 12270 12271 /** 12272 * Check if layout direction resolution can be done. 12273 * 12274 * @return true if layout direction resolution can be done otherwise return false. 12275 */ 12276 public boolean canResolveLayoutDirection() { 12277 switch (getRawLayoutDirection()) { 12278 case LAYOUT_DIRECTION_INHERIT: 12279 if (mParent != null) { 12280 try { 12281 return mParent.canResolveLayoutDirection(); 12282 } catch (AbstractMethodError e) { 12283 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12284 " does not fully implement ViewParent", e); 12285 } 12286 } 12287 return false; 12288 12289 default: 12290 return true; 12291 } 12292 } 12293 12294 /** 12295 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12296 * {@link #onMeasure(int, int)}. 12297 * 12298 * @hide 12299 */ 12300 public void resetResolvedLayoutDirection() { 12301 // Reset the current resolved bits 12302 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12303 } 12304 12305 /** 12306 * @return true if the layout direction is inherited. 12307 * 12308 * @hide 12309 */ 12310 public boolean isLayoutDirectionInherited() { 12311 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12312 } 12313 12314 /** 12315 * @return true if layout direction has been resolved. 12316 */ 12317 public boolean isLayoutDirectionResolved() { 12318 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12319 } 12320 12321 /** 12322 * Return if padding has been resolved 12323 * 12324 * @hide 12325 */ 12326 boolean isPaddingResolved() { 12327 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12328 } 12329 12330 /** 12331 * Resolves padding depending on layout direction, if applicable, and 12332 * recomputes internal padding values to adjust for scroll bars. 12333 * 12334 * @hide 12335 */ 12336 public void resolvePadding() { 12337 final int resolvedLayoutDirection = getLayoutDirection(); 12338 12339 if (!isRtlCompatibilityMode()) { 12340 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12341 // If start / end padding are defined, they will be resolved (hence overriding) to 12342 // left / right or right / left depending on the resolved layout direction. 12343 // If start / end padding are not defined, use the left / right ones. 12344 switch (resolvedLayoutDirection) { 12345 case LAYOUT_DIRECTION_RTL: 12346 if (mUserPaddingStart != UNDEFINED_PADDING) { 12347 mUserPaddingRight = mUserPaddingStart; 12348 } else { 12349 mUserPaddingRight = mUserPaddingRightInitial; 12350 } 12351 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12352 mUserPaddingLeft = mUserPaddingEnd; 12353 } else { 12354 mUserPaddingLeft = mUserPaddingLeftInitial; 12355 } 12356 break; 12357 case LAYOUT_DIRECTION_LTR: 12358 default: 12359 if (mUserPaddingStart != UNDEFINED_PADDING) { 12360 mUserPaddingLeft = mUserPaddingStart; 12361 } else { 12362 mUserPaddingLeft = mUserPaddingLeftInitial; 12363 } 12364 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12365 mUserPaddingRight = mUserPaddingEnd; 12366 } else { 12367 mUserPaddingRight = mUserPaddingRightInitial; 12368 } 12369 } 12370 12371 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12372 } 12373 12374 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12375 onRtlPropertiesChanged(resolvedLayoutDirection); 12376 12377 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12378 } 12379 12380 /** 12381 * Reset the resolved layout direction. 12382 * 12383 * @hide 12384 */ 12385 public void resetResolvedPadding() { 12386 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12387 } 12388 12389 /** 12390 * This is called when the view is detached from a window. At this point it 12391 * no longer has a surface for drawing. 12392 * 12393 * @see #onAttachedToWindow() 12394 */ 12395 protected void onDetachedFromWindow() { 12396 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 12397 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12398 12399 removeUnsetPressCallback(); 12400 removeLongPressCallback(); 12401 removePerformClickCallback(); 12402 removeSendViewScrolledAccessibilityEventCallback(); 12403 12404 destroyDrawingCache(); 12405 destroyLayer(false); 12406 12407 cleanupDraw(); 12408 12409 mCurrentAnimation = null; 12410 } 12411 12412 private void cleanupDraw() { 12413 if (mAttachInfo != null) { 12414 if (mDisplayList != null) { 12415 mDisplayList.markDirty(); 12416 mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList); 12417 } 12418 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 12419 } else { 12420 // Should never happen 12421 resetDisplayList(); 12422 } 12423 } 12424 12425 /** 12426 * This method ensures the hardware renderer is in a valid state 12427 * before executing the specified action. 12428 * 12429 * This method will attempt to set a valid state even if the window 12430 * the renderer is attached to was destroyed. 12431 * 12432 * This method is not guaranteed to work. If the hardware renderer 12433 * does not exist or cannot be put in a valid state, this method 12434 * will not executed the specified action. 12435 * 12436 * The specified action is executed synchronously. 12437 * 12438 * @param action The action to execute after the renderer is in a valid state 12439 * 12440 * @return True if the specified Runnable was executed, false otherwise 12441 * 12442 * @hide 12443 */ 12444 public boolean executeHardwareAction(Runnable action) { 12445 //noinspection SimplifiableIfStatement 12446 if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) { 12447 return mAttachInfo.mHardwareRenderer.safelyRun(action); 12448 } 12449 return false; 12450 } 12451 12452 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 12453 } 12454 12455 /** 12456 * @return The number of times this view has been attached to a window 12457 */ 12458 protected int getWindowAttachCount() { 12459 return mWindowAttachCount; 12460 } 12461 12462 /** 12463 * Retrieve a unique token identifying the window this view is attached to. 12464 * @return Return the window's token for use in 12465 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 12466 */ 12467 public IBinder getWindowToken() { 12468 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 12469 } 12470 12471 /** 12472 * Retrieve the {@link WindowId} for the window this view is 12473 * currently attached to. 12474 */ 12475 public WindowId getWindowId() { 12476 if (mAttachInfo == null) { 12477 return null; 12478 } 12479 if (mAttachInfo.mWindowId == null) { 12480 try { 12481 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 12482 mAttachInfo.mWindowToken); 12483 mAttachInfo.mWindowId = new WindowId( 12484 mAttachInfo.mIWindowId); 12485 } catch (RemoteException e) { 12486 } 12487 } 12488 return mAttachInfo.mWindowId; 12489 } 12490 12491 /** 12492 * Retrieve a unique token identifying the top-level "real" window of 12493 * the window that this view is attached to. That is, this is like 12494 * {@link #getWindowToken}, except if the window this view in is a panel 12495 * window (attached to another containing window), then the token of 12496 * the containing window is returned instead. 12497 * 12498 * @return Returns the associated window token, either 12499 * {@link #getWindowToken()} or the containing window's token. 12500 */ 12501 public IBinder getApplicationWindowToken() { 12502 AttachInfo ai = mAttachInfo; 12503 if (ai != null) { 12504 IBinder appWindowToken = ai.mPanelParentWindowToken; 12505 if (appWindowToken == null) { 12506 appWindowToken = ai.mWindowToken; 12507 } 12508 return appWindowToken; 12509 } 12510 return null; 12511 } 12512 12513 /** 12514 * Gets the logical display to which the view's window has been attached. 12515 * 12516 * @return The logical display, or null if the view is not currently attached to a window. 12517 */ 12518 public Display getDisplay() { 12519 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 12520 } 12521 12522 /** 12523 * Retrieve private session object this view hierarchy is using to 12524 * communicate with the window manager. 12525 * @return the session object to communicate with the window manager 12526 */ 12527 /*package*/ IWindowSession getWindowSession() { 12528 return mAttachInfo != null ? mAttachInfo.mSession : null; 12529 } 12530 12531 /** 12532 * @param info the {@link android.view.View.AttachInfo} to associated with 12533 * this view 12534 */ 12535 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 12536 //System.out.println("Attached! " + this); 12537 mAttachInfo = info; 12538 if (mOverlay != null) { 12539 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 12540 } 12541 mWindowAttachCount++; 12542 // We will need to evaluate the drawable state at least once. 12543 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 12544 if (mFloatingTreeObserver != null) { 12545 info.mTreeObserver.merge(mFloatingTreeObserver); 12546 mFloatingTreeObserver = null; 12547 } 12548 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 12549 mAttachInfo.mScrollContainers.add(this); 12550 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 12551 } 12552 performCollectViewAttributes(mAttachInfo, visibility); 12553 onAttachedToWindow(); 12554 12555 ListenerInfo li = mListenerInfo; 12556 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 12557 li != null ? li.mOnAttachStateChangeListeners : null; 12558 if (listeners != null && listeners.size() > 0) { 12559 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 12560 // perform the dispatching. The iterator is a safe guard against listeners that 12561 // could mutate the list by calling the various add/remove methods. This prevents 12562 // the array from being modified while we iterate it. 12563 for (OnAttachStateChangeListener listener : listeners) { 12564 listener.onViewAttachedToWindow(this); 12565 } 12566 } 12567 12568 int vis = info.mWindowVisibility; 12569 if (vis != GONE) { 12570 onWindowVisibilityChanged(vis); 12571 } 12572 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 12573 // If nobody has evaluated the drawable state yet, then do it now. 12574 refreshDrawableState(); 12575 } 12576 needGlobalAttributesUpdate(false); 12577 } 12578 12579 void dispatchDetachedFromWindow() { 12580 AttachInfo info = mAttachInfo; 12581 if (info != null) { 12582 int vis = info.mWindowVisibility; 12583 if (vis != GONE) { 12584 onWindowVisibilityChanged(GONE); 12585 } 12586 } 12587 12588 onDetachedFromWindow(); 12589 12590 ListenerInfo li = mListenerInfo; 12591 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 12592 li != null ? li.mOnAttachStateChangeListeners : null; 12593 if (listeners != null && listeners.size() > 0) { 12594 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 12595 // perform the dispatching. The iterator is a safe guard against listeners that 12596 // could mutate the list by calling the various add/remove methods. This prevents 12597 // the array from being modified while we iterate it. 12598 for (OnAttachStateChangeListener listener : listeners) { 12599 listener.onViewDetachedFromWindow(this); 12600 } 12601 } 12602 12603 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 12604 mAttachInfo.mScrollContainers.remove(this); 12605 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 12606 } 12607 12608 mAttachInfo = null; 12609 if (mOverlay != null) { 12610 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 12611 } 12612 } 12613 12614 /** 12615 * Cancel any deferred high-level input events that were previously posted to the event queue. 12616 * 12617 * <p>Many views post high-level events such as click handlers to the event queue 12618 * to run deferred in order to preserve a desired user experience - clearing visible 12619 * pressed states before executing, etc. This method will abort any events of this nature 12620 * that are currently in flight.</p> 12621 * 12622 * <p>Custom views that generate their own high-level deferred input events should override 12623 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 12624 * 12625 * <p>This will also cancel pending input events for any child views.</p> 12626 * 12627 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 12628 * This will not impact newer events posted after this call that may occur as a result of 12629 * lower-level input events still waiting in the queue. If you are trying to prevent 12630 * double-submitted events for the duration of some sort of asynchronous transaction 12631 * you should also take other steps to protect against unexpected double inputs e.g. calling 12632 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 12633 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 12634 */ 12635 public final void cancelPendingInputEvents() { 12636 dispatchCancelPendingInputEvents(); 12637 } 12638 12639 /** 12640 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 12641 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 12642 */ 12643 void dispatchCancelPendingInputEvents() { 12644 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 12645 onCancelPendingInputEvents(); 12646 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 12647 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 12648 " did not call through to super.onCancelPendingInputEvents()"); 12649 } 12650 } 12651 12652 /** 12653 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 12654 * a parent view. 12655 * 12656 * <p>This method is responsible for removing any pending high-level input events that were 12657 * posted to the event queue to run later. Custom view classes that post their own deferred 12658 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 12659 * {@link android.os.Handler} should override this method, call 12660 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 12661 * </p> 12662 */ 12663 public void onCancelPendingInputEvents() { 12664 removePerformClickCallback(); 12665 cancelLongPress(); 12666 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 12667 } 12668 12669 /** 12670 * Store this view hierarchy's frozen state into the given container. 12671 * 12672 * @param container The SparseArray in which to save the view's state. 12673 * 12674 * @see #restoreHierarchyState(android.util.SparseArray) 12675 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12676 * @see #onSaveInstanceState() 12677 */ 12678 public void saveHierarchyState(SparseArray<Parcelable> container) { 12679 dispatchSaveInstanceState(container); 12680 } 12681 12682 /** 12683 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 12684 * this view and its children. May be overridden to modify how freezing happens to a 12685 * view's children; for example, some views may want to not store state for their children. 12686 * 12687 * @param container The SparseArray in which to save the view's state. 12688 * 12689 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12690 * @see #saveHierarchyState(android.util.SparseArray) 12691 * @see #onSaveInstanceState() 12692 */ 12693 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 12694 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 12695 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 12696 Parcelable state = onSaveInstanceState(); 12697 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 12698 throw new IllegalStateException( 12699 "Derived class did not call super.onSaveInstanceState()"); 12700 } 12701 if (state != null) { 12702 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 12703 // + ": " + state); 12704 container.put(mID, state); 12705 } 12706 } 12707 } 12708 12709 /** 12710 * Hook allowing a view to generate a representation of its internal state 12711 * that can later be used to create a new instance with that same state. 12712 * This state should only contain information that is not persistent or can 12713 * not be reconstructed later. For example, you will never store your 12714 * current position on screen because that will be computed again when a 12715 * new instance of the view is placed in its view hierarchy. 12716 * <p> 12717 * Some examples of things you may store here: the current cursor position 12718 * in a text view (but usually not the text itself since that is stored in a 12719 * content provider or other persistent storage), the currently selected 12720 * item in a list view. 12721 * 12722 * @return Returns a Parcelable object containing the view's current dynamic 12723 * state, or null if there is nothing interesting to save. The 12724 * default implementation returns null. 12725 * @see #onRestoreInstanceState(android.os.Parcelable) 12726 * @see #saveHierarchyState(android.util.SparseArray) 12727 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12728 * @see #setSaveEnabled(boolean) 12729 */ 12730 protected Parcelable onSaveInstanceState() { 12731 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 12732 return BaseSavedState.EMPTY_STATE; 12733 } 12734 12735 /** 12736 * Restore this view hierarchy's frozen state from the given container. 12737 * 12738 * @param container The SparseArray which holds previously frozen states. 12739 * 12740 * @see #saveHierarchyState(android.util.SparseArray) 12741 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12742 * @see #onRestoreInstanceState(android.os.Parcelable) 12743 */ 12744 public void restoreHierarchyState(SparseArray<Parcelable> container) { 12745 dispatchRestoreInstanceState(container); 12746 } 12747 12748 /** 12749 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 12750 * state for this view and its children. May be overridden to modify how restoring 12751 * happens to a view's children; for example, some views may want to not store state 12752 * for their children. 12753 * 12754 * @param container The SparseArray which holds previously saved state. 12755 * 12756 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12757 * @see #restoreHierarchyState(android.util.SparseArray) 12758 * @see #onRestoreInstanceState(android.os.Parcelable) 12759 */ 12760 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 12761 if (mID != NO_ID) { 12762 Parcelable state = container.get(mID); 12763 if (state != null) { 12764 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 12765 // + ": " + state); 12766 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 12767 onRestoreInstanceState(state); 12768 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 12769 throw new IllegalStateException( 12770 "Derived class did not call super.onRestoreInstanceState()"); 12771 } 12772 } 12773 } 12774 } 12775 12776 /** 12777 * Hook allowing a view to re-apply a representation of its internal state that had previously 12778 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 12779 * null state. 12780 * 12781 * @param state The frozen state that had previously been returned by 12782 * {@link #onSaveInstanceState}. 12783 * 12784 * @see #onSaveInstanceState() 12785 * @see #restoreHierarchyState(android.util.SparseArray) 12786 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12787 */ 12788 protected void onRestoreInstanceState(Parcelable state) { 12789 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 12790 if (state != BaseSavedState.EMPTY_STATE && state != null) { 12791 throw new IllegalArgumentException("Wrong state class, expecting View State but " 12792 + "received " + state.getClass().toString() + " instead. This usually happens " 12793 + "when two views of different type have the same id in the same hierarchy. " 12794 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 12795 + "other views do not use the same id."); 12796 } 12797 } 12798 12799 /** 12800 * <p>Return the time at which the drawing of the view hierarchy started.</p> 12801 * 12802 * @return the drawing start time in milliseconds 12803 */ 12804 public long getDrawingTime() { 12805 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 12806 } 12807 12808 /** 12809 * <p>Enables or disables the duplication of the parent's state into this view. When 12810 * duplication is enabled, this view gets its drawable state from its parent rather 12811 * than from its own internal properties.</p> 12812 * 12813 * <p>Note: in the current implementation, setting this property to true after the 12814 * view was added to a ViewGroup might have no effect at all. This property should 12815 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 12816 * 12817 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 12818 * property is enabled, an exception will be thrown.</p> 12819 * 12820 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 12821 * parent, these states should not be affected by this method.</p> 12822 * 12823 * @param enabled True to enable duplication of the parent's drawable state, false 12824 * to disable it. 12825 * 12826 * @see #getDrawableState() 12827 * @see #isDuplicateParentStateEnabled() 12828 */ 12829 public void setDuplicateParentStateEnabled(boolean enabled) { 12830 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 12831 } 12832 12833 /** 12834 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 12835 * 12836 * @return True if this view's drawable state is duplicated from the parent, 12837 * false otherwise 12838 * 12839 * @see #getDrawableState() 12840 * @see #setDuplicateParentStateEnabled(boolean) 12841 */ 12842 public boolean isDuplicateParentStateEnabled() { 12843 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 12844 } 12845 12846 /** 12847 * <p>Specifies the type of layer backing this view. The layer can be 12848 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12849 * {@link #LAYER_TYPE_HARDWARE}.</p> 12850 * 12851 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12852 * instance that controls how the layer is composed on screen. The following 12853 * properties of the paint are taken into account when composing the layer:</p> 12854 * <ul> 12855 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12856 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12857 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12858 * </ul> 12859 * 12860 * <p>If this view has an alpha value set to < 1.0 by calling 12861 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 12862 * by this view's alpha value.</p> 12863 * 12864 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 12865 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 12866 * for more information on when and how to use layers.</p> 12867 * 12868 * @param layerType The type of layer to use with this view, must be one of 12869 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12870 * {@link #LAYER_TYPE_HARDWARE} 12871 * @param paint The paint used to compose the layer. This argument is optional 12872 * and can be null. It is ignored when the layer type is 12873 * {@link #LAYER_TYPE_NONE} 12874 * 12875 * @see #getLayerType() 12876 * @see #LAYER_TYPE_NONE 12877 * @see #LAYER_TYPE_SOFTWARE 12878 * @see #LAYER_TYPE_HARDWARE 12879 * @see #setAlpha(float) 12880 * 12881 * @attr ref android.R.styleable#View_layerType 12882 */ 12883 public void setLayerType(int layerType, Paint paint) { 12884 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 12885 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 12886 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 12887 } 12888 12889 if (layerType == mLayerType) { 12890 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 12891 mLayerPaint = paint == null ? new Paint() : paint; 12892 invalidateParentCaches(); 12893 invalidate(true); 12894 } 12895 return; 12896 } 12897 12898 // Destroy any previous software drawing cache if needed 12899 switch (mLayerType) { 12900 case LAYER_TYPE_HARDWARE: 12901 destroyLayer(false); 12902 // fall through - non-accelerated views may use software layer mechanism instead 12903 case LAYER_TYPE_SOFTWARE: 12904 destroyDrawingCache(); 12905 break; 12906 default: 12907 break; 12908 } 12909 12910 mLayerType = layerType; 12911 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 12912 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 12913 mLocalDirtyRect = layerDisabled ? null : new Rect(); 12914 12915 invalidateParentCaches(); 12916 invalidate(true); 12917 } 12918 12919 /** 12920 * Updates the {@link Paint} object used with the current layer (used only if the current 12921 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 12922 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 12923 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 12924 * ensure that the view gets redrawn immediately. 12925 * 12926 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12927 * instance that controls how the layer is composed on screen. The following 12928 * properties of the paint are taken into account when composing the layer:</p> 12929 * <ul> 12930 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12931 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12932 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12933 * </ul> 12934 * 12935 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 12936 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 12937 * 12938 * @param paint The paint used to compose the layer. This argument is optional 12939 * and can be null. It is ignored when the layer type is 12940 * {@link #LAYER_TYPE_NONE} 12941 * 12942 * @see #setLayerType(int, android.graphics.Paint) 12943 */ 12944 public void setLayerPaint(Paint paint) { 12945 int layerType = getLayerType(); 12946 if (layerType != LAYER_TYPE_NONE) { 12947 mLayerPaint = paint == null ? new Paint() : paint; 12948 if (layerType == LAYER_TYPE_HARDWARE) { 12949 HardwareLayer layer = getHardwareLayer(); 12950 if (layer != null) { 12951 layer.setLayerPaint(paint); 12952 } 12953 invalidateViewProperty(false, false); 12954 } else { 12955 invalidate(); 12956 } 12957 } 12958 } 12959 12960 /** 12961 * Indicates whether this view has a static layer. A view with layer type 12962 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 12963 * dynamic. 12964 */ 12965 boolean hasStaticLayer() { 12966 return true; 12967 } 12968 12969 /** 12970 * Indicates what type of layer is currently associated with this view. By default 12971 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 12972 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 12973 * for more information on the different types of layers. 12974 * 12975 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12976 * {@link #LAYER_TYPE_HARDWARE} 12977 * 12978 * @see #setLayerType(int, android.graphics.Paint) 12979 * @see #buildLayer() 12980 * @see #LAYER_TYPE_NONE 12981 * @see #LAYER_TYPE_SOFTWARE 12982 * @see #LAYER_TYPE_HARDWARE 12983 */ 12984 public int getLayerType() { 12985 return mLayerType; 12986 } 12987 12988 /** 12989 * Forces this view's layer to be created and this view to be rendered 12990 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 12991 * invoking this method will have no effect. 12992 * 12993 * This method can for instance be used to render a view into its layer before 12994 * starting an animation. If this view is complex, rendering into the layer 12995 * before starting the animation will avoid skipping frames. 12996 * 12997 * @throws IllegalStateException If this view is not attached to a window 12998 * 12999 * @see #setLayerType(int, android.graphics.Paint) 13000 */ 13001 public void buildLayer() { 13002 if (mLayerType == LAYER_TYPE_NONE) return; 13003 13004 final AttachInfo attachInfo = mAttachInfo; 13005 if (attachInfo == null) { 13006 throw new IllegalStateException("This view must be attached to a window first"); 13007 } 13008 13009 switch (mLayerType) { 13010 case LAYER_TYPE_HARDWARE: 13011 if (attachInfo.mHardwareRenderer != null && 13012 attachInfo.mHardwareRenderer.isEnabled() && 13013 attachInfo.mHardwareRenderer.validate()) { 13014 getHardwareLayer(); 13015 // TODO: We need a better way to handle this case 13016 // If views have registered pre-draw listeners they need 13017 // to be notified before we build the layer. Those listeners 13018 // may however rely on other events to happen first so we 13019 // cannot just invoke them here until they don't cancel the 13020 // current frame 13021 if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) { 13022 attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates(); 13023 } 13024 } 13025 break; 13026 case LAYER_TYPE_SOFTWARE: 13027 buildDrawingCache(true); 13028 break; 13029 } 13030 } 13031 13032 /** 13033 * <p>Returns a hardware layer that can be used to draw this view again 13034 * without executing its draw method.</p> 13035 * 13036 * @return A HardwareLayer ready to render, or null if an error occurred. 13037 */ 13038 HardwareLayer getHardwareLayer() { 13039 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 13040 !mAttachInfo.mHardwareRenderer.isEnabled()) { 13041 return null; 13042 } 13043 13044 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 13045 13046 final int width = mRight - mLeft; 13047 final int height = mBottom - mTop; 13048 13049 if (width == 0 || height == 0) { 13050 return null; 13051 } 13052 13053 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 13054 if (mHardwareLayer == null) { 13055 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 13056 width, height, isOpaque()); 13057 mLocalDirtyRect.set(0, 0, width, height); 13058 } else { 13059 if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 13060 if (mHardwareLayer.resize(width, height)) { 13061 mLocalDirtyRect.set(0, 0, width, height); 13062 } 13063 } 13064 13065 // This should not be necessary but applications that change 13066 // the parameters of their background drawable without calling 13067 // this.setBackground(Drawable) can leave the view in a bad state 13068 // (for instance isOpaque() returns true, but the background is 13069 // not opaque.) 13070 computeOpaqueFlags(); 13071 13072 final boolean opaque = isOpaque(); 13073 if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) { 13074 mHardwareLayer.setOpaque(opaque); 13075 mLocalDirtyRect.set(0, 0, width, height); 13076 } 13077 } 13078 13079 // The layer is not valid if the underlying GPU resources cannot be allocated 13080 if (!mHardwareLayer.isValid()) { 13081 return null; 13082 } 13083 13084 mHardwareLayer.setLayerPaint(mLayerPaint); 13085 mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect); 13086 ViewRootImpl viewRoot = getViewRootImpl(); 13087 if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer); 13088 13089 mLocalDirtyRect.setEmpty(); 13090 } 13091 13092 return mHardwareLayer; 13093 } 13094 13095 /** 13096 * Destroys this View's hardware layer if possible. 13097 * 13098 * @return True if the layer was destroyed, false otherwise. 13099 * 13100 * @see #setLayerType(int, android.graphics.Paint) 13101 * @see #LAYER_TYPE_HARDWARE 13102 */ 13103 boolean destroyLayer(boolean valid) { 13104 if (mHardwareLayer != null) { 13105 AttachInfo info = mAttachInfo; 13106 if (info != null && info.mHardwareRenderer != null && 13107 info.mHardwareRenderer.isEnabled() && 13108 (valid || info.mHardwareRenderer.validate())) { 13109 13110 info.mHardwareRenderer.cancelLayerUpdate(mHardwareLayer); 13111 mHardwareLayer.destroy(); 13112 mHardwareLayer = null; 13113 13114 invalidate(true); 13115 invalidateParentCaches(); 13116 } 13117 return true; 13118 } 13119 return false; 13120 } 13121 13122 /** 13123 * Destroys all hardware rendering resources. This method is invoked 13124 * when the system needs to reclaim resources. Upon execution of this 13125 * method, you should free any OpenGL resources created by the view. 13126 * 13127 * Note: you <strong>must</strong> call 13128 * <code>super.destroyHardwareResources()</code> when overriding 13129 * this method. 13130 * 13131 * @hide 13132 */ 13133 protected void destroyHardwareResources() { 13134 resetDisplayList(); 13135 destroyLayer(true); 13136 } 13137 13138 /** 13139 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13140 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13141 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13142 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13143 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13144 * null.</p> 13145 * 13146 * <p>Enabling the drawing cache is similar to 13147 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13148 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13149 * drawing cache has no effect on rendering because the system uses a different mechanism 13150 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13151 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13152 * for information on how to enable software and hardware layers.</p> 13153 * 13154 * <p>This API can be used to manually generate 13155 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13156 * {@link #getDrawingCache()}.</p> 13157 * 13158 * @param enabled true to enable the drawing cache, false otherwise 13159 * 13160 * @see #isDrawingCacheEnabled() 13161 * @see #getDrawingCache() 13162 * @see #buildDrawingCache() 13163 * @see #setLayerType(int, android.graphics.Paint) 13164 */ 13165 public void setDrawingCacheEnabled(boolean enabled) { 13166 mCachingFailed = false; 13167 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13168 } 13169 13170 /** 13171 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13172 * 13173 * @return true if the drawing cache is enabled 13174 * 13175 * @see #setDrawingCacheEnabled(boolean) 13176 * @see #getDrawingCache() 13177 */ 13178 @ViewDebug.ExportedProperty(category = "drawing") 13179 public boolean isDrawingCacheEnabled() { 13180 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13181 } 13182 13183 /** 13184 * Debugging utility which recursively outputs the dirty state of a view and its 13185 * descendants. 13186 * 13187 * @hide 13188 */ 13189 @SuppressWarnings({"UnusedDeclaration"}) 13190 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13191 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13192 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13193 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13194 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13195 if (clear) { 13196 mPrivateFlags &= clearMask; 13197 } 13198 if (this instanceof ViewGroup) { 13199 ViewGroup parent = (ViewGroup) this; 13200 final int count = parent.getChildCount(); 13201 for (int i = 0; i < count; i++) { 13202 final View child = parent.getChildAt(i); 13203 child.outputDirtyFlags(indent + " ", clear, clearMask); 13204 } 13205 } 13206 } 13207 13208 /** 13209 * This method is used by ViewGroup to cause its children to restore or recreate their 13210 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13211 * to recreate its own display list, which would happen if it went through the normal 13212 * draw/dispatchDraw mechanisms. 13213 * 13214 * @hide 13215 */ 13216 protected void dispatchGetDisplayList() {} 13217 13218 /** 13219 * A view that is not attached or hardware accelerated cannot create a display list. 13220 * This method checks these conditions and returns the appropriate result. 13221 * 13222 * @return true if view has the ability to create a display list, false otherwise. 13223 * 13224 * @hide 13225 */ 13226 public boolean canHaveDisplayList() { 13227 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13228 } 13229 13230 /** 13231 * @return The {@link HardwareRenderer} associated with that view or null if 13232 * hardware rendering is not supported or this view is not attached 13233 * to a window. 13234 * 13235 * @hide 13236 */ 13237 public HardwareRenderer getHardwareRenderer() { 13238 if (mAttachInfo != null) { 13239 return mAttachInfo.mHardwareRenderer; 13240 } 13241 return null; 13242 } 13243 13244 /** 13245 * Returns a DisplayList. If the incoming displayList is null, one will be created. 13246 * Otherwise, the same display list will be returned (after having been rendered into 13247 * along the way, depending on the invalidation state of the view). 13248 * 13249 * @param displayList The previous version of this displayList, could be null. 13250 * @param isLayer Whether the requester of the display list is a layer. If so, 13251 * the view will avoid creating a layer inside the resulting display list. 13252 * @return A new or reused DisplayList object. 13253 */ 13254 private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) { 13255 if (!canHaveDisplayList()) { 13256 return null; 13257 } 13258 13259 if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || 13260 displayList == null || !displayList.isValid() || 13261 (!isLayer && mRecreateDisplayList))) { 13262 // Don't need to recreate the display list, just need to tell our 13263 // children to restore/recreate theirs 13264 if (displayList != null && displayList.isValid() && 13265 !isLayer && !mRecreateDisplayList) { 13266 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13267 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13268 dispatchGetDisplayList(); 13269 13270 return displayList; 13271 } 13272 13273 if (!isLayer) { 13274 // If we got here, we're recreating it. Mark it as such to ensure that 13275 // we copy in child display lists into ours in drawChild() 13276 mRecreateDisplayList = true; 13277 } 13278 if (displayList == null) { 13279 displayList = mAttachInfo.mHardwareRenderer.createDisplayList(getClass().getName()); 13280 // If we're creating a new display list, make sure our parent gets invalidated 13281 // since they will need to recreate their display list to account for this 13282 // new child display list. 13283 invalidateParentCaches(); 13284 } 13285 13286 boolean caching = false; 13287 int width = mRight - mLeft; 13288 int height = mBottom - mTop; 13289 int layerType = getLayerType(); 13290 13291 final HardwareCanvas canvas = displayList.start(width, height); 13292 13293 try { 13294 if (!isLayer && layerType != LAYER_TYPE_NONE) { 13295 if (layerType == LAYER_TYPE_HARDWARE) { 13296 final HardwareLayer layer = getHardwareLayer(); 13297 if (layer != null && layer.isValid()) { 13298 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13299 } else { 13300 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 13301 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 13302 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13303 } 13304 caching = true; 13305 } else { 13306 buildDrawingCache(true); 13307 Bitmap cache = getDrawingCache(true); 13308 if (cache != null) { 13309 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13310 caching = true; 13311 } 13312 } 13313 } else { 13314 13315 computeScroll(); 13316 13317 canvas.translate(-mScrollX, -mScrollY); 13318 if (!isLayer) { 13319 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13320 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13321 } 13322 13323 // Fast path for layouts with no backgrounds 13324 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13325 dispatchDraw(canvas); 13326 if (mOverlay != null && !mOverlay.isEmpty()) { 13327 mOverlay.getOverlayView().draw(canvas); 13328 } 13329 } else { 13330 draw(canvas); 13331 } 13332 } 13333 } finally { 13334 displayList.end(); 13335 displayList.setCaching(caching); 13336 if (isLayer) { 13337 displayList.setLeftTopRightBottom(0, 0, width, height); 13338 } else { 13339 setDisplayListProperties(displayList); 13340 } 13341 } 13342 } else if (!isLayer) { 13343 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13344 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13345 } 13346 13347 return displayList; 13348 } 13349 13350 /** 13351 * Get the DisplayList for the HardwareLayer 13352 * 13353 * @param layer The HardwareLayer whose DisplayList we want 13354 * @return A DisplayList fopr the specified HardwareLayer 13355 */ 13356 private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) { 13357 DisplayList displayList = getDisplayList(layer.getDisplayList(), true); 13358 layer.setDisplayList(displayList); 13359 return displayList; 13360 } 13361 13362 13363 /** 13364 * <p>Returns a display list that can be used to draw this view again 13365 * without executing its draw method.</p> 13366 * 13367 * @return A DisplayList ready to replay, or null if caching is not enabled. 13368 * 13369 * @hide 13370 */ 13371 public DisplayList getDisplayList() { 13372 mDisplayList = getDisplayList(mDisplayList, false); 13373 return mDisplayList; 13374 } 13375 13376 private void clearDisplayList() { 13377 if (mDisplayList != null) { 13378 mDisplayList.clear(); 13379 } 13380 } 13381 13382 private void resetDisplayList() { 13383 if (mDisplayList != null) { 13384 mDisplayList.reset(); 13385 } 13386 } 13387 13388 /** 13389 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13390 * 13391 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13392 * 13393 * @see #getDrawingCache(boolean) 13394 */ 13395 public Bitmap getDrawingCache() { 13396 return getDrawingCache(false); 13397 } 13398 13399 /** 13400 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13401 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13402 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13403 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13404 * request the drawing cache by calling this method and draw it on screen if the 13405 * returned bitmap is not null.</p> 13406 * 13407 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13408 * this method will create a bitmap of the same size as this view. Because this bitmap 13409 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13410 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13411 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13412 * size than the view. This implies that your application must be able to handle this 13413 * size.</p> 13414 * 13415 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13416 * the current density of the screen when the application is in compatibility 13417 * mode. 13418 * 13419 * @return A bitmap representing this view or null if cache is disabled. 13420 * 13421 * @see #setDrawingCacheEnabled(boolean) 13422 * @see #isDrawingCacheEnabled() 13423 * @see #buildDrawingCache(boolean) 13424 * @see #destroyDrawingCache() 13425 */ 13426 public Bitmap getDrawingCache(boolean autoScale) { 13427 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13428 return null; 13429 } 13430 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13431 buildDrawingCache(autoScale); 13432 } 13433 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13434 } 13435 13436 /** 13437 * <p>Frees the resources used by the drawing cache. If you call 13438 * {@link #buildDrawingCache()} manually without calling 13439 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13440 * should cleanup the cache with this method afterwards.</p> 13441 * 13442 * @see #setDrawingCacheEnabled(boolean) 13443 * @see #buildDrawingCache() 13444 * @see #getDrawingCache() 13445 */ 13446 public void destroyDrawingCache() { 13447 if (mDrawingCache != null) { 13448 mDrawingCache.recycle(); 13449 mDrawingCache = null; 13450 } 13451 if (mUnscaledDrawingCache != null) { 13452 mUnscaledDrawingCache.recycle(); 13453 mUnscaledDrawingCache = null; 13454 } 13455 } 13456 13457 /** 13458 * Setting a solid background color for the drawing cache's bitmaps will improve 13459 * performance and memory usage. Note, though that this should only be used if this 13460 * view will always be drawn on top of a solid color. 13461 * 13462 * @param color The background color to use for the drawing cache's bitmap 13463 * 13464 * @see #setDrawingCacheEnabled(boolean) 13465 * @see #buildDrawingCache() 13466 * @see #getDrawingCache() 13467 */ 13468 public void setDrawingCacheBackgroundColor(int color) { 13469 if (color != mDrawingCacheBackgroundColor) { 13470 mDrawingCacheBackgroundColor = color; 13471 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13472 } 13473 } 13474 13475 /** 13476 * @see #setDrawingCacheBackgroundColor(int) 13477 * 13478 * @return The background color to used for the drawing cache's bitmap 13479 */ 13480 public int getDrawingCacheBackgroundColor() { 13481 return mDrawingCacheBackgroundColor; 13482 } 13483 13484 /** 13485 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13486 * 13487 * @see #buildDrawingCache(boolean) 13488 */ 13489 public void buildDrawingCache() { 13490 buildDrawingCache(false); 13491 } 13492 13493 /** 13494 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13495 * 13496 * <p>If you call {@link #buildDrawingCache()} manually without calling 13497 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13498 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13499 * 13500 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13501 * this method will create a bitmap of the same size as this view. Because this bitmap 13502 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13503 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13504 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13505 * size than the view. This implies that your application must be able to handle this 13506 * size.</p> 13507 * 13508 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13509 * you do not need the drawing cache bitmap, calling this method will increase memory 13510 * usage and cause the view to be rendered in software once, thus negatively impacting 13511 * performance.</p> 13512 * 13513 * @see #getDrawingCache() 13514 * @see #destroyDrawingCache() 13515 */ 13516 public void buildDrawingCache(boolean autoScale) { 13517 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13518 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13519 mCachingFailed = false; 13520 13521 int width = mRight - mLeft; 13522 int height = mBottom - mTop; 13523 13524 final AttachInfo attachInfo = mAttachInfo; 13525 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13526 13527 if (autoScale && scalingRequired) { 13528 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13529 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13530 } 13531 13532 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13533 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13534 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13535 13536 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13537 final long drawingCacheSize = 13538 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13539 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13540 if (width > 0 && height > 0) { 13541 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13542 + projectedBitmapSize + " bytes, only " 13543 + drawingCacheSize + " available"); 13544 } 13545 destroyDrawingCache(); 13546 mCachingFailed = true; 13547 return; 13548 } 13549 13550 boolean clear = true; 13551 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 13552 13553 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 13554 Bitmap.Config quality; 13555 if (!opaque) { 13556 // Never pick ARGB_4444 because it looks awful 13557 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 13558 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 13559 case DRAWING_CACHE_QUALITY_AUTO: 13560 case DRAWING_CACHE_QUALITY_LOW: 13561 case DRAWING_CACHE_QUALITY_HIGH: 13562 default: 13563 quality = Bitmap.Config.ARGB_8888; 13564 break; 13565 } 13566 } else { 13567 // Optimization for translucent windows 13568 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 13569 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 13570 } 13571 13572 // Try to cleanup memory 13573 if (bitmap != null) bitmap.recycle(); 13574 13575 try { 13576 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13577 width, height, quality); 13578 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 13579 if (autoScale) { 13580 mDrawingCache = bitmap; 13581 } else { 13582 mUnscaledDrawingCache = bitmap; 13583 } 13584 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 13585 } catch (OutOfMemoryError e) { 13586 // If there is not enough memory to create the bitmap cache, just 13587 // ignore the issue as bitmap caches are not required to draw the 13588 // view hierarchy 13589 if (autoScale) { 13590 mDrawingCache = null; 13591 } else { 13592 mUnscaledDrawingCache = null; 13593 } 13594 mCachingFailed = true; 13595 return; 13596 } 13597 13598 clear = drawingCacheBackgroundColor != 0; 13599 } 13600 13601 Canvas canvas; 13602 if (attachInfo != null) { 13603 canvas = attachInfo.mCanvas; 13604 if (canvas == null) { 13605 canvas = new Canvas(); 13606 } 13607 canvas.setBitmap(bitmap); 13608 // Temporarily clobber the cached Canvas in case one of our children 13609 // is also using a drawing cache. Without this, the children would 13610 // steal the canvas by attaching their own bitmap to it and bad, bad 13611 // thing would happen (invisible views, corrupted drawings, etc.) 13612 attachInfo.mCanvas = null; 13613 } else { 13614 // This case should hopefully never or seldom happen 13615 canvas = new Canvas(bitmap); 13616 } 13617 13618 if (clear) { 13619 bitmap.eraseColor(drawingCacheBackgroundColor); 13620 } 13621 13622 computeScroll(); 13623 final int restoreCount = canvas.save(); 13624 13625 if (autoScale && scalingRequired) { 13626 final float scale = attachInfo.mApplicationScale; 13627 canvas.scale(scale, scale); 13628 } 13629 13630 canvas.translate(-mScrollX, -mScrollY); 13631 13632 mPrivateFlags |= PFLAG_DRAWN; 13633 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 13634 mLayerType != LAYER_TYPE_NONE) { 13635 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 13636 } 13637 13638 // Fast path for layouts with no backgrounds 13639 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13640 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13641 dispatchDraw(canvas); 13642 if (mOverlay != null && !mOverlay.isEmpty()) { 13643 mOverlay.getOverlayView().draw(canvas); 13644 } 13645 } else { 13646 draw(canvas); 13647 } 13648 13649 canvas.restoreToCount(restoreCount); 13650 canvas.setBitmap(null); 13651 13652 if (attachInfo != null) { 13653 // Restore the cached Canvas for our siblings 13654 attachInfo.mCanvas = canvas; 13655 } 13656 } 13657 } 13658 13659 /** 13660 * Create a snapshot of the view into a bitmap. We should probably make 13661 * some form of this public, but should think about the API. 13662 */ 13663 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 13664 int width = mRight - mLeft; 13665 int height = mBottom - mTop; 13666 13667 final AttachInfo attachInfo = mAttachInfo; 13668 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 13669 width = (int) ((width * scale) + 0.5f); 13670 height = (int) ((height * scale) + 0.5f); 13671 13672 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13673 width > 0 ? width : 1, height > 0 ? height : 1, quality); 13674 if (bitmap == null) { 13675 throw new OutOfMemoryError(); 13676 } 13677 13678 Resources resources = getResources(); 13679 if (resources != null) { 13680 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 13681 } 13682 13683 Canvas canvas; 13684 if (attachInfo != null) { 13685 canvas = attachInfo.mCanvas; 13686 if (canvas == null) { 13687 canvas = new Canvas(); 13688 } 13689 canvas.setBitmap(bitmap); 13690 // Temporarily clobber the cached Canvas in case one of our children 13691 // is also using a drawing cache. Without this, the children would 13692 // steal the canvas by attaching their own bitmap to it and bad, bad 13693 // things would happen (invisible views, corrupted drawings, etc.) 13694 attachInfo.mCanvas = null; 13695 } else { 13696 // This case should hopefully never or seldom happen 13697 canvas = new Canvas(bitmap); 13698 } 13699 13700 if ((backgroundColor & 0xff000000) != 0) { 13701 bitmap.eraseColor(backgroundColor); 13702 } 13703 13704 computeScroll(); 13705 final int restoreCount = canvas.save(); 13706 canvas.scale(scale, scale); 13707 canvas.translate(-mScrollX, -mScrollY); 13708 13709 // Temporarily remove the dirty mask 13710 int flags = mPrivateFlags; 13711 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13712 13713 // Fast path for layouts with no backgrounds 13714 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13715 dispatchDraw(canvas); 13716 if (mOverlay != null && !mOverlay.isEmpty()) { 13717 mOverlay.getOverlayView().draw(canvas); 13718 } 13719 } else { 13720 draw(canvas); 13721 } 13722 13723 mPrivateFlags = flags; 13724 13725 canvas.restoreToCount(restoreCount); 13726 canvas.setBitmap(null); 13727 13728 if (attachInfo != null) { 13729 // Restore the cached Canvas for our siblings 13730 attachInfo.mCanvas = canvas; 13731 } 13732 13733 return bitmap; 13734 } 13735 13736 /** 13737 * Indicates whether this View is currently in edit mode. A View is usually 13738 * in edit mode when displayed within a developer tool. For instance, if 13739 * this View is being drawn by a visual user interface builder, this method 13740 * should return true. 13741 * 13742 * Subclasses should check the return value of this method to provide 13743 * different behaviors if their normal behavior might interfere with the 13744 * host environment. For instance: the class spawns a thread in its 13745 * constructor, the drawing code relies on device-specific features, etc. 13746 * 13747 * This method is usually checked in the drawing code of custom widgets. 13748 * 13749 * @return True if this View is in edit mode, false otherwise. 13750 */ 13751 public boolean isInEditMode() { 13752 return false; 13753 } 13754 13755 /** 13756 * If the View draws content inside its padding and enables fading edges, 13757 * it needs to support padding offsets. Padding offsets are added to the 13758 * fading edges to extend the length of the fade so that it covers pixels 13759 * drawn inside the padding. 13760 * 13761 * Subclasses of this class should override this method if they need 13762 * to draw content inside the padding. 13763 * 13764 * @return True if padding offset must be applied, false otherwise. 13765 * 13766 * @see #getLeftPaddingOffset() 13767 * @see #getRightPaddingOffset() 13768 * @see #getTopPaddingOffset() 13769 * @see #getBottomPaddingOffset() 13770 * 13771 * @since CURRENT 13772 */ 13773 protected boolean isPaddingOffsetRequired() { 13774 return false; 13775 } 13776 13777 /** 13778 * Amount by which to extend the left fading region. Called only when 13779 * {@link #isPaddingOffsetRequired()} returns true. 13780 * 13781 * @return The left padding offset in pixels. 13782 * 13783 * @see #isPaddingOffsetRequired() 13784 * 13785 * @since CURRENT 13786 */ 13787 protected int getLeftPaddingOffset() { 13788 return 0; 13789 } 13790 13791 /** 13792 * Amount by which to extend the right fading region. Called only when 13793 * {@link #isPaddingOffsetRequired()} returns true. 13794 * 13795 * @return The right padding offset in pixels. 13796 * 13797 * @see #isPaddingOffsetRequired() 13798 * 13799 * @since CURRENT 13800 */ 13801 protected int getRightPaddingOffset() { 13802 return 0; 13803 } 13804 13805 /** 13806 * Amount by which to extend the top fading region. Called only when 13807 * {@link #isPaddingOffsetRequired()} returns true. 13808 * 13809 * @return The top padding offset in pixels. 13810 * 13811 * @see #isPaddingOffsetRequired() 13812 * 13813 * @since CURRENT 13814 */ 13815 protected int getTopPaddingOffset() { 13816 return 0; 13817 } 13818 13819 /** 13820 * Amount by which to extend the bottom fading region. Called only when 13821 * {@link #isPaddingOffsetRequired()} returns true. 13822 * 13823 * @return The bottom padding offset in pixels. 13824 * 13825 * @see #isPaddingOffsetRequired() 13826 * 13827 * @since CURRENT 13828 */ 13829 protected int getBottomPaddingOffset() { 13830 return 0; 13831 } 13832 13833 /** 13834 * @hide 13835 * @param offsetRequired 13836 */ 13837 protected int getFadeTop(boolean offsetRequired) { 13838 int top = mPaddingTop; 13839 if (offsetRequired) top += getTopPaddingOffset(); 13840 return top; 13841 } 13842 13843 /** 13844 * @hide 13845 * @param offsetRequired 13846 */ 13847 protected int getFadeHeight(boolean offsetRequired) { 13848 int padding = mPaddingTop; 13849 if (offsetRequired) padding += getTopPaddingOffset(); 13850 return mBottom - mTop - mPaddingBottom - padding; 13851 } 13852 13853 /** 13854 * <p>Indicates whether this view is attached to a hardware accelerated 13855 * window or not.</p> 13856 * 13857 * <p>Even if this method returns true, it does not mean that every call 13858 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 13859 * accelerated {@link android.graphics.Canvas}. For instance, if this view 13860 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 13861 * window is hardware accelerated, 13862 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 13863 * return false, and this method will return true.</p> 13864 * 13865 * @return True if the view is attached to a window and the window is 13866 * hardware accelerated; false in any other case. 13867 */ 13868 public boolean isHardwareAccelerated() { 13869 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13870 } 13871 13872 /** 13873 * Sets a rectangular area on this view to which the view will be clipped 13874 * when it is drawn. Setting the value to null will remove the clip bounds 13875 * and the view will draw normally, using its full bounds. 13876 * 13877 * @param clipBounds The rectangular area, in the local coordinates of 13878 * this view, to which future drawing operations will be clipped. 13879 */ 13880 public void setClipBounds(Rect clipBounds) { 13881 if (clipBounds != null) { 13882 if (clipBounds.equals(mClipBounds)) { 13883 return; 13884 } 13885 if (mClipBounds == null) { 13886 invalidate(); 13887 mClipBounds = new Rect(clipBounds); 13888 } else { 13889 invalidate(Math.min(mClipBounds.left, clipBounds.left), 13890 Math.min(mClipBounds.top, clipBounds.top), 13891 Math.max(mClipBounds.right, clipBounds.right), 13892 Math.max(mClipBounds.bottom, clipBounds.bottom)); 13893 mClipBounds.set(clipBounds); 13894 } 13895 } else { 13896 if (mClipBounds != null) { 13897 invalidate(); 13898 mClipBounds = null; 13899 } 13900 } 13901 } 13902 13903 /** 13904 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 13905 * 13906 * @return A copy of the current clip bounds if clip bounds are set, 13907 * otherwise null. 13908 */ 13909 public Rect getClipBounds() { 13910 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 13911 } 13912 13913 /** 13914 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 13915 * case of an active Animation being run on the view. 13916 */ 13917 private boolean drawAnimation(ViewGroup parent, long drawingTime, 13918 Animation a, boolean scalingRequired) { 13919 Transformation invalidationTransform; 13920 final int flags = parent.mGroupFlags; 13921 final boolean initialized = a.isInitialized(); 13922 if (!initialized) { 13923 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 13924 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 13925 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 13926 onAnimationStart(); 13927 } 13928 13929 final Transformation t = parent.getChildTransformation(); 13930 boolean more = a.getTransformation(drawingTime, t, 1f); 13931 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 13932 if (parent.mInvalidationTransformation == null) { 13933 parent.mInvalidationTransformation = new Transformation(); 13934 } 13935 invalidationTransform = parent.mInvalidationTransformation; 13936 a.getTransformation(drawingTime, invalidationTransform, 1f); 13937 } else { 13938 invalidationTransform = t; 13939 } 13940 13941 if (more) { 13942 if (!a.willChangeBounds()) { 13943 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 13944 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 13945 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 13946 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 13947 // The child need to draw an animation, potentially offscreen, so 13948 // make sure we do not cancel invalidate requests 13949 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13950 parent.invalidate(mLeft, mTop, mRight, mBottom); 13951 } 13952 } else { 13953 if (parent.mInvalidateRegion == null) { 13954 parent.mInvalidateRegion = new RectF(); 13955 } 13956 final RectF region = parent.mInvalidateRegion; 13957 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 13958 invalidationTransform); 13959 13960 // The child need to draw an animation, potentially offscreen, so 13961 // make sure we do not cancel invalidate requests 13962 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13963 13964 final int left = mLeft + (int) region.left; 13965 final int top = mTop + (int) region.top; 13966 parent.invalidate(left, top, left + (int) (region.width() + .5f), 13967 top + (int) (region.height() + .5f)); 13968 } 13969 } 13970 return more; 13971 } 13972 13973 /** 13974 * This method is called by getDisplayList() when a display list is created or re-rendered. 13975 * It sets or resets the current value of all properties on that display list (resetting is 13976 * necessary when a display list is being re-created, because we need to make sure that 13977 * previously-set transform values 13978 */ 13979 void setDisplayListProperties(DisplayList displayList) { 13980 if (displayList != null) { 13981 displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 13982 displayList.setHasOverlappingRendering(hasOverlappingRendering()); 13983 if (mParent instanceof ViewGroup) { 13984 displayList.setClipToBounds( 13985 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 13986 } 13987 float alpha = 1; 13988 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 13989 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 13990 ViewGroup parentVG = (ViewGroup) mParent; 13991 final Transformation t = parentVG.getChildTransformation(); 13992 if (parentVG.getChildStaticTransformation(this, t)) { 13993 final int transformType = t.getTransformationType(); 13994 if (transformType != Transformation.TYPE_IDENTITY) { 13995 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 13996 alpha = t.getAlpha(); 13997 } 13998 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 13999 displayList.setMatrix(t.getMatrix()); 14000 } 14001 } 14002 } 14003 } 14004 if (mTransformationInfo != null) { 14005 alpha *= getFinalAlpha(); 14006 if (alpha < 1) { 14007 final int multipliedAlpha = (int) (255 * alpha); 14008 if (onSetAlpha(multipliedAlpha)) { 14009 alpha = 1; 14010 } 14011 } 14012 displayList.setTransformationInfo(alpha, 14013 mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY, 14014 mTransformationInfo.mRotation, mTransformationInfo.mRotationX, 14015 mTransformationInfo.mRotationY, mTransformationInfo.mScaleX, 14016 mTransformationInfo.mScaleY); 14017 if (mTransformationInfo.mCamera == null) { 14018 mTransformationInfo.mCamera = new Camera(); 14019 mTransformationInfo.matrix3D = new Matrix(); 14020 } 14021 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ()); 14022 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) { 14023 displayList.setPivotX(getPivotX()); 14024 displayList.setPivotY(getPivotY()); 14025 } 14026 } else if (alpha < 1) { 14027 displayList.setAlpha(alpha); 14028 } 14029 } 14030 } 14031 14032 /** 14033 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14034 * This draw() method is an implementation detail and is not intended to be overridden or 14035 * to be called from anywhere else other than ViewGroup.drawChild(). 14036 */ 14037 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14038 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14039 boolean more = false; 14040 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14041 final int flags = parent.mGroupFlags; 14042 14043 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14044 parent.getChildTransformation().clear(); 14045 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14046 } 14047 14048 Transformation transformToApply = null; 14049 boolean concatMatrix = false; 14050 14051 boolean scalingRequired = false; 14052 boolean caching; 14053 int layerType = getLayerType(); 14054 14055 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14056 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14057 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14058 caching = true; 14059 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14060 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14061 } else { 14062 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14063 } 14064 14065 final Animation a = getAnimation(); 14066 if (a != null) { 14067 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14068 concatMatrix = a.willChangeTransformationMatrix(); 14069 if (concatMatrix) { 14070 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14071 } 14072 transformToApply = parent.getChildTransformation(); 14073 } else { 14074 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == 14075 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) { 14076 // No longer animating: clear out old animation matrix 14077 mDisplayList.setAnimationMatrix(null); 14078 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14079 } 14080 if (!useDisplayListProperties && 14081 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14082 final Transformation t = parent.getChildTransformation(); 14083 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14084 if (hasTransform) { 14085 final int transformType = t.getTransformationType(); 14086 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14087 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14088 } 14089 } 14090 } 14091 14092 concatMatrix |= !childHasIdentityMatrix; 14093 14094 // Sets the flag as early as possible to allow draw() implementations 14095 // to call invalidate() successfully when doing animations 14096 mPrivateFlags |= PFLAG_DRAWN; 14097 14098 if (!concatMatrix && 14099 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14100 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14101 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14102 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14103 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14104 return more; 14105 } 14106 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14107 14108 if (hardwareAccelerated) { 14109 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14110 // retain the flag's value temporarily in the mRecreateDisplayList flag 14111 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14112 mPrivateFlags &= ~PFLAG_INVALIDATED; 14113 } 14114 14115 DisplayList displayList = null; 14116 Bitmap cache = null; 14117 boolean hasDisplayList = false; 14118 if (caching) { 14119 if (!hardwareAccelerated) { 14120 if (layerType != LAYER_TYPE_NONE) { 14121 layerType = LAYER_TYPE_SOFTWARE; 14122 buildDrawingCache(true); 14123 } 14124 cache = getDrawingCache(true); 14125 } else { 14126 switch (layerType) { 14127 case LAYER_TYPE_SOFTWARE: 14128 if (useDisplayListProperties) { 14129 hasDisplayList = canHaveDisplayList(); 14130 } else { 14131 buildDrawingCache(true); 14132 cache = getDrawingCache(true); 14133 } 14134 break; 14135 case LAYER_TYPE_HARDWARE: 14136 if (useDisplayListProperties) { 14137 hasDisplayList = canHaveDisplayList(); 14138 } 14139 break; 14140 case LAYER_TYPE_NONE: 14141 // Delay getting the display list until animation-driven alpha values are 14142 // set up and possibly passed on to the view 14143 hasDisplayList = canHaveDisplayList(); 14144 break; 14145 } 14146 } 14147 } 14148 useDisplayListProperties &= hasDisplayList; 14149 if (useDisplayListProperties) { 14150 displayList = getDisplayList(); 14151 if (!displayList.isValid()) { 14152 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14153 // to getDisplayList(), the display list will be marked invalid and we should not 14154 // try to use it again. 14155 displayList = null; 14156 hasDisplayList = false; 14157 useDisplayListProperties = false; 14158 } 14159 } 14160 14161 int sx = 0; 14162 int sy = 0; 14163 if (!hasDisplayList) { 14164 computeScroll(); 14165 sx = mScrollX; 14166 sy = mScrollY; 14167 } 14168 14169 final boolean hasNoCache = cache == null || hasDisplayList; 14170 final boolean offsetForScroll = cache == null && !hasDisplayList && 14171 layerType != LAYER_TYPE_HARDWARE; 14172 14173 int restoreTo = -1; 14174 if (!useDisplayListProperties || transformToApply != null) { 14175 restoreTo = canvas.save(); 14176 } 14177 if (offsetForScroll) { 14178 canvas.translate(mLeft - sx, mTop - sy); 14179 } else { 14180 if (!useDisplayListProperties) { 14181 canvas.translate(mLeft, mTop); 14182 } 14183 if (scalingRequired) { 14184 if (useDisplayListProperties) { 14185 // TODO: Might not need this if we put everything inside the DL 14186 restoreTo = canvas.save(); 14187 } 14188 // mAttachInfo cannot be null, otherwise scalingRequired == false 14189 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14190 canvas.scale(scale, scale); 14191 } 14192 } 14193 14194 float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14195 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14196 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14197 if (transformToApply != null || !childHasIdentityMatrix) { 14198 int transX = 0; 14199 int transY = 0; 14200 14201 if (offsetForScroll) { 14202 transX = -sx; 14203 transY = -sy; 14204 } 14205 14206 if (transformToApply != null) { 14207 if (concatMatrix) { 14208 if (useDisplayListProperties) { 14209 displayList.setAnimationMatrix(transformToApply.getMatrix()); 14210 } else { 14211 // Undo the scroll translation, apply the transformation matrix, 14212 // then redo the scroll translate to get the correct result. 14213 canvas.translate(-transX, -transY); 14214 canvas.concat(transformToApply.getMatrix()); 14215 canvas.translate(transX, transY); 14216 } 14217 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14218 } 14219 14220 float transformAlpha = transformToApply.getAlpha(); 14221 if (transformAlpha < 1) { 14222 alpha *= transformAlpha; 14223 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14224 } 14225 } 14226 14227 if (!childHasIdentityMatrix && !useDisplayListProperties) { 14228 canvas.translate(-transX, -transY); 14229 canvas.concat(getMatrix()); 14230 canvas.translate(transX, transY); 14231 } 14232 } 14233 14234 // Deal with alpha if it is or used to be <1 14235 if (alpha < 1 || 14236 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14237 if (alpha < 1) { 14238 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14239 } else { 14240 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14241 } 14242 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14243 if (hasNoCache) { 14244 final int multipliedAlpha = (int) (255 * alpha); 14245 if (!onSetAlpha(multipliedAlpha)) { 14246 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14247 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14248 layerType != LAYER_TYPE_NONE) { 14249 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14250 } 14251 if (useDisplayListProperties) { 14252 displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14253 } else if (layerType == LAYER_TYPE_NONE) { 14254 final int scrollX = hasDisplayList ? 0 : sx; 14255 final int scrollY = hasDisplayList ? 0 : sy; 14256 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 14257 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 14258 } 14259 } else { 14260 // Alpha is handled by the child directly, clobber the layer's alpha 14261 mPrivateFlags |= PFLAG_ALPHA_SET; 14262 } 14263 } 14264 } 14265 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14266 onSetAlpha(255); 14267 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14268 } 14269 14270 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 14271 !useDisplayListProperties && cache == null) { 14272 if (offsetForScroll) { 14273 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14274 } else { 14275 if (!scalingRequired || cache == null) { 14276 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14277 } else { 14278 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14279 } 14280 } 14281 } 14282 14283 if (!useDisplayListProperties && hasDisplayList) { 14284 displayList = getDisplayList(); 14285 if (!displayList.isValid()) { 14286 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14287 // to getDisplayList(), the display list will be marked invalid and we should not 14288 // try to use it again. 14289 displayList = null; 14290 hasDisplayList = false; 14291 } 14292 } 14293 14294 if (hasNoCache) { 14295 boolean layerRendered = false; 14296 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 14297 final HardwareLayer layer = getHardwareLayer(); 14298 if (layer != null && layer.isValid()) { 14299 mLayerPaint.setAlpha((int) (alpha * 255)); 14300 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14301 layerRendered = true; 14302 } else { 14303 final int scrollX = hasDisplayList ? 0 : sx; 14304 final int scrollY = hasDisplayList ? 0 : sy; 14305 canvas.saveLayer(scrollX, scrollY, 14306 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14307 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14308 } 14309 } 14310 14311 if (!layerRendered) { 14312 if (!hasDisplayList) { 14313 // Fast path for layouts with no backgrounds 14314 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14315 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14316 dispatchDraw(canvas); 14317 } else { 14318 draw(canvas); 14319 } 14320 } else { 14321 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14322 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 14323 } 14324 } 14325 } else if (cache != null) { 14326 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14327 Paint cachePaint; 14328 14329 if (layerType == LAYER_TYPE_NONE) { 14330 cachePaint = parent.mCachePaint; 14331 if (cachePaint == null) { 14332 cachePaint = new Paint(); 14333 cachePaint.setDither(false); 14334 parent.mCachePaint = cachePaint; 14335 } 14336 if (alpha < 1) { 14337 cachePaint.setAlpha((int) (alpha * 255)); 14338 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14339 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14340 cachePaint.setAlpha(255); 14341 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14342 } 14343 } else { 14344 cachePaint = mLayerPaint; 14345 cachePaint.setAlpha((int) (alpha * 255)); 14346 } 14347 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14348 } 14349 14350 if (restoreTo >= 0) { 14351 canvas.restoreToCount(restoreTo); 14352 } 14353 14354 if (a != null && !more) { 14355 if (!hardwareAccelerated && !a.getFillAfter()) { 14356 onSetAlpha(255); 14357 } 14358 parent.finishAnimatingView(this, a); 14359 } 14360 14361 if (more && hardwareAccelerated) { 14362 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14363 // alpha animations should cause the child to recreate its display list 14364 invalidate(true); 14365 } 14366 } 14367 14368 mRecreateDisplayList = false; 14369 14370 return more; 14371 } 14372 14373 /** 14374 * Manually render this view (and all of its children) to the given Canvas. 14375 * The view must have already done a full layout before this function is 14376 * called. When implementing a view, implement 14377 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14378 * If you do need to override this method, call the superclass version. 14379 * 14380 * @param canvas The Canvas to which the View is rendered. 14381 */ 14382 public void draw(Canvas canvas) { 14383 if (mClipBounds != null) { 14384 canvas.clipRect(mClipBounds); 14385 } 14386 final int privateFlags = mPrivateFlags; 14387 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14388 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14389 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14390 14391 /* 14392 * Draw traversal performs several drawing steps which must be executed 14393 * in the appropriate order: 14394 * 14395 * 1. Draw the background 14396 * 2. If necessary, save the canvas' layers to prepare for fading 14397 * 3. Draw view's content 14398 * 4. Draw children 14399 * 5. If necessary, draw the fading edges and restore layers 14400 * 6. Draw decorations (scrollbars for instance) 14401 */ 14402 14403 // Step 1, draw the background, if needed 14404 int saveCount; 14405 14406 if (!dirtyOpaque) { 14407 final Drawable background = mBackground; 14408 if (background != null) { 14409 final int scrollX = mScrollX; 14410 final int scrollY = mScrollY; 14411 14412 if (mBackgroundSizeChanged) { 14413 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 14414 mBackgroundSizeChanged = false; 14415 } 14416 14417 if ((scrollX | scrollY) == 0) { 14418 background.draw(canvas); 14419 } else { 14420 canvas.translate(scrollX, scrollY); 14421 background.draw(canvas); 14422 canvas.translate(-scrollX, -scrollY); 14423 } 14424 } 14425 } 14426 14427 // skip step 2 & 5 if possible (common case) 14428 final int viewFlags = mViewFlags; 14429 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14430 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14431 if (!verticalEdges && !horizontalEdges) { 14432 // Step 3, draw the content 14433 if (!dirtyOpaque) onDraw(canvas); 14434 14435 // Step 4, draw the children 14436 dispatchDraw(canvas); 14437 14438 // Step 6, draw decorations (scrollbars) 14439 onDrawScrollBars(canvas); 14440 14441 if (mOverlay != null && !mOverlay.isEmpty()) { 14442 mOverlay.getOverlayView().dispatchDraw(canvas); 14443 } 14444 14445 // we're done... 14446 return; 14447 } 14448 14449 /* 14450 * Here we do the full fledged routine... 14451 * (this is an uncommon case where speed matters less, 14452 * this is why we repeat some of the tests that have been 14453 * done above) 14454 */ 14455 14456 boolean drawTop = false; 14457 boolean drawBottom = false; 14458 boolean drawLeft = false; 14459 boolean drawRight = false; 14460 14461 float topFadeStrength = 0.0f; 14462 float bottomFadeStrength = 0.0f; 14463 float leftFadeStrength = 0.0f; 14464 float rightFadeStrength = 0.0f; 14465 14466 // Step 2, save the canvas' layers 14467 int paddingLeft = mPaddingLeft; 14468 14469 final boolean offsetRequired = isPaddingOffsetRequired(); 14470 if (offsetRequired) { 14471 paddingLeft += getLeftPaddingOffset(); 14472 } 14473 14474 int left = mScrollX + paddingLeft; 14475 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14476 int top = mScrollY + getFadeTop(offsetRequired); 14477 int bottom = top + getFadeHeight(offsetRequired); 14478 14479 if (offsetRequired) { 14480 right += getRightPaddingOffset(); 14481 bottom += getBottomPaddingOffset(); 14482 } 14483 14484 final ScrollabilityCache scrollabilityCache = mScrollCache; 14485 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14486 int length = (int) fadeHeight; 14487 14488 // clip the fade length if top and bottom fades overlap 14489 // overlapping fades produce odd-looking artifacts 14490 if (verticalEdges && (top + length > bottom - length)) { 14491 length = (bottom - top) / 2; 14492 } 14493 14494 // also clip horizontal fades if necessary 14495 if (horizontalEdges && (left + length > right - length)) { 14496 length = (right - left) / 2; 14497 } 14498 14499 if (verticalEdges) { 14500 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14501 drawTop = topFadeStrength * fadeHeight > 1.0f; 14502 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14503 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14504 } 14505 14506 if (horizontalEdges) { 14507 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14508 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14509 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14510 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14511 } 14512 14513 saveCount = canvas.getSaveCount(); 14514 14515 int solidColor = getSolidColor(); 14516 if (solidColor == 0) { 14517 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14518 14519 if (drawTop) { 14520 canvas.saveLayer(left, top, right, top + length, null, flags); 14521 } 14522 14523 if (drawBottom) { 14524 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14525 } 14526 14527 if (drawLeft) { 14528 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14529 } 14530 14531 if (drawRight) { 14532 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14533 } 14534 } else { 14535 scrollabilityCache.setFadeColor(solidColor); 14536 } 14537 14538 // Step 3, draw the content 14539 if (!dirtyOpaque) onDraw(canvas); 14540 14541 // Step 4, draw the children 14542 dispatchDraw(canvas); 14543 14544 // Step 5, draw the fade effect and restore layers 14545 final Paint p = scrollabilityCache.paint; 14546 final Matrix matrix = scrollabilityCache.matrix; 14547 final Shader fade = scrollabilityCache.shader; 14548 14549 if (drawTop) { 14550 matrix.setScale(1, fadeHeight * topFadeStrength); 14551 matrix.postTranslate(left, top); 14552 fade.setLocalMatrix(matrix); 14553 canvas.drawRect(left, top, right, top + length, p); 14554 } 14555 14556 if (drawBottom) { 14557 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14558 matrix.postRotate(180); 14559 matrix.postTranslate(left, bottom); 14560 fade.setLocalMatrix(matrix); 14561 canvas.drawRect(left, bottom - length, right, bottom, p); 14562 } 14563 14564 if (drawLeft) { 14565 matrix.setScale(1, fadeHeight * leftFadeStrength); 14566 matrix.postRotate(-90); 14567 matrix.postTranslate(left, top); 14568 fade.setLocalMatrix(matrix); 14569 canvas.drawRect(left, top, left + length, bottom, p); 14570 } 14571 14572 if (drawRight) { 14573 matrix.setScale(1, fadeHeight * rightFadeStrength); 14574 matrix.postRotate(90); 14575 matrix.postTranslate(right, top); 14576 fade.setLocalMatrix(matrix); 14577 canvas.drawRect(right - length, top, right, bottom, p); 14578 } 14579 14580 canvas.restoreToCount(saveCount); 14581 14582 // Step 6, draw decorations (scrollbars) 14583 onDrawScrollBars(canvas); 14584 14585 if (mOverlay != null && !mOverlay.isEmpty()) { 14586 mOverlay.getOverlayView().dispatchDraw(canvas); 14587 } 14588 } 14589 14590 /** 14591 * Returns the overlay for this view, creating it if it does not yet exist. 14592 * Adding drawables to the overlay will cause them to be displayed whenever 14593 * the view itself is redrawn. Objects in the overlay should be actively 14594 * managed: remove them when they should not be displayed anymore. The 14595 * overlay will always have the same size as its host view. 14596 * 14597 * <p>Note: Overlays do not currently work correctly with {@link 14598 * SurfaceView} or {@link TextureView}; contents in overlays for these 14599 * types of views may not display correctly.</p> 14600 * 14601 * @return The ViewOverlay object for this view. 14602 * @see ViewOverlay 14603 */ 14604 public ViewOverlay getOverlay() { 14605 if (mOverlay == null) { 14606 mOverlay = new ViewOverlay(mContext, this); 14607 } 14608 return mOverlay; 14609 } 14610 14611 /** 14612 * Override this if your view is known to always be drawn on top of a solid color background, 14613 * and needs to draw fading edges. Returning a non-zero color enables the view system to 14614 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 14615 * should be set to 0xFF. 14616 * 14617 * @see #setVerticalFadingEdgeEnabled(boolean) 14618 * @see #setHorizontalFadingEdgeEnabled(boolean) 14619 * 14620 * @return The known solid color background for this view, or 0 if the color may vary 14621 */ 14622 @ViewDebug.ExportedProperty(category = "drawing") 14623 public int getSolidColor() { 14624 return 0; 14625 } 14626 14627 /** 14628 * Build a human readable string representation of the specified view flags. 14629 * 14630 * @param flags the view flags to convert to a string 14631 * @return a String representing the supplied flags 14632 */ 14633 private static String printFlags(int flags) { 14634 String output = ""; 14635 int numFlags = 0; 14636 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 14637 output += "TAKES_FOCUS"; 14638 numFlags++; 14639 } 14640 14641 switch (flags & VISIBILITY_MASK) { 14642 case INVISIBLE: 14643 if (numFlags > 0) { 14644 output += " "; 14645 } 14646 output += "INVISIBLE"; 14647 // USELESS HERE numFlags++; 14648 break; 14649 case GONE: 14650 if (numFlags > 0) { 14651 output += " "; 14652 } 14653 output += "GONE"; 14654 // USELESS HERE numFlags++; 14655 break; 14656 default: 14657 break; 14658 } 14659 return output; 14660 } 14661 14662 /** 14663 * Build a human readable string representation of the specified private 14664 * view flags. 14665 * 14666 * @param privateFlags the private view flags to convert to a string 14667 * @return a String representing the supplied flags 14668 */ 14669 private static String printPrivateFlags(int privateFlags) { 14670 String output = ""; 14671 int numFlags = 0; 14672 14673 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 14674 output += "WANTS_FOCUS"; 14675 numFlags++; 14676 } 14677 14678 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 14679 if (numFlags > 0) { 14680 output += " "; 14681 } 14682 output += "FOCUSED"; 14683 numFlags++; 14684 } 14685 14686 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 14687 if (numFlags > 0) { 14688 output += " "; 14689 } 14690 output += "SELECTED"; 14691 numFlags++; 14692 } 14693 14694 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 14695 if (numFlags > 0) { 14696 output += " "; 14697 } 14698 output += "IS_ROOT_NAMESPACE"; 14699 numFlags++; 14700 } 14701 14702 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 14703 if (numFlags > 0) { 14704 output += " "; 14705 } 14706 output += "HAS_BOUNDS"; 14707 numFlags++; 14708 } 14709 14710 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 14711 if (numFlags > 0) { 14712 output += " "; 14713 } 14714 output += "DRAWN"; 14715 // USELESS HERE numFlags++; 14716 } 14717 return output; 14718 } 14719 14720 /** 14721 * <p>Indicates whether or not this view's layout will be requested during 14722 * the next hierarchy layout pass.</p> 14723 * 14724 * @return true if the layout will be forced during next layout pass 14725 */ 14726 public boolean isLayoutRequested() { 14727 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 14728 } 14729 14730 /** 14731 * Return true if o is a ViewGroup that is laying out using optical bounds. 14732 * @hide 14733 */ 14734 public static boolean isLayoutModeOptical(Object o) { 14735 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 14736 } 14737 14738 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 14739 Insets parentInsets = mParent instanceof View ? 14740 ((View) mParent).getOpticalInsets() : Insets.NONE; 14741 Insets childInsets = getOpticalInsets(); 14742 return setFrame( 14743 left + parentInsets.left - childInsets.left, 14744 top + parentInsets.top - childInsets.top, 14745 right + parentInsets.left + childInsets.right, 14746 bottom + parentInsets.top + childInsets.bottom); 14747 } 14748 14749 /** 14750 * Assign a size and position to a view and all of its 14751 * descendants 14752 * 14753 * <p>This is the second phase of the layout mechanism. 14754 * (The first is measuring). In this phase, each parent calls 14755 * layout on all of its children to position them. 14756 * This is typically done using the child measurements 14757 * that were stored in the measure pass().</p> 14758 * 14759 * <p>Derived classes should not override this method. 14760 * Derived classes with children should override 14761 * onLayout. In that method, they should 14762 * call layout on each of their children.</p> 14763 * 14764 * @param l Left position, relative to parent 14765 * @param t Top position, relative to parent 14766 * @param r Right position, relative to parent 14767 * @param b Bottom position, relative to parent 14768 */ 14769 @SuppressWarnings({"unchecked"}) 14770 public void layout(int l, int t, int r, int b) { 14771 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 14772 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 14773 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 14774 } 14775 14776 int oldL = mLeft; 14777 int oldT = mTop; 14778 int oldB = mBottom; 14779 int oldR = mRight; 14780 14781 boolean changed = isLayoutModeOptical(mParent) ? 14782 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 14783 14784 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 14785 onLayout(changed, l, t, r, b); 14786 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 14787 14788 ListenerInfo li = mListenerInfo; 14789 if (li != null && li.mOnLayoutChangeListeners != null) { 14790 ArrayList<OnLayoutChangeListener> listenersCopy = 14791 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 14792 int numListeners = listenersCopy.size(); 14793 for (int i = 0; i < numListeners; ++i) { 14794 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 14795 } 14796 } 14797 } 14798 14799 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 14800 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 14801 } 14802 14803 /** 14804 * Called from layout when this view should 14805 * assign a size and position to each of its children. 14806 * 14807 * Derived classes with children should override 14808 * this method and call layout on each of 14809 * their children. 14810 * @param changed This is a new size or position for this view 14811 * @param left Left position, relative to parent 14812 * @param top Top position, relative to parent 14813 * @param right Right position, relative to parent 14814 * @param bottom Bottom position, relative to parent 14815 */ 14816 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 14817 } 14818 14819 /** 14820 * Assign a size and position to this view. 14821 * 14822 * This is called from layout. 14823 * 14824 * @param left Left position, relative to parent 14825 * @param top Top position, relative to parent 14826 * @param right Right position, relative to parent 14827 * @param bottom Bottom position, relative to parent 14828 * @return true if the new size and position are different than the 14829 * previous ones 14830 * {@hide} 14831 */ 14832 protected boolean setFrame(int left, int top, int right, int bottom) { 14833 boolean changed = false; 14834 14835 if (DBG) { 14836 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 14837 + right + "," + bottom + ")"); 14838 } 14839 14840 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 14841 changed = true; 14842 14843 // Remember our drawn bit 14844 int drawn = mPrivateFlags & PFLAG_DRAWN; 14845 14846 int oldWidth = mRight - mLeft; 14847 int oldHeight = mBottom - mTop; 14848 int newWidth = right - left; 14849 int newHeight = bottom - top; 14850 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 14851 14852 // Invalidate our old position 14853 invalidate(sizeChanged); 14854 14855 mLeft = left; 14856 mTop = top; 14857 mRight = right; 14858 mBottom = bottom; 14859 if (mDisplayList != null) { 14860 mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 14861 } 14862 14863 mPrivateFlags |= PFLAG_HAS_BOUNDS; 14864 14865 14866 if (sizeChanged) { 14867 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 14868 // A change in dimension means an auto-centered pivot point changes, too 14869 if (mTransformationInfo != null) { 14870 mTransformationInfo.mMatrixDirty = true; 14871 } 14872 } 14873 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 14874 } 14875 14876 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 14877 // If we are visible, force the DRAWN bit to on so that 14878 // this invalidate will go through (at least to our parent). 14879 // This is because someone may have invalidated this view 14880 // before this call to setFrame came in, thereby clearing 14881 // the DRAWN bit. 14882 mPrivateFlags |= PFLAG_DRAWN; 14883 invalidate(sizeChanged); 14884 // parent display list may need to be recreated based on a change in the bounds 14885 // of any child 14886 invalidateParentCaches(); 14887 } 14888 14889 // Reset drawn bit to original value (invalidate turns it off) 14890 mPrivateFlags |= drawn; 14891 14892 mBackgroundSizeChanged = true; 14893 14894 notifySubtreeAccessibilityStateChangedIfNeeded(); 14895 } 14896 return changed; 14897 } 14898 14899 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 14900 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 14901 if (mOverlay != null) { 14902 mOverlay.getOverlayView().setRight(newWidth); 14903 mOverlay.getOverlayView().setBottom(newHeight); 14904 } 14905 } 14906 14907 /** 14908 * Finalize inflating a view from XML. This is called as the last phase 14909 * of inflation, after all child views have been added. 14910 * 14911 * <p>Even if the subclass overrides onFinishInflate, they should always be 14912 * sure to call the super method, so that we get called. 14913 */ 14914 protected void onFinishInflate() { 14915 } 14916 14917 /** 14918 * Returns the resources associated with this view. 14919 * 14920 * @return Resources object. 14921 */ 14922 public Resources getResources() { 14923 return mResources; 14924 } 14925 14926 /** 14927 * Invalidates the specified Drawable. 14928 * 14929 * @param drawable the drawable to invalidate 14930 */ 14931 public void invalidateDrawable(Drawable drawable) { 14932 if (verifyDrawable(drawable)) { 14933 final Rect dirty = drawable.getBounds(); 14934 final int scrollX = mScrollX; 14935 final int scrollY = mScrollY; 14936 14937 invalidate(dirty.left + scrollX, dirty.top + scrollY, 14938 dirty.right + scrollX, dirty.bottom + scrollY); 14939 } 14940 } 14941 14942 /** 14943 * Schedules an action on a drawable to occur at a specified time. 14944 * 14945 * @param who the recipient of the action 14946 * @param what the action to run on the drawable 14947 * @param when the time at which the action must occur. Uses the 14948 * {@link SystemClock#uptimeMillis} timebase. 14949 */ 14950 public void scheduleDrawable(Drawable who, Runnable what, long when) { 14951 if (verifyDrawable(who) && what != null) { 14952 final long delay = when - SystemClock.uptimeMillis(); 14953 if (mAttachInfo != null) { 14954 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 14955 Choreographer.CALLBACK_ANIMATION, what, who, 14956 Choreographer.subtractFrameDelay(delay)); 14957 } else { 14958 ViewRootImpl.getRunQueue().postDelayed(what, delay); 14959 } 14960 } 14961 } 14962 14963 /** 14964 * Cancels a scheduled action on a drawable. 14965 * 14966 * @param who the recipient of the action 14967 * @param what the action to cancel 14968 */ 14969 public void unscheduleDrawable(Drawable who, Runnable what) { 14970 if (verifyDrawable(who) && what != null) { 14971 if (mAttachInfo != null) { 14972 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14973 Choreographer.CALLBACK_ANIMATION, what, who); 14974 } else { 14975 ViewRootImpl.getRunQueue().removeCallbacks(what); 14976 } 14977 } 14978 } 14979 14980 /** 14981 * Unschedule any events associated with the given Drawable. This can be 14982 * used when selecting a new Drawable into a view, so that the previous 14983 * one is completely unscheduled. 14984 * 14985 * @param who The Drawable to unschedule. 14986 * 14987 * @see #drawableStateChanged 14988 */ 14989 public void unscheduleDrawable(Drawable who) { 14990 if (mAttachInfo != null && who != null) { 14991 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14992 Choreographer.CALLBACK_ANIMATION, null, who); 14993 } 14994 } 14995 14996 /** 14997 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 14998 * that the View directionality can and will be resolved before its Drawables. 14999 * 15000 * Will call {@link View#onResolveDrawables} when resolution is done. 15001 * 15002 * @hide 15003 */ 15004 protected void resolveDrawables() { 15005 // Drawables resolution may need to happen before resolving the layout direction (which is 15006 // done only during the measure() call). 15007 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15008 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15009 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15010 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15011 // direction to be resolved as its resolved value will be the same as its raw value. 15012 if (!isLayoutDirectionResolved() && 15013 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15014 return; 15015 } 15016 15017 final int layoutDirection = isLayoutDirectionResolved() ? 15018 getLayoutDirection() : getRawLayoutDirection(); 15019 15020 if (mBackground != null) { 15021 mBackground.setLayoutDirection(layoutDirection); 15022 } 15023 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15024 onResolveDrawables(layoutDirection); 15025 } 15026 15027 /** 15028 * Called when layout direction has been resolved. 15029 * 15030 * The default implementation does nothing. 15031 * 15032 * @param layoutDirection The resolved layout direction. 15033 * 15034 * @see #LAYOUT_DIRECTION_LTR 15035 * @see #LAYOUT_DIRECTION_RTL 15036 * 15037 * @hide 15038 */ 15039 public void onResolveDrawables(int layoutDirection) { 15040 } 15041 15042 /** 15043 * @hide 15044 */ 15045 protected void resetResolvedDrawables() { 15046 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15047 } 15048 15049 private boolean isDrawablesResolved() { 15050 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15051 } 15052 15053 /** 15054 * If your view subclass is displaying its own Drawable objects, it should 15055 * override this function and return true for any Drawable it is 15056 * displaying. This allows animations for those drawables to be 15057 * scheduled. 15058 * 15059 * <p>Be sure to call through to the super class when overriding this 15060 * function. 15061 * 15062 * @param who The Drawable to verify. Return true if it is one you are 15063 * displaying, else return the result of calling through to the 15064 * super class. 15065 * 15066 * @return boolean If true than the Drawable is being displayed in the 15067 * view; else false and it is not allowed to animate. 15068 * 15069 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15070 * @see #drawableStateChanged() 15071 */ 15072 protected boolean verifyDrawable(Drawable who) { 15073 return who == mBackground; 15074 } 15075 15076 /** 15077 * This function is called whenever the state of the view changes in such 15078 * a way that it impacts the state of drawables being shown. 15079 * 15080 * <p>Be sure to call through to the superclass when overriding this 15081 * function. 15082 * 15083 * @see Drawable#setState(int[]) 15084 */ 15085 protected void drawableStateChanged() { 15086 Drawable d = mBackground; 15087 if (d != null && d.isStateful()) { 15088 d.setState(getDrawableState()); 15089 } 15090 } 15091 15092 /** 15093 * Call this to force a view to update its drawable state. This will cause 15094 * drawableStateChanged to be called on this view. Views that are interested 15095 * in the new state should call getDrawableState. 15096 * 15097 * @see #drawableStateChanged 15098 * @see #getDrawableState 15099 */ 15100 public void refreshDrawableState() { 15101 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15102 drawableStateChanged(); 15103 15104 ViewParent parent = mParent; 15105 if (parent != null) { 15106 parent.childDrawableStateChanged(this); 15107 } 15108 } 15109 15110 /** 15111 * Return an array of resource IDs of the drawable states representing the 15112 * current state of the view. 15113 * 15114 * @return The current drawable state 15115 * 15116 * @see Drawable#setState(int[]) 15117 * @see #drawableStateChanged() 15118 * @see #onCreateDrawableState(int) 15119 */ 15120 public final int[] getDrawableState() { 15121 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15122 return mDrawableState; 15123 } else { 15124 mDrawableState = onCreateDrawableState(0); 15125 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15126 return mDrawableState; 15127 } 15128 } 15129 15130 /** 15131 * Generate the new {@link android.graphics.drawable.Drawable} state for 15132 * this view. This is called by the view 15133 * system when the cached Drawable state is determined to be invalid. To 15134 * retrieve the current state, you should use {@link #getDrawableState}. 15135 * 15136 * @param extraSpace if non-zero, this is the number of extra entries you 15137 * would like in the returned array in which you can place your own 15138 * states. 15139 * 15140 * @return Returns an array holding the current {@link Drawable} state of 15141 * the view. 15142 * 15143 * @see #mergeDrawableStates(int[], int[]) 15144 */ 15145 protected int[] onCreateDrawableState(int extraSpace) { 15146 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15147 mParent instanceof View) { 15148 return ((View) mParent).onCreateDrawableState(extraSpace); 15149 } 15150 15151 int[] drawableState; 15152 15153 int privateFlags = mPrivateFlags; 15154 15155 int viewStateIndex = 0; 15156 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15157 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15158 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15159 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15160 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15161 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15162 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15163 HardwareRenderer.isAvailable()) { 15164 // This is set if HW acceleration is requested, even if the current 15165 // process doesn't allow it. This is just to allow app preview 15166 // windows to better match their app. 15167 viewStateIndex |= VIEW_STATE_ACCELERATED; 15168 } 15169 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15170 15171 final int privateFlags2 = mPrivateFlags2; 15172 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15173 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15174 15175 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15176 15177 //noinspection ConstantIfStatement 15178 if (false) { 15179 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15180 Log.i("View", toString() 15181 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15182 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15183 + " fo=" + hasFocus() 15184 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15185 + " wf=" + hasWindowFocus() 15186 + ": " + Arrays.toString(drawableState)); 15187 } 15188 15189 if (extraSpace == 0) { 15190 return drawableState; 15191 } 15192 15193 final int[] fullState; 15194 if (drawableState != null) { 15195 fullState = new int[drawableState.length + extraSpace]; 15196 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15197 } else { 15198 fullState = new int[extraSpace]; 15199 } 15200 15201 return fullState; 15202 } 15203 15204 /** 15205 * Merge your own state values in <var>additionalState</var> into the base 15206 * state values <var>baseState</var> that were returned by 15207 * {@link #onCreateDrawableState(int)}. 15208 * 15209 * @param baseState The base state values returned by 15210 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15211 * own additional state values. 15212 * 15213 * @param additionalState The additional state values you would like 15214 * added to <var>baseState</var>; this array is not modified. 15215 * 15216 * @return As a convenience, the <var>baseState</var> array you originally 15217 * passed into the function is returned. 15218 * 15219 * @see #onCreateDrawableState(int) 15220 */ 15221 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15222 final int N = baseState.length; 15223 int i = N - 1; 15224 while (i >= 0 && baseState[i] == 0) { 15225 i--; 15226 } 15227 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15228 return baseState; 15229 } 15230 15231 /** 15232 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15233 * on all Drawable objects associated with this view. 15234 */ 15235 public void jumpDrawablesToCurrentState() { 15236 if (mBackground != null) { 15237 mBackground.jumpToCurrentState(); 15238 } 15239 } 15240 15241 /** 15242 * Sets the background color for this view. 15243 * @param color the color of the background 15244 */ 15245 @RemotableViewMethod 15246 public void setBackgroundColor(int color) { 15247 if (mBackground instanceof ColorDrawable) { 15248 ((ColorDrawable) mBackground.mutate()).setColor(color); 15249 computeOpaqueFlags(); 15250 mBackgroundResource = 0; 15251 } else { 15252 setBackground(new ColorDrawable(color)); 15253 } 15254 } 15255 15256 /** 15257 * Set the background to a given resource. The resource should refer to 15258 * a Drawable object or 0 to remove the background. 15259 * @param resid The identifier of the resource. 15260 * 15261 * @attr ref android.R.styleable#View_background 15262 */ 15263 @RemotableViewMethod 15264 public void setBackgroundResource(int resid) { 15265 if (resid != 0 && resid == mBackgroundResource) { 15266 return; 15267 } 15268 15269 Drawable d= null; 15270 if (resid != 0) { 15271 d = mResources.getDrawable(resid); 15272 } 15273 setBackground(d); 15274 15275 mBackgroundResource = resid; 15276 } 15277 15278 /** 15279 * Set the background to a given Drawable, or remove the background. If the 15280 * background has padding, this View's padding is set to the background's 15281 * padding. However, when a background is removed, this View's padding isn't 15282 * touched. If setting the padding is desired, please use 15283 * {@link #setPadding(int, int, int, int)}. 15284 * 15285 * @param background The Drawable to use as the background, or null to remove the 15286 * background 15287 */ 15288 public void setBackground(Drawable background) { 15289 //noinspection deprecation 15290 setBackgroundDrawable(background); 15291 } 15292 15293 /** 15294 * @deprecated use {@link #setBackground(Drawable)} instead 15295 */ 15296 @Deprecated 15297 public void setBackgroundDrawable(Drawable background) { 15298 computeOpaqueFlags(); 15299 15300 if (background == mBackground) { 15301 return; 15302 } 15303 15304 boolean requestLayout = false; 15305 15306 mBackgroundResource = 0; 15307 15308 /* 15309 * Regardless of whether we're setting a new background or not, we want 15310 * to clear the previous drawable. 15311 */ 15312 if (mBackground != null) { 15313 mBackground.setCallback(null); 15314 unscheduleDrawable(mBackground); 15315 } 15316 15317 if (background != null) { 15318 Rect padding = sThreadLocal.get(); 15319 if (padding == null) { 15320 padding = new Rect(); 15321 sThreadLocal.set(padding); 15322 } 15323 resetResolvedDrawables(); 15324 background.setLayoutDirection(getLayoutDirection()); 15325 if (background.getPadding(padding)) { 15326 resetResolvedPadding(); 15327 switch (background.getLayoutDirection()) { 15328 case LAYOUT_DIRECTION_RTL: 15329 mUserPaddingLeftInitial = padding.right; 15330 mUserPaddingRightInitial = padding.left; 15331 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15332 break; 15333 case LAYOUT_DIRECTION_LTR: 15334 default: 15335 mUserPaddingLeftInitial = padding.left; 15336 mUserPaddingRightInitial = padding.right; 15337 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15338 } 15339 } 15340 15341 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15342 // if it has a different minimum size, we should layout again 15343 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 15344 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15345 requestLayout = true; 15346 } 15347 15348 background.setCallback(this); 15349 if (background.isStateful()) { 15350 background.setState(getDrawableState()); 15351 } 15352 background.setVisible(getVisibility() == VISIBLE, false); 15353 mBackground = background; 15354 15355 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15356 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15357 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15358 requestLayout = true; 15359 } 15360 } else { 15361 /* Remove the background */ 15362 mBackground = null; 15363 15364 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15365 /* 15366 * This view ONLY drew the background before and we're removing 15367 * the background, so now it won't draw anything 15368 * (hence we SKIP_DRAW) 15369 */ 15370 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15371 mPrivateFlags |= PFLAG_SKIP_DRAW; 15372 } 15373 15374 /* 15375 * When the background is set, we try to apply its padding to this 15376 * View. When the background is removed, we don't touch this View's 15377 * padding. This is noted in the Javadocs. Hence, we don't need to 15378 * requestLayout(), the invalidate() below is sufficient. 15379 */ 15380 15381 // The old background's minimum size could have affected this 15382 // View's layout, so let's requestLayout 15383 requestLayout = true; 15384 } 15385 15386 computeOpaqueFlags(); 15387 15388 if (requestLayout) { 15389 requestLayout(); 15390 } 15391 15392 mBackgroundSizeChanged = true; 15393 invalidate(true); 15394 } 15395 15396 /** 15397 * Gets the background drawable 15398 * 15399 * @return The drawable used as the background for this view, if any. 15400 * 15401 * @see #setBackground(Drawable) 15402 * 15403 * @attr ref android.R.styleable#View_background 15404 */ 15405 public Drawable getBackground() { 15406 return mBackground; 15407 } 15408 15409 /** 15410 * Sets the padding. The view may add on the space required to display 15411 * the scrollbars, depending on the style and visibility of the scrollbars. 15412 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15413 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 15414 * from the values set in this call. 15415 * 15416 * @attr ref android.R.styleable#View_padding 15417 * @attr ref android.R.styleable#View_paddingBottom 15418 * @attr ref android.R.styleable#View_paddingLeft 15419 * @attr ref android.R.styleable#View_paddingRight 15420 * @attr ref android.R.styleable#View_paddingTop 15421 * @param left the left padding in pixels 15422 * @param top the top padding in pixels 15423 * @param right the right padding in pixels 15424 * @param bottom the bottom padding in pixels 15425 */ 15426 public void setPadding(int left, int top, int right, int bottom) { 15427 resetResolvedPadding(); 15428 15429 mUserPaddingStart = UNDEFINED_PADDING; 15430 mUserPaddingEnd = UNDEFINED_PADDING; 15431 15432 mUserPaddingLeftInitial = left; 15433 mUserPaddingRightInitial = right; 15434 15435 internalSetPadding(left, top, right, bottom); 15436 } 15437 15438 /** 15439 * @hide 15440 */ 15441 protected void internalSetPadding(int left, int top, int right, int bottom) { 15442 mUserPaddingLeft = left; 15443 mUserPaddingRight = right; 15444 mUserPaddingBottom = bottom; 15445 15446 final int viewFlags = mViewFlags; 15447 boolean changed = false; 15448 15449 // Common case is there are no scroll bars. 15450 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 15451 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 15452 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 15453 ? 0 : getVerticalScrollbarWidth(); 15454 switch (mVerticalScrollbarPosition) { 15455 case SCROLLBAR_POSITION_DEFAULT: 15456 if (isLayoutRtl()) { 15457 left += offset; 15458 } else { 15459 right += offset; 15460 } 15461 break; 15462 case SCROLLBAR_POSITION_RIGHT: 15463 right += offset; 15464 break; 15465 case SCROLLBAR_POSITION_LEFT: 15466 left += offset; 15467 break; 15468 } 15469 } 15470 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 15471 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 15472 ? 0 : getHorizontalScrollbarHeight(); 15473 } 15474 } 15475 15476 if (mPaddingLeft != left) { 15477 changed = true; 15478 mPaddingLeft = left; 15479 } 15480 if (mPaddingTop != top) { 15481 changed = true; 15482 mPaddingTop = top; 15483 } 15484 if (mPaddingRight != right) { 15485 changed = true; 15486 mPaddingRight = right; 15487 } 15488 if (mPaddingBottom != bottom) { 15489 changed = true; 15490 mPaddingBottom = bottom; 15491 } 15492 15493 if (changed) { 15494 requestLayout(); 15495 } 15496 } 15497 15498 /** 15499 * Sets the relative padding. The view may add on the space required to display 15500 * the scrollbars, depending on the style and visibility of the scrollbars. 15501 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 15502 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 15503 * from the values set in this call. 15504 * 15505 * @attr ref android.R.styleable#View_padding 15506 * @attr ref android.R.styleable#View_paddingBottom 15507 * @attr ref android.R.styleable#View_paddingStart 15508 * @attr ref android.R.styleable#View_paddingEnd 15509 * @attr ref android.R.styleable#View_paddingTop 15510 * @param start the start padding in pixels 15511 * @param top the top padding in pixels 15512 * @param end the end padding in pixels 15513 * @param bottom the bottom padding in pixels 15514 */ 15515 public void setPaddingRelative(int start, int top, int end, int bottom) { 15516 resetResolvedPadding(); 15517 15518 mUserPaddingStart = start; 15519 mUserPaddingEnd = end; 15520 15521 switch(getLayoutDirection()) { 15522 case LAYOUT_DIRECTION_RTL: 15523 mUserPaddingLeftInitial = end; 15524 mUserPaddingRightInitial = start; 15525 internalSetPadding(end, top, start, bottom); 15526 break; 15527 case LAYOUT_DIRECTION_LTR: 15528 default: 15529 mUserPaddingLeftInitial = start; 15530 mUserPaddingRightInitial = end; 15531 internalSetPadding(start, top, end, bottom); 15532 } 15533 } 15534 15535 /** 15536 * Returns the top padding of this view. 15537 * 15538 * @return the top padding in pixels 15539 */ 15540 public int getPaddingTop() { 15541 return mPaddingTop; 15542 } 15543 15544 /** 15545 * Returns the bottom padding of this view. If there are inset and enabled 15546 * scrollbars, this value may include the space required to display the 15547 * scrollbars as well. 15548 * 15549 * @return the bottom padding in pixels 15550 */ 15551 public int getPaddingBottom() { 15552 return mPaddingBottom; 15553 } 15554 15555 /** 15556 * Returns the left padding of this view. If there are inset and enabled 15557 * scrollbars, this value may include the space required to display the 15558 * scrollbars as well. 15559 * 15560 * @return the left padding in pixels 15561 */ 15562 public int getPaddingLeft() { 15563 if (!isPaddingResolved()) { 15564 resolvePadding(); 15565 } 15566 return mPaddingLeft; 15567 } 15568 15569 /** 15570 * Returns the start padding of this view depending on its resolved layout direction. 15571 * If there are inset and enabled scrollbars, this value may include the space 15572 * required to display the scrollbars as well. 15573 * 15574 * @return the start padding in pixels 15575 */ 15576 public int getPaddingStart() { 15577 if (!isPaddingResolved()) { 15578 resolvePadding(); 15579 } 15580 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 15581 mPaddingRight : mPaddingLeft; 15582 } 15583 15584 /** 15585 * Returns the right padding of this view. If there are inset and enabled 15586 * scrollbars, this value may include the space required to display the 15587 * scrollbars as well. 15588 * 15589 * @return the right padding in pixels 15590 */ 15591 public int getPaddingRight() { 15592 if (!isPaddingResolved()) { 15593 resolvePadding(); 15594 } 15595 return mPaddingRight; 15596 } 15597 15598 /** 15599 * Returns the end padding of this view depending on its resolved layout direction. 15600 * If there are inset and enabled scrollbars, this value may include the space 15601 * required to display the scrollbars as well. 15602 * 15603 * @return the end padding in pixels 15604 */ 15605 public int getPaddingEnd() { 15606 if (!isPaddingResolved()) { 15607 resolvePadding(); 15608 } 15609 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 15610 mPaddingLeft : mPaddingRight; 15611 } 15612 15613 /** 15614 * Return if the padding as been set thru relative values 15615 * {@link #setPaddingRelative(int, int, int, int)} or thru 15616 * @attr ref android.R.styleable#View_paddingStart or 15617 * @attr ref android.R.styleable#View_paddingEnd 15618 * 15619 * @return true if the padding is relative or false if it is not. 15620 */ 15621 public boolean isPaddingRelative() { 15622 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 15623 } 15624 15625 Insets computeOpticalInsets() { 15626 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 15627 } 15628 15629 /** 15630 * @hide 15631 */ 15632 public void resetPaddingToInitialValues() { 15633 if (isRtlCompatibilityMode()) { 15634 mPaddingLeft = mUserPaddingLeftInitial; 15635 mPaddingRight = mUserPaddingRightInitial; 15636 return; 15637 } 15638 if (isLayoutRtl()) { 15639 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 15640 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 15641 } else { 15642 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 15643 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 15644 } 15645 } 15646 15647 /** 15648 * @hide 15649 */ 15650 public Insets getOpticalInsets() { 15651 if (mLayoutInsets == null) { 15652 mLayoutInsets = computeOpticalInsets(); 15653 } 15654 return mLayoutInsets; 15655 } 15656 15657 /** 15658 * Changes the selection state of this view. A view can be selected or not. 15659 * Note that selection is not the same as focus. Views are typically 15660 * selected in the context of an AdapterView like ListView or GridView; 15661 * the selected view is the view that is highlighted. 15662 * 15663 * @param selected true if the view must be selected, false otherwise 15664 */ 15665 public void setSelected(boolean selected) { 15666 //noinspection DoubleNegation 15667 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 15668 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 15669 if (!selected) resetPressedState(); 15670 invalidate(true); 15671 refreshDrawableState(); 15672 dispatchSetSelected(selected); 15673 notifyViewAccessibilityStateChangedIfNeeded( 15674 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 15675 } 15676 } 15677 15678 /** 15679 * Dispatch setSelected to all of this View's children. 15680 * 15681 * @see #setSelected(boolean) 15682 * 15683 * @param selected The new selected state 15684 */ 15685 protected void dispatchSetSelected(boolean selected) { 15686 } 15687 15688 /** 15689 * Indicates the selection state of this view. 15690 * 15691 * @return true if the view is selected, false otherwise 15692 */ 15693 @ViewDebug.ExportedProperty 15694 public boolean isSelected() { 15695 return (mPrivateFlags & PFLAG_SELECTED) != 0; 15696 } 15697 15698 /** 15699 * Changes the activated state of this view. A view can be activated or not. 15700 * Note that activation is not the same as selection. Selection is 15701 * a transient property, representing the view (hierarchy) the user is 15702 * currently interacting with. Activation is a longer-term state that the 15703 * user can move views in and out of. For example, in a list view with 15704 * single or multiple selection enabled, the views in the current selection 15705 * set are activated. (Um, yeah, we are deeply sorry about the terminology 15706 * here.) The activated state is propagated down to children of the view it 15707 * is set on. 15708 * 15709 * @param activated true if the view must be activated, false otherwise 15710 */ 15711 public void setActivated(boolean activated) { 15712 //noinspection DoubleNegation 15713 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 15714 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 15715 invalidate(true); 15716 refreshDrawableState(); 15717 dispatchSetActivated(activated); 15718 } 15719 } 15720 15721 /** 15722 * Dispatch setActivated to all of this View's children. 15723 * 15724 * @see #setActivated(boolean) 15725 * 15726 * @param activated The new activated state 15727 */ 15728 protected void dispatchSetActivated(boolean activated) { 15729 } 15730 15731 /** 15732 * Indicates the activation state of this view. 15733 * 15734 * @return true if the view is activated, false otherwise 15735 */ 15736 @ViewDebug.ExportedProperty 15737 public boolean isActivated() { 15738 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 15739 } 15740 15741 /** 15742 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 15743 * observer can be used to get notifications when global events, like 15744 * layout, happen. 15745 * 15746 * The returned ViewTreeObserver observer is not guaranteed to remain 15747 * valid for the lifetime of this View. If the caller of this method keeps 15748 * a long-lived reference to ViewTreeObserver, it should always check for 15749 * the return value of {@link ViewTreeObserver#isAlive()}. 15750 * 15751 * @return The ViewTreeObserver for this view's hierarchy. 15752 */ 15753 public ViewTreeObserver getViewTreeObserver() { 15754 if (mAttachInfo != null) { 15755 return mAttachInfo.mTreeObserver; 15756 } 15757 if (mFloatingTreeObserver == null) { 15758 mFloatingTreeObserver = new ViewTreeObserver(); 15759 } 15760 return mFloatingTreeObserver; 15761 } 15762 15763 /** 15764 * <p>Finds the topmost view in the current view hierarchy.</p> 15765 * 15766 * @return the topmost view containing this view 15767 */ 15768 public View getRootView() { 15769 if (mAttachInfo != null) { 15770 final View v = mAttachInfo.mRootView; 15771 if (v != null) { 15772 return v; 15773 } 15774 } 15775 15776 View parent = this; 15777 15778 while (parent.mParent != null && parent.mParent instanceof View) { 15779 parent = (View) parent.mParent; 15780 } 15781 15782 return parent; 15783 } 15784 15785 /** 15786 * Transforms a motion event from view-local coordinates to on-screen 15787 * coordinates. 15788 * 15789 * @param ev the view-local motion event 15790 * @return false if the transformation could not be applied 15791 * @hide 15792 */ 15793 public boolean toGlobalMotionEvent(MotionEvent ev) { 15794 final AttachInfo info = mAttachInfo; 15795 if (info == null) { 15796 return false; 15797 } 15798 15799 transformMotionEventToGlobal(ev); 15800 ev.offsetLocation(info.mWindowLeft, info.mWindowTop); 15801 return true; 15802 } 15803 15804 /** 15805 * Transforms a motion event from on-screen coordinates to view-local 15806 * coordinates. 15807 * 15808 * @param ev the on-screen motion event 15809 * @return false if the transformation could not be applied 15810 * @hide 15811 */ 15812 public boolean toLocalMotionEvent(MotionEvent ev) { 15813 final AttachInfo info = mAttachInfo; 15814 if (info == null) { 15815 return false; 15816 } 15817 15818 ev.offsetLocation(-info.mWindowLeft, -info.mWindowTop); 15819 transformMotionEventToLocal(ev); 15820 return true; 15821 } 15822 15823 /** 15824 * Recursive helper method that applies transformations in post-order. 15825 * 15826 * @param ev the on-screen motion event 15827 */ 15828 private void transformMotionEventToLocal(MotionEvent ev) { 15829 final ViewParent parent = mParent; 15830 if (parent instanceof View) { 15831 final View vp = (View) parent; 15832 vp.transformMotionEventToLocal(ev); 15833 ev.offsetLocation(vp.mScrollX, vp.mScrollY); 15834 } else if (parent instanceof ViewRootImpl) { 15835 final ViewRootImpl vr = (ViewRootImpl) parent; 15836 ev.offsetLocation(0, vr.mCurScrollY); 15837 } 15838 15839 ev.offsetLocation(-mLeft, -mTop); 15840 15841 if (!hasIdentityMatrix()) { 15842 ev.transform(getInverseMatrix()); 15843 } 15844 } 15845 15846 /** 15847 * Recursive helper method that applies transformations in pre-order. 15848 * 15849 * @param ev the on-screen motion event 15850 */ 15851 private void transformMotionEventToGlobal(MotionEvent ev) { 15852 if (!hasIdentityMatrix()) { 15853 ev.transform(getMatrix()); 15854 } 15855 15856 ev.offsetLocation(mLeft, mTop); 15857 15858 final ViewParent parent = mParent; 15859 if (parent instanceof View) { 15860 final View vp = (View) parent; 15861 ev.offsetLocation(-vp.mScrollX, -vp.mScrollY); 15862 vp.transformMotionEventToGlobal(ev); 15863 } else if (parent instanceof ViewRootImpl) { 15864 final ViewRootImpl vr = (ViewRootImpl) parent; 15865 ev.offsetLocation(0, -vr.mCurScrollY); 15866 } 15867 } 15868 15869 /** 15870 * <p>Computes the coordinates of this view on the screen. The argument 15871 * must be an array of two integers. After the method returns, the array 15872 * contains the x and y location in that order.</p> 15873 * 15874 * @param location an array of two integers in which to hold the coordinates 15875 */ 15876 public void getLocationOnScreen(int[] location) { 15877 getLocationInWindow(location); 15878 15879 final AttachInfo info = mAttachInfo; 15880 if (info != null) { 15881 location[0] += info.mWindowLeft; 15882 location[1] += info.mWindowTop; 15883 } 15884 } 15885 15886 /** 15887 * <p>Computes the coordinates of this view in its window. The argument 15888 * must be an array of two integers. After the method returns, the array 15889 * contains the x and y location in that order.</p> 15890 * 15891 * @param location an array of two integers in which to hold the coordinates 15892 */ 15893 public void getLocationInWindow(int[] location) { 15894 if (location == null || location.length < 2) { 15895 throw new IllegalArgumentException("location must be an array of two integers"); 15896 } 15897 15898 if (mAttachInfo == null) { 15899 // When the view is not attached to a window, this method does not make sense 15900 location[0] = location[1] = 0; 15901 return; 15902 } 15903 15904 float[] position = mAttachInfo.mTmpTransformLocation; 15905 position[0] = position[1] = 0.0f; 15906 15907 if (!hasIdentityMatrix()) { 15908 getMatrix().mapPoints(position); 15909 } 15910 15911 position[0] += mLeft; 15912 position[1] += mTop; 15913 15914 ViewParent viewParent = mParent; 15915 while (viewParent instanceof View) { 15916 final View view = (View) viewParent; 15917 15918 position[0] -= view.mScrollX; 15919 position[1] -= view.mScrollY; 15920 15921 if (!view.hasIdentityMatrix()) { 15922 view.getMatrix().mapPoints(position); 15923 } 15924 15925 position[0] += view.mLeft; 15926 position[1] += view.mTop; 15927 15928 viewParent = view.mParent; 15929 } 15930 15931 if (viewParent instanceof ViewRootImpl) { 15932 // *cough* 15933 final ViewRootImpl vr = (ViewRootImpl) viewParent; 15934 position[1] -= vr.mCurScrollY; 15935 } 15936 15937 location[0] = (int) (position[0] + 0.5f); 15938 location[1] = (int) (position[1] + 0.5f); 15939 } 15940 15941 /** 15942 * {@hide} 15943 * @param id the id of the view to be found 15944 * @return the view of the specified id, null if cannot be found 15945 */ 15946 protected View findViewTraversal(int id) { 15947 if (id == mID) { 15948 return this; 15949 } 15950 return null; 15951 } 15952 15953 /** 15954 * {@hide} 15955 * @param tag the tag of the view to be found 15956 * @return the view of specified tag, null if cannot be found 15957 */ 15958 protected View findViewWithTagTraversal(Object tag) { 15959 if (tag != null && tag.equals(mTag)) { 15960 return this; 15961 } 15962 return null; 15963 } 15964 15965 /** 15966 * {@hide} 15967 * @param predicate The predicate to evaluate. 15968 * @param childToSkip If not null, ignores this child during the recursive traversal. 15969 * @return The first view that matches the predicate or null. 15970 */ 15971 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 15972 if (predicate.apply(this)) { 15973 return this; 15974 } 15975 return null; 15976 } 15977 15978 /** 15979 * Look for a child view with the given id. If this view has the given 15980 * id, return this view. 15981 * 15982 * @param id The id to search for. 15983 * @return The view that has the given id in the hierarchy or null 15984 */ 15985 public final View findViewById(int id) { 15986 if (id < 0) { 15987 return null; 15988 } 15989 return findViewTraversal(id); 15990 } 15991 15992 /** 15993 * Finds a view by its unuque and stable accessibility id. 15994 * 15995 * @param accessibilityId The searched accessibility id. 15996 * @return The found view. 15997 */ 15998 final View findViewByAccessibilityId(int accessibilityId) { 15999 if (accessibilityId < 0) { 16000 return null; 16001 } 16002 return findViewByAccessibilityIdTraversal(accessibilityId); 16003 } 16004 16005 /** 16006 * Performs the traversal to find a view by its unuque and stable accessibility id. 16007 * 16008 * <strong>Note:</strong>This method does not stop at the root namespace 16009 * boundary since the user can touch the screen at an arbitrary location 16010 * potentially crossing the root namespace bounday which will send an 16011 * accessibility event to accessibility services and they should be able 16012 * to obtain the event source. Also accessibility ids are guaranteed to be 16013 * unique in the window. 16014 * 16015 * @param accessibilityId The accessibility id. 16016 * @return The found view. 16017 * 16018 * @hide 16019 */ 16020 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16021 if (getAccessibilityViewId() == accessibilityId) { 16022 return this; 16023 } 16024 return null; 16025 } 16026 16027 /** 16028 * Look for a child view with the given tag. If this view has the given 16029 * tag, return this view. 16030 * 16031 * @param tag The tag to search for, using "tag.equals(getTag())". 16032 * @return The View that has the given tag in the hierarchy or null 16033 */ 16034 public final View findViewWithTag(Object tag) { 16035 if (tag == null) { 16036 return null; 16037 } 16038 return findViewWithTagTraversal(tag); 16039 } 16040 16041 /** 16042 * {@hide} 16043 * Look for a child view that matches the specified predicate. 16044 * If this view matches the predicate, return this view. 16045 * 16046 * @param predicate The predicate to evaluate. 16047 * @return The first view that matches the predicate or null. 16048 */ 16049 public final View findViewByPredicate(Predicate<View> predicate) { 16050 return findViewByPredicateTraversal(predicate, null); 16051 } 16052 16053 /** 16054 * {@hide} 16055 * Look for a child view that matches the specified predicate, 16056 * starting with the specified view and its descendents and then 16057 * recusively searching the ancestors and siblings of that view 16058 * until this view is reached. 16059 * 16060 * This method is useful in cases where the predicate does not match 16061 * a single unique view (perhaps multiple views use the same id) 16062 * and we are trying to find the view that is "closest" in scope to the 16063 * starting view. 16064 * 16065 * @param start The view to start from. 16066 * @param predicate The predicate to evaluate. 16067 * @return The first view that matches the predicate or null. 16068 */ 16069 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16070 View childToSkip = null; 16071 for (;;) { 16072 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16073 if (view != null || start == this) { 16074 return view; 16075 } 16076 16077 ViewParent parent = start.getParent(); 16078 if (parent == null || !(parent instanceof View)) { 16079 return null; 16080 } 16081 16082 childToSkip = start; 16083 start = (View) parent; 16084 } 16085 } 16086 16087 /** 16088 * Sets the identifier for this view. The identifier does not have to be 16089 * unique in this view's hierarchy. The identifier should be a positive 16090 * number. 16091 * 16092 * @see #NO_ID 16093 * @see #getId() 16094 * @see #findViewById(int) 16095 * 16096 * @param id a number used to identify the view 16097 * 16098 * @attr ref android.R.styleable#View_id 16099 */ 16100 public void setId(int id) { 16101 mID = id; 16102 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 16103 mID = generateViewId(); 16104 } 16105 } 16106 16107 /** 16108 * {@hide} 16109 * 16110 * @param isRoot true if the view belongs to the root namespace, false 16111 * otherwise 16112 */ 16113 public void setIsRootNamespace(boolean isRoot) { 16114 if (isRoot) { 16115 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 16116 } else { 16117 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 16118 } 16119 } 16120 16121 /** 16122 * {@hide} 16123 * 16124 * @return true if the view belongs to the root namespace, false otherwise 16125 */ 16126 public boolean isRootNamespace() { 16127 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 16128 } 16129 16130 /** 16131 * Returns this view's identifier. 16132 * 16133 * @return a positive integer used to identify the view or {@link #NO_ID} 16134 * if the view has no ID 16135 * 16136 * @see #setId(int) 16137 * @see #findViewById(int) 16138 * @attr ref android.R.styleable#View_id 16139 */ 16140 @ViewDebug.CapturedViewProperty 16141 public int getId() { 16142 return mID; 16143 } 16144 16145 /** 16146 * Returns this view's tag. 16147 * 16148 * @return the Object stored in this view as a tag 16149 * 16150 * @see #setTag(Object) 16151 * @see #getTag(int) 16152 */ 16153 @ViewDebug.ExportedProperty 16154 public Object getTag() { 16155 return mTag; 16156 } 16157 16158 /** 16159 * Sets the tag associated with this view. A tag can be used to mark 16160 * a view in its hierarchy and does not have to be unique within the 16161 * hierarchy. Tags can also be used to store data within a view without 16162 * resorting to another data structure. 16163 * 16164 * @param tag an Object to tag the view with 16165 * 16166 * @see #getTag() 16167 * @see #setTag(int, Object) 16168 */ 16169 public void setTag(final Object tag) { 16170 mTag = tag; 16171 } 16172 16173 /** 16174 * Returns the tag associated with this view and the specified key. 16175 * 16176 * @param key The key identifying the tag 16177 * 16178 * @return the Object stored in this view as a tag 16179 * 16180 * @see #setTag(int, Object) 16181 * @see #getTag() 16182 */ 16183 public Object getTag(int key) { 16184 if (mKeyedTags != null) return mKeyedTags.get(key); 16185 return null; 16186 } 16187 16188 /** 16189 * Sets a tag associated with this view and a key. A tag can be used 16190 * to mark a view in its hierarchy and does not have to be unique within 16191 * the hierarchy. Tags can also be used to store data within a view 16192 * without resorting to another data structure. 16193 * 16194 * The specified key should be an id declared in the resources of the 16195 * application to ensure it is unique (see the <a 16196 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 16197 * Keys identified as belonging to 16198 * the Android framework or not associated with any package will cause 16199 * an {@link IllegalArgumentException} to be thrown. 16200 * 16201 * @param key The key identifying the tag 16202 * @param tag An Object to tag the view with 16203 * 16204 * @throws IllegalArgumentException If they specified key is not valid 16205 * 16206 * @see #setTag(Object) 16207 * @see #getTag(int) 16208 */ 16209 public void setTag(int key, final Object tag) { 16210 // If the package id is 0x00 or 0x01, it's either an undefined package 16211 // or a framework id 16212 if ((key >>> 24) < 2) { 16213 throw new IllegalArgumentException("The key must be an application-specific " 16214 + "resource id."); 16215 } 16216 16217 setKeyedTag(key, tag); 16218 } 16219 16220 /** 16221 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16222 * framework id. 16223 * 16224 * @hide 16225 */ 16226 public void setTagInternal(int key, Object tag) { 16227 if ((key >>> 24) != 0x1) { 16228 throw new IllegalArgumentException("The key must be a framework-specific " 16229 + "resource id."); 16230 } 16231 16232 setKeyedTag(key, tag); 16233 } 16234 16235 private void setKeyedTag(int key, Object tag) { 16236 if (mKeyedTags == null) { 16237 mKeyedTags = new SparseArray<Object>(2); 16238 } 16239 16240 mKeyedTags.put(key, tag); 16241 } 16242 16243 /** 16244 * Prints information about this view in the log output, with the tag 16245 * {@link #VIEW_LOG_TAG}. 16246 * 16247 * @hide 16248 */ 16249 public void debug() { 16250 debug(0); 16251 } 16252 16253 /** 16254 * Prints information about this view in the log output, with the tag 16255 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16256 * indentation defined by the <code>depth</code>. 16257 * 16258 * @param depth the indentation level 16259 * 16260 * @hide 16261 */ 16262 protected void debug(int depth) { 16263 String output = debugIndent(depth - 1); 16264 16265 output += "+ " + this; 16266 int id = getId(); 16267 if (id != -1) { 16268 output += " (id=" + id + ")"; 16269 } 16270 Object tag = getTag(); 16271 if (tag != null) { 16272 output += " (tag=" + tag + ")"; 16273 } 16274 Log.d(VIEW_LOG_TAG, output); 16275 16276 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16277 output = debugIndent(depth) + " FOCUSED"; 16278 Log.d(VIEW_LOG_TAG, output); 16279 } 16280 16281 output = debugIndent(depth); 16282 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16283 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16284 + "} "; 16285 Log.d(VIEW_LOG_TAG, output); 16286 16287 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16288 || mPaddingBottom != 0) { 16289 output = debugIndent(depth); 16290 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16291 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16292 Log.d(VIEW_LOG_TAG, output); 16293 } 16294 16295 output = debugIndent(depth); 16296 output += "mMeasureWidth=" + mMeasuredWidth + 16297 " mMeasureHeight=" + mMeasuredHeight; 16298 Log.d(VIEW_LOG_TAG, output); 16299 16300 output = debugIndent(depth); 16301 if (mLayoutParams == null) { 16302 output += "BAD! no layout params"; 16303 } else { 16304 output = mLayoutParams.debug(output); 16305 } 16306 Log.d(VIEW_LOG_TAG, output); 16307 16308 output = debugIndent(depth); 16309 output += "flags={"; 16310 output += View.printFlags(mViewFlags); 16311 output += "}"; 16312 Log.d(VIEW_LOG_TAG, output); 16313 16314 output = debugIndent(depth); 16315 output += "privateFlags={"; 16316 output += View.printPrivateFlags(mPrivateFlags); 16317 output += "}"; 16318 Log.d(VIEW_LOG_TAG, output); 16319 } 16320 16321 /** 16322 * Creates a string of whitespaces used for indentation. 16323 * 16324 * @param depth the indentation level 16325 * @return a String containing (depth * 2 + 3) * 2 white spaces 16326 * 16327 * @hide 16328 */ 16329 protected static String debugIndent(int depth) { 16330 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16331 for (int i = 0; i < (depth * 2) + 3; i++) { 16332 spaces.append(' ').append(' '); 16333 } 16334 return spaces.toString(); 16335 } 16336 16337 /** 16338 * <p>Return the offset of the widget's text baseline from the widget's top 16339 * boundary. If this widget does not support baseline alignment, this 16340 * method returns -1. </p> 16341 * 16342 * @return the offset of the baseline within the widget's bounds or -1 16343 * if baseline alignment is not supported 16344 */ 16345 @ViewDebug.ExportedProperty(category = "layout") 16346 public int getBaseline() { 16347 return -1; 16348 } 16349 16350 /** 16351 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16352 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16353 * a layout pass. 16354 * 16355 * @return whether the view hierarchy is currently undergoing a layout pass 16356 */ 16357 public boolean isInLayout() { 16358 ViewRootImpl viewRoot = getViewRootImpl(); 16359 return (viewRoot != null && viewRoot.isInLayout()); 16360 } 16361 16362 /** 16363 * Call this when something has changed which has invalidated the 16364 * layout of this view. This will schedule a layout pass of the view 16365 * tree. This should not be called while the view hierarchy is currently in a layout 16366 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16367 * end of the current layout pass (and then layout will run again) or after the current 16368 * frame is drawn and the next layout occurs. 16369 * 16370 * <p>Subclasses which override this method should call the superclass method to 16371 * handle possible request-during-layout errors correctly.</p> 16372 */ 16373 public void requestLayout() { 16374 if (mMeasureCache != null) mMeasureCache.clear(); 16375 16376 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16377 // Only trigger request-during-layout logic if this is the view requesting it, 16378 // not the views in its parent hierarchy 16379 ViewRootImpl viewRoot = getViewRootImpl(); 16380 if (viewRoot != null && viewRoot.isInLayout()) { 16381 if (!viewRoot.requestLayoutDuringLayout(this)) { 16382 return; 16383 } 16384 } 16385 mAttachInfo.mViewRequestingLayout = this; 16386 } 16387 16388 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16389 mPrivateFlags |= PFLAG_INVALIDATED; 16390 16391 if (mParent != null && !mParent.isLayoutRequested()) { 16392 mParent.requestLayout(); 16393 } 16394 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 16395 mAttachInfo.mViewRequestingLayout = null; 16396 } 16397 } 16398 16399 /** 16400 * Forces this view to be laid out during the next layout pass. 16401 * This method does not call requestLayout() or forceLayout() 16402 * on the parent. 16403 */ 16404 public void forceLayout() { 16405 if (mMeasureCache != null) mMeasureCache.clear(); 16406 16407 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16408 mPrivateFlags |= PFLAG_INVALIDATED; 16409 } 16410 16411 /** 16412 * <p> 16413 * This is called to find out how big a view should be. The parent 16414 * supplies constraint information in the width and height parameters. 16415 * </p> 16416 * 16417 * <p> 16418 * The actual measurement work of a view is performed in 16419 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 16420 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 16421 * </p> 16422 * 16423 * 16424 * @param widthMeasureSpec Horizontal space requirements as imposed by the 16425 * parent 16426 * @param heightMeasureSpec Vertical space requirements as imposed by the 16427 * parent 16428 * 16429 * @see #onMeasure(int, int) 16430 */ 16431 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 16432 boolean optical = isLayoutModeOptical(this); 16433 if (optical != isLayoutModeOptical(mParent)) { 16434 Insets insets = getOpticalInsets(); 16435 int oWidth = insets.left + insets.right; 16436 int oHeight = insets.top + insets.bottom; 16437 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 16438 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 16439 } 16440 16441 // Suppress sign extension for the low bytes 16442 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 16443 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 16444 16445 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 16446 widthMeasureSpec != mOldWidthMeasureSpec || 16447 heightMeasureSpec != mOldHeightMeasureSpec) { 16448 16449 // first clears the measured dimension flag 16450 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 16451 16452 resolveRtlPropertiesIfNeeded(); 16453 16454 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 16455 mMeasureCache.indexOfKey(key); 16456 if (cacheIndex < 0 || sIgnoreMeasureCache) { 16457 // measure ourselves, this should set the measured dimension flag back 16458 onMeasure(widthMeasureSpec, heightMeasureSpec); 16459 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16460 } else { 16461 long value = mMeasureCache.valueAt(cacheIndex); 16462 // Casting a long to int drops the high 32 bits, no mask needed 16463 setMeasuredDimension((int) (value >> 32), (int) value); 16464 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16465 } 16466 16467 // flag not set, setMeasuredDimension() was not invoked, we raise 16468 // an exception to warn the developer 16469 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 16470 throw new IllegalStateException("onMeasure() did not set the" 16471 + " measured dimension by calling" 16472 + " setMeasuredDimension()"); 16473 } 16474 16475 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 16476 } 16477 16478 mOldWidthMeasureSpec = widthMeasureSpec; 16479 mOldHeightMeasureSpec = heightMeasureSpec; 16480 16481 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 16482 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 16483 } 16484 16485 /** 16486 * <p> 16487 * Measure the view and its content to determine the measured width and the 16488 * measured height. This method is invoked by {@link #measure(int, int)} and 16489 * should be overriden by subclasses to provide accurate and efficient 16490 * measurement of their contents. 16491 * </p> 16492 * 16493 * <p> 16494 * <strong>CONTRACT:</strong> When overriding this method, you 16495 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 16496 * measured width and height of this view. Failure to do so will trigger an 16497 * <code>IllegalStateException</code>, thrown by 16498 * {@link #measure(int, int)}. Calling the superclass' 16499 * {@link #onMeasure(int, int)} is a valid use. 16500 * </p> 16501 * 16502 * <p> 16503 * The base class implementation of measure defaults to the background size, 16504 * unless a larger size is allowed by the MeasureSpec. Subclasses should 16505 * override {@link #onMeasure(int, int)} to provide better measurements of 16506 * their content. 16507 * </p> 16508 * 16509 * <p> 16510 * If this method is overridden, it is the subclass's responsibility to make 16511 * sure the measured height and width are at least the view's minimum height 16512 * and width ({@link #getSuggestedMinimumHeight()} and 16513 * {@link #getSuggestedMinimumWidth()}). 16514 * </p> 16515 * 16516 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 16517 * The requirements are encoded with 16518 * {@link android.view.View.MeasureSpec}. 16519 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 16520 * The requirements are encoded with 16521 * {@link android.view.View.MeasureSpec}. 16522 * 16523 * @see #getMeasuredWidth() 16524 * @see #getMeasuredHeight() 16525 * @see #setMeasuredDimension(int, int) 16526 * @see #getSuggestedMinimumHeight() 16527 * @see #getSuggestedMinimumWidth() 16528 * @see android.view.View.MeasureSpec#getMode(int) 16529 * @see android.view.View.MeasureSpec#getSize(int) 16530 */ 16531 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 16532 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 16533 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 16534 } 16535 16536 /** 16537 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 16538 * measured width and measured height. Failing to do so will trigger an 16539 * exception at measurement time.</p> 16540 * 16541 * @param measuredWidth The measured width of this view. May be a complex 16542 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16543 * {@link #MEASURED_STATE_TOO_SMALL}. 16544 * @param measuredHeight The measured height of this view. May be a complex 16545 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16546 * {@link #MEASURED_STATE_TOO_SMALL}. 16547 */ 16548 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 16549 boolean optical = isLayoutModeOptical(this); 16550 if (optical != isLayoutModeOptical(mParent)) { 16551 Insets insets = getOpticalInsets(); 16552 int opticalWidth = insets.left + insets.right; 16553 int opticalHeight = insets.top + insets.bottom; 16554 16555 measuredWidth += optical ? opticalWidth : -opticalWidth; 16556 measuredHeight += optical ? opticalHeight : -opticalHeight; 16557 } 16558 mMeasuredWidth = measuredWidth; 16559 mMeasuredHeight = measuredHeight; 16560 16561 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 16562 } 16563 16564 /** 16565 * Merge two states as returned by {@link #getMeasuredState()}. 16566 * @param curState The current state as returned from a view or the result 16567 * of combining multiple views. 16568 * @param newState The new view state to combine. 16569 * @return Returns a new integer reflecting the combination of the two 16570 * states. 16571 */ 16572 public static int combineMeasuredStates(int curState, int newState) { 16573 return curState | newState; 16574 } 16575 16576 /** 16577 * Version of {@link #resolveSizeAndState(int, int, int)} 16578 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 16579 */ 16580 public static int resolveSize(int size, int measureSpec) { 16581 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 16582 } 16583 16584 /** 16585 * Utility to reconcile a desired size and state, with constraints imposed 16586 * by a MeasureSpec. Will take the desired size, unless a different size 16587 * is imposed by the constraints. The returned value is a compound integer, 16588 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 16589 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 16590 * size is smaller than the size the view wants to be. 16591 * 16592 * @param size How big the view wants to be 16593 * @param measureSpec Constraints imposed by the parent 16594 * @return Size information bit mask as defined by 16595 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 16596 */ 16597 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 16598 int result = size; 16599 int specMode = MeasureSpec.getMode(measureSpec); 16600 int specSize = MeasureSpec.getSize(measureSpec); 16601 switch (specMode) { 16602 case MeasureSpec.UNSPECIFIED: 16603 result = size; 16604 break; 16605 case MeasureSpec.AT_MOST: 16606 if (specSize < size) { 16607 result = specSize | MEASURED_STATE_TOO_SMALL; 16608 } else { 16609 result = size; 16610 } 16611 break; 16612 case MeasureSpec.EXACTLY: 16613 result = specSize; 16614 break; 16615 } 16616 return result | (childMeasuredState&MEASURED_STATE_MASK); 16617 } 16618 16619 /** 16620 * Utility to return a default size. Uses the supplied size if the 16621 * MeasureSpec imposed no constraints. Will get larger if allowed 16622 * by the MeasureSpec. 16623 * 16624 * @param size Default size for this view 16625 * @param measureSpec Constraints imposed by the parent 16626 * @return The size this view should be. 16627 */ 16628 public static int getDefaultSize(int size, int measureSpec) { 16629 int result = size; 16630 int specMode = MeasureSpec.getMode(measureSpec); 16631 int specSize = MeasureSpec.getSize(measureSpec); 16632 16633 switch (specMode) { 16634 case MeasureSpec.UNSPECIFIED: 16635 result = size; 16636 break; 16637 case MeasureSpec.AT_MOST: 16638 case MeasureSpec.EXACTLY: 16639 result = specSize; 16640 break; 16641 } 16642 return result; 16643 } 16644 16645 /** 16646 * Returns the suggested minimum height that the view should use. This 16647 * returns the maximum of the view's minimum height 16648 * and the background's minimum height 16649 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 16650 * <p> 16651 * When being used in {@link #onMeasure(int, int)}, the caller should still 16652 * ensure the returned height is within the requirements of the parent. 16653 * 16654 * @return The suggested minimum height of the view. 16655 */ 16656 protected int getSuggestedMinimumHeight() { 16657 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 16658 16659 } 16660 16661 /** 16662 * Returns the suggested minimum width that the view should use. This 16663 * returns the maximum of the view's minimum width) 16664 * and the background's minimum width 16665 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 16666 * <p> 16667 * When being used in {@link #onMeasure(int, int)}, the caller should still 16668 * ensure the returned width is within the requirements of the parent. 16669 * 16670 * @return The suggested minimum width of the view. 16671 */ 16672 protected int getSuggestedMinimumWidth() { 16673 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 16674 } 16675 16676 /** 16677 * Returns the minimum height of the view. 16678 * 16679 * @return the minimum height the view will try to be. 16680 * 16681 * @see #setMinimumHeight(int) 16682 * 16683 * @attr ref android.R.styleable#View_minHeight 16684 */ 16685 public int getMinimumHeight() { 16686 return mMinHeight; 16687 } 16688 16689 /** 16690 * Sets the minimum height of the view. It is not guaranteed the view will 16691 * be able to achieve this minimum height (for example, if its parent layout 16692 * constrains it with less available height). 16693 * 16694 * @param minHeight The minimum height the view will try to be. 16695 * 16696 * @see #getMinimumHeight() 16697 * 16698 * @attr ref android.R.styleable#View_minHeight 16699 */ 16700 public void setMinimumHeight(int minHeight) { 16701 mMinHeight = minHeight; 16702 requestLayout(); 16703 } 16704 16705 /** 16706 * Returns the minimum width of the view. 16707 * 16708 * @return the minimum width the view will try to be. 16709 * 16710 * @see #setMinimumWidth(int) 16711 * 16712 * @attr ref android.R.styleable#View_minWidth 16713 */ 16714 public int getMinimumWidth() { 16715 return mMinWidth; 16716 } 16717 16718 /** 16719 * Sets the minimum width of the view. It is not guaranteed the view will 16720 * be able to achieve this minimum width (for example, if its parent layout 16721 * constrains it with less available width). 16722 * 16723 * @param minWidth The minimum width the view will try to be. 16724 * 16725 * @see #getMinimumWidth() 16726 * 16727 * @attr ref android.R.styleable#View_minWidth 16728 */ 16729 public void setMinimumWidth(int minWidth) { 16730 mMinWidth = minWidth; 16731 requestLayout(); 16732 16733 } 16734 16735 /** 16736 * Get the animation currently associated with this view. 16737 * 16738 * @return The animation that is currently playing or 16739 * scheduled to play for this view. 16740 */ 16741 public Animation getAnimation() { 16742 return mCurrentAnimation; 16743 } 16744 16745 /** 16746 * Start the specified animation now. 16747 * 16748 * @param animation the animation to start now 16749 */ 16750 public void startAnimation(Animation animation) { 16751 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 16752 setAnimation(animation); 16753 invalidateParentCaches(); 16754 invalidate(true); 16755 } 16756 16757 /** 16758 * Cancels any animations for this view. 16759 */ 16760 public void clearAnimation() { 16761 if (mCurrentAnimation != null) { 16762 mCurrentAnimation.detach(); 16763 } 16764 mCurrentAnimation = null; 16765 invalidateParentIfNeeded(); 16766 } 16767 16768 /** 16769 * Sets the next animation to play for this view. 16770 * If you want the animation to play immediately, use 16771 * {@link #startAnimation(android.view.animation.Animation)} instead. 16772 * This method provides allows fine-grained 16773 * control over the start time and invalidation, but you 16774 * must make sure that 1) the animation has a start time set, and 16775 * 2) the view's parent (which controls animations on its children) 16776 * will be invalidated when the animation is supposed to 16777 * start. 16778 * 16779 * @param animation The next animation, or null. 16780 */ 16781 public void setAnimation(Animation animation) { 16782 mCurrentAnimation = animation; 16783 16784 if (animation != null) { 16785 // If the screen is off assume the animation start time is now instead of 16786 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 16787 // would cause the animation to start when the screen turns back on 16788 if (mAttachInfo != null && !mAttachInfo.mScreenOn && 16789 animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 16790 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 16791 } 16792 animation.reset(); 16793 } 16794 } 16795 16796 /** 16797 * Invoked by a parent ViewGroup to notify the start of the animation 16798 * currently associated with this view. If you override this method, 16799 * always call super.onAnimationStart(); 16800 * 16801 * @see #setAnimation(android.view.animation.Animation) 16802 * @see #getAnimation() 16803 */ 16804 protected void onAnimationStart() { 16805 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 16806 } 16807 16808 /** 16809 * Invoked by a parent ViewGroup to notify the end of the animation 16810 * currently associated with this view. If you override this method, 16811 * always call super.onAnimationEnd(); 16812 * 16813 * @see #setAnimation(android.view.animation.Animation) 16814 * @see #getAnimation() 16815 */ 16816 protected void onAnimationEnd() { 16817 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 16818 } 16819 16820 /** 16821 * Invoked if there is a Transform that involves alpha. Subclass that can 16822 * draw themselves with the specified alpha should return true, and then 16823 * respect that alpha when their onDraw() is called. If this returns false 16824 * then the view may be redirected to draw into an offscreen buffer to 16825 * fulfill the request, which will look fine, but may be slower than if the 16826 * subclass handles it internally. The default implementation returns false. 16827 * 16828 * @param alpha The alpha (0..255) to apply to the view's drawing 16829 * @return true if the view can draw with the specified alpha. 16830 */ 16831 protected boolean onSetAlpha(int alpha) { 16832 return false; 16833 } 16834 16835 /** 16836 * This is used by the RootView to perform an optimization when 16837 * the view hierarchy contains one or several SurfaceView. 16838 * SurfaceView is always considered transparent, but its children are not, 16839 * therefore all View objects remove themselves from the global transparent 16840 * region (passed as a parameter to this function). 16841 * 16842 * @param region The transparent region for this ViewAncestor (window). 16843 * 16844 * @return Returns true if the effective visibility of the view at this 16845 * point is opaque, regardless of the transparent region; returns false 16846 * if it is possible for underlying windows to be seen behind the view. 16847 * 16848 * {@hide} 16849 */ 16850 public boolean gatherTransparentRegion(Region region) { 16851 final AttachInfo attachInfo = mAttachInfo; 16852 if (region != null && attachInfo != null) { 16853 final int pflags = mPrivateFlags; 16854 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 16855 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 16856 // remove it from the transparent region. 16857 final int[] location = attachInfo.mTransparentLocation; 16858 getLocationInWindow(location); 16859 region.op(location[0], location[1], location[0] + mRight - mLeft, 16860 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 16861 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 16862 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 16863 // exists, so we remove the background drawable's non-transparent 16864 // parts from this transparent region. 16865 applyDrawableToTransparentRegion(mBackground, region); 16866 } 16867 } 16868 return true; 16869 } 16870 16871 /** 16872 * Play a sound effect for this view. 16873 * 16874 * <p>The framework will play sound effects for some built in actions, such as 16875 * clicking, but you may wish to play these effects in your widget, 16876 * for instance, for internal navigation. 16877 * 16878 * <p>The sound effect will only be played if sound effects are enabled by the user, and 16879 * {@link #isSoundEffectsEnabled()} is true. 16880 * 16881 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 16882 */ 16883 public void playSoundEffect(int soundConstant) { 16884 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 16885 return; 16886 } 16887 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 16888 } 16889 16890 /** 16891 * BZZZTT!!1! 16892 * 16893 * <p>Provide haptic feedback to the user for this view. 16894 * 16895 * <p>The framework will provide haptic feedback for some built in actions, 16896 * such as long presses, but you may wish to provide feedback for your 16897 * own widget. 16898 * 16899 * <p>The feedback will only be performed if 16900 * {@link #isHapticFeedbackEnabled()} is true. 16901 * 16902 * @param feedbackConstant One of the constants defined in 16903 * {@link HapticFeedbackConstants} 16904 */ 16905 public boolean performHapticFeedback(int feedbackConstant) { 16906 return performHapticFeedback(feedbackConstant, 0); 16907 } 16908 16909 /** 16910 * BZZZTT!!1! 16911 * 16912 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 16913 * 16914 * @param feedbackConstant One of the constants defined in 16915 * {@link HapticFeedbackConstants} 16916 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 16917 */ 16918 public boolean performHapticFeedback(int feedbackConstant, int flags) { 16919 if (mAttachInfo == null) { 16920 return false; 16921 } 16922 //noinspection SimplifiableIfStatement 16923 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 16924 && !isHapticFeedbackEnabled()) { 16925 return false; 16926 } 16927 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 16928 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 16929 } 16930 16931 /** 16932 * Request that the visibility of the status bar or other screen/window 16933 * decorations be changed. 16934 * 16935 * <p>This method is used to put the over device UI into temporary modes 16936 * where the user's attention is focused more on the application content, 16937 * by dimming or hiding surrounding system affordances. This is typically 16938 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 16939 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 16940 * to be placed behind the action bar (and with these flags other system 16941 * affordances) so that smooth transitions between hiding and showing them 16942 * can be done. 16943 * 16944 * <p>Two representative examples of the use of system UI visibility is 16945 * implementing a content browsing application (like a magazine reader) 16946 * and a video playing application. 16947 * 16948 * <p>The first code shows a typical implementation of a View in a content 16949 * browsing application. In this implementation, the application goes 16950 * into a content-oriented mode by hiding the status bar and action bar, 16951 * and putting the navigation elements into lights out mode. The user can 16952 * then interact with content while in this mode. Such an application should 16953 * provide an easy way for the user to toggle out of the mode (such as to 16954 * check information in the status bar or access notifications). In the 16955 * implementation here, this is done simply by tapping on the content. 16956 * 16957 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 16958 * content} 16959 * 16960 * <p>This second code sample shows a typical implementation of a View 16961 * in a video playing application. In this situation, while the video is 16962 * playing the application would like to go into a complete full-screen mode, 16963 * to use as much of the display as possible for the video. When in this state 16964 * the user can not interact with the application; the system intercepts 16965 * touching on the screen to pop the UI out of full screen mode. See 16966 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 16967 * 16968 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 16969 * content} 16970 * 16971 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 16972 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 16973 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 16974 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 16975 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 16976 */ 16977 public void setSystemUiVisibility(int visibility) { 16978 if (visibility != mSystemUiVisibility) { 16979 mSystemUiVisibility = visibility; 16980 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 16981 mParent.recomputeViewAttributes(this); 16982 } 16983 } 16984 } 16985 16986 /** 16987 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 16988 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 16989 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 16990 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 16991 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 16992 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 16993 */ 16994 public int getSystemUiVisibility() { 16995 return mSystemUiVisibility; 16996 } 16997 16998 /** 16999 * Returns the current system UI visibility that is currently set for 17000 * the entire window. This is the combination of the 17001 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17002 * views in the window. 17003 */ 17004 public int getWindowSystemUiVisibility() { 17005 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17006 } 17007 17008 /** 17009 * Override to find out when the window's requested system UI visibility 17010 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17011 * This is different from the callbacks received through 17012 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17013 * in that this is only telling you about the local request of the window, 17014 * not the actual values applied by the system. 17015 */ 17016 public void onWindowSystemUiVisibilityChanged(int visible) { 17017 } 17018 17019 /** 17020 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17021 * the view hierarchy. 17022 */ 17023 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17024 onWindowSystemUiVisibilityChanged(visible); 17025 } 17026 17027 /** 17028 * Set a listener to receive callbacks when the visibility of the system bar changes. 17029 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17030 */ 17031 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17032 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17033 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17034 mParent.recomputeViewAttributes(this); 17035 } 17036 } 17037 17038 /** 17039 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17040 * the view hierarchy. 17041 */ 17042 public void dispatchSystemUiVisibilityChanged(int visibility) { 17043 ListenerInfo li = mListenerInfo; 17044 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17045 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17046 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17047 } 17048 } 17049 17050 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17051 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17052 if (val != mSystemUiVisibility) { 17053 setSystemUiVisibility(val); 17054 return true; 17055 } 17056 return false; 17057 } 17058 17059 /** @hide */ 17060 public void setDisabledSystemUiVisibility(int flags) { 17061 if (mAttachInfo != null) { 17062 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17063 mAttachInfo.mDisabledSystemUiVisibility = flags; 17064 if (mParent != null) { 17065 mParent.recomputeViewAttributes(this); 17066 } 17067 } 17068 } 17069 } 17070 17071 /** 17072 * Creates an image that the system displays during the drag and drop 17073 * operation. This is called a "drag shadow". The default implementation 17074 * for a DragShadowBuilder based on a View returns an image that has exactly the same 17075 * appearance as the given View. The default also positions the center of the drag shadow 17076 * directly under the touch point. If no View is provided (the constructor with no parameters 17077 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 17078 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 17079 * default is an invisible drag shadow. 17080 * <p> 17081 * You are not required to use the View you provide to the constructor as the basis of the 17082 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 17083 * anything you want as the drag shadow. 17084 * </p> 17085 * <p> 17086 * You pass a DragShadowBuilder object to the system when you start the drag. The system 17087 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 17088 * size and position of the drag shadow. It uses this data to construct a 17089 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 17090 * so that your application can draw the shadow image in the Canvas. 17091 * </p> 17092 * 17093 * <div class="special reference"> 17094 * <h3>Developer Guides</h3> 17095 * <p>For a guide to implementing drag and drop features, read the 17096 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17097 * </div> 17098 */ 17099 public static class DragShadowBuilder { 17100 private final WeakReference<View> mView; 17101 17102 /** 17103 * Constructs a shadow image builder based on a View. By default, the resulting drag 17104 * shadow will have the same appearance and dimensions as the View, with the touch point 17105 * over the center of the View. 17106 * @param view A View. Any View in scope can be used. 17107 */ 17108 public DragShadowBuilder(View view) { 17109 mView = new WeakReference<View>(view); 17110 } 17111 17112 /** 17113 * Construct a shadow builder object with no associated View. This 17114 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 17115 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 17116 * to supply the drag shadow's dimensions and appearance without 17117 * reference to any View object. If they are not overridden, then the result is an 17118 * invisible drag shadow. 17119 */ 17120 public DragShadowBuilder() { 17121 mView = new WeakReference<View>(null); 17122 } 17123 17124 /** 17125 * Returns the View object that had been passed to the 17126 * {@link #View.DragShadowBuilder(View)} 17127 * constructor. If that View parameter was {@code null} or if the 17128 * {@link #View.DragShadowBuilder()} 17129 * constructor was used to instantiate the builder object, this method will return 17130 * null. 17131 * 17132 * @return The View object associate with this builder object. 17133 */ 17134 @SuppressWarnings({"JavadocReference"}) 17135 final public View getView() { 17136 return mView.get(); 17137 } 17138 17139 /** 17140 * Provides the metrics for the shadow image. These include the dimensions of 17141 * the shadow image, and the point within that shadow that should 17142 * be centered under the touch location while dragging. 17143 * <p> 17144 * The default implementation sets the dimensions of the shadow to be the 17145 * same as the dimensions of the View itself and centers the shadow under 17146 * the touch point. 17147 * </p> 17148 * 17149 * @param shadowSize A {@link android.graphics.Point} containing the width and height 17150 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 17151 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 17152 * image. 17153 * 17154 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 17155 * shadow image that should be underneath the touch point during the drag and drop 17156 * operation. Your application must set {@link android.graphics.Point#x} to the 17157 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 17158 */ 17159 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 17160 final View view = mView.get(); 17161 if (view != null) { 17162 shadowSize.set(view.getWidth(), view.getHeight()); 17163 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 17164 } else { 17165 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 17166 } 17167 } 17168 17169 /** 17170 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 17171 * based on the dimensions it received from the 17172 * {@link #onProvideShadowMetrics(Point, Point)} callback. 17173 * 17174 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 17175 */ 17176 public void onDrawShadow(Canvas canvas) { 17177 final View view = mView.get(); 17178 if (view != null) { 17179 view.draw(canvas); 17180 } else { 17181 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 17182 } 17183 } 17184 } 17185 17186 /** 17187 * Starts a drag and drop operation. When your application calls this method, it passes a 17188 * {@link android.view.View.DragShadowBuilder} object to the system. The 17189 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 17190 * to get metrics for the drag shadow, and then calls the object's 17191 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 17192 * <p> 17193 * Once the system has the drag shadow, it begins the drag and drop operation by sending 17194 * drag events to all the View objects in your application that are currently visible. It does 17195 * this either by calling the View object's drag listener (an implementation of 17196 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 17197 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17198 * Both are passed a {@link android.view.DragEvent} object that has a 17199 * {@link android.view.DragEvent#getAction()} value of 17200 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17201 * </p> 17202 * <p> 17203 * Your application can invoke startDrag() on any attached View object. The View object does not 17204 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17205 * be related to the View the user selected for dragging. 17206 * </p> 17207 * @param data A {@link android.content.ClipData} object pointing to the data to be 17208 * transferred by the drag and drop operation. 17209 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17210 * drag shadow. 17211 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17212 * drop operation. This Object is put into every DragEvent object sent by the system during the 17213 * current drag. 17214 * <p> 17215 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17216 * to the target Views. For example, it can contain flags that differentiate between a 17217 * a copy operation and a move operation. 17218 * </p> 17219 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17220 * so the parameter should be set to 0. 17221 * @return {@code true} if the method completes successfully, or 17222 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17223 * do a drag, and so no drag operation is in progress. 17224 */ 17225 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17226 Object myLocalState, int flags) { 17227 if (ViewDebug.DEBUG_DRAG) { 17228 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17229 } 17230 boolean okay = false; 17231 17232 Point shadowSize = new Point(); 17233 Point shadowTouchPoint = new Point(); 17234 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17235 17236 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17237 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17238 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17239 } 17240 17241 if (ViewDebug.DEBUG_DRAG) { 17242 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17243 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17244 } 17245 Surface surface = new Surface(); 17246 try { 17247 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17248 flags, shadowSize.x, shadowSize.y, surface); 17249 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17250 + " surface=" + surface); 17251 if (token != null) { 17252 Canvas canvas = surface.lockCanvas(null); 17253 try { 17254 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17255 shadowBuilder.onDrawShadow(canvas); 17256 } finally { 17257 surface.unlockCanvasAndPost(canvas); 17258 } 17259 17260 final ViewRootImpl root = getViewRootImpl(); 17261 17262 // Cache the local state object for delivery with DragEvents 17263 root.setLocalDragState(myLocalState); 17264 17265 // repurpose 'shadowSize' for the last touch point 17266 root.getLastTouchPoint(shadowSize); 17267 17268 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17269 shadowSize.x, shadowSize.y, 17270 shadowTouchPoint.x, shadowTouchPoint.y, data); 17271 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17272 17273 // Off and running! Release our local surface instance; the drag 17274 // shadow surface is now managed by the system process. 17275 surface.release(); 17276 } 17277 } catch (Exception e) { 17278 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17279 surface.destroy(); 17280 } 17281 17282 return okay; 17283 } 17284 17285 /** 17286 * Handles drag events sent by the system following a call to 17287 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17288 *<p> 17289 * When the system calls this method, it passes a 17290 * {@link android.view.DragEvent} object. A call to 17291 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17292 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17293 * operation. 17294 * @param event The {@link android.view.DragEvent} sent by the system. 17295 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17296 * in DragEvent, indicating the type of drag event represented by this object. 17297 * @return {@code true} if the method was successful, otherwise {@code false}. 17298 * <p> 17299 * The method should return {@code true} in response to an action type of 17300 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17301 * operation. 17302 * </p> 17303 * <p> 17304 * The method should also return {@code true} in response to an action type of 17305 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17306 * {@code false} if it didn't. 17307 * </p> 17308 */ 17309 public boolean onDragEvent(DragEvent event) { 17310 return false; 17311 } 17312 17313 /** 17314 * Detects if this View is enabled and has a drag event listener. 17315 * If both are true, then it calls the drag event listener with the 17316 * {@link android.view.DragEvent} it received. If the drag event listener returns 17317 * {@code true}, then dispatchDragEvent() returns {@code true}. 17318 * <p> 17319 * For all other cases, the method calls the 17320 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17321 * method and returns its result. 17322 * </p> 17323 * <p> 17324 * This ensures that a drag event is always consumed, even if the View does not have a drag 17325 * event listener. However, if the View has a listener and the listener returns true, then 17326 * onDragEvent() is not called. 17327 * </p> 17328 */ 17329 public boolean dispatchDragEvent(DragEvent event) { 17330 ListenerInfo li = mListenerInfo; 17331 //noinspection SimplifiableIfStatement 17332 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17333 && li.mOnDragListener.onDrag(this, event)) { 17334 return true; 17335 } 17336 return onDragEvent(event); 17337 } 17338 17339 boolean canAcceptDrag() { 17340 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17341 } 17342 17343 /** 17344 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17345 * it is ever exposed at all. 17346 * @hide 17347 */ 17348 public void onCloseSystemDialogs(String reason) { 17349 } 17350 17351 /** 17352 * Given a Drawable whose bounds have been set to draw into this view, 17353 * update a Region being computed for 17354 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17355 * that any non-transparent parts of the Drawable are removed from the 17356 * given transparent region. 17357 * 17358 * @param dr The Drawable whose transparency is to be applied to the region. 17359 * @param region A Region holding the current transparency information, 17360 * where any parts of the region that are set are considered to be 17361 * transparent. On return, this region will be modified to have the 17362 * transparency information reduced by the corresponding parts of the 17363 * Drawable that are not transparent. 17364 * {@hide} 17365 */ 17366 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17367 if (DBG) { 17368 Log.i("View", "Getting transparent region for: " + this); 17369 } 17370 final Region r = dr.getTransparentRegion(); 17371 final Rect db = dr.getBounds(); 17372 final AttachInfo attachInfo = mAttachInfo; 17373 if (r != null && attachInfo != null) { 17374 final int w = getRight()-getLeft(); 17375 final int h = getBottom()-getTop(); 17376 if (db.left > 0) { 17377 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 17378 r.op(0, 0, db.left, h, Region.Op.UNION); 17379 } 17380 if (db.right < w) { 17381 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 17382 r.op(db.right, 0, w, h, Region.Op.UNION); 17383 } 17384 if (db.top > 0) { 17385 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 17386 r.op(0, 0, w, db.top, Region.Op.UNION); 17387 } 17388 if (db.bottom < h) { 17389 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 17390 r.op(0, db.bottom, w, h, Region.Op.UNION); 17391 } 17392 final int[] location = attachInfo.mTransparentLocation; 17393 getLocationInWindow(location); 17394 r.translate(location[0], location[1]); 17395 region.op(r, Region.Op.INTERSECT); 17396 } else { 17397 region.op(db, Region.Op.DIFFERENCE); 17398 } 17399 } 17400 17401 private void checkForLongClick(int delayOffset) { 17402 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 17403 mHasPerformedLongPress = false; 17404 17405 if (mPendingCheckForLongPress == null) { 17406 mPendingCheckForLongPress = new CheckForLongPress(); 17407 } 17408 mPendingCheckForLongPress.rememberWindowAttachCount(); 17409 postDelayed(mPendingCheckForLongPress, 17410 ViewConfiguration.getLongPressTimeout() - delayOffset); 17411 } 17412 } 17413 17414 /** 17415 * Inflate a view from an XML resource. This convenience method wraps the {@link 17416 * LayoutInflater} class, which provides a full range of options for view inflation. 17417 * 17418 * @param context The Context object for your activity or application. 17419 * @param resource The resource ID to inflate 17420 * @param root A view group that will be the parent. Used to properly inflate the 17421 * layout_* parameters. 17422 * @see LayoutInflater 17423 */ 17424 public static View inflate(Context context, int resource, ViewGroup root) { 17425 LayoutInflater factory = LayoutInflater.from(context); 17426 return factory.inflate(resource, root); 17427 } 17428 17429 /** 17430 * Scroll the view with standard behavior for scrolling beyond the normal 17431 * content boundaries. Views that call this method should override 17432 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 17433 * results of an over-scroll operation. 17434 * 17435 * Views can use this method to handle any touch or fling-based scrolling. 17436 * 17437 * @param deltaX Change in X in pixels 17438 * @param deltaY Change in Y in pixels 17439 * @param scrollX Current X scroll value in pixels before applying deltaX 17440 * @param scrollY Current Y scroll value in pixels before applying deltaY 17441 * @param scrollRangeX Maximum content scroll range along the X axis 17442 * @param scrollRangeY Maximum content scroll range along the Y axis 17443 * @param maxOverScrollX Number of pixels to overscroll by in either direction 17444 * along the X axis. 17445 * @param maxOverScrollY Number of pixels to overscroll by in either direction 17446 * along the Y axis. 17447 * @param isTouchEvent true if this scroll operation is the result of a touch event. 17448 * @return true if scrolling was clamped to an over-scroll boundary along either 17449 * axis, false otherwise. 17450 */ 17451 @SuppressWarnings({"UnusedParameters"}) 17452 protected boolean overScrollBy(int deltaX, int deltaY, 17453 int scrollX, int scrollY, 17454 int scrollRangeX, int scrollRangeY, 17455 int maxOverScrollX, int maxOverScrollY, 17456 boolean isTouchEvent) { 17457 final int overScrollMode = mOverScrollMode; 17458 final boolean canScrollHorizontal = 17459 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 17460 final boolean canScrollVertical = 17461 computeVerticalScrollRange() > computeVerticalScrollExtent(); 17462 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 17463 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 17464 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 17465 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 17466 17467 int newScrollX = scrollX + deltaX; 17468 if (!overScrollHorizontal) { 17469 maxOverScrollX = 0; 17470 } 17471 17472 int newScrollY = scrollY + deltaY; 17473 if (!overScrollVertical) { 17474 maxOverScrollY = 0; 17475 } 17476 17477 // Clamp values if at the limits and record 17478 final int left = -maxOverScrollX; 17479 final int right = maxOverScrollX + scrollRangeX; 17480 final int top = -maxOverScrollY; 17481 final int bottom = maxOverScrollY + scrollRangeY; 17482 17483 boolean clampedX = false; 17484 if (newScrollX > right) { 17485 newScrollX = right; 17486 clampedX = true; 17487 } else if (newScrollX < left) { 17488 newScrollX = left; 17489 clampedX = true; 17490 } 17491 17492 boolean clampedY = false; 17493 if (newScrollY > bottom) { 17494 newScrollY = bottom; 17495 clampedY = true; 17496 } else if (newScrollY < top) { 17497 newScrollY = top; 17498 clampedY = true; 17499 } 17500 17501 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 17502 17503 return clampedX || clampedY; 17504 } 17505 17506 /** 17507 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 17508 * respond to the results of an over-scroll operation. 17509 * 17510 * @param scrollX New X scroll value in pixels 17511 * @param scrollY New Y scroll value in pixels 17512 * @param clampedX True if scrollX was clamped to an over-scroll boundary 17513 * @param clampedY True if scrollY was clamped to an over-scroll boundary 17514 */ 17515 protected void onOverScrolled(int scrollX, int scrollY, 17516 boolean clampedX, boolean clampedY) { 17517 // Intentionally empty. 17518 } 17519 17520 /** 17521 * Returns the over-scroll mode for this view. The result will be 17522 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 17523 * (allow over-scrolling only if the view content is larger than the container), 17524 * or {@link #OVER_SCROLL_NEVER}. 17525 * 17526 * @return This view's over-scroll mode. 17527 */ 17528 public int getOverScrollMode() { 17529 return mOverScrollMode; 17530 } 17531 17532 /** 17533 * Set the over-scroll mode for this view. Valid over-scroll modes are 17534 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 17535 * (allow over-scrolling only if the view content is larger than the container), 17536 * or {@link #OVER_SCROLL_NEVER}. 17537 * 17538 * Setting the over-scroll mode of a view will have an effect only if the 17539 * view is capable of scrolling. 17540 * 17541 * @param overScrollMode The new over-scroll mode for this view. 17542 */ 17543 public void setOverScrollMode(int overScrollMode) { 17544 if (overScrollMode != OVER_SCROLL_ALWAYS && 17545 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 17546 overScrollMode != OVER_SCROLL_NEVER) { 17547 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 17548 } 17549 mOverScrollMode = overScrollMode; 17550 } 17551 17552 /** 17553 * Gets a scale factor that determines the distance the view should scroll 17554 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 17555 * @return The vertical scroll scale factor. 17556 * @hide 17557 */ 17558 protected float getVerticalScrollFactor() { 17559 if (mVerticalScrollFactor == 0) { 17560 TypedValue outValue = new TypedValue(); 17561 if (!mContext.getTheme().resolveAttribute( 17562 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 17563 throw new IllegalStateException( 17564 "Expected theme to define listPreferredItemHeight."); 17565 } 17566 mVerticalScrollFactor = outValue.getDimension( 17567 mContext.getResources().getDisplayMetrics()); 17568 } 17569 return mVerticalScrollFactor; 17570 } 17571 17572 /** 17573 * Gets a scale factor that determines the distance the view should scroll 17574 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 17575 * @return The horizontal scroll scale factor. 17576 * @hide 17577 */ 17578 protected float getHorizontalScrollFactor() { 17579 // TODO: Should use something else. 17580 return getVerticalScrollFactor(); 17581 } 17582 17583 /** 17584 * Return the value specifying the text direction or policy that was set with 17585 * {@link #setTextDirection(int)}. 17586 * 17587 * @return the defined text direction. It can be one of: 17588 * 17589 * {@link #TEXT_DIRECTION_INHERIT}, 17590 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17591 * {@link #TEXT_DIRECTION_ANY_RTL}, 17592 * {@link #TEXT_DIRECTION_LTR}, 17593 * {@link #TEXT_DIRECTION_RTL}, 17594 * {@link #TEXT_DIRECTION_LOCALE} 17595 * 17596 * @attr ref android.R.styleable#View_textDirection 17597 * 17598 * @hide 17599 */ 17600 @ViewDebug.ExportedProperty(category = "text", mapping = { 17601 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 17602 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 17603 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 17604 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 17605 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 17606 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 17607 }) 17608 public int getRawTextDirection() { 17609 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 17610 } 17611 17612 /** 17613 * Set the text direction. 17614 * 17615 * @param textDirection the direction to set. Should be one of: 17616 * 17617 * {@link #TEXT_DIRECTION_INHERIT}, 17618 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17619 * {@link #TEXT_DIRECTION_ANY_RTL}, 17620 * {@link #TEXT_DIRECTION_LTR}, 17621 * {@link #TEXT_DIRECTION_RTL}, 17622 * {@link #TEXT_DIRECTION_LOCALE} 17623 * 17624 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 17625 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 17626 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 17627 * 17628 * @attr ref android.R.styleable#View_textDirection 17629 */ 17630 public void setTextDirection(int textDirection) { 17631 if (getRawTextDirection() != textDirection) { 17632 // Reset the current text direction and the resolved one 17633 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 17634 resetResolvedTextDirection(); 17635 // Set the new text direction 17636 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 17637 // Do resolution 17638 resolveTextDirection(); 17639 // Notify change 17640 onRtlPropertiesChanged(getLayoutDirection()); 17641 // Refresh 17642 requestLayout(); 17643 invalidate(true); 17644 } 17645 } 17646 17647 /** 17648 * Return the resolved text direction. 17649 * 17650 * @return the resolved text direction. Returns one of: 17651 * 17652 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17653 * {@link #TEXT_DIRECTION_ANY_RTL}, 17654 * {@link #TEXT_DIRECTION_LTR}, 17655 * {@link #TEXT_DIRECTION_RTL}, 17656 * {@link #TEXT_DIRECTION_LOCALE} 17657 * 17658 * @attr ref android.R.styleable#View_textDirection 17659 */ 17660 @ViewDebug.ExportedProperty(category = "text", mapping = { 17661 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 17662 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 17663 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 17664 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 17665 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 17666 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 17667 }) 17668 public int getTextDirection() { 17669 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 17670 } 17671 17672 /** 17673 * Resolve the text direction. 17674 * 17675 * @return true if resolution has been done, false otherwise. 17676 * 17677 * @hide 17678 */ 17679 public boolean resolveTextDirection() { 17680 // Reset any previous text direction resolution 17681 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 17682 17683 if (hasRtlSupport()) { 17684 // Set resolved text direction flag depending on text direction flag 17685 final int textDirection = getRawTextDirection(); 17686 switch(textDirection) { 17687 case TEXT_DIRECTION_INHERIT: 17688 if (!canResolveTextDirection()) { 17689 // We cannot do the resolution if there is no parent, so use the default one 17690 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17691 // Resolution will need to happen again later 17692 return false; 17693 } 17694 17695 // Parent has not yet resolved, so we still return the default 17696 try { 17697 if (!mParent.isTextDirectionResolved()) { 17698 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17699 // Resolution will need to happen again later 17700 return false; 17701 } 17702 } catch (AbstractMethodError e) { 17703 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17704 " does not fully implement ViewParent", e); 17705 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 17706 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17707 return true; 17708 } 17709 17710 // Set current resolved direction to the same value as the parent's one 17711 int parentResolvedDirection; 17712 try { 17713 parentResolvedDirection = mParent.getTextDirection(); 17714 } catch (AbstractMethodError e) { 17715 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17716 " does not fully implement ViewParent", e); 17717 parentResolvedDirection = TEXT_DIRECTION_LTR; 17718 } 17719 switch (parentResolvedDirection) { 17720 case TEXT_DIRECTION_FIRST_STRONG: 17721 case TEXT_DIRECTION_ANY_RTL: 17722 case TEXT_DIRECTION_LTR: 17723 case TEXT_DIRECTION_RTL: 17724 case TEXT_DIRECTION_LOCALE: 17725 mPrivateFlags2 |= 17726 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 17727 break; 17728 default: 17729 // Default resolved direction is "first strong" heuristic 17730 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17731 } 17732 break; 17733 case TEXT_DIRECTION_FIRST_STRONG: 17734 case TEXT_DIRECTION_ANY_RTL: 17735 case TEXT_DIRECTION_LTR: 17736 case TEXT_DIRECTION_RTL: 17737 case TEXT_DIRECTION_LOCALE: 17738 // Resolved direction is the same as text direction 17739 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 17740 break; 17741 default: 17742 // Default resolved direction is "first strong" heuristic 17743 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17744 } 17745 } else { 17746 // Default resolved direction is "first strong" heuristic 17747 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17748 } 17749 17750 // Set to resolved 17751 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 17752 return true; 17753 } 17754 17755 /** 17756 * Check if text direction resolution can be done. 17757 * 17758 * @return true if text direction resolution can be done otherwise return false. 17759 */ 17760 public boolean canResolveTextDirection() { 17761 switch (getRawTextDirection()) { 17762 case TEXT_DIRECTION_INHERIT: 17763 if (mParent != null) { 17764 try { 17765 return mParent.canResolveTextDirection(); 17766 } catch (AbstractMethodError e) { 17767 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17768 " does not fully implement ViewParent", e); 17769 } 17770 } 17771 return false; 17772 17773 default: 17774 return true; 17775 } 17776 } 17777 17778 /** 17779 * Reset resolved text direction. Text direction will be resolved during a call to 17780 * {@link #onMeasure(int, int)}. 17781 * 17782 * @hide 17783 */ 17784 public void resetResolvedTextDirection() { 17785 // Reset any previous text direction resolution 17786 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 17787 // Set to default value 17788 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17789 } 17790 17791 /** 17792 * @return true if text direction is inherited. 17793 * 17794 * @hide 17795 */ 17796 public boolean isTextDirectionInherited() { 17797 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 17798 } 17799 17800 /** 17801 * @return true if text direction is resolved. 17802 */ 17803 public boolean isTextDirectionResolved() { 17804 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 17805 } 17806 17807 /** 17808 * Return the value specifying the text alignment or policy that was set with 17809 * {@link #setTextAlignment(int)}. 17810 * 17811 * @return the defined text alignment. It can be one of: 17812 * 17813 * {@link #TEXT_ALIGNMENT_INHERIT}, 17814 * {@link #TEXT_ALIGNMENT_GRAVITY}, 17815 * {@link #TEXT_ALIGNMENT_CENTER}, 17816 * {@link #TEXT_ALIGNMENT_TEXT_START}, 17817 * {@link #TEXT_ALIGNMENT_TEXT_END}, 17818 * {@link #TEXT_ALIGNMENT_VIEW_START}, 17819 * {@link #TEXT_ALIGNMENT_VIEW_END} 17820 * 17821 * @attr ref android.R.styleable#View_textAlignment 17822 * 17823 * @hide 17824 */ 17825 @ViewDebug.ExportedProperty(category = "text", mapping = { 17826 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 17827 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 17828 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 17829 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 17830 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 17831 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 17832 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 17833 }) 17834 public int getRawTextAlignment() { 17835 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 17836 } 17837 17838 /** 17839 * Set the text alignment. 17840 * 17841 * @param textAlignment The text alignment to set. Should be one of 17842 * 17843 * {@link #TEXT_ALIGNMENT_INHERIT}, 17844 * {@link #TEXT_ALIGNMENT_GRAVITY}, 17845 * {@link #TEXT_ALIGNMENT_CENTER}, 17846 * {@link #TEXT_ALIGNMENT_TEXT_START}, 17847 * {@link #TEXT_ALIGNMENT_TEXT_END}, 17848 * {@link #TEXT_ALIGNMENT_VIEW_START}, 17849 * {@link #TEXT_ALIGNMENT_VIEW_END} 17850 * 17851 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 17852 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 17853 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 17854 * 17855 * @attr ref android.R.styleable#View_textAlignment 17856 */ 17857 public void setTextAlignment(int textAlignment) { 17858 if (textAlignment != getRawTextAlignment()) { 17859 // Reset the current and resolved text alignment 17860 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 17861 resetResolvedTextAlignment(); 17862 // Set the new text alignment 17863 mPrivateFlags2 |= 17864 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 17865 // Do resolution 17866 resolveTextAlignment(); 17867 // Notify change 17868 onRtlPropertiesChanged(getLayoutDirection()); 17869 // Refresh 17870 requestLayout(); 17871 invalidate(true); 17872 } 17873 } 17874 17875 /** 17876 * Return the resolved text alignment. 17877 * 17878 * @return the resolved text alignment. Returns one of: 17879 * 17880 * {@link #TEXT_ALIGNMENT_GRAVITY}, 17881 * {@link #TEXT_ALIGNMENT_CENTER}, 17882 * {@link #TEXT_ALIGNMENT_TEXT_START}, 17883 * {@link #TEXT_ALIGNMENT_TEXT_END}, 17884 * {@link #TEXT_ALIGNMENT_VIEW_START}, 17885 * {@link #TEXT_ALIGNMENT_VIEW_END} 17886 * 17887 * @attr ref android.R.styleable#View_textAlignment 17888 */ 17889 @ViewDebug.ExportedProperty(category = "text", mapping = { 17890 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 17891 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 17892 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 17893 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 17894 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 17895 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 17896 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 17897 }) 17898 public int getTextAlignment() { 17899 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 17900 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 17901 } 17902 17903 /** 17904 * Resolve the text alignment. 17905 * 17906 * @return true if resolution has been done, false otherwise. 17907 * 17908 * @hide 17909 */ 17910 public boolean resolveTextAlignment() { 17911 // Reset any previous text alignment resolution 17912 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 17913 17914 if (hasRtlSupport()) { 17915 // Set resolved text alignment flag depending on text alignment flag 17916 final int textAlignment = getRawTextAlignment(); 17917 switch (textAlignment) { 17918 case TEXT_ALIGNMENT_INHERIT: 17919 // Check if we can resolve the text alignment 17920 if (!canResolveTextAlignment()) { 17921 // We cannot do the resolution if there is no parent so use the default 17922 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17923 // Resolution will need to happen again later 17924 return false; 17925 } 17926 17927 // Parent has not yet resolved, so we still return the default 17928 try { 17929 if (!mParent.isTextAlignmentResolved()) { 17930 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17931 // Resolution will need to happen again later 17932 return false; 17933 } 17934 } catch (AbstractMethodError e) { 17935 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17936 " does not fully implement ViewParent", e); 17937 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 17938 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17939 return true; 17940 } 17941 17942 int parentResolvedTextAlignment; 17943 try { 17944 parentResolvedTextAlignment = mParent.getTextAlignment(); 17945 } catch (AbstractMethodError e) { 17946 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17947 " does not fully implement ViewParent", e); 17948 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 17949 } 17950 switch (parentResolvedTextAlignment) { 17951 case TEXT_ALIGNMENT_GRAVITY: 17952 case TEXT_ALIGNMENT_TEXT_START: 17953 case TEXT_ALIGNMENT_TEXT_END: 17954 case TEXT_ALIGNMENT_CENTER: 17955 case TEXT_ALIGNMENT_VIEW_START: 17956 case TEXT_ALIGNMENT_VIEW_END: 17957 // Resolved text alignment is the same as the parent resolved 17958 // text alignment 17959 mPrivateFlags2 |= 17960 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 17961 break; 17962 default: 17963 // Use default resolved text alignment 17964 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17965 } 17966 break; 17967 case TEXT_ALIGNMENT_GRAVITY: 17968 case TEXT_ALIGNMENT_TEXT_START: 17969 case TEXT_ALIGNMENT_TEXT_END: 17970 case TEXT_ALIGNMENT_CENTER: 17971 case TEXT_ALIGNMENT_VIEW_START: 17972 case TEXT_ALIGNMENT_VIEW_END: 17973 // Resolved text alignment is the same as text alignment 17974 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 17975 break; 17976 default: 17977 // Use default resolved text alignment 17978 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17979 } 17980 } else { 17981 // Use default resolved text alignment 17982 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17983 } 17984 17985 // Set the resolved 17986 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 17987 return true; 17988 } 17989 17990 /** 17991 * Check if text alignment resolution can be done. 17992 * 17993 * @return true if text alignment resolution can be done otherwise return false. 17994 */ 17995 public boolean canResolveTextAlignment() { 17996 switch (getRawTextAlignment()) { 17997 case TEXT_DIRECTION_INHERIT: 17998 if (mParent != null) { 17999 try { 18000 return mParent.canResolveTextAlignment(); 18001 } catch (AbstractMethodError e) { 18002 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18003 " does not fully implement ViewParent", e); 18004 } 18005 } 18006 return false; 18007 18008 default: 18009 return true; 18010 } 18011 } 18012 18013 /** 18014 * Reset resolved text alignment. Text alignment will be resolved during a call to 18015 * {@link #onMeasure(int, int)}. 18016 * 18017 * @hide 18018 */ 18019 public void resetResolvedTextAlignment() { 18020 // Reset any previous text alignment resolution 18021 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18022 // Set to default 18023 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18024 } 18025 18026 /** 18027 * @return true if text alignment is inherited. 18028 * 18029 * @hide 18030 */ 18031 public boolean isTextAlignmentInherited() { 18032 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 18033 } 18034 18035 /** 18036 * @return true if text alignment is resolved. 18037 */ 18038 public boolean isTextAlignmentResolved() { 18039 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18040 } 18041 18042 /** 18043 * Generate a value suitable for use in {@link #setId(int)}. 18044 * This value will not collide with ID values generated at build time by aapt for R.id. 18045 * 18046 * @return a generated ID value 18047 */ 18048 public static int generateViewId() { 18049 for (;;) { 18050 final int result = sNextGeneratedId.get(); 18051 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 18052 int newValue = result + 1; 18053 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 18054 if (sNextGeneratedId.compareAndSet(result, newValue)) { 18055 return result; 18056 } 18057 } 18058 } 18059 18060 // 18061 // Properties 18062 // 18063 /** 18064 * A Property wrapper around the <code>alpha</code> functionality handled by the 18065 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 18066 */ 18067 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 18068 @Override 18069 public void setValue(View object, float value) { 18070 object.setAlpha(value); 18071 } 18072 18073 @Override 18074 public Float get(View object) { 18075 return object.getAlpha(); 18076 } 18077 }; 18078 18079 /** 18080 * A Property wrapper around the <code>translationX</code> functionality handled by the 18081 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 18082 */ 18083 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 18084 @Override 18085 public void setValue(View object, float value) { 18086 object.setTranslationX(value); 18087 } 18088 18089 @Override 18090 public Float get(View object) { 18091 return object.getTranslationX(); 18092 } 18093 }; 18094 18095 /** 18096 * A Property wrapper around the <code>translationY</code> functionality handled by the 18097 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 18098 */ 18099 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 18100 @Override 18101 public void setValue(View object, float value) { 18102 object.setTranslationY(value); 18103 } 18104 18105 @Override 18106 public Float get(View object) { 18107 return object.getTranslationY(); 18108 } 18109 }; 18110 18111 /** 18112 * A Property wrapper around the <code>x</code> functionality handled by the 18113 * {@link View#setX(float)} and {@link View#getX()} methods. 18114 */ 18115 public static final Property<View, Float> X = new FloatProperty<View>("x") { 18116 @Override 18117 public void setValue(View object, float value) { 18118 object.setX(value); 18119 } 18120 18121 @Override 18122 public Float get(View object) { 18123 return object.getX(); 18124 } 18125 }; 18126 18127 /** 18128 * A Property wrapper around the <code>y</code> functionality handled by the 18129 * {@link View#setY(float)} and {@link View#getY()} methods. 18130 */ 18131 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 18132 @Override 18133 public void setValue(View object, float value) { 18134 object.setY(value); 18135 } 18136 18137 @Override 18138 public Float get(View object) { 18139 return object.getY(); 18140 } 18141 }; 18142 18143 /** 18144 * A Property wrapper around the <code>rotation</code> functionality handled by the 18145 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 18146 */ 18147 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 18148 @Override 18149 public void setValue(View object, float value) { 18150 object.setRotation(value); 18151 } 18152 18153 @Override 18154 public Float get(View object) { 18155 return object.getRotation(); 18156 } 18157 }; 18158 18159 /** 18160 * A Property wrapper around the <code>rotationX</code> functionality handled by the 18161 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 18162 */ 18163 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 18164 @Override 18165 public void setValue(View object, float value) { 18166 object.setRotationX(value); 18167 } 18168 18169 @Override 18170 public Float get(View object) { 18171 return object.getRotationX(); 18172 } 18173 }; 18174 18175 /** 18176 * A Property wrapper around the <code>rotationY</code> functionality handled by the 18177 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 18178 */ 18179 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 18180 @Override 18181 public void setValue(View object, float value) { 18182 object.setRotationY(value); 18183 } 18184 18185 @Override 18186 public Float get(View object) { 18187 return object.getRotationY(); 18188 } 18189 }; 18190 18191 /** 18192 * A Property wrapper around the <code>scaleX</code> functionality handled by the 18193 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 18194 */ 18195 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 18196 @Override 18197 public void setValue(View object, float value) { 18198 object.setScaleX(value); 18199 } 18200 18201 @Override 18202 public Float get(View object) { 18203 return object.getScaleX(); 18204 } 18205 }; 18206 18207 /** 18208 * A Property wrapper around the <code>scaleY</code> functionality handled by the 18209 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 18210 */ 18211 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 18212 @Override 18213 public void setValue(View object, float value) { 18214 object.setScaleY(value); 18215 } 18216 18217 @Override 18218 public Float get(View object) { 18219 return object.getScaleY(); 18220 } 18221 }; 18222 18223 /** 18224 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 18225 * Each MeasureSpec represents a requirement for either the width or the height. 18226 * A MeasureSpec is comprised of a size and a mode. There are three possible 18227 * modes: 18228 * <dl> 18229 * <dt>UNSPECIFIED</dt> 18230 * <dd> 18231 * The parent has not imposed any constraint on the child. It can be whatever size 18232 * it wants. 18233 * </dd> 18234 * 18235 * <dt>EXACTLY</dt> 18236 * <dd> 18237 * The parent has determined an exact size for the child. The child is going to be 18238 * given those bounds regardless of how big it wants to be. 18239 * </dd> 18240 * 18241 * <dt>AT_MOST</dt> 18242 * <dd> 18243 * The child can be as large as it wants up to the specified size. 18244 * </dd> 18245 * </dl> 18246 * 18247 * MeasureSpecs are implemented as ints to reduce object allocation. This class 18248 * is provided to pack and unpack the <size, mode> tuple into the int. 18249 */ 18250 public static class MeasureSpec { 18251 private static final int MODE_SHIFT = 30; 18252 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 18253 18254 /** 18255 * Measure specification mode: The parent has not imposed any constraint 18256 * on the child. It can be whatever size it wants. 18257 */ 18258 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 18259 18260 /** 18261 * Measure specification mode: The parent has determined an exact size 18262 * for the child. The child is going to be given those bounds regardless 18263 * of how big it wants to be. 18264 */ 18265 public static final int EXACTLY = 1 << MODE_SHIFT; 18266 18267 /** 18268 * Measure specification mode: The child can be as large as it wants up 18269 * to the specified size. 18270 */ 18271 public static final int AT_MOST = 2 << MODE_SHIFT; 18272 18273 /** 18274 * Creates a measure specification based on the supplied size and mode. 18275 * 18276 * The mode must always be one of the following: 18277 * <ul> 18278 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 18279 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 18280 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 18281 * </ul> 18282 * 18283 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 18284 * implementation was such that the order of arguments did not matter 18285 * and overflow in either value could impact the resulting MeasureSpec. 18286 * {@link android.widget.RelativeLayout} was affected by this bug. 18287 * Apps targeting API levels greater than 17 will get the fixed, more strict 18288 * behavior.</p> 18289 * 18290 * @param size the size of the measure specification 18291 * @param mode the mode of the measure specification 18292 * @return the measure specification based on size and mode 18293 */ 18294 public static int makeMeasureSpec(int size, int mode) { 18295 if (sUseBrokenMakeMeasureSpec) { 18296 return size + mode; 18297 } else { 18298 return (size & ~MODE_MASK) | (mode & MODE_MASK); 18299 } 18300 } 18301 18302 /** 18303 * Extracts the mode from the supplied measure specification. 18304 * 18305 * @param measureSpec the measure specification to extract the mode from 18306 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 18307 * {@link android.view.View.MeasureSpec#AT_MOST} or 18308 * {@link android.view.View.MeasureSpec#EXACTLY} 18309 */ 18310 public static int getMode(int measureSpec) { 18311 return (measureSpec & MODE_MASK); 18312 } 18313 18314 /** 18315 * Extracts the size from the supplied measure specification. 18316 * 18317 * @param measureSpec the measure specification to extract the size from 18318 * @return the size in pixels defined in the supplied measure specification 18319 */ 18320 public static int getSize(int measureSpec) { 18321 return (measureSpec & ~MODE_MASK); 18322 } 18323 18324 static int adjust(int measureSpec, int delta) { 18325 return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec)); 18326 } 18327 18328 /** 18329 * Returns a String representation of the specified measure 18330 * specification. 18331 * 18332 * @param measureSpec the measure specification to convert to a String 18333 * @return a String with the following format: "MeasureSpec: MODE SIZE" 18334 */ 18335 public static String toString(int measureSpec) { 18336 int mode = getMode(measureSpec); 18337 int size = getSize(measureSpec); 18338 18339 StringBuilder sb = new StringBuilder("MeasureSpec: "); 18340 18341 if (mode == UNSPECIFIED) 18342 sb.append("UNSPECIFIED "); 18343 else if (mode == EXACTLY) 18344 sb.append("EXACTLY "); 18345 else if (mode == AT_MOST) 18346 sb.append("AT_MOST "); 18347 else 18348 sb.append(mode).append(" "); 18349 18350 sb.append(size); 18351 return sb.toString(); 18352 } 18353 } 18354 18355 class CheckForLongPress implements Runnable { 18356 18357 private int mOriginalWindowAttachCount; 18358 18359 public void run() { 18360 if (isPressed() && (mParent != null) 18361 && mOriginalWindowAttachCount == mWindowAttachCount) { 18362 if (performLongClick()) { 18363 mHasPerformedLongPress = true; 18364 } 18365 } 18366 } 18367 18368 public void rememberWindowAttachCount() { 18369 mOriginalWindowAttachCount = mWindowAttachCount; 18370 } 18371 } 18372 18373 private final class CheckForTap implements Runnable { 18374 public void run() { 18375 mPrivateFlags &= ~PFLAG_PREPRESSED; 18376 setPressed(true); 18377 checkForLongClick(ViewConfiguration.getTapTimeout()); 18378 } 18379 } 18380 18381 private final class PerformClick implements Runnable { 18382 public void run() { 18383 performClick(); 18384 } 18385 } 18386 18387 /** @hide */ 18388 public void hackTurnOffWindowResizeAnim(boolean off) { 18389 mAttachInfo.mTurnOffWindowResizeAnim = off; 18390 } 18391 18392 /** 18393 * This method returns a ViewPropertyAnimator object, which can be used to animate 18394 * specific properties on this View. 18395 * 18396 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 18397 */ 18398 public ViewPropertyAnimator animate() { 18399 if (mAnimator == null) { 18400 mAnimator = new ViewPropertyAnimator(this); 18401 } 18402 return mAnimator; 18403 } 18404 18405 /** 18406 * Interface definition for a callback to be invoked when a hardware key event is 18407 * dispatched to this view. The callback will be invoked before the key event is 18408 * given to the view. This is only useful for hardware keyboards; a software input 18409 * method has no obligation to trigger this listener. 18410 */ 18411 public interface OnKeyListener { 18412 /** 18413 * Called when a hardware key is dispatched to a view. This allows listeners to 18414 * get a chance to respond before the target view. 18415 * <p>Key presses in software keyboards will generally NOT trigger this method, 18416 * although some may elect to do so in some situations. Do not assume a 18417 * software input method has to be key-based; even if it is, it may use key presses 18418 * in a different way than you expect, so there is no way to reliably catch soft 18419 * input key presses. 18420 * 18421 * @param v The view the key has been dispatched to. 18422 * @param keyCode The code for the physical key that was pressed 18423 * @param event The KeyEvent object containing full information about 18424 * the event. 18425 * @return True if the listener has consumed the event, false otherwise. 18426 */ 18427 boolean onKey(View v, int keyCode, KeyEvent event); 18428 } 18429 18430 /** 18431 * Interface definition for a callback to be invoked when a touch event is 18432 * dispatched to this view. The callback will be invoked before the touch 18433 * event is given to the view. 18434 */ 18435 public interface OnTouchListener { 18436 /** 18437 * Called when a touch event is dispatched to a view. This allows listeners to 18438 * get a chance to respond before the target view. 18439 * 18440 * @param v The view the touch event has been dispatched to. 18441 * @param event The MotionEvent object containing full information about 18442 * the event. 18443 * @return True if the listener has consumed the event, false otherwise. 18444 */ 18445 boolean onTouch(View v, MotionEvent event); 18446 } 18447 18448 /** 18449 * Interface definition for a callback to be invoked when a hover event is 18450 * dispatched to this view. The callback will be invoked before the hover 18451 * event is given to the view. 18452 */ 18453 public interface OnHoverListener { 18454 /** 18455 * Called when a hover event is dispatched to a view. This allows listeners to 18456 * get a chance to respond before the target view. 18457 * 18458 * @param v The view the hover event has been dispatched to. 18459 * @param event The MotionEvent object containing full information about 18460 * the event. 18461 * @return True if the listener has consumed the event, false otherwise. 18462 */ 18463 boolean onHover(View v, MotionEvent event); 18464 } 18465 18466 /** 18467 * Interface definition for a callback to be invoked when a generic motion event is 18468 * dispatched to this view. The callback will be invoked before the generic motion 18469 * event is given to the view. 18470 */ 18471 public interface OnGenericMotionListener { 18472 /** 18473 * Called when a generic motion event is dispatched to a view. This allows listeners to 18474 * get a chance to respond before the target view. 18475 * 18476 * @param v The view the generic motion event has been dispatched to. 18477 * @param event The MotionEvent object containing full information about 18478 * the event. 18479 * @return True if the listener has consumed the event, false otherwise. 18480 */ 18481 boolean onGenericMotion(View v, MotionEvent event); 18482 } 18483 18484 /** 18485 * Interface definition for a callback to be invoked when a view has been clicked and held. 18486 */ 18487 public interface OnLongClickListener { 18488 /** 18489 * Called when a view has been clicked and held. 18490 * 18491 * @param v The view that was clicked and held. 18492 * 18493 * @return true if the callback consumed the long click, false otherwise. 18494 */ 18495 boolean onLongClick(View v); 18496 } 18497 18498 /** 18499 * Interface definition for a callback to be invoked when a drag is being dispatched 18500 * to this view. The callback will be invoked before the hosting view's own 18501 * onDrag(event) method. If the listener wants to fall back to the hosting view's 18502 * onDrag(event) behavior, it should return 'false' from this callback. 18503 * 18504 * <div class="special reference"> 18505 * <h3>Developer Guides</h3> 18506 * <p>For a guide to implementing drag and drop features, read the 18507 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 18508 * </div> 18509 */ 18510 public interface OnDragListener { 18511 /** 18512 * Called when a drag event is dispatched to a view. This allows listeners 18513 * to get a chance to override base View behavior. 18514 * 18515 * @param v The View that received the drag event. 18516 * @param event The {@link android.view.DragEvent} object for the drag event. 18517 * @return {@code true} if the drag event was handled successfully, or {@code false} 18518 * if the drag event was not handled. Note that {@code false} will trigger the View 18519 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 18520 */ 18521 boolean onDrag(View v, DragEvent event); 18522 } 18523 18524 /** 18525 * Interface definition for a callback to be invoked when the focus state of 18526 * a view changed. 18527 */ 18528 public interface OnFocusChangeListener { 18529 /** 18530 * Called when the focus state of a view has changed. 18531 * 18532 * @param v The view whose state has changed. 18533 * @param hasFocus The new focus state of v. 18534 */ 18535 void onFocusChange(View v, boolean hasFocus); 18536 } 18537 18538 /** 18539 * Interface definition for a callback to be invoked when a view is clicked. 18540 */ 18541 public interface OnClickListener { 18542 /** 18543 * Called when a view has been clicked. 18544 * 18545 * @param v The view that was clicked. 18546 */ 18547 void onClick(View v); 18548 } 18549 18550 /** 18551 * Interface definition for a callback to be invoked when the context menu 18552 * for this view is being built. 18553 */ 18554 public interface OnCreateContextMenuListener { 18555 /** 18556 * Called when the context menu for this view is being built. It is not 18557 * safe to hold onto the menu after this method returns. 18558 * 18559 * @param menu The context menu that is being built 18560 * @param v The view for which the context menu is being built 18561 * @param menuInfo Extra information about the item for which the 18562 * context menu should be shown. This information will vary 18563 * depending on the class of v. 18564 */ 18565 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 18566 } 18567 18568 /** 18569 * Interface definition for a callback to be invoked when the status bar changes 18570 * visibility. This reports <strong>global</strong> changes to the system UI 18571 * state, not what the application is requesting. 18572 * 18573 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 18574 */ 18575 public interface OnSystemUiVisibilityChangeListener { 18576 /** 18577 * Called when the status bar changes visibility because of a call to 18578 * {@link View#setSystemUiVisibility(int)}. 18579 * 18580 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 18581 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 18582 * This tells you the <strong>global</strong> state of these UI visibility 18583 * flags, not what your app is currently applying. 18584 */ 18585 public void onSystemUiVisibilityChange(int visibility); 18586 } 18587 18588 /** 18589 * Interface definition for a callback to be invoked when this view is attached 18590 * or detached from its window. 18591 */ 18592 public interface OnAttachStateChangeListener { 18593 /** 18594 * Called when the view is attached to a window. 18595 * @param v The view that was attached 18596 */ 18597 public void onViewAttachedToWindow(View v); 18598 /** 18599 * Called when the view is detached from a window. 18600 * @param v The view that was detached 18601 */ 18602 public void onViewDetachedFromWindow(View v); 18603 } 18604 18605 private final class UnsetPressedState implements Runnable { 18606 public void run() { 18607 setPressed(false); 18608 } 18609 } 18610 18611 /** 18612 * Base class for derived classes that want to save and restore their own 18613 * state in {@link android.view.View#onSaveInstanceState()}. 18614 */ 18615 public static class BaseSavedState extends AbsSavedState { 18616 /** 18617 * Constructor used when reading from a parcel. Reads the state of the superclass. 18618 * 18619 * @param source 18620 */ 18621 public BaseSavedState(Parcel source) { 18622 super(source); 18623 } 18624 18625 /** 18626 * Constructor called by derived classes when creating their SavedState objects 18627 * 18628 * @param superState The state of the superclass of this view 18629 */ 18630 public BaseSavedState(Parcelable superState) { 18631 super(superState); 18632 } 18633 18634 public static final Parcelable.Creator<BaseSavedState> CREATOR = 18635 new Parcelable.Creator<BaseSavedState>() { 18636 public BaseSavedState createFromParcel(Parcel in) { 18637 return new BaseSavedState(in); 18638 } 18639 18640 public BaseSavedState[] newArray(int size) { 18641 return new BaseSavedState[size]; 18642 } 18643 }; 18644 } 18645 18646 /** 18647 * A set of information given to a view when it is attached to its parent 18648 * window. 18649 */ 18650 static class AttachInfo { 18651 interface Callbacks { 18652 void playSoundEffect(int effectId); 18653 boolean performHapticFeedback(int effectId, boolean always); 18654 } 18655 18656 /** 18657 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 18658 * to a Handler. This class contains the target (View) to invalidate and 18659 * the coordinates of the dirty rectangle. 18660 * 18661 * For performance purposes, this class also implements a pool of up to 18662 * POOL_LIMIT objects that get reused. This reduces memory allocations 18663 * whenever possible. 18664 */ 18665 static class InvalidateInfo { 18666 private static final int POOL_LIMIT = 10; 18667 18668 private static final SynchronizedPool<InvalidateInfo> sPool = 18669 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 18670 18671 View target; 18672 18673 int left; 18674 int top; 18675 int right; 18676 int bottom; 18677 18678 public static InvalidateInfo obtain() { 18679 InvalidateInfo instance = sPool.acquire(); 18680 return (instance != null) ? instance : new InvalidateInfo(); 18681 } 18682 18683 public void recycle() { 18684 target = null; 18685 sPool.release(this); 18686 } 18687 } 18688 18689 final IWindowSession mSession; 18690 18691 final IWindow mWindow; 18692 18693 final IBinder mWindowToken; 18694 18695 final Display mDisplay; 18696 18697 final Callbacks mRootCallbacks; 18698 18699 HardwareCanvas mHardwareCanvas; 18700 18701 IWindowId mIWindowId; 18702 WindowId mWindowId; 18703 18704 /** 18705 * The top view of the hierarchy. 18706 */ 18707 View mRootView; 18708 18709 IBinder mPanelParentWindowToken; 18710 Surface mSurface; 18711 18712 boolean mHardwareAccelerated; 18713 boolean mHardwareAccelerationRequested; 18714 HardwareRenderer mHardwareRenderer; 18715 18716 boolean mScreenOn; 18717 18718 /** 18719 * Scale factor used by the compatibility mode 18720 */ 18721 float mApplicationScale; 18722 18723 /** 18724 * Indicates whether the application is in compatibility mode 18725 */ 18726 boolean mScalingRequired; 18727 18728 /** 18729 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 18730 */ 18731 boolean mTurnOffWindowResizeAnim; 18732 18733 /** 18734 * Left position of this view's window 18735 */ 18736 int mWindowLeft; 18737 18738 /** 18739 * Top position of this view's window 18740 */ 18741 int mWindowTop; 18742 18743 /** 18744 * Indicates whether views need to use 32-bit drawing caches 18745 */ 18746 boolean mUse32BitDrawingCache; 18747 18748 /** 18749 * For windows that are full-screen but using insets to layout inside 18750 * of the screen areas, these are the current insets to appear inside 18751 * the overscan area of the display. 18752 */ 18753 final Rect mOverscanInsets = new Rect(); 18754 18755 /** 18756 * For windows that are full-screen but using insets to layout inside 18757 * of the screen decorations, these are the current insets for the 18758 * content of the window. 18759 */ 18760 final Rect mContentInsets = new Rect(); 18761 18762 /** 18763 * For windows that are full-screen but using insets to layout inside 18764 * of the screen decorations, these are the current insets for the 18765 * actual visible parts of the window. 18766 */ 18767 final Rect mVisibleInsets = new Rect(); 18768 18769 /** 18770 * The internal insets given by this window. This value is 18771 * supplied by the client (through 18772 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 18773 * be given to the window manager when changed to be used in laying 18774 * out windows behind it. 18775 */ 18776 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 18777 = new ViewTreeObserver.InternalInsetsInfo(); 18778 18779 /** 18780 * Set to true when mGivenInternalInsets is non-empty. 18781 */ 18782 boolean mHasNonEmptyGivenInternalInsets; 18783 18784 /** 18785 * All views in the window's hierarchy that serve as scroll containers, 18786 * used to determine if the window can be resized or must be panned 18787 * to adjust for a soft input area. 18788 */ 18789 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 18790 18791 final KeyEvent.DispatcherState mKeyDispatchState 18792 = new KeyEvent.DispatcherState(); 18793 18794 /** 18795 * Indicates whether the view's window currently has the focus. 18796 */ 18797 boolean mHasWindowFocus; 18798 18799 /** 18800 * The current visibility of the window. 18801 */ 18802 int mWindowVisibility; 18803 18804 /** 18805 * Indicates the time at which drawing started to occur. 18806 */ 18807 long mDrawingTime; 18808 18809 /** 18810 * Indicates whether or not ignoring the DIRTY_MASK flags. 18811 */ 18812 boolean mIgnoreDirtyState; 18813 18814 /** 18815 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 18816 * to avoid clearing that flag prematurely. 18817 */ 18818 boolean mSetIgnoreDirtyState = false; 18819 18820 /** 18821 * Indicates whether the view's window is currently in touch mode. 18822 */ 18823 boolean mInTouchMode; 18824 18825 /** 18826 * Indicates that ViewAncestor should trigger a global layout change 18827 * the next time it performs a traversal 18828 */ 18829 boolean mRecomputeGlobalAttributes; 18830 18831 /** 18832 * Always report new attributes at next traversal. 18833 */ 18834 boolean mForceReportNewAttributes; 18835 18836 /** 18837 * Set during a traveral if any views want to keep the screen on. 18838 */ 18839 boolean mKeepScreenOn; 18840 18841 /** 18842 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 18843 */ 18844 int mSystemUiVisibility; 18845 18846 /** 18847 * Hack to force certain system UI visibility flags to be cleared. 18848 */ 18849 int mDisabledSystemUiVisibility; 18850 18851 /** 18852 * Last global system UI visibility reported by the window manager. 18853 */ 18854 int mGlobalSystemUiVisibility; 18855 18856 /** 18857 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 18858 * attached. 18859 */ 18860 boolean mHasSystemUiListeners; 18861 18862 /** 18863 * Set if the window has requested to extend into the overscan region 18864 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 18865 */ 18866 boolean mOverscanRequested; 18867 18868 /** 18869 * Set if the visibility of any views has changed. 18870 */ 18871 boolean mViewVisibilityChanged; 18872 18873 /** 18874 * Set to true if a view has been scrolled. 18875 */ 18876 boolean mViewScrollChanged; 18877 18878 /** 18879 * Global to the view hierarchy used as a temporary for dealing with 18880 * x/y points in the transparent region computations. 18881 */ 18882 final int[] mTransparentLocation = new int[2]; 18883 18884 /** 18885 * Global to the view hierarchy used as a temporary for dealing with 18886 * x/y points in the ViewGroup.invalidateChild implementation. 18887 */ 18888 final int[] mInvalidateChildLocation = new int[2]; 18889 18890 18891 /** 18892 * Global to the view hierarchy used as a temporary for dealing with 18893 * x/y location when view is transformed. 18894 */ 18895 final float[] mTmpTransformLocation = new float[2]; 18896 18897 /** 18898 * The view tree observer used to dispatch global events like 18899 * layout, pre-draw, touch mode change, etc. 18900 */ 18901 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 18902 18903 /** 18904 * A Canvas used by the view hierarchy to perform bitmap caching. 18905 */ 18906 Canvas mCanvas; 18907 18908 /** 18909 * The view root impl. 18910 */ 18911 final ViewRootImpl mViewRootImpl; 18912 18913 /** 18914 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 18915 * handler can be used to pump events in the UI events queue. 18916 */ 18917 final Handler mHandler; 18918 18919 /** 18920 * Temporary for use in computing invalidate rectangles while 18921 * calling up the hierarchy. 18922 */ 18923 final Rect mTmpInvalRect = new Rect(); 18924 18925 /** 18926 * Temporary for use in computing hit areas with transformed views 18927 */ 18928 final RectF mTmpTransformRect = new RectF(); 18929 18930 /** 18931 * Temporary for use in transforming invalidation rect 18932 */ 18933 final Matrix mTmpMatrix = new Matrix(); 18934 18935 /** 18936 * Temporary for use in transforming invalidation rect 18937 */ 18938 final Transformation mTmpTransformation = new Transformation(); 18939 18940 /** 18941 * Temporary list for use in collecting focusable descendents of a view. 18942 */ 18943 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 18944 18945 /** 18946 * The id of the window for accessibility purposes. 18947 */ 18948 int mAccessibilityWindowId = View.NO_ID; 18949 18950 /** 18951 * Flags related to accessibility processing. 18952 * 18953 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 18954 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 18955 */ 18956 int mAccessibilityFetchFlags; 18957 18958 /** 18959 * The drawable for highlighting accessibility focus. 18960 */ 18961 Drawable mAccessibilityFocusDrawable; 18962 18963 /** 18964 * Show where the margins, bounds and layout bounds are for each view. 18965 */ 18966 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 18967 18968 /** 18969 * Point used to compute visible regions. 18970 */ 18971 final Point mPoint = new Point(); 18972 18973 /** 18974 * Used to track which View originated a requestLayout() call, used when 18975 * requestLayout() is called during layout. 18976 */ 18977 View mViewRequestingLayout; 18978 18979 /** 18980 * Creates a new set of attachment information with the specified 18981 * events handler and thread. 18982 * 18983 * @param handler the events handler the view must use 18984 */ 18985 AttachInfo(IWindowSession session, IWindow window, Display display, 18986 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 18987 mSession = session; 18988 mWindow = window; 18989 mWindowToken = window.asBinder(); 18990 mDisplay = display; 18991 mViewRootImpl = viewRootImpl; 18992 mHandler = handler; 18993 mRootCallbacks = effectPlayer; 18994 } 18995 } 18996 18997 /** 18998 * <p>ScrollabilityCache holds various fields used by a View when scrolling 18999 * is supported. This avoids keeping too many unused fields in most 19000 * instances of View.</p> 19001 */ 19002 private static class ScrollabilityCache implements Runnable { 19003 19004 /** 19005 * Scrollbars are not visible 19006 */ 19007 public static final int OFF = 0; 19008 19009 /** 19010 * Scrollbars are visible 19011 */ 19012 public static final int ON = 1; 19013 19014 /** 19015 * Scrollbars are fading away 19016 */ 19017 public static final int FADING = 2; 19018 19019 public boolean fadeScrollBars; 19020 19021 public int fadingEdgeLength; 19022 public int scrollBarDefaultDelayBeforeFade; 19023 public int scrollBarFadeDuration; 19024 19025 public int scrollBarSize; 19026 public ScrollBarDrawable scrollBar; 19027 public float[] interpolatorValues; 19028 public View host; 19029 19030 public final Paint paint; 19031 public final Matrix matrix; 19032 public Shader shader; 19033 19034 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 19035 19036 private static final float[] OPAQUE = { 255 }; 19037 private static final float[] TRANSPARENT = { 0.0f }; 19038 19039 /** 19040 * When fading should start. This time moves into the future every time 19041 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 19042 */ 19043 public long fadeStartTime; 19044 19045 19046 /** 19047 * The current state of the scrollbars: ON, OFF, or FADING 19048 */ 19049 public int state = OFF; 19050 19051 private int mLastColor; 19052 19053 public ScrollabilityCache(ViewConfiguration configuration, View host) { 19054 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 19055 scrollBarSize = configuration.getScaledScrollBarSize(); 19056 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 19057 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 19058 19059 paint = new Paint(); 19060 matrix = new Matrix(); 19061 // use use a height of 1, and then wack the matrix each time we 19062 // actually use it. 19063 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 19064 paint.setShader(shader); 19065 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 19066 19067 this.host = host; 19068 } 19069 19070 public void setFadeColor(int color) { 19071 if (color != mLastColor) { 19072 mLastColor = color; 19073 19074 if (color != 0) { 19075 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 19076 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 19077 paint.setShader(shader); 19078 // Restore the default transfer mode (src_over) 19079 paint.setXfermode(null); 19080 } else { 19081 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 19082 paint.setShader(shader); 19083 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 19084 } 19085 } 19086 } 19087 19088 public void run() { 19089 long now = AnimationUtils.currentAnimationTimeMillis(); 19090 if (now >= fadeStartTime) { 19091 19092 // the animation fades the scrollbars out by changing 19093 // the opacity (alpha) from fully opaque to fully 19094 // transparent 19095 int nextFrame = (int) now; 19096 int framesCount = 0; 19097 19098 Interpolator interpolator = scrollBarInterpolator; 19099 19100 // Start opaque 19101 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 19102 19103 // End transparent 19104 nextFrame += scrollBarFadeDuration; 19105 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 19106 19107 state = FADING; 19108 19109 // Kick off the fade animation 19110 host.invalidate(true); 19111 } 19112 } 19113 } 19114 19115 /** 19116 * Resuable callback for sending 19117 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 19118 */ 19119 private class SendViewScrolledAccessibilityEvent implements Runnable { 19120 public volatile boolean mIsPending; 19121 19122 public void run() { 19123 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 19124 mIsPending = false; 19125 } 19126 } 19127 19128 /** 19129 * <p> 19130 * This class represents a delegate that can be registered in a {@link View} 19131 * to enhance accessibility support via composition rather via inheritance. 19132 * It is specifically targeted to widget developers that extend basic View 19133 * classes i.e. classes in package android.view, that would like their 19134 * applications to be backwards compatible. 19135 * </p> 19136 * <div class="special reference"> 19137 * <h3>Developer Guides</h3> 19138 * <p>For more information about making applications accessible, read the 19139 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 19140 * developer guide.</p> 19141 * </div> 19142 * <p> 19143 * A scenario in which a developer would like to use an accessibility delegate 19144 * is overriding a method introduced in a later API version then the minimal API 19145 * version supported by the application. For example, the method 19146 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 19147 * in API version 4 when the accessibility APIs were first introduced. If a 19148 * developer would like his application to run on API version 4 devices (assuming 19149 * all other APIs used by the application are version 4 or lower) and take advantage 19150 * of this method, instead of overriding the method which would break the application's 19151 * backwards compatibility, he can override the corresponding method in this 19152 * delegate and register the delegate in the target View if the API version of 19153 * the system is high enough i.e. the API version is same or higher to the API 19154 * version that introduced 19155 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 19156 * </p> 19157 * <p> 19158 * Here is an example implementation: 19159 * </p> 19160 * <code><pre><p> 19161 * if (Build.VERSION.SDK_INT >= 14) { 19162 * // If the API version is equal of higher than the version in 19163 * // which onInitializeAccessibilityNodeInfo was introduced we 19164 * // register a delegate with a customized implementation. 19165 * View view = findViewById(R.id.view_id); 19166 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 19167 * public void onInitializeAccessibilityNodeInfo(View host, 19168 * AccessibilityNodeInfo info) { 19169 * // Let the default implementation populate the info. 19170 * super.onInitializeAccessibilityNodeInfo(host, info); 19171 * // Set some other information. 19172 * info.setEnabled(host.isEnabled()); 19173 * } 19174 * }); 19175 * } 19176 * </code></pre></p> 19177 * <p> 19178 * This delegate contains methods that correspond to the accessibility methods 19179 * in View. If a delegate has been specified the implementation in View hands 19180 * off handling to the corresponding method in this delegate. The default 19181 * implementation the delegate methods behaves exactly as the corresponding 19182 * method in View for the case of no accessibility delegate been set. Hence, 19183 * to customize the behavior of a View method, clients can override only the 19184 * corresponding delegate method without altering the behavior of the rest 19185 * accessibility related methods of the host view. 19186 * </p> 19187 */ 19188 public static class AccessibilityDelegate { 19189 19190 /** 19191 * Sends an accessibility event of the given type. If accessibility is not 19192 * enabled this method has no effect. 19193 * <p> 19194 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 19195 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 19196 * been set. 19197 * </p> 19198 * 19199 * @param host The View hosting the delegate. 19200 * @param eventType The type of the event to send. 19201 * 19202 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 19203 */ 19204 public void sendAccessibilityEvent(View host, int eventType) { 19205 host.sendAccessibilityEventInternal(eventType); 19206 } 19207 19208 /** 19209 * Performs the specified accessibility action on the view. For 19210 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 19211 * <p> 19212 * The default implementation behaves as 19213 * {@link View#performAccessibilityAction(int, Bundle) 19214 * View#performAccessibilityAction(int, Bundle)} for the case of 19215 * no accessibility delegate been set. 19216 * </p> 19217 * 19218 * @param action The action to perform. 19219 * @return Whether the action was performed. 19220 * 19221 * @see View#performAccessibilityAction(int, Bundle) 19222 * View#performAccessibilityAction(int, Bundle) 19223 */ 19224 public boolean performAccessibilityAction(View host, int action, Bundle args) { 19225 return host.performAccessibilityActionInternal(action, args); 19226 } 19227 19228 /** 19229 * Sends an accessibility event. This method behaves exactly as 19230 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 19231 * empty {@link AccessibilityEvent} and does not perform a check whether 19232 * accessibility is enabled. 19233 * <p> 19234 * The default implementation behaves as 19235 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19236 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 19237 * the case of no accessibility delegate been set. 19238 * </p> 19239 * 19240 * @param host The View hosting the delegate. 19241 * @param event The event to send. 19242 * 19243 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19244 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19245 */ 19246 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 19247 host.sendAccessibilityEventUncheckedInternal(event); 19248 } 19249 19250 /** 19251 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 19252 * to its children for adding their text content to the event. 19253 * <p> 19254 * The default implementation behaves as 19255 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19256 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 19257 * the case of no accessibility delegate been set. 19258 * </p> 19259 * 19260 * @param host The View hosting the delegate. 19261 * @param event The event. 19262 * @return True if the event population was completed. 19263 * 19264 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19265 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19266 */ 19267 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 19268 return host.dispatchPopulateAccessibilityEventInternal(event); 19269 } 19270 19271 /** 19272 * Gives a chance to the host View to populate the accessibility event with its 19273 * text content. 19274 * <p> 19275 * The default implementation behaves as 19276 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 19277 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 19278 * the case of no accessibility delegate been set. 19279 * </p> 19280 * 19281 * @param host The View hosting the delegate. 19282 * @param event The accessibility event which to populate. 19283 * 19284 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 19285 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 19286 */ 19287 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 19288 host.onPopulateAccessibilityEventInternal(event); 19289 } 19290 19291 /** 19292 * Initializes an {@link AccessibilityEvent} with information about the 19293 * the host View which is the event source. 19294 * <p> 19295 * The default implementation behaves as 19296 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 19297 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 19298 * the case of no accessibility delegate been set. 19299 * </p> 19300 * 19301 * @param host The View hosting the delegate. 19302 * @param event The event to initialize. 19303 * 19304 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 19305 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 19306 */ 19307 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 19308 host.onInitializeAccessibilityEventInternal(event); 19309 } 19310 19311 /** 19312 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 19313 * <p> 19314 * The default implementation behaves as 19315 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19316 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 19317 * the case of no accessibility delegate been set. 19318 * </p> 19319 * 19320 * @param host The View hosting the delegate. 19321 * @param info The instance to initialize. 19322 * 19323 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19324 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19325 */ 19326 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 19327 host.onInitializeAccessibilityNodeInfoInternal(info); 19328 } 19329 19330 /** 19331 * Called when a child of the host View has requested sending an 19332 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 19333 * to augment the event. 19334 * <p> 19335 * The default implementation behaves as 19336 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19337 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 19338 * the case of no accessibility delegate been set. 19339 * </p> 19340 * 19341 * @param host The View hosting the delegate. 19342 * @param child The child which requests sending the event. 19343 * @param event The event to be sent. 19344 * @return True if the event should be sent 19345 * 19346 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19347 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19348 */ 19349 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 19350 AccessibilityEvent event) { 19351 return host.onRequestSendAccessibilityEventInternal(child, event); 19352 } 19353 19354 /** 19355 * Gets the provider for managing a virtual view hierarchy rooted at this View 19356 * and reported to {@link android.accessibilityservice.AccessibilityService}s 19357 * that explore the window content. 19358 * <p> 19359 * The default implementation behaves as 19360 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 19361 * the case of no accessibility delegate been set. 19362 * </p> 19363 * 19364 * @return The provider. 19365 * 19366 * @see AccessibilityNodeProvider 19367 */ 19368 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 19369 return null; 19370 } 19371 19372 /** 19373 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 19374 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 19375 * This method is responsible for obtaining an accessibility node info from a 19376 * pool of reusable instances and calling 19377 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 19378 * view to initialize the former. 19379 * <p> 19380 * <strong>Note:</strong> The client is responsible for recycling the obtained 19381 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 19382 * creation. 19383 * </p> 19384 * <p> 19385 * The default implementation behaves as 19386 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 19387 * the case of no accessibility delegate been set. 19388 * </p> 19389 * @return A populated {@link AccessibilityNodeInfo}. 19390 * 19391 * @see AccessibilityNodeInfo 19392 * 19393 * @hide 19394 */ 19395 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 19396 return host.createAccessibilityNodeInfoInternal(); 19397 } 19398 } 19399 19400 private class MatchIdPredicate implements Predicate<View> { 19401 public int mId; 19402 19403 @Override 19404 public boolean apply(View view) { 19405 return (view.mID == mId); 19406 } 19407 } 19408 19409 private class MatchLabelForPredicate implements Predicate<View> { 19410 private int mLabeledId; 19411 19412 @Override 19413 public boolean apply(View view) { 19414 return (view.mLabelForId == mLabeledId); 19415 } 19416 } 19417 19418 private class SendViewStateChangedAccessibilityEvent implements Runnable { 19419 private int mChangeTypes = 0; 19420 private boolean mPosted; 19421 private boolean mPostedWithDelay; 19422 private long mLastEventTimeMillis; 19423 19424 @Override 19425 public void run() { 19426 mPosted = false; 19427 mPostedWithDelay = false; 19428 mLastEventTimeMillis = SystemClock.uptimeMillis(); 19429 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 19430 final AccessibilityEvent event = AccessibilityEvent.obtain(); 19431 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 19432 event.setContentChangeTypes(mChangeTypes); 19433 sendAccessibilityEventUnchecked(event); 19434 } 19435 mChangeTypes = 0; 19436 } 19437 19438 public void runOrPost(int changeType) { 19439 mChangeTypes |= changeType; 19440 19441 // If this is a live region or the child of a live region, collect 19442 // all events from this frame and send them on the next frame. 19443 if (inLiveRegion()) { 19444 // If we're already posted with a delay, remove that. 19445 if (mPostedWithDelay) { 19446 removeCallbacks(this); 19447 mPostedWithDelay = false; 19448 } 19449 // Only post if we're not already posted. 19450 if (!mPosted) { 19451 post(this); 19452 mPosted = true; 19453 } 19454 return; 19455 } 19456 19457 if (mPosted) { 19458 return; 19459 } 19460 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 19461 final long minEventIntevalMillis = 19462 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 19463 if (timeSinceLastMillis >= minEventIntevalMillis) { 19464 removeCallbacks(this); 19465 run(); 19466 } else { 19467 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 19468 mPosted = true; 19469 mPostedWithDelay = true; 19470 } 19471 } 19472 } 19473 19474 private boolean inLiveRegion() { 19475 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 19476 return true; 19477 } 19478 19479 ViewParent parent = getParent(); 19480 while (parent instanceof View) { 19481 if (((View) parent).getAccessibilityLiveRegion() 19482 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 19483 return true; 19484 } 19485 parent = parent.getParent(); 19486 } 19487 19488 return false; 19489 } 19490 19491 /** 19492 * Dump all private flags in readable format, useful for documentation and 19493 * sanity checking. 19494 */ 19495 private static void dumpFlags() { 19496 final HashMap<String, String> found = Maps.newHashMap(); 19497 try { 19498 for (Field field : View.class.getDeclaredFields()) { 19499 final int modifiers = field.getModifiers(); 19500 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 19501 if (field.getType().equals(int.class)) { 19502 final int value = field.getInt(null); 19503 dumpFlag(found, field.getName(), value); 19504 } else if (field.getType().equals(int[].class)) { 19505 final int[] values = (int[]) field.get(null); 19506 for (int i = 0; i < values.length; i++) { 19507 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 19508 } 19509 } 19510 } 19511 } 19512 } catch (IllegalAccessException e) { 19513 throw new RuntimeException(e); 19514 } 19515 19516 final ArrayList<String> keys = Lists.newArrayList(); 19517 keys.addAll(found.keySet()); 19518 Collections.sort(keys); 19519 for (String key : keys) { 19520 Log.d(VIEW_LOG_TAG, found.get(key)); 19521 } 19522 } 19523 19524 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 19525 // Sort flags by prefix, then by bits, always keeping unique keys 19526 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 19527 final int prefix = name.indexOf('_'); 19528 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 19529 final String output = bits + " " + name; 19530 found.put(key, output); 19531 } 19532 } 19533