View.java revision 2a7a6ca00ab176105b5bbfa6b17bb0dcd058d517
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.content.ClipData; 20import android.content.Context; 21import android.content.res.Configuration; 22import android.content.res.Resources; 23import android.content.res.TypedArray; 24import android.graphics.Bitmap; 25import android.graphics.Camera; 26import android.graphics.Canvas; 27import android.graphics.Insets; 28import android.graphics.Interpolator; 29import android.graphics.LinearGradient; 30import android.graphics.Matrix; 31import android.graphics.Paint; 32import android.graphics.PixelFormat; 33import android.graphics.Point; 34import android.graphics.PorterDuff; 35import android.graphics.PorterDuffXfermode; 36import android.graphics.Rect; 37import android.graphics.RectF; 38import android.graphics.Region; 39import android.graphics.Shader; 40import android.graphics.drawable.ColorDrawable; 41import android.graphics.drawable.Drawable; 42import android.os.Bundle; 43import android.os.Handler; 44import android.os.IBinder; 45import android.os.Parcel; 46import android.os.Parcelable; 47import android.os.RemoteException; 48import android.os.SystemClock; 49import android.os.SystemProperties; 50import android.util.AttributeSet; 51import android.util.FloatProperty; 52import android.util.LocaleUtil; 53import android.util.Log; 54import android.util.Pool; 55import android.util.Poolable; 56import android.util.PoolableManager; 57import android.util.Pools; 58import android.util.Property; 59import android.util.SparseArray; 60import android.util.TypedValue; 61import android.view.ContextMenu.ContextMenuInfo; 62import android.view.AccessibilityIterators.TextSegmentIterator; 63import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 64import android.view.AccessibilityIterators.WordTextSegmentIterator; 65import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 66import android.view.accessibility.AccessibilityEvent; 67import android.view.accessibility.AccessibilityEventSource; 68import android.view.accessibility.AccessibilityManager; 69import android.view.accessibility.AccessibilityNodeInfo; 70import android.view.accessibility.AccessibilityNodeProvider; 71import android.view.animation.Animation; 72import android.view.animation.AnimationUtils; 73import android.view.animation.Transformation; 74import android.view.inputmethod.EditorInfo; 75import android.view.inputmethod.InputConnection; 76import android.view.inputmethod.InputMethodManager; 77import android.widget.ScrollBarDrawable; 78 79import static android.os.Build.VERSION_CODES.*; 80import static java.lang.Math.max; 81 82import com.android.internal.R; 83import com.android.internal.util.Predicate; 84import com.android.internal.view.menu.MenuBuilder; 85 86import java.lang.ref.WeakReference; 87import java.lang.reflect.InvocationTargetException; 88import java.lang.reflect.Method; 89import java.util.ArrayList; 90import java.util.Arrays; 91import java.util.Locale; 92import java.util.concurrent.CopyOnWriteArrayList; 93 94/** 95 * <p> 96 * This class represents the basic building block for user interface components. A View 97 * occupies a rectangular area on the screen and is responsible for drawing and 98 * event handling. View is the base class for <em>widgets</em>, which are 99 * used to create interactive UI components (buttons, text fields, etc.). The 100 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 101 * are invisible containers that hold other Views (or other ViewGroups) and define 102 * their layout properties. 103 * </p> 104 * 105 * <div class="special reference"> 106 * <h3>Developer Guides</h3> 107 * <p>For information about using this class to develop your application's user interface, 108 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 109 * </div> 110 * 111 * <a name="Using"></a> 112 * <h3>Using Views</h3> 113 * <p> 114 * All of the views in a window are arranged in a single tree. You can add views 115 * either from code or by specifying a tree of views in one or more XML layout 116 * files. There are many specialized subclasses of views that act as controls or 117 * are capable of displaying text, images, or other content. 118 * </p> 119 * <p> 120 * Once you have created a tree of views, there are typically a few types of 121 * common operations you may wish to perform: 122 * <ul> 123 * <li><strong>Set properties:</strong> for example setting the text of a 124 * {@link android.widget.TextView}. The available properties and the methods 125 * that set them will vary among the different subclasses of views. Note that 126 * properties that are known at build time can be set in the XML layout 127 * files.</li> 128 * <li><strong>Set focus:</strong> The framework will handled moving focus in 129 * response to user input. To force focus to a specific view, call 130 * {@link #requestFocus}.</li> 131 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 132 * that will be notified when something interesting happens to the view. For 133 * example, all views will let you set a listener to be notified when the view 134 * gains or loses focus. You can register such a listener using 135 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 136 * Other view subclasses offer more specialized listeners. For example, a Button 137 * exposes a listener to notify clients when the button is clicked.</li> 138 * <li><strong>Set visibility:</strong> You can hide or show views using 139 * {@link #setVisibility(int)}.</li> 140 * </ul> 141 * </p> 142 * <p><em> 143 * Note: The Android framework is responsible for measuring, laying out and 144 * drawing views. You should not call methods that perform these actions on 145 * views yourself unless you are actually implementing a 146 * {@link android.view.ViewGroup}. 147 * </em></p> 148 * 149 * <a name="Lifecycle"></a> 150 * <h3>Implementing a Custom View</h3> 151 * 152 * <p> 153 * To implement a custom view, you will usually begin by providing overrides for 154 * some of the standard methods that the framework calls on all views. You do 155 * not need to override all of these methods. In fact, you can start by just 156 * overriding {@link #onDraw(android.graphics.Canvas)}. 157 * <table border="2" width="85%" align="center" cellpadding="5"> 158 * <thead> 159 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 160 * </thead> 161 * 162 * <tbody> 163 * <tr> 164 * <td rowspan="2">Creation</td> 165 * <td>Constructors</td> 166 * <td>There is a form of the constructor that are called when the view 167 * is created from code and a form that is called when the view is 168 * inflated from a layout file. The second form should parse and apply 169 * any attributes defined in the layout file. 170 * </td> 171 * </tr> 172 * <tr> 173 * <td><code>{@link #onFinishInflate()}</code></td> 174 * <td>Called after a view and all of its children has been inflated 175 * from XML.</td> 176 * </tr> 177 * 178 * <tr> 179 * <td rowspan="3">Layout</td> 180 * <td><code>{@link #onMeasure(int, int)}</code></td> 181 * <td>Called to determine the size requirements for this view and all 182 * of its children. 183 * </td> 184 * </tr> 185 * <tr> 186 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 187 * <td>Called when this view should assign a size and position to all 188 * of its children. 189 * </td> 190 * </tr> 191 * <tr> 192 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 193 * <td>Called when the size of this view has changed. 194 * </td> 195 * </tr> 196 * 197 * <tr> 198 * <td>Drawing</td> 199 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 200 * <td>Called when the view should render its content. 201 * </td> 202 * </tr> 203 * 204 * <tr> 205 * <td rowspan="4">Event processing</td> 206 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 207 * <td>Called when a new key event occurs. 208 * </td> 209 * </tr> 210 * <tr> 211 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 212 * <td>Called when a key up event occurs. 213 * </td> 214 * </tr> 215 * <tr> 216 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 217 * <td>Called when a trackball motion event occurs. 218 * </td> 219 * </tr> 220 * <tr> 221 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 222 * <td>Called when a touch screen motion event occurs. 223 * </td> 224 * </tr> 225 * 226 * <tr> 227 * <td rowspan="2">Focus</td> 228 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 229 * <td>Called when the view gains or loses focus. 230 * </td> 231 * </tr> 232 * 233 * <tr> 234 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 235 * <td>Called when the window containing the view gains or loses focus. 236 * </td> 237 * </tr> 238 * 239 * <tr> 240 * <td rowspan="3">Attaching</td> 241 * <td><code>{@link #onAttachedToWindow()}</code></td> 242 * <td>Called when the view is attached to a window. 243 * </td> 244 * </tr> 245 * 246 * <tr> 247 * <td><code>{@link #onDetachedFromWindow}</code></td> 248 * <td>Called when the view is detached from its window. 249 * </td> 250 * </tr> 251 * 252 * <tr> 253 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 254 * <td>Called when the visibility of the window containing the view 255 * has changed. 256 * </td> 257 * </tr> 258 * </tbody> 259 * 260 * </table> 261 * </p> 262 * 263 * <a name="IDs"></a> 264 * <h3>IDs</h3> 265 * Views may have an integer id associated with them. These ids are typically 266 * assigned in the layout XML files, and are used to find specific views within 267 * the view tree. A common pattern is to: 268 * <ul> 269 * <li>Define a Button in the layout file and assign it a unique ID. 270 * <pre> 271 * <Button 272 * android:id="@+id/my_button" 273 * android:layout_width="wrap_content" 274 * android:layout_height="wrap_content" 275 * android:text="@string/my_button_text"/> 276 * </pre></li> 277 * <li>From the onCreate method of an Activity, find the Button 278 * <pre class="prettyprint"> 279 * Button myButton = (Button) findViewById(R.id.my_button); 280 * </pre></li> 281 * </ul> 282 * <p> 283 * View IDs need not be unique throughout the tree, but it is good practice to 284 * ensure that they are at least unique within the part of the tree you are 285 * searching. 286 * </p> 287 * 288 * <a name="Position"></a> 289 * <h3>Position</h3> 290 * <p> 291 * The geometry of a view is that of a rectangle. A view has a location, 292 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 293 * two dimensions, expressed as a width and a height. The unit for location 294 * and dimensions is the pixel. 295 * </p> 296 * 297 * <p> 298 * It is possible to retrieve the location of a view by invoking the methods 299 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 300 * coordinate of the rectangle representing the view. The latter returns the 301 * top, or Y, coordinate of the rectangle representing the view. These methods 302 * both return the location of the view relative to its parent. For instance, 303 * when getLeft() returns 20, that means the view is located 20 pixels to the 304 * right of the left edge of its direct parent. 305 * </p> 306 * 307 * <p> 308 * In addition, several convenience methods are offered to avoid unnecessary 309 * computations, namely {@link #getRight()} and {@link #getBottom()}. 310 * These methods return the coordinates of the right and bottom edges of the 311 * rectangle representing the view. For instance, calling {@link #getRight()} 312 * is similar to the following computation: <code>getLeft() + getWidth()</code> 313 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 314 * </p> 315 * 316 * <a name="SizePaddingMargins"></a> 317 * <h3>Size, padding and margins</h3> 318 * <p> 319 * The size of a view is expressed with a width and a height. A view actually 320 * possess two pairs of width and height values. 321 * </p> 322 * 323 * <p> 324 * The first pair is known as <em>measured width</em> and 325 * <em>measured height</em>. These dimensions define how big a view wants to be 326 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 327 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 328 * and {@link #getMeasuredHeight()}. 329 * </p> 330 * 331 * <p> 332 * The second pair is simply known as <em>width</em> and <em>height</em>, or 333 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 334 * dimensions define the actual size of the view on screen, at drawing time and 335 * after layout. These values may, but do not have to, be different from the 336 * measured width and height. The width and height can be obtained by calling 337 * {@link #getWidth()} and {@link #getHeight()}. 338 * </p> 339 * 340 * <p> 341 * To measure its dimensions, a view takes into account its padding. The padding 342 * is expressed in pixels for the left, top, right and bottom parts of the view. 343 * Padding can be used to offset the content of the view by a specific amount of 344 * pixels. For instance, a left padding of 2 will push the view's content by 345 * 2 pixels to the right of the left edge. Padding can be set using the 346 * {@link #setPadding(int, int, int, int)} method and queried by calling 347 * {@link #getPaddingLeft()}, {@link #getPaddingTop()}, {@link #getPaddingRight()}, 348 * {@link #getPaddingBottom()}. 349 * </p> 350 * 351 * <p> 352 * Even though a view can define a padding, it does not provide any support for 353 * margins. However, view groups provide such a support. Refer to 354 * {@link android.view.ViewGroup} and 355 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 356 * </p> 357 * 358 * <a name="Layout"></a> 359 * <h3>Layout</h3> 360 * <p> 361 * Layout is a two pass process: a measure pass and a layout pass. The measuring 362 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 363 * of the view tree. Each view pushes dimension specifications down the tree 364 * during the recursion. At the end of the measure pass, every view has stored 365 * its measurements. The second pass happens in 366 * {@link #layout(int,int,int,int)} and is also top-down. During 367 * this pass each parent is responsible for positioning all of its children 368 * using the sizes computed in the measure pass. 369 * </p> 370 * 371 * <p> 372 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 373 * {@link #getMeasuredHeight()} values must be set, along with those for all of 374 * that view's descendants. A view's measured width and measured height values 375 * must respect the constraints imposed by the view's parents. This guarantees 376 * that at the end of the measure pass, all parents accept all of their 377 * children's measurements. A parent view may call measure() more than once on 378 * its children. For example, the parent may measure each child once with 379 * unspecified dimensions to find out how big they want to be, then call 380 * measure() on them again with actual numbers if the sum of all the children's 381 * unconstrained sizes is too big or too small. 382 * </p> 383 * 384 * <p> 385 * The measure pass uses two classes to communicate dimensions. The 386 * {@link MeasureSpec} class is used by views to tell their parents how they 387 * want to be measured and positioned. The base LayoutParams class just 388 * describes how big the view wants to be for both width and height. For each 389 * dimension, it can specify one of: 390 * <ul> 391 * <li> an exact number 392 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 393 * (minus padding) 394 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 395 * enclose its content (plus padding). 396 * </ul> 397 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 398 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 399 * an X and Y value. 400 * </p> 401 * 402 * <p> 403 * MeasureSpecs are used to push requirements down the tree from parent to 404 * child. A MeasureSpec can be in one of three modes: 405 * <ul> 406 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 407 * of a child view. For example, a LinearLayout may call measure() on its child 408 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 409 * tall the child view wants to be given a width of 240 pixels. 410 * <li>EXACTLY: This is used by the parent to impose an exact size on the 411 * child. The child must use this size, and guarantee that all of its 412 * descendants will fit within this size. 413 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 414 * child. The child must gurantee that it and all of its descendants will fit 415 * within this size. 416 * </ul> 417 * </p> 418 * 419 * <p> 420 * To intiate a layout, call {@link #requestLayout}. This method is typically 421 * called by a view on itself when it believes that is can no longer fit within 422 * its current bounds. 423 * </p> 424 * 425 * <a name="Drawing"></a> 426 * <h3>Drawing</h3> 427 * <p> 428 * Drawing is handled by walking the tree and rendering each view that 429 * intersects the invalid region. Because the tree is traversed in-order, 430 * this means that parents will draw before (i.e., behind) their children, with 431 * siblings drawn in the order they appear in the tree. 432 * If you set a background drawable for a View, then the View will draw it for you 433 * before calling back to its <code>onDraw()</code> method. 434 * </p> 435 * 436 * <p> 437 * Note that the framework will not draw views that are not in the invalid region. 438 * </p> 439 * 440 * <p> 441 * To force a view to draw, call {@link #invalidate()}. 442 * </p> 443 * 444 * <a name="EventHandlingThreading"></a> 445 * <h3>Event Handling and Threading</h3> 446 * <p> 447 * The basic cycle of a view is as follows: 448 * <ol> 449 * <li>An event comes in and is dispatched to the appropriate view. The view 450 * handles the event and notifies any listeners.</li> 451 * <li>If in the course of processing the event, the view's bounds may need 452 * to be changed, the view will call {@link #requestLayout()}.</li> 453 * <li>Similarly, if in the course of processing the event the view's appearance 454 * may need to be changed, the view will call {@link #invalidate()}.</li> 455 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 456 * the framework will take care of measuring, laying out, and drawing the tree 457 * as appropriate.</li> 458 * </ol> 459 * </p> 460 * 461 * <p><em>Note: The entire view tree is single threaded. You must always be on 462 * the UI thread when calling any method on any view.</em> 463 * If you are doing work on other threads and want to update the state of a view 464 * from that thread, you should use a {@link Handler}. 465 * </p> 466 * 467 * <a name="FocusHandling"></a> 468 * <h3>Focus Handling</h3> 469 * <p> 470 * The framework will handle routine focus movement in response to user input. 471 * This includes changing the focus as views are removed or hidden, or as new 472 * views become available. Views indicate their willingness to take focus 473 * through the {@link #isFocusable} method. To change whether a view can take 474 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 475 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 476 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 477 * </p> 478 * <p> 479 * Focus movement is based on an algorithm which finds the nearest neighbor in a 480 * given direction. In rare cases, the default algorithm may not match the 481 * intended behavior of the developer. In these situations, you can provide 482 * explicit overrides by using these XML attributes in the layout file: 483 * <pre> 484 * nextFocusDown 485 * nextFocusLeft 486 * nextFocusRight 487 * nextFocusUp 488 * </pre> 489 * </p> 490 * 491 * 492 * <p> 493 * To get a particular view to take focus, call {@link #requestFocus()}. 494 * </p> 495 * 496 * <a name="TouchMode"></a> 497 * <h3>Touch Mode</h3> 498 * <p> 499 * When a user is navigating a user interface via directional keys such as a D-pad, it is 500 * necessary to give focus to actionable items such as buttons so the user can see 501 * what will take input. If the device has touch capabilities, however, and the user 502 * begins interacting with the interface by touching it, it is no longer necessary to 503 * always highlight, or give focus to, a particular view. This motivates a mode 504 * for interaction named 'touch mode'. 505 * </p> 506 * <p> 507 * For a touch capable device, once the user touches the screen, the device 508 * will enter touch mode. From this point onward, only views for which 509 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 510 * Other views that are touchable, like buttons, will not take focus when touched; they will 511 * only fire the on click listeners. 512 * </p> 513 * <p> 514 * Any time a user hits a directional key, such as a D-pad direction, the view device will 515 * exit touch mode, and find a view to take focus, so that the user may resume interacting 516 * with the user interface without touching the screen again. 517 * </p> 518 * <p> 519 * The touch mode state is maintained across {@link android.app.Activity}s. Call 520 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 521 * </p> 522 * 523 * <a name="Scrolling"></a> 524 * <h3>Scrolling</h3> 525 * <p> 526 * The framework provides basic support for views that wish to internally 527 * scroll their content. This includes keeping track of the X and Y scroll 528 * offset as well as mechanisms for drawing scrollbars. See 529 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 530 * {@link #awakenScrollBars()} for more details. 531 * </p> 532 * 533 * <a name="Tags"></a> 534 * <h3>Tags</h3> 535 * <p> 536 * Unlike IDs, tags are not used to identify views. Tags are essentially an 537 * extra piece of information that can be associated with a view. They are most 538 * often used as a convenience to store data related to views in the views 539 * themselves rather than by putting them in a separate structure. 540 * </p> 541 * 542 * <a name="Properties"></a> 543 * <h3>Properties</h3> 544 * <p> 545 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 546 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 547 * available both in the {@link Property} form as well as in similarly-named setter/getter 548 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 549 * be used to set persistent state associated with these rendering-related properties on the view. 550 * The properties and methods can also be used in conjunction with 551 * {@link android.animation.Animator Animator}-based animations, described more in the 552 * <a href="#Animation">Animation</a> section. 553 * </p> 554 * 555 * <a name="Animation"></a> 556 * <h3>Animation</h3> 557 * <p> 558 * Starting with Android 3.0, the preferred way of animating views is to use the 559 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 560 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 561 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 562 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 563 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 564 * makes animating these View properties particularly easy and efficient. 565 * </p> 566 * <p> 567 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 568 * You can attach an {@link Animation} object to a view using 569 * {@link #setAnimation(Animation)} or 570 * {@link #startAnimation(Animation)}. The animation can alter the scale, 571 * rotation, translation and alpha of a view over time. If the animation is 572 * attached to a view that has children, the animation will affect the entire 573 * subtree rooted by that node. When an animation is started, the framework will 574 * take care of redrawing the appropriate views until the animation completes. 575 * </p> 576 * 577 * <a name="Security"></a> 578 * <h3>Security</h3> 579 * <p> 580 * Sometimes it is essential that an application be able to verify that an action 581 * is being performed with the full knowledge and consent of the user, such as 582 * granting a permission request, making a purchase or clicking on an advertisement. 583 * Unfortunately, a malicious application could try to spoof the user into 584 * performing these actions, unaware, by concealing the intended purpose of the view. 585 * As a remedy, the framework offers a touch filtering mechanism that can be used to 586 * improve the security of views that provide access to sensitive functionality. 587 * </p><p> 588 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 589 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 590 * will discard touches that are received whenever the view's window is obscured by 591 * another visible window. As a result, the view will not receive touches whenever a 592 * toast, dialog or other window appears above the view's window. 593 * </p><p> 594 * For more fine-grained control over security, consider overriding the 595 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 596 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 597 * </p> 598 * 599 * @attr ref android.R.styleable#View_alpha 600 * @attr ref android.R.styleable#View_background 601 * @attr ref android.R.styleable#View_clickable 602 * @attr ref android.R.styleable#View_contentDescription 603 * @attr ref android.R.styleable#View_drawingCacheQuality 604 * @attr ref android.R.styleable#View_duplicateParentState 605 * @attr ref android.R.styleable#View_id 606 * @attr ref android.R.styleable#View_requiresFadingEdge 607 * @attr ref android.R.styleable#View_fadeScrollbars 608 * @attr ref android.R.styleable#View_fadingEdgeLength 609 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 610 * @attr ref android.R.styleable#View_fitsSystemWindows 611 * @attr ref android.R.styleable#View_isScrollContainer 612 * @attr ref android.R.styleable#View_focusable 613 * @attr ref android.R.styleable#View_focusableInTouchMode 614 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 615 * @attr ref android.R.styleable#View_keepScreenOn 616 * @attr ref android.R.styleable#View_layerType 617 * @attr ref android.R.styleable#View_longClickable 618 * @attr ref android.R.styleable#View_minHeight 619 * @attr ref android.R.styleable#View_minWidth 620 * @attr ref android.R.styleable#View_nextFocusDown 621 * @attr ref android.R.styleable#View_nextFocusLeft 622 * @attr ref android.R.styleable#View_nextFocusRight 623 * @attr ref android.R.styleable#View_nextFocusUp 624 * @attr ref android.R.styleable#View_onClick 625 * @attr ref android.R.styleable#View_padding 626 * @attr ref android.R.styleable#View_paddingBottom 627 * @attr ref android.R.styleable#View_paddingLeft 628 * @attr ref android.R.styleable#View_paddingRight 629 * @attr ref android.R.styleable#View_paddingTop 630 * @attr ref android.R.styleable#View_saveEnabled 631 * @attr ref android.R.styleable#View_rotation 632 * @attr ref android.R.styleable#View_rotationX 633 * @attr ref android.R.styleable#View_rotationY 634 * @attr ref android.R.styleable#View_scaleX 635 * @attr ref android.R.styleable#View_scaleY 636 * @attr ref android.R.styleable#View_scrollX 637 * @attr ref android.R.styleable#View_scrollY 638 * @attr ref android.R.styleable#View_scrollbarSize 639 * @attr ref android.R.styleable#View_scrollbarStyle 640 * @attr ref android.R.styleable#View_scrollbars 641 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 642 * @attr ref android.R.styleable#View_scrollbarFadeDuration 643 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 644 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 645 * @attr ref android.R.styleable#View_scrollbarThumbVertical 646 * @attr ref android.R.styleable#View_scrollbarTrackVertical 647 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 648 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 649 * @attr ref android.R.styleable#View_soundEffectsEnabled 650 * @attr ref android.R.styleable#View_tag 651 * @attr ref android.R.styleable#View_transformPivotX 652 * @attr ref android.R.styleable#View_transformPivotY 653 * @attr ref android.R.styleable#View_translationX 654 * @attr ref android.R.styleable#View_translationY 655 * @attr ref android.R.styleable#View_visibility 656 * 657 * @see android.view.ViewGroup 658 */ 659public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback, 660 AccessibilityEventSource { 661 private static final boolean DBG = false; 662 663 /** 664 * The logging tag used by this class with android.util.Log. 665 */ 666 protected static final String VIEW_LOG_TAG = "View"; 667 668 /** 669 * When set to true, apps will draw debugging information about their layouts. 670 * 671 * @hide 672 */ 673 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 674 675 /** 676 * Used to mark a View that has no ID. 677 */ 678 public static final int NO_ID = -1; 679 680 /** 681 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 682 * calling setFlags. 683 */ 684 private static final int NOT_FOCUSABLE = 0x00000000; 685 686 /** 687 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 688 * setFlags. 689 */ 690 private static final int FOCUSABLE = 0x00000001; 691 692 /** 693 * Mask for use with setFlags indicating bits used for focus. 694 */ 695 private static final int FOCUSABLE_MASK = 0x00000001; 696 697 /** 698 * This view will adjust its padding to fit sytem windows (e.g. status bar) 699 */ 700 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 701 702 /** 703 * This view is visible. 704 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 705 * android:visibility}. 706 */ 707 public static final int VISIBLE = 0x00000000; 708 709 /** 710 * This view is invisible, but it still takes up space for layout purposes. 711 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 712 * android:visibility}. 713 */ 714 public static final int INVISIBLE = 0x00000004; 715 716 /** 717 * This view is invisible, and it doesn't take any space for layout 718 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 719 * android:visibility}. 720 */ 721 public static final int GONE = 0x00000008; 722 723 /** 724 * Mask for use with setFlags indicating bits used for visibility. 725 * {@hide} 726 */ 727 static final int VISIBILITY_MASK = 0x0000000C; 728 729 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 730 731 /** 732 * This view is enabled. Interpretation varies by subclass. 733 * Use with ENABLED_MASK when calling setFlags. 734 * {@hide} 735 */ 736 static final int ENABLED = 0x00000000; 737 738 /** 739 * This view is disabled. Interpretation varies by subclass. 740 * Use with ENABLED_MASK when calling setFlags. 741 * {@hide} 742 */ 743 static final int DISABLED = 0x00000020; 744 745 /** 746 * Mask for use with setFlags indicating bits used for indicating whether 747 * this view is enabled 748 * {@hide} 749 */ 750 static final int ENABLED_MASK = 0x00000020; 751 752 /** 753 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 754 * called and further optimizations will be performed. It is okay to have 755 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 756 * {@hide} 757 */ 758 static final int WILL_NOT_DRAW = 0x00000080; 759 760 /** 761 * Mask for use with setFlags indicating bits used for indicating whether 762 * this view is will draw 763 * {@hide} 764 */ 765 static final int DRAW_MASK = 0x00000080; 766 767 /** 768 * <p>This view doesn't show scrollbars.</p> 769 * {@hide} 770 */ 771 static final int SCROLLBARS_NONE = 0x00000000; 772 773 /** 774 * <p>This view shows horizontal scrollbars.</p> 775 * {@hide} 776 */ 777 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 778 779 /** 780 * <p>This view shows vertical scrollbars.</p> 781 * {@hide} 782 */ 783 static final int SCROLLBARS_VERTICAL = 0x00000200; 784 785 /** 786 * <p>Mask for use with setFlags indicating bits used for indicating which 787 * scrollbars are enabled.</p> 788 * {@hide} 789 */ 790 static final int SCROLLBARS_MASK = 0x00000300; 791 792 /** 793 * Indicates that the view should filter touches when its window is obscured. 794 * Refer to the class comments for more information about this security feature. 795 * {@hide} 796 */ 797 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 798 799 /** 800 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 801 * that they are optional and should be skipped if the window has 802 * requested system UI flags that ignore those insets for layout. 803 */ 804 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 805 806 /** 807 * <p>This view doesn't show fading edges.</p> 808 * {@hide} 809 */ 810 static final int FADING_EDGE_NONE = 0x00000000; 811 812 /** 813 * <p>This view shows horizontal fading edges.</p> 814 * {@hide} 815 */ 816 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 817 818 /** 819 * <p>This view shows vertical fading edges.</p> 820 * {@hide} 821 */ 822 static final int FADING_EDGE_VERTICAL = 0x00002000; 823 824 /** 825 * <p>Mask for use with setFlags indicating bits used for indicating which 826 * fading edges are enabled.</p> 827 * {@hide} 828 */ 829 static final int FADING_EDGE_MASK = 0x00003000; 830 831 /** 832 * <p>Indicates this view can be clicked. When clickable, a View reacts 833 * to clicks by notifying the OnClickListener.<p> 834 * {@hide} 835 */ 836 static final int CLICKABLE = 0x00004000; 837 838 /** 839 * <p>Indicates this view is caching its drawing into a bitmap.</p> 840 * {@hide} 841 */ 842 static final int DRAWING_CACHE_ENABLED = 0x00008000; 843 844 /** 845 * <p>Indicates that no icicle should be saved for this view.<p> 846 * {@hide} 847 */ 848 static final int SAVE_DISABLED = 0x000010000; 849 850 /** 851 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 852 * property.</p> 853 * {@hide} 854 */ 855 static final int SAVE_DISABLED_MASK = 0x000010000; 856 857 /** 858 * <p>Indicates that no drawing cache should ever be created for this view.<p> 859 * {@hide} 860 */ 861 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 862 863 /** 864 * <p>Indicates this view can take / keep focus when int touch mode.</p> 865 * {@hide} 866 */ 867 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 868 869 /** 870 * <p>Enables low quality mode for the drawing cache.</p> 871 */ 872 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 873 874 /** 875 * <p>Enables high quality mode for the drawing cache.</p> 876 */ 877 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 878 879 /** 880 * <p>Enables automatic quality mode for the drawing cache.</p> 881 */ 882 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 883 884 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 885 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 886 }; 887 888 /** 889 * <p>Mask for use with setFlags indicating bits used for the cache 890 * quality property.</p> 891 * {@hide} 892 */ 893 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 894 895 /** 896 * <p> 897 * Indicates this view can be long clicked. When long clickable, a View 898 * reacts to long clicks by notifying the OnLongClickListener or showing a 899 * context menu. 900 * </p> 901 * {@hide} 902 */ 903 static final int LONG_CLICKABLE = 0x00200000; 904 905 /** 906 * <p>Indicates that this view gets its drawable states from its direct parent 907 * and ignores its original internal states.</p> 908 * 909 * @hide 910 */ 911 static final int DUPLICATE_PARENT_STATE = 0x00400000; 912 913 /** 914 * The scrollbar style to display the scrollbars inside the content area, 915 * without increasing the padding. The scrollbars will be overlaid with 916 * translucency on the view's content. 917 */ 918 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 919 920 /** 921 * The scrollbar style to display the scrollbars inside the padded area, 922 * increasing the padding of the view. The scrollbars will not overlap the 923 * content area of the view. 924 */ 925 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 926 927 /** 928 * The scrollbar style to display the scrollbars at the edge of the view, 929 * without increasing the padding. The scrollbars will be overlaid with 930 * translucency. 931 */ 932 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 933 934 /** 935 * The scrollbar style to display the scrollbars at the edge of the view, 936 * increasing the padding of the view. The scrollbars will only overlap the 937 * background, if any. 938 */ 939 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 940 941 /** 942 * Mask to check if the scrollbar style is overlay or inset. 943 * {@hide} 944 */ 945 static final int SCROLLBARS_INSET_MASK = 0x01000000; 946 947 /** 948 * Mask to check if the scrollbar style is inside or outside. 949 * {@hide} 950 */ 951 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 952 953 /** 954 * Mask for scrollbar style. 955 * {@hide} 956 */ 957 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 958 959 /** 960 * View flag indicating that the screen should remain on while the 961 * window containing this view is visible to the user. This effectively 962 * takes care of automatically setting the WindowManager's 963 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 964 */ 965 public static final int KEEP_SCREEN_ON = 0x04000000; 966 967 /** 968 * View flag indicating whether this view should have sound effects enabled 969 * for events such as clicking and touching. 970 */ 971 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 972 973 /** 974 * View flag indicating whether this view should have haptic feedback 975 * enabled for events such as long presses. 976 */ 977 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 978 979 /** 980 * <p>Indicates that the view hierarchy should stop saving state when 981 * it reaches this view. If state saving is initiated immediately at 982 * the view, it will be allowed. 983 * {@hide} 984 */ 985 static final int PARENT_SAVE_DISABLED = 0x20000000; 986 987 /** 988 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 989 * {@hide} 990 */ 991 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 992 993 /** 994 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 995 * should add all focusable Views regardless if they are focusable in touch mode. 996 */ 997 public static final int FOCUSABLES_ALL = 0x00000000; 998 999 /** 1000 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1001 * should add only Views focusable in touch mode. 1002 */ 1003 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1004 1005 /** 1006 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1007 * should add only accessibility focusable Views. 1008 * 1009 * @hide 1010 */ 1011 public static final int FOCUSABLES_ACCESSIBILITY = 0x00000002; 1012 1013 /** 1014 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1015 * item. 1016 */ 1017 public static final int FOCUS_BACKWARD = 0x00000001; 1018 1019 /** 1020 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1021 * item. 1022 */ 1023 public static final int FOCUS_FORWARD = 0x00000002; 1024 1025 /** 1026 * Use with {@link #focusSearch(int)}. Move focus to the left. 1027 */ 1028 public static final int FOCUS_LEFT = 0x00000011; 1029 1030 /** 1031 * Use with {@link #focusSearch(int)}. Move focus up. 1032 */ 1033 public static final int FOCUS_UP = 0x00000021; 1034 1035 /** 1036 * Use with {@link #focusSearch(int)}. Move focus to the right. 1037 */ 1038 public static final int FOCUS_RIGHT = 0x00000042; 1039 1040 /** 1041 * Use with {@link #focusSearch(int)}. Move focus down. 1042 */ 1043 public static final int FOCUS_DOWN = 0x00000082; 1044 1045 // Accessibility focus directions. 1046 1047 /** 1048 * The accessibility focus which is the current user position when 1049 * interacting with the accessibility framework. 1050 */ 1051 public static final int FOCUS_ACCESSIBILITY = 0x00001000; 1052 1053 /** 1054 * Use with {@link #focusSearch(int)}. Move acessibility focus left. 1055 */ 1056 public static final int ACCESSIBILITY_FOCUS_LEFT = FOCUS_LEFT | FOCUS_ACCESSIBILITY; 1057 1058 /** 1059 * Use with {@link #focusSearch(int)}. Move acessibility focus up. 1060 */ 1061 public static final int ACCESSIBILITY_FOCUS_UP = FOCUS_UP | FOCUS_ACCESSIBILITY; 1062 1063 /** 1064 * Use with {@link #focusSearch(int)}. Move acessibility focus right. 1065 */ 1066 public static final int ACCESSIBILITY_FOCUS_RIGHT = FOCUS_RIGHT | FOCUS_ACCESSIBILITY; 1067 1068 /** 1069 * Use with {@link #focusSearch(int)}. Move acessibility focus down. 1070 */ 1071 public static final int ACCESSIBILITY_FOCUS_DOWN = FOCUS_DOWN | FOCUS_ACCESSIBILITY; 1072 1073 /** 1074 * Use with {@link #focusSearch(int)}. Move acessibility focus forward. 1075 */ 1076 public static final int ACCESSIBILITY_FOCUS_FORWARD = FOCUS_FORWARD | FOCUS_ACCESSIBILITY; 1077 1078 /** 1079 * Use with {@link #focusSearch(int)}. Move acessibility focus backward. 1080 */ 1081 public static final int ACCESSIBILITY_FOCUS_BACKWARD = FOCUS_BACKWARD | FOCUS_ACCESSIBILITY; 1082 1083 /** 1084 * Bits of {@link #getMeasuredWidthAndState()} and 1085 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1086 */ 1087 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1088 1089 /** 1090 * Bits of {@link #getMeasuredWidthAndState()} and 1091 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1092 */ 1093 public static final int MEASURED_STATE_MASK = 0xff000000; 1094 1095 /** 1096 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1097 * for functions that combine both width and height into a single int, 1098 * such as {@link #getMeasuredState()} and the childState argument of 1099 * {@link #resolveSizeAndState(int, int, int)}. 1100 */ 1101 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1102 1103 /** 1104 * Bit of {@link #getMeasuredWidthAndState()} and 1105 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1106 * is smaller that the space the view would like to have. 1107 */ 1108 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1109 1110 /** 1111 * Base View state sets 1112 */ 1113 // Singles 1114 /** 1115 * Indicates the view has no states set. States are used with 1116 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1117 * view depending on its state. 1118 * 1119 * @see android.graphics.drawable.Drawable 1120 * @see #getDrawableState() 1121 */ 1122 protected static final int[] EMPTY_STATE_SET; 1123 /** 1124 * Indicates the view is enabled. States are used with 1125 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1126 * view depending on its state. 1127 * 1128 * @see android.graphics.drawable.Drawable 1129 * @see #getDrawableState() 1130 */ 1131 protected static final int[] ENABLED_STATE_SET; 1132 /** 1133 * Indicates the view is focused. States are used with 1134 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1135 * view depending on its state. 1136 * 1137 * @see android.graphics.drawable.Drawable 1138 * @see #getDrawableState() 1139 */ 1140 protected static final int[] FOCUSED_STATE_SET; 1141 /** 1142 * Indicates the view is selected. States are used with 1143 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1144 * view depending on its state. 1145 * 1146 * @see android.graphics.drawable.Drawable 1147 * @see #getDrawableState() 1148 */ 1149 protected static final int[] SELECTED_STATE_SET; 1150 /** 1151 * Indicates the view is pressed. States are used with 1152 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1153 * view depending on its state. 1154 * 1155 * @see android.graphics.drawable.Drawable 1156 * @see #getDrawableState() 1157 * @hide 1158 */ 1159 protected static final int[] PRESSED_STATE_SET; 1160 /** 1161 * Indicates the view's window has focus. States are used with 1162 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1163 * view depending on its state. 1164 * 1165 * @see android.graphics.drawable.Drawable 1166 * @see #getDrawableState() 1167 */ 1168 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1169 // Doubles 1170 /** 1171 * Indicates the view is enabled and has the focus. 1172 * 1173 * @see #ENABLED_STATE_SET 1174 * @see #FOCUSED_STATE_SET 1175 */ 1176 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1177 /** 1178 * Indicates the view is enabled and selected. 1179 * 1180 * @see #ENABLED_STATE_SET 1181 * @see #SELECTED_STATE_SET 1182 */ 1183 protected static final int[] ENABLED_SELECTED_STATE_SET; 1184 /** 1185 * Indicates the view is enabled and that its window has focus. 1186 * 1187 * @see #ENABLED_STATE_SET 1188 * @see #WINDOW_FOCUSED_STATE_SET 1189 */ 1190 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1191 /** 1192 * Indicates the view is focused and selected. 1193 * 1194 * @see #FOCUSED_STATE_SET 1195 * @see #SELECTED_STATE_SET 1196 */ 1197 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1198 /** 1199 * Indicates the view has the focus and that its window has the focus. 1200 * 1201 * @see #FOCUSED_STATE_SET 1202 * @see #WINDOW_FOCUSED_STATE_SET 1203 */ 1204 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1205 /** 1206 * Indicates the view is selected and that its window has the focus. 1207 * 1208 * @see #SELECTED_STATE_SET 1209 * @see #WINDOW_FOCUSED_STATE_SET 1210 */ 1211 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1212 // Triples 1213 /** 1214 * Indicates the view is enabled, focused and selected. 1215 * 1216 * @see #ENABLED_STATE_SET 1217 * @see #FOCUSED_STATE_SET 1218 * @see #SELECTED_STATE_SET 1219 */ 1220 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1221 /** 1222 * Indicates the view is enabled, focused and its window has the focus. 1223 * 1224 * @see #ENABLED_STATE_SET 1225 * @see #FOCUSED_STATE_SET 1226 * @see #WINDOW_FOCUSED_STATE_SET 1227 */ 1228 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1229 /** 1230 * Indicates the view is enabled, selected and its window has the focus. 1231 * 1232 * @see #ENABLED_STATE_SET 1233 * @see #SELECTED_STATE_SET 1234 * @see #WINDOW_FOCUSED_STATE_SET 1235 */ 1236 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1237 /** 1238 * Indicates the view is focused, selected and its window has the focus. 1239 * 1240 * @see #FOCUSED_STATE_SET 1241 * @see #SELECTED_STATE_SET 1242 * @see #WINDOW_FOCUSED_STATE_SET 1243 */ 1244 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1245 /** 1246 * Indicates the view is enabled, focused, selected and its window 1247 * has the focus. 1248 * 1249 * @see #ENABLED_STATE_SET 1250 * @see #FOCUSED_STATE_SET 1251 * @see #SELECTED_STATE_SET 1252 * @see #WINDOW_FOCUSED_STATE_SET 1253 */ 1254 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1255 /** 1256 * Indicates the view is pressed and its window has the focus. 1257 * 1258 * @see #PRESSED_STATE_SET 1259 * @see #WINDOW_FOCUSED_STATE_SET 1260 */ 1261 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1262 /** 1263 * Indicates the view is pressed and selected. 1264 * 1265 * @see #PRESSED_STATE_SET 1266 * @see #SELECTED_STATE_SET 1267 */ 1268 protected static final int[] PRESSED_SELECTED_STATE_SET; 1269 /** 1270 * Indicates the view is pressed, selected and its window has the focus. 1271 * 1272 * @see #PRESSED_STATE_SET 1273 * @see #SELECTED_STATE_SET 1274 * @see #WINDOW_FOCUSED_STATE_SET 1275 */ 1276 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1277 /** 1278 * Indicates the view is pressed and focused. 1279 * 1280 * @see #PRESSED_STATE_SET 1281 * @see #FOCUSED_STATE_SET 1282 */ 1283 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1284 /** 1285 * Indicates the view is pressed, focused and its window has the focus. 1286 * 1287 * @see #PRESSED_STATE_SET 1288 * @see #FOCUSED_STATE_SET 1289 * @see #WINDOW_FOCUSED_STATE_SET 1290 */ 1291 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1292 /** 1293 * Indicates the view is pressed, focused and selected. 1294 * 1295 * @see #PRESSED_STATE_SET 1296 * @see #SELECTED_STATE_SET 1297 * @see #FOCUSED_STATE_SET 1298 */ 1299 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1300 /** 1301 * Indicates the view is pressed, focused, selected and its window has the focus. 1302 * 1303 * @see #PRESSED_STATE_SET 1304 * @see #FOCUSED_STATE_SET 1305 * @see #SELECTED_STATE_SET 1306 * @see #WINDOW_FOCUSED_STATE_SET 1307 */ 1308 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1309 /** 1310 * Indicates the view is pressed and enabled. 1311 * 1312 * @see #PRESSED_STATE_SET 1313 * @see #ENABLED_STATE_SET 1314 */ 1315 protected static final int[] PRESSED_ENABLED_STATE_SET; 1316 /** 1317 * Indicates the view is pressed, enabled and its window has the focus. 1318 * 1319 * @see #PRESSED_STATE_SET 1320 * @see #ENABLED_STATE_SET 1321 * @see #WINDOW_FOCUSED_STATE_SET 1322 */ 1323 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1324 /** 1325 * Indicates the view is pressed, enabled and selected. 1326 * 1327 * @see #PRESSED_STATE_SET 1328 * @see #ENABLED_STATE_SET 1329 * @see #SELECTED_STATE_SET 1330 */ 1331 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1332 /** 1333 * Indicates the view is pressed, enabled, selected and its window has the 1334 * focus. 1335 * 1336 * @see #PRESSED_STATE_SET 1337 * @see #ENABLED_STATE_SET 1338 * @see #SELECTED_STATE_SET 1339 * @see #WINDOW_FOCUSED_STATE_SET 1340 */ 1341 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1342 /** 1343 * Indicates the view is pressed, enabled and focused. 1344 * 1345 * @see #PRESSED_STATE_SET 1346 * @see #ENABLED_STATE_SET 1347 * @see #FOCUSED_STATE_SET 1348 */ 1349 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1350 /** 1351 * Indicates the view is pressed, enabled, focused and its window has the 1352 * focus. 1353 * 1354 * @see #PRESSED_STATE_SET 1355 * @see #ENABLED_STATE_SET 1356 * @see #FOCUSED_STATE_SET 1357 * @see #WINDOW_FOCUSED_STATE_SET 1358 */ 1359 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1360 /** 1361 * Indicates the view is pressed, enabled, focused and selected. 1362 * 1363 * @see #PRESSED_STATE_SET 1364 * @see #ENABLED_STATE_SET 1365 * @see #SELECTED_STATE_SET 1366 * @see #FOCUSED_STATE_SET 1367 */ 1368 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1369 /** 1370 * Indicates the view is pressed, enabled, focused, selected and its window 1371 * has the focus. 1372 * 1373 * @see #PRESSED_STATE_SET 1374 * @see #ENABLED_STATE_SET 1375 * @see #SELECTED_STATE_SET 1376 * @see #FOCUSED_STATE_SET 1377 * @see #WINDOW_FOCUSED_STATE_SET 1378 */ 1379 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1380 1381 /** 1382 * The order here is very important to {@link #getDrawableState()} 1383 */ 1384 private static final int[][] VIEW_STATE_SETS; 1385 1386 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1387 static final int VIEW_STATE_SELECTED = 1 << 1; 1388 static final int VIEW_STATE_FOCUSED = 1 << 2; 1389 static final int VIEW_STATE_ENABLED = 1 << 3; 1390 static final int VIEW_STATE_PRESSED = 1 << 4; 1391 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1392 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1393 static final int VIEW_STATE_HOVERED = 1 << 7; 1394 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1395 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1396 1397 static final int[] VIEW_STATE_IDS = new int[] { 1398 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1399 R.attr.state_selected, VIEW_STATE_SELECTED, 1400 R.attr.state_focused, VIEW_STATE_FOCUSED, 1401 R.attr.state_enabled, VIEW_STATE_ENABLED, 1402 R.attr.state_pressed, VIEW_STATE_PRESSED, 1403 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1404 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1405 R.attr.state_hovered, VIEW_STATE_HOVERED, 1406 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1407 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1408 }; 1409 1410 static { 1411 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1412 throw new IllegalStateException( 1413 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1414 } 1415 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1416 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1417 int viewState = R.styleable.ViewDrawableStates[i]; 1418 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1419 if (VIEW_STATE_IDS[j] == viewState) { 1420 orderedIds[i * 2] = viewState; 1421 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1422 } 1423 } 1424 } 1425 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1426 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1427 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1428 int numBits = Integer.bitCount(i); 1429 int[] set = new int[numBits]; 1430 int pos = 0; 1431 for (int j = 0; j < orderedIds.length; j += 2) { 1432 if ((i & orderedIds[j+1]) != 0) { 1433 set[pos++] = orderedIds[j]; 1434 } 1435 } 1436 VIEW_STATE_SETS[i] = set; 1437 } 1438 1439 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1440 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1441 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1442 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1443 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1444 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1445 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1446 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1447 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1448 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1449 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1450 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1451 | VIEW_STATE_FOCUSED]; 1452 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1453 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1454 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1455 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1456 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1457 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1458 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1459 | VIEW_STATE_ENABLED]; 1460 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1461 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1462 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1463 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1464 | VIEW_STATE_ENABLED]; 1465 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1466 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1467 | VIEW_STATE_ENABLED]; 1468 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1469 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1470 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1471 1472 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1473 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1474 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1475 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1476 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1477 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1478 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1479 | VIEW_STATE_PRESSED]; 1480 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1481 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1482 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1483 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1484 | VIEW_STATE_PRESSED]; 1485 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1486 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1487 | VIEW_STATE_PRESSED]; 1488 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1489 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1490 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1491 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1492 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1493 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1494 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1495 | VIEW_STATE_PRESSED]; 1496 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1497 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1498 | VIEW_STATE_PRESSED]; 1499 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1500 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1501 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1502 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1503 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1504 | VIEW_STATE_PRESSED]; 1505 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1506 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1507 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1508 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1509 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1510 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1511 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1512 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1513 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1514 | VIEW_STATE_PRESSED]; 1515 } 1516 1517 /** 1518 * Accessibility event types that are dispatched for text population. 1519 */ 1520 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1521 AccessibilityEvent.TYPE_VIEW_CLICKED 1522 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1523 | AccessibilityEvent.TYPE_VIEW_SELECTED 1524 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1525 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1526 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1527 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1528 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1529 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1530 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1531 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1532 1533 /** 1534 * Temporary Rect currently for use in setBackground(). This will probably 1535 * be extended in the future to hold our own class with more than just 1536 * a Rect. :) 1537 */ 1538 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1539 1540 /** 1541 * Map used to store views' tags. 1542 */ 1543 private SparseArray<Object> mKeyedTags; 1544 1545 /** 1546 * The next available accessiiblity id. 1547 */ 1548 private static int sNextAccessibilityViewId; 1549 1550 /** 1551 * The animation currently associated with this view. 1552 * @hide 1553 */ 1554 protected Animation mCurrentAnimation = null; 1555 1556 /** 1557 * Width as measured during measure pass. 1558 * {@hide} 1559 */ 1560 @ViewDebug.ExportedProperty(category = "measurement") 1561 int mMeasuredWidth; 1562 1563 /** 1564 * Height as measured during measure pass. 1565 * {@hide} 1566 */ 1567 @ViewDebug.ExportedProperty(category = "measurement") 1568 int mMeasuredHeight; 1569 1570 /** 1571 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1572 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1573 * its display list. This flag, used only when hw accelerated, allows us to clear the 1574 * flag while retaining this information until it's needed (at getDisplayList() time and 1575 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1576 * 1577 * {@hide} 1578 */ 1579 boolean mRecreateDisplayList = false; 1580 1581 /** 1582 * The view's identifier. 1583 * {@hide} 1584 * 1585 * @see #setId(int) 1586 * @see #getId() 1587 */ 1588 @ViewDebug.ExportedProperty(resolveId = true) 1589 int mID = NO_ID; 1590 1591 /** 1592 * The stable ID of this view for accessibility purposes. 1593 */ 1594 int mAccessibilityViewId = NO_ID; 1595 1596 /** 1597 * @hide 1598 */ 1599 private int mAccessibilityCursorPosition = -1; 1600 1601 /** 1602 * The view's tag. 1603 * {@hide} 1604 * 1605 * @see #setTag(Object) 1606 * @see #getTag() 1607 */ 1608 protected Object mTag; 1609 1610 // for mPrivateFlags: 1611 /** {@hide} */ 1612 static final int WANTS_FOCUS = 0x00000001; 1613 /** {@hide} */ 1614 static final int FOCUSED = 0x00000002; 1615 /** {@hide} */ 1616 static final int SELECTED = 0x00000004; 1617 /** {@hide} */ 1618 static final int IS_ROOT_NAMESPACE = 0x00000008; 1619 /** {@hide} */ 1620 static final int HAS_BOUNDS = 0x00000010; 1621 /** {@hide} */ 1622 static final int DRAWN = 0x00000020; 1623 /** 1624 * When this flag is set, this view is running an animation on behalf of its 1625 * children and should therefore not cancel invalidate requests, even if they 1626 * lie outside of this view's bounds. 1627 * 1628 * {@hide} 1629 */ 1630 static final int DRAW_ANIMATION = 0x00000040; 1631 /** {@hide} */ 1632 static final int SKIP_DRAW = 0x00000080; 1633 /** {@hide} */ 1634 static final int ONLY_DRAWS_BACKGROUND = 0x00000100; 1635 /** {@hide} */ 1636 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1637 /** {@hide} */ 1638 static final int DRAWABLE_STATE_DIRTY = 0x00000400; 1639 /** {@hide} */ 1640 static final int MEASURED_DIMENSION_SET = 0x00000800; 1641 /** {@hide} */ 1642 static final int FORCE_LAYOUT = 0x00001000; 1643 /** {@hide} */ 1644 static final int LAYOUT_REQUIRED = 0x00002000; 1645 1646 private static final int PRESSED = 0x00004000; 1647 1648 /** {@hide} */ 1649 static final int DRAWING_CACHE_VALID = 0x00008000; 1650 /** 1651 * Flag used to indicate that this view should be drawn once more (and only once 1652 * more) after its animation has completed. 1653 * {@hide} 1654 */ 1655 static final int ANIMATION_STARTED = 0x00010000; 1656 1657 private static final int SAVE_STATE_CALLED = 0x00020000; 1658 1659 /** 1660 * Indicates that the View returned true when onSetAlpha() was called and that 1661 * the alpha must be restored. 1662 * {@hide} 1663 */ 1664 static final int ALPHA_SET = 0x00040000; 1665 1666 /** 1667 * Set by {@link #setScrollContainer(boolean)}. 1668 */ 1669 static final int SCROLL_CONTAINER = 0x00080000; 1670 1671 /** 1672 * Set by {@link #setScrollContainer(boolean)}. 1673 */ 1674 static final int SCROLL_CONTAINER_ADDED = 0x00100000; 1675 1676 /** 1677 * View flag indicating whether this view was invalidated (fully or partially.) 1678 * 1679 * @hide 1680 */ 1681 static final int DIRTY = 0x00200000; 1682 1683 /** 1684 * View flag indicating whether this view was invalidated by an opaque 1685 * invalidate request. 1686 * 1687 * @hide 1688 */ 1689 static final int DIRTY_OPAQUE = 0x00400000; 1690 1691 /** 1692 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}. 1693 * 1694 * @hide 1695 */ 1696 static final int DIRTY_MASK = 0x00600000; 1697 1698 /** 1699 * Indicates whether the background is opaque. 1700 * 1701 * @hide 1702 */ 1703 static final int OPAQUE_BACKGROUND = 0x00800000; 1704 1705 /** 1706 * Indicates whether the scrollbars are opaque. 1707 * 1708 * @hide 1709 */ 1710 static final int OPAQUE_SCROLLBARS = 0x01000000; 1711 1712 /** 1713 * Indicates whether the view is opaque. 1714 * 1715 * @hide 1716 */ 1717 static final int OPAQUE_MASK = 0x01800000; 1718 1719 /** 1720 * Indicates a prepressed state; 1721 * the short time between ACTION_DOWN and recognizing 1722 * a 'real' press. Prepressed is used to recognize quick taps 1723 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1724 * 1725 * @hide 1726 */ 1727 private static final int PREPRESSED = 0x02000000; 1728 1729 /** 1730 * Indicates whether the view is temporarily detached. 1731 * 1732 * @hide 1733 */ 1734 static final int CANCEL_NEXT_UP_EVENT = 0x04000000; 1735 1736 /** 1737 * Indicates that we should awaken scroll bars once attached 1738 * 1739 * @hide 1740 */ 1741 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1742 1743 /** 1744 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1745 * @hide 1746 */ 1747 private static final int HOVERED = 0x10000000; 1748 1749 /** 1750 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1751 * for transform operations 1752 * 1753 * @hide 1754 */ 1755 private static final int PIVOT_EXPLICITLY_SET = 0x20000000; 1756 1757 /** {@hide} */ 1758 static final int ACTIVATED = 0x40000000; 1759 1760 /** 1761 * Indicates that this view was specifically invalidated, not just dirtied because some 1762 * child view was invalidated. The flag is used to determine when we need to recreate 1763 * a view's display list (as opposed to just returning a reference to its existing 1764 * display list). 1765 * 1766 * @hide 1767 */ 1768 static final int INVALIDATED = 0x80000000; 1769 1770 /* Masks for mPrivateFlags2 */ 1771 1772 /** 1773 * Indicates that this view has reported that it can accept the current drag's content. 1774 * Cleared when the drag operation concludes. 1775 * @hide 1776 */ 1777 static final int DRAG_CAN_ACCEPT = 0x00000001; 1778 1779 /** 1780 * Indicates that this view is currently directly under the drag location in a 1781 * drag-and-drop operation involving content that it can accept. Cleared when 1782 * the drag exits the view, or when the drag operation concludes. 1783 * @hide 1784 */ 1785 static final int DRAG_HOVERED = 0x00000002; 1786 1787 /** 1788 * Horizontal layout direction of this view is from Left to Right. 1789 * Use with {@link #setLayoutDirection}. 1790 * @hide 1791 */ 1792 public static final int LAYOUT_DIRECTION_LTR = 0; 1793 1794 /** 1795 * Horizontal layout direction of this view is from Right to Left. 1796 * Use with {@link #setLayoutDirection}. 1797 * @hide 1798 */ 1799 public static final int LAYOUT_DIRECTION_RTL = 1; 1800 1801 /** 1802 * Horizontal layout direction of this view is inherited from its parent. 1803 * Use with {@link #setLayoutDirection}. 1804 * @hide 1805 */ 1806 public static final int LAYOUT_DIRECTION_INHERIT = 2; 1807 1808 /** 1809 * Horizontal layout direction of this view is from deduced from the default language 1810 * script for the locale. Use with {@link #setLayoutDirection}. 1811 * @hide 1812 */ 1813 public static final int LAYOUT_DIRECTION_LOCALE = 3; 1814 1815 /** 1816 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1817 * @hide 1818 */ 1819 static final int LAYOUT_DIRECTION_MASK_SHIFT = 2; 1820 1821 /** 1822 * Mask for use with private flags indicating bits used for horizontal layout direction. 1823 * @hide 1824 */ 1825 static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT; 1826 1827 /** 1828 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1829 * right-to-left direction. 1830 * @hide 1831 */ 1832 static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT; 1833 1834 /** 1835 * Indicates whether the view horizontal layout direction has been resolved. 1836 * @hide 1837 */ 1838 static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT; 1839 1840 /** 1841 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1842 * @hide 1843 */ 1844 static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT; 1845 1846 /* 1847 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1848 * flag value. 1849 * @hide 1850 */ 1851 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1852 LAYOUT_DIRECTION_LTR, 1853 LAYOUT_DIRECTION_RTL, 1854 LAYOUT_DIRECTION_INHERIT, 1855 LAYOUT_DIRECTION_LOCALE 1856 }; 1857 1858 /** 1859 * Default horizontal layout direction. 1860 * @hide 1861 */ 1862 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1863 1864 /** 1865 * Indicates that the view is tracking some sort of transient state 1866 * that the app should not need to be aware of, but that the framework 1867 * should take special care to preserve. 1868 * 1869 * @hide 1870 */ 1871 static final int HAS_TRANSIENT_STATE = 0x00000100; 1872 1873 1874 /** 1875 * Text direction is inherited thru {@link ViewGroup} 1876 * @hide 1877 */ 1878 public static final int TEXT_DIRECTION_INHERIT = 0; 1879 1880 /** 1881 * Text direction is using "first strong algorithm". The first strong directional character 1882 * determines the paragraph direction. If there is no strong directional character, the 1883 * paragraph direction is the view's resolved layout direction. 1884 * @hide 1885 */ 1886 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1887 1888 /** 1889 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1890 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1891 * If there are neither, the paragraph direction is the view's resolved layout direction. 1892 * @hide 1893 */ 1894 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1895 1896 /** 1897 * Text direction is forced to LTR. 1898 * @hide 1899 */ 1900 public static final int TEXT_DIRECTION_LTR = 3; 1901 1902 /** 1903 * Text direction is forced to RTL. 1904 * @hide 1905 */ 1906 public static final int TEXT_DIRECTION_RTL = 4; 1907 1908 /** 1909 * Text direction is coming from the system Locale. 1910 * @hide 1911 */ 1912 public static final int TEXT_DIRECTION_LOCALE = 5; 1913 1914 /** 1915 * Default text direction is inherited 1916 * @hide 1917 */ 1918 protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 1919 1920 /** 1921 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 1922 * @hide 1923 */ 1924 static final int TEXT_DIRECTION_MASK_SHIFT = 6; 1925 1926 /** 1927 * Mask for use with private flags indicating bits used for text direction. 1928 * @hide 1929 */ 1930 static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT; 1931 1932 /** 1933 * Array of text direction flags for mapping attribute "textDirection" to correct 1934 * flag value. 1935 * @hide 1936 */ 1937 private static final int[] TEXT_DIRECTION_FLAGS = { 1938 TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT, 1939 TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT, 1940 TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT, 1941 TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT, 1942 TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT, 1943 TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT 1944 }; 1945 1946 /** 1947 * Indicates whether the view text direction has been resolved. 1948 * @hide 1949 */ 1950 static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT; 1951 1952 /** 1953 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1954 * @hide 1955 */ 1956 static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 1957 1958 /** 1959 * Mask for use with private flags indicating bits used for resolved text direction. 1960 * @hide 1961 */ 1962 static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1963 1964 /** 1965 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 1966 * @hide 1967 */ 1968 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = 1969 TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1970 1971 /* 1972 * Default text alignment. The text alignment of this View is inherited from its parent. 1973 * Use with {@link #setTextAlignment(int)} 1974 * @hide 1975 */ 1976 public static final int TEXT_ALIGNMENT_INHERIT = 0; 1977 1978 /** 1979 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 1980 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 1981 * 1982 * Use with {@link #setTextAlignment(int)} 1983 * @hide 1984 */ 1985 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 1986 1987 /** 1988 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 1989 * 1990 * Use with {@link #setTextAlignment(int)} 1991 * @hide 1992 */ 1993 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 1994 1995 /** 1996 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 1997 * 1998 * Use with {@link #setTextAlignment(int)} 1999 * @hide 2000 */ 2001 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2002 2003 /** 2004 * Center the paragraph, e.g. ALIGN_CENTER. 2005 * 2006 * Use with {@link #setTextAlignment(int)} 2007 * @hide 2008 */ 2009 public static final int TEXT_ALIGNMENT_CENTER = 4; 2010 2011 /** 2012 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2013 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2014 * 2015 * Use with {@link #setTextAlignment(int)} 2016 * @hide 2017 */ 2018 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2019 2020 /** 2021 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2022 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2023 * 2024 * Use with {@link #setTextAlignment(int)} 2025 * @hide 2026 */ 2027 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2028 2029 /** 2030 * Default text alignment is inherited 2031 * @hide 2032 */ 2033 protected static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2034 2035 /** 2036 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2037 * @hide 2038 */ 2039 static final int TEXT_ALIGNMENT_MASK_SHIFT = 13; 2040 2041 /** 2042 * Mask for use with private flags indicating bits used for text alignment. 2043 * @hide 2044 */ 2045 static final int TEXT_ALIGNMENT_MASK = 0x00000007 << TEXT_ALIGNMENT_MASK_SHIFT; 2046 2047 /** 2048 * Array of text direction flags for mapping attribute "textAlignment" to correct 2049 * flag value. 2050 * @hide 2051 */ 2052 private static final int[] TEXT_ALIGNMENT_FLAGS = { 2053 TEXT_ALIGNMENT_INHERIT << TEXT_ALIGNMENT_MASK_SHIFT, 2054 TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_MASK_SHIFT, 2055 TEXT_ALIGNMENT_TEXT_START << TEXT_ALIGNMENT_MASK_SHIFT, 2056 TEXT_ALIGNMENT_TEXT_END << TEXT_ALIGNMENT_MASK_SHIFT, 2057 TEXT_ALIGNMENT_CENTER << TEXT_ALIGNMENT_MASK_SHIFT, 2058 TEXT_ALIGNMENT_VIEW_START << TEXT_ALIGNMENT_MASK_SHIFT, 2059 TEXT_ALIGNMENT_VIEW_END << TEXT_ALIGNMENT_MASK_SHIFT 2060 }; 2061 2062 /** 2063 * Indicates whether the view text alignment has been resolved. 2064 * @hide 2065 */ 2066 static final int TEXT_ALIGNMENT_RESOLVED = 0x00000008 << TEXT_ALIGNMENT_MASK_SHIFT; 2067 2068 /** 2069 * Bit shift to get the resolved text alignment. 2070 * @hide 2071 */ 2072 static final int TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2073 2074 /** 2075 * Mask for use with private flags indicating bits used for text alignment. 2076 * @hide 2077 */ 2078 static final int TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2079 2080 /** 2081 * Indicates whether if the view text alignment has been resolved to gravity 2082 */ 2083 public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2084 TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2085 2086 // Accessiblity constants for mPrivateFlags2 2087 2088 /** 2089 * Shift for accessibility related bits in {@link #mPrivateFlags2}. 2090 */ 2091 static final int IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2092 2093 /** 2094 * Automatically determine whether a view is important for accessibility. 2095 */ 2096 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2097 2098 /** 2099 * The view is important for accessibility. 2100 */ 2101 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2102 2103 /** 2104 * The view is not important for accessibility. 2105 */ 2106 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2107 2108 /** 2109 * The default whether the view is important for accessiblity. 2110 */ 2111 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2112 2113 /** 2114 * Mask for obtainig the bits which specify how to determine 2115 * whether a view is important for accessibility. 2116 */ 2117 static final int IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2118 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO) 2119 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2120 2121 /** 2122 * Flag indicating whether a view has accessibility focus. 2123 */ 2124 static final int ACCESSIBILITY_FOCUSED = 0x00000040 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2125 2126 /** 2127 * Flag indicating whether a view state for accessibility has changed. 2128 */ 2129 static final int ACCESSIBILITY_STATE_CHANGED = 0x00000080 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2130 2131 /** 2132 * Flag indicating that view has an animation set on it. This is used to track whether an 2133 * animation is cleared between successive frames, in order to tell the associated 2134 * DisplayList to clear its animation matrix. 2135 */ 2136 static final int VIEW_IS_ANIMATING_TRANSFORM = 0x10000000; 2137 2138 /** 2139 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2140 * is used to check whether later changes to the view's transform should invalidate the 2141 * view to force the quickReject test to run again. 2142 */ 2143 static final int VIEW_QUICK_REJECTED = 0x20000000; 2144 2145 /* End of masks for mPrivateFlags2 */ 2146 2147 static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED; 2148 2149 /** 2150 * Always allow a user to over-scroll this view, provided it is a 2151 * view that can scroll. 2152 * 2153 * @see #getOverScrollMode() 2154 * @see #setOverScrollMode(int) 2155 */ 2156 public static final int OVER_SCROLL_ALWAYS = 0; 2157 2158 /** 2159 * Allow a user to over-scroll this view only if the content is large 2160 * enough to meaningfully scroll, provided it is a view that can scroll. 2161 * 2162 * @see #getOverScrollMode() 2163 * @see #setOverScrollMode(int) 2164 */ 2165 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2166 2167 /** 2168 * Never allow a user to over-scroll this view. 2169 * 2170 * @see #getOverScrollMode() 2171 * @see #setOverScrollMode(int) 2172 */ 2173 public static final int OVER_SCROLL_NEVER = 2; 2174 2175 /** 2176 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2177 * requested the system UI (status bar) to be visible (the default). 2178 * 2179 * @see #setSystemUiVisibility(int) 2180 */ 2181 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2182 2183 /** 2184 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2185 * system UI to enter an unobtrusive "low profile" mode. 2186 * 2187 * <p>This is for use in games, book readers, video players, or any other 2188 * "immersive" application where the usual system chrome is deemed too distracting. 2189 * 2190 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2191 * 2192 * @see #setSystemUiVisibility(int) 2193 */ 2194 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2195 2196 /** 2197 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2198 * system navigation be temporarily hidden. 2199 * 2200 * <p>This is an even less obtrusive state than that called for by 2201 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2202 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2203 * those to disappear. This is useful (in conjunction with the 2204 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2205 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2206 * window flags) for displaying content using every last pixel on the display. 2207 * 2208 * <p>There is a limitation: because navigation controls are so important, the least user 2209 * interaction will cause them to reappear immediately. When this happens, both 2210 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2211 * so that both elements reappear at the same time. 2212 * 2213 * @see #setSystemUiVisibility(int) 2214 */ 2215 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2216 2217 /** 2218 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2219 * into the normal fullscreen mode so that its content can take over the screen 2220 * while still allowing the user to interact with the application. 2221 * 2222 * <p>This has the same visual effect as 2223 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2224 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2225 * meaning that non-critical screen decorations (such as the status bar) will be 2226 * hidden while the user is in the View's window, focusing the experience on 2227 * that content. Unlike the window flag, if you are using ActionBar in 2228 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2229 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2230 * hide the action bar. 2231 * 2232 * <p>This approach to going fullscreen is best used over the window flag when 2233 * it is a transient state -- that is, the application does this at certain 2234 * points in its user interaction where it wants to allow the user to focus 2235 * on content, but not as a continuous state. For situations where the application 2236 * would like to simply stay full screen the entire time (such as a game that 2237 * wants to take over the screen), the 2238 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2239 * is usually a better approach. The state set here will be removed by the system 2240 * in various situations (such as the user moving to another application) like 2241 * the other system UI states. 2242 * 2243 * <p>When using this flag, the application should provide some easy facility 2244 * for the user to go out of it. A common example would be in an e-book 2245 * reader, where tapping on the screen brings back whatever screen and UI 2246 * decorations that had been hidden while the user was immersed in reading 2247 * the book. 2248 * 2249 * @see #setSystemUiVisibility(int) 2250 */ 2251 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2252 2253 /** 2254 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2255 * flags, we would like a stable view of the content insets given to 2256 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2257 * will always represent the worst case that the application can expect 2258 * as a continue state. In practice this means with any of system bar, 2259 * nav bar, and status bar shown, but not the space that would be needed 2260 * for an input method. 2261 * 2262 * <p>If you are using ActionBar in 2263 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2264 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2265 * insets it adds to those given to the application. 2266 */ 2267 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2268 2269 /** 2270 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2271 * to be layed out as if it has requested 2272 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2273 * allows it to avoid artifacts when switching in and out of that mode, at 2274 * the expense that some of its user interface may be covered by screen 2275 * decorations when they are shown. You can perform layout of your inner 2276 * UI elements to account for the navagation system UI through the 2277 * {@link #fitSystemWindows(Rect)} method. 2278 */ 2279 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2280 2281 /** 2282 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2283 * to be layed out as if it has requested 2284 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2285 * allows it to avoid artifacts when switching in and out of that mode, at 2286 * the expense that some of its user interface may be covered by screen 2287 * decorations when they are shown. You can perform layout of your inner 2288 * UI elements to account for non-fullscreen system UI through the 2289 * {@link #fitSystemWindows(Rect)} method. 2290 */ 2291 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2292 2293 /** 2294 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2295 */ 2296 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2297 2298 /** 2299 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2300 */ 2301 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2302 2303 /** 2304 * @hide 2305 * 2306 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2307 * out of the public fields to keep the undefined bits out of the developer's way. 2308 * 2309 * Flag to make the status bar not expandable. Unless you also 2310 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2311 */ 2312 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2313 2314 /** 2315 * @hide 2316 * 2317 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2318 * out of the public fields to keep the undefined bits out of the developer's way. 2319 * 2320 * Flag to hide notification icons and scrolling ticker text. 2321 */ 2322 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2323 2324 /** 2325 * @hide 2326 * 2327 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2328 * out of the public fields to keep the undefined bits out of the developer's way. 2329 * 2330 * Flag to disable incoming notification alerts. This will not block 2331 * icons, but it will block sound, vibrating and other visual or aural notifications. 2332 */ 2333 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2334 2335 /** 2336 * @hide 2337 * 2338 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2339 * out of the public fields to keep the undefined bits out of the developer's way. 2340 * 2341 * Flag to hide only the scrolling ticker. Note that 2342 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2343 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2344 */ 2345 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2346 2347 /** 2348 * @hide 2349 * 2350 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2351 * out of the public fields to keep the undefined bits out of the developer's way. 2352 * 2353 * Flag to hide the center system info area. 2354 */ 2355 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2356 2357 /** 2358 * @hide 2359 * 2360 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2361 * out of the public fields to keep the undefined bits out of the developer's way. 2362 * 2363 * Flag to hide only the home button. Don't use this 2364 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2365 */ 2366 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2367 2368 /** 2369 * @hide 2370 * 2371 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2372 * out of the public fields to keep the undefined bits out of the developer's way. 2373 * 2374 * Flag to hide only the back button. Don't use this 2375 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2376 */ 2377 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2378 2379 /** 2380 * @hide 2381 * 2382 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2383 * out of the public fields to keep the undefined bits out of the developer's way. 2384 * 2385 * Flag to hide only the clock. You might use this if your activity has 2386 * its own clock making the status bar's clock redundant. 2387 */ 2388 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2389 2390 /** 2391 * @hide 2392 * 2393 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2394 * out of the public fields to keep the undefined bits out of the developer's way. 2395 * 2396 * Flag to hide only the recent apps button. Don't use this 2397 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2398 */ 2399 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2400 2401 /** 2402 * @hide 2403 */ 2404 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2405 2406 /** 2407 * These are the system UI flags that can be cleared by events outside 2408 * of an application. Currently this is just the ability to tap on the 2409 * screen while hiding the navigation bar to have it return. 2410 * @hide 2411 */ 2412 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2413 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2414 | SYSTEM_UI_FLAG_FULLSCREEN; 2415 2416 /** 2417 * Flags that can impact the layout in relation to system UI. 2418 */ 2419 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2420 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2421 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2422 2423 /** 2424 * Find views that render the specified text. 2425 * 2426 * @see #findViewsWithText(ArrayList, CharSequence, int) 2427 */ 2428 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2429 2430 /** 2431 * Find find views that contain the specified content description. 2432 * 2433 * @see #findViewsWithText(ArrayList, CharSequence, int) 2434 */ 2435 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2436 2437 /** 2438 * Find views that contain {@link AccessibilityNodeProvider}. Such 2439 * a View is a root of virtual view hierarchy and may contain the searched 2440 * text. If this flag is set Views with providers are automatically 2441 * added and it is a responsibility of the client to call the APIs of 2442 * the provider to determine whether the virtual tree rooted at this View 2443 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2444 * represeting the virtual views with this text. 2445 * 2446 * @see #findViewsWithText(ArrayList, CharSequence, int) 2447 * 2448 * @hide 2449 */ 2450 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2451 2452 /** 2453 * Indicates that the screen has changed state and is now off. 2454 * 2455 * @see #onScreenStateChanged(int) 2456 */ 2457 public static final int SCREEN_STATE_OFF = 0x0; 2458 2459 /** 2460 * Indicates that the screen has changed state and is now on. 2461 * 2462 * @see #onScreenStateChanged(int) 2463 */ 2464 public static final int SCREEN_STATE_ON = 0x1; 2465 2466 /** 2467 * Controls the over-scroll mode for this view. 2468 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2469 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2470 * and {@link #OVER_SCROLL_NEVER}. 2471 */ 2472 private int mOverScrollMode; 2473 2474 /** 2475 * The parent this view is attached to. 2476 * {@hide} 2477 * 2478 * @see #getParent() 2479 */ 2480 protected ViewParent mParent; 2481 2482 /** 2483 * {@hide} 2484 */ 2485 AttachInfo mAttachInfo; 2486 2487 /** 2488 * {@hide} 2489 */ 2490 @ViewDebug.ExportedProperty(flagMapping = { 2491 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT, 2492 name = "FORCE_LAYOUT"), 2493 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED, 2494 name = "LAYOUT_REQUIRED"), 2495 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID, 2496 name = "DRAWING_CACHE_INVALID", outputIf = false), 2497 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true), 2498 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false), 2499 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2500 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY") 2501 }) 2502 int mPrivateFlags; 2503 int mPrivateFlags2; 2504 2505 /** 2506 * This view's request for the visibility of the status bar. 2507 * @hide 2508 */ 2509 @ViewDebug.ExportedProperty(flagMapping = { 2510 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2511 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2512 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2513 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2514 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2515 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2516 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2517 equals = SYSTEM_UI_FLAG_VISIBLE, 2518 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2519 }) 2520 int mSystemUiVisibility; 2521 2522 /** 2523 * Reference count for transient state. 2524 * @see #setHasTransientState(boolean) 2525 */ 2526 int mTransientStateCount = 0; 2527 2528 /** 2529 * Count of how many windows this view has been attached to. 2530 */ 2531 int mWindowAttachCount; 2532 2533 /** 2534 * The layout parameters associated with this view and used by the parent 2535 * {@link android.view.ViewGroup} to determine how this view should be 2536 * laid out. 2537 * {@hide} 2538 */ 2539 protected ViewGroup.LayoutParams mLayoutParams; 2540 2541 /** 2542 * The view flags hold various views states. 2543 * {@hide} 2544 */ 2545 @ViewDebug.ExportedProperty 2546 int mViewFlags; 2547 2548 static class TransformationInfo { 2549 /** 2550 * The transform matrix for the View. This transform is calculated internally 2551 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2552 * is used by default. Do *not* use this variable directly; instead call 2553 * getMatrix(), which will automatically recalculate the matrix if necessary 2554 * to get the correct matrix based on the latest rotation and scale properties. 2555 */ 2556 private final Matrix mMatrix = new Matrix(); 2557 2558 /** 2559 * The transform matrix for the View. This transform is calculated internally 2560 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2561 * is used by default. Do *not* use this variable directly; instead call 2562 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2563 * to get the correct matrix based on the latest rotation and scale properties. 2564 */ 2565 private Matrix mInverseMatrix; 2566 2567 /** 2568 * An internal variable that tracks whether we need to recalculate the 2569 * transform matrix, based on whether the rotation or scaleX/Y properties 2570 * have changed since the matrix was last calculated. 2571 */ 2572 boolean mMatrixDirty = false; 2573 2574 /** 2575 * An internal variable that tracks whether we need to recalculate the 2576 * transform matrix, based on whether the rotation or scaleX/Y properties 2577 * have changed since the matrix was last calculated. 2578 */ 2579 private boolean mInverseMatrixDirty = true; 2580 2581 /** 2582 * A variable that tracks whether we need to recalculate the 2583 * transform matrix, based on whether the rotation or scaleX/Y properties 2584 * have changed since the matrix was last calculated. This variable 2585 * is only valid after a call to updateMatrix() or to a function that 2586 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2587 */ 2588 private boolean mMatrixIsIdentity = true; 2589 2590 /** 2591 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2592 */ 2593 private Camera mCamera = null; 2594 2595 /** 2596 * This matrix is used when computing the matrix for 3D rotations. 2597 */ 2598 private Matrix matrix3D = null; 2599 2600 /** 2601 * These prev values are used to recalculate a centered pivot point when necessary. The 2602 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2603 * set), so thes values are only used then as well. 2604 */ 2605 private int mPrevWidth = -1; 2606 private int mPrevHeight = -1; 2607 2608 /** 2609 * The degrees rotation around the vertical axis through the pivot point. 2610 */ 2611 @ViewDebug.ExportedProperty 2612 float mRotationY = 0f; 2613 2614 /** 2615 * The degrees rotation around the horizontal axis through the pivot point. 2616 */ 2617 @ViewDebug.ExportedProperty 2618 float mRotationX = 0f; 2619 2620 /** 2621 * The degrees rotation around the pivot point. 2622 */ 2623 @ViewDebug.ExportedProperty 2624 float mRotation = 0f; 2625 2626 /** 2627 * The amount of translation of the object away from its left property (post-layout). 2628 */ 2629 @ViewDebug.ExportedProperty 2630 float mTranslationX = 0f; 2631 2632 /** 2633 * The amount of translation of the object away from its top property (post-layout). 2634 */ 2635 @ViewDebug.ExportedProperty 2636 float mTranslationY = 0f; 2637 2638 /** 2639 * The amount of scale in the x direction around the pivot point. A 2640 * value of 1 means no scaling is applied. 2641 */ 2642 @ViewDebug.ExportedProperty 2643 float mScaleX = 1f; 2644 2645 /** 2646 * The amount of scale in the y direction around the pivot point. A 2647 * value of 1 means no scaling is applied. 2648 */ 2649 @ViewDebug.ExportedProperty 2650 float mScaleY = 1f; 2651 2652 /** 2653 * The x location of the point around which the view is rotated and scaled. 2654 */ 2655 @ViewDebug.ExportedProperty 2656 float mPivotX = 0f; 2657 2658 /** 2659 * The y location of the point around which the view is rotated and scaled. 2660 */ 2661 @ViewDebug.ExportedProperty 2662 float mPivotY = 0f; 2663 2664 /** 2665 * The opacity of the View. This is a value from 0 to 1, where 0 means 2666 * completely transparent and 1 means completely opaque. 2667 */ 2668 @ViewDebug.ExportedProperty 2669 float mAlpha = 1f; 2670 } 2671 2672 TransformationInfo mTransformationInfo; 2673 2674 private boolean mLastIsOpaque; 2675 2676 /** 2677 * Convenience value to check for float values that are close enough to zero to be considered 2678 * zero. 2679 */ 2680 private static final float NONZERO_EPSILON = .001f; 2681 2682 /** 2683 * The distance in pixels from the left edge of this view's parent 2684 * to the left edge of this view. 2685 * {@hide} 2686 */ 2687 @ViewDebug.ExportedProperty(category = "layout") 2688 protected int mLeft; 2689 /** 2690 * The distance in pixels from the left edge of this view's parent 2691 * to the right edge of this view. 2692 * {@hide} 2693 */ 2694 @ViewDebug.ExportedProperty(category = "layout") 2695 protected int mRight; 2696 /** 2697 * The distance in pixels from the top edge of this view's parent 2698 * to the top edge of this view. 2699 * {@hide} 2700 */ 2701 @ViewDebug.ExportedProperty(category = "layout") 2702 protected int mTop; 2703 /** 2704 * The distance in pixels from the top edge of this view's parent 2705 * to the bottom edge of this view. 2706 * {@hide} 2707 */ 2708 @ViewDebug.ExportedProperty(category = "layout") 2709 protected int mBottom; 2710 2711 /** 2712 * The offset, in pixels, by which the content of this view is scrolled 2713 * horizontally. 2714 * {@hide} 2715 */ 2716 @ViewDebug.ExportedProperty(category = "scrolling") 2717 protected int mScrollX; 2718 /** 2719 * The offset, in pixels, by which the content of this view is scrolled 2720 * vertically. 2721 * {@hide} 2722 */ 2723 @ViewDebug.ExportedProperty(category = "scrolling") 2724 protected int mScrollY; 2725 2726 /** 2727 * The left padding in pixels, that is the distance in pixels between the 2728 * left edge of this view and the left edge of its content. 2729 * {@hide} 2730 */ 2731 @ViewDebug.ExportedProperty(category = "padding") 2732 protected int mPaddingLeft; 2733 /** 2734 * The right padding in pixels, that is the distance in pixels between the 2735 * right edge of this view and the right edge of its content. 2736 * {@hide} 2737 */ 2738 @ViewDebug.ExportedProperty(category = "padding") 2739 protected int mPaddingRight; 2740 /** 2741 * The top padding in pixels, that is the distance in pixels between the 2742 * top edge of this view and the top edge of its content. 2743 * {@hide} 2744 */ 2745 @ViewDebug.ExportedProperty(category = "padding") 2746 protected int mPaddingTop; 2747 /** 2748 * The bottom padding in pixels, that is the distance in pixels between the 2749 * bottom edge of this view and the bottom edge of its content. 2750 * {@hide} 2751 */ 2752 @ViewDebug.ExportedProperty(category = "padding") 2753 protected int mPaddingBottom; 2754 2755 /** 2756 * The layout insets in pixels, that is the distance in pixels between the 2757 * visible edges of this view its bounds. 2758 */ 2759 private Insets mLayoutInsets; 2760 2761 /** 2762 * Briefly describes the view and is primarily used for accessibility support. 2763 */ 2764 private CharSequence mContentDescription; 2765 2766 /** 2767 * Cache the paddingRight set by the user to append to the scrollbar's size. 2768 * 2769 * @hide 2770 */ 2771 @ViewDebug.ExportedProperty(category = "padding") 2772 protected int mUserPaddingRight; 2773 2774 /** 2775 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2776 * 2777 * @hide 2778 */ 2779 @ViewDebug.ExportedProperty(category = "padding") 2780 protected int mUserPaddingBottom; 2781 2782 /** 2783 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2784 * 2785 * @hide 2786 */ 2787 @ViewDebug.ExportedProperty(category = "padding") 2788 protected int mUserPaddingLeft; 2789 2790 /** 2791 * Cache if the user padding is relative. 2792 * 2793 */ 2794 @ViewDebug.ExportedProperty(category = "padding") 2795 boolean mUserPaddingRelative; 2796 2797 /** 2798 * Cache the paddingStart set by the user to append to the scrollbar's size. 2799 * 2800 */ 2801 @ViewDebug.ExportedProperty(category = "padding") 2802 int mUserPaddingStart; 2803 2804 /** 2805 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2806 * 2807 */ 2808 @ViewDebug.ExportedProperty(category = "padding") 2809 int mUserPaddingEnd; 2810 2811 /** 2812 * @hide 2813 */ 2814 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2815 /** 2816 * @hide 2817 */ 2818 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2819 2820 private Drawable mBackground; 2821 2822 private int mBackgroundResource; 2823 private boolean mBackgroundSizeChanged; 2824 2825 static class ListenerInfo { 2826 /** 2827 * Listener used to dispatch focus change events. 2828 * This field should be made private, so it is hidden from the SDK. 2829 * {@hide} 2830 */ 2831 protected OnFocusChangeListener mOnFocusChangeListener; 2832 2833 /** 2834 * Listeners for layout change events. 2835 */ 2836 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2837 2838 /** 2839 * Listeners for attach events. 2840 */ 2841 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2842 2843 /** 2844 * Listener used to dispatch click events. 2845 * This field should be made private, so it is hidden from the SDK. 2846 * {@hide} 2847 */ 2848 public OnClickListener mOnClickListener; 2849 2850 /** 2851 * Listener used to dispatch long click events. 2852 * This field should be made private, so it is hidden from the SDK. 2853 * {@hide} 2854 */ 2855 protected OnLongClickListener mOnLongClickListener; 2856 2857 /** 2858 * Listener used to build the context menu. 2859 * This field should be made private, so it is hidden from the SDK. 2860 * {@hide} 2861 */ 2862 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2863 2864 private OnKeyListener mOnKeyListener; 2865 2866 private OnTouchListener mOnTouchListener; 2867 2868 private OnHoverListener mOnHoverListener; 2869 2870 private OnGenericMotionListener mOnGenericMotionListener; 2871 2872 private OnDragListener mOnDragListener; 2873 2874 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2875 } 2876 2877 ListenerInfo mListenerInfo; 2878 2879 /** 2880 * The application environment this view lives in. 2881 * This field should be made private, so it is hidden from the SDK. 2882 * {@hide} 2883 */ 2884 protected Context mContext; 2885 2886 private final Resources mResources; 2887 2888 private ScrollabilityCache mScrollCache; 2889 2890 private int[] mDrawableState = null; 2891 2892 /** 2893 * Set to true when drawing cache is enabled and cannot be created. 2894 * 2895 * @hide 2896 */ 2897 public boolean mCachingFailed; 2898 2899 private Bitmap mDrawingCache; 2900 private Bitmap mUnscaledDrawingCache; 2901 private HardwareLayer mHardwareLayer; 2902 DisplayList mDisplayList; 2903 2904 /** 2905 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2906 * the user may specify which view to go to next. 2907 */ 2908 private int mNextFocusLeftId = View.NO_ID; 2909 2910 /** 2911 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2912 * the user may specify which view to go to next. 2913 */ 2914 private int mNextFocusRightId = View.NO_ID; 2915 2916 /** 2917 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2918 * the user may specify which view to go to next. 2919 */ 2920 private int mNextFocusUpId = View.NO_ID; 2921 2922 /** 2923 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2924 * the user may specify which view to go to next. 2925 */ 2926 private int mNextFocusDownId = View.NO_ID; 2927 2928 /** 2929 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 2930 * the user may specify which view to go to next. 2931 */ 2932 int mNextFocusForwardId = View.NO_ID; 2933 2934 private CheckForLongPress mPendingCheckForLongPress; 2935 private CheckForTap mPendingCheckForTap = null; 2936 private PerformClick mPerformClick; 2937 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 2938 2939 private UnsetPressedState mUnsetPressedState; 2940 2941 /** 2942 * Whether the long press's action has been invoked. The tap's action is invoked on the 2943 * up event while a long press is invoked as soon as the long press duration is reached, so 2944 * a long press could be performed before the tap is checked, in which case the tap's action 2945 * should not be invoked. 2946 */ 2947 private boolean mHasPerformedLongPress; 2948 2949 /** 2950 * The minimum height of the view. We'll try our best to have the height 2951 * of this view to at least this amount. 2952 */ 2953 @ViewDebug.ExportedProperty(category = "measurement") 2954 private int mMinHeight; 2955 2956 /** 2957 * The minimum width of the view. We'll try our best to have the width 2958 * of this view to at least this amount. 2959 */ 2960 @ViewDebug.ExportedProperty(category = "measurement") 2961 private int mMinWidth; 2962 2963 /** 2964 * The delegate to handle touch events that are physically in this view 2965 * but should be handled by another view. 2966 */ 2967 private TouchDelegate mTouchDelegate = null; 2968 2969 /** 2970 * Solid color to use as a background when creating the drawing cache. Enables 2971 * the cache to use 16 bit bitmaps instead of 32 bit. 2972 */ 2973 private int mDrawingCacheBackgroundColor = 0; 2974 2975 /** 2976 * Special tree observer used when mAttachInfo is null. 2977 */ 2978 private ViewTreeObserver mFloatingTreeObserver; 2979 2980 /** 2981 * Cache the touch slop from the context that created the view. 2982 */ 2983 private int mTouchSlop; 2984 2985 /** 2986 * Object that handles automatic animation of view properties. 2987 */ 2988 private ViewPropertyAnimator mAnimator = null; 2989 2990 /** 2991 * Flag indicating that a drag can cross window boundaries. When 2992 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 2993 * with this flag set, all visible applications will be able to participate 2994 * in the drag operation and receive the dragged content. 2995 * 2996 * @hide 2997 */ 2998 public static final int DRAG_FLAG_GLOBAL = 1; 2999 3000 /** 3001 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3002 */ 3003 private float mVerticalScrollFactor; 3004 3005 /** 3006 * Position of the vertical scroll bar. 3007 */ 3008 private int mVerticalScrollbarPosition; 3009 3010 /** 3011 * Position the scroll bar at the default position as determined by the system. 3012 */ 3013 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3014 3015 /** 3016 * Position the scroll bar along the left edge. 3017 */ 3018 public static final int SCROLLBAR_POSITION_LEFT = 1; 3019 3020 /** 3021 * Position the scroll bar along the right edge. 3022 */ 3023 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3024 3025 /** 3026 * Indicates that the view does not have a layer. 3027 * 3028 * @see #getLayerType() 3029 * @see #setLayerType(int, android.graphics.Paint) 3030 * @see #LAYER_TYPE_SOFTWARE 3031 * @see #LAYER_TYPE_HARDWARE 3032 */ 3033 public static final int LAYER_TYPE_NONE = 0; 3034 3035 /** 3036 * <p>Indicates that the view has a software layer. A software layer is backed 3037 * by a bitmap and causes the view to be rendered using Android's software 3038 * rendering pipeline, even if hardware acceleration is enabled.</p> 3039 * 3040 * <p>Software layers have various usages:</p> 3041 * <p>When the application is not using hardware acceleration, a software layer 3042 * is useful to apply a specific color filter and/or blending mode and/or 3043 * translucency to a view and all its children.</p> 3044 * <p>When the application is using hardware acceleration, a software layer 3045 * is useful to render drawing primitives not supported by the hardware 3046 * accelerated pipeline. It can also be used to cache a complex view tree 3047 * into a texture and reduce the complexity of drawing operations. For instance, 3048 * when animating a complex view tree with a translation, a software layer can 3049 * be used to render the view tree only once.</p> 3050 * <p>Software layers should be avoided when the affected view tree updates 3051 * often. Every update will require to re-render the software layer, which can 3052 * potentially be slow (particularly when hardware acceleration is turned on 3053 * since the layer will have to be uploaded into a hardware texture after every 3054 * update.)</p> 3055 * 3056 * @see #getLayerType() 3057 * @see #setLayerType(int, android.graphics.Paint) 3058 * @see #LAYER_TYPE_NONE 3059 * @see #LAYER_TYPE_HARDWARE 3060 */ 3061 public static final int LAYER_TYPE_SOFTWARE = 1; 3062 3063 /** 3064 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3065 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3066 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3067 * rendering pipeline, but only if hardware acceleration is turned on for the 3068 * view hierarchy. When hardware acceleration is turned off, hardware layers 3069 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3070 * 3071 * <p>A hardware layer is useful to apply a specific color filter and/or 3072 * blending mode and/or translucency to a view and all its children.</p> 3073 * <p>A hardware layer can be used to cache a complex view tree into a 3074 * texture and reduce the complexity of drawing operations. For instance, 3075 * when animating a complex view tree with a translation, a hardware layer can 3076 * be used to render the view tree only once.</p> 3077 * <p>A hardware layer can also be used to increase the rendering quality when 3078 * rotation transformations are applied on a view. It can also be used to 3079 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3080 * 3081 * @see #getLayerType() 3082 * @see #setLayerType(int, android.graphics.Paint) 3083 * @see #LAYER_TYPE_NONE 3084 * @see #LAYER_TYPE_SOFTWARE 3085 */ 3086 public static final int LAYER_TYPE_HARDWARE = 2; 3087 3088 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3089 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3090 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3091 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3092 }) 3093 int mLayerType = LAYER_TYPE_NONE; 3094 Paint mLayerPaint; 3095 Rect mLocalDirtyRect; 3096 3097 /** 3098 * Set to true when the view is sending hover accessibility events because it 3099 * is the innermost hovered view. 3100 */ 3101 private boolean mSendingHoverAccessibilityEvents; 3102 3103 /** 3104 * Simple constructor to use when creating a view from code. 3105 * 3106 * @param context The Context the view is running in, through which it can 3107 * access the current theme, resources, etc. 3108 */ 3109 public View(Context context) { 3110 mContext = context; 3111 mResources = context != null ? context.getResources() : null; 3112 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3113 // Set layout and text direction defaults 3114 mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) | 3115 (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) | 3116 (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) | 3117 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3118 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3119 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3120 mUserPaddingStart = -1; 3121 mUserPaddingEnd = -1; 3122 mUserPaddingRelative = false; 3123 } 3124 3125 /** 3126 * Delegate for injecting accessiblity functionality. 3127 */ 3128 AccessibilityDelegate mAccessibilityDelegate; 3129 3130 /** 3131 * Consistency verifier for debugging purposes. 3132 * @hide 3133 */ 3134 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3135 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3136 new InputEventConsistencyVerifier(this, 0) : null; 3137 3138 /** 3139 * Constructor that is called when inflating a view from XML. This is called 3140 * when a view is being constructed from an XML file, supplying attributes 3141 * that were specified in the XML file. This version uses a default style of 3142 * 0, so the only attribute values applied are those in the Context's Theme 3143 * and the given AttributeSet. 3144 * 3145 * <p> 3146 * The method onFinishInflate() will be called after all children have been 3147 * added. 3148 * 3149 * @param context The Context the view is running in, through which it can 3150 * access the current theme, resources, etc. 3151 * @param attrs The attributes of the XML tag that is inflating the view. 3152 * @see #View(Context, AttributeSet, int) 3153 */ 3154 public View(Context context, AttributeSet attrs) { 3155 this(context, attrs, 0); 3156 } 3157 3158 /** 3159 * Perform inflation from XML and apply a class-specific base style. This 3160 * constructor of View allows subclasses to use their own base style when 3161 * they are inflating. For example, a Button class's constructor would call 3162 * this version of the super class constructor and supply 3163 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 3164 * the theme's button style to modify all of the base view attributes (in 3165 * particular its background) as well as the Button class's attributes. 3166 * 3167 * @param context The Context the view is running in, through which it can 3168 * access the current theme, resources, etc. 3169 * @param attrs The attributes of the XML tag that is inflating the view. 3170 * @param defStyle The default style to apply to this view. If 0, no style 3171 * will be applied (beyond what is included in the theme). This may 3172 * either be an attribute resource, whose value will be retrieved 3173 * from the current theme, or an explicit style resource. 3174 * @see #View(Context, AttributeSet) 3175 */ 3176 public View(Context context, AttributeSet attrs, int defStyle) { 3177 this(context); 3178 3179 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 3180 defStyle, 0); 3181 3182 Drawable background = null; 3183 3184 int leftPadding = -1; 3185 int topPadding = -1; 3186 int rightPadding = -1; 3187 int bottomPadding = -1; 3188 int startPadding = -1; 3189 int endPadding = -1; 3190 3191 int padding = -1; 3192 3193 int viewFlagValues = 0; 3194 int viewFlagMasks = 0; 3195 3196 boolean setScrollContainer = false; 3197 3198 int x = 0; 3199 int y = 0; 3200 3201 float tx = 0; 3202 float ty = 0; 3203 float rotation = 0; 3204 float rotationX = 0; 3205 float rotationY = 0; 3206 float sx = 1f; 3207 float sy = 1f; 3208 boolean transformSet = false; 3209 3210 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3211 3212 int overScrollMode = mOverScrollMode; 3213 final int N = a.getIndexCount(); 3214 for (int i = 0; i < N; i++) { 3215 int attr = a.getIndex(i); 3216 switch (attr) { 3217 case com.android.internal.R.styleable.View_background: 3218 background = a.getDrawable(attr); 3219 break; 3220 case com.android.internal.R.styleable.View_padding: 3221 padding = a.getDimensionPixelSize(attr, -1); 3222 break; 3223 case com.android.internal.R.styleable.View_paddingLeft: 3224 leftPadding = a.getDimensionPixelSize(attr, -1); 3225 break; 3226 case com.android.internal.R.styleable.View_paddingTop: 3227 topPadding = a.getDimensionPixelSize(attr, -1); 3228 break; 3229 case com.android.internal.R.styleable.View_paddingRight: 3230 rightPadding = a.getDimensionPixelSize(attr, -1); 3231 break; 3232 case com.android.internal.R.styleable.View_paddingBottom: 3233 bottomPadding = a.getDimensionPixelSize(attr, -1); 3234 break; 3235 case com.android.internal.R.styleable.View_paddingStart: 3236 startPadding = a.getDimensionPixelSize(attr, -1); 3237 break; 3238 case com.android.internal.R.styleable.View_paddingEnd: 3239 endPadding = a.getDimensionPixelSize(attr, -1); 3240 break; 3241 case com.android.internal.R.styleable.View_scrollX: 3242 x = a.getDimensionPixelOffset(attr, 0); 3243 break; 3244 case com.android.internal.R.styleable.View_scrollY: 3245 y = a.getDimensionPixelOffset(attr, 0); 3246 break; 3247 case com.android.internal.R.styleable.View_alpha: 3248 setAlpha(a.getFloat(attr, 1f)); 3249 break; 3250 case com.android.internal.R.styleable.View_transformPivotX: 3251 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3252 break; 3253 case com.android.internal.R.styleable.View_transformPivotY: 3254 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3255 break; 3256 case com.android.internal.R.styleable.View_translationX: 3257 tx = a.getDimensionPixelOffset(attr, 0); 3258 transformSet = true; 3259 break; 3260 case com.android.internal.R.styleable.View_translationY: 3261 ty = a.getDimensionPixelOffset(attr, 0); 3262 transformSet = true; 3263 break; 3264 case com.android.internal.R.styleable.View_rotation: 3265 rotation = a.getFloat(attr, 0); 3266 transformSet = true; 3267 break; 3268 case com.android.internal.R.styleable.View_rotationX: 3269 rotationX = a.getFloat(attr, 0); 3270 transformSet = true; 3271 break; 3272 case com.android.internal.R.styleable.View_rotationY: 3273 rotationY = a.getFloat(attr, 0); 3274 transformSet = true; 3275 break; 3276 case com.android.internal.R.styleable.View_scaleX: 3277 sx = a.getFloat(attr, 1f); 3278 transformSet = true; 3279 break; 3280 case com.android.internal.R.styleable.View_scaleY: 3281 sy = a.getFloat(attr, 1f); 3282 transformSet = true; 3283 break; 3284 case com.android.internal.R.styleable.View_id: 3285 mID = a.getResourceId(attr, NO_ID); 3286 break; 3287 case com.android.internal.R.styleable.View_tag: 3288 mTag = a.getText(attr); 3289 break; 3290 case com.android.internal.R.styleable.View_fitsSystemWindows: 3291 if (a.getBoolean(attr, false)) { 3292 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3293 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3294 } 3295 break; 3296 case com.android.internal.R.styleable.View_focusable: 3297 if (a.getBoolean(attr, false)) { 3298 viewFlagValues |= FOCUSABLE; 3299 viewFlagMasks |= FOCUSABLE_MASK; 3300 } 3301 break; 3302 case com.android.internal.R.styleable.View_focusableInTouchMode: 3303 if (a.getBoolean(attr, false)) { 3304 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3305 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3306 } 3307 break; 3308 case com.android.internal.R.styleable.View_clickable: 3309 if (a.getBoolean(attr, false)) { 3310 viewFlagValues |= CLICKABLE; 3311 viewFlagMasks |= CLICKABLE; 3312 } 3313 break; 3314 case com.android.internal.R.styleable.View_longClickable: 3315 if (a.getBoolean(attr, false)) { 3316 viewFlagValues |= LONG_CLICKABLE; 3317 viewFlagMasks |= LONG_CLICKABLE; 3318 } 3319 break; 3320 case com.android.internal.R.styleable.View_saveEnabled: 3321 if (!a.getBoolean(attr, true)) { 3322 viewFlagValues |= SAVE_DISABLED; 3323 viewFlagMasks |= SAVE_DISABLED_MASK; 3324 } 3325 break; 3326 case com.android.internal.R.styleable.View_duplicateParentState: 3327 if (a.getBoolean(attr, false)) { 3328 viewFlagValues |= DUPLICATE_PARENT_STATE; 3329 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3330 } 3331 break; 3332 case com.android.internal.R.styleable.View_visibility: 3333 final int visibility = a.getInt(attr, 0); 3334 if (visibility != 0) { 3335 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3336 viewFlagMasks |= VISIBILITY_MASK; 3337 } 3338 break; 3339 case com.android.internal.R.styleable.View_layoutDirection: 3340 // Clear any layout direction flags (included resolved bits) already set 3341 mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK); 3342 // Set the layout direction flags depending on the value of the attribute 3343 final int layoutDirection = a.getInt(attr, -1); 3344 final int value = (layoutDirection != -1) ? 3345 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3346 mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT); 3347 break; 3348 case com.android.internal.R.styleable.View_drawingCacheQuality: 3349 final int cacheQuality = a.getInt(attr, 0); 3350 if (cacheQuality != 0) { 3351 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3352 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3353 } 3354 break; 3355 case com.android.internal.R.styleable.View_contentDescription: 3356 mContentDescription = a.getString(attr); 3357 break; 3358 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3359 if (!a.getBoolean(attr, true)) { 3360 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3361 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3362 } 3363 break; 3364 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3365 if (!a.getBoolean(attr, true)) { 3366 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3367 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3368 } 3369 break; 3370 case R.styleable.View_scrollbars: 3371 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3372 if (scrollbars != SCROLLBARS_NONE) { 3373 viewFlagValues |= scrollbars; 3374 viewFlagMasks |= SCROLLBARS_MASK; 3375 initializeScrollbars(a); 3376 } 3377 break; 3378 //noinspection deprecation 3379 case R.styleable.View_fadingEdge: 3380 if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) { 3381 // Ignore the attribute starting with ICS 3382 break; 3383 } 3384 // With builds < ICS, fall through and apply fading edges 3385 case R.styleable.View_requiresFadingEdge: 3386 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3387 if (fadingEdge != FADING_EDGE_NONE) { 3388 viewFlagValues |= fadingEdge; 3389 viewFlagMasks |= FADING_EDGE_MASK; 3390 initializeFadingEdge(a); 3391 } 3392 break; 3393 case R.styleable.View_scrollbarStyle: 3394 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3395 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3396 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3397 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3398 } 3399 break; 3400 case R.styleable.View_isScrollContainer: 3401 setScrollContainer = true; 3402 if (a.getBoolean(attr, false)) { 3403 setScrollContainer(true); 3404 } 3405 break; 3406 case com.android.internal.R.styleable.View_keepScreenOn: 3407 if (a.getBoolean(attr, false)) { 3408 viewFlagValues |= KEEP_SCREEN_ON; 3409 viewFlagMasks |= KEEP_SCREEN_ON; 3410 } 3411 break; 3412 case R.styleable.View_filterTouchesWhenObscured: 3413 if (a.getBoolean(attr, false)) { 3414 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3415 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3416 } 3417 break; 3418 case R.styleable.View_nextFocusLeft: 3419 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3420 break; 3421 case R.styleable.View_nextFocusRight: 3422 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3423 break; 3424 case R.styleable.View_nextFocusUp: 3425 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3426 break; 3427 case R.styleable.View_nextFocusDown: 3428 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3429 break; 3430 case R.styleable.View_nextFocusForward: 3431 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3432 break; 3433 case R.styleable.View_minWidth: 3434 mMinWidth = a.getDimensionPixelSize(attr, 0); 3435 break; 3436 case R.styleable.View_minHeight: 3437 mMinHeight = a.getDimensionPixelSize(attr, 0); 3438 break; 3439 case R.styleable.View_onClick: 3440 if (context.isRestricted()) { 3441 throw new IllegalStateException("The android:onClick attribute cannot " 3442 + "be used within a restricted context"); 3443 } 3444 3445 final String handlerName = a.getString(attr); 3446 if (handlerName != null) { 3447 setOnClickListener(new OnClickListener() { 3448 private Method mHandler; 3449 3450 public void onClick(View v) { 3451 if (mHandler == null) { 3452 try { 3453 mHandler = getContext().getClass().getMethod(handlerName, 3454 View.class); 3455 } catch (NoSuchMethodException e) { 3456 int id = getId(); 3457 String idText = id == NO_ID ? "" : " with id '" 3458 + getContext().getResources().getResourceEntryName( 3459 id) + "'"; 3460 throw new IllegalStateException("Could not find a method " + 3461 handlerName + "(View) in the activity " 3462 + getContext().getClass() + " for onClick handler" 3463 + " on view " + View.this.getClass() + idText, e); 3464 } 3465 } 3466 3467 try { 3468 mHandler.invoke(getContext(), View.this); 3469 } catch (IllegalAccessException e) { 3470 throw new IllegalStateException("Could not execute non " 3471 + "public method of the activity", e); 3472 } catch (InvocationTargetException e) { 3473 throw new IllegalStateException("Could not execute " 3474 + "method of the activity", e); 3475 } 3476 } 3477 }); 3478 } 3479 break; 3480 case R.styleable.View_overScrollMode: 3481 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3482 break; 3483 case R.styleable.View_verticalScrollbarPosition: 3484 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3485 break; 3486 case R.styleable.View_layerType: 3487 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3488 break; 3489 case R.styleable.View_textDirection: 3490 // Clear any text direction flag already set 3491 mPrivateFlags2 &= ~TEXT_DIRECTION_MASK; 3492 // Set the text direction flags depending on the value of the attribute 3493 final int textDirection = a.getInt(attr, -1); 3494 if (textDirection != -1) { 3495 mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection]; 3496 } 3497 break; 3498 case R.styleable.View_textAlignment: 3499 // Clear any text alignment flag already set 3500 mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK; 3501 // Set the text alignment flag depending on the value of the attribute 3502 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 3503 mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment]; 3504 break; 3505 case R.styleable.View_importantForAccessibility: 3506 setImportantForAccessibility(a.getInt(attr, 3507 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 3508 } 3509 } 3510 3511 a.recycle(); 3512 3513 setOverScrollMode(overScrollMode); 3514 3515 if (background != null) { 3516 setBackground(background); 3517 } 3518 3519 // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved 3520 // layout direction). Those cached values will be used later during padding resolution. 3521 mUserPaddingStart = startPadding; 3522 mUserPaddingEnd = endPadding; 3523 3524 updateUserPaddingRelative(); 3525 3526 if (padding >= 0) { 3527 leftPadding = padding; 3528 topPadding = padding; 3529 rightPadding = padding; 3530 bottomPadding = padding; 3531 } 3532 3533 // If the user specified the padding (either with android:padding or 3534 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 3535 // use the default padding or the padding from the background drawable 3536 // (stored at this point in mPadding*) 3537 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft, 3538 topPadding >= 0 ? topPadding : mPaddingTop, 3539 rightPadding >= 0 ? rightPadding : mPaddingRight, 3540 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3541 3542 if (viewFlagMasks != 0) { 3543 setFlags(viewFlagValues, viewFlagMasks); 3544 } 3545 3546 // Needs to be called after mViewFlags is set 3547 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3548 recomputePadding(); 3549 } 3550 3551 if (x != 0 || y != 0) { 3552 scrollTo(x, y); 3553 } 3554 3555 if (transformSet) { 3556 setTranslationX(tx); 3557 setTranslationY(ty); 3558 setRotation(rotation); 3559 setRotationX(rotationX); 3560 setRotationY(rotationY); 3561 setScaleX(sx); 3562 setScaleY(sy); 3563 } 3564 3565 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3566 setScrollContainer(true); 3567 } 3568 3569 computeOpaqueFlags(); 3570 } 3571 3572 private void updateUserPaddingRelative() { 3573 mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0); 3574 } 3575 3576 /** 3577 * Non-public constructor for use in testing 3578 */ 3579 View() { 3580 mResources = null; 3581 } 3582 3583 /** 3584 * <p> 3585 * Initializes the fading edges from a given set of styled attributes. This 3586 * method should be called by subclasses that need fading edges and when an 3587 * instance of these subclasses is created programmatically rather than 3588 * being inflated from XML. This method is automatically called when the XML 3589 * is inflated. 3590 * </p> 3591 * 3592 * @param a the styled attributes set to initialize the fading edges from 3593 */ 3594 protected void initializeFadingEdge(TypedArray a) { 3595 initScrollCache(); 3596 3597 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3598 R.styleable.View_fadingEdgeLength, 3599 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3600 } 3601 3602 /** 3603 * Returns the size of the vertical faded edges used to indicate that more 3604 * content in this view is visible. 3605 * 3606 * @return The size in pixels of the vertical faded edge or 0 if vertical 3607 * faded edges are not enabled for this view. 3608 * @attr ref android.R.styleable#View_fadingEdgeLength 3609 */ 3610 public int getVerticalFadingEdgeLength() { 3611 if (isVerticalFadingEdgeEnabled()) { 3612 ScrollabilityCache cache = mScrollCache; 3613 if (cache != null) { 3614 return cache.fadingEdgeLength; 3615 } 3616 } 3617 return 0; 3618 } 3619 3620 /** 3621 * Set the size of the faded edge used to indicate that more content in this 3622 * view is available. Will not change whether the fading edge is enabled; use 3623 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3624 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3625 * for the vertical or horizontal fading edges. 3626 * 3627 * @param length The size in pixels of the faded edge used to indicate that more 3628 * content in this view is visible. 3629 */ 3630 public void setFadingEdgeLength(int length) { 3631 initScrollCache(); 3632 mScrollCache.fadingEdgeLength = length; 3633 } 3634 3635 /** 3636 * Returns the size of the horizontal faded edges used to indicate that more 3637 * content in this view is visible. 3638 * 3639 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3640 * faded edges are not enabled for this view. 3641 * @attr ref android.R.styleable#View_fadingEdgeLength 3642 */ 3643 public int getHorizontalFadingEdgeLength() { 3644 if (isHorizontalFadingEdgeEnabled()) { 3645 ScrollabilityCache cache = mScrollCache; 3646 if (cache != null) { 3647 return cache.fadingEdgeLength; 3648 } 3649 } 3650 return 0; 3651 } 3652 3653 /** 3654 * Returns the width of the vertical scrollbar. 3655 * 3656 * @return The width in pixels of the vertical scrollbar or 0 if there 3657 * is no vertical scrollbar. 3658 */ 3659 public int getVerticalScrollbarWidth() { 3660 ScrollabilityCache cache = mScrollCache; 3661 if (cache != null) { 3662 ScrollBarDrawable scrollBar = cache.scrollBar; 3663 if (scrollBar != null) { 3664 int size = scrollBar.getSize(true); 3665 if (size <= 0) { 3666 size = cache.scrollBarSize; 3667 } 3668 return size; 3669 } 3670 return 0; 3671 } 3672 return 0; 3673 } 3674 3675 /** 3676 * Returns the height of the horizontal scrollbar. 3677 * 3678 * @return The height in pixels of the horizontal scrollbar or 0 if 3679 * there is no horizontal scrollbar. 3680 */ 3681 protected int getHorizontalScrollbarHeight() { 3682 ScrollabilityCache cache = mScrollCache; 3683 if (cache != null) { 3684 ScrollBarDrawable scrollBar = cache.scrollBar; 3685 if (scrollBar != null) { 3686 int size = scrollBar.getSize(false); 3687 if (size <= 0) { 3688 size = cache.scrollBarSize; 3689 } 3690 return size; 3691 } 3692 return 0; 3693 } 3694 return 0; 3695 } 3696 3697 /** 3698 * <p> 3699 * Initializes the scrollbars from a given set of styled attributes. This 3700 * method should be called by subclasses that need scrollbars and when an 3701 * instance of these subclasses is created programmatically rather than 3702 * being inflated from XML. This method is automatically called when the XML 3703 * is inflated. 3704 * </p> 3705 * 3706 * @param a the styled attributes set to initialize the scrollbars from 3707 */ 3708 protected void initializeScrollbars(TypedArray a) { 3709 initScrollCache(); 3710 3711 final ScrollabilityCache scrollabilityCache = mScrollCache; 3712 3713 if (scrollabilityCache.scrollBar == null) { 3714 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 3715 } 3716 3717 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 3718 3719 if (!fadeScrollbars) { 3720 scrollabilityCache.state = ScrollabilityCache.ON; 3721 } 3722 scrollabilityCache.fadeScrollBars = fadeScrollbars; 3723 3724 3725 scrollabilityCache.scrollBarFadeDuration = a.getInt( 3726 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 3727 .getScrollBarFadeDuration()); 3728 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 3729 R.styleable.View_scrollbarDefaultDelayBeforeFade, 3730 ViewConfiguration.getScrollDefaultDelay()); 3731 3732 3733 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 3734 com.android.internal.R.styleable.View_scrollbarSize, 3735 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3736 3737 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3738 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3739 3740 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3741 if (thumb != null) { 3742 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3743 } 3744 3745 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3746 false); 3747 if (alwaysDraw) { 3748 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3749 } 3750 3751 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3752 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3753 3754 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3755 if (thumb != null) { 3756 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3757 } 3758 3759 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3760 false); 3761 if (alwaysDraw) { 3762 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3763 } 3764 3765 // Re-apply user/background padding so that scrollbar(s) get added 3766 resolvePadding(); 3767 } 3768 3769 /** 3770 * <p> 3771 * Initalizes the scrollability cache if necessary. 3772 * </p> 3773 */ 3774 private void initScrollCache() { 3775 if (mScrollCache == null) { 3776 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 3777 } 3778 } 3779 3780 private ScrollabilityCache getScrollCache() { 3781 initScrollCache(); 3782 return mScrollCache; 3783 } 3784 3785 /** 3786 * Set the position of the vertical scroll bar. Should be one of 3787 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 3788 * {@link #SCROLLBAR_POSITION_RIGHT}. 3789 * 3790 * @param position Where the vertical scroll bar should be positioned. 3791 */ 3792 public void setVerticalScrollbarPosition(int position) { 3793 if (mVerticalScrollbarPosition != position) { 3794 mVerticalScrollbarPosition = position; 3795 computeOpaqueFlags(); 3796 resolvePadding(); 3797 } 3798 } 3799 3800 /** 3801 * @return The position where the vertical scroll bar will show, if applicable. 3802 * @see #setVerticalScrollbarPosition(int) 3803 */ 3804 public int getVerticalScrollbarPosition() { 3805 return mVerticalScrollbarPosition; 3806 } 3807 3808 ListenerInfo getListenerInfo() { 3809 if (mListenerInfo != null) { 3810 return mListenerInfo; 3811 } 3812 mListenerInfo = new ListenerInfo(); 3813 return mListenerInfo; 3814 } 3815 3816 /** 3817 * Register a callback to be invoked when focus of this view changed. 3818 * 3819 * @param l The callback that will run. 3820 */ 3821 public void setOnFocusChangeListener(OnFocusChangeListener l) { 3822 getListenerInfo().mOnFocusChangeListener = l; 3823 } 3824 3825 /** 3826 * Add a listener that will be called when the bounds of the view change due to 3827 * layout processing. 3828 * 3829 * @param listener The listener that will be called when layout bounds change. 3830 */ 3831 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 3832 ListenerInfo li = getListenerInfo(); 3833 if (li.mOnLayoutChangeListeners == null) { 3834 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 3835 } 3836 if (!li.mOnLayoutChangeListeners.contains(listener)) { 3837 li.mOnLayoutChangeListeners.add(listener); 3838 } 3839 } 3840 3841 /** 3842 * Remove a listener for layout changes. 3843 * 3844 * @param listener The listener for layout bounds change. 3845 */ 3846 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 3847 ListenerInfo li = mListenerInfo; 3848 if (li == null || li.mOnLayoutChangeListeners == null) { 3849 return; 3850 } 3851 li.mOnLayoutChangeListeners.remove(listener); 3852 } 3853 3854 /** 3855 * Add a listener for attach state changes. 3856 * 3857 * This listener will be called whenever this view is attached or detached 3858 * from a window. Remove the listener using 3859 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 3860 * 3861 * @param listener Listener to attach 3862 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 3863 */ 3864 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3865 ListenerInfo li = getListenerInfo(); 3866 if (li.mOnAttachStateChangeListeners == null) { 3867 li.mOnAttachStateChangeListeners 3868 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 3869 } 3870 li.mOnAttachStateChangeListeners.add(listener); 3871 } 3872 3873 /** 3874 * Remove a listener for attach state changes. The listener will receive no further 3875 * notification of window attach/detach events. 3876 * 3877 * @param listener Listener to remove 3878 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 3879 */ 3880 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3881 ListenerInfo li = mListenerInfo; 3882 if (li == null || li.mOnAttachStateChangeListeners == null) { 3883 return; 3884 } 3885 li.mOnAttachStateChangeListeners.remove(listener); 3886 } 3887 3888 /** 3889 * Returns the focus-change callback registered for this view. 3890 * 3891 * @return The callback, or null if one is not registered. 3892 */ 3893 public OnFocusChangeListener getOnFocusChangeListener() { 3894 ListenerInfo li = mListenerInfo; 3895 return li != null ? li.mOnFocusChangeListener : null; 3896 } 3897 3898 /** 3899 * Register a callback to be invoked when this view is clicked. If this view is not 3900 * clickable, it becomes clickable. 3901 * 3902 * @param l The callback that will run 3903 * 3904 * @see #setClickable(boolean) 3905 */ 3906 public void setOnClickListener(OnClickListener l) { 3907 if (!isClickable()) { 3908 setClickable(true); 3909 } 3910 getListenerInfo().mOnClickListener = l; 3911 } 3912 3913 /** 3914 * Return whether this view has an attached OnClickListener. Returns 3915 * true if there is a listener, false if there is none. 3916 */ 3917 public boolean hasOnClickListeners() { 3918 ListenerInfo li = mListenerInfo; 3919 return (li != null && li.mOnClickListener != null); 3920 } 3921 3922 /** 3923 * Register a callback to be invoked when this view is clicked and held. If this view is not 3924 * long clickable, it becomes long clickable. 3925 * 3926 * @param l The callback that will run 3927 * 3928 * @see #setLongClickable(boolean) 3929 */ 3930 public void setOnLongClickListener(OnLongClickListener l) { 3931 if (!isLongClickable()) { 3932 setLongClickable(true); 3933 } 3934 getListenerInfo().mOnLongClickListener = l; 3935 } 3936 3937 /** 3938 * Register a callback to be invoked when the context menu for this view is 3939 * being built. If this view is not long clickable, it becomes long clickable. 3940 * 3941 * @param l The callback that will run 3942 * 3943 */ 3944 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 3945 if (!isLongClickable()) { 3946 setLongClickable(true); 3947 } 3948 getListenerInfo().mOnCreateContextMenuListener = l; 3949 } 3950 3951 /** 3952 * Call this view's OnClickListener, if it is defined. Performs all normal 3953 * actions associated with clicking: reporting accessibility event, playing 3954 * a sound, etc. 3955 * 3956 * @return True there was an assigned OnClickListener that was called, false 3957 * otherwise is returned. 3958 */ 3959 public boolean performClick() { 3960 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 3961 3962 ListenerInfo li = mListenerInfo; 3963 if (li != null && li.mOnClickListener != null) { 3964 playSoundEffect(SoundEffectConstants.CLICK); 3965 li.mOnClickListener.onClick(this); 3966 return true; 3967 } 3968 3969 return false; 3970 } 3971 3972 /** 3973 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 3974 * this only calls the listener, and does not do any associated clicking 3975 * actions like reporting an accessibility event. 3976 * 3977 * @return True there was an assigned OnClickListener that was called, false 3978 * otherwise is returned. 3979 */ 3980 public boolean callOnClick() { 3981 ListenerInfo li = mListenerInfo; 3982 if (li != null && li.mOnClickListener != null) { 3983 li.mOnClickListener.onClick(this); 3984 return true; 3985 } 3986 return false; 3987 } 3988 3989 /** 3990 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 3991 * OnLongClickListener did not consume the event. 3992 * 3993 * @return True if one of the above receivers consumed the event, false otherwise. 3994 */ 3995 public boolean performLongClick() { 3996 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 3997 3998 boolean handled = false; 3999 ListenerInfo li = mListenerInfo; 4000 if (li != null && li.mOnLongClickListener != null) { 4001 handled = li.mOnLongClickListener.onLongClick(View.this); 4002 } 4003 if (!handled) { 4004 handled = showContextMenu(); 4005 } 4006 if (handled) { 4007 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4008 } 4009 return handled; 4010 } 4011 4012 /** 4013 * Performs button-related actions during a touch down event. 4014 * 4015 * @param event The event. 4016 * @return True if the down was consumed. 4017 * 4018 * @hide 4019 */ 4020 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4021 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4022 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4023 return true; 4024 } 4025 } 4026 return false; 4027 } 4028 4029 /** 4030 * Bring up the context menu for this view. 4031 * 4032 * @return Whether a context menu was displayed. 4033 */ 4034 public boolean showContextMenu() { 4035 return getParent().showContextMenuForChild(this); 4036 } 4037 4038 /** 4039 * Bring up the context menu for this view, referring to the item under the specified point. 4040 * 4041 * @param x The referenced x coordinate. 4042 * @param y The referenced y coordinate. 4043 * @param metaState The keyboard modifiers that were pressed. 4044 * @return Whether a context menu was displayed. 4045 * 4046 * @hide 4047 */ 4048 public boolean showContextMenu(float x, float y, int metaState) { 4049 return showContextMenu(); 4050 } 4051 4052 /** 4053 * Start an action mode. 4054 * 4055 * @param callback Callback that will control the lifecycle of the action mode 4056 * @return The new action mode if it is started, null otherwise 4057 * 4058 * @see ActionMode 4059 */ 4060 public ActionMode startActionMode(ActionMode.Callback callback) { 4061 ViewParent parent = getParent(); 4062 if (parent == null) return null; 4063 return parent.startActionModeForChild(this, callback); 4064 } 4065 4066 /** 4067 * Register a callback to be invoked when a key is pressed in this view. 4068 * @param l the key listener to attach to this view 4069 */ 4070 public void setOnKeyListener(OnKeyListener l) { 4071 getListenerInfo().mOnKeyListener = l; 4072 } 4073 4074 /** 4075 * Register a callback to be invoked when a touch event is sent to this view. 4076 * @param l the touch listener to attach to this view 4077 */ 4078 public void setOnTouchListener(OnTouchListener l) { 4079 getListenerInfo().mOnTouchListener = l; 4080 } 4081 4082 /** 4083 * Register a callback to be invoked when a generic motion event is sent to this view. 4084 * @param l the generic motion listener to attach to this view 4085 */ 4086 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4087 getListenerInfo().mOnGenericMotionListener = l; 4088 } 4089 4090 /** 4091 * Register a callback to be invoked when a hover event is sent to this view. 4092 * @param l the hover listener to attach to this view 4093 */ 4094 public void setOnHoverListener(OnHoverListener l) { 4095 getListenerInfo().mOnHoverListener = l; 4096 } 4097 4098 /** 4099 * Register a drag event listener callback object for this View. The parameter is 4100 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4101 * View, the system calls the 4102 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4103 * @param l An implementation of {@link android.view.View.OnDragListener}. 4104 */ 4105 public void setOnDragListener(OnDragListener l) { 4106 getListenerInfo().mOnDragListener = l; 4107 } 4108 4109 /** 4110 * Give this view focus. This will cause 4111 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4112 * 4113 * Note: this does not check whether this {@link View} should get focus, it just 4114 * gives it focus no matter what. It should only be called internally by framework 4115 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4116 * 4117 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4118 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4119 * focus moved when requestFocus() is called. It may not always 4120 * apply, in which case use the default View.FOCUS_DOWN. 4121 * @param previouslyFocusedRect The rectangle of the view that had focus 4122 * prior in this View's coordinate system. 4123 */ 4124 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 4125 if (DBG) { 4126 System.out.println(this + " requestFocus()"); 4127 } 4128 4129 if ((mPrivateFlags & FOCUSED) == 0) { 4130 mPrivateFlags |= FOCUSED; 4131 4132 if (mParent != null) { 4133 mParent.requestChildFocus(this, this); 4134 } 4135 4136 onFocusChanged(true, direction, previouslyFocusedRect); 4137 refreshDrawableState(); 4138 4139 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4140 notifyAccessibilityStateChanged(); 4141 } 4142 } 4143 } 4144 4145 /** 4146 * Request that a rectangle of this view be visible on the screen, 4147 * scrolling if necessary just enough. 4148 * 4149 * <p>A View should call this if it maintains some notion of which part 4150 * of its content is interesting. For example, a text editing view 4151 * should call this when its cursor moves. 4152 * 4153 * @param rectangle The rectangle. 4154 * @return Whether any parent scrolled. 4155 */ 4156 public boolean requestRectangleOnScreen(Rect rectangle) { 4157 return requestRectangleOnScreen(rectangle, false); 4158 } 4159 4160 /** 4161 * Request that a rectangle of this view be visible on the screen, 4162 * scrolling if necessary just enough. 4163 * 4164 * <p>A View should call this if it maintains some notion of which part 4165 * of its content is interesting. For example, a text editing view 4166 * should call this when its cursor moves. 4167 * 4168 * <p>When <code>immediate</code> is set to true, scrolling will not be 4169 * animated. 4170 * 4171 * @param rectangle The rectangle. 4172 * @param immediate True to forbid animated scrolling, false otherwise 4173 * @return Whether any parent scrolled. 4174 */ 4175 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4176 View child = this; 4177 ViewParent parent = mParent; 4178 boolean scrolled = false; 4179 while (parent != null) { 4180 scrolled |= parent.requestChildRectangleOnScreen(child, 4181 rectangle, immediate); 4182 4183 // offset rect so next call has the rectangle in the 4184 // coordinate system of its direct child. 4185 rectangle.offset(child.getLeft(), child.getTop()); 4186 rectangle.offset(-child.getScrollX(), -child.getScrollY()); 4187 4188 if (!(parent instanceof View)) { 4189 break; 4190 } 4191 4192 child = (View) parent; 4193 parent = child.getParent(); 4194 } 4195 return scrolled; 4196 } 4197 4198 /** 4199 * Called when this view wants to give up focus. If focus is cleared 4200 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4201 * <p> 4202 * <strong>Note:</strong> When a View clears focus the framework is trying 4203 * to give focus to the first focusable View from the top. Hence, if this 4204 * View is the first from the top that can take focus, then all callbacks 4205 * related to clearing focus will be invoked after wich the framework will 4206 * give focus to this view. 4207 * </p> 4208 */ 4209 public void clearFocus() { 4210 if (DBG) { 4211 System.out.println(this + " clearFocus()"); 4212 } 4213 4214 if ((mPrivateFlags & FOCUSED) != 0) { 4215 mPrivateFlags &= ~FOCUSED; 4216 4217 if (mParent != null) { 4218 mParent.clearChildFocus(this); 4219 } 4220 4221 onFocusChanged(false, 0, null); 4222 4223 refreshDrawableState(); 4224 4225 ensureInputFocusOnFirstFocusable(); 4226 4227 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4228 notifyAccessibilityStateChanged(); 4229 } 4230 } 4231 } 4232 4233 void ensureInputFocusOnFirstFocusable() { 4234 View root = getRootView(); 4235 if (root != null) { 4236 root.requestFocus(); 4237 } 4238 } 4239 4240 /** 4241 * Called internally by the view system when a new view is getting focus. 4242 * This is what clears the old focus. 4243 */ 4244 void unFocus() { 4245 if (DBG) { 4246 System.out.println(this + " unFocus()"); 4247 } 4248 4249 if ((mPrivateFlags & FOCUSED) != 0) { 4250 mPrivateFlags &= ~FOCUSED; 4251 4252 onFocusChanged(false, 0, null); 4253 refreshDrawableState(); 4254 4255 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4256 notifyAccessibilityStateChanged(); 4257 } 4258 } 4259 } 4260 4261 /** 4262 * Returns true if this view has focus iteself, or is the ancestor of the 4263 * view that has focus. 4264 * 4265 * @return True if this view has or contains focus, false otherwise. 4266 */ 4267 @ViewDebug.ExportedProperty(category = "focus") 4268 public boolean hasFocus() { 4269 return (mPrivateFlags & FOCUSED) != 0; 4270 } 4271 4272 /** 4273 * Returns true if this view is focusable or if it contains a reachable View 4274 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4275 * is a View whose parents do not block descendants focus. 4276 * 4277 * Only {@link #VISIBLE} views are considered focusable. 4278 * 4279 * @return True if the view is focusable or if the view contains a focusable 4280 * View, false otherwise. 4281 * 4282 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4283 */ 4284 public boolean hasFocusable() { 4285 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4286 } 4287 4288 /** 4289 * Called by the view system when the focus state of this view changes. 4290 * When the focus change event is caused by directional navigation, direction 4291 * and previouslyFocusedRect provide insight into where the focus is coming from. 4292 * When overriding, be sure to call up through to the super class so that 4293 * the standard focus handling will occur. 4294 * 4295 * @param gainFocus True if the View has focus; false otherwise. 4296 * @param direction The direction focus has moved when requestFocus() 4297 * is called to give this view focus. Values are 4298 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4299 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4300 * It may not always apply, in which case use the default. 4301 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4302 * system, of the previously focused view. If applicable, this will be 4303 * passed in as finer grained information about where the focus is coming 4304 * from (in addition to direction). Will be <code>null</code> otherwise. 4305 */ 4306 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 4307 if (gainFocus) { 4308 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4309 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 4310 requestAccessibilityFocus(); 4311 } 4312 } 4313 4314 InputMethodManager imm = InputMethodManager.peekInstance(); 4315 if (!gainFocus) { 4316 if (isPressed()) { 4317 setPressed(false); 4318 } 4319 if (imm != null && mAttachInfo != null 4320 && mAttachInfo.mHasWindowFocus) { 4321 imm.focusOut(this); 4322 } 4323 onFocusLost(); 4324 } else if (imm != null && mAttachInfo != null 4325 && mAttachInfo.mHasWindowFocus) { 4326 imm.focusIn(this); 4327 } 4328 4329 invalidate(true); 4330 ListenerInfo li = mListenerInfo; 4331 if (li != null && li.mOnFocusChangeListener != null) { 4332 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 4333 } 4334 4335 if (mAttachInfo != null) { 4336 mAttachInfo.mKeyDispatchState.reset(this); 4337 } 4338 } 4339 4340 /** 4341 * Sends an accessibility event of the given type. If accessiiblity is 4342 * not enabled this method has no effect. The default implementation calls 4343 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 4344 * to populate information about the event source (this View), then calls 4345 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 4346 * populate the text content of the event source including its descendants, 4347 * and last calls 4348 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 4349 * on its parent to resuest sending of the event to interested parties. 4350 * <p> 4351 * If an {@link AccessibilityDelegate} has been specified via calling 4352 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4353 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 4354 * responsible for handling this call. 4355 * </p> 4356 * 4357 * @param eventType The type of the event to send, as defined by several types from 4358 * {@link android.view.accessibility.AccessibilityEvent}, such as 4359 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 4360 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 4361 * 4362 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4363 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4364 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 4365 * @see AccessibilityDelegate 4366 */ 4367 public void sendAccessibilityEvent(int eventType) { 4368 if (mAccessibilityDelegate != null) { 4369 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 4370 } else { 4371 sendAccessibilityEventInternal(eventType); 4372 } 4373 } 4374 4375 /** 4376 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 4377 * {@link AccessibilityEvent} to make an announcement which is related to some 4378 * sort of a context change for which none of the events representing UI transitions 4379 * is a good fit. For example, announcing a new page in a book. If accessibility 4380 * is not enabled this method does nothing. 4381 * 4382 * @param text The announcement text. 4383 */ 4384 public void announceForAccessibility(CharSequence text) { 4385 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4386 AccessibilityEvent event = AccessibilityEvent.obtain( 4387 AccessibilityEvent.TYPE_ANNOUNCEMENT); 4388 event.getText().add(text); 4389 sendAccessibilityEventUnchecked(event); 4390 } 4391 } 4392 4393 /** 4394 * @see #sendAccessibilityEvent(int) 4395 * 4396 * Note: Called from the default {@link AccessibilityDelegate}. 4397 */ 4398 void sendAccessibilityEventInternal(int eventType) { 4399 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4400 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 4401 } 4402 } 4403 4404 /** 4405 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 4406 * takes as an argument an empty {@link AccessibilityEvent} and does not 4407 * perform a check whether accessibility is enabled. 4408 * <p> 4409 * If an {@link AccessibilityDelegate} has been specified via calling 4410 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4411 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 4412 * is responsible for handling this call. 4413 * </p> 4414 * 4415 * @param event The event to send. 4416 * 4417 * @see #sendAccessibilityEvent(int) 4418 */ 4419 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 4420 if (mAccessibilityDelegate != null) { 4421 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 4422 } else { 4423 sendAccessibilityEventUncheckedInternal(event); 4424 } 4425 } 4426 4427 /** 4428 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 4429 * 4430 * Note: Called from the default {@link AccessibilityDelegate}. 4431 */ 4432 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 4433 if (!isShown()) { 4434 return; 4435 } 4436 onInitializeAccessibilityEvent(event); 4437 // Only a subset of accessibility events populates text content. 4438 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 4439 dispatchPopulateAccessibilityEvent(event); 4440 } 4441 // Intercept accessibility focus events fired by virtual nodes to keep 4442 // track of accessibility focus position in such nodes. 4443 final int eventType = event.getEventType(); 4444 switch (eventType) { 4445 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: { 4446 final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId( 4447 event.getSourceNodeId()); 4448 if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) { 4449 ViewRootImpl viewRootImpl = getViewRootImpl(); 4450 if (viewRootImpl != null) { 4451 viewRootImpl.setAccessibilityFocusedHost(this); 4452 } 4453 } 4454 } break; 4455 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: { 4456 final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId( 4457 event.getSourceNodeId()); 4458 if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) { 4459 ViewRootImpl viewRootImpl = getViewRootImpl(); 4460 if (viewRootImpl != null) { 4461 viewRootImpl.setAccessibilityFocusedHost(null); 4462 } 4463 } 4464 } break; 4465 } 4466 // In the beginning we called #isShown(), so we know that getParent() is not null. 4467 getParent().requestSendAccessibilityEvent(this, event); 4468 } 4469 4470 /** 4471 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 4472 * to its children for adding their text content to the event. Note that the 4473 * event text is populated in a separate dispatch path since we add to the 4474 * event not only the text of the source but also the text of all its descendants. 4475 * A typical implementation will call 4476 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 4477 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4478 * on each child. Override this method if custom population of the event text 4479 * content is required. 4480 * <p> 4481 * If an {@link AccessibilityDelegate} has been specified via calling 4482 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4483 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 4484 * is responsible for handling this call. 4485 * </p> 4486 * <p> 4487 * <em>Note:</em> Accessibility events of certain types are not dispatched for 4488 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 4489 * </p> 4490 * 4491 * @param event The event. 4492 * 4493 * @return True if the event population was completed. 4494 */ 4495 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 4496 if (mAccessibilityDelegate != null) { 4497 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 4498 } else { 4499 return dispatchPopulateAccessibilityEventInternal(event); 4500 } 4501 } 4502 4503 /** 4504 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4505 * 4506 * Note: Called from the default {@link AccessibilityDelegate}. 4507 */ 4508 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4509 onPopulateAccessibilityEvent(event); 4510 return false; 4511 } 4512 4513 /** 4514 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4515 * giving a chance to this View to populate the accessibility event with its 4516 * text content. While this method is free to modify event 4517 * attributes other than text content, doing so should normally be performed in 4518 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 4519 * <p> 4520 * Example: Adding formatted date string to an accessibility event in addition 4521 * to the text added by the super implementation: 4522 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4523 * super.onPopulateAccessibilityEvent(event); 4524 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 4525 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 4526 * mCurrentDate.getTimeInMillis(), flags); 4527 * event.getText().add(selectedDateUtterance); 4528 * }</pre> 4529 * <p> 4530 * If an {@link AccessibilityDelegate} has been specified via calling 4531 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4532 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 4533 * is responsible for handling this call. 4534 * </p> 4535 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4536 * information to the event, in case the default implementation has basic information to add. 4537 * </p> 4538 * 4539 * @param event The accessibility event which to populate. 4540 * 4541 * @see #sendAccessibilityEvent(int) 4542 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4543 */ 4544 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4545 if (mAccessibilityDelegate != null) { 4546 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 4547 } else { 4548 onPopulateAccessibilityEventInternal(event); 4549 } 4550 } 4551 4552 /** 4553 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 4554 * 4555 * Note: Called from the default {@link AccessibilityDelegate}. 4556 */ 4557 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4558 4559 } 4560 4561 /** 4562 * Initializes an {@link AccessibilityEvent} with information about 4563 * this View which is the event source. In other words, the source of 4564 * an accessibility event is the view whose state change triggered firing 4565 * the event. 4566 * <p> 4567 * Example: Setting the password property of an event in addition 4568 * to properties set by the super implementation: 4569 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4570 * super.onInitializeAccessibilityEvent(event); 4571 * event.setPassword(true); 4572 * }</pre> 4573 * <p> 4574 * If an {@link AccessibilityDelegate} has been specified via calling 4575 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4576 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 4577 * is responsible for handling this call. 4578 * </p> 4579 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4580 * information to the event, in case the default implementation has basic information to add. 4581 * </p> 4582 * @param event The event to initialize. 4583 * 4584 * @see #sendAccessibilityEvent(int) 4585 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4586 */ 4587 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4588 if (mAccessibilityDelegate != null) { 4589 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 4590 } else { 4591 onInitializeAccessibilityEventInternal(event); 4592 } 4593 } 4594 4595 /** 4596 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4597 * 4598 * Note: Called from the default {@link AccessibilityDelegate}. 4599 */ 4600 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 4601 event.setSource(this); 4602 event.setClassName(View.class.getName()); 4603 event.setPackageName(getContext().getPackageName()); 4604 event.setEnabled(isEnabled()); 4605 event.setContentDescription(mContentDescription); 4606 4607 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) { 4608 ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList; 4609 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, 4610 FOCUSABLES_ALL); 4611 event.setItemCount(focusablesTempList.size()); 4612 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 4613 focusablesTempList.clear(); 4614 } 4615 } 4616 4617 /** 4618 * Returns an {@link AccessibilityNodeInfo} representing this view from the 4619 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 4620 * This method is responsible for obtaining an accessibility node info from a 4621 * pool of reusable instances and calling 4622 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 4623 * initialize the former. 4624 * <p> 4625 * Note: The client is responsible for recycling the obtained instance by calling 4626 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 4627 * </p> 4628 * 4629 * @return A populated {@link AccessibilityNodeInfo}. 4630 * 4631 * @see AccessibilityNodeInfo 4632 */ 4633 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 4634 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 4635 if (provider != null) { 4636 return provider.createAccessibilityNodeInfo(View.NO_ID); 4637 } else { 4638 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 4639 onInitializeAccessibilityNodeInfo(info); 4640 return info; 4641 } 4642 } 4643 4644 /** 4645 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 4646 * The base implementation sets: 4647 * <ul> 4648 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 4649 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 4650 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 4651 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 4652 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 4653 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 4654 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 4655 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 4656 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 4657 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 4658 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 4659 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 4660 * </ul> 4661 * <p> 4662 * Subclasses should override this method, call the super implementation, 4663 * and set additional attributes. 4664 * </p> 4665 * <p> 4666 * If an {@link AccessibilityDelegate} has been specified via calling 4667 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4668 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 4669 * is responsible for handling this call. 4670 * </p> 4671 * 4672 * @param info The instance to initialize. 4673 */ 4674 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 4675 if (mAccessibilityDelegate != null) { 4676 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 4677 } else { 4678 onInitializeAccessibilityNodeInfoInternal(info); 4679 } 4680 } 4681 4682 /** 4683 * Gets the location of this view in screen coordintates. 4684 * 4685 * @param outRect The output location 4686 */ 4687 private void getBoundsOnScreen(Rect outRect) { 4688 if (mAttachInfo == null) { 4689 return; 4690 } 4691 4692 RectF position = mAttachInfo.mTmpTransformRect; 4693 position.set(0, 0, mRight - mLeft, mBottom - mTop); 4694 4695 if (!hasIdentityMatrix()) { 4696 getMatrix().mapRect(position); 4697 } 4698 4699 position.offset(mLeft, mTop); 4700 4701 ViewParent parent = mParent; 4702 while (parent instanceof View) { 4703 View parentView = (View) parent; 4704 4705 position.offset(-parentView.mScrollX, -parentView.mScrollY); 4706 4707 if (!parentView.hasIdentityMatrix()) { 4708 parentView.getMatrix().mapRect(position); 4709 } 4710 4711 position.offset(parentView.mLeft, parentView.mTop); 4712 4713 parent = parentView.mParent; 4714 } 4715 4716 if (parent instanceof ViewRootImpl) { 4717 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 4718 position.offset(0, -viewRootImpl.mCurScrollY); 4719 } 4720 4721 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 4722 4723 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 4724 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 4725 } 4726 4727 /** 4728 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 4729 * 4730 * Note: Called from the default {@link AccessibilityDelegate}. 4731 */ 4732 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 4733 Rect bounds = mAttachInfo.mTmpInvalRect; 4734 getDrawingRect(bounds); 4735 info.setBoundsInParent(bounds); 4736 4737 getBoundsOnScreen(bounds); 4738 info.setBoundsInScreen(bounds); 4739 4740 if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { 4741 ViewParent parent = getParentForAccessibility(); 4742 if (parent instanceof View) { 4743 info.setParent((View) parent); 4744 } 4745 } 4746 4747 info.setVisibleToUser(isVisibleToUser()); 4748 4749 info.setPackageName(mContext.getPackageName()); 4750 info.setClassName(View.class.getName()); 4751 info.setContentDescription(getContentDescription()); 4752 4753 info.setEnabled(isEnabled()); 4754 info.setClickable(isClickable()); 4755 info.setFocusable(isFocusable()); 4756 info.setFocused(isFocused()); 4757 info.setAccessibilityFocused(isAccessibilityFocused()); 4758 info.setSelected(isSelected()); 4759 info.setLongClickable(isLongClickable()); 4760 4761 // TODO: These make sense only if we are in an AdapterView but all 4762 // views can be selected. Maybe from accessiiblity perspective 4763 // we should report as selectable view in an AdapterView. 4764 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 4765 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 4766 4767 if (isFocusable()) { 4768 if (isFocused()) { 4769 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 4770 } else { 4771 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 4772 } 4773 } 4774 4775 if (!isAccessibilityFocused()) { 4776 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 4777 } else { 4778 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 4779 } 4780 4781 if (isClickable()) { 4782 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 4783 } 4784 4785 if (isLongClickable()) { 4786 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 4787 } 4788 4789 if (mContentDescription != null && mContentDescription.length() > 0) { 4790 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 4791 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 4792 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 4793 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 4794 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 4795 } 4796 } 4797 4798 /** 4799 * Computes whether this view is visible to the user. Such a view is 4800 * attached, visible, all its predecessors are visible, it is not clipped 4801 * entirely by its predecessors, and has an alpha greater than zero. 4802 * 4803 * @return Whether the view is visible on the screen. 4804 * 4805 * @hide 4806 */ 4807 protected boolean isVisibleToUser() { 4808 return isVisibleToUser(null); 4809 } 4810 4811 /** 4812 * Computes whether the given portion of this view is visible to the user. Such a view is 4813 * attached, visible, all its predecessors are visible, has an alpha greater than zero, and 4814 * the specified portion is not clipped entirely by its predecessors. 4815 * 4816 * @param boundInView the portion of the view to test; coordinates should be relative; may be 4817 * <code>null</code>, and the entire view will be tested in this case. 4818 * When <code>true</code> is returned by the function, the actual visible 4819 * region will be stored in this parameter; that is, if boundInView is fully 4820 * contained within the view, no modification will be made, otherwise regions 4821 * outside of the visible area of the view will be clipped. 4822 * 4823 * @return Whether the specified portion of the view is visible on the screen. 4824 * 4825 * @hide 4826 */ 4827 protected boolean isVisibleToUser(Rect boundInView) { 4828 Rect visibleRect = mAttachInfo.mTmpInvalRect; 4829 Point offset = mAttachInfo.mPoint; 4830 // The first two checks are made also made by isShown() which 4831 // however traverses the tree up to the parent to catch that. 4832 // Therefore, we do some fail fast check to minimize the up 4833 // tree traversal. 4834 boolean isVisible = mAttachInfo != null 4835 && mAttachInfo.mWindowVisibility == View.VISIBLE 4836 && getAlpha() > 0 4837 && isShown() 4838 && getGlobalVisibleRect(visibleRect, offset); 4839 if (isVisible && boundInView != null) { 4840 visibleRect.offset(-offset.x, -offset.y); 4841 isVisible &= boundInView.intersect(visibleRect); 4842 } 4843 return isVisible; 4844 } 4845 4846 /** 4847 * Sets a delegate for implementing accessibility support via compositon as 4848 * opposed to inheritance. The delegate's primary use is for implementing 4849 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 4850 * 4851 * @param delegate The delegate instance. 4852 * 4853 * @see AccessibilityDelegate 4854 */ 4855 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 4856 mAccessibilityDelegate = delegate; 4857 } 4858 4859 /** 4860 * Gets the provider for managing a virtual view hierarchy rooted at this View 4861 * and reported to {@link android.accessibilityservice.AccessibilityService}s 4862 * that explore the window content. 4863 * <p> 4864 * If this method returns an instance, this instance is responsible for managing 4865 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 4866 * View including the one representing the View itself. Similarly the returned 4867 * instance is responsible for performing accessibility actions on any virtual 4868 * view or the root view itself. 4869 * </p> 4870 * <p> 4871 * If an {@link AccessibilityDelegate} has been specified via calling 4872 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4873 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 4874 * is responsible for handling this call. 4875 * </p> 4876 * 4877 * @return The provider. 4878 * 4879 * @see AccessibilityNodeProvider 4880 */ 4881 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 4882 if (mAccessibilityDelegate != null) { 4883 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 4884 } else { 4885 return null; 4886 } 4887 } 4888 4889 /** 4890 * Gets the unique identifier of this view on the screen for accessibility purposes. 4891 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 4892 * 4893 * @return The view accessibility id. 4894 * 4895 * @hide 4896 */ 4897 public int getAccessibilityViewId() { 4898 if (mAccessibilityViewId == NO_ID) { 4899 mAccessibilityViewId = sNextAccessibilityViewId++; 4900 } 4901 return mAccessibilityViewId; 4902 } 4903 4904 /** 4905 * Gets the unique identifier of the window in which this View reseides. 4906 * 4907 * @return The window accessibility id. 4908 * 4909 * @hide 4910 */ 4911 public int getAccessibilityWindowId() { 4912 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 4913 } 4914 4915 /** 4916 * Gets the {@link View} description. It briefly describes the view and is 4917 * primarily used for accessibility support. Set this property to enable 4918 * better accessibility support for your application. This is especially 4919 * true for views that do not have textual representation (For example, 4920 * ImageButton). 4921 * 4922 * @return The content description. 4923 * 4924 * @attr ref android.R.styleable#View_contentDescription 4925 */ 4926 @ViewDebug.ExportedProperty(category = "accessibility") 4927 public CharSequence getContentDescription() { 4928 return mContentDescription; 4929 } 4930 4931 /** 4932 * Sets the {@link View} description. It briefly describes the view and is 4933 * primarily used for accessibility support. Set this property to enable 4934 * better accessibility support for your application. This is especially 4935 * true for views that do not have textual representation (For example, 4936 * ImageButton). 4937 * 4938 * @param contentDescription The content description. 4939 * 4940 * @attr ref android.R.styleable#View_contentDescription 4941 */ 4942 @RemotableViewMethod 4943 public void setContentDescription(CharSequence contentDescription) { 4944 mContentDescription = contentDescription; 4945 } 4946 4947 /** 4948 * Invoked whenever this view loses focus, either by losing window focus or by losing 4949 * focus within its window. This method can be used to clear any state tied to the 4950 * focus. For instance, if a button is held pressed with the trackball and the window 4951 * loses focus, this method can be used to cancel the press. 4952 * 4953 * Subclasses of View overriding this method should always call super.onFocusLost(). 4954 * 4955 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 4956 * @see #onWindowFocusChanged(boolean) 4957 * 4958 * @hide pending API council approval 4959 */ 4960 protected void onFocusLost() { 4961 resetPressedState(); 4962 } 4963 4964 private void resetPressedState() { 4965 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 4966 return; 4967 } 4968 4969 if (isPressed()) { 4970 setPressed(false); 4971 4972 if (!mHasPerformedLongPress) { 4973 removeLongPressCallback(); 4974 } 4975 } 4976 } 4977 4978 /** 4979 * Returns true if this view has focus 4980 * 4981 * @return True if this view has focus, false otherwise. 4982 */ 4983 @ViewDebug.ExportedProperty(category = "focus") 4984 public boolean isFocused() { 4985 return (mPrivateFlags & FOCUSED) != 0; 4986 } 4987 4988 /** 4989 * Find the view in the hierarchy rooted at this view that currently has 4990 * focus. 4991 * 4992 * @return The view that currently has focus, or null if no focused view can 4993 * be found. 4994 */ 4995 public View findFocus() { 4996 return (mPrivateFlags & FOCUSED) != 0 ? this : null; 4997 } 4998 4999 /** 5000 * Indicates whether this view is one of the set of scrollable containers in 5001 * its window. 5002 * 5003 * @return whether this view is one of the set of scrollable containers in 5004 * its window 5005 * 5006 * @attr ref android.R.styleable#View_isScrollContainer 5007 */ 5008 public boolean isScrollContainer() { 5009 return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0; 5010 } 5011 5012 /** 5013 * Change whether this view is one of the set of scrollable containers in 5014 * its window. This will be used to determine whether the window can 5015 * resize or must pan when a soft input area is open -- scrollable 5016 * containers allow the window to use resize mode since the container 5017 * will appropriately shrink. 5018 * 5019 * @attr ref android.R.styleable#View_isScrollContainer 5020 */ 5021 public void setScrollContainer(boolean isScrollContainer) { 5022 if (isScrollContainer) { 5023 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) { 5024 mAttachInfo.mScrollContainers.add(this); 5025 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 5026 } 5027 mPrivateFlags |= SCROLL_CONTAINER; 5028 } else { 5029 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 5030 mAttachInfo.mScrollContainers.remove(this); 5031 } 5032 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED); 5033 } 5034 } 5035 5036 /** 5037 * Returns the quality of the drawing cache. 5038 * 5039 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5040 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5041 * 5042 * @see #setDrawingCacheQuality(int) 5043 * @see #setDrawingCacheEnabled(boolean) 5044 * @see #isDrawingCacheEnabled() 5045 * 5046 * @attr ref android.R.styleable#View_drawingCacheQuality 5047 */ 5048 public int getDrawingCacheQuality() { 5049 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5050 } 5051 5052 /** 5053 * Set the drawing cache quality of this view. This value is used only when the 5054 * drawing cache is enabled 5055 * 5056 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5057 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5058 * 5059 * @see #getDrawingCacheQuality() 5060 * @see #setDrawingCacheEnabled(boolean) 5061 * @see #isDrawingCacheEnabled() 5062 * 5063 * @attr ref android.R.styleable#View_drawingCacheQuality 5064 */ 5065 public void setDrawingCacheQuality(int quality) { 5066 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5067 } 5068 5069 /** 5070 * Returns whether the screen should remain on, corresponding to the current 5071 * value of {@link #KEEP_SCREEN_ON}. 5072 * 5073 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5074 * 5075 * @see #setKeepScreenOn(boolean) 5076 * 5077 * @attr ref android.R.styleable#View_keepScreenOn 5078 */ 5079 public boolean getKeepScreenOn() { 5080 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5081 } 5082 5083 /** 5084 * Controls whether the screen should remain on, modifying the 5085 * value of {@link #KEEP_SCREEN_ON}. 5086 * 5087 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5088 * 5089 * @see #getKeepScreenOn() 5090 * 5091 * @attr ref android.R.styleable#View_keepScreenOn 5092 */ 5093 public void setKeepScreenOn(boolean keepScreenOn) { 5094 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5095 } 5096 5097 /** 5098 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5099 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5100 * 5101 * @attr ref android.R.styleable#View_nextFocusLeft 5102 */ 5103 public int getNextFocusLeftId() { 5104 return mNextFocusLeftId; 5105 } 5106 5107 /** 5108 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5109 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5110 * decide automatically. 5111 * 5112 * @attr ref android.R.styleable#View_nextFocusLeft 5113 */ 5114 public void setNextFocusLeftId(int nextFocusLeftId) { 5115 mNextFocusLeftId = nextFocusLeftId; 5116 } 5117 5118 /** 5119 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5120 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5121 * 5122 * @attr ref android.R.styleable#View_nextFocusRight 5123 */ 5124 public int getNextFocusRightId() { 5125 return mNextFocusRightId; 5126 } 5127 5128 /** 5129 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5130 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5131 * decide automatically. 5132 * 5133 * @attr ref android.R.styleable#View_nextFocusRight 5134 */ 5135 public void setNextFocusRightId(int nextFocusRightId) { 5136 mNextFocusRightId = nextFocusRightId; 5137 } 5138 5139 /** 5140 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5141 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5142 * 5143 * @attr ref android.R.styleable#View_nextFocusUp 5144 */ 5145 public int getNextFocusUpId() { 5146 return mNextFocusUpId; 5147 } 5148 5149 /** 5150 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5151 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5152 * decide automatically. 5153 * 5154 * @attr ref android.R.styleable#View_nextFocusUp 5155 */ 5156 public void setNextFocusUpId(int nextFocusUpId) { 5157 mNextFocusUpId = nextFocusUpId; 5158 } 5159 5160 /** 5161 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5162 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5163 * 5164 * @attr ref android.R.styleable#View_nextFocusDown 5165 */ 5166 public int getNextFocusDownId() { 5167 return mNextFocusDownId; 5168 } 5169 5170 /** 5171 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5172 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 5173 * decide automatically. 5174 * 5175 * @attr ref android.R.styleable#View_nextFocusDown 5176 */ 5177 public void setNextFocusDownId(int nextFocusDownId) { 5178 mNextFocusDownId = nextFocusDownId; 5179 } 5180 5181 /** 5182 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5183 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5184 * 5185 * @attr ref android.R.styleable#View_nextFocusForward 5186 */ 5187 public int getNextFocusForwardId() { 5188 return mNextFocusForwardId; 5189 } 5190 5191 /** 5192 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5193 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 5194 * decide automatically. 5195 * 5196 * @attr ref android.R.styleable#View_nextFocusForward 5197 */ 5198 public void setNextFocusForwardId(int nextFocusForwardId) { 5199 mNextFocusForwardId = nextFocusForwardId; 5200 } 5201 5202 /** 5203 * Returns the visibility of this view and all of its ancestors 5204 * 5205 * @return True if this view and all of its ancestors are {@link #VISIBLE} 5206 */ 5207 public boolean isShown() { 5208 View current = this; 5209 //noinspection ConstantConditions 5210 do { 5211 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5212 return false; 5213 } 5214 ViewParent parent = current.mParent; 5215 if (parent == null) { 5216 return false; // We are not attached to the view root 5217 } 5218 if (!(parent instanceof View)) { 5219 return true; 5220 } 5221 current = (View) parent; 5222 } while (current != null); 5223 5224 return false; 5225 } 5226 5227 /** 5228 * Called by the view hierarchy when the content insets for a window have 5229 * changed, to allow it to adjust its content to fit within those windows. 5230 * The content insets tell you the space that the status bar, input method, 5231 * and other system windows infringe on the application's window. 5232 * 5233 * <p>You do not normally need to deal with this function, since the default 5234 * window decoration given to applications takes care of applying it to the 5235 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 5236 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 5237 * and your content can be placed under those system elements. You can then 5238 * use this method within your view hierarchy if you have parts of your UI 5239 * which you would like to ensure are not being covered. 5240 * 5241 * <p>The default implementation of this method simply applies the content 5242 * inset's to the view's padding. This can be enabled through 5243 * {@link #setFitsSystemWindows(boolean)}. Alternatively, you can override 5244 * the method and handle the insets however you would like. Note that the 5245 * insets provided by the framework are always relative to the far edges 5246 * of the window, not accounting for the location of the called view within 5247 * that window. (In fact when this method is called you do not yet know 5248 * where the layout will place the view, as it is done before layout happens.) 5249 * 5250 * <p>Note: unlike many View methods, there is no dispatch phase to this 5251 * call. If you are overriding it in a ViewGroup and want to allow the 5252 * call to continue to your children, you must be sure to call the super 5253 * implementation. 5254 * 5255 * <p>Here is a sample layout that makes use of fitting system windows 5256 * to have controls for a video view placed inside of the window decorations 5257 * that it hides and shows. This can be used with code like the second 5258 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 5259 * 5260 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 5261 * 5262 * @param insets Current content insets of the window. Prior to 5263 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 5264 * the insets or else you and Android will be unhappy. 5265 * 5266 * @return Return true if this view applied the insets and it should not 5267 * continue propagating further down the hierarchy, false otherwise. 5268 */ 5269 protected boolean fitSystemWindows(Rect insets) { 5270 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 5271 mUserPaddingStart = -1; 5272 mUserPaddingEnd = -1; 5273 mUserPaddingRelative = false; 5274 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 5275 || mAttachInfo == null 5276 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 5277 internalSetPadding(insets.left, insets.top, insets.right, insets.bottom); 5278 return true; 5279 } else { 5280 internalSetPadding(0, 0, 0, 0); 5281 return false; 5282 } 5283 } 5284 return false; 5285 } 5286 5287 /** 5288 * Set whether or not this view should account for system screen decorations 5289 * such as the status bar and inset its content. This allows this view to be 5290 * positioned in absolute screen coordinates and remain visible to the user. 5291 * 5292 * <p>This should only be used by top-level window decor views. 5293 * 5294 * @param fitSystemWindows true to inset content for system screen decorations, false for 5295 * default behavior. 5296 * 5297 * @attr ref android.R.styleable#View_fitsSystemWindows 5298 */ 5299 public void setFitsSystemWindows(boolean fitSystemWindows) { 5300 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 5301 } 5302 5303 /** 5304 * Check for state of {@link #setFitsSystemWindows(boolean). If this method 5305 * returns true, this view 5306 * will account for system screen decorations such as the status bar and inset its 5307 * content. This allows the view to be positioned in absolute screen coordinates 5308 * and remain visible to the user. 5309 * 5310 * @return true if this view will adjust its content bounds for system screen decorations. 5311 * 5312 * @attr ref android.R.styleable#View_fitsSystemWindows 5313 */ 5314 public boolean getFitsSystemWindows() { 5315 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 5316 } 5317 5318 /** @hide */ 5319 public boolean fitsSystemWindows() { 5320 return getFitsSystemWindows(); 5321 } 5322 5323 /** 5324 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 5325 */ 5326 public void requestFitSystemWindows() { 5327 if (mParent != null) { 5328 mParent.requestFitSystemWindows(); 5329 } 5330 } 5331 5332 /** 5333 * For use by PhoneWindow to make its own system window fitting optional. 5334 * @hide 5335 */ 5336 public void makeOptionalFitsSystemWindows() { 5337 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 5338 } 5339 5340 /** 5341 * Returns the visibility status for this view. 5342 * 5343 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5344 * @attr ref android.R.styleable#View_visibility 5345 */ 5346 @ViewDebug.ExportedProperty(mapping = { 5347 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 5348 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 5349 @ViewDebug.IntToString(from = GONE, to = "GONE") 5350 }) 5351 public int getVisibility() { 5352 return mViewFlags & VISIBILITY_MASK; 5353 } 5354 5355 /** 5356 * Set the enabled state of this view. 5357 * 5358 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5359 * @attr ref android.R.styleable#View_visibility 5360 */ 5361 @RemotableViewMethod 5362 public void setVisibility(int visibility) { 5363 setFlags(visibility, VISIBILITY_MASK); 5364 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 5365 } 5366 5367 /** 5368 * Returns the enabled status for this view. The interpretation of the 5369 * enabled state varies by subclass. 5370 * 5371 * @return True if this view is enabled, false otherwise. 5372 */ 5373 @ViewDebug.ExportedProperty 5374 public boolean isEnabled() { 5375 return (mViewFlags & ENABLED_MASK) == ENABLED; 5376 } 5377 5378 /** 5379 * Set the enabled state of this view. The interpretation of the enabled 5380 * state varies by subclass. 5381 * 5382 * @param enabled True if this view is enabled, false otherwise. 5383 */ 5384 @RemotableViewMethod 5385 public void setEnabled(boolean enabled) { 5386 if (enabled == isEnabled()) return; 5387 5388 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 5389 5390 /* 5391 * The View most likely has to change its appearance, so refresh 5392 * the drawable state. 5393 */ 5394 refreshDrawableState(); 5395 5396 // Invalidate too, since the default behavior for views is to be 5397 // be drawn at 50% alpha rather than to change the drawable. 5398 invalidate(true); 5399 } 5400 5401 /** 5402 * Set whether this view can receive the focus. 5403 * 5404 * Setting this to false will also ensure that this view is not focusable 5405 * in touch mode. 5406 * 5407 * @param focusable If true, this view can receive the focus. 5408 * 5409 * @see #setFocusableInTouchMode(boolean) 5410 * @attr ref android.R.styleable#View_focusable 5411 */ 5412 public void setFocusable(boolean focusable) { 5413 if (!focusable) { 5414 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 5415 } 5416 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 5417 } 5418 5419 /** 5420 * Set whether this view can receive focus while in touch mode. 5421 * 5422 * Setting this to true will also ensure that this view is focusable. 5423 * 5424 * @param focusableInTouchMode If true, this view can receive the focus while 5425 * in touch mode. 5426 * 5427 * @see #setFocusable(boolean) 5428 * @attr ref android.R.styleable#View_focusableInTouchMode 5429 */ 5430 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 5431 // Focusable in touch mode should always be set before the focusable flag 5432 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 5433 // which, in touch mode, will not successfully request focus on this view 5434 // because the focusable in touch mode flag is not set 5435 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 5436 if (focusableInTouchMode) { 5437 setFlags(FOCUSABLE, FOCUSABLE_MASK); 5438 } 5439 } 5440 5441 /** 5442 * Set whether this view should have sound effects enabled for events such as 5443 * clicking and touching. 5444 * 5445 * <p>You may wish to disable sound effects for a view if you already play sounds, 5446 * for instance, a dial key that plays dtmf tones. 5447 * 5448 * @param soundEffectsEnabled whether sound effects are enabled for this view. 5449 * @see #isSoundEffectsEnabled() 5450 * @see #playSoundEffect(int) 5451 * @attr ref android.R.styleable#View_soundEffectsEnabled 5452 */ 5453 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 5454 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 5455 } 5456 5457 /** 5458 * @return whether this view should have sound effects enabled for events such as 5459 * clicking and touching. 5460 * 5461 * @see #setSoundEffectsEnabled(boolean) 5462 * @see #playSoundEffect(int) 5463 * @attr ref android.R.styleable#View_soundEffectsEnabled 5464 */ 5465 @ViewDebug.ExportedProperty 5466 public boolean isSoundEffectsEnabled() { 5467 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 5468 } 5469 5470 /** 5471 * Set whether this view should have haptic feedback for events such as 5472 * long presses. 5473 * 5474 * <p>You may wish to disable haptic feedback if your view already controls 5475 * its own haptic feedback. 5476 * 5477 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 5478 * @see #isHapticFeedbackEnabled() 5479 * @see #performHapticFeedback(int) 5480 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 5481 */ 5482 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 5483 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 5484 } 5485 5486 /** 5487 * @return whether this view should have haptic feedback enabled for events 5488 * long presses. 5489 * 5490 * @see #setHapticFeedbackEnabled(boolean) 5491 * @see #performHapticFeedback(int) 5492 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 5493 */ 5494 @ViewDebug.ExportedProperty 5495 public boolean isHapticFeedbackEnabled() { 5496 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 5497 } 5498 5499 /** 5500 * Returns the layout direction for this view. 5501 * 5502 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 5503 * {@link #LAYOUT_DIRECTION_RTL}, 5504 * {@link #LAYOUT_DIRECTION_INHERIT} or 5505 * {@link #LAYOUT_DIRECTION_LOCALE}. 5506 * 5507 * @attr ref android.R.styleable#View_layoutDirection 5508 * @hide 5509 */ 5510 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5511 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 5512 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 5513 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 5514 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 5515 }) 5516 public int getLayoutDirection() { 5517 return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT; 5518 } 5519 5520 /** 5521 * Set the layout direction for this view. This will propagate a reset of layout direction 5522 * resolution to the view's children and resolve layout direction for this view. 5523 * 5524 * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR}, 5525 * {@link #LAYOUT_DIRECTION_RTL}, 5526 * {@link #LAYOUT_DIRECTION_INHERIT} or 5527 * {@link #LAYOUT_DIRECTION_LOCALE}. 5528 * 5529 * @attr ref android.R.styleable#View_layoutDirection 5530 * @hide 5531 */ 5532 @RemotableViewMethod 5533 public void setLayoutDirection(int layoutDirection) { 5534 if (getLayoutDirection() != layoutDirection) { 5535 // Reset the current layout direction and the resolved one 5536 mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK; 5537 resetResolvedLayoutDirection(); 5538 // Set the new layout direction (filtered) and ask for a layout pass 5539 mPrivateFlags2 |= 5540 ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK); 5541 requestLayout(); 5542 } 5543 } 5544 5545 /** 5546 * Returns the resolved layout direction for this view. 5547 * 5548 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 5549 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 5550 * @hide 5551 */ 5552 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5553 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 5554 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 5555 }) 5556 public int getResolvedLayoutDirection() { 5557 // The layout diretion will be resolved only if needed 5558 if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) { 5559 resolveLayoutDirection(); 5560 } 5561 return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ? 5562 LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 5563 } 5564 5565 /** 5566 * Indicates whether or not this view's layout is right-to-left. This is resolved from 5567 * layout attribute and/or the inherited value from the parent 5568 * 5569 * @return true if the layout is right-to-left. 5570 * @hide 5571 */ 5572 @ViewDebug.ExportedProperty(category = "layout") 5573 public boolean isLayoutRtl() { 5574 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 5575 } 5576 5577 /** 5578 * Indicates whether the view is currently tracking transient state that the 5579 * app should not need to concern itself with saving and restoring, but that 5580 * the framework should take special note to preserve when possible. 5581 * 5582 * <p>A view with transient state cannot be trivially rebound from an external 5583 * data source, such as an adapter binding item views in a list. This may be 5584 * because the view is performing an animation, tracking user selection 5585 * of content, or similar.</p> 5586 * 5587 * @return true if the view has transient state 5588 */ 5589 @ViewDebug.ExportedProperty(category = "layout") 5590 public boolean hasTransientState() { 5591 return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE; 5592 } 5593 5594 /** 5595 * Set whether this view is currently tracking transient state that the 5596 * framework should attempt to preserve when possible. This flag is reference counted, 5597 * so every call to setHasTransientState(true) should be paired with a later call 5598 * to setHasTransientState(false). 5599 * 5600 * <p>A view with transient state cannot be trivially rebound from an external 5601 * data source, such as an adapter binding item views in a list. This may be 5602 * because the view is performing an animation, tracking user selection 5603 * of content, or similar.</p> 5604 * 5605 * @param hasTransientState true if this view has transient state 5606 */ 5607 public void setHasTransientState(boolean hasTransientState) { 5608 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 5609 mTransientStateCount - 1; 5610 if (mTransientStateCount < 0) { 5611 mTransientStateCount = 0; 5612 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 5613 "unmatched pair of setHasTransientState calls"); 5614 } 5615 if ((hasTransientState && mTransientStateCount == 1) || 5616 (!hasTransientState && mTransientStateCount == 0)) { 5617 // update flag if we've just incremented up from 0 or decremented down to 0 5618 mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) | 5619 (hasTransientState ? HAS_TRANSIENT_STATE : 0); 5620 if (mParent != null) { 5621 try { 5622 mParent.childHasTransientStateChanged(this, hasTransientState); 5623 } catch (AbstractMethodError e) { 5624 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 5625 " does not fully implement ViewParent", e); 5626 } 5627 } 5628 } 5629 } 5630 5631 /** 5632 * If this view doesn't do any drawing on its own, set this flag to 5633 * allow further optimizations. By default, this flag is not set on 5634 * View, but could be set on some View subclasses such as ViewGroup. 5635 * 5636 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 5637 * you should clear this flag. 5638 * 5639 * @param willNotDraw whether or not this View draw on its own 5640 */ 5641 public void setWillNotDraw(boolean willNotDraw) { 5642 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 5643 } 5644 5645 /** 5646 * Returns whether or not this View draws on its own. 5647 * 5648 * @return true if this view has nothing to draw, false otherwise 5649 */ 5650 @ViewDebug.ExportedProperty(category = "drawing") 5651 public boolean willNotDraw() { 5652 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 5653 } 5654 5655 /** 5656 * When a View's drawing cache is enabled, drawing is redirected to an 5657 * offscreen bitmap. Some views, like an ImageView, must be able to 5658 * bypass this mechanism if they already draw a single bitmap, to avoid 5659 * unnecessary usage of the memory. 5660 * 5661 * @param willNotCacheDrawing true if this view does not cache its 5662 * drawing, false otherwise 5663 */ 5664 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 5665 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 5666 } 5667 5668 /** 5669 * Returns whether or not this View can cache its drawing or not. 5670 * 5671 * @return true if this view does not cache its drawing, false otherwise 5672 */ 5673 @ViewDebug.ExportedProperty(category = "drawing") 5674 public boolean willNotCacheDrawing() { 5675 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 5676 } 5677 5678 /** 5679 * Indicates whether this view reacts to click events or not. 5680 * 5681 * @return true if the view is clickable, false otherwise 5682 * 5683 * @see #setClickable(boolean) 5684 * @attr ref android.R.styleable#View_clickable 5685 */ 5686 @ViewDebug.ExportedProperty 5687 public boolean isClickable() { 5688 return (mViewFlags & CLICKABLE) == CLICKABLE; 5689 } 5690 5691 /** 5692 * Enables or disables click events for this view. When a view 5693 * is clickable it will change its state to "pressed" on every click. 5694 * Subclasses should set the view clickable to visually react to 5695 * user's clicks. 5696 * 5697 * @param clickable true to make the view clickable, false otherwise 5698 * 5699 * @see #isClickable() 5700 * @attr ref android.R.styleable#View_clickable 5701 */ 5702 public void setClickable(boolean clickable) { 5703 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 5704 } 5705 5706 /** 5707 * Indicates whether this view reacts to long click events or not. 5708 * 5709 * @return true if the view is long clickable, false otherwise 5710 * 5711 * @see #setLongClickable(boolean) 5712 * @attr ref android.R.styleable#View_longClickable 5713 */ 5714 public boolean isLongClickable() { 5715 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 5716 } 5717 5718 /** 5719 * Enables or disables long click events for this view. When a view is long 5720 * clickable it reacts to the user holding down the button for a longer 5721 * duration than a tap. This event can either launch the listener or a 5722 * context menu. 5723 * 5724 * @param longClickable true to make the view long clickable, false otherwise 5725 * @see #isLongClickable() 5726 * @attr ref android.R.styleable#View_longClickable 5727 */ 5728 public void setLongClickable(boolean longClickable) { 5729 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 5730 } 5731 5732 /** 5733 * Sets the pressed state for this view. 5734 * 5735 * @see #isClickable() 5736 * @see #setClickable(boolean) 5737 * 5738 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 5739 * the View's internal state from a previously set "pressed" state. 5740 */ 5741 public void setPressed(boolean pressed) { 5742 final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED); 5743 5744 if (pressed) { 5745 mPrivateFlags |= PRESSED; 5746 } else { 5747 mPrivateFlags &= ~PRESSED; 5748 } 5749 5750 if (needsRefresh) { 5751 refreshDrawableState(); 5752 } 5753 dispatchSetPressed(pressed); 5754 } 5755 5756 /** 5757 * Dispatch setPressed to all of this View's children. 5758 * 5759 * @see #setPressed(boolean) 5760 * 5761 * @param pressed The new pressed state 5762 */ 5763 protected void dispatchSetPressed(boolean pressed) { 5764 } 5765 5766 /** 5767 * Indicates whether the view is currently in pressed state. Unless 5768 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 5769 * the pressed state. 5770 * 5771 * @see #setPressed(boolean) 5772 * @see #isClickable() 5773 * @see #setClickable(boolean) 5774 * 5775 * @return true if the view is currently pressed, false otherwise 5776 */ 5777 public boolean isPressed() { 5778 return (mPrivateFlags & PRESSED) == PRESSED; 5779 } 5780 5781 /** 5782 * Indicates whether this view will save its state (that is, 5783 * whether its {@link #onSaveInstanceState} method will be called). 5784 * 5785 * @return Returns true if the view state saving is enabled, else false. 5786 * 5787 * @see #setSaveEnabled(boolean) 5788 * @attr ref android.R.styleable#View_saveEnabled 5789 */ 5790 public boolean isSaveEnabled() { 5791 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 5792 } 5793 5794 /** 5795 * Controls whether the saving of this view's state is 5796 * enabled (that is, whether its {@link #onSaveInstanceState} method 5797 * will be called). Note that even if freezing is enabled, the 5798 * view still must have an id assigned to it (via {@link #setId(int)}) 5799 * for its state to be saved. This flag can only disable the 5800 * saving of this view; any child views may still have their state saved. 5801 * 5802 * @param enabled Set to false to <em>disable</em> state saving, or true 5803 * (the default) to allow it. 5804 * 5805 * @see #isSaveEnabled() 5806 * @see #setId(int) 5807 * @see #onSaveInstanceState() 5808 * @attr ref android.R.styleable#View_saveEnabled 5809 */ 5810 public void setSaveEnabled(boolean enabled) { 5811 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 5812 } 5813 5814 /** 5815 * Gets whether the framework should discard touches when the view's 5816 * window is obscured by another visible window. 5817 * Refer to the {@link View} security documentation for more details. 5818 * 5819 * @return True if touch filtering is enabled. 5820 * 5821 * @see #setFilterTouchesWhenObscured(boolean) 5822 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 5823 */ 5824 @ViewDebug.ExportedProperty 5825 public boolean getFilterTouchesWhenObscured() { 5826 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 5827 } 5828 5829 /** 5830 * Sets whether the framework should discard touches when the view's 5831 * window is obscured by another visible window. 5832 * Refer to the {@link View} security documentation for more details. 5833 * 5834 * @param enabled True if touch filtering should be enabled. 5835 * 5836 * @see #getFilterTouchesWhenObscured 5837 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 5838 */ 5839 public void setFilterTouchesWhenObscured(boolean enabled) { 5840 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 5841 FILTER_TOUCHES_WHEN_OBSCURED); 5842 } 5843 5844 /** 5845 * Indicates whether the entire hierarchy under this view will save its 5846 * state when a state saving traversal occurs from its parent. The default 5847 * is true; if false, these views will not be saved unless 5848 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 5849 * 5850 * @return Returns true if the view state saving from parent is enabled, else false. 5851 * 5852 * @see #setSaveFromParentEnabled(boolean) 5853 */ 5854 public boolean isSaveFromParentEnabled() { 5855 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 5856 } 5857 5858 /** 5859 * Controls whether the entire hierarchy under this view will save its 5860 * state when a state saving traversal occurs from its parent. The default 5861 * is true; if false, these views will not be saved unless 5862 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 5863 * 5864 * @param enabled Set to false to <em>disable</em> state saving, or true 5865 * (the default) to allow it. 5866 * 5867 * @see #isSaveFromParentEnabled() 5868 * @see #setId(int) 5869 * @see #onSaveInstanceState() 5870 */ 5871 public void setSaveFromParentEnabled(boolean enabled) { 5872 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 5873 } 5874 5875 5876 /** 5877 * Returns whether this View is able to take focus. 5878 * 5879 * @return True if this view can take focus, or false otherwise. 5880 * @attr ref android.R.styleable#View_focusable 5881 */ 5882 @ViewDebug.ExportedProperty(category = "focus") 5883 public final boolean isFocusable() { 5884 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 5885 } 5886 5887 /** 5888 * When a view is focusable, it may not want to take focus when in touch mode. 5889 * For example, a button would like focus when the user is navigating via a D-pad 5890 * so that the user can click on it, but once the user starts touching the screen, 5891 * the button shouldn't take focus 5892 * @return Whether the view is focusable in touch mode. 5893 * @attr ref android.R.styleable#View_focusableInTouchMode 5894 */ 5895 @ViewDebug.ExportedProperty 5896 public final boolean isFocusableInTouchMode() { 5897 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 5898 } 5899 5900 /** 5901 * Find the nearest view in the specified direction that can take focus. 5902 * This does not actually give focus to that view. 5903 * 5904 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5905 * 5906 * @return The nearest focusable in the specified direction, or null if none 5907 * can be found. 5908 */ 5909 public View focusSearch(int direction) { 5910 if (mParent != null) { 5911 return mParent.focusSearch(this, direction); 5912 } else { 5913 return null; 5914 } 5915 } 5916 5917 /** 5918 * This method is the last chance for the focused view and its ancestors to 5919 * respond to an arrow key. This is called when the focused view did not 5920 * consume the key internally, nor could the view system find a new view in 5921 * the requested direction to give focus to. 5922 * 5923 * @param focused The currently focused view. 5924 * @param direction The direction focus wants to move. One of FOCUS_UP, 5925 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 5926 * @return True if the this view consumed this unhandled move. 5927 */ 5928 public boolean dispatchUnhandledMove(View focused, int direction) { 5929 return false; 5930 } 5931 5932 /** 5933 * If a user manually specified the next view id for a particular direction, 5934 * use the root to look up the view. 5935 * @param root The root view of the hierarchy containing this view. 5936 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 5937 * or FOCUS_BACKWARD. 5938 * @return The user specified next view, or null if there is none. 5939 */ 5940 View findUserSetNextFocus(View root, int direction) { 5941 switch (direction) { 5942 case FOCUS_LEFT: 5943 if (mNextFocusLeftId == View.NO_ID) return null; 5944 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 5945 case FOCUS_RIGHT: 5946 if (mNextFocusRightId == View.NO_ID) return null; 5947 return findViewInsideOutShouldExist(root, mNextFocusRightId); 5948 case FOCUS_UP: 5949 if (mNextFocusUpId == View.NO_ID) return null; 5950 return findViewInsideOutShouldExist(root, mNextFocusUpId); 5951 case FOCUS_DOWN: 5952 if (mNextFocusDownId == View.NO_ID) return null; 5953 return findViewInsideOutShouldExist(root, mNextFocusDownId); 5954 case FOCUS_FORWARD: 5955 if (mNextFocusForwardId == View.NO_ID) return null; 5956 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 5957 case FOCUS_BACKWARD: { 5958 if (mID == View.NO_ID) return null; 5959 final int id = mID; 5960 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5961 @Override 5962 public boolean apply(View t) { 5963 return t.mNextFocusForwardId == id; 5964 } 5965 }); 5966 } 5967 } 5968 return null; 5969 } 5970 5971 private View findViewInsideOutShouldExist(View root, final int childViewId) { 5972 View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5973 @Override 5974 public boolean apply(View t) { 5975 return t.mID == childViewId; 5976 } 5977 }); 5978 5979 if (result == null) { 5980 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified " 5981 + "by user for id " + childViewId); 5982 } 5983 return result; 5984 } 5985 5986 /** 5987 * Find and return all focusable views that are descendants of this view, 5988 * possibly including this view if it is focusable itself. 5989 * 5990 * @param direction The direction of the focus 5991 * @return A list of focusable views 5992 */ 5993 public ArrayList<View> getFocusables(int direction) { 5994 ArrayList<View> result = new ArrayList<View>(24); 5995 addFocusables(result, direction); 5996 return result; 5997 } 5998 5999 /** 6000 * Add any focusable views that are descendants of this view (possibly 6001 * including this view if it is focusable itself) to views. If we are in touch mode, 6002 * only add views that are also focusable in touch mode. 6003 * 6004 * @param views Focusable views found so far 6005 * @param direction The direction of the focus 6006 */ 6007 public void addFocusables(ArrayList<View> views, int direction) { 6008 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 6009 } 6010 6011 /** 6012 * Adds any focusable views that are descendants of this view (possibly 6013 * including this view if it is focusable itself) to views. This method 6014 * adds all focusable views regardless if we are in touch mode or 6015 * only views focusable in touch mode if we are in touch mode or 6016 * only views that can take accessibility focus if accessibility is enabeld 6017 * depending on the focusable mode paramater. 6018 * 6019 * @param views Focusable views found so far or null if all we are interested is 6020 * the number of focusables. 6021 * @param direction The direction of the focus. 6022 * @param focusableMode The type of focusables to be added. 6023 * 6024 * @see #FOCUSABLES_ALL 6025 * @see #FOCUSABLES_TOUCH_MODE 6026 */ 6027 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 6028 if (views == null) { 6029 return; 6030 } 6031 if ((focusableMode & FOCUSABLES_ACCESSIBILITY) == FOCUSABLES_ACCESSIBILITY) { 6032 if (AccessibilityManager.getInstance(mContext).isEnabled() 6033 && includeForAccessibility()) { 6034 views.add(this); 6035 return; 6036 } 6037 } 6038 if (!isFocusable()) { 6039 return; 6040 } 6041 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 6042 && isInTouchMode() && !isFocusableInTouchMode()) { 6043 return; 6044 } 6045 views.add(this); 6046 } 6047 6048 /** 6049 * Finds the Views that contain given text. The containment is case insensitive. 6050 * The search is performed by either the text that the View renders or the content 6051 * description that describes the view for accessibility purposes and the view does 6052 * not render or both. Clients can specify how the search is to be performed via 6053 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 6054 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 6055 * 6056 * @param outViews The output list of matching Views. 6057 * @param searched The text to match against. 6058 * 6059 * @see #FIND_VIEWS_WITH_TEXT 6060 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 6061 * @see #setContentDescription(CharSequence) 6062 */ 6063 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 6064 if (getAccessibilityNodeProvider() != null) { 6065 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 6066 outViews.add(this); 6067 } 6068 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 6069 && (searched != null && searched.length() > 0) 6070 && (mContentDescription != null && mContentDescription.length() > 0)) { 6071 String searchedLowerCase = searched.toString().toLowerCase(); 6072 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 6073 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 6074 outViews.add(this); 6075 } 6076 } 6077 } 6078 6079 /** 6080 * Find and return all touchable views that are descendants of this view, 6081 * possibly including this view if it is touchable itself. 6082 * 6083 * @return A list of touchable views 6084 */ 6085 public ArrayList<View> getTouchables() { 6086 ArrayList<View> result = new ArrayList<View>(); 6087 addTouchables(result); 6088 return result; 6089 } 6090 6091 /** 6092 * Add any touchable views that are descendants of this view (possibly 6093 * including this view if it is touchable itself) to views. 6094 * 6095 * @param views Touchable views found so far 6096 */ 6097 public void addTouchables(ArrayList<View> views) { 6098 final int viewFlags = mViewFlags; 6099 6100 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 6101 && (viewFlags & ENABLED_MASK) == ENABLED) { 6102 views.add(this); 6103 } 6104 } 6105 6106 /** 6107 * Returns whether this View is accessibility focused. 6108 * 6109 * @return True if this View is accessibility focused. 6110 */ 6111 boolean isAccessibilityFocused() { 6112 return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0; 6113 } 6114 6115 /** 6116 * Call this to try to give accessibility focus to this view. 6117 * 6118 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 6119 * returns false or the view is no visible or the view already has accessibility 6120 * focus. 6121 * 6122 * See also {@link #focusSearch(int)}, which is what you call to say that you 6123 * have focus, and you want your parent to look for the next one. 6124 * 6125 * @return Whether this view actually took accessibility focus. 6126 * 6127 * @hide 6128 */ 6129 public boolean requestAccessibilityFocus() { 6130 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 6131 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 6132 return false; 6133 } 6134 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6135 return false; 6136 } 6137 if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) { 6138 mPrivateFlags2 |= ACCESSIBILITY_FOCUSED; 6139 ViewRootImpl viewRootImpl = getViewRootImpl(); 6140 if (viewRootImpl != null) { 6141 viewRootImpl.setAccessibilityFocusedHost(this); 6142 } 6143 invalidate(); 6144 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 6145 notifyAccessibilityStateChanged(); 6146 // Try to give input focus to this view - not a descendant. 6147 requestFocusNoSearch(View.FOCUS_DOWN, null); 6148 return true; 6149 } 6150 return false; 6151 } 6152 6153 /** 6154 * Call this to try to clear accessibility focus of this view. 6155 * 6156 * See also {@link #focusSearch(int)}, which is what you call to say that you 6157 * have focus, and you want your parent to look for the next one. 6158 * 6159 * @hide 6160 */ 6161 public void clearAccessibilityFocus() { 6162 if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) { 6163 mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED; 6164 ViewRootImpl viewRootImpl = getViewRootImpl(); 6165 if (viewRootImpl != null) { 6166 viewRootImpl.setAccessibilityFocusedHost(null); 6167 } 6168 invalidate(); 6169 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 6170 notifyAccessibilityStateChanged(); 6171 6172 // Clear the text navigation state. 6173 setAccessibilityCursorPosition(-1); 6174 6175 // Try to move accessibility focus to the input focus. 6176 View rootView = getRootView(); 6177 if (rootView != null) { 6178 View inputFocus = rootView.findFocus(); 6179 if (inputFocus != null) { 6180 inputFocus.requestAccessibilityFocus(); 6181 } 6182 } 6183 } 6184 } 6185 6186 /** 6187 * Find the best view to take accessibility focus from a hover. 6188 * This function finds the deepest actionable view and if that 6189 * fails ask the parent to take accessibility focus from hover. 6190 * 6191 * @param x The X hovered location in this view coorditantes. 6192 * @param y The Y hovered location in this view coorditantes. 6193 * @return Whether the request was handled. 6194 * 6195 * @hide 6196 */ 6197 public boolean requestAccessibilityFocusFromHover(float x, float y) { 6198 if (onRequestAccessibilityFocusFromHover(x, y)) { 6199 return true; 6200 } 6201 ViewParent parent = mParent; 6202 if (parent instanceof View) { 6203 View parentView = (View) parent; 6204 6205 float[] position = mAttachInfo.mTmpTransformLocation; 6206 position[0] = x; 6207 position[1] = y; 6208 6209 // Compensate for the transformation of the current matrix. 6210 if (!hasIdentityMatrix()) { 6211 getMatrix().mapPoints(position); 6212 } 6213 6214 // Compensate for the parent scroll and the offset 6215 // of this view stop from the parent top. 6216 position[0] += mLeft - parentView.mScrollX; 6217 position[1] += mTop - parentView.mScrollY; 6218 6219 return parentView.requestAccessibilityFocusFromHover(position[0], position[1]); 6220 } 6221 return false; 6222 } 6223 6224 /** 6225 * Requests to give this View focus from hover. 6226 * 6227 * @param x The X hovered location in this view coorditantes. 6228 * @param y The Y hovered location in this view coorditantes. 6229 * @return Whether the request was handled. 6230 * 6231 * @hide 6232 */ 6233 public boolean onRequestAccessibilityFocusFromHover(float x, float y) { 6234 if (includeForAccessibility() 6235 && (isActionableForAccessibility() || hasListenersForAccessibility())) { 6236 return requestAccessibilityFocus(); 6237 } 6238 return false; 6239 } 6240 6241 /** 6242 * Clears accessibility focus without calling any callback methods 6243 * normally invoked in {@link #clearAccessibilityFocus()}. This method 6244 * is used for clearing accessibility focus when giving this focus to 6245 * another view. 6246 */ 6247 void clearAccessibilityFocusNoCallbacks() { 6248 if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) { 6249 mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED; 6250 invalidate(); 6251 } 6252 } 6253 6254 /** 6255 * Call this to try to give focus to a specific view or to one of its 6256 * descendants. 6257 * 6258 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6259 * false), or if it is focusable and it is not focusable in touch mode 6260 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6261 * 6262 * See also {@link #focusSearch(int)}, which is what you call to say that you 6263 * have focus, and you want your parent to look for the next one. 6264 * 6265 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 6266 * {@link #FOCUS_DOWN} and <code>null</code>. 6267 * 6268 * @return Whether this view or one of its descendants actually took focus. 6269 */ 6270 public final boolean requestFocus() { 6271 return requestFocus(View.FOCUS_DOWN); 6272 } 6273 6274 /** 6275 * Call this to try to give focus to a specific view or to one of its 6276 * descendants and give it a hint about what direction focus is heading. 6277 * 6278 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6279 * false), or if it is focusable and it is not focusable in touch mode 6280 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6281 * 6282 * See also {@link #focusSearch(int)}, which is what you call to say that you 6283 * have focus, and you want your parent to look for the next one. 6284 * 6285 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 6286 * <code>null</code> set for the previously focused rectangle. 6287 * 6288 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6289 * @return Whether this view or one of its descendants actually took focus. 6290 */ 6291 public final boolean requestFocus(int direction) { 6292 return requestFocus(direction, null); 6293 } 6294 6295 /** 6296 * Call this to try to give focus to a specific view or to one of its descendants 6297 * and give it hints about the direction and a specific rectangle that the focus 6298 * is coming from. The rectangle can help give larger views a finer grained hint 6299 * about where focus is coming from, and therefore, where to show selection, or 6300 * forward focus change internally. 6301 * 6302 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6303 * false), or if it is focusable and it is not focusable in touch mode 6304 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6305 * 6306 * A View will not take focus if it is not visible. 6307 * 6308 * A View will not take focus if one of its parents has 6309 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 6310 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 6311 * 6312 * See also {@link #focusSearch(int)}, which is what you call to say that you 6313 * have focus, and you want your parent to look for the next one. 6314 * 6315 * You may wish to override this method if your custom {@link View} has an internal 6316 * {@link View} that it wishes to forward the request to. 6317 * 6318 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6319 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 6320 * to give a finer grained hint about where focus is coming from. May be null 6321 * if there is no hint. 6322 * @return Whether this view or one of its descendants actually took focus. 6323 */ 6324 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 6325 return requestFocusNoSearch(direction, previouslyFocusedRect); 6326 } 6327 6328 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 6329 // need to be focusable 6330 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 6331 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6332 return false; 6333 } 6334 6335 // need to be focusable in touch mode if in touch mode 6336 if (isInTouchMode() && 6337 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 6338 return false; 6339 } 6340 6341 // need to not have any parents blocking us 6342 if (hasAncestorThatBlocksDescendantFocus()) { 6343 return false; 6344 } 6345 6346 handleFocusGainInternal(direction, previouslyFocusedRect); 6347 return true; 6348 } 6349 6350 /** 6351 * Call this to try to give focus to a specific view or to one of its descendants. This is a 6352 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 6353 * touch mode to request focus when they are touched. 6354 * 6355 * @return Whether this view or one of its descendants actually took focus. 6356 * 6357 * @see #isInTouchMode() 6358 * 6359 */ 6360 public final boolean requestFocusFromTouch() { 6361 // Leave touch mode if we need to 6362 if (isInTouchMode()) { 6363 ViewRootImpl viewRoot = getViewRootImpl(); 6364 if (viewRoot != null) { 6365 viewRoot.ensureTouchMode(false); 6366 } 6367 } 6368 return requestFocus(View.FOCUS_DOWN); 6369 } 6370 6371 /** 6372 * @return Whether any ancestor of this view blocks descendant focus. 6373 */ 6374 private boolean hasAncestorThatBlocksDescendantFocus() { 6375 ViewParent ancestor = mParent; 6376 while (ancestor instanceof ViewGroup) { 6377 final ViewGroup vgAncestor = (ViewGroup) ancestor; 6378 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 6379 return true; 6380 } else { 6381 ancestor = vgAncestor.getParent(); 6382 } 6383 } 6384 return false; 6385 } 6386 6387 /** 6388 * Gets the mode for determining whether this View is important for accessibility 6389 * which is if it fires accessibility events and if it is reported to 6390 * accessibility services that query the screen. 6391 * 6392 * @return The mode for determining whether a View is important for accessibility. 6393 * 6394 * @attr ref android.R.styleable#View_importantForAccessibility 6395 * 6396 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 6397 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 6398 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 6399 */ 6400 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 6401 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, 6402 to = "IMPORTANT_FOR_ACCESSIBILITY_AUTO"), 6403 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, 6404 to = "IMPORTANT_FOR_ACCESSIBILITY_YES"), 6405 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, 6406 to = "IMPORTANT_FOR_ACCESSIBILITY_NO") 6407 }) 6408 public int getImportantForAccessibility() { 6409 return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK) 6410 >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 6411 } 6412 6413 /** 6414 * Sets how to determine whether this view is important for accessibility 6415 * which is if it fires accessibility events and if it is reported to 6416 * accessibility services that query the screen. 6417 * 6418 * @param mode How to determine whether this view is important for accessibility. 6419 * 6420 * @attr ref android.R.styleable#View_importantForAccessibility 6421 * 6422 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 6423 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 6424 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 6425 */ 6426 public void setImportantForAccessibility(int mode) { 6427 if (mode != getImportantForAccessibility()) { 6428 mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK; 6429 mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 6430 & IMPORTANT_FOR_ACCESSIBILITY_MASK; 6431 notifyAccessibilityStateChanged(); 6432 } 6433 } 6434 6435 /** 6436 * Gets whether this view should be exposed for accessibility. 6437 * 6438 * @return Whether the view is exposed for accessibility. 6439 * 6440 * @hide 6441 */ 6442 public boolean isImportantForAccessibility() { 6443 final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK) 6444 >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 6445 switch (mode) { 6446 case IMPORTANT_FOR_ACCESSIBILITY_YES: 6447 return true; 6448 case IMPORTANT_FOR_ACCESSIBILITY_NO: 6449 return false; 6450 case IMPORTANT_FOR_ACCESSIBILITY_AUTO: 6451 return isActionableForAccessibility() || hasListenersForAccessibility(); 6452 default: 6453 throw new IllegalArgumentException("Unknow important for accessibility mode: " 6454 + mode); 6455 } 6456 } 6457 6458 /** 6459 * Gets the parent for accessibility purposes. Note that the parent for 6460 * accessibility is not necessary the immediate parent. It is the first 6461 * predecessor that is important for accessibility. 6462 * 6463 * @return The parent for accessibility purposes. 6464 */ 6465 public ViewParent getParentForAccessibility() { 6466 if (mParent instanceof View) { 6467 View parentView = (View) mParent; 6468 if (parentView.includeForAccessibility()) { 6469 return mParent; 6470 } else { 6471 return mParent.getParentForAccessibility(); 6472 } 6473 } 6474 return null; 6475 } 6476 6477 /** 6478 * Adds the children of a given View for accessibility. Since some Views are 6479 * not important for accessibility the children for accessibility are not 6480 * necessarily direct children of the riew, rather they are the first level of 6481 * descendants important for accessibility. 6482 * 6483 * @param children The list of children for accessibility. 6484 */ 6485 public void addChildrenForAccessibility(ArrayList<View> children) { 6486 if (includeForAccessibility()) { 6487 children.add(this); 6488 } 6489 } 6490 6491 /** 6492 * Whether to regard this view for accessibility. A view is regarded for 6493 * accessibility if it is important for accessibility or the querying 6494 * accessibility service has explicitly requested that view not 6495 * important for accessibility are regarded. 6496 * 6497 * @return Whether to regard the view for accessibility. 6498 */ 6499 boolean includeForAccessibility() { 6500 if (mAttachInfo != null) { 6501 if (!mAttachInfo.mIncludeNotImportantViews) { 6502 return isImportantForAccessibility(); 6503 } else { 6504 return true; 6505 } 6506 } 6507 return false; 6508 } 6509 6510 /** 6511 * Returns whether the View is considered actionable from 6512 * accessibility perspective. Such view are important for 6513 * accessiiblity. 6514 * 6515 * @return True if the view is actionable for accessibility. 6516 */ 6517 private boolean isActionableForAccessibility() { 6518 return (isClickable() || isLongClickable() || isFocusable()); 6519 } 6520 6521 /** 6522 * Returns whether the View has registered callbacks wich makes it 6523 * important for accessiiblity. 6524 * 6525 * @return True if the view is actionable for accessibility. 6526 */ 6527 private boolean hasListenersForAccessibility() { 6528 ListenerInfo info = getListenerInfo(); 6529 return mTouchDelegate != null || info.mOnKeyListener != null 6530 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 6531 || info.mOnHoverListener != null || info.mOnDragListener != null; 6532 } 6533 6534 /** 6535 * Notifies accessibility services that some view's important for 6536 * accessibility state has changed. Note that such notifications 6537 * are made at most once every 6538 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 6539 * to avoid unnecessary load to the system. Also once a view has 6540 * made a notifucation this method is a NOP until the notification has 6541 * been sent to clients. 6542 * 6543 * @hide 6544 * 6545 * TODO: Makse sure this method is called for any view state change 6546 * that is interesting for accessilility purposes. 6547 */ 6548 public void notifyAccessibilityStateChanged() { 6549 if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) { 6550 mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED; 6551 if (mParent != null) { 6552 mParent.childAccessibilityStateChanged(this); 6553 } 6554 } 6555 } 6556 6557 /** 6558 * Reset the state indicating the this view has requested clients 6559 * interested in its accessiblity state to be notified. 6560 * 6561 * @hide 6562 */ 6563 public void resetAccessibilityStateChanged() { 6564 mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED; 6565 } 6566 6567 /** 6568 * Performs the specified accessibility action on the view. For 6569 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 6570 * <p> 6571 * If an {@link AccessibilityDelegate} has been specified via calling 6572 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6573 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 6574 * is responsible for handling this call. 6575 * </p> 6576 * 6577 * @param action The action to perform. 6578 * @param arguments Optional action arguments. 6579 * @return Whether the action was performed. 6580 */ 6581 public boolean performAccessibilityAction(int action, Bundle arguments) { 6582 if (mAccessibilityDelegate != null) { 6583 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 6584 } else { 6585 return performAccessibilityActionInternal(action, arguments); 6586 } 6587 } 6588 6589 /** 6590 * @see #performAccessibilityAction(int, Bundle) 6591 * 6592 * Note: Called from the default {@link AccessibilityDelegate}. 6593 */ 6594 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 6595 switch (action) { 6596 case AccessibilityNodeInfo.ACTION_CLICK: { 6597 if (isClickable()) { 6598 return performClick(); 6599 } 6600 } break; 6601 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 6602 if (isLongClickable()) { 6603 return performLongClick(); 6604 } 6605 } break; 6606 case AccessibilityNodeInfo.ACTION_FOCUS: { 6607 if (!hasFocus()) { 6608 // Get out of touch mode since accessibility 6609 // wants to move focus around. 6610 getViewRootImpl().ensureTouchMode(false); 6611 return requestFocus(); 6612 } 6613 } break; 6614 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 6615 if (hasFocus()) { 6616 clearFocus(); 6617 return !isFocused(); 6618 } 6619 } break; 6620 case AccessibilityNodeInfo.ACTION_SELECT: { 6621 if (!isSelected()) { 6622 setSelected(true); 6623 return isSelected(); 6624 } 6625 } break; 6626 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 6627 if (isSelected()) { 6628 setSelected(false); 6629 return !isSelected(); 6630 } 6631 } break; 6632 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 6633 if (!isAccessibilityFocused()) { 6634 return requestAccessibilityFocus(); 6635 } 6636 } break; 6637 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 6638 if (isAccessibilityFocused()) { 6639 clearAccessibilityFocus(); 6640 return true; 6641 } 6642 } break; 6643 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 6644 if (arguments != null) { 6645 final int granularity = arguments.getInt( 6646 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 6647 return nextAtGranularity(granularity); 6648 } 6649 } break; 6650 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 6651 if (arguments != null) { 6652 final int granularity = arguments.getInt( 6653 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 6654 return previousAtGranularity(granularity); 6655 } 6656 } break; 6657 } 6658 return false; 6659 } 6660 6661 private boolean nextAtGranularity(int granularity) { 6662 CharSequence text = getIterableTextForAccessibility(); 6663 if (text != null && text.length() > 0) { 6664 return false; 6665 } 6666 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 6667 if (iterator == null) { 6668 return false; 6669 } 6670 final int current = getAccessibilityCursorPosition(); 6671 final int[] range = iterator.following(current); 6672 if (range == null) { 6673 setAccessibilityCursorPosition(-1); 6674 return false; 6675 } 6676 final int start = range[0]; 6677 final int end = range[1]; 6678 setAccessibilityCursorPosition(start); 6679 sendViewTextTraversedAtGranularityEvent( 6680 AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY, 6681 granularity, start, end); 6682 return true; 6683 } 6684 6685 private boolean previousAtGranularity(int granularity) { 6686 CharSequence text = getIterableTextForAccessibility(); 6687 if (text != null && text.length() > 0) { 6688 return false; 6689 } 6690 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 6691 if (iterator == null) { 6692 return false; 6693 } 6694 final int selectionStart = getAccessibilityCursorPosition(); 6695 final int current = selectionStart >= 0 ? selectionStart : text.length() + 1; 6696 final int[] range = iterator.preceding(current); 6697 if (range == null) { 6698 setAccessibilityCursorPosition(-1); 6699 return false; 6700 } 6701 final int start = range[0]; 6702 final int end = range[1]; 6703 setAccessibilityCursorPosition(end); 6704 sendViewTextTraversedAtGranularityEvent( 6705 AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, 6706 granularity, start, end); 6707 return true; 6708 } 6709 6710 /** 6711 * Gets the text reported for accessibility purposes. 6712 * 6713 * @return The accessibility text. 6714 * 6715 * @hide 6716 */ 6717 public CharSequence getIterableTextForAccessibility() { 6718 return mContentDescription; 6719 } 6720 6721 /** 6722 * @hide 6723 */ 6724 public int getAccessibilityCursorPosition() { 6725 return mAccessibilityCursorPosition; 6726 } 6727 6728 /** 6729 * @hide 6730 */ 6731 public void setAccessibilityCursorPosition(int position) { 6732 mAccessibilityCursorPosition = position; 6733 } 6734 6735 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 6736 int fromIndex, int toIndex) { 6737 if (mParent == null) { 6738 return; 6739 } 6740 AccessibilityEvent event = AccessibilityEvent.obtain( 6741 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 6742 onInitializeAccessibilityEvent(event); 6743 onPopulateAccessibilityEvent(event); 6744 event.setFromIndex(fromIndex); 6745 event.setToIndex(toIndex); 6746 event.setAction(action); 6747 event.setMovementGranularity(granularity); 6748 mParent.requestSendAccessibilityEvent(this, event); 6749 } 6750 6751 /** 6752 * @hide 6753 */ 6754 public TextSegmentIterator getIteratorForGranularity(int granularity) { 6755 switch (granularity) { 6756 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 6757 CharSequence text = getIterableTextForAccessibility(); 6758 if (text != null && text.length() > 0) { 6759 CharacterTextSegmentIterator iterator = 6760 CharacterTextSegmentIterator.getInstance(mContext); 6761 iterator.initialize(text.toString()); 6762 return iterator; 6763 } 6764 } break; 6765 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 6766 CharSequence text = getIterableTextForAccessibility(); 6767 if (text != null && text.length() > 0) { 6768 WordTextSegmentIterator iterator = 6769 WordTextSegmentIterator.getInstance(mContext); 6770 iterator.initialize(text.toString()); 6771 return iterator; 6772 } 6773 } break; 6774 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 6775 CharSequence text = getIterableTextForAccessibility(); 6776 if (text != null && text.length() > 0) { 6777 ParagraphTextSegmentIterator iterator = 6778 ParagraphTextSegmentIterator.getInstance(); 6779 iterator.initialize(text.toString()); 6780 return iterator; 6781 } 6782 } break; 6783 } 6784 return null; 6785 } 6786 6787 /** 6788 * @hide 6789 */ 6790 public void dispatchStartTemporaryDetach() { 6791 clearAccessibilityFocus(); 6792 onStartTemporaryDetach(); 6793 } 6794 6795 /** 6796 * This is called when a container is going to temporarily detach a child, with 6797 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 6798 * It will either be followed by {@link #onFinishTemporaryDetach()} or 6799 * {@link #onDetachedFromWindow()} when the container is done. 6800 */ 6801 public void onStartTemporaryDetach() { 6802 removeUnsetPressCallback(); 6803 mPrivateFlags |= CANCEL_NEXT_UP_EVENT; 6804 } 6805 6806 /** 6807 * @hide 6808 */ 6809 public void dispatchFinishTemporaryDetach() { 6810 onFinishTemporaryDetach(); 6811 } 6812 6813 /** 6814 * Called after {@link #onStartTemporaryDetach} when the container is done 6815 * changing the view. 6816 */ 6817 public void onFinishTemporaryDetach() { 6818 } 6819 6820 /** 6821 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 6822 * for this view's window. Returns null if the view is not currently attached 6823 * to the window. Normally you will not need to use this directly, but 6824 * just use the standard high-level event callbacks like 6825 * {@link #onKeyDown(int, KeyEvent)}. 6826 */ 6827 public KeyEvent.DispatcherState getKeyDispatcherState() { 6828 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 6829 } 6830 6831 /** 6832 * Dispatch a key event before it is processed by any input method 6833 * associated with the view hierarchy. This can be used to intercept 6834 * key events in special situations before the IME consumes them; a 6835 * typical example would be handling the BACK key to update the application's 6836 * UI instead of allowing the IME to see it and close itself. 6837 * 6838 * @param event The key event to be dispatched. 6839 * @return True if the event was handled, false otherwise. 6840 */ 6841 public boolean dispatchKeyEventPreIme(KeyEvent event) { 6842 return onKeyPreIme(event.getKeyCode(), event); 6843 } 6844 6845 /** 6846 * Dispatch a key event to the next view on the focus path. This path runs 6847 * from the top of the view tree down to the currently focused view. If this 6848 * view has focus, it will dispatch to itself. Otherwise it will dispatch 6849 * the next node down the focus path. This method also fires any key 6850 * listeners. 6851 * 6852 * @param event The key event to be dispatched. 6853 * @return True if the event was handled, false otherwise. 6854 */ 6855 public boolean dispatchKeyEvent(KeyEvent event) { 6856 if (mInputEventConsistencyVerifier != null) { 6857 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 6858 } 6859 6860 // Give any attached key listener a first crack at the event. 6861 //noinspection SimplifiableIfStatement 6862 ListenerInfo li = mListenerInfo; 6863 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 6864 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 6865 return true; 6866 } 6867 6868 if (event.dispatch(this, mAttachInfo != null 6869 ? mAttachInfo.mKeyDispatchState : null, this)) { 6870 return true; 6871 } 6872 6873 if (mInputEventConsistencyVerifier != null) { 6874 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 6875 } 6876 return false; 6877 } 6878 6879 /** 6880 * Dispatches a key shortcut event. 6881 * 6882 * @param event The key event to be dispatched. 6883 * @return True if the event was handled by the view, false otherwise. 6884 */ 6885 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 6886 return onKeyShortcut(event.getKeyCode(), event); 6887 } 6888 6889 /** 6890 * Pass the touch screen motion event down to the target view, or this 6891 * view if it is the target. 6892 * 6893 * @param event The motion event to be dispatched. 6894 * @return True if the event was handled by the view, false otherwise. 6895 */ 6896 public boolean dispatchTouchEvent(MotionEvent event) { 6897 if (mInputEventConsistencyVerifier != null) { 6898 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 6899 } 6900 6901 if (onFilterTouchEventForSecurity(event)) { 6902 //noinspection SimplifiableIfStatement 6903 ListenerInfo li = mListenerInfo; 6904 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 6905 && li.mOnTouchListener.onTouch(this, event)) { 6906 return true; 6907 } 6908 6909 if (onTouchEvent(event)) { 6910 return true; 6911 } 6912 } 6913 6914 if (mInputEventConsistencyVerifier != null) { 6915 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 6916 } 6917 return false; 6918 } 6919 6920 /** 6921 * Filter the touch event to apply security policies. 6922 * 6923 * @param event The motion event to be filtered. 6924 * @return True if the event should be dispatched, false if the event should be dropped. 6925 * 6926 * @see #getFilterTouchesWhenObscured 6927 */ 6928 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 6929 //noinspection RedundantIfStatement 6930 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 6931 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 6932 // Window is obscured, drop this touch. 6933 return false; 6934 } 6935 return true; 6936 } 6937 6938 /** 6939 * Pass a trackball motion event down to the focused view. 6940 * 6941 * @param event The motion event to be dispatched. 6942 * @return True if the event was handled by the view, false otherwise. 6943 */ 6944 public boolean dispatchTrackballEvent(MotionEvent event) { 6945 if (mInputEventConsistencyVerifier != null) { 6946 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 6947 } 6948 6949 return onTrackballEvent(event); 6950 } 6951 6952 /** 6953 * Dispatch a generic motion event. 6954 * <p> 6955 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 6956 * are delivered to the view under the pointer. All other generic motion events are 6957 * delivered to the focused view. Hover events are handled specially and are delivered 6958 * to {@link #onHoverEvent(MotionEvent)}. 6959 * </p> 6960 * 6961 * @param event The motion event to be dispatched. 6962 * @return True if the event was handled by the view, false otherwise. 6963 */ 6964 public boolean dispatchGenericMotionEvent(MotionEvent event) { 6965 if (mInputEventConsistencyVerifier != null) { 6966 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 6967 } 6968 6969 final int source = event.getSource(); 6970 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 6971 final int action = event.getAction(); 6972 if (action == MotionEvent.ACTION_HOVER_ENTER 6973 || action == MotionEvent.ACTION_HOVER_MOVE 6974 || action == MotionEvent.ACTION_HOVER_EXIT) { 6975 if (dispatchHoverEvent(event)) { 6976 return true; 6977 } 6978 } else if (dispatchGenericPointerEvent(event)) { 6979 return true; 6980 } 6981 } else if (dispatchGenericFocusedEvent(event)) { 6982 return true; 6983 } 6984 6985 if (dispatchGenericMotionEventInternal(event)) { 6986 return true; 6987 } 6988 6989 if (mInputEventConsistencyVerifier != null) { 6990 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 6991 } 6992 return false; 6993 } 6994 6995 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 6996 //noinspection SimplifiableIfStatement 6997 ListenerInfo li = mListenerInfo; 6998 if (li != null && li.mOnGenericMotionListener != null 6999 && (mViewFlags & ENABLED_MASK) == ENABLED 7000 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 7001 return true; 7002 } 7003 7004 if (onGenericMotionEvent(event)) { 7005 return true; 7006 } 7007 7008 if (mInputEventConsistencyVerifier != null) { 7009 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7010 } 7011 return false; 7012 } 7013 7014 /** 7015 * Dispatch a hover event. 7016 * <p> 7017 * Do not call this method directly. 7018 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7019 * </p> 7020 * 7021 * @param event The motion event to be dispatched. 7022 * @return True if the event was handled by the view, false otherwise. 7023 */ 7024 protected boolean dispatchHoverEvent(MotionEvent event) { 7025 //noinspection SimplifiableIfStatement 7026 ListenerInfo li = mListenerInfo; 7027 if (li != null && li.mOnHoverListener != null 7028 && (mViewFlags & ENABLED_MASK) == ENABLED 7029 && li.mOnHoverListener.onHover(this, event)) { 7030 return true; 7031 } 7032 7033 return onHoverEvent(event); 7034 } 7035 7036 /** 7037 * Returns true if the view has a child to which it has recently sent 7038 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 7039 * it does not have a hovered child, then it must be the innermost hovered view. 7040 * @hide 7041 */ 7042 protected boolean hasHoveredChild() { 7043 return false; 7044 } 7045 7046 /** 7047 * Dispatch a generic motion event to the view under the first pointer. 7048 * <p> 7049 * Do not call this method directly. 7050 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7051 * </p> 7052 * 7053 * @param event The motion event to be dispatched. 7054 * @return True if the event was handled by the view, false otherwise. 7055 */ 7056 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 7057 return false; 7058 } 7059 7060 /** 7061 * Dispatch a generic motion event to the currently focused view. 7062 * <p> 7063 * Do not call this method directly. 7064 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7065 * </p> 7066 * 7067 * @param event The motion event to be dispatched. 7068 * @return True if the event was handled by the view, false otherwise. 7069 */ 7070 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 7071 return false; 7072 } 7073 7074 /** 7075 * Dispatch a pointer event. 7076 * <p> 7077 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 7078 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 7079 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 7080 * and should not be expected to handle other pointing device features. 7081 * </p> 7082 * 7083 * @param event The motion event to be dispatched. 7084 * @return True if the event was handled by the view, false otherwise. 7085 * @hide 7086 */ 7087 public final boolean dispatchPointerEvent(MotionEvent event) { 7088 if (event.isTouchEvent()) { 7089 return dispatchTouchEvent(event); 7090 } else { 7091 return dispatchGenericMotionEvent(event); 7092 } 7093 } 7094 7095 /** 7096 * Called when the window containing this view gains or loses window focus. 7097 * ViewGroups should override to route to their children. 7098 * 7099 * @param hasFocus True if the window containing this view now has focus, 7100 * false otherwise. 7101 */ 7102 public void dispatchWindowFocusChanged(boolean hasFocus) { 7103 onWindowFocusChanged(hasFocus); 7104 } 7105 7106 /** 7107 * Called when the window containing this view gains or loses focus. Note 7108 * that this is separate from view focus: to receive key events, both 7109 * your view and its window must have focus. If a window is displayed 7110 * on top of yours that takes input focus, then your own window will lose 7111 * focus but the view focus will remain unchanged. 7112 * 7113 * @param hasWindowFocus True if the window containing this view now has 7114 * focus, false otherwise. 7115 */ 7116 public void onWindowFocusChanged(boolean hasWindowFocus) { 7117 InputMethodManager imm = InputMethodManager.peekInstance(); 7118 if (!hasWindowFocus) { 7119 if (isPressed()) { 7120 setPressed(false); 7121 } 7122 if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 7123 imm.focusOut(this); 7124 } 7125 removeLongPressCallback(); 7126 removeTapCallback(); 7127 onFocusLost(); 7128 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 7129 imm.focusIn(this); 7130 } 7131 refreshDrawableState(); 7132 } 7133 7134 /** 7135 * Returns true if this view is in a window that currently has window focus. 7136 * Note that this is not the same as the view itself having focus. 7137 * 7138 * @return True if this view is in a window that currently has window focus. 7139 */ 7140 public boolean hasWindowFocus() { 7141 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 7142 } 7143 7144 /** 7145 * Dispatch a view visibility change down the view hierarchy. 7146 * ViewGroups should override to route to their children. 7147 * @param changedView The view whose visibility changed. Could be 'this' or 7148 * an ancestor view. 7149 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7150 * {@link #INVISIBLE} or {@link #GONE}. 7151 */ 7152 protected void dispatchVisibilityChanged(View changedView, int visibility) { 7153 onVisibilityChanged(changedView, visibility); 7154 } 7155 7156 /** 7157 * Called when the visibility of the view or an ancestor of the view is changed. 7158 * @param changedView The view whose visibility changed. Could be 'this' or 7159 * an ancestor view. 7160 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7161 * {@link #INVISIBLE} or {@link #GONE}. 7162 */ 7163 protected void onVisibilityChanged(View changedView, int visibility) { 7164 if (visibility == VISIBLE) { 7165 if (mAttachInfo != null) { 7166 initialAwakenScrollBars(); 7167 } else { 7168 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH; 7169 } 7170 } 7171 } 7172 7173 /** 7174 * Dispatch a hint about whether this view is displayed. For instance, when 7175 * a View moves out of the screen, it might receives a display hint indicating 7176 * the view is not displayed. Applications should not <em>rely</em> on this hint 7177 * as there is no guarantee that they will receive one. 7178 * 7179 * @param hint A hint about whether or not this view is displayed: 7180 * {@link #VISIBLE} or {@link #INVISIBLE}. 7181 */ 7182 public void dispatchDisplayHint(int hint) { 7183 onDisplayHint(hint); 7184 } 7185 7186 /** 7187 * Gives this view a hint about whether is displayed or not. For instance, when 7188 * a View moves out of the screen, it might receives a display hint indicating 7189 * the view is not displayed. Applications should not <em>rely</em> on this hint 7190 * as there is no guarantee that they will receive one. 7191 * 7192 * @param hint A hint about whether or not this view is displayed: 7193 * {@link #VISIBLE} or {@link #INVISIBLE}. 7194 */ 7195 protected void onDisplayHint(int hint) { 7196 } 7197 7198 /** 7199 * Dispatch a window visibility change down the view hierarchy. 7200 * ViewGroups should override to route to their children. 7201 * 7202 * @param visibility The new visibility of the window. 7203 * 7204 * @see #onWindowVisibilityChanged(int) 7205 */ 7206 public void dispatchWindowVisibilityChanged(int visibility) { 7207 onWindowVisibilityChanged(visibility); 7208 } 7209 7210 /** 7211 * Called when the window containing has change its visibility 7212 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 7213 * that this tells you whether or not your window is being made visible 7214 * to the window manager; this does <em>not</em> tell you whether or not 7215 * your window is obscured by other windows on the screen, even if it 7216 * is itself visible. 7217 * 7218 * @param visibility The new visibility of the window. 7219 */ 7220 protected void onWindowVisibilityChanged(int visibility) { 7221 if (visibility == VISIBLE) { 7222 initialAwakenScrollBars(); 7223 } 7224 } 7225 7226 /** 7227 * Returns the current visibility of the window this view is attached to 7228 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 7229 * 7230 * @return Returns the current visibility of the view's window. 7231 */ 7232 public int getWindowVisibility() { 7233 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 7234 } 7235 7236 /** 7237 * Retrieve the overall visible display size in which the window this view is 7238 * attached to has been positioned in. This takes into account screen 7239 * decorations above the window, for both cases where the window itself 7240 * is being position inside of them or the window is being placed under 7241 * then and covered insets are used for the window to position its content 7242 * inside. In effect, this tells you the available area where content can 7243 * be placed and remain visible to users. 7244 * 7245 * <p>This function requires an IPC back to the window manager to retrieve 7246 * the requested information, so should not be used in performance critical 7247 * code like drawing. 7248 * 7249 * @param outRect Filled in with the visible display frame. If the view 7250 * is not attached to a window, this is simply the raw display size. 7251 */ 7252 public void getWindowVisibleDisplayFrame(Rect outRect) { 7253 if (mAttachInfo != null) { 7254 try { 7255 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 7256 } catch (RemoteException e) { 7257 return; 7258 } 7259 // XXX This is really broken, and probably all needs to be done 7260 // in the window manager, and we need to know more about whether 7261 // we want the area behind or in front of the IME. 7262 final Rect insets = mAttachInfo.mVisibleInsets; 7263 outRect.left += insets.left; 7264 outRect.top += insets.top; 7265 outRect.right -= insets.right; 7266 outRect.bottom -= insets.bottom; 7267 return; 7268 } 7269 Display d = WindowManagerImpl.getDefault().getDefaultDisplay(); 7270 d.getRectSize(outRect); 7271 } 7272 7273 /** 7274 * Dispatch a notification about a resource configuration change down 7275 * the view hierarchy. 7276 * ViewGroups should override to route to their children. 7277 * 7278 * @param newConfig The new resource configuration. 7279 * 7280 * @see #onConfigurationChanged(android.content.res.Configuration) 7281 */ 7282 public void dispatchConfigurationChanged(Configuration newConfig) { 7283 onConfigurationChanged(newConfig); 7284 } 7285 7286 /** 7287 * Called when the current configuration of the resources being used 7288 * by the application have changed. You can use this to decide when 7289 * to reload resources that can changed based on orientation and other 7290 * configuration characterstics. You only need to use this if you are 7291 * not relying on the normal {@link android.app.Activity} mechanism of 7292 * recreating the activity instance upon a configuration change. 7293 * 7294 * @param newConfig The new resource configuration. 7295 */ 7296 protected void onConfigurationChanged(Configuration newConfig) { 7297 } 7298 7299 /** 7300 * Private function to aggregate all per-view attributes in to the view 7301 * root. 7302 */ 7303 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7304 performCollectViewAttributes(attachInfo, visibility); 7305 } 7306 7307 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7308 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 7309 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 7310 attachInfo.mKeepScreenOn = true; 7311 } 7312 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 7313 ListenerInfo li = mListenerInfo; 7314 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 7315 attachInfo.mHasSystemUiListeners = true; 7316 } 7317 } 7318 } 7319 7320 void needGlobalAttributesUpdate(boolean force) { 7321 final AttachInfo ai = mAttachInfo; 7322 if (ai != null) { 7323 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 7324 || ai.mHasSystemUiListeners) { 7325 ai.mRecomputeGlobalAttributes = true; 7326 } 7327 } 7328 } 7329 7330 /** 7331 * Returns whether the device is currently in touch mode. Touch mode is entered 7332 * once the user begins interacting with the device by touch, and affects various 7333 * things like whether focus is always visible to the user. 7334 * 7335 * @return Whether the device is in touch mode. 7336 */ 7337 @ViewDebug.ExportedProperty 7338 public boolean isInTouchMode() { 7339 if (mAttachInfo != null) { 7340 return mAttachInfo.mInTouchMode; 7341 } else { 7342 return ViewRootImpl.isInTouchMode(); 7343 } 7344 } 7345 7346 /** 7347 * Returns the context the view is running in, through which it can 7348 * access the current theme, resources, etc. 7349 * 7350 * @return The view's Context. 7351 */ 7352 @ViewDebug.CapturedViewProperty 7353 public final Context getContext() { 7354 return mContext; 7355 } 7356 7357 /** 7358 * Handle a key event before it is processed by any input method 7359 * associated with the view hierarchy. This can be used to intercept 7360 * key events in special situations before the IME consumes them; a 7361 * typical example would be handling the BACK key to update the application's 7362 * UI instead of allowing the IME to see it and close itself. 7363 * 7364 * @param keyCode The value in event.getKeyCode(). 7365 * @param event Description of the key event. 7366 * @return If you handled the event, return true. If you want to allow the 7367 * event to be handled by the next receiver, return false. 7368 */ 7369 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 7370 return false; 7371 } 7372 7373 /** 7374 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 7375 * KeyEvent.Callback.onKeyDown()}: perform press of the view 7376 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 7377 * is released, if the view is enabled and clickable. 7378 * 7379 * @param keyCode A key code that represents the button pressed, from 7380 * {@link android.view.KeyEvent}. 7381 * @param event The KeyEvent object that defines the button action. 7382 */ 7383 public boolean onKeyDown(int keyCode, KeyEvent event) { 7384 boolean result = false; 7385 7386 switch (keyCode) { 7387 case KeyEvent.KEYCODE_DPAD_CENTER: 7388 case KeyEvent.KEYCODE_ENTER: { 7389 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7390 return true; 7391 } 7392 // Long clickable items don't necessarily have to be clickable 7393 if (((mViewFlags & CLICKABLE) == CLICKABLE || 7394 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 7395 (event.getRepeatCount() == 0)) { 7396 setPressed(true); 7397 checkForLongClick(0); 7398 return true; 7399 } 7400 break; 7401 } 7402 } 7403 return result; 7404 } 7405 7406 /** 7407 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 7408 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 7409 * the event). 7410 */ 7411 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 7412 return false; 7413 } 7414 7415 /** 7416 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 7417 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 7418 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 7419 * {@link KeyEvent#KEYCODE_ENTER} is released. 7420 * 7421 * @param keyCode A key code that represents the button pressed, from 7422 * {@link android.view.KeyEvent}. 7423 * @param event The KeyEvent object that defines the button action. 7424 */ 7425 public boolean onKeyUp(int keyCode, KeyEvent event) { 7426 boolean result = false; 7427 7428 switch (keyCode) { 7429 case KeyEvent.KEYCODE_DPAD_CENTER: 7430 case KeyEvent.KEYCODE_ENTER: { 7431 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7432 return true; 7433 } 7434 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 7435 setPressed(false); 7436 7437 if (!mHasPerformedLongPress) { 7438 // This is a tap, so remove the longpress check 7439 removeLongPressCallback(); 7440 7441 result = performClick(); 7442 } 7443 } 7444 break; 7445 } 7446 } 7447 return result; 7448 } 7449 7450 /** 7451 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 7452 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 7453 * the event). 7454 * 7455 * @param keyCode A key code that represents the button pressed, from 7456 * {@link android.view.KeyEvent}. 7457 * @param repeatCount The number of times the action was made. 7458 * @param event The KeyEvent object that defines the button action. 7459 */ 7460 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 7461 return false; 7462 } 7463 7464 /** 7465 * Called on the focused view when a key shortcut event is not handled. 7466 * Override this method to implement local key shortcuts for the View. 7467 * Key shortcuts can also be implemented by setting the 7468 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 7469 * 7470 * @param keyCode The value in event.getKeyCode(). 7471 * @param event Description of the key event. 7472 * @return If you handled the event, return true. If you want to allow the 7473 * event to be handled by the next receiver, return false. 7474 */ 7475 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 7476 return false; 7477 } 7478 7479 /** 7480 * Check whether the called view is a text editor, in which case it 7481 * would make sense to automatically display a soft input window for 7482 * it. Subclasses should override this if they implement 7483 * {@link #onCreateInputConnection(EditorInfo)} to return true if 7484 * a call on that method would return a non-null InputConnection, and 7485 * they are really a first-class editor that the user would normally 7486 * start typing on when the go into a window containing your view. 7487 * 7488 * <p>The default implementation always returns false. This does 7489 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 7490 * will not be called or the user can not otherwise perform edits on your 7491 * view; it is just a hint to the system that this is not the primary 7492 * purpose of this view. 7493 * 7494 * @return Returns true if this view is a text editor, else false. 7495 */ 7496 public boolean onCheckIsTextEditor() { 7497 return false; 7498 } 7499 7500 /** 7501 * Create a new InputConnection for an InputMethod to interact 7502 * with the view. The default implementation returns null, since it doesn't 7503 * support input methods. You can override this to implement such support. 7504 * This is only needed for views that take focus and text input. 7505 * 7506 * <p>When implementing this, you probably also want to implement 7507 * {@link #onCheckIsTextEditor()} to indicate you will return a 7508 * non-null InputConnection. 7509 * 7510 * @param outAttrs Fill in with attribute information about the connection. 7511 */ 7512 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 7513 return null; 7514 } 7515 7516 /** 7517 * Called by the {@link android.view.inputmethod.InputMethodManager} 7518 * when a view who is not the current 7519 * input connection target is trying to make a call on the manager. The 7520 * default implementation returns false; you can override this to return 7521 * true for certain views if you are performing InputConnection proxying 7522 * to them. 7523 * @param view The View that is making the InputMethodManager call. 7524 * @return Return true to allow the call, false to reject. 7525 */ 7526 public boolean checkInputConnectionProxy(View view) { 7527 return false; 7528 } 7529 7530 /** 7531 * Show the context menu for this view. It is not safe to hold on to the 7532 * menu after returning from this method. 7533 * 7534 * You should normally not overload this method. Overload 7535 * {@link #onCreateContextMenu(ContextMenu)} or define an 7536 * {@link OnCreateContextMenuListener} to add items to the context menu. 7537 * 7538 * @param menu The context menu to populate 7539 */ 7540 public void createContextMenu(ContextMenu menu) { 7541 ContextMenuInfo menuInfo = getContextMenuInfo(); 7542 7543 // Sets the current menu info so all items added to menu will have 7544 // my extra info set. 7545 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 7546 7547 onCreateContextMenu(menu); 7548 ListenerInfo li = mListenerInfo; 7549 if (li != null && li.mOnCreateContextMenuListener != null) { 7550 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 7551 } 7552 7553 // Clear the extra information so subsequent items that aren't mine don't 7554 // have my extra info. 7555 ((MenuBuilder)menu).setCurrentMenuInfo(null); 7556 7557 if (mParent != null) { 7558 mParent.createContextMenu(menu); 7559 } 7560 } 7561 7562 /** 7563 * Views should implement this if they have extra information to associate 7564 * with the context menu. The return result is supplied as a parameter to 7565 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 7566 * callback. 7567 * 7568 * @return Extra information about the item for which the context menu 7569 * should be shown. This information will vary across different 7570 * subclasses of View. 7571 */ 7572 protected ContextMenuInfo getContextMenuInfo() { 7573 return null; 7574 } 7575 7576 /** 7577 * Views should implement this if the view itself is going to add items to 7578 * the context menu. 7579 * 7580 * @param menu the context menu to populate 7581 */ 7582 protected void onCreateContextMenu(ContextMenu menu) { 7583 } 7584 7585 /** 7586 * Implement this method to handle trackball motion events. The 7587 * <em>relative</em> movement of the trackball since the last event 7588 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 7589 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 7590 * that a movement of 1 corresponds to the user pressing one DPAD key (so 7591 * they will often be fractional values, representing the more fine-grained 7592 * movement information available from a trackball). 7593 * 7594 * @param event The motion event. 7595 * @return True if the event was handled, false otherwise. 7596 */ 7597 public boolean onTrackballEvent(MotionEvent event) { 7598 return false; 7599 } 7600 7601 /** 7602 * Implement this method to handle generic motion events. 7603 * <p> 7604 * Generic motion events describe joystick movements, mouse hovers, track pad 7605 * touches, scroll wheel movements and other input events. The 7606 * {@link MotionEvent#getSource() source} of the motion event specifies 7607 * the class of input that was received. Implementations of this method 7608 * must examine the bits in the source before processing the event. 7609 * The following code example shows how this is done. 7610 * </p><p> 7611 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 7612 * are delivered to the view under the pointer. All other generic motion events are 7613 * delivered to the focused view. 7614 * </p> 7615 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 7616 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 7617 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 7618 * // process the joystick movement... 7619 * return true; 7620 * } 7621 * } 7622 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 7623 * switch (event.getAction()) { 7624 * case MotionEvent.ACTION_HOVER_MOVE: 7625 * // process the mouse hover movement... 7626 * return true; 7627 * case MotionEvent.ACTION_SCROLL: 7628 * // process the scroll wheel movement... 7629 * return true; 7630 * } 7631 * } 7632 * return super.onGenericMotionEvent(event); 7633 * }</pre> 7634 * 7635 * @param event The generic motion event being processed. 7636 * @return True if the event was handled, false otherwise. 7637 */ 7638 public boolean onGenericMotionEvent(MotionEvent event) { 7639 return false; 7640 } 7641 7642 /** 7643 * Implement this method to handle hover events. 7644 * <p> 7645 * This method is called whenever a pointer is hovering into, over, or out of the 7646 * bounds of a view and the view is not currently being touched. 7647 * Hover events are represented as pointer events with action 7648 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 7649 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 7650 * </p> 7651 * <ul> 7652 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 7653 * when the pointer enters the bounds of the view.</li> 7654 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 7655 * when the pointer has already entered the bounds of the view and has moved.</li> 7656 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 7657 * when the pointer has exited the bounds of the view or when the pointer is 7658 * about to go down due to a button click, tap, or similar user action that 7659 * causes the view to be touched.</li> 7660 * </ul> 7661 * <p> 7662 * The view should implement this method to return true to indicate that it is 7663 * handling the hover event, such as by changing its drawable state. 7664 * </p><p> 7665 * The default implementation calls {@link #setHovered} to update the hovered state 7666 * of the view when a hover enter or hover exit event is received, if the view 7667 * is enabled and is clickable. The default implementation also sends hover 7668 * accessibility events. 7669 * </p> 7670 * 7671 * @param event The motion event that describes the hover. 7672 * @return True if the view handled the hover event. 7673 * 7674 * @see #isHovered 7675 * @see #setHovered 7676 * @see #onHoverChanged 7677 */ 7678 public boolean onHoverEvent(MotionEvent event) { 7679 // The root view may receive hover (or touch) events that are outside the bounds of 7680 // the window. This code ensures that we only send accessibility events for 7681 // hovers that are actually within the bounds of the root view. 7682 final int action = event.getActionMasked(); 7683 if (!mSendingHoverAccessibilityEvents) { 7684 if ((action == MotionEvent.ACTION_HOVER_ENTER 7685 || action == MotionEvent.ACTION_HOVER_MOVE) 7686 && !hasHoveredChild() 7687 && pointInView(event.getX(), event.getY())) { 7688 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 7689 mSendingHoverAccessibilityEvents = true; 7690 requestAccessibilityFocusFromHover((int) event.getX(), (int) event.getY()); 7691 } 7692 } else { 7693 if (action == MotionEvent.ACTION_HOVER_EXIT 7694 || (action == MotionEvent.ACTION_MOVE 7695 && !pointInView(event.getX(), event.getY()))) { 7696 mSendingHoverAccessibilityEvents = false; 7697 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 7698 // If the window does not have input focus we take away accessibility 7699 // focus as soon as the user stop hovering over the view. 7700 if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) { 7701 getViewRootImpl().setAccessibilityFocusedHost(null); 7702 } 7703 } 7704 } 7705 7706 if (isHoverable()) { 7707 switch (action) { 7708 case MotionEvent.ACTION_HOVER_ENTER: 7709 setHovered(true); 7710 break; 7711 case MotionEvent.ACTION_HOVER_EXIT: 7712 setHovered(false); 7713 break; 7714 } 7715 7716 // Dispatch the event to onGenericMotionEvent before returning true. 7717 // This is to provide compatibility with existing applications that 7718 // handled HOVER_MOVE events in onGenericMotionEvent and that would 7719 // break because of the new default handling for hoverable views 7720 // in onHoverEvent. 7721 // Note that onGenericMotionEvent will be called by default when 7722 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 7723 dispatchGenericMotionEventInternal(event); 7724 return true; 7725 } 7726 7727 return false; 7728 } 7729 7730 /** 7731 * Returns true if the view should handle {@link #onHoverEvent} 7732 * by calling {@link #setHovered} to change its hovered state. 7733 * 7734 * @return True if the view is hoverable. 7735 */ 7736 private boolean isHoverable() { 7737 final int viewFlags = mViewFlags; 7738 if ((viewFlags & ENABLED_MASK) == DISABLED) { 7739 return false; 7740 } 7741 7742 return (viewFlags & CLICKABLE) == CLICKABLE 7743 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 7744 } 7745 7746 /** 7747 * Returns true if the view is currently hovered. 7748 * 7749 * @return True if the view is currently hovered. 7750 * 7751 * @see #setHovered 7752 * @see #onHoverChanged 7753 */ 7754 @ViewDebug.ExportedProperty 7755 public boolean isHovered() { 7756 return (mPrivateFlags & HOVERED) != 0; 7757 } 7758 7759 /** 7760 * Sets whether the view is currently hovered. 7761 * <p> 7762 * Calling this method also changes the drawable state of the view. This 7763 * enables the view to react to hover by using different drawable resources 7764 * to change its appearance. 7765 * </p><p> 7766 * The {@link #onHoverChanged} method is called when the hovered state changes. 7767 * </p> 7768 * 7769 * @param hovered True if the view is hovered. 7770 * 7771 * @see #isHovered 7772 * @see #onHoverChanged 7773 */ 7774 public void setHovered(boolean hovered) { 7775 if (hovered) { 7776 if ((mPrivateFlags & HOVERED) == 0) { 7777 mPrivateFlags |= HOVERED; 7778 refreshDrawableState(); 7779 onHoverChanged(true); 7780 } 7781 } else { 7782 if ((mPrivateFlags & HOVERED) != 0) { 7783 mPrivateFlags &= ~HOVERED; 7784 refreshDrawableState(); 7785 onHoverChanged(false); 7786 } 7787 } 7788 } 7789 7790 /** 7791 * Implement this method to handle hover state changes. 7792 * <p> 7793 * This method is called whenever the hover state changes as a result of a 7794 * call to {@link #setHovered}. 7795 * </p> 7796 * 7797 * @param hovered The current hover state, as returned by {@link #isHovered}. 7798 * 7799 * @see #isHovered 7800 * @see #setHovered 7801 */ 7802 public void onHoverChanged(boolean hovered) { 7803 } 7804 7805 /** 7806 * Implement this method to handle touch screen motion events. 7807 * 7808 * @param event The motion event. 7809 * @return True if the event was handled, false otherwise. 7810 */ 7811 public boolean onTouchEvent(MotionEvent event) { 7812 final int viewFlags = mViewFlags; 7813 7814 if ((viewFlags & ENABLED_MASK) == DISABLED) { 7815 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) { 7816 setPressed(false); 7817 } 7818 // A disabled view that is clickable still consumes the touch 7819 // events, it just doesn't respond to them. 7820 return (((viewFlags & CLICKABLE) == CLICKABLE || 7821 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 7822 } 7823 7824 if (mTouchDelegate != null) { 7825 if (mTouchDelegate.onTouchEvent(event)) { 7826 return true; 7827 } 7828 } 7829 7830 if (((viewFlags & CLICKABLE) == CLICKABLE || 7831 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 7832 switch (event.getAction()) { 7833 case MotionEvent.ACTION_UP: 7834 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; 7835 if ((mPrivateFlags & PRESSED) != 0 || prepressed) { 7836 // take focus if we don't have it already and we should in 7837 // touch mode. 7838 boolean focusTaken = false; 7839 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 7840 focusTaken = requestFocus(); 7841 } 7842 7843 if (prepressed) { 7844 // The button is being released before we actually 7845 // showed it as pressed. Make it show the pressed 7846 // state now (before scheduling the click) to ensure 7847 // the user sees it. 7848 setPressed(true); 7849 } 7850 7851 if (!mHasPerformedLongPress) { 7852 // This is a tap, so remove the longpress check 7853 removeLongPressCallback(); 7854 7855 // Only perform take click actions if we were in the pressed state 7856 if (!focusTaken) { 7857 // Use a Runnable and post this rather than calling 7858 // performClick directly. This lets other visual state 7859 // of the view update before click actions start. 7860 if (mPerformClick == null) { 7861 mPerformClick = new PerformClick(); 7862 } 7863 if (!post(mPerformClick)) { 7864 performClick(); 7865 } 7866 } 7867 } 7868 7869 if (mUnsetPressedState == null) { 7870 mUnsetPressedState = new UnsetPressedState(); 7871 } 7872 7873 if (prepressed) { 7874 postDelayed(mUnsetPressedState, 7875 ViewConfiguration.getPressedStateDuration()); 7876 } else if (!post(mUnsetPressedState)) { 7877 // If the post failed, unpress right now 7878 mUnsetPressedState.run(); 7879 } 7880 removeTapCallback(); 7881 } 7882 break; 7883 7884 case MotionEvent.ACTION_DOWN: 7885 mHasPerformedLongPress = false; 7886 7887 if (performButtonActionOnTouchDown(event)) { 7888 break; 7889 } 7890 7891 // Walk up the hierarchy to determine if we're inside a scrolling container. 7892 boolean isInScrollingContainer = isInScrollingContainer(); 7893 7894 // For views inside a scrolling container, delay the pressed feedback for 7895 // a short period in case this is a scroll. 7896 if (isInScrollingContainer) { 7897 mPrivateFlags |= PREPRESSED; 7898 if (mPendingCheckForTap == null) { 7899 mPendingCheckForTap = new CheckForTap(); 7900 } 7901 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 7902 } else { 7903 // Not inside a scrolling container, so show the feedback right away 7904 setPressed(true); 7905 checkForLongClick(0); 7906 } 7907 break; 7908 7909 case MotionEvent.ACTION_CANCEL: 7910 setPressed(false); 7911 removeTapCallback(); 7912 break; 7913 7914 case MotionEvent.ACTION_MOVE: 7915 final int x = (int) event.getX(); 7916 final int y = (int) event.getY(); 7917 7918 // Be lenient about moving outside of buttons 7919 if (!pointInView(x, y, mTouchSlop)) { 7920 // Outside button 7921 removeTapCallback(); 7922 if ((mPrivateFlags & PRESSED) != 0) { 7923 // Remove any future long press/tap checks 7924 removeLongPressCallback(); 7925 7926 setPressed(false); 7927 } 7928 } 7929 break; 7930 } 7931 return true; 7932 } 7933 7934 return false; 7935 } 7936 7937 /** 7938 * @hide 7939 */ 7940 public boolean isInScrollingContainer() { 7941 ViewParent p = getParent(); 7942 while (p != null && p instanceof ViewGroup) { 7943 if (((ViewGroup) p).shouldDelayChildPressedState()) { 7944 return true; 7945 } 7946 p = p.getParent(); 7947 } 7948 return false; 7949 } 7950 7951 /** 7952 * Remove the longpress detection timer. 7953 */ 7954 private void removeLongPressCallback() { 7955 if (mPendingCheckForLongPress != null) { 7956 removeCallbacks(mPendingCheckForLongPress); 7957 } 7958 } 7959 7960 /** 7961 * Remove the pending click action 7962 */ 7963 private void removePerformClickCallback() { 7964 if (mPerformClick != null) { 7965 removeCallbacks(mPerformClick); 7966 } 7967 } 7968 7969 /** 7970 * Remove the prepress detection timer. 7971 */ 7972 private void removeUnsetPressCallback() { 7973 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) { 7974 setPressed(false); 7975 removeCallbacks(mUnsetPressedState); 7976 } 7977 } 7978 7979 /** 7980 * Remove the tap detection timer. 7981 */ 7982 private void removeTapCallback() { 7983 if (mPendingCheckForTap != null) { 7984 mPrivateFlags &= ~PREPRESSED; 7985 removeCallbacks(mPendingCheckForTap); 7986 } 7987 } 7988 7989 /** 7990 * Cancels a pending long press. Your subclass can use this if you 7991 * want the context menu to come up if the user presses and holds 7992 * at the same place, but you don't want it to come up if they press 7993 * and then move around enough to cause scrolling. 7994 */ 7995 public void cancelLongPress() { 7996 removeLongPressCallback(); 7997 7998 /* 7999 * The prepressed state handled by the tap callback is a display 8000 * construct, but the tap callback will post a long press callback 8001 * less its own timeout. Remove it here. 8002 */ 8003 removeTapCallback(); 8004 } 8005 8006 /** 8007 * Remove the pending callback for sending a 8008 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 8009 */ 8010 private void removeSendViewScrolledAccessibilityEventCallback() { 8011 if (mSendViewScrolledAccessibilityEvent != null) { 8012 removeCallbacks(mSendViewScrolledAccessibilityEvent); 8013 } 8014 } 8015 8016 /** 8017 * Sets the TouchDelegate for this View. 8018 */ 8019 public void setTouchDelegate(TouchDelegate delegate) { 8020 mTouchDelegate = delegate; 8021 } 8022 8023 /** 8024 * Gets the TouchDelegate for this View. 8025 */ 8026 public TouchDelegate getTouchDelegate() { 8027 return mTouchDelegate; 8028 } 8029 8030 /** 8031 * Set flags controlling behavior of this view. 8032 * 8033 * @param flags Constant indicating the value which should be set 8034 * @param mask Constant indicating the bit range that should be changed 8035 */ 8036 void setFlags(int flags, int mask) { 8037 int old = mViewFlags; 8038 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 8039 8040 int changed = mViewFlags ^ old; 8041 if (changed == 0) { 8042 return; 8043 } 8044 int privateFlags = mPrivateFlags; 8045 8046 /* Check if the FOCUSABLE bit has changed */ 8047 if (((changed & FOCUSABLE_MASK) != 0) && 8048 ((privateFlags & HAS_BOUNDS) !=0)) { 8049 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 8050 && ((privateFlags & FOCUSED) != 0)) { 8051 /* Give up focus if we are no longer focusable */ 8052 clearFocus(); 8053 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 8054 && ((privateFlags & FOCUSED) == 0)) { 8055 /* 8056 * Tell the view system that we are now available to take focus 8057 * if no one else already has it. 8058 */ 8059 if (mParent != null) mParent.focusableViewAvailable(this); 8060 } 8061 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8062 notifyAccessibilityStateChanged(); 8063 } 8064 } 8065 8066 if ((flags & VISIBILITY_MASK) == VISIBLE) { 8067 if ((changed & VISIBILITY_MASK) != 0) { 8068 /* 8069 * If this view is becoming visible, invalidate it in case it changed while 8070 * it was not visible. Marking it drawn ensures that the invalidation will 8071 * go through. 8072 */ 8073 mPrivateFlags |= DRAWN; 8074 invalidate(true); 8075 8076 needGlobalAttributesUpdate(true); 8077 8078 // a view becoming visible is worth notifying the parent 8079 // about in case nothing has focus. even if this specific view 8080 // isn't focusable, it may contain something that is, so let 8081 // the root view try to give this focus if nothing else does. 8082 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 8083 mParent.focusableViewAvailable(this); 8084 } 8085 } 8086 } 8087 8088 /* Check if the GONE bit has changed */ 8089 if ((changed & GONE) != 0) { 8090 needGlobalAttributesUpdate(false); 8091 requestLayout(); 8092 8093 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 8094 if (hasFocus()) clearFocus(); 8095 clearAccessibilityFocus(); 8096 destroyDrawingCache(); 8097 if (mParent instanceof View) { 8098 // GONE views noop invalidation, so invalidate the parent 8099 ((View) mParent).invalidate(true); 8100 } 8101 // Mark the view drawn to ensure that it gets invalidated properly the next 8102 // time it is visible and gets invalidated 8103 mPrivateFlags |= DRAWN; 8104 } 8105 if (mAttachInfo != null) { 8106 mAttachInfo.mViewVisibilityChanged = true; 8107 } 8108 } 8109 8110 /* Check if the VISIBLE bit has changed */ 8111 if ((changed & INVISIBLE) != 0) { 8112 needGlobalAttributesUpdate(false); 8113 /* 8114 * If this view is becoming invisible, set the DRAWN flag so that 8115 * the next invalidate() will not be skipped. 8116 */ 8117 mPrivateFlags |= DRAWN; 8118 8119 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 8120 // root view becoming invisible shouldn't clear focus and accessibility focus 8121 if (getRootView() != this) { 8122 clearFocus(); 8123 clearAccessibilityFocus(); 8124 } 8125 } 8126 if (mAttachInfo != null) { 8127 mAttachInfo.mViewVisibilityChanged = true; 8128 } 8129 } 8130 8131 if ((changed & VISIBILITY_MASK) != 0) { 8132 if (mParent instanceof ViewGroup) { 8133 ((ViewGroup) mParent).onChildVisibilityChanged(this, 8134 (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK)); 8135 ((View) mParent).invalidate(true); 8136 } else if (mParent != null) { 8137 mParent.invalidateChild(this, null); 8138 } 8139 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 8140 } 8141 8142 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 8143 destroyDrawingCache(); 8144 } 8145 8146 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 8147 destroyDrawingCache(); 8148 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8149 invalidateParentCaches(); 8150 } 8151 8152 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 8153 destroyDrawingCache(); 8154 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8155 } 8156 8157 if ((changed & DRAW_MASK) != 0) { 8158 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 8159 if (mBackground != null) { 8160 mPrivateFlags &= ~SKIP_DRAW; 8161 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 8162 } else { 8163 mPrivateFlags |= SKIP_DRAW; 8164 } 8165 } else { 8166 mPrivateFlags &= ~SKIP_DRAW; 8167 } 8168 requestLayout(); 8169 invalidate(true); 8170 } 8171 8172 if ((changed & KEEP_SCREEN_ON) != 0) { 8173 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 8174 mParent.recomputeViewAttributes(this); 8175 } 8176 } 8177 8178 if (AccessibilityManager.getInstance(mContext).isEnabled() 8179 && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0 8180 || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) { 8181 notifyAccessibilityStateChanged(); 8182 } 8183 } 8184 8185 /** 8186 * Change the view's z order in the tree, so it's on top of other sibling 8187 * views 8188 */ 8189 public void bringToFront() { 8190 if (mParent != null) { 8191 mParent.bringChildToFront(this); 8192 } 8193 } 8194 8195 /** 8196 * This is called in response to an internal scroll in this view (i.e., the 8197 * view scrolled its own contents). This is typically as a result of 8198 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 8199 * called. 8200 * 8201 * @param l Current horizontal scroll origin. 8202 * @param t Current vertical scroll origin. 8203 * @param oldl Previous horizontal scroll origin. 8204 * @param oldt Previous vertical scroll origin. 8205 */ 8206 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 8207 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8208 postSendViewScrolledAccessibilityEventCallback(); 8209 } 8210 8211 mBackgroundSizeChanged = true; 8212 8213 final AttachInfo ai = mAttachInfo; 8214 if (ai != null) { 8215 ai.mViewScrollChanged = true; 8216 } 8217 } 8218 8219 /** 8220 * Interface definition for a callback to be invoked when the layout bounds of a view 8221 * changes due to layout processing. 8222 */ 8223 public interface OnLayoutChangeListener { 8224 /** 8225 * Called when the focus state of a view has changed. 8226 * 8227 * @param v The view whose state has changed. 8228 * @param left The new value of the view's left property. 8229 * @param top The new value of the view's top property. 8230 * @param right The new value of the view's right property. 8231 * @param bottom The new value of the view's bottom property. 8232 * @param oldLeft The previous value of the view's left property. 8233 * @param oldTop The previous value of the view's top property. 8234 * @param oldRight The previous value of the view's right property. 8235 * @param oldBottom The previous value of the view's bottom property. 8236 */ 8237 void onLayoutChange(View v, int left, int top, int right, int bottom, 8238 int oldLeft, int oldTop, int oldRight, int oldBottom); 8239 } 8240 8241 /** 8242 * This is called during layout when the size of this view has changed. If 8243 * you were just added to the view hierarchy, you're called with the old 8244 * values of 0. 8245 * 8246 * @param w Current width of this view. 8247 * @param h Current height of this view. 8248 * @param oldw Old width of this view. 8249 * @param oldh Old height of this view. 8250 */ 8251 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 8252 } 8253 8254 /** 8255 * Called by draw to draw the child views. This may be overridden 8256 * by derived classes to gain control just before its children are drawn 8257 * (but after its own view has been drawn). 8258 * @param canvas the canvas on which to draw the view 8259 */ 8260 protected void dispatchDraw(Canvas canvas) { 8261 8262 } 8263 8264 /** 8265 * Gets the parent of this view. Note that the parent is a 8266 * ViewParent and not necessarily a View. 8267 * 8268 * @return Parent of this view. 8269 */ 8270 public final ViewParent getParent() { 8271 return mParent; 8272 } 8273 8274 /** 8275 * Set the horizontal scrolled position of your view. This will cause a call to 8276 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8277 * invalidated. 8278 * @param value the x position to scroll to 8279 */ 8280 public void setScrollX(int value) { 8281 scrollTo(value, mScrollY); 8282 } 8283 8284 /** 8285 * Set the vertical scrolled position of your view. This will cause a call to 8286 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8287 * invalidated. 8288 * @param value the y position to scroll to 8289 */ 8290 public void setScrollY(int value) { 8291 scrollTo(mScrollX, value); 8292 } 8293 8294 /** 8295 * Return the scrolled left position of this view. This is the left edge of 8296 * the displayed part of your view. You do not need to draw any pixels 8297 * farther left, since those are outside of the frame of your view on 8298 * screen. 8299 * 8300 * @return The left edge of the displayed part of your view, in pixels. 8301 */ 8302 public final int getScrollX() { 8303 return mScrollX; 8304 } 8305 8306 /** 8307 * Return the scrolled top position of this view. This is the top edge of 8308 * the displayed part of your view. You do not need to draw any pixels above 8309 * it, since those are outside of the frame of your view on screen. 8310 * 8311 * @return The top edge of the displayed part of your view, in pixels. 8312 */ 8313 public final int getScrollY() { 8314 return mScrollY; 8315 } 8316 8317 /** 8318 * Return the width of the your view. 8319 * 8320 * @return The width of your view, in pixels. 8321 */ 8322 @ViewDebug.ExportedProperty(category = "layout") 8323 public final int getWidth() { 8324 return mRight - mLeft; 8325 } 8326 8327 /** 8328 * Return the height of your view. 8329 * 8330 * @return The height of your view, in pixels. 8331 */ 8332 @ViewDebug.ExportedProperty(category = "layout") 8333 public final int getHeight() { 8334 return mBottom - mTop; 8335 } 8336 8337 /** 8338 * Return the visible drawing bounds of your view. Fills in the output 8339 * rectangle with the values from getScrollX(), getScrollY(), 8340 * getWidth(), and getHeight(). 8341 * 8342 * @param outRect The (scrolled) drawing bounds of the view. 8343 */ 8344 public void getDrawingRect(Rect outRect) { 8345 outRect.left = mScrollX; 8346 outRect.top = mScrollY; 8347 outRect.right = mScrollX + (mRight - mLeft); 8348 outRect.bottom = mScrollY + (mBottom - mTop); 8349 } 8350 8351 /** 8352 * Like {@link #getMeasuredWidthAndState()}, but only returns the 8353 * raw width component (that is the result is masked by 8354 * {@link #MEASURED_SIZE_MASK}). 8355 * 8356 * @return The raw measured width of this view. 8357 */ 8358 public final int getMeasuredWidth() { 8359 return mMeasuredWidth & MEASURED_SIZE_MASK; 8360 } 8361 8362 /** 8363 * Return the full width measurement information for this view as computed 8364 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 8365 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 8366 * This should be used during measurement and layout calculations only. Use 8367 * {@link #getWidth()} to see how wide a view is after layout. 8368 * 8369 * @return The measured width of this view as a bit mask. 8370 */ 8371 public final int getMeasuredWidthAndState() { 8372 return mMeasuredWidth; 8373 } 8374 8375 /** 8376 * Like {@link #getMeasuredHeightAndState()}, but only returns the 8377 * raw width component (that is the result is masked by 8378 * {@link #MEASURED_SIZE_MASK}). 8379 * 8380 * @return The raw measured height of this view. 8381 */ 8382 public final int getMeasuredHeight() { 8383 return mMeasuredHeight & MEASURED_SIZE_MASK; 8384 } 8385 8386 /** 8387 * Return the full height measurement information for this view as computed 8388 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 8389 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 8390 * This should be used during measurement and layout calculations only. Use 8391 * {@link #getHeight()} to see how wide a view is after layout. 8392 * 8393 * @return The measured width of this view as a bit mask. 8394 */ 8395 public final int getMeasuredHeightAndState() { 8396 return mMeasuredHeight; 8397 } 8398 8399 /** 8400 * Return only the state bits of {@link #getMeasuredWidthAndState()} 8401 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 8402 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 8403 * and the height component is at the shifted bits 8404 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 8405 */ 8406 public final int getMeasuredState() { 8407 return (mMeasuredWidth&MEASURED_STATE_MASK) 8408 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 8409 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 8410 } 8411 8412 /** 8413 * The transform matrix of this view, which is calculated based on the current 8414 * roation, scale, and pivot properties. 8415 * 8416 * @see #getRotation() 8417 * @see #getScaleX() 8418 * @see #getScaleY() 8419 * @see #getPivotX() 8420 * @see #getPivotY() 8421 * @return The current transform matrix for the view 8422 */ 8423 public Matrix getMatrix() { 8424 if (mTransformationInfo != null) { 8425 updateMatrix(); 8426 return mTransformationInfo.mMatrix; 8427 } 8428 return Matrix.IDENTITY_MATRIX; 8429 } 8430 8431 /** 8432 * Utility function to determine if the value is far enough away from zero to be 8433 * considered non-zero. 8434 * @param value A floating point value to check for zero-ness 8435 * @return whether the passed-in value is far enough away from zero to be considered non-zero 8436 */ 8437 private static boolean nonzero(float value) { 8438 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 8439 } 8440 8441 /** 8442 * Returns true if the transform matrix is the identity matrix. 8443 * Recomputes the matrix if necessary. 8444 * 8445 * @return True if the transform matrix is the identity matrix, false otherwise. 8446 */ 8447 final boolean hasIdentityMatrix() { 8448 if (mTransformationInfo != null) { 8449 updateMatrix(); 8450 return mTransformationInfo.mMatrixIsIdentity; 8451 } 8452 return true; 8453 } 8454 8455 void ensureTransformationInfo() { 8456 if (mTransformationInfo == null) { 8457 mTransformationInfo = new TransformationInfo(); 8458 } 8459 } 8460 8461 /** 8462 * Recomputes the transform matrix if necessary. 8463 */ 8464 private void updateMatrix() { 8465 final TransformationInfo info = mTransformationInfo; 8466 if (info == null) { 8467 return; 8468 } 8469 if (info.mMatrixDirty) { 8470 // transform-related properties have changed since the last time someone 8471 // asked for the matrix; recalculate it with the current values 8472 8473 // Figure out if we need to update the pivot point 8474 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 8475 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 8476 info.mPrevWidth = mRight - mLeft; 8477 info.mPrevHeight = mBottom - mTop; 8478 info.mPivotX = info.mPrevWidth / 2f; 8479 info.mPivotY = info.mPrevHeight / 2f; 8480 } 8481 } 8482 info.mMatrix.reset(); 8483 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 8484 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 8485 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 8486 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 8487 } else { 8488 if (info.mCamera == null) { 8489 info.mCamera = new Camera(); 8490 info.matrix3D = new Matrix(); 8491 } 8492 info.mCamera.save(); 8493 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 8494 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 8495 info.mCamera.getMatrix(info.matrix3D); 8496 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 8497 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 8498 info.mPivotY + info.mTranslationY); 8499 info.mMatrix.postConcat(info.matrix3D); 8500 info.mCamera.restore(); 8501 } 8502 info.mMatrixDirty = false; 8503 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 8504 info.mInverseMatrixDirty = true; 8505 } 8506 } 8507 8508 /** 8509 * Utility method to retrieve the inverse of the current mMatrix property. 8510 * We cache the matrix to avoid recalculating it when transform properties 8511 * have not changed. 8512 * 8513 * @return The inverse of the current matrix of this view. 8514 */ 8515 final Matrix getInverseMatrix() { 8516 final TransformationInfo info = mTransformationInfo; 8517 if (info != null) { 8518 updateMatrix(); 8519 if (info.mInverseMatrixDirty) { 8520 if (info.mInverseMatrix == null) { 8521 info.mInverseMatrix = new Matrix(); 8522 } 8523 info.mMatrix.invert(info.mInverseMatrix); 8524 info.mInverseMatrixDirty = false; 8525 } 8526 return info.mInverseMatrix; 8527 } 8528 return Matrix.IDENTITY_MATRIX; 8529 } 8530 8531 /** 8532 * Gets the distance along the Z axis from the camera to this view. 8533 * 8534 * @see #setCameraDistance(float) 8535 * 8536 * @return The distance along the Z axis. 8537 */ 8538 public float getCameraDistance() { 8539 ensureTransformationInfo(); 8540 final float dpi = mResources.getDisplayMetrics().densityDpi; 8541 final TransformationInfo info = mTransformationInfo; 8542 if (info.mCamera == null) { 8543 info.mCamera = new Camera(); 8544 info.matrix3D = new Matrix(); 8545 } 8546 return -(info.mCamera.getLocationZ() * dpi); 8547 } 8548 8549 /** 8550 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 8551 * views are drawn) from the camera to this view. The camera's distance 8552 * affects 3D transformations, for instance rotations around the X and Y 8553 * axis. If the rotationX or rotationY properties are changed and this view is 8554 * large (more than half the size of the screen), it is recommended to always 8555 * use a camera distance that's greater than the height (X axis rotation) or 8556 * the width (Y axis rotation) of this view.</p> 8557 * 8558 * <p>The distance of the camera from the view plane can have an affect on the 8559 * perspective distortion of the view when it is rotated around the x or y axis. 8560 * For example, a large distance will result in a large viewing angle, and there 8561 * will not be much perspective distortion of the view as it rotates. A short 8562 * distance may cause much more perspective distortion upon rotation, and can 8563 * also result in some drawing artifacts if the rotated view ends up partially 8564 * behind the camera (which is why the recommendation is to use a distance at 8565 * least as far as the size of the view, if the view is to be rotated.)</p> 8566 * 8567 * <p>The distance is expressed in "depth pixels." The default distance depends 8568 * on the screen density. For instance, on a medium density display, the 8569 * default distance is 1280. On a high density display, the default distance 8570 * is 1920.</p> 8571 * 8572 * <p>If you want to specify a distance that leads to visually consistent 8573 * results across various densities, use the following formula:</p> 8574 * <pre> 8575 * float scale = context.getResources().getDisplayMetrics().density; 8576 * view.setCameraDistance(distance * scale); 8577 * </pre> 8578 * 8579 * <p>The density scale factor of a high density display is 1.5, 8580 * and 1920 = 1280 * 1.5.</p> 8581 * 8582 * @param distance The distance in "depth pixels", if negative the opposite 8583 * value is used 8584 * 8585 * @see #setRotationX(float) 8586 * @see #setRotationY(float) 8587 */ 8588 public void setCameraDistance(float distance) { 8589 invalidateViewProperty(true, false); 8590 8591 ensureTransformationInfo(); 8592 final float dpi = mResources.getDisplayMetrics().densityDpi; 8593 final TransformationInfo info = mTransformationInfo; 8594 if (info.mCamera == null) { 8595 info.mCamera = new Camera(); 8596 info.matrix3D = new Matrix(); 8597 } 8598 8599 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 8600 info.mMatrixDirty = true; 8601 8602 invalidateViewProperty(false, false); 8603 if (mDisplayList != null) { 8604 mDisplayList.setCameraDistance(-Math.abs(distance) / dpi); 8605 } 8606 if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) { 8607 // View was rejected last time it was drawn by its parent; this may have changed 8608 invalidateParentIfNeeded(); 8609 } 8610 } 8611 8612 /** 8613 * The degrees that the view is rotated around the pivot point. 8614 * 8615 * @see #setRotation(float) 8616 * @see #getPivotX() 8617 * @see #getPivotY() 8618 * 8619 * @return The degrees of rotation. 8620 */ 8621 @ViewDebug.ExportedProperty(category = "drawing") 8622 public float getRotation() { 8623 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 8624 } 8625 8626 /** 8627 * Sets the degrees that the view is rotated around the pivot point. Increasing values 8628 * result in clockwise rotation. 8629 * 8630 * @param rotation The degrees of rotation. 8631 * 8632 * @see #getRotation() 8633 * @see #getPivotX() 8634 * @see #getPivotY() 8635 * @see #setRotationX(float) 8636 * @see #setRotationY(float) 8637 * 8638 * @attr ref android.R.styleable#View_rotation 8639 */ 8640 public void setRotation(float rotation) { 8641 ensureTransformationInfo(); 8642 final TransformationInfo info = mTransformationInfo; 8643 if (info.mRotation != rotation) { 8644 // Double-invalidation is necessary to capture view's old and new areas 8645 invalidateViewProperty(true, false); 8646 info.mRotation = rotation; 8647 info.mMatrixDirty = true; 8648 invalidateViewProperty(false, true); 8649 if (mDisplayList != null) { 8650 mDisplayList.setRotation(rotation); 8651 } 8652 if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) { 8653 // View was rejected last time it was drawn by its parent; this may have changed 8654 invalidateParentIfNeeded(); 8655 } 8656 } 8657 } 8658 8659 /** 8660 * The degrees that the view is rotated around the vertical axis through the pivot point. 8661 * 8662 * @see #getPivotX() 8663 * @see #getPivotY() 8664 * @see #setRotationY(float) 8665 * 8666 * @return The degrees of Y rotation. 8667 */ 8668 @ViewDebug.ExportedProperty(category = "drawing") 8669 public float getRotationY() { 8670 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 8671 } 8672 8673 /** 8674 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 8675 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 8676 * down the y axis. 8677 * 8678 * When rotating large views, it is recommended to adjust the camera distance 8679 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 8680 * 8681 * @param rotationY The degrees of Y rotation. 8682 * 8683 * @see #getRotationY() 8684 * @see #getPivotX() 8685 * @see #getPivotY() 8686 * @see #setRotation(float) 8687 * @see #setRotationX(float) 8688 * @see #setCameraDistance(float) 8689 * 8690 * @attr ref android.R.styleable#View_rotationY 8691 */ 8692 public void setRotationY(float rotationY) { 8693 ensureTransformationInfo(); 8694 final TransformationInfo info = mTransformationInfo; 8695 if (info.mRotationY != rotationY) { 8696 invalidateViewProperty(true, false); 8697 info.mRotationY = rotationY; 8698 info.mMatrixDirty = true; 8699 invalidateViewProperty(false, true); 8700 if (mDisplayList != null) { 8701 mDisplayList.setRotationY(rotationY); 8702 } 8703 if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) { 8704 // View was rejected last time it was drawn by its parent; this may have changed 8705 invalidateParentIfNeeded(); 8706 } 8707 } 8708 } 8709 8710 /** 8711 * The degrees that the view is rotated around the horizontal axis through the pivot point. 8712 * 8713 * @see #getPivotX() 8714 * @see #getPivotY() 8715 * @see #setRotationX(float) 8716 * 8717 * @return The degrees of X rotation. 8718 */ 8719 @ViewDebug.ExportedProperty(category = "drawing") 8720 public float getRotationX() { 8721 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 8722 } 8723 8724 /** 8725 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 8726 * Increasing values result in clockwise rotation from the viewpoint of looking down the 8727 * x axis. 8728 * 8729 * When rotating large views, it is recommended to adjust the camera distance 8730 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 8731 * 8732 * @param rotationX The degrees of X rotation. 8733 * 8734 * @see #getRotationX() 8735 * @see #getPivotX() 8736 * @see #getPivotY() 8737 * @see #setRotation(float) 8738 * @see #setRotationY(float) 8739 * @see #setCameraDistance(float) 8740 * 8741 * @attr ref android.R.styleable#View_rotationX 8742 */ 8743 public void setRotationX(float rotationX) { 8744 ensureTransformationInfo(); 8745 final TransformationInfo info = mTransformationInfo; 8746 if (info.mRotationX != rotationX) { 8747 invalidateViewProperty(true, false); 8748 info.mRotationX = rotationX; 8749 info.mMatrixDirty = true; 8750 invalidateViewProperty(false, true); 8751 if (mDisplayList != null) { 8752 mDisplayList.setRotationX(rotationX); 8753 } 8754 if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) { 8755 // View was rejected last time it was drawn by its parent; this may have changed 8756 invalidateParentIfNeeded(); 8757 } 8758 } 8759 } 8760 8761 /** 8762 * The amount that the view is scaled in x around the pivot point, as a proportion of 8763 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 8764 * 8765 * <p>By default, this is 1.0f. 8766 * 8767 * @see #getPivotX() 8768 * @see #getPivotY() 8769 * @return The scaling factor. 8770 */ 8771 @ViewDebug.ExportedProperty(category = "drawing") 8772 public float getScaleX() { 8773 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 8774 } 8775 8776 /** 8777 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 8778 * the view's unscaled width. A value of 1 means that no scaling is applied. 8779 * 8780 * @param scaleX The scaling factor. 8781 * @see #getPivotX() 8782 * @see #getPivotY() 8783 * 8784 * @attr ref android.R.styleable#View_scaleX 8785 */ 8786 public void setScaleX(float scaleX) { 8787 ensureTransformationInfo(); 8788 final TransformationInfo info = mTransformationInfo; 8789 if (info.mScaleX != scaleX) { 8790 invalidateViewProperty(true, false); 8791 info.mScaleX = scaleX; 8792 info.mMatrixDirty = true; 8793 invalidateViewProperty(false, true); 8794 if (mDisplayList != null) { 8795 mDisplayList.setScaleX(scaleX); 8796 } 8797 if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) { 8798 // View was rejected last time it was drawn by its parent; this may have changed 8799 invalidateParentIfNeeded(); 8800 } 8801 } 8802 } 8803 8804 /** 8805 * The amount that the view is scaled in y around the pivot point, as a proportion of 8806 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 8807 * 8808 * <p>By default, this is 1.0f. 8809 * 8810 * @see #getPivotX() 8811 * @see #getPivotY() 8812 * @return The scaling factor. 8813 */ 8814 @ViewDebug.ExportedProperty(category = "drawing") 8815 public float getScaleY() { 8816 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 8817 } 8818 8819 /** 8820 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 8821 * the view's unscaled width. A value of 1 means that no scaling is applied. 8822 * 8823 * @param scaleY The scaling factor. 8824 * @see #getPivotX() 8825 * @see #getPivotY() 8826 * 8827 * @attr ref android.R.styleable#View_scaleY 8828 */ 8829 public void setScaleY(float scaleY) { 8830 ensureTransformationInfo(); 8831 final TransformationInfo info = mTransformationInfo; 8832 if (info.mScaleY != scaleY) { 8833 invalidateViewProperty(true, false); 8834 info.mScaleY = scaleY; 8835 info.mMatrixDirty = true; 8836 invalidateViewProperty(false, true); 8837 if (mDisplayList != null) { 8838 mDisplayList.setScaleY(scaleY); 8839 } 8840 if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) { 8841 // View was rejected last time it was drawn by its parent; this may have changed 8842 invalidateParentIfNeeded(); 8843 } 8844 } 8845 } 8846 8847 /** 8848 * The x location of the point around which the view is {@link #setRotation(float) rotated} 8849 * and {@link #setScaleX(float) scaled}. 8850 * 8851 * @see #getRotation() 8852 * @see #getScaleX() 8853 * @see #getScaleY() 8854 * @see #getPivotY() 8855 * @return The x location of the pivot point. 8856 * 8857 * @attr ref android.R.styleable#View_transformPivotX 8858 */ 8859 @ViewDebug.ExportedProperty(category = "drawing") 8860 public float getPivotX() { 8861 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 8862 } 8863 8864 /** 8865 * Sets the x location of the point around which the view is 8866 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 8867 * By default, the pivot point is centered on the object. 8868 * Setting this property disables this behavior and causes the view to use only the 8869 * explicitly set pivotX and pivotY values. 8870 * 8871 * @param pivotX The x location of the pivot point. 8872 * @see #getRotation() 8873 * @see #getScaleX() 8874 * @see #getScaleY() 8875 * @see #getPivotY() 8876 * 8877 * @attr ref android.R.styleable#View_transformPivotX 8878 */ 8879 public void setPivotX(float pivotX) { 8880 ensureTransformationInfo(); 8881 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 8882 final TransformationInfo info = mTransformationInfo; 8883 if (info.mPivotX != pivotX) { 8884 invalidateViewProperty(true, false); 8885 info.mPivotX = pivotX; 8886 info.mMatrixDirty = true; 8887 invalidateViewProperty(false, true); 8888 if (mDisplayList != null) { 8889 mDisplayList.setPivotX(pivotX); 8890 } 8891 if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) { 8892 // View was rejected last time it was drawn by its parent; this may have changed 8893 invalidateParentIfNeeded(); 8894 } 8895 } 8896 } 8897 8898 /** 8899 * The y location of the point around which the view is {@link #setRotation(float) rotated} 8900 * and {@link #setScaleY(float) scaled}. 8901 * 8902 * @see #getRotation() 8903 * @see #getScaleX() 8904 * @see #getScaleY() 8905 * @see #getPivotY() 8906 * @return The y location of the pivot point. 8907 * 8908 * @attr ref android.R.styleable#View_transformPivotY 8909 */ 8910 @ViewDebug.ExportedProperty(category = "drawing") 8911 public float getPivotY() { 8912 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 8913 } 8914 8915 /** 8916 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 8917 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 8918 * Setting this property disables this behavior and causes the view to use only the 8919 * explicitly set pivotX and pivotY values. 8920 * 8921 * @param pivotY The y location of the pivot point. 8922 * @see #getRotation() 8923 * @see #getScaleX() 8924 * @see #getScaleY() 8925 * @see #getPivotY() 8926 * 8927 * @attr ref android.R.styleable#View_transformPivotY 8928 */ 8929 public void setPivotY(float pivotY) { 8930 ensureTransformationInfo(); 8931 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 8932 final TransformationInfo info = mTransformationInfo; 8933 if (info.mPivotY != pivotY) { 8934 invalidateViewProperty(true, false); 8935 info.mPivotY = pivotY; 8936 info.mMatrixDirty = true; 8937 invalidateViewProperty(false, true); 8938 if (mDisplayList != null) { 8939 mDisplayList.setPivotY(pivotY); 8940 } 8941 if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) { 8942 // View was rejected last time it was drawn by its parent; this may have changed 8943 invalidateParentIfNeeded(); 8944 } 8945 } 8946 } 8947 8948 /** 8949 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 8950 * completely transparent and 1 means the view is completely opaque. 8951 * 8952 * <p>By default this is 1.0f. 8953 * @return The opacity of the view. 8954 */ 8955 @ViewDebug.ExportedProperty(category = "drawing") 8956 public float getAlpha() { 8957 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 8958 } 8959 8960 /** 8961 * Returns whether this View has content which overlaps. This function, intended to be 8962 * overridden by specific View types, is an optimization when alpha is set on a view. If 8963 * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer 8964 * and then composited it into place, which can be expensive. If the view has no overlapping 8965 * rendering, the view can draw each primitive with the appropriate alpha value directly. 8966 * An example of overlapping rendering is a TextView with a background image, such as a 8967 * Button. An example of non-overlapping rendering is a TextView with no background, or 8968 * an ImageView with only the foreground image. The default implementation returns true; 8969 * subclasses should override if they have cases which can be optimized. 8970 * 8971 * @return true if the content in this view might overlap, false otherwise. 8972 */ 8973 public boolean hasOverlappingRendering() { 8974 return true; 8975 } 8976 8977 /** 8978 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 8979 * completely transparent and 1 means the view is completely opaque.</p> 8980 * 8981 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 8982 * responsible for applying the opacity itself. Otherwise, calling this method is 8983 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 8984 * setting a hardware layer.</p> 8985 * 8986 * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have 8987 * performance implications. It is generally best to use the alpha property sparingly and 8988 * transiently, as in the case of fading animations.</p> 8989 * 8990 * @param alpha The opacity of the view. 8991 * 8992 * @see #setLayerType(int, android.graphics.Paint) 8993 * 8994 * @attr ref android.R.styleable#View_alpha 8995 */ 8996 public void setAlpha(float alpha) { 8997 ensureTransformationInfo(); 8998 if (mTransformationInfo.mAlpha != alpha) { 8999 mTransformationInfo.mAlpha = alpha; 9000 if (onSetAlpha((int) (alpha * 255))) { 9001 mPrivateFlags |= ALPHA_SET; 9002 // subclass is handling alpha - don't optimize rendering cache invalidation 9003 invalidateParentCaches(); 9004 invalidate(true); 9005 } else { 9006 mPrivateFlags &= ~ALPHA_SET; 9007 invalidateViewProperty(true, false); 9008 if (mDisplayList != null) { 9009 mDisplayList.setAlpha(alpha); 9010 } 9011 } 9012 } 9013 } 9014 9015 /** 9016 * Faster version of setAlpha() which performs the same steps except there are 9017 * no calls to invalidate(). The caller of this function should perform proper invalidation 9018 * on the parent and this object. The return value indicates whether the subclass handles 9019 * alpha (the return value for onSetAlpha()). 9020 * 9021 * @param alpha The new value for the alpha property 9022 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 9023 * the new value for the alpha property is different from the old value 9024 */ 9025 boolean setAlphaNoInvalidation(float alpha) { 9026 ensureTransformationInfo(); 9027 if (mTransformationInfo.mAlpha != alpha) { 9028 mTransformationInfo.mAlpha = alpha; 9029 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 9030 if (subclassHandlesAlpha) { 9031 mPrivateFlags |= ALPHA_SET; 9032 return true; 9033 } else { 9034 mPrivateFlags &= ~ALPHA_SET; 9035 if (mDisplayList != null) { 9036 mDisplayList.setAlpha(alpha); 9037 } 9038 } 9039 } 9040 return false; 9041 } 9042 9043 /** 9044 * Top position of this view relative to its parent. 9045 * 9046 * @return The top of this view, in pixels. 9047 */ 9048 @ViewDebug.CapturedViewProperty 9049 public final int getTop() { 9050 return mTop; 9051 } 9052 9053 /** 9054 * Sets the top position of this view relative to its parent. This method is meant to be called 9055 * by the layout system and should not generally be called otherwise, because the property 9056 * may be changed at any time by the layout. 9057 * 9058 * @param top The top of this view, in pixels. 9059 */ 9060 public final void setTop(int top) { 9061 if (top != mTop) { 9062 updateMatrix(); 9063 final boolean matrixIsIdentity = mTransformationInfo == null 9064 || mTransformationInfo.mMatrixIsIdentity; 9065 if (matrixIsIdentity) { 9066 if (mAttachInfo != null) { 9067 int minTop; 9068 int yLoc; 9069 if (top < mTop) { 9070 minTop = top; 9071 yLoc = top - mTop; 9072 } else { 9073 minTop = mTop; 9074 yLoc = 0; 9075 } 9076 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 9077 } 9078 } else { 9079 // Double-invalidation is necessary to capture view's old and new areas 9080 invalidate(true); 9081 } 9082 9083 int width = mRight - mLeft; 9084 int oldHeight = mBottom - mTop; 9085 9086 mTop = top; 9087 if (mDisplayList != null) { 9088 mDisplayList.setTop(mTop); 9089 } 9090 9091 onSizeChanged(width, mBottom - mTop, width, oldHeight); 9092 9093 if (!matrixIsIdentity) { 9094 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 9095 // A change in dimension means an auto-centered pivot point changes, too 9096 mTransformationInfo.mMatrixDirty = true; 9097 } 9098 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 9099 invalidate(true); 9100 } 9101 mBackgroundSizeChanged = true; 9102 invalidateParentIfNeeded(); 9103 if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) { 9104 // View was rejected last time it was drawn by its parent; this may have changed 9105 invalidateParentIfNeeded(); 9106 } 9107 } 9108 } 9109 9110 /** 9111 * Bottom position of this view relative to its parent. 9112 * 9113 * @return The bottom of this view, in pixels. 9114 */ 9115 @ViewDebug.CapturedViewProperty 9116 public final int getBottom() { 9117 return mBottom; 9118 } 9119 9120 /** 9121 * True if this view has changed since the last time being drawn. 9122 * 9123 * @return The dirty state of this view. 9124 */ 9125 public boolean isDirty() { 9126 return (mPrivateFlags & DIRTY_MASK) != 0; 9127 } 9128 9129 /** 9130 * Sets the bottom position of this view relative to its parent. This method is meant to be 9131 * called by the layout system and should not generally be called otherwise, because the 9132 * property may be changed at any time by the layout. 9133 * 9134 * @param bottom The bottom of this view, in pixels. 9135 */ 9136 public final void setBottom(int bottom) { 9137 if (bottom != mBottom) { 9138 updateMatrix(); 9139 final boolean matrixIsIdentity = mTransformationInfo == null 9140 || mTransformationInfo.mMatrixIsIdentity; 9141 if (matrixIsIdentity) { 9142 if (mAttachInfo != null) { 9143 int maxBottom; 9144 if (bottom < mBottom) { 9145 maxBottom = mBottom; 9146 } else { 9147 maxBottom = bottom; 9148 } 9149 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 9150 } 9151 } else { 9152 // Double-invalidation is necessary to capture view's old and new areas 9153 invalidate(true); 9154 } 9155 9156 int width = mRight - mLeft; 9157 int oldHeight = mBottom - mTop; 9158 9159 mBottom = bottom; 9160 if (mDisplayList != null) { 9161 mDisplayList.setBottom(mBottom); 9162 } 9163 9164 onSizeChanged(width, mBottom - mTop, width, oldHeight); 9165 9166 if (!matrixIsIdentity) { 9167 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 9168 // A change in dimension means an auto-centered pivot point changes, too 9169 mTransformationInfo.mMatrixDirty = true; 9170 } 9171 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 9172 invalidate(true); 9173 } 9174 mBackgroundSizeChanged = true; 9175 invalidateParentIfNeeded(); 9176 if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) { 9177 // View was rejected last time it was drawn by its parent; this may have changed 9178 invalidateParentIfNeeded(); 9179 } 9180 } 9181 } 9182 9183 /** 9184 * Left position of this view relative to its parent. 9185 * 9186 * @return The left edge of this view, in pixels. 9187 */ 9188 @ViewDebug.CapturedViewProperty 9189 public final int getLeft() { 9190 return mLeft; 9191 } 9192 9193 /** 9194 * Sets the left position of this view relative to its parent. This method is meant to be called 9195 * by the layout system and should not generally be called otherwise, because the property 9196 * may be changed at any time by the layout. 9197 * 9198 * @param left The bottom of this view, in pixels. 9199 */ 9200 public final void setLeft(int left) { 9201 if (left != mLeft) { 9202 updateMatrix(); 9203 final boolean matrixIsIdentity = mTransformationInfo == null 9204 || mTransformationInfo.mMatrixIsIdentity; 9205 if (matrixIsIdentity) { 9206 if (mAttachInfo != null) { 9207 int minLeft; 9208 int xLoc; 9209 if (left < mLeft) { 9210 minLeft = left; 9211 xLoc = left - mLeft; 9212 } else { 9213 minLeft = mLeft; 9214 xLoc = 0; 9215 } 9216 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 9217 } 9218 } else { 9219 // Double-invalidation is necessary to capture view's old and new areas 9220 invalidate(true); 9221 } 9222 9223 int oldWidth = mRight - mLeft; 9224 int height = mBottom - mTop; 9225 9226 mLeft = left; 9227 if (mDisplayList != null) { 9228 mDisplayList.setLeft(left); 9229 } 9230 9231 onSizeChanged(mRight - mLeft, height, oldWidth, height); 9232 9233 if (!matrixIsIdentity) { 9234 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 9235 // A change in dimension means an auto-centered pivot point changes, too 9236 mTransformationInfo.mMatrixDirty = true; 9237 } 9238 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 9239 invalidate(true); 9240 } 9241 mBackgroundSizeChanged = true; 9242 invalidateParentIfNeeded(); 9243 if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) { 9244 // View was rejected last time it was drawn by its parent; this may have changed 9245 invalidateParentIfNeeded(); 9246 } 9247 } 9248 } 9249 9250 /** 9251 * Right position of this view relative to its parent. 9252 * 9253 * @return The right edge of this view, in pixels. 9254 */ 9255 @ViewDebug.CapturedViewProperty 9256 public final int getRight() { 9257 return mRight; 9258 } 9259 9260 /** 9261 * Sets the right position of this view relative to its parent. This method is meant to be called 9262 * by the layout system and should not generally be called otherwise, because the property 9263 * may be changed at any time by the layout. 9264 * 9265 * @param right The bottom of this view, in pixels. 9266 */ 9267 public final void setRight(int right) { 9268 if (right != mRight) { 9269 updateMatrix(); 9270 final boolean matrixIsIdentity = mTransformationInfo == null 9271 || mTransformationInfo.mMatrixIsIdentity; 9272 if (matrixIsIdentity) { 9273 if (mAttachInfo != null) { 9274 int maxRight; 9275 if (right < mRight) { 9276 maxRight = mRight; 9277 } else { 9278 maxRight = right; 9279 } 9280 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 9281 } 9282 } else { 9283 // Double-invalidation is necessary to capture view's old and new areas 9284 invalidate(true); 9285 } 9286 9287 int oldWidth = mRight - mLeft; 9288 int height = mBottom - mTop; 9289 9290 mRight = right; 9291 if (mDisplayList != null) { 9292 mDisplayList.setRight(mRight); 9293 } 9294 9295 onSizeChanged(mRight - mLeft, height, oldWidth, height); 9296 9297 if (!matrixIsIdentity) { 9298 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 9299 // A change in dimension means an auto-centered pivot point changes, too 9300 mTransformationInfo.mMatrixDirty = true; 9301 } 9302 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 9303 invalidate(true); 9304 } 9305 mBackgroundSizeChanged = true; 9306 invalidateParentIfNeeded(); 9307 if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) { 9308 // View was rejected last time it was drawn by its parent; this may have changed 9309 invalidateParentIfNeeded(); 9310 } 9311 } 9312 } 9313 9314 /** 9315 * The visual x position of this view, in pixels. This is equivalent to the 9316 * {@link #setTranslationX(float) translationX} property plus the current 9317 * {@link #getLeft() left} property. 9318 * 9319 * @return The visual x position of this view, in pixels. 9320 */ 9321 @ViewDebug.ExportedProperty(category = "drawing") 9322 public float getX() { 9323 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 9324 } 9325 9326 /** 9327 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 9328 * {@link #setTranslationX(float) translationX} property to be the difference between 9329 * the x value passed in and the current {@link #getLeft() left} property. 9330 * 9331 * @param x The visual x position of this view, in pixels. 9332 */ 9333 public void setX(float x) { 9334 setTranslationX(x - mLeft); 9335 } 9336 9337 /** 9338 * The visual y position of this view, in pixels. This is equivalent to the 9339 * {@link #setTranslationY(float) translationY} property plus the current 9340 * {@link #getTop() top} property. 9341 * 9342 * @return The visual y position of this view, in pixels. 9343 */ 9344 @ViewDebug.ExportedProperty(category = "drawing") 9345 public float getY() { 9346 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 9347 } 9348 9349 /** 9350 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 9351 * {@link #setTranslationY(float) translationY} property to be the difference between 9352 * the y value passed in and the current {@link #getTop() top} property. 9353 * 9354 * @param y The visual y position of this view, in pixels. 9355 */ 9356 public void setY(float y) { 9357 setTranslationY(y - mTop); 9358 } 9359 9360 9361 /** 9362 * The horizontal location of this view relative to its {@link #getLeft() left} position. 9363 * This position is post-layout, in addition to wherever the object's 9364 * layout placed it. 9365 * 9366 * @return The horizontal position of this view relative to its left position, in pixels. 9367 */ 9368 @ViewDebug.ExportedProperty(category = "drawing") 9369 public float getTranslationX() { 9370 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 9371 } 9372 9373 /** 9374 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 9375 * This effectively positions the object post-layout, in addition to wherever the object's 9376 * layout placed it. 9377 * 9378 * @param translationX The horizontal position of this view relative to its left position, 9379 * in pixels. 9380 * 9381 * @attr ref android.R.styleable#View_translationX 9382 */ 9383 public void setTranslationX(float translationX) { 9384 ensureTransformationInfo(); 9385 final TransformationInfo info = mTransformationInfo; 9386 if (info.mTranslationX != translationX) { 9387 // Double-invalidation is necessary to capture view's old and new areas 9388 invalidateViewProperty(true, false); 9389 info.mTranslationX = translationX; 9390 info.mMatrixDirty = true; 9391 invalidateViewProperty(false, true); 9392 if (mDisplayList != null) { 9393 mDisplayList.setTranslationX(translationX); 9394 } 9395 if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) { 9396 // View was rejected last time it was drawn by its parent; this may have changed 9397 invalidateParentIfNeeded(); 9398 } 9399 } 9400 } 9401 9402 /** 9403 * The horizontal location of this view relative to its {@link #getTop() top} position. 9404 * This position is post-layout, in addition to wherever the object's 9405 * layout placed it. 9406 * 9407 * @return The vertical position of this view relative to its top position, 9408 * in pixels. 9409 */ 9410 @ViewDebug.ExportedProperty(category = "drawing") 9411 public float getTranslationY() { 9412 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 9413 } 9414 9415 /** 9416 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 9417 * This effectively positions the object post-layout, in addition to wherever the object's 9418 * layout placed it. 9419 * 9420 * @param translationY The vertical position of this view relative to its top position, 9421 * in pixels. 9422 * 9423 * @attr ref android.R.styleable#View_translationY 9424 */ 9425 public void setTranslationY(float translationY) { 9426 ensureTransformationInfo(); 9427 final TransformationInfo info = mTransformationInfo; 9428 if (info.mTranslationY != translationY) { 9429 invalidateViewProperty(true, false); 9430 info.mTranslationY = translationY; 9431 info.mMatrixDirty = true; 9432 invalidateViewProperty(false, true); 9433 if (mDisplayList != null) { 9434 mDisplayList.setTranslationY(translationY); 9435 } 9436 if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) { 9437 // View was rejected last time it was drawn by its parent; this may have changed 9438 invalidateParentIfNeeded(); 9439 } 9440 } 9441 } 9442 9443 /** 9444 * Hit rectangle in parent's coordinates 9445 * 9446 * @param outRect The hit rectangle of the view. 9447 */ 9448 public void getHitRect(Rect outRect) { 9449 updateMatrix(); 9450 final TransformationInfo info = mTransformationInfo; 9451 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 9452 outRect.set(mLeft, mTop, mRight, mBottom); 9453 } else { 9454 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 9455 tmpRect.set(-info.mPivotX, -info.mPivotY, 9456 getWidth() - info.mPivotX, getHeight() - info.mPivotY); 9457 info.mMatrix.mapRect(tmpRect); 9458 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 9459 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 9460 } 9461 } 9462 9463 /** 9464 * Determines whether the given point, in local coordinates is inside the view. 9465 */ 9466 /*package*/ final boolean pointInView(float localX, float localY) { 9467 return localX >= 0 && localX < (mRight - mLeft) 9468 && localY >= 0 && localY < (mBottom - mTop); 9469 } 9470 9471 /** 9472 * Utility method to determine whether the given point, in local coordinates, 9473 * is inside the view, where the area of the view is expanded by the slop factor. 9474 * This method is called while processing touch-move events to determine if the event 9475 * is still within the view. 9476 */ 9477 private boolean pointInView(float localX, float localY, float slop) { 9478 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 9479 localY < ((mBottom - mTop) + slop); 9480 } 9481 9482 /** 9483 * When a view has focus and the user navigates away from it, the next view is searched for 9484 * starting from the rectangle filled in by this method. 9485 * 9486 * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)}) 9487 * of the view. However, if your view maintains some idea of internal selection, 9488 * such as a cursor, or a selected row or column, you should override this method and 9489 * fill in a more specific rectangle. 9490 * 9491 * @param r The rectangle to fill in, in this view's coordinates. 9492 */ 9493 public void getFocusedRect(Rect r) { 9494 getDrawingRect(r); 9495 } 9496 9497 /** 9498 * If some part of this view is not clipped by any of its parents, then 9499 * return that area in r in global (root) coordinates. To convert r to local 9500 * coordinates (without taking possible View rotations into account), offset 9501 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 9502 * If the view is completely clipped or translated out, return false. 9503 * 9504 * @param r If true is returned, r holds the global coordinates of the 9505 * visible portion of this view. 9506 * @param globalOffset If true is returned, globalOffset holds the dx,dy 9507 * between this view and its root. globalOffet may be null. 9508 * @return true if r is non-empty (i.e. part of the view is visible at the 9509 * root level. 9510 */ 9511 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 9512 int width = mRight - mLeft; 9513 int height = mBottom - mTop; 9514 if (width > 0 && height > 0) { 9515 r.set(0, 0, width, height); 9516 if (globalOffset != null) { 9517 globalOffset.set(-mScrollX, -mScrollY); 9518 } 9519 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 9520 } 9521 return false; 9522 } 9523 9524 public final boolean getGlobalVisibleRect(Rect r) { 9525 return getGlobalVisibleRect(r, null); 9526 } 9527 9528 public final boolean getLocalVisibleRect(Rect r) { 9529 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 9530 if (getGlobalVisibleRect(r, offset)) { 9531 r.offset(-offset.x, -offset.y); // make r local 9532 return true; 9533 } 9534 return false; 9535 } 9536 9537 /** 9538 * Offset this view's vertical location by the specified number of pixels. 9539 * 9540 * @param offset the number of pixels to offset the view by 9541 */ 9542 public void offsetTopAndBottom(int offset) { 9543 if (offset != 0) { 9544 updateMatrix(); 9545 final boolean matrixIsIdentity = mTransformationInfo == null 9546 || mTransformationInfo.mMatrixIsIdentity; 9547 if (matrixIsIdentity) { 9548 if (mDisplayList != null) { 9549 invalidateViewProperty(false, false); 9550 } else { 9551 final ViewParent p = mParent; 9552 if (p != null && mAttachInfo != null) { 9553 final Rect r = mAttachInfo.mTmpInvalRect; 9554 int minTop; 9555 int maxBottom; 9556 int yLoc; 9557 if (offset < 0) { 9558 minTop = mTop + offset; 9559 maxBottom = mBottom; 9560 yLoc = offset; 9561 } else { 9562 minTop = mTop; 9563 maxBottom = mBottom + offset; 9564 yLoc = 0; 9565 } 9566 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 9567 p.invalidateChild(this, r); 9568 } 9569 } 9570 } else { 9571 invalidateViewProperty(false, false); 9572 } 9573 9574 mTop += offset; 9575 mBottom += offset; 9576 if (mDisplayList != null) { 9577 mDisplayList.offsetTopBottom(offset); 9578 invalidateViewProperty(false, false); 9579 } else { 9580 if (!matrixIsIdentity) { 9581 invalidateViewProperty(false, true); 9582 } 9583 invalidateParentIfNeeded(); 9584 } 9585 } 9586 } 9587 9588 /** 9589 * Offset this view's horizontal location by the specified amount of pixels. 9590 * 9591 * @param offset the numer of pixels to offset the view by 9592 */ 9593 public void offsetLeftAndRight(int offset) { 9594 if (offset != 0) { 9595 updateMatrix(); 9596 final boolean matrixIsIdentity = mTransformationInfo == null 9597 || mTransformationInfo.mMatrixIsIdentity; 9598 if (matrixIsIdentity) { 9599 if (mDisplayList != null) { 9600 invalidateViewProperty(false, false); 9601 } else { 9602 final ViewParent p = mParent; 9603 if (p != null && mAttachInfo != null) { 9604 final Rect r = mAttachInfo.mTmpInvalRect; 9605 int minLeft; 9606 int maxRight; 9607 if (offset < 0) { 9608 minLeft = mLeft + offset; 9609 maxRight = mRight; 9610 } else { 9611 minLeft = mLeft; 9612 maxRight = mRight + offset; 9613 } 9614 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 9615 p.invalidateChild(this, r); 9616 } 9617 } 9618 } else { 9619 invalidateViewProperty(false, false); 9620 } 9621 9622 mLeft += offset; 9623 mRight += offset; 9624 if (mDisplayList != null) { 9625 mDisplayList.offsetLeftRight(offset); 9626 invalidateViewProperty(false, false); 9627 } else { 9628 if (!matrixIsIdentity) { 9629 invalidateViewProperty(false, true); 9630 } 9631 invalidateParentIfNeeded(); 9632 } 9633 } 9634 } 9635 9636 /** 9637 * Get the LayoutParams associated with this view. All views should have 9638 * layout parameters. These supply parameters to the <i>parent</i> of this 9639 * view specifying how it should be arranged. There are many subclasses of 9640 * ViewGroup.LayoutParams, and these correspond to the different subclasses 9641 * of ViewGroup that are responsible for arranging their children. 9642 * 9643 * This method may return null if this View is not attached to a parent 9644 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 9645 * was not invoked successfully. When a View is attached to a parent 9646 * ViewGroup, this method must not return null. 9647 * 9648 * @return The LayoutParams associated with this view, or null if no 9649 * parameters have been set yet 9650 */ 9651 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 9652 public ViewGroup.LayoutParams getLayoutParams() { 9653 return mLayoutParams; 9654 } 9655 9656 /** 9657 * Set the layout parameters associated with this view. These supply 9658 * parameters to the <i>parent</i> of this view specifying how it should be 9659 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 9660 * correspond to the different subclasses of ViewGroup that are responsible 9661 * for arranging their children. 9662 * 9663 * @param params The layout parameters for this view, cannot be null 9664 */ 9665 public void setLayoutParams(ViewGroup.LayoutParams params) { 9666 if (params == null) { 9667 throw new NullPointerException("Layout parameters cannot be null"); 9668 } 9669 mLayoutParams = params; 9670 if (mParent instanceof ViewGroup) { 9671 ((ViewGroup) mParent).onSetLayoutParams(this, params); 9672 } 9673 requestLayout(); 9674 } 9675 9676 /** 9677 * Set the scrolled position of your view. This will cause a call to 9678 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9679 * invalidated. 9680 * @param x the x position to scroll to 9681 * @param y the y position to scroll to 9682 */ 9683 public void scrollTo(int x, int y) { 9684 if (mScrollX != x || mScrollY != y) { 9685 int oldX = mScrollX; 9686 int oldY = mScrollY; 9687 mScrollX = x; 9688 mScrollY = y; 9689 invalidateParentCaches(); 9690 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 9691 if (!awakenScrollBars()) { 9692 postInvalidateOnAnimation(); 9693 } 9694 } 9695 } 9696 9697 /** 9698 * Move the scrolled position of your view. This will cause a call to 9699 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9700 * invalidated. 9701 * @param x the amount of pixels to scroll by horizontally 9702 * @param y the amount of pixels to scroll by vertically 9703 */ 9704 public void scrollBy(int x, int y) { 9705 scrollTo(mScrollX + x, mScrollY + y); 9706 } 9707 9708 /** 9709 * <p>Trigger the scrollbars to draw. When invoked this method starts an 9710 * animation to fade the scrollbars out after a default delay. If a subclass 9711 * provides animated scrolling, the start delay should equal the duration 9712 * of the scrolling animation.</p> 9713 * 9714 * <p>The animation starts only if at least one of the scrollbars is 9715 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 9716 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 9717 * this method returns true, and false otherwise. If the animation is 9718 * started, this method calls {@link #invalidate()}; in that case the 9719 * caller should not call {@link #invalidate()}.</p> 9720 * 9721 * <p>This method should be invoked every time a subclass directly updates 9722 * the scroll parameters.</p> 9723 * 9724 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 9725 * and {@link #scrollTo(int, int)}.</p> 9726 * 9727 * @return true if the animation is played, false otherwise 9728 * 9729 * @see #awakenScrollBars(int) 9730 * @see #scrollBy(int, int) 9731 * @see #scrollTo(int, int) 9732 * @see #isHorizontalScrollBarEnabled() 9733 * @see #isVerticalScrollBarEnabled() 9734 * @see #setHorizontalScrollBarEnabled(boolean) 9735 * @see #setVerticalScrollBarEnabled(boolean) 9736 */ 9737 protected boolean awakenScrollBars() { 9738 return mScrollCache != null && 9739 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 9740 } 9741 9742 /** 9743 * Trigger the scrollbars to draw. 9744 * This method differs from awakenScrollBars() only in its default duration. 9745 * initialAwakenScrollBars() will show the scroll bars for longer than 9746 * usual to give the user more of a chance to notice them. 9747 * 9748 * @return true if the animation is played, false otherwise. 9749 */ 9750 private boolean initialAwakenScrollBars() { 9751 return mScrollCache != null && 9752 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 9753 } 9754 9755 /** 9756 * <p> 9757 * Trigger the scrollbars to draw. When invoked this method starts an 9758 * animation to fade the scrollbars out after a fixed delay. If a subclass 9759 * provides animated scrolling, the start delay should equal the duration of 9760 * the scrolling animation. 9761 * </p> 9762 * 9763 * <p> 9764 * The animation starts only if at least one of the scrollbars is enabled, 9765 * as specified by {@link #isHorizontalScrollBarEnabled()} and 9766 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 9767 * this method returns true, and false otherwise. If the animation is 9768 * started, this method calls {@link #invalidate()}; in that case the caller 9769 * should not call {@link #invalidate()}. 9770 * </p> 9771 * 9772 * <p> 9773 * This method should be invoked everytime a subclass directly updates the 9774 * scroll parameters. 9775 * </p> 9776 * 9777 * @param startDelay the delay, in milliseconds, after which the animation 9778 * should start; when the delay is 0, the animation starts 9779 * immediately 9780 * @return true if the animation is played, false otherwise 9781 * 9782 * @see #scrollBy(int, int) 9783 * @see #scrollTo(int, int) 9784 * @see #isHorizontalScrollBarEnabled() 9785 * @see #isVerticalScrollBarEnabled() 9786 * @see #setHorizontalScrollBarEnabled(boolean) 9787 * @see #setVerticalScrollBarEnabled(boolean) 9788 */ 9789 protected boolean awakenScrollBars(int startDelay) { 9790 return awakenScrollBars(startDelay, true); 9791 } 9792 9793 /** 9794 * <p> 9795 * Trigger the scrollbars to draw. When invoked this method starts an 9796 * animation to fade the scrollbars out after a fixed delay. If a subclass 9797 * provides animated scrolling, the start delay should equal the duration of 9798 * the scrolling animation. 9799 * </p> 9800 * 9801 * <p> 9802 * The animation starts only if at least one of the scrollbars is enabled, 9803 * as specified by {@link #isHorizontalScrollBarEnabled()} and 9804 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 9805 * this method returns true, and false otherwise. If the animation is 9806 * started, this method calls {@link #invalidate()} if the invalidate parameter 9807 * is set to true; in that case the caller 9808 * should not call {@link #invalidate()}. 9809 * </p> 9810 * 9811 * <p> 9812 * This method should be invoked everytime a subclass directly updates the 9813 * scroll parameters. 9814 * </p> 9815 * 9816 * @param startDelay the delay, in milliseconds, after which the animation 9817 * should start; when the delay is 0, the animation starts 9818 * immediately 9819 * 9820 * @param invalidate Wheter this method should call invalidate 9821 * 9822 * @return true if the animation is played, false otherwise 9823 * 9824 * @see #scrollBy(int, int) 9825 * @see #scrollTo(int, int) 9826 * @see #isHorizontalScrollBarEnabled() 9827 * @see #isVerticalScrollBarEnabled() 9828 * @see #setHorizontalScrollBarEnabled(boolean) 9829 * @see #setVerticalScrollBarEnabled(boolean) 9830 */ 9831 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 9832 final ScrollabilityCache scrollCache = mScrollCache; 9833 9834 if (scrollCache == null || !scrollCache.fadeScrollBars) { 9835 return false; 9836 } 9837 9838 if (scrollCache.scrollBar == null) { 9839 scrollCache.scrollBar = new ScrollBarDrawable(); 9840 } 9841 9842 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 9843 9844 if (invalidate) { 9845 // Invalidate to show the scrollbars 9846 postInvalidateOnAnimation(); 9847 } 9848 9849 if (scrollCache.state == ScrollabilityCache.OFF) { 9850 // FIXME: this is copied from WindowManagerService. 9851 // We should get this value from the system when it 9852 // is possible to do so. 9853 final int KEY_REPEAT_FIRST_DELAY = 750; 9854 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 9855 } 9856 9857 // Tell mScrollCache when we should start fading. This may 9858 // extend the fade start time if one was already scheduled 9859 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 9860 scrollCache.fadeStartTime = fadeStartTime; 9861 scrollCache.state = ScrollabilityCache.ON; 9862 9863 // Schedule our fader to run, unscheduling any old ones first 9864 if (mAttachInfo != null) { 9865 mAttachInfo.mHandler.removeCallbacks(scrollCache); 9866 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 9867 } 9868 9869 return true; 9870 } 9871 9872 return false; 9873 } 9874 9875 /** 9876 * Do not invalidate views which are not visible and which are not running an animation. They 9877 * will not get drawn and they should not set dirty flags as if they will be drawn 9878 */ 9879 private boolean skipInvalidate() { 9880 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 9881 (!(mParent instanceof ViewGroup) || 9882 !((ViewGroup) mParent).isViewTransitioning(this)); 9883 } 9884 /** 9885 * Mark the area defined by dirty as needing to be drawn. If the view is 9886 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 9887 * in the future. This must be called from a UI thread. To call from a non-UI 9888 * thread, call {@link #postInvalidate()}. 9889 * 9890 * WARNING: This method is destructive to dirty. 9891 * @param dirty the rectangle representing the bounds of the dirty region 9892 */ 9893 public void invalidate(Rect dirty) { 9894 if (ViewDebug.TRACE_HIERARCHY) { 9895 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 9896 } 9897 9898 if (skipInvalidate()) { 9899 return; 9900 } 9901 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 9902 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 9903 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 9904 mPrivateFlags &= ~DRAWING_CACHE_VALID; 9905 mPrivateFlags |= INVALIDATED; 9906 mPrivateFlags |= DIRTY; 9907 final ViewParent p = mParent; 9908 final AttachInfo ai = mAttachInfo; 9909 //noinspection PointlessBooleanExpression,ConstantConditions 9910 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 9911 if (p != null && ai != null && ai.mHardwareAccelerated) { 9912 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 9913 // with a null dirty rect, which tells the ViewAncestor to redraw everything 9914 p.invalidateChild(this, null); 9915 return; 9916 } 9917 } 9918 if (p != null && ai != null) { 9919 final int scrollX = mScrollX; 9920 final int scrollY = mScrollY; 9921 final Rect r = ai.mTmpInvalRect; 9922 r.set(dirty.left - scrollX, dirty.top - scrollY, 9923 dirty.right - scrollX, dirty.bottom - scrollY); 9924 mParent.invalidateChild(this, r); 9925 } 9926 } 9927 } 9928 9929 /** 9930 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 9931 * The coordinates of the dirty rect are relative to the view. 9932 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 9933 * will be called at some point in the future. This must be called from 9934 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 9935 * @param l the left position of the dirty region 9936 * @param t the top position of the dirty region 9937 * @param r the right position of the dirty region 9938 * @param b the bottom position of the dirty region 9939 */ 9940 public void invalidate(int l, int t, int r, int b) { 9941 if (ViewDebug.TRACE_HIERARCHY) { 9942 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 9943 } 9944 9945 if (skipInvalidate()) { 9946 return; 9947 } 9948 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 9949 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 9950 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 9951 mPrivateFlags &= ~DRAWING_CACHE_VALID; 9952 mPrivateFlags |= INVALIDATED; 9953 mPrivateFlags |= DIRTY; 9954 final ViewParent p = mParent; 9955 final AttachInfo ai = mAttachInfo; 9956 //noinspection PointlessBooleanExpression,ConstantConditions 9957 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 9958 if (p != null && ai != null && ai.mHardwareAccelerated) { 9959 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 9960 // with a null dirty rect, which tells the ViewAncestor to redraw everything 9961 p.invalidateChild(this, null); 9962 return; 9963 } 9964 } 9965 if (p != null && ai != null && l < r && t < b) { 9966 final int scrollX = mScrollX; 9967 final int scrollY = mScrollY; 9968 final Rect tmpr = ai.mTmpInvalRect; 9969 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 9970 p.invalidateChild(this, tmpr); 9971 } 9972 } 9973 } 9974 9975 /** 9976 * Invalidate the whole view. If the view is visible, 9977 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 9978 * the future. This must be called from a UI thread. To call from a non-UI thread, 9979 * call {@link #postInvalidate()}. 9980 */ 9981 public void invalidate() { 9982 invalidate(true); 9983 } 9984 9985 /** 9986 * This is where the invalidate() work actually happens. A full invalidate() 9987 * causes the drawing cache to be invalidated, but this function can be called with 9988 * invalidateCache set to false to skip that invalidation step for cases that do not 9989 * need it (for example, a component that remains at the same dimensions with the same 9990 * content). 9991 * 9992 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 9993 * well. This is usually true for a full invalidate, but may be set to false if the 9994 * View's contents or dimensions have not changed. 9995 */ 9996 void invalidate(boolean invalidateCache) { 9997 if (ViewDebug.TRACE_HIERARCHY) { 9998 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 9999 } 10000 10001 if (skipInvalidate()) { 10002 return; 10003 } 10004 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 10005 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) || 10006 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) { 10007 mLastIsOpaque = isOpaque(); 10008 mPrivateFlags &= ~DRAWN; 10009 mPrivateFlags |= DIRTY; 10010 if (invalidateCache) { 10011 mPrivateFlags |= INVALIDATED; 10012 mPrivateFlags &= ~DRAWING_CACHE_VALID; 10013 } 10014 final AttachInfo ai = mAttachInfo; 10015 final ViewParent p = mParent; 10016 //noinspection PointlessBooleanExpression,ConstantConditions 10017 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10018 if (p != null && ai != null && ai.mHardwareAccelerated) { 10019 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10020 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10021 p.invalidateChild(this, null); 10022 return; 10023 } 10024 } 10025 10026 if (p != null && ai != null) { 10027 final Rect r = ai.mTmpInvalRect; 10028 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10029 // Don't call invalidate -- we don't want to internally scroll 10030 // our own bounds 10031 p.invalidateChild(this, r); 10032 } 10033 } 10034 } 10035 10036 /** 10037 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 10038 * set any flags or handle all of the cases handled by the default invalidation methods. 10039 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 10040 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 10041 * walk up the hierarchy, transforming the dirty rect as necessary. 10042 * 10043 * The method also handles normal invalidation logic if display list properties are not 10044 * being used in this view. The invalidateParent and forceRedraw flags are used by that 10045 * backup approach, to handle these cases used in the various property-setting methods. 10046 * 10047 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 10048 * are not being used in this view 10049 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 10050 * list properties are not being used in this view 10051 */ 10052 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 10053 if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) { 10054 if (invalidateParent) { 10055 invalidateParentCaches(); 10056 } 10057 if (forceRedraw) { 10058 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 10059 } 10060 invalidate(false); 10061 } else { 10062 final AttachInfo ai = mAttachInfo; 10063 final ViewParent p = mParent; 10064 if (p != null && ai != null) { 10065 final Rect r = ai.mTmpInvalRect; 10066 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10067 if (mParent instanceof ViewGroup) { 10068 ((ViewGroup) mParent).invalidateChildFast(this, r); 10069 } else { 10070 mParent.invalidateChild(this, r); 10071 } 10072 } 10073 } 10074 } 10075 10076 /** 10077 * Utility method to transform a given Rect by the current matrix of this view. 10078 */ 10079 void transformRect(final Rect rect) { 10080 if (!getMatrix().isIdentity()) { 10081 RectF boundingRect = mAttachInfo.mTmpTransformRect; 10082 boundingRect.set(rect); 10083 getMatrix().mapRect(boundingRect); 10084 rect.set((int) (boundingRect.left - 0.5f), 10085 (int) (boundingRect.top - 0.5f), 10086 (int) (boundingRect.right + 0.5f), 10087 (int) (boundingRect.bottom + 0.5f)); 10088 } 10089 } 10090 10091 /** 10092 * Used to indicate that the parent of this view should clear its caches. This functionality 10093 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10094 * which is necessary when various parent-managed properties of the view change, such as 10095 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 10096 * clears the parent caches and does not causes an invalidate event. 10097 * 10098 * @hide 10099 */ 10100 protected void invalidateParentCaches() { 10101 if (mParent instanceof View) { 10102 ((View) mParent).mPrivateFlags |= INVALIDATED; 10103 } 10104 } 10105 10106 /** 10107 * Used to indicate that the parent of this view should be invalidated. This functionality 10108 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10109 * which is necessary when various parent-managed properties of the view change, such as 10110 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 10111 * an invalidation event to the parent. 10112 * 10113 * @hide 10114 */ 10115 protected void invalidateParentIfNeeded() { 10116 if (isHardwareAccelerated() && mParent instanceof View) { 10117 ((View) mParent).invalidate(true); 10118 } 10119 } 10120 10121 /** 10122 * Indicates whether this View is opaque. An opaque View guarantees that it will 10123 * draw all the pixels overlapping its bounds using a fully opaque color. 10124 * 10125 * Subclasses of View should override this method whenever possible to indicate 10126 * whether an instance is opaque. Opaque Views are treated in a special way by 10127 * the View hierarchy, possibly allowing it to perform optimizations during 10128 * invalidate/draw passes. 10129 * 10130 * @return True if this View is guaranteed to be fully opaque, false otherwise. 10131 */ 10132 @ViewDebug.ExportedProperty(category = "drawing") 10133 public boolean isOpaque() { 10134 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK && 10135 ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1) 10136 >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD); 10137 } 10138 10139 /** 10140 * @hide 10141 */ 10142 protected void computeOpaqueFlags() { 10143 // Opaque if: 10144 // - Has a background 10145 // - Background is opaque 10146 // - Doesn't have scrollbars or scrollbars are inside overlay 10147 10148 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 10149 mPrivateFlags |= OPAQUE_BACKGROUND; 10150 } else { 10151 mPrivateFlags &= ~OPAQUE_BACKGROUND; 10152 } 10153 10154 final int flags = mViewFlags; 10155 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 10156 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 10157 mPrivateFlags |= OPAQUE_SCROLLBARS; 10158 } else { 10159 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 10160 } 10161 } 10162 10163 /** 10164 * @hide 10165 */ 10166 protected boolean hasOpaqueScrollbars() { 10167 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 10168 } 10169 10170 /** 10171 * @return A handler associated with the thread running the View. This 10172 * handler can be used to pump events in the UI events queue. 10173 */ 10174 public Handler getHandler() { 10175 if (mAttachInfo != null) { 10176 return mAttachInfo.mHandler; 10177 } 10178 return null; 10179 } 10180 10181 /** 10182 * Gets the view root associated with the View. 10183 * @return The view root, or null if none. 10184 * @hide 10185 */ 10186 public ViewRootImpl getViewRootImpl() { 10187 if (mAttachInfo != null) { 10188 return mAttachInfo.mViewRootImpl; 10189 } 10190 return null; 10191 } 10192 10193 /** 10194 * <p>Causes the Runnable to be added to the message queue. 10195 * The runnable will be run on the user interface thread.</p> 10196 * 10197 * <p>This method can be invoked from outside of the UI thread 10198 * only when this View is attached to a window.</p> 10199 * 10200 * @param action The Runnable that will be executed. 10201 * 10202 * @return Returns true if the Runnable was successfully placed in to the 10203 * message queue. Returns false on failure, usually because the 10204 * looper processing the message queue is exiting. 10205 * 10206 * @see #postDelayed 10207 * @see #removeCallbacks 10208 */ 10209 public boolean post(Runnable action) { 10210 final AttachInfo attachInfo = mAttachInfo; 10211 if (attachInfo != null) { 10212 return attachInfo.mHandler.post(action); 10213 } 10214 // Assume that post will succeed later 10215 ViewRootImpl.getRunQueue().post(action); 10216 return true; 10217 } 10218 10219 /** 10220 * <p>Causes the Runnable to be added to the message queue, to be run 10221 * after the specified amount of time elapses. 10222 * The runnable will be run on the user interface thread.</p> 10223 * 10224 * <p>This method can be invoked from outside of the UI thread 10225 * only when this View is attached to a window.</p> 10226 * 10227 * @param action The Runnable that will be executed. 10228 * @param delayMillis The delay (in milliseconds) until the Runnable 10229 * will be executed. 10230 * 10231 * @return true if the Runnable was successfully placed in to the 10232 * message queue. Returns false on failure, usually because the 10233 * looper processing the message queue is exiting. Note that a 10234 * result of true does not mean the Runnable will be processed -- 10235 * if the looper is quit before the delivery time of the message 10236 * occurs then the message will be dropped. 10237 * 10238 * @see #post 10239 * @see #removeCallbacks 10240 */ 10241 public boolean postDelayed(Runnable action, long delayMillis) { 10242 final AttachInfo attachInfo = mAttachInfo; 10243 if (attachInfo != null) { 10244 return attachInfo.mHandler.postDelayed(action, delayMillis); 10245 } 10246 // Assume that post will succeed later 10247 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 10248 return true; 10249 } 10250 10251 /** 10252 * <p>Causes the Runnable to execute on the next animation time step. 10253 * The runnable will be run on the user interface thread.</p> 10254 * 10255 * <p>This method can be invoked from outside of the UI thread 10256 * only when this View is attached to a window.</p> 10257 * 10258 * @param action The Runnable that will be executed. 10259 * 10260 * @see #postOnAnimationDelayed 10261 * @see #removeCallbacks 10262 */ 10263 public void postOnAnimation(Runnable action) { 10264 final AttachInfo attachInfo = mAttachInfo; 10265 if (attachInfo != null) { 10266 attachInfo.mViewRootImpl.mChoreographer.postCallback( 10267 Choreographer.CALLBACK_ANIMATION, action, null); 10268 } else { 10269 // Assume that post will succeed later 10270 ViewRootImpl.getRunQueue().post(action); 10271 } 10272 } 10273 10274 /** 10275 * <p>Causes the Runnable to execute on the next animation time step, 10276 * after the specified amount of time elapses. 10277 * The runnable will be run on the user interface thread.</p> 10278 * 10279 * <p>This method can be invoked from outside of the UI thread 10280 * only when this View is attached to a window.</p> 10281 * 10282 * @param action The Runnable that will be executed. 10283 * @param delayMillis The delay (in milliseconds) until the Runnable 10284 * will be executed. 10285 * 10286 * @see #postOnAnimation 10287 * @see #removeCallbacks 10288 */ 10289 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 10290 final AttachInfo attachInfo = mAttachInfo; 10291 if (attachInfo != null) { 10292 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 10293 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 10294 } else { 10295 // Assume that post will succeed later 10296 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 10297 } 10298 } 10299 10300 /** 10301 * <p>Removes the specified Runnable from the message queue.</p> 10302 * 10303 * <p>This method can be invoked from outside of the UI thread 10304 * only when this View is attached to a window.</p> 10305 * 10306 * @param action The Runnable to remove from the message handling queue 10307 * 10308 * @return true if this view could ask the Handler to remove the Runnable, 10309 * false otherwise. When the returned value is true, the Runnable 10310 * may or may not have been actually removed from the message queue 10311 * (for instance, if the Runnable was not in the queue already.) 10312 * 10313 * @see #post 10314 * @see #postDelayed 10315 * @see #postOnAnimation 10316 * @see #postOnAnimationDelayed 10317 */ 10318 public boolean removeCallbacks(Runnable action) { 10319 if (action != null) { 10320 final AttachInfo attachInfo = mAttachInfo; 10321 if (attachInfo != null) { 10322 attachInfo.mHandler.removeCallbacks(action); 10323 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 10324 Choreographer.CALLBACK_ANIMATION, action, null); 10325 } else { 10326 // Assume that post will succeed later 10327 ViewRootImpl.getRunQueue().removeCallbacks(action); 10328 } 10329 } 10330 return true; 10331 } 10332 10333 /** 10334 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 10335 * Use this to invalidate the View from a non-UI thread.</p> 10336 * 10337 * <p>This method can be invoked from outside of the UI thread 10338 * only when this View is attached to a window.</p> 10339 * 10340 * @see #invalidate() 10341 * @see #postInvalidateDelayed(long) 10342 */ 10343 public void postInvalidate() { 10344 postInvalidateDelayed(0); 10345 } 10346 10347 /** 10348 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 10349 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 10350 * 10351 * <p>This method can be invoked from outside of the UI thread 10352 * only when this View is attached to a window.</p> 10353 * 10354 * @param left The left coordinate of the rectangle to invalidate. 10355 * @param top The top coordinate of the rectangle to invalidate. 10356 * @param right The right coordinate of the rectangle to invalidate. 10357 * @param bottom The bottom coordinate of the rectangle to invalidate. 10358 * 10359 * @see #invalidate(int, int, int, int) 10360 * @see #invalidate(Rect) 10361 * @see #postInvalidateDelayed(long, int, int, int, int) 10362 */ 10363 public void postInvalidate(int left, int top, int right, int bottom) { 10364 postInvalidateDelayed(0, left, top, right, bottom); 10365 } 10366 10367 /** 10368 * <p>Cause an invalidate to happen on a subsequent cycle through the event 10369 * loop. Waits for the specified amount of time.</p> 10370 * 10371 * <p>This method can be invoked from outside of the UI thread 10372 * only when this View is attached to a window.</p> 10373 * 10374 * @param delayMilliseconds the duration in milliseconds to delay the 10375 * invalidation by 10376 * 10377 * @see #invalidate() 10378 * @see #postInvalidate() 10379 */ 10380 public void postInvalidateDelayed(long delayMilliseconds) { 10381 // We try only with the AttachInfo because there's no point in invalidating 10382 // if we are not attached to our window 10383 final AttachInfo attachInfo = mAttachInfo; 10384 if (attachInfo != null) { 10385 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 10386 } 10387 } 10388 10389 /** 10390 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 10391 * through the event loop. Waits for the specified amount of time.</p> 10392 * 10393 * <p>This method can be invoked from outside of the UI thread 10394 * only when this View is attached to a window.</p> 10395 * 10396 * @param delayMilliseconds the duration in milliseconds to delay the 10397 * invalidation by 10398 * @param left The left coordinate of the rectangle to invalidate. 10399 * @param top The top coordinate of the rectangle to invalidate. 10400 * @param right The right coordinate of the rectangle to invalidate. 10401 * @param bottom The bottom coordinate of the rectangle to invalidate. 10402 * 10403 * @see #invalidate(int, int, int, int) 10404 * @see #invalidate(Rect) 10405 * @see #postInvalidate(int, int, int, int) 10406 */ 10407 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 10408 int right, int bottom) { 10409 10410 // We try only with the AttachInfo because there's no point in invalidating 10411 // if we are not attached to our window 10412 final AttachInfo attachInfo = mAttachInfo; 10413 if (attachInfo != null) { 10414 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 10415 info.target = this; 10416 info.left = left; 10417 info.top = top; 10418 info.right = right; 10419 info.bottom = bottom; 10420 10421 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 10422 } 10423 } 10424 10425 /** 10426 * <p>Cause an invalidate to happen on the next animation time step, typically the 10427 * next display frame.</p> 10428 * 10429 * <p>This method can be invoked from outside of the UI thread 10430 * only when this View is attached to a window.</p> 10431 * 10432 * @see #invalidate() 10433 */ 10434 public void postInvalidateOnAnimation() { 10435 // We try only with the AttachInfo because there's no point in invalidating 10436 // if we are not attached to our window 10437 final AttachInfo attachInfo = mAttachInfo; 10438 if (attachInfo != null) { 10439 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 10440 } 10441 } 10442 10443 /** 10444 * <p>Cause an invalidate of the specified area to happen on the next animation 10445 * time step, typically the next display frame.</p> 10446 * 10447 * <p>This method can be invoked from outside of the UI thread 10448 * only when this View is attached to a window.</p> 10449 * 10450 * @param left The left coordinate of the rectangle to invalidate. 10451 * @param top The top coordinate of the rectangle to invalidate. 10452 * @param right The right coordinate of the rectangle to invalidate. 10453 * @param bottom The bottom coordinate of the rectangle to invalidate. 10454 * 10455 * @see #invalidate(int, int, int, int) 10456 * @see #invalidate(Rect) 10457 */ 10458 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 10459 // We try only with the AttachInfo because there's no point in invalidating 10460 // if we are not attached to our window 10461 final AttachInfo attachInfo = mAttachInfo; 10462 if (attachInfo != null) { 10463 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 10464 info.target = this; 10465 info.left = left; 10466 info.top = top; 10467 info.right = right; 10468 info.bottom = bottom; 10469 10470 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 10471 } 10472 } 10473 10474 /** 10475 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 10476 * This event is sent at most once every 10477 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 10478 */ 10479 private void postSendViewScrolledAccessibilityEventCallback() { 10480 if (mSendViewScrolledAccessibilityEvent == null) { 10481 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 10482 } 10483 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 10484 mSendViewScrolledAccessibilityEvent.mIsPending = true; 10485 postDelayed(mSendViewScrolledAccessibilityEvent, 10486 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 10487 } 10488 } 10489 10490 /** 10491 * Called by a parent to request that a child update its values for mScrollX 10492 * and mScrollY if necessary. This will typically be done if the child is 10493 * animating a scroll using a {@link android.widget.Scroller Scroller} 10494 * object. 10495 */ 10496 public void computeScroll() { 10497 } 10498 10499 /** 10500 * <p>Indicate whether the horizontal edges are faded when the view is 10501 * scrolled horizontally.</p> 10502 * 10503 * @return true if the horizontal edges should are faded on scroll, false 10504 * otherwise 10505 * 10506 * @see #setHorizontalFadingEdgeEnabled(boolean) 10507 * 10508 * @attr ref android.R.styleable#View_requiresFadingEdge 10509 */ 10510 public boolean isHorizontalFadingEdgeEnabled() { 10511 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 10512 } 10513 10514 /** 10515 * <p>Define whether the horizontal edges should be faded when this view 10516 * is scrolled horizontally.</p> 10517 * 10518 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 10519 * be faded when the view is scrolled 10520 * horizontally 10521 * 10522 * @see #isHorizontalFadingEdgeEnabled() 10523 * 10524 * @attr ref android.R.styleable#View_requiresFadingEdge 10525 */ 10526 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 10527 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 10528 if (horizontalFadingEdgeEnabled) { 10529 initScrollCache(); 10530 } 10531 10532 mViewFlags ^= FADING_EDGE_HORIZONTAL; 10533 } 10534 } 10535 10536 /** 10537 * <p>Indicate whether the vertical edges are faded when the view is 10538 * scrolled horizontally.</p> 10539 * 10540 * @return true if the vertical edges should are faded on scroll, false 10541 * otherwise 10542 * 10543 * @see #setVerticalFadingEdgeEnabled(boolean) 10544 * 10545 * @attr ref android.R.styleable#View_requiresFadingEdge 10546 */ 10547 public boolean isVerticalFadingEdgeEnabled() { 10548 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 10549 } 10550 10551 /** 10552 * <p>Define whether the vertical edges should be faded when this view 10553 * is scrolled vertically.</p> 10554 * 10555 * @param verticalFadingEdgeEnabled true if the vertical edges should 10556 * be faded when the view is scrolled 10557 * vertically 10558 * 10559 * @see #isVerticalFadingEdgeEnabled() 10560 * 10561 * @attr ref android.R.styleable#View_requiresFadingEdge 10562 */ 10563 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 10564 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 10565 if (verticalFadingEdgeEnabled) { 10566 initScrollCache(); 10567 } 10568 10569 mViewFlags ^= FADING_EDGE_VERTICAL; 10570 } 10571 } 10572 10573 /** 10574 * Returns the strength, or intensity, of the top faded edge. The strength is 10575 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10576 * returns 0.0 or 1.0 but no value in between. 10577 * 10578 * Subclasses should override this method to provide a smoother fade transition 10579 * when scrolling occurs. 10580 * 10581 * @return the intensity of the top fade as a float between 0.0f and 1.0f 10582 */ 10583 protected float getTopFadingEdgeStrength() { 10584 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 10585 } 10586 10587 /** 10588 * Returns the strength, or intensity, of the bottom faded edge. The strength is 10589 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10590 * returns 0.0 or 1.0 but no value in between. 10591 * 10592 * Subclasses should override this method to provide a smoother fade transition 10593 * when scrolling occurs. 10594 * 10595 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 10596 */ 10597 protected float getBottomFadingEdgeStrength() { 10598 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 10599 computeVerticalScrollRange() ? 1.0f : 0.0f; 10600 } 10601 10602 /** 10603 * Returns the strength, or intensity, of the left faded edge. The strength is 10604 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10605 * returns 0.0 or 1.0 but no value in between. 10606 * 10607 * Subclasses should override this method to provide a smoother fade transition 10608 * when scrolling occurs. 10609 * 10610 * @return the intensity of the left fade as a float between 0.0f and 1.0f 10611 */ 10612 protected float getLeftFadingEdgeStrength() { 10613 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 10614 } 10615 10616 /** 10617 * Returns the strength, or intensity, of the right faded edge. The strength is 10618 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10619 * returns 0.0 or 1.0 but no value in between. 10620 * 10621 * Subclasses should override this method to provide a smoother fade transition 10622 * when scrolling occurs. 10623 * 10624 * @return the intensity of the right fade as a float between 0.0f and 1.0f 10625 */ 10626 protected float getRightFadingEdgeStrength() { 10627 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 10628 computeHorizontalScrollRange() ? 1.0f : 0.0f; 10629 } 10630 10631 /** 10632 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 10633 * scrollbar is not drawn by default.</p> 10634 * 10635 * @return true if the horizontal scrollbar should be painted, false 10636 * otherwise 10637 * 10638 * @see #setHorizontalScrollBarEnabled(boolean) 10639 */ 10640 public boolean isHorizontalScrollBarEnabled() { 10641 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 10642 } 10643 10644 /** 10645 * <p>Define whether the horizontal scrollbar should be drawn or not. The 10646 * scrollbar is not drawn by default.</p> 10647 * 10648 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 10649 * be painted 10650 * 10651 * @see #isHorizontalScrollBarEnabled() 10652 */ 10653 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 10654 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 10655 mViewFlags ^= SCROLLBARS_HORIZONTAL; 10656 computeOpaqueFlags(); 10657 resolvePadding(); 10658 } 10659 } 10660 10661 /** 10662 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 10663 * scrollbar is not drawn by default.</p> 10664 * 10665 * @return true if the vertical scrollbar should be painted, false 10666 * otherwise 10667 * 10668 * @see #setVerticalScrollBarEnabled(boolean) 10669 */ 10670 public boolean isVerticalScrollBarEnabled() { 10671 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 10672 } 10673 10674 /** 10675 * <p>Define whether the vertical scrollbar should be drawn or not. The 10676 * scrollbar is not drawn by default.</p> 10677 * 10678 * @param verticalScrollBarEnabled true if the vertical scrollbar should 10679 * be painted 10680 * 10681 * @see #isVerticalScrollBarEnabled() 10682 */ 10683 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 10684 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 10685 mViewFlags ^= SCROLLBARS_VERTICAL; 10686 computeOpaqueFlags(); 10687 resolvePadding(); 10688 } 10689 } 10690 10691 /** 10692 * @hide 10693 */ 10694 protected void recomputePadding() { 10695 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 10696 } 10697 10698 /** 10699 * Define whether scrollbars will fade when the view is not scrolling. 10700 * 10701 * @param fadeScrollbars wheter to enable fading 10702 * 10703 * @attr ref android.R.styleable#View_fadeScrollbars 10704 */ 10705 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 10706 initScrollCache(); 10707 final ScrollabilityCache scrollabilityCache = mScrollCache; 10708 scrollabilityCache.fadeScrollBars = fadeScrollbars; 10709 if (fadeScrollbars) { 10710 scrollabilityCache.state = ScrollabilityCache.OFF; 10711 } else { 10712 scrollabilityCache.state = ScrollabilityCache.ON; 10713 } 10714 } 10715 10716 /** 10717 * 10718 * Returns true if scrollbars will fade when this view is not scrolling 10719 * 10720 * @return true if scrollbar fading is enabled 10721 * 10722 * @attr ref android.R.styleable#View_fadeScrollbars 10723 */ 10724 public boolean isScrollbarFadingEnabled() { 10725 return mScrollCache != null && mScrollCache.fadeScrollBars; 10726 } 10727 10728 /** 10729 * 10730 * Returns the delay before scrollbars fade. 10731 * 10732 * @return the delay before scrollbars fade 10733 * 10734 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 10735 */ 10736 public int getScrollBarDefaultDelayBeforeFade() { 10737 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 10738 mScrollCache.scrollBarDefaultDelayBeforeFade; 10739 } 10740 10741 /** 10742 * Define the delay before scrollbars fade. 10743 * 10744 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 10745 * 10746 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 10747 */ 10748 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 10749 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 10750 } 10751 10752 /** 10753 * 10754 * Returns the scrollbar fade duration. 10755 * 10756 * @return the scrollbar fade duration 10757 * 10758 * @attr ref android.R.styleable#View_scrollbarFadeDuration 10759 */ 10760 public int getScrollBarFadeDuration() { 10761 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 10762 mScrollCache.scrollBarFadeDuration; 10763 } 10764 10765 /** 10766 * Define the scrollbar fade duration. 10767 * 10768 * @param scrollBarFadeDuration - the scrollbar fade duration 10769 * 10770 * @attr ref android.R.styleable#View_scrollbarFadeDuration 10771 */ 10772 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 10773 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 10774 } 10775 10776 /** 10777 * 10778 * Returns the scrollbar size. 10779 * 10780 * @return the scrollbar size 10781 * 10782 * @attr ref android.R.styleable#View_scrollbarSize 10783 */ 10784 public int getScrollBarSize() { 10785 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 10786 mScrollCache.scrollBarSize; 10787 } 10788 10789 /** 10790 * Define the scrollbar size. 10791 * 10792 * @param scrollBarSize - the scrollbar size 10793 * 10794 * @attr ref android.R.styleable#View_scrollbarSize 10795 */ 10796 public void setScrollBarSize(int scrollBarSize) { 10797 getScrollCache().scrollBarSize = scrollBarSize; 10798 } 10799 10800 /** 10801 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 10802 * inset. When inset, they add to the padding of the view. And the scrollbars 10803 * can be drawn inside the padding area or on the edge of the view. For example, 10804 * if a view has a background drawable and you want to draw the scrollbars 10805 * inside the padding specified by the drawable, you can use 10806 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 10807 * appear at the edge of the view, ignoring the padding, then you can use 10808 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 10809 * @param style the style of the scrollbars. Should be one of 10810 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 10811 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 10812 * @see #SCROLLBARS_INSIDE_OVERLAY 10813 * @see #SCROLLBARS_INSIDE_INSET 10814 * @see #SCROLLBARS_OUTSIDE_OVERLAY 10815 * @see #SCROLLBARS_OUTSIDE_INSET 10816 * 10817 * @attr ref android.R.styleable#View_scrollbarStyle 10818 */ 10819 public void setScrollBarStyle(int style) { 10820 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 10821 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 10822 computeOpaqueFlags(); 10823 resolvePadding(); 10824 } 10825 } 10826 10827 /** 10828 * <p>Returns the current scrollbar style.</p> 10829 * @return the current scrollbar style 10830 * @see #SCROLLBARS_INSIDE_OVERLAY 10831 * @see #SCROLLBARS_INSIDE_INSET 10832 * @see #SCROLLBARS_OUTSIDE_OVERLAY 10833 * @see #SCROLLBARS_OUTSIDE_INSET 10834 * 10835 * @attr ref android.R.styleable#View_scrollbarStyle 10836 */ 10837 @ViewDebug.ExportedProperty(mapping = { 10838 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 10839 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 10840 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 10841 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 10842 }) 10843 public int getScrollBarStyle() { 10844 return mViewFlags & SCROLLBARS_STYLE_MASK; 10845 } 10846 10847 /** 10848 * <p>Compute the horizontal range that the horizontal scrollbar 10849 * represents.</p> 10850 * 10851 * <p>The range is expressed in arbitrary units that must be the same as the 10852 * units used by {@link #computeHorizontalScrollExtent()} and 10853 * {@link #computeHorizontalScrollOffset()}.</p> 10854 * 10855 * <p>The default range is the drawing width of this view.</p> 10856 * 10857 * @return the total horizontal range represented by the horizontal 10858 * scrollbar 10859 * 10860 * @see #computeHorizontalScrollExtent() 10861 * @see #computeHorizontalScrollOffset() 10862 * @see android.widget.ScrollBarDrawable 10863 */ 10864 protected int computeHorizontalScrollRange() { 10865 return getWidth(); 10866 } 10867 10868 /** 10869 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 10870 * within the horizontal range. This value is used to compute the position 10871 * of the thumb within the scrollbar's track.</p> 10872 * 10873 * <p>The range is expressed in arbitrary units that must be the same as the 10874 * units used by {@link #computeHorizontalScrollRange()} and 10875 * {@link #computeHorizontalScrollExtent()}.</p> 10876 * 10877 * <p>The default offset is the scroll offset of this view.</p> 10878 * 10879 * @return the horizontal offset of the scrollbar's thumb 10880 * 10881 * @see #computeHorizontalScrollRange() 10882 * @see #computeHorizontalScrollExtent() 10883 * @see android.widget.ScrollBarDrawable 10884 */ 10885 protected int computeHorizontalScrollOffset() { 10886 return mScrollX; 10887 } 10888 10889 /** 10890 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 10891 * within the horizontal range. This value is used to compute the length 10892 * of the thumb within the scrollbar's track.</p> 10893 * 10894 * <p>The range is expressed in arbitrary units that must be the same as the 10895 * units used by {@link #computeHorizontalScrollRange()} and 10896 * {@link #computeHorizontalScrollOffset()}.</p> 10897 * 10898 * <p>The default extent is the drawing width of this view.</p> 10899 * 10900 * @return the horizontal extent of the scrollbar's thumb 10901 * 10902 * @see #computeHorizontalScrollRange() 10903 * @see #computeHorizontalScrollOffset() 10904 * @see android.widget.ScrollBarDrawable 10905 */ 10906 protected int computeHorizontalScrollExtent() { 10907 return getWidth(); 10908 } 10909 10910 /** 10911 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 10912 * 10913 * <p>The range is expressed in arbitrary units that must be the same as the 10914 * units used by {@link #computeVerticalScrollExtent()} and 10915 * {@link #computeVerticalScrollOffset()}.</p> 10916 * 10917 * @return the total vertical range represented by the vertical scrollbar 10918 * 10919 * <p>The default range is the drawing height of this view.</p> 10920 * 10921 * @see #computeVerticalScrollExtent() 10922 * @see #computeVerticalScrollOffset() 10923 * @see android.widget.ScrollBarDrawable 10924 */ 10925 protected int computeVerticalScrollRange() { 10926 return getHeight(); 10927 } 10928 10929 /** 10930 * <p>Compute the vertical offset of the vertical scrollbar's thumb 10931 * within the horizontal range. This value is used to compute the position 10932 * of the thumb within the scrollbar's track.</p> 10933 * 10934 * <p>The range is expressed in arbitrary units that must be the same as the 10935 * units used by {@link #computeVerticalScrollRange()} and 10936 * {@link #computeVerticalScrollExtent()}.</p> 10937 * 10938 * <p>The default offset is the scroll offset of this view.</p> 10939 * 10940 * @return the vertical offset of the scrollbar's thumb 10941 * 10942 * @see #computeVerticalScrollRange() 10943 * @see #computeVerticalScrollExtent() 10944 * @see android.widget.ScrollBarDrawable 10945 */ 10946 protected int computeVerticalScrollOffset() { 10947 return mScrollY; 10948 } 10949 10950 /** 10951 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 10952 * within the vertical range. This value is used to compute the length 10953 * of the thumb within the scrollbar's track.</p> 10954 * 10955 * <p>The range is expressed in arbitrary units that must be the same as the 10956 * units used by {@link #computeVerticalScrollRange()} and 10957 * {@link #computeVerticalScrollOffset()}.</p> 10958 * 10959 * <p>The default extent is the drawing height of this view.</p> 10960 * 10961 * @return the vertical extent of the scrollbar's thumb 10962 * 10963 * @see #computeVerticalScrollRange() 10964 * @see #computeVerticalScrollOffset() 10965 * @see android.widget.ScrollBarDrawable 10966 */ 10967 protected int computeVerticalScrollExtent() { 10968 return getHeight(); 10969 } 10970 10971 /** 10972 * Check if this view can be scrolled horizontally in a certain direction. 10973 * 10974 * @param direction Negative to check scrolling left, positive to check scrolling right. 10975 * @return true if this view can be scrolled in the specified direction, false otherwise. 10976 */ 10977 public boolean canScrollHorizontally(int direction) { 10978 final int offset = computeHorizontalScrollOffset(); 10979 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 10980 if (range == 0) return false; 10981 if (direction < 0) { 10982 return offset > 0; 10983 } else { 10984 return offset < range - 1; 10985 } 10986 } 10987 10988 /** 10989 * Check if this view can be scrolled vertically in a certain direction. 10990 * 10991 * @param direction Negative to check scrolling up, positive to check scrolling down. 10992 * @return true if this view can be scrolled in the specified direction, false otherwise. 10993 */ 10994 public boolean canScrollVertically(int direction) { 10995 final int offset = computeVerticalScrollOffset(); 10996 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 10997 if (range == 0) return false; 10998 if (direction < 0) { 10999 return offset > 0; 11000 } else { 11001 return offset < range - 1; 11002 } 11003 } 11004 11005 /** 11006 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 11007 * scrollbars are painted only if they have been awakened first.</p> 11008 * 11009 * @param canvas the canvas on which to draw the scrollbars 11010 * 11011 * @see #awakenScrollBars(int) 11012 */ 11013 protected final void onDrawScrollBars(Canvas canvas) { 11014 // scrollbars are drawn only when the animation is running 11015 final ScrollabilityCache cache = mScrollCache; 11016 if (cache != null) { 11017 11018 int state = cache.state; 11019 11020 if (state == ScrollabilityCache.OFF) { 11021 return; 11022 } 11023 11024 boolean invalidate = false; 11025 11026 if (state == ScrollabilityCache.FADING) { 11027 // We're fading -- get our fade interpolation 11028 if (cache.interpolatorValues == null) { 11029 cache.interpolatorValues = new float[1]; 11030 } 11031 11032 float[] values = cache.interpolatorValues; 11033 11034 // Stops the animation if we're done 11035 if (cache.scrollBarInterpolator.timeToValues(values) == 11036 Interpolator.Result.FREEZE_END) { 11037 cache.state = ScrollabilityCache.OFF; 11038 } else { 11039 cache.scrollBar.setAlpha(Math.round(values[0])); 11040 } 11041 11042 // This will make the scroll bars inval themselves after 11043 // drawing. We only want this when we're fading so that 11044 // we prevent excessive redraws 11045 invalidate = true; 11046 } else { 11047 // We're just on -- but we may have been fading before so 11048 // reset alpha 11049 cache.scrollBar.setAlpha(255); 11050 } 11051 11052 11053 final int viewFlags = mViewFlags; 11054 11055 final boolean drawHorizontalScrollBar = 11056 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11057 final boolean drawVerticalScrollBar = 11058 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 11059 && !isVerticalScrollBarHidden(); 11060 11061 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 11062 final int width = mRight - mLeft; 11063 final int height = mBottom - mTop; 11064 11065 final ScrollBarDrawable scrollBar = cache.scrollBar; 11066 11067 final int scrollX = mScrollX; 11068 final int scrollY = mScrollY; 11069 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 11070 11071 int left, top, right, bottom; 11072 11073 if (drawHorizontalScrollBar) { 11074 int size = scrollBar.getSize(false); 11075 if (size <= 0) { 11076 size = cache.scrollBarSize; 11077 } 11078 11079 scrollBar.setParameters(computeHorizontalScrollRange(), 11080 computeHorizontalScrollOffset(), 11081 computeHorizontalScrollExtent(), false); 11082 final int verticalScrollBarGap = drawVerticalScrollBar ? 11083 getVerticalScrollbarWidth() : 0; 11084 top = scrollY + height - size - (mUserPaddingBottom & inside); 11085 left = scrollX + (mPaddingLeft & inside); 11086 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 11087 bottom = top + size; 11088 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 11089 if (invalidate) { 11090 invalidate(left, top, right, bottom); 11091 } 11092 } 11093 11094 if (drawVerticalScrollBar) { 11095 int size = scrollBar.getSize(true); 11096 if (size <= 0) { 11097 size = cache.scrollBarSize; 11098 } 11099 11100 scrollBar.setParameters(computeVerticalScrollRange(), 11101 computeVerticalScrollOffset(), 11102 computeVerticalScrollExtent(), true); 11103 switch (mVerticalScrollbarPosition) { 11104 default: 11105 case SCROLLBAR_POSITION_DEFAULT: 11106 case SCROLLBAR_POSITION_RIGHT: 11107 left = scrollX + width - size - (mUserPaddingRight & inside); 11108 break; 11109 case SCROLLBAR_POSITION_LEFT: 11110 left = scrollX + (mUserPaddingLeft & inside); 11111 break; 11112 } 11113 top = scrollY + (mPaddingTop & inside); 11114 right = left + size; 11115 bottom = scrollY + height - (mUserPaddingBottom & inside); 11116 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 11117 if (invalidate) { 11118 invalidate(left, top, right, bottom); 11119 } 11120 } 11121 } 11122 } 11123 } 11124 11125 /** 11126 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 11127 * FastScroller is visible. 11128 * @return whether to temporarily hide the vertical scrollbar 11129 * @hide 11130 */ 11131 protected boolean isVerticalScrollBarHidden() { 11132 return false; 11133 } 11134 11135 /** 11136 * <p>Draw the horizontal scrollbar if 11137 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 11138 * 11139 * @param canvas the canvas on which to draw the scrollbar 11140 * @param scrollBar the scrollbar's drawable 11141 * 11142 * @see #isHorizontalScrollBarEnabled() 11143 * @see #computeHorizontalScrollRange() 11144 * @see #computeHorizontalScrollExtent() 11145 * @see #computeHorizontalScrollOffset() 11146 * @see android.widget.ScrollBarDrawable 11147 * @hide 11148 */ 11149 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 11150 int l, int t, int r, int b) { 11151 scrollBar.setBounds(l, t, r, b); 11152 scrollBar.draw(canvas); 11153 } 11154 11155 /** 11156 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 11157 * returns true.</p> 11158 * 11159 * @param canvas the canvas on which to draw the scrollbar 11160 * @param scrollBar the scrollbar's drawable 11161 * 11162 * @see #isVerticalScrollBarEnabled() 11163 * @see #computeVerticalScrollRange() 11164 * @see #computeVerticalScrollExtent() 11165 * @see #computeVerticalScrollOffset() 11166 * @see android.widget.ScrollBarDrawable 11167 * @hide 11168 */ 11169 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 11170 int l, int t, int r, int b) { 11171 scrollBar.setBounds(l, t, r, b); 11172 scrollBar.draw(canvas); 11173 } 11174 11175 /** 11176 * Implement this to do your drawing. 11177 * 11178 * @param canvas the canvas on which the background will be drawn 11179 */ 11180 protected void onDraw(Canvas canvas) { 11181 } 11182 11183 /* 11184 * Caller is responsible for calling requestLayout if necessary. 11185 * (This allows addViewInLayout to not request a new layout.) 11186 */ 11187 void assignParent(ViewParent parent) { 11188 if (mParent == null) { 11189 mParent = parent; 11190 } else if (parent == null) { 11191 mParent = null; 11192 } else { 11193 throw new RuntimeException("view " + this + " being added, but" 11194 + " it already has a parent"); 11195 } 11196 } 11197 11198 /** 11199 * This is called when the view is attached to a window. At this point it 11200 * has a Surface and will start drawing. Note that this function is 11201 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 11202 * however it may be called any time before the first onDraw -- including 11203 * before or after {@link #onMeasure(int, int)}. 11204 * 11205 * @see #onDetachedFromWindow() 11206 */ 11207 protected void onAttachedToWindow() { 11208 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 11209 mParent.requestTransparentRegion(this); 11210 } 11211 11212 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 11213 initialAwakenScrollBars(); 11214 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH; 11215 } 11216 11217 jumpDrawablesToCurrentState(); 11218 11219 // Order is important here: LayoutDirection MUST be resolved before Padding 11220 // and TextDirection 11221 resolveLayoutDirection(); 11222 resolvePadding(); 11223 resolveTextDirection(); 11224 resolveTextAlignment(); 11225 11226 clearAccessibilityFocus(); 11227 if (isFocused()) { 11228 InputMethodManager imm = InputMethodManager.peekInstance(); 11229 imm.focusIn(this); 11230 } 11231 11232 if (mAttachInfo != null && mDisplayList != null) { 11233 mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList); 11234 } 11235 } 11236 11237 /** 11238 * @see #onScreenStateChanged(int) 11239 */ 11240 void dispatchScreenStateChanged(int screenState) { 11241 onScreenStateChanged(screenState); 11242 } 11243 11244 /** 11245 * This method is called whenever the state of the screen this view is 11246 * attached to changes. A state change will usually occurs when the screen 11247 * turns on or off (whether it happens automatically or the user does it 11248 * manually.) 11249 * 11250 * @param screenState The new state of the screen. Can be either 11251 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 11252 */ 11253 public void onScreenStateChanged(int screenState) { 11254 } 11255 11256 /** 11257 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 11258 */ 11259 private boolean hasRtlSupport() { 11260 return mContext.getApplicationInfo().hasRtlSupport(); 11261 } 11262 11263 /** 11264 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 11265 * that the parent directionality can and will be resolved before its children. 11266 * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done. 11267 * @hide 11268 */ 11269 public void resolveLayoutDirection() { 11270 // Clear any previous layout direction resolution 11271 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK; 11272 11273 if (hasRtlSupport()) { 11274 // Set resolved depending on layout direction 11275 switch (getLayoutDirection()) { 11276 case LAYOUT_DIRECTION_INHERIT: 11277 // If this is root view, no need to look at parent's layout dir. 11278 if (canResolveLayoutDirection()) { 11279 ViewGroup viewGroup = ((ViewGroup) mParent); 11280 11281 if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 11282 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 11283 } 11284 } else { 11285 // Nothing to do, LTR by default 11286 } 11287 break; 11288 case LAYOUT_DIRECTION_RTL: 11289 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 11290 break; 11291 case LAYOUT_DIRECTION_LOCALE: 11292 if(isLayoutDirectionRtl(Locale.getDefault())) { 11293 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 11294 } 11295 break; 11296 default: 11297 // Nothing to do, LTR by default 11298 } 11299 } 11300 11301 // Set to resolved 11302 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED; 11303 onResolvedLayoutDirectionChanged(); 11304 // Resolve padding 11305 resolvePadding(); 11306 } 11307 11308 /** 11309 * Called when layout direction has been resolved. 11310 * 11311 * The default implementation does nothing. 11312 * @hide 11313 */ 11314 public void onResolvedLayoutDirectionChanged() { 11315 } 11316 11317 /** 11318 * Resolve padding depending on layout direction. 11319 * @hide 11320 */ 11321 public void resolvePadding() { 11322 // If the user specified the absolute padding (either with android:padding or 11323 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 11324 // use the default padding or the padding from the background drawable 11325 // (stored at this point in mPadding*) 11326 int resolvedLayoutDirection = getResolvedLayoutDirection(); 11327 switch (resolvedLayoutDirection) { 11328 case LAYOUT_DIRECTION_RTL: 11329 // Start user padding override Right user padding. Otherwise, if Right user 11330 // padding is not defined, use the default Right padding. If Right user padding 11331 // is defined, just use it. 11332 if (mUserPaddingStart >= 0) { 11333 mUserPaddingRight = mUserPaddingStart; 11334 } else if (mUserPaddingRight < 0) { 11335 mUserPaddingRight = mPaddingRight; 11336 } 11337 if (mUserPaddingEnd >= 0) { 11338 mUserPaddingLeft = mUserPaddingEnd; 11339 } else if (mUserPaddingLeft < 0) { 11340 mUserPaddingLeft = mPaddingLeft; 11341 } 11342 break; 11343 case LAYOUT_DIRECTION_LTR: 11344 default: 11345 // Start user padding override Left user padding. Otherwise, if Left user 11346 // padding is not defined, use the default left padding. If Left user padding 11347 // is defined, just use it. 11348 if (mUserPaddingStart >= 0) { 11349 mUserPaddingLeft = mUserPaddingStart; 11350 } else if (mUserPaddingLeft < 0) { 11351 mUserPaddingLeft = mPaddingLeft; 11352 } 11353 if (mUserPaddingEnd >= 0) { 11354 mUserPaddingRight = mUserPaddingEnd; 11355 } else if (mUserPaddingRight < 0) { 11356 mUserPaddingRight = mPaddingRight; 11357 } 11358 } 11359 11360 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 11361 11362 if(isPaddingRelative()) { 11363 setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom); 11364 } else { 11365 recomputePadding(); 11366 } 11367 onPaddingChanged(resolvedLayoutDirection); 11368 } 11369 11370 /** 11371 * Resolve padding depending on the layout direction. Subclasses that care about 11372 * padding resolution should override this method. The default implementation does 11373 * nothing. 11374 * 11375 * @param layoutDirection the direction of the layout 11376 * 11377 * @see {@link #LAYOUT_DIRECTION_LTR} 11378 * @see {@link #LAYOUT_DIRECTION_RTL} 11379 * @hide 11380 */ 11381 public void onPaddingChanged(int layoutDirection) { 11382 } 11383 11384 /** 11385 * Check if layout direction resolution can be done. 11386 * 11387 * @return true if layout direction resolution can be done otherwise return false. 11388 * @hide 11389 */ 11390 public boolean canResolveLayoutDirection() { 11391 switch (getLayoutDirection()) { 11392 case LAYOUT_DIRECTION_INHERIT: 11393 return (mParent != null) && (mParent instanceof ViewGroup); 11394 default: 11395 return true; 11396 } 11397 } 11398 11399 /** 11400 * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset} 11401 * when reset is done. 11402 * @hide 11403 */ 11404 public void resetResolvedLayoutDirection() { 11405 // Reset the current resolved bits 11406 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK; 11407 onResolvedLayoutDirectionReset(); 11408 // Reset also the text direction 11409 resetResolvedTextDirection(); 11410 } 11411 11412 /** 11413 * Called during reset of resolved layout direction. 11414 * 11415 * Subclasses need to override this method to clear cached information that depends on the 11416 * resolved layout direction, or to inform child views that inherit their layout direction. 11417 * 11418 * The default implementation does nothing. 11419 * @hide 11420 */ 11421 public void onResolvedLayoutDirectionReset() { 11422 } 11423 11424 /** 11425 * Check if a Locale uses an RTL script. 11426 * 11427 * @param locale Locale to check 11428 * @return true if the Locale uses an RTL script. 11429 * @hide 11430 */ 11431 protected static boolean isLayoutDirectionRtl(Locale locale) { 11432 return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale)); 11433 } 11434 11435 /** 11436 * This is called when the view is detached from a window. At this point it 11437 * no longer has a surface for drawing. 11438 * 11439 * @see #onAttachedToWindow() 11440 */ 11441 protected void onDetachedFromWindow() { 11442 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 11443 11444 removeUnsetPressCallback(); 11445 removeLongPressCallback(); 11446 removePerformClickCallback(); 11447 removeSendViewScrolledAccessibilityEventCallback(); 11448 11449 destroyDrawingCache(); 11450 11451 destroyLayer(false); 11452 11453 if (mAttachInfo != null) { 11454 if (mDisplayList != null) { 11455 mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList); 11456 } 11457 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 11458 } else { 11459 if (mDisplayList != null) { 11460 // Should never happen 11461 mDisplayList.invalidate(); 11462 } 11463 } 11464 11465 mCurrentAnimation = null; 11466 11467 resetResolvedLayoutDirection(); 11468 resetResolvedTextAlignment(); 11469 resetAccessibilityStateChanged(); 11470 } 11471 11472 /** 11473 * @return The number of times this view has been attached to a window 11474 */ 11475 protected int getWindowAttachCount() { 11476 return mWindowAttachCount; 11477 } 11478 11479 /** 11480 * Retrieve a unique token identifying the window this view is attached to. 11481 * @return Return the window's token for use in 11482 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 11483 */ 11484 public IBinder getWindowToken() { 11485 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 11486 } 11487 11488 /** 11489 * Retrieve a unique token identifying the top-level "real" window of 11490 * the window that this view is attached to. That is, this is like 11491 * {@link #getWindowToken}, except if the window this view in is a panel 11492 * window (attached to another containing window), then the token of 11493 * the containing window is returned instead. 11494 * 11495 * @return Returns the associated window token, either 11496 * {@link #getWindowToken()} or the containing window's token. 11497 */ 11498 public IBinder getApplicationWindowToken() { 11499 AttachInfo ai = mAttachInfo; 11500 if (ai != null) { 11501 IBinder appWindowToken = ai.mPanelParentWindowToken; 11502 if (appWindowToken == null) { 11503 appWindowToken = ai.mWindowToken; 11504 } 11505 return appWindowToken; 11506 } 11507 return null; 11508 } 11509 11510 /** 11511 * Retrieve private session object this view hierarchy is using to 11512 * communicate with the window manager. 11513 * @return the session object to communicate with the window manager 11514 */ 11515 /*package*/ IWindowSession getWindowSession() { 11516 return mAttachInfo != null ? mAttachInfo.mSession : null; 11517 } 11518 11519 /** 11520 * @param info the {@link android.view.View.AttachInfo} to associated with 11521 * this view 11522 */ 11523 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 11524 //System.out.println("Attached! " + this); 11525 mAttachInfo = info; 11526 mWindowAttachCount++; 11527 // We will need to evaluate the drawable state at least once. 11528 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 11529 if (mFloatingTreeObserver != null) { 11530 info.mTreeObserver.merge(mFloatingTreeObserver); 11531 mFloatingTreeObserver = null; 11532 } 11533 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 11534 mAttachInfo.mScrollContainers.add(this); 11535 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 11536 } 11537 performCollectViewAttributes(mAttachInfo, visibility); 11538 onAttachedToWindow(); 11539 11540 ListenerInfo li = mListenerInfo; 11541 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 11542 li != null ? li.mOnAttachStateChangeListeners : null; 11543 if (listeners != null && listeners.size() > 0) { 11544 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 11545 // perform the dispatching. The iterator is a safe guard against listeners that 11546 // could mutate the list by calling the various add/remove methods. This prevents 11547 // the array from being modified while we iterate it. 11548 for (OnAttachStateChangeListener listener : listeners) { 11549 listener.onViewAttachedToWindow(this); 11550 } 11551 } 11552 11553 int vis = info.mWindowVisibility; 11554 if (vis != GONE) { 11555 onWindowVisibilityChanged(vis); 11556 } 11557 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 11558 // If nobody has evaluated the drawable state yet, then do it now. 11559 refreshDrawableState(); 11560 } 11561 } 11562 11563 void dispatchDetachedFromWindow() { 11564 AttachInfo info = mAttachInfo; 11565 if (info != null) { 11566 int vis = info.mWindowVisibility; 11567 if (vis != GONE) { 11568 onWindowVisibilityChanged(GONE); 11569 } 11570 } 11571 11572 onDetachedFromWindow(); 11573 11574 ListenerInfo li = mListenerInfo; 11575 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 11576 li != null ? li.mOnAttachStateChangeListeners : null; 11577 if (listeners != null && listeners.size() > 0) { 11578 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 11579 // perform the dispatching. The iterator is a safe guard against listeners that 11580 // could mutate the list by calling the various add/remove methods. This prevents 11581 // the array from being modified while we iterate it. 11582 for (OnAttachStateChangeListener listener : listeners) { 11583 listener.onViewDetachedFromWindow(this); 11584 } 11585 } 11586 11587 if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) { 11588 mAttachInfo.mScrollContainers.remove(this); 11589 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 11590 } 11591 11592 mAttachInfo = null; 11593 } 11594 11595 /** 11596 * Store this view hierarchy's frozen state into the given container. 11597 * 11598 * @param container The SparseArray in which to save the view's state. 11599 * 11600 * @see #restoreHierarchyState(android.util.SparseArray) 11601 * @see #dispatchSaveInstanceState(android.util.SparseArray) 11602 * @see #onSaveInstanceState() 11603 */ 11604 public void saveHierarchyState(SparseArray<Parcelable> container) { 11605 dispatchSaveInstanceState(container); 11606 } 11607 11608 /** 11609 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 11610 * this view and its children. May be overridden to modify how freezing happens to a 11611 * view's children; for example, some views may want to not store state for their children. 11612 * 11613 * @param container The SparseArray in which to save the view's state. 11614 * 11615 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 11616 * @see #saveHierarchyState(android.util.SparseArray) 11617 * @see #onSaveInstanceState() 11618 */ 11619 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 11620 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 11621 mPrivateFlags &= ~SAVE_STATE_CALLED; 11622 Parcelable state = onSaveInstanceState(); 11623 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 11624 throw new IllegalStateException( 11625 "Derived class did not call super.onSaveInstanceState()"); 11626 } 11627 if (state != null) { 11628 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 11629 // + ": " + state); 11630 container.put(mID, state); 11631 } 11632 } 11633 } 11634 11635 /** 11636 * Hook allowing a view to generate a representation of its internal state 11637 * that can later be used to create a new instance with that same state. 11638 * This state should only contain information that is not persistent or can 11639 * not be reconstructed later. For example, you will never store your 11640 * current position on screen because that will be computed again when a 11641 * new instance of the view is placed in its view hierarchy. 11642 * <p> 11643 * Some examples of things you may store here: the current cursor position 11644 * in a text view (but usually not the text itself since that is stored in a 11645 * content provider or other persistent storage), the currently selected 11646 * item in a list view. 11647 * 11648 * @return Returns a Parcelable object containing the view's current dynamic 11649 * state, or null if there is nothing interesting to save. The 11650 * default implementation returns null. 11651 * @see #onRestoreInstanceState(android.os.Parcelable) 11652 * @see #saveHierarchyState(android.util.SparseArray) 11653 * @see #dispatchSaveInstanceState(android.util.SparseArray) 11654 * @see #setSaveEnabled(boolean) 11655 */ 11656 protected Parcelable onSaveInstanceState() { 11657 mPrivateFlags |= SAVE_STATE_CALLED; 11658 return BaseSavedState.EMPTY_STATE; 11659 } 11660 11661 /** 11662 * Restore this view hierarchy's frozen state from the given container. 11663 * 11664 * @param container The SparseArray which holds previously frozen states. 11665 * 11666 * @see #saveHierarchyState(android.util.SparseArray) 11667 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 11668 * @see #onRestoreInstanceState(android.os.Parcelable) 11669 */ 11670 public void restoreHierarchyState(SparseArray<Parcelable> container) { 11671 dispatchRestoreInstanceState(container); 11672 } 11673 11674 /** 11675 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 11676 * state for this view and its children. May be overridden to modify how restoring 11677 * happens to a view's children; for example, some views may want to not store state 11678 * for their children. 11679 * 11680 * @param container The SparseArray which holds previously saved state. 11681 * 11682 * @see #dispatchSaveInstanceState(android.util.SparseArray) 11683 * @see #restoreHierarchyState(android.util.SparseArray) 11684 * @see #onRestoreInstanceState(android.os.Parcelable) 11685 */ 11686 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 11687 if (mID != NO_ID) { 11688 Parcelable state = container.get(mID); 11689 if (state != null) { 11690 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 11691 // + ": " + state); 11692 mPrivateFlags &= ~SAVE_STATE_CALLED; 11693 onRestoreInstanceState(state); 11694 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 11695 throw new IllegalStateException( 11696 "Derived class did not call super.onRestoreInstanceState()"); 11697 } 11698 } 11699 } 11700 } 11701 11702 /** 11703 * Hook allowing a view to re-apply a representation of its internal state that had previously 11704 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 11705 * null state. 11706 * 11707 * @param state The frozen state that had previously been returned by 11708 * {@link #onSaveInstanceState}. 11709 * 11710 * @see #onSaveInstanceState() 11711 * @see #restoreHierarchyState(android.util.SparseArray) 11712 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 11713 */ 11714 protected void onRestoreInstanceState(Parcelable state) { 11715 mPrivateFlags |= SAVE_STATE_CALLED; 11716 if (state != BaseSavedState.EMPTY_STATE && state != null) { 11717 throw new IllegalArgumentException("Wrong state class, expecting View State but " 11718 + "received " + state.getClass().toString() + " instead. This usually happens " 11719 + "when two views of different type have the same id in the same hierarchy. " 11720 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 11721 + "other views do not use the same id."); 11722 } 11723 } 11724 11725 /** 11726 * <p>Return the time at which the drawing of the view hierarchy started.</p> 11727 * 11728 * @return the drawing start time in milliseconds 11729 */ 11730 public long getDrawingTime() { 11731 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 11732 } 11733 11734 /** 11735 * <p>Enables or disables the duplication of the parent's state into this view. When 11736 * duplication is enabled, this view gets its drawable state from its parent rather 11737 * than from its own internal properties.</p> 11738 * 11739 * <p>Note: in the current implementation, setting this property to true after the 11740 * view was added to a ViewGroup might have no effect at all. This property should 11741 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 11742 * 11743 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 11744 * property is enabled, an exception will be thrown.</p> 11745 * 11746 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 11747 * parent, these states should not be affected by this method.</p> 11748 * 11749 * @param enabled True to enable duplication of the parent's drawable state, false 11750 * to disable it. 11751 * 11752 * @see #getDrawableState() 11753 * @see #isDuplicateParentStateEnabled() 11754 */ 11755 public void setDuplicateParentStateEnabled(boolean enabled) { 11756 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 11757 } 11758 11759 /** 11760 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 11761 * 11762 * @return True if this view's drawable state is duplicated from the parent, 11763 * false otherwise 11764 * 11765 * @see #getDrawableState() 11766 * @see #setDuplicateParentStateEnabled(boolean) 11767 */ 11768 public boolean isDuplicateParentStateEnabled() { 11769 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 11770 } 11771 11772 /** 11773 * <p>Specifies the type of layer backing this view. The layer can be 11774 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 11775 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 11776 * 11777 * <p>A layer is associated with an optional {@link android.graphics.Paint} 11778 * instance that controls how the layer is composed on screen. The following 11779 * properties of the paint are taken into account when composing the layer:</p> 11780 * <ul> 11781 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 11782 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 11783 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 11784 * </ul> 11785 * 11786 * <p>If this view has an alpha value set to < 1.0 by calling 11787 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 11788 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 11789 * equivalent to setting a hardware layer on this view and providing a paint with 11790 * the desired alpha value.<p> 11791 * 11792 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 11793 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 11794 * for more information on when and how to use layers.</p> 11795 * 11796 * @param layerType The ype of layer to use with this view, must be one of 11797 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 11798 * {@link #LAYER_TYPE_HARDWARE} 11799 * @param paint The paint used to compose the layer. This argument is optional 11800 * and can be null. It is ignored when the layer type is 11801 * {@link #LAYER_TYPE_NONE} 11802 * 11803 * @see #getLayerType() 11804 * @see #LAYER_TYPE_NONE 11805 * @see #LAYER_TYPE_SOFTWARE 11806 * @see #LAYER_TYPE_HARDWARE 11807 * @see #setAlpha(float) 11808 * 11809 * @attr ref android.R.styleable#View_layerType 11810 */ 11811 public void setLayerType(int layerType, Paint paint) { 11812 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 11813 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 11814 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 11815 } 11816 11817 if (layerType == mLayerType) { 11818 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 11819 mLayerPaint = paint == null ? new Paint() : paint; 11820 invalidateParentCaches(); 11821 invalidate(true); 11822 } 11823 return; 11824 } 11825 11826 // Destroy any previous software drawing cache if needed 11827 switch (mLayerType) { 11828 case LAYER_TYPE_HARDWARE: 11829 destroyLayer(false); 11830 // fall through - non-accelerated views may use software layer mechanism instead 11831 case LAYER_TYPE_SOFTWARE: 11832 destroyDrawingCache(); 11833 break; 11834 default: 11835 break; 11836 } 11837 11838 mLayerType = layerType; 11839 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 11840 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 11841 mLocalDirtyRect = layerDisabled ? null : new Rect(); 11842 11843 invalidateParentCaches(); 11844 invalidate(true); 11845 } 11846 11847 /** 11848 * Indicates whether this view has a static layer. A view with layer type 11849 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 11850 * dynamic. 11851 */ 11852 boolean hasStaticLayer() { 11853 return true; 11854 } 11855 11856 /** 11857 * Indicates what type of layer is currently associated with this view. By default 11858 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 11859 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 11860 * for more information on the different types of layers. 11861 * 11862 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 11863 * {@link #LAYER_TYPE_HARDWARE} 11864 * 11865 * @see #setLayerType(int, android.graphics.Paint) 11866 * @see #buildLayer() 11867 * @see #LAYER_TYPE_NONE 11868 * @see #LAYER_TYPE_SOFTWARE 11869 * @see #LAYER_TYPE_HARDWARE 11870 */ 11871 public int getLayerType() { 11872 return mLayerType; 11873 } 11874 11875 /** 11876 * Forces this view's layer to be created and this view to be rendered 11877 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 11878 * invoking this method will have no effect. 11879 * 11880 * This method can for instance be used to render a view into its layer before 11881 * starting an animation. If this view is complex, rendering into the layer 11882 * before starting the animation will avoid skipping frames. 11883 * 11884 * @throws IllegalStateException If this view is not attached to a window 11885 * 11886 * @see #setLayerType(int, android.graphics.Paint) 11887 */ 11888 public void buildLayer() { 11889 if (mLayerType == LAYER_TYPE_NONE) return; 11890 11891 if (mAttachInfo == null) { 11892 throw new IllegalStateException("This view must be attached to a window first"); 11893 } 11894 11895 switch (mLayerType) { 11896 case LAYER_TYPE_HARDWARE: 11897 if (mAttachInfo.mHardwareRenderer != null && 11898 mAttachInfo.mHardwareRenderer.isEnabled() && 11899 mAttachInfo.mHardwareRenderer.validate()) { 11900 getHardwareLayer(); 11901 } 11902 break; 11903 case LAYER_TYPE_SOFTWARE: 11904 buildDrawingCache(true); 11905 break; 11906 } 11907 } 11908 11909 // Make sure the HardwareRenderer.validate() was invoked before calling this method 11910 void flushLayer() { 11911 if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) { 11912 mHardwareLayer.flush(); 11913 } 11914 } 11915 11916 /** 11917 * <p>Returns a hardware layer that can be used to draw this view again 11918 * without executing its draw method.</p> 11919 * 11920 * @return A HardwareLayer ready to render, or null if an error occurred. 11921 */ 11922 HardwareLayer getHardwareLayer() { 11923 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 11924 !mAttachInfo.mHardwareRenderer.isEnabled()) { 11925 return null; 11926 } 11927 11928 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 11929 11930 final int width = mRight - mLeft; 11931 final int height = mBottom - mTop; 11932 11933 if (width == 0 || height == 0) { 11934 return null; 11935 } 11936 11937 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 11938 if (mHardwareLayer == null) { 11939 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 11940 width, height, isOpaque()); 11941 mLocalDirtyRect.set(0, 0, width, height); 11942 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 11943 mHardwareLayer.resize(width, height); 11944 mLocalDirtyRect.set(0, 0, width, height); 11945 } 11946 11947 // The layer is not valid if the underlying GPU resources cannot be allocated 11948 if (!mHardwareLayer.isValid()) { 11949 return null; 11950 } 11951 11952 mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect); 11953 mLocalDirtyRect.setEmpty(); 11954 } 11955 11956 return mHardwareLayer; 11957 } 11958 11959 /** 11960 * Destroys this View's hardware layer if possible. 11961 * 11962 * @return True if the layer was destroyed, false otherwise. 11963 * 11964 * @see #setLayerType(int, android.graphics.Paint) 11965 * @see #LAYER_TYPE_HARDWARE 11966 */ 11967 boolean destroyLayer(boolean valid) { 11968 if (mHardwareLayer != null) { 11969 AttachInfo info = mAttachInfo; 11970 if (info != null && info.mHardwareRenderer != null && 11971 info.mHardwareRenderer.isEnabled() && 11972 (valid || info.mHardwareRenderer.validate())) { 11973 mHardwareLayer.destroy(); 11974 mHardwareLayer = null; 11975 11976 invalidate(true); 11977 invalidateParentCaches(); 11978 } 11979 return true; 11980 } 11981 return false; 11982 } 11983 11984 /** 11985 * Destroys all hardware rendering resources. This method is invoked 11986 * when the system needs to reclaim resources. Upon execution of this 11987 * method, you should free any OpenGL resources created by the view. 11988 * 11989 * Note: you <strong>must</strong> call 11990 * <code>super.destroyHardwareResources()</code> when overriding 11991 * this method. 11992 * 11993 * @hide 11994 */ 11995 protected void destroyHardwareResources() { 11996 destroyLayer(true); 11997 } 11998 11999 /** 12000 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 12001 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 12002 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 12003 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 12004 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 12005 * null.</p> 12006 * 12007 * <p>Enabling the drawing cache is similar to 12008 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 12009 * acceleration is turned off. When hardware acceleration is turned on, enabling the 12010 * drawing cache has no effect on rendering because the system uses a different mechanism 12011 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 12012 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 12013 * for information on how to enable software and hardware layers.</p> 12014 * 12015 * <p>This API can be used to manually generate 12016 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 12017 * {@link #getDrawingCache()}.</p> 12018 * 12019 * @param enabled true to enable the drawing cache, false otherwise 12020 * 12021 * @see #isDrawingCacheEnabled() 12022 * @see #getDrawingCache() 12023 * @see #buildDrawingCache() 12024 * @see #setLayerType(int, android.graphics.Paint) 12025 */ 12026 public void setDrawingCacheEnabled(boolean enabled) { 12027 mCachingFailed = false; 12028 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 12029 } 12030 12031 /** 12032 * <p>Indicates whether the drawing cache is enabled for this view.</p> 12033 * 12034 * @return true if the drawing cache is enabled 12035 * 12036 * @see #setDrawingCacheEnabled(boolean) 12037 * @see #getDrawingCache() 12038 */ 12039 @ViewDebug.ExportedProperty(category = "drawing") 12040 public boolean isDrawingCacheEnabled() { 12041 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 12042 } 12043 12044 /** 12045 * Debugging utility which recursively outputs the dirty state of a view and its 12046 * descendants. 12047 * 12048 * @hide 12049 */ 12050 @SuppressWarnings({"UnusedDeclaration"}) 12051 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 12052 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) + 12053 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" + 12054 (mPrivateFlags & View.DRAWING_CACHE_VALID) + 12055 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")"); 12056 if (clear) { 12057 mPrivateFlags &= clearMask; 12058 } 12059 if (this instanceof ViewGroup) { 12060 ViewGroup parent = (ViewGroup) this; 12061 final int count = parent.getChildCount(); 12062 for (int i = 0; i < count; i++) { 12063 final View child = parent.getChildAt(i); 12064 child.outputDirtyFlags(indent + " ", clear, clearMask); 12065 } 12066 } 12067 } 12068 12069 /** 12070 * This method is used by ViewGroup to cause its children to restore or recreate their 12071 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 12072 * to recreate its own display list, which would happen if it went through the normal 12073 * draw/dispatchDraw mechanisms. 12074 * 12075 * @hide 12076 */ 12077 protected void dispatchGetDisplayList() {} 12078 12079 /** 12080 * A view that is not attached or hardware accelerated cannot create a display list. 12081 * This method checks these conditions and returns the appropriate result. 12082 * 12083 * @return true if view has the ability to create a display list, false otherwise. 12084 * 12085 * @hide 12086 */ 12087 public boolean canHaveDisplayList() { 12088 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 12089 } 12090 12091 /** 12092 * @return The HardwareRenderer associated with that view or null if hardware rendering 12093 * is not supported or this this has not been attached to a window. 12094 * 12095 * @hide 12096 */ 12097 public HardwareRenderer getHardwareRenderer() { 12098 if (mAttachInfo != null) { 12099 return mAttachInfo.mHardwareRenderer; 12100 } 12101 return null; 12102 } 12103 12104 /** 12105 * Returns a DisplayList. If the incoming displayList is null, one will be created. 12106 * Otherwise, the same display list will be returned (after having been rendered into 12107 * along the way, depending on the invalidation state of the view). 12108 * 12109 * @param displayList The previous version of this displayList, could be null. 12110 * @param isLayer Whether the requester of the display list is a layer. If so, 12111 * the view will avoid creating a layer inside the resulting display list. 12112 * @return A new or reused DisplayList object. 12113 */ 12114 private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) { 12115 if (!canHaveDisplayList()) { 12116 return null; 12117 } 12118 12119 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || 12120 displayList == null || !displayList.isValid() || 12121 (!isLayer && mRecreateDisplayList))) { 12122 // Don't need to recreate the display list, just need to tell our 12123 // children to restore/recreate theirs 12124 if (displayList != null && displayList.isValid() && 12125 !isLayer && !mRecreateDisplayList) { 12126 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 12127 mPrivateFlags &= ~DIRTY_MASK; 12128 dispatchGetDisplayList(); 12129 12130 return displayList; 12131 } 12132 12133 if (!isLayer) { 12134 // If we got here, we're recreating it. Mark it as such to ensure that 12135 // we copy in child display lists into ours in drawChild() 12136 mRecreateDisplayList = true; 12137 } 12138 if (displayList == null) { 12139 final String name = getClass().getSimpleName(); 12140 displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name); 12141 // If we're creating a new display list, make sure our parent gets invalidated 12142 // since they will need to recreate their display list to account for this 12143 // new child display list. 12144 invalidateParentCaches(); 12145 } 12146 12147 boolean caching = false; 12148 final HardwareCanvas canvas = displayList.start(); 12149 int width = mRight - mLeft; 12150 int height = mBottom - mTop; 12151 12152 try { 12153 canvas.setViewport(width, height); 12154 // The dirty rect should always be null for a display list 12155 canvas.onPreDraw(null); 12156 int layerType = ( 12157 !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ? 12158 getLayerType() : LAYER_TYPE_NONE; 12159 if (!isLayer && layerType != LAYER_TYPE_NONE) { 12160 if (layerType == LAYER_TYPE_HARDWARE) { 12161 final HardwareLayer layer = getHardwareLayer(); 12162 if (layer != null && layer.isValid()) { 12163 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 12164 } else { 12165 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 12166 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 12167 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 12168 } 12169 caching = true; 12170 } else { 12171 buildDrawingCache(true); 12172 Bitmap cache = getDrawingCache(true); 12173 if (cache != null) { 12174 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 12175 caching = true; 12176 } 12177 } 12178 } else { 12179 12180 computeScroll(); 12181 12182 canvas.translate(-mScrollX, -mScrollY); 12183 if (!isLayer) { 12184 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 12185 mPrivateFlags &= ~DIRTY_MASK; 12186 } 12187 12188 // Fast path for layouts with no backgrounds 12189 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 12190 dispatchDraw(canvas); 12191 } else { 12192 draw(canvas); 12193 } 12194 } 12195 } finally { 12196 canvas.onPostDraw(); 12197 12198 displayList.end(); 12199 displayList.setCaching(caching); 12200 if (isLayer) { 12201 displayList.setLeftTopRightBottom(0, 0, width, height); 12202 } else { 12203 setDisplayListProperties(displayList); 12204 } 12205 } 12206 } else if (!isLayer) { 12207 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 12208 mPrivateFlags &= ~DIRTY_MASK; 12209 } 12210 12211 return displayList; 12212 } 12213 12214 /** 12215 * Get the DisplayList for the HardwareLayer 12216 * 12217 * @param layer The HardwareLayer whose DisplayList we want 12218 * @return A DisplayList fopr the specified HardwareLayer 12219 */ 12220 private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) { 12221 DisplayList displayList = getDisplayList(layer.getDisplayList(), true); 12222 layer.setDisplayList(displayList); 12223 return displayList; 12224 } 12225 12226 12227 /** 12228 * <p>Returns a display list that can be used to draw this view again 12229 * without executing its draw method.</p> 12230 * 12231 * @return A DisplayList ready to replay, or null if caching is not enabled. 12232 * 12233 * @hide 12234 */ 12235 public DisplayList getDisplayList() { 12236 mDisplayList = getDisplayList(mDisplayList, false); 12237 return mDisplayList; 12238 } 12239 12240 /** 12241 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 12242 * 12243 * @return A non-scaled bitmap representing this view or null if cache is disabled. 12244 * 12245 * @see #getDrawingCache(boolean) 12246 */ 12247 public Bitmap getDrawingCache() { 12248 return getDrawingCache(false); 12249 } 12250 12251 /** 12252 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 12253 * is null when caching is disabled. If caching is enabled and the cache is not ready, 12254 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 12255 * draw from the cache when the cache is enabled. To benefit from the cache, you must 12256 * request the drawing cache by calling this method and draw it on screen if the 12257 * returned bitmap is not null.</p> 12258 * 12259 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 12260 * this method will create a bitmap of the same size as this view. Because this bitmap 12261 * will be drawn scaled by the parent ViewGroup, the result on screen might show 12262 * scaling artifacts. To avoid such artifacts, you should call this method by setting 12263 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 12264 * size than the view. This implies that your application must be able to handle this 12265 * size.</p> 12266 * 12267 * @param autoScale Indicates whether the generated bitmap should be scaled based on 12268 * the current density of the screen when the application is in compatibility 12269 * mode. 12270 * 12271 * @return A bitmap representing this view or null if cache is disabled. 12272 * 12273 * @see #setDrawingCacheEnabled(boolean) 12274 * @see #isDrawingCacheEnabled() 12275 * @see #buildDrawingCache(boolean) 12276 * @see #destroyDrawingCache() 12277 */ 12278 public Bitmap getDrawingCache(boolean autoScale) { 12279 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 12280 return null; 12281 } 12282 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 12283 buildDrawingCache(autoScale); 12284 } 12285 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 12286 } 12287 12288 /** 12289 * <p>Frees the resources used by the drawing cache. If you call 12290 * {@link #buildDrawingCache()} manually without calling 12291 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 12292 * should cleanup the cache with this method afterwards.</p> 12293 * 12294 * @see #setDrawingCacheEnabled(boolean) 12295 * @see #buildDrawingCache() 12296 * @see #getDrawingCache() 12297 */ 12298 public void destroyDrawingCache() { 12299 if (mDrawingCache != null) { 12300 mDrawingCache.recycle(); 12301 mDrawingCache = null; 12302 } 12303 if (mUnscaledDrawingCache != null) { 12304 mUnscaledDrawingCache.recycle(); 12305 mUnscaledDrawingCache = null; 12306 } 12307 } 12308 12309 /** 12310 * Setting a solid background color for the drawing cache's bitmaps will improve 12311 * performance and memory usage. Note, though that this should only be used if this 12312 * view will always be drawn on top of a solid color. 12313 * 12314 * @param color The background color to use for the drawing cache's bitmap 12315 * 12316 * @see #setDrawingCacheEnabled(boolean) 12317 * @see #buildDrawingCache() 12318 * @see #getDrawingCache() 12319 */ 12320 public void setDrawingCacheBackgroundColor(int color) { 12321 if (color != mDrawingCacheBackgroundColor) { 12322 mDrawingCacheBackgroundColor = color; 12323 mPrivateFlags &= ~DRAWING_CACHE_VALID; 12324 } 12325 } 12326 12327 /** 12328 * @see #setDrawingCacheBackgroundColor(int) 12329 * 12330 * @return The background color to used for the drawing cache's bitmap 12331 */ 12332 public int getDrawingCacheBackgroundColor() { 12333 return mDrawingCacheBackgroundColor; 12334 } 12335 12336 /** 12337 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 12338 * 12339 * @see #buildDrawingCache(boolean) 12340 */ 12341 public void buildDrawingCache() { 12342 buildDrawingCache(false); 12343 } 12344 12345 /** 12346 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 12347 * 12348 * <p>If you call {@link #buildDrawingCache()} manually without calling 12349 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 12350 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 12351 * 12352 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 12353 * this method will create a bitmap of the same size as this view. Because this bitmap 12354 * will be drawn scaled by the parent ViewGroup, the result on screen might show 12355 * scaling artifacts. To avoid such artifacts, you should call this method by setting 12356 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 12357 * size than the view. This implies that your application must be able to handle this 12358 * size.</p> 12359 * 12360 * <p>You should avoid calling this method when hardware acceleration is enabled. If 12361 * you do not need the drawing cache bitmap, calling this method will increase memory 12362 * usage and cause the view to be rendered in software once, thus negatively impacting 12363 * performance.</p> 12364 * 12365 * @see #getDrawingCache() 12366 * @see #destroyDrawingCache() 12367 */ 12368 public void buildDrawingCache(boolean autoScale) { 12369 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 12370 mDrawingCache == null : mUnscaledDrawingCache == null)) { 12371 mCachingFailed = false; 12372 12373 if (ViewDebug.TRACE_HIERARCHY) { 12374 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 12375 } 12376 12377 int width = mRight - mLeft; 12378 int height = mBottom - mTop; 12379 12380 final AttachInfo attachInfo = mAttachInfo; 12381 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 12382 12383 if (autoScale && scalingRequired) { 12384 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 12385 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 12386 } 12387 12388 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 12389 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 12390 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 12391 12392 if (width <= 0 || height <= 0 || 12393 // Projected bitmap size in bytes 12394 (width * height * (opaque && !use32BitCache ? 2 : 4) > 12395 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 12396 destroyDrawingCache(); 12397 mCachingFailed = true; 12398 return; 12399 } 12400 12401 boolean clear = true; 12402 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 12403 12404 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 12405 Bitmap.Config quality; 12406 if (!opaque) { 12407 // Never pick ARGB_4444 because it looks awful 12408 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 12409 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 12410 case DRAWING_CACHE_QUALITY_AUTO: 12411 quality = Bitmap.Config.ARGB_8888; 12412 break; 12413 case DRAWING_CACHE_QUALITY_LOW: 12414 quality = Bitmap.Config.ARGB_8888; 12415 break; 12416 case DRAWING_CACHE_QUALITY_HIGH: 12417 quality = Bitmap.Config.ARGB_8888; 12418 break; 12419 default: 12420 quality = Bitmap.Config.ARGB_8888; 12421 break; 12422 } 12423 } else { 12424 // Optimization for translucent windows 12425 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 12426 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 12427 } 12428 12429 // Try to cleanup memory 12430 if (bitmap != null) bitmap.recycle(); 12431 12432 try { 12433 bitmap = Bitmap.createBitmap(width, height, quality); 12434 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 12435 if (autoScale) { 12436 mDrawingCache = bitmap; 12437 } else { 12438 mUnscaledDrawingCache = bitmap; 12439 } 12440 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 12441 } catch (OutOfMemoryError e) { 12442 // If there is not enough memory to create the bitmap cache, just 12443 // ignore the issue as bitmap caches are not required to draw the 12444 // view hierarchy 12445 if (autoScale) { 12446 mDrawingCache = null; 12447 } else { 12448 mUnscaledDrawingCache = null; 12449 } 12450 mCachingFailed = true; 12451 return; 12452 } 12453 12454 clear = drawingCacheBackgroundColor != 0; 12455 } 12456 12457 Canvas canvas; 12458 if (attachInfo != null) { 12459 canvas = attachInfo.mCanvas; 12460 if (canvas == null) { 12461 canvas = new Canvas(); 12462 } 12463 canvas.setBitmap(bitmap); 12464 // Temporarily clobber the cached Canvas in case one of our children 12465 // is also using a drawing cache. Without this, the children would 12466 // steal the canvas by attaching their own bitmap to it and bad, bad 12467 // thing would happen (invisible views, corrupted drawings, etc.) 12468 attachInfo.mCanvas = null; 12469 } else { 12470 // This case should hopefully never or seldom happen 12471 canvas = new Canvas(bitmap); 12472 } 12473 12474 if (clear) { 12475 bitmap.eraseColor(drawingCacheBackgroundColor); 12476 } 12477 12478 computeScroll(); 12479 final int restoreCount = canvas.save(); 12480 12481 if (autoScale && scalingRequired) { 12482 final float scale = attachInfo.mApplicationScale; 12483 canvas.scale(scale, scale); 12484 } 12485 12486 canvas.translate(-mScrollX, -mScrollY); 12487 12488 mPrivateFlags |= DRAWN; 12489 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 12490 mLayerType != LAYER_TYPE_NONE) { 12491 mPrivateFlags |= DRAWING_CACHE_VALID; 12492 } 12493 12494 // Fast path for layouts with no backgrounds 12495 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 12496 if (ViewDebug.TRACE_HIERARCHY) { 12497 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 12498 } 12499 mPrivateFlags &= ~DIRTY_MASK; 12500 dispatchDraw(canvas); 12501 } else { 12502 draw(canvas); 12503 } 12504 12505 canvas.restoreToCount(restoreCount); 12506 canvas.setBitmap(null); 12507 12508 if (attachInfo != null) { 12509 // Restore the cached Canvas for our siblings 12510 attachInfo.mCanvas = canvas; 12511 } 12512 } 12513 } 12514 12515 /** 12516 * Create a snapshot of the view into a bitmap. We should probably make 12517 * some form of this public, but should think about the API. 12518 */ 12519 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 12520 int width = mRight - mLeft; 12521 int height = mBottom - mTop; 12522 12523 final AttachInfo attachInfo = mAttachInfo; 12524 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 12525 width = (int) ((width * scale) + 0.5f); 12526 height = (int) ((height * scale) + 0.5f); 12527 12528 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 12529 if (bitmap == null) { 12530 throw new OutOfMemoryError(); 12531 } 12532 12533 Resources resources = getResources(); 12534 if (resources != null) { 12535 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 12536 } 12537 12538 Canvas canvas; 12539 if (attachInfo != null) { 12540 canvas = attachInfo.mCanvas; 12541 if (canvas == null) { 12542 canvas = new Canvas(); 12543 } 12544 canvas.setBitmap(bitmap); 12545 // Temporarily clobber the cached Canvas in case one of our children 12546 // is also using a drawing cache. Without this, the children would 12547 // steal the canvas by attaching their own bitmap to it and bad, bad 12548 // things would happen (invisible views, corrupted drawings, etc.) 12549 attachInfo.mCanvas = null; 12550 } else { 12551 // This case should hopefully never or seldom happen 12552 canvas = new Canvas(bitmap); 12553 } 12554 12555 if ((backgroundColor & 0xff000000) != 0) { 12556 bitmap.eraseColor(backgroundColor); 12557 } 12558 12559 computeScroll(); 12560 final int restoreCount = canvas.save(); 12561 canvas.scale(scale, scale); 12562 canvas.translate(-mScrollX, -mScrollY); 12563 12564 // Temporarily remove the dirty mask 12565 int flags = mPrivateFlags; 12566 mPrivateFlags &= ~DIRTY_MASK; 12567 12568 // Fast path for layouts with no backgrounds 12569 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 12570 dispatchDraw(canvas); 12571 } else { 12572 draw(canvas); 12573 } 12574 12575 mPrivateFlags = flags; 12576 12577 canvas.restoreToCount(restoreCount); 12578 canvas.setBitmap(null); 12579 12580 if (attachInfo != null) { 12581 // Restore the cached Canvas for our siblings 12582 attachInfo.mCanvas = canvas; 12583 } 12584 12585 return bitmap; 12586 } 12587 12588 /** 12589 * Indicates whether this View is currently in edit mode. A View is usually 12590 * in edit mode when displayed within a developer tool. For instance, if 12591 * this View is being drawn by a visual user interface builder, this method 12592 * should return true. 12593 * 12594 * Subclasses should check the return value of this method to provide 12595 * different behaviors if their normal behavior might interfere with the 12596 * host environment. For instance: the class spawns a thread in its 12597 * constructor, the drawing code relies on device-specific features, etc. 12598 * 12599 * This method is usually checked in the drawing code of custom widgets. 12600 * 12601 * @return True if this View is in edit mode, false otherwise. 12602 */ 12603 public boolean isInEditMode() { 12604 return false; 12605 } 12606 12607 /** 12608 * If the View draws content inside its padding and enables fading edges, 12609 * it needs to support padding offsets. Padding offsets are added to the 12610 * fading edges to extend the length of the fade so that it covers pixels 12611 * drawn inside the padding. 12612 * 12613 * Subclasses of this class should override this method if they need 12614 * to draw content inside the padding. 12615 * 12616 * @return True if padding offset must be applied, false otherwise. 12617 * 12618 * @see #getLeftPaddingOffset() 12619 * @see #getRightPaddingOffset() 12620 * @see #getTopPaddingOffset() 12621 * @see #getBottomPaddingOffset() 12622 * 12623 * @since CURRENT 12624 */ 12625 protected boolean isPaddingOffsetRequired() { 12626 return false; 12627 } 12628 12629 /** 12630 * Amount by which to extend the left fading region. Called only when 12631 * {@link #isPaddingOffsetRequired()} returns true. 12632 * 12633 * @return The left padding offset in pixels. 12634 * 12635 * @see #isPaddingOffsetRequired() 12636 * 12637 * @since CURRENT 12638 */ 12639 protected int getLeftPaddingOffset() { 12640 return 0; 12641 } 12642 12643 /** 12644 * Amount by which to extend the right fading region. Called only when 12645 * {@link #isPaddingOffsetRequired()} returns true. 12646 * 12647 * @return The right padding offset in pixels. 12648 * 12649 * @see #isPaddingOffsetRequired() 12650 * 12651 * @since CURRENT 12652 */ 12653 protected int getRightPaddingOffset() { 12654 return 0; 12655 } 12656 12657 /** 12658 * Amount by which to extend the top fading region. Called only when 12659 * {@link #isPaddingOffsetRequired()} returns true. 12660 * 12661 * @return The top padding offset in pixels. 12662 * 12663 * @see #isPaddingOffsetRequired() 12664 * 12665 * @since CURRENT 12666 */ 12667 protected int getTopPaddingOffset() { 12668 return 0; 12669 } 12670 12671 /** 12672 * Amount by which to extend the bottom fading region. Called only when 12673 * {@link #isPaddingOffsetRequired()} returns true. 12674 * 12675 * @return The bottom padding offset in pixels. 12676 * 12677 * @see #isPaddingOffsetRequired() 12678 * 12679 * @since CURRENT 12680 */ 12681 protected int getBottomPaddingOffset() { 12682 return 0; 12683 } 12684 12685 /** 12686 * @hide 12687 * @param offsetRequired 12688 */ 12689 protected int getFadeTop(boolean offsetRequired) { 12690 int top = mPaddingTop; 12691 if (offsetRequired) top += getTopPaddingOffset(); 12692 return top; 12693 } 12694 12695 /** 12696 * @hide 12697 * @param offsetRequired 12698 */ 12699 protected int getFadeHeight(boolean offsetRequired) { 12700 int padding = mPaddingTop; 12701 if (offsetRequired) padding += getTopPaddingOffset(); 12702 return mBottom - mTop - mPaddingBottom - padding; 12703 } 12704 12705 /** 12706 * <p>Indicates whether this view is attached to a hardware accelerated 12707 * window or not.</p> 12708 * 12709 * <p>Even if this method returns true, it does not mean that every call 12710 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 12711 * accelerated {@link android.graphics.Canvas}. For instance, if this view 12712 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 12713 * window is hardware accelerated, 12714 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 12715 * return false, and this method will return true.</p> 12716 * 12717 * @return True if the view is attached to a window and the window is 12718 * hardware accelerated; false in any other case. 12719 */ 12720 public boolean isHardwareAccelerated() { 12721 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 12722 } 12723 12724 /** 12725 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 12726 * case of an active Animation being run on the view. 12727 */ 12728 private boolean drawAnimation(ViewGroup parent, long drawingTime, 12729 Animation a, boolean scalingRequired) { 12730 Transformation invalidationTransform; 12731 final int flags = parent.mGroupFlags; 12732 final boolean initialized = a.isInitialized(); 12733 if (!initialized) { 12734 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 12735 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 12736 onAnimationStart(); 12737 } 12738 12739 boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f); 12740 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 12741 if (parent.mInvalidationTransformation == null) { 12742 parent.mInvalidationTransformation = new Transformation(); 12743 } 12744 invalidationTransform = parent.mInvalidationTransformation; 12745 a.getTransformation(drawingTime, invalidationTransform, 1f); 12746 } else { 12747 invalidationTransform = parent.mChildTransformation; 12748 } 12749 if (more) { 12750 if (!a.willChangeBounds()) { 12751 if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) == 12752 parent.FLAG_OPTIMIZE_INVALIDATE) { 12753 parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED; 12754 } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) { 12755 // The child need to draw an animation, potentially offscreen, so 12756 // make sure we do not cancel invalidate requests 12757 parent.mPrivateFlags |= DRAW_ANIMATION; 12758 parent.invalidate(mLeft, mTop, mRight, mBottom); 12759 } 12760 } else { 12761 if (parent.mInvalidateRegion == null) { 12762 parent.mInvalidateRegion = new RectF(); 12763 } 12764 final RectF region = parent.mInvalidateRegion; 12765 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 12766 invalidationTransform); 12767 12768 // The child need to draw an animation, potentially offscreen, so 12769 // make sure we do not cancel invalidate requests 12770 parent.mPrivateFlags |= DRAW_ANIMATION; 12771 12772 final int left = mLeft + (int) region.left; 12773 final int top = mTop + (int) region.top; 12774 parent.invalidate(left, top, left + (int) (region.width() + .5f), 12775 top + (int) (region.height() + .5f)); 12776 } 12777 } 12778 return more; 12779 } 12780 12781 /** 12782 * This method is called by getDisplayList() when a display list is created or re-rendered. 12783 * It sets or resets the current value of all properties on that display list (resetting is 12784 * necessary when a display list is being re-created, because we need to make sure that 12785 * previously-set transform values 12786 */ 12787 void setDisplayListProperties(DisplayList displayList) { 12788 if (displayList != null) { 12789 displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 12790 displayList.setHasOverlappingRendering(hasOverlappingRendering()); 12791 if (mParent instanceof ViewGroup) { 12792 displayList.setClipChildren( 12793 (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 12794 } 12795 float alpha = 1; 12796 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 12797 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 12798 ViewGroup parentVG = (ViewGroup) mParent; 12799 final boolean hasTransform = 12800 parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation); 12801 if (hasTransform) { 12802 Transformation transform = parentVG.mChildTransformation; 12803 final int transformType = parentVG.mChildTransformation.getTransformationType(); 12804 if (transformType != Transformation.TYPE_IDENTITY) { 12805 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 12806 alpha = transform.getAlpha(); 12807 } 12808 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 12809 displayList.setStaticMatrix(transform.getMatrix()); 12810 } 12811 } 12812 } 12813 } 12814 if (mTransformationInfo != null) { 12815 alpha *= mTransformationInfo.mAlpha; 12816 if (alpha < 1) { 12817 final int multipliedAlpha = (int) (255 * alpha); 12818 if (onSetAlpha(multipliedAlpha)) { 12819 alpha = 1; 12820 } 12821 } 12822 displayList.setTransformationInfo(alpha, 12823 mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY, 12824 mTransformationInfo.mRotation, mTransformationInfo.mRotationX, 12825 mTransformationInfo.mRotationY, mTransformationInfo.mScaleX, 12826 mTransformationInfo.mScaleY); 12827 if (mTransformationInfo.mCamera == null) { 12828 mTransformationInfo.mCamera = new Camera(); 12829 mTransformationInfo.matrix3D = new Matrix(); 12830 } 12831 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ()); 12832 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) { 12833 displayList.setPivotX(getPivotX()); 12834 displayList.setPivotY(getPivotY()); 12835 } 12836 } else if (alpha < 1) { 12837 displayList.setAlpha(alpha); 12838 } 12839 } 12840 } 12841 12842 /** 12843 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 12844 * This draw() method is an implementation detail and is not intended to be overridden or 12845 * to be called from anywhere else other than ViewGroup.drawChild(). 12846 */ 12847 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 12848 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 12849 boolean more = false; 12850 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 12851 final int flags = parent.mGroupFlags; 12852 12853 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 12854 parent.mChildTransformation.clear(); 12855 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 12856 } 12857 12858 Transformation transformToApply = null; 12859 boolean concatMatrix = false; 12860 12861 boolean scalingRequired = false; 12862 boolean caching; 12863 int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE; 12864 12865 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 12866 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 12867 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 12868 caching = true; 12869 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 12870 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 12871 } else { 12872 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 12873 } 12874 12875 final Animation a = getAnimation(); 12876 if (a != null) { 12877 more = drawAnimation(parent, drawingTime, a, scalingRequired); 12878 concatMatrix = a.willChangeTransformationMatrix(); 12879 if (concatMatrix) { 12880 mPrivateFlags2 |= VIEW_IS_ANIMATING_TRANSFORM; 12881 } 12882 transformToApply = parent.mChildTransformation; 12883 } else { 12884 if ((mPrivateFlags2 & VIEW_IS_ANIMATING_TRANSFORM) == VIEW_IS_ANIMATING_TRANSFORM && 12885 mDisplayList != null) { 12886 // No longer animating: clear out old animation matrix 12887 mDisplayList.setAnimationMatrix(null); 12888 mPrivateFlags2 &= ~VIEW_IS_ANIMATING_TRANSFORM; 12889 } 12890 if (!useDisplayListProperties && 12891 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 12892 final boolean hasTransform = 12893 parent.getChildStaticTransformation(this, parent.mChildTransformation); 12894 if (hasTransform) { 12895 final int transformType = parent.mChildTransformation.getTransformationType(); 12896 transformToApply = transformType != Transformation.TYPE_IDENTITY ? 12897 parent.mChildTransformation : null; 12898 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 12899 } 12900 } 12901 } 12902 12903 concatMatrix |= !childHasIdentityMatrix; 12904 12905 // Sets the flag as early as possible to allow draw() implementations 12906 // to call invalidate() successfully when doing animations 12907 mPrivateFlags |= DRAWN; 12908 12909 if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 12910 (mPrivateFlags & DRAW_ANIMATION) == 0) { 12911 mPrivateFlags2 |= VIEW_QUICK_REJECTED; 12912 return more; 12913 } 12914 mPrivateFlags2 &= ~VIEW_QUICK_REJECTED; 12915 12916 if (hardwareAccelerated) { 12917 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 12918 // retain the flag's value temporarily in the mRecreateDisplayList flag 12919 mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED; 12920 mPrivateFlags &= ~INVALIDATED; 12921 } 12922 12923 computeScroll(); 12924 12925 final int sx = mScrollX; 12926 final int sy = mScrollY; 12927 12928 DisplayList displayList = null; 12929 Bitmap cache = null; 12930 boolean hasDisplayList = false; 12931 if (caching) { 12932 if (!hardwareAccelerated) { 12933 if (layerType != LAYER_TYPE_NONE) { 12934 layerType = LAYER_TYPE_SOFTWARE; 12935 buildDrawingCache(true); 12936 } 12937 cache = getDrawingCache(true); 12938 } else { 12939 switch (layerType) { 12940 case LAYER_TYPE_SOFTWARE: 12941 if (useDisplayListProperties) { 12942 hasDisplayList = canHaveDisplayList(); 12943 } else { 12944 buildDrawingCache(true); 12945 cache = getDrawingCache(true); 12946 } 12947 break; 12948 case LAYER_TYPE_HARDWARE: 12949 if (useDisplayListProperties) { 12950 hasDisplayList = canHaveDisplayList(); 12951 } 12952 break; 12953 case LAYER_TYPE_NONE: 12954 // Delay getting the display list until animation-driven alpha values are 12955 // set up and possibly passed on to the view 12956 hasDisplayList = canHaveDisplayList(); 12957 break; 12958 } 12959 } 12960 } 12961 useDisplayListProperties &= hasDisplayList; 12962 if (useDisplayListProperties) { 12963 displayList = getDisplayList(); 12964 if (!displayList.isValid()) { 12965 // Uncommon, but possible. If a view is removed from the hierarchy during the call 12966 // to getDisplayList(), the display list will be marked invalid and we should not 12967 // try to use it again. 12968 displayList = null; 12969 hasDisplayList = false; 12970 useDisplayListProperties = false; 12971 } 12972 } 12973 12974 final boolean hasNoCache = cache == null || hasDisplayList; 12975 final boolean offsetForScroll = cache == null && !hasDisplayList && 12976 layerType != LAYER_TYPE_HARDWARE; 12977 12978 int restoreTo = -1; 12979 if (!useDisplayListProperties || transformToApply != null) { 12980 restoreTo = canvas.save(); 12981 } 12982 if (offsetForScroll) { 12983 canvas.translate(mLeft - sx, mTop - sy); 12984 } else { 12985 if (!useDisplayListProperties) { 12986 canvas.translate(mLeft, mTop); 12987 } 12988 if (scalingRequired) { 12989 if (useDisplayListProperties) { 12990 // TODO: Might not need this if we put everything inside the DL 12991 restoreTo = canvas.save(); 12992 } 12993 // mAttachInfo cannot be null, otherwise scalingRequired == false 12994 final float scale = 1.0f / mAttachInfo.mApplicationScale; 12995 canvas.scale(scale, scale); 12996 } 12997 } 12998 12999 float alpha = useDisplayListProperties ? 1 : getAlpha(); 13000 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) { 13001 if (transformToApply != null || !childHasIdentityMatrix) { 13002 int transX = 0; 13003 int transY = 0; 13004 13005 if (offsetForScroll) { 13006 transX = -sx; 13007 transY = -sy; 13008 } 13009 13010 if (transformToApply != null) { 13011 if (concatMatrix) { 13012 if (useDisplayListProperties) { 13013 displayList.setAnimationMatrix(transformToApply.getMatrix()); 13014 } else { 13015 // Undo the scroll translation, apply the transformation matrix, 13016 // then redo the scroll translate to get the correct result. 13017 canvas.translate(-transX, -transY); 13018 canvas.concat(transformToApply.getMatrix()); 13019 canvas.translate(transX, transY); 13020 } 13021 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13022 } 13023 13024 float transformAlpha = transformToApply.getAlpha(); 13025 if (transformAlpha < 1) { 13026 alpha *= transformToApply.getAlpha(); 13027 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13028 } 13029 } 13030 13031 if (!childHasIdentityMatrix && !useDisplayListProperties) { 13032 canvas.translate(-transX, -transY); 13033 canvas.concat(getMatrix()); 13034 canvas.translate(transX, transY); 13035 } 13036 } 13037 13038 if (alpha < 1) { 13039 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13040 if (hasNoCache) { 13041 final int multipliedAlpha = (int) (255 * alpha); 13042 if (!onSetAlpha(multipliedAlpha)) { 13043 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 13044 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 13045 layerType != LAYER_TYPE_NONE) { 13046 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 13047 } 13048 if (useDisplayListProperties) { 13049 displayList.setAlpha(alpha * getAlpha()); 13050 } else if (layerType == LAYER_TYPE_NONE) { 13051 final int scrollX = hasDisplayList ? 0 : sx; 13052 final int scrollY = hasDisplayList ? 0 : sy; 13053 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 13054 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 13055 } 13056 } else { 13057 // Alpha is handled by the child directly, clobber the layer's alpha 13058 mPrivateFlags |= ALPHA_SET; 13059 } 13060 } 13061 } 13062 } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) { 13063 onSetAlpha(255); 13064 mPrivateFlags &= ~ALPHA_SET; 13065 } 13066 13067 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 13068 !useDisplayListProperties) { 13069 if (offsetForScroll) { 13070 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 13071 } else { 13072 if (!scalingRequired || cache == null) { 13073 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 13074 } else { 13075 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 13076 } 13077 } 13078 } 13079 13080 if (!useDisplayListProperties && hasDisplayList) { 13081 displayList = getDisplayList(); 13082 if (!displayList.isValid()) { 13083 // Uncommon, but possible. If a view is removed from the hierarchy during the call 13084 // to getDisplayList(), the display list will be marked invalid and we should not 13085 // try to use it again. 13086 displayList = null; 13087 hasDisplayList = false; 13088 } 13089 } 13090 13091 if (hasNoCache) { 13092 boolean layerRendered = false; 13093 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 13094 final HardwareLayer layer = getHardwareLayer(); 13095 if (layer != null && layer.isValid()) { 13096 mLayerPaint.setAlpha((int) (alpha * 255)); 13097 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 13098 layerRendered = true; 13099 } else { 13100 final int scrollX = hasDisplayList ? 0 : sx; 13101 final int scrollY = hasDisplayList ? 0 : sy; 13102 canvas.saveLayer(scrollX, scrollY, 13103 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 13104 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13105 } 13106 } 13107 13108 if (!layerRendered) { 13109 if (!hasDisplayList) { 13110 // Fast path for layouts with no backgrounds 13111 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 13112 if (ViewDebug.TRACE_HIERARCHY) { 13113 ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW); 13114 } 13115 mPrivateFlags &= ~DIRTY_MASK; 13116 dispatchDraw(canvas); 13117 } else { 13118 draw(canvas); 13119 } 13120 } else { 13121 mPrivateFlags &= ~DIRTY_MASK; 13122 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 13123 } 13124 } 13125 } else if (cache != null) { 13126 mPrivateFlags &= ~DIRTY_MASK; 13127 Paint cachePaint; 13128 13129 if (layerType == LAYER_TYPE_NONE) { 13130 cachePaint = parent.mCachePaint; 13131 if (cachePaint == null) { 13132 cachePaint = new Paint(); 13133 cachePaint.setDither(false); 13134 parent.mCachePaint = cachePaint; 13135 } 13136 if (alpha < 1) { 13137 cachePaint.setAlpha((int) (alpha * 255)); 13138 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 13139 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 13140 cachePaint.setAlpha(255); 13141 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 13142 } 13143 } else { 13144 cachePaint = mLayerPaint; 13145 cachePaint.setAlpha((int) (alpha * 255)); 13146 } 13147 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 13148 } 13149 13150 if (restoreTo >= 0) { 13151 canvas.restoreToCount(restoreTo); 13152 } 13153 13154 if (a != null && !more) { 13155 if (!hardwareAccelerated && !a.getFillAfter()) { 13156 onSetAlpha(255); 13157 } 13158 parent.finishAnimatingView(this, a); 13159 } 13160 13161 if (more && hardwareAccelerated) { 13162 // invalidation is the trigger to recreate display lists, so if we're using 13163 // display lists to render, force an invalidate to allow the animation to 13164 // continue drawing another frame 13165 parent.invalidate(true); 13166 if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) { 13167 // alpha animations should cause the child to recreate its display list 13168 invalidate(true); 13169 } 13170 } 13171 13172 mRecreateDisplayList = false; 13173 13174 return more; 13175 } 13176 13177 /** 13178 * Manually render this view (and all of its children) to the given Canvas. 13179 * The view must have already done a full layout before this function is 13180 * called. When implementing a view, implement 13181 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 13182 * If you do need to override this method, call the superclass version. 13183 * 13184 * @param canvas The Canvas to which the View is rendered. 13185 */ 13186 public void draw(Canvas canvas) { 13187 if (ViewDebug.TRACE_HIERARCHY) { 13188 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 13189 } 13190 13191 final int privateFlags = mPrivateFlags; 13192 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 13193 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 13194 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 13195 13196 /* 13197 * Draw traversal performs several drawing steps which must be executed 13198 * in the appropriate order: 13199 * 13200 * 1. Draw the background 13201 * 2. If necessary, save the canvas' layers to prepare for fading 13202 * 3. Draw view's content 13203 * 4. Draw children 13204 * 5. If necessary, draw the fading edges and restore layers 13205 * 6. Draw decorations (scrollbars for instance) 13206 */ 13207 13208 // Step 1, draw the background, if needed 13209 int saveCount; 13210 13211 if (!dirtyOpaque) { 13212 final Drawable background = mBackground; 13213 if (background != null) { 13214 final int scrollX = mScrollX; 13215 final int scrollY = mScrollY; 13216 13217 if (mBackgroundSizeChanged) { 13218 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 13219 mBackgroundSizeChanged = false; 13220 } 13221 13222 if ((scrollX | scrollY) == 0) { 13223 background.draw(canvas); 13224 } else { 13225 canvas.translate(scrollX, scrollY); 13226 background.draw(canvas); 13227 canvas.translate(-scrollX, -scrollY); 13228 } 13229 } 13230 } 13231 13232 // skip step 2 & 5 if possible (common case) 13233 final int viewFlags = mViewFlags; 13234 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 13235 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 13236 if (!verticalEdges && !horizontalEdges) { 13237 // Step 3, draw the content 13238 if (!dirtyOpaque) onDraw(canvas); 13239 13240 // Step 4, draw the children 13241 dispatchDraw(canvas); 13242 13243 // Step 6, draw decorations (scrollbars) 13244 onDrawScrollBars(canvas); 13245 13246 // we're done... 13247 return; 13248 } 13249 13250 /* 13251 * Here we do the full fledged routine... 13252 * (this is an uncommon case where speed matters less, 13253 * this is why we repeat some of the tests that have been 13254 * done above) 13255 */ 13256 13257 boolean drawTop = false; 13258 boolean drawBottom = false; 13259 boolean drawLeft = false; 13260 boolean drawRight = false; 13261 13262 float topFadeStrength = 0.0f; 13263 float bottomFadeStrength = 0.0f; 13264 float leftFadeStrength = 0.0f; 13265 float rightFadeStrength = 0.0f; 13266 13267 // Step 2, save the canvas' layers 13268 int paddingLeft = mPaddingLeft; 13269 13270 final boolean offsetRequired = isPaddingOffsetRequired(); 13271 if (offsetRequired) { 13272 paddingLeft += getLeftPaddingOffset(); 13273 } 13274 13275 int left = mScrollX + paddingLeft; 13276 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 13277 int top = mScrollY + getFadeTop(offsetRequired); 13278 int bottom = top + getFadeHeight(offsetRequired); 13279 13280 if (offsetRequired) { 13281 right += getRightPaddingOffset(); 13282 bottom += getBottomPaddingOffset(); 13283 } 13284 13285 final ScrollabilityCache scrollabilityCache = mScrollCache; 13286 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 13287 int length = (int) fadeHeight; 13288 13289 // clip the fade length if top and bottom fades overlap 13290 // overlapping fades produce odd-looking artifacts 13291 if (verticalEdges && (top + length > bottom - length)) { 13292 length = (bottom - top) / 2; 13293 } 13294 13295 // also clip horizontal fades if necessary 13296 if (horizontalEdges && (left + length > right - length)) { 13297 length = (right - left) / 2; 13298 } 13299 13300 if (verticalEdges) { 13301 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 13302 drawTop = topFadeStrength * fadeHeight > 1.0f; 13303 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 13304 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 13305 } 13306 13307 if (horizontalEdges) { 13308 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 13309 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 13310 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 13311 drawRight = rightFadeStrength * fadeHeight > 1.0f; 13312 } 13313 13314 saveCount = canvas.getSaveCount(); 13315 13316 int solidColor = getSolidColor(); 13317 if (solidColor == 0) { 13318 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 13319 13320 if (drawTop) { 13321 canvas.saveLayer(left, top, right, top + length, null, flags); 13322 } 13323 13324 if (drawBottom) { 13325 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 13326 } 13327 13328 if (drawLeft) { 13329 canvas.saveLayer(left, top, left + length, bottom, null, flags); 13330 } 13331 13332 if (drawRight) { 13333 canvas.saveLayer(right - length, top, right, bottom, null, flags); 13334 } 13335 } else { 13336 scrollabilityCache.setFadeColor(solidColor); 13337 } 13338 13339 // Step 3, draw the content 13340 if (!dirtyOpaque) onDraw(canvas); 13341 13342 // Step 4, draw the children 13343 dispatchDraw(canvas); 13344 13345 // Step 5, draw the fade effect and restore layers 13346 final Paint p = scrollabilityCache.paint; 13347 final Matrix matrix = scrollabilityCache.matrix; 13348 final Shader fade = scrollabilityCache.shader; 13349 13350 if (drawTop) { 13351 matrix.setScale(1, fadeHeight * topFadeStrength); 13352 matrix.postTranslate(left, top); 13353 fade.setLocalMatrix(matrix); 13354 canvas.drawRect(left, top, right, top + length, p); 13355 } 13356 13357 if (drawBottom) { 13358 matrix.setScale(1, fadeHeight * bottomFadeStrength); 13359 matrix.postRotate(180); 13360 matrix.postTranslate(left, bottom); 13361 fade.setLocalMatrix(matrix); 13362 canvas.drawRect(left, bottom - length, right, bottom, p); 13363 } 13364 13365 if (drawLeft) { 13366 matrix.setScale(1, fadeHeight * leftFadeStrength); 13367 matrix.postRotate(-90); 13368 matrix.postTranslate(left, top); 13369 fade.setLocalMatrix(matrix); 13370 canvas.drawRect(left, top, left + length, bottom, p); 13371 } 13372 13373 if (drawRight) { 13374 matrix.setScale(1, fadeHeight * rightFadeStrength); 13375 matrix.postRotate(90); 13376 matrix.postTranslate(right, top); 13377 fade.setLocalMatrix(matrix); 13378 canvas.drawRect(right - length, top, right, bottom, p); 13379 } 13380 13381 canvas.restoreToCount(saveCount); 13382 13383 // Step 6, draw decorations (scrollbars) 13384 onDrawScrollBars(canvas); 13385 } 13386 13387 /** 13388 * Override this if your view is known to always be drawn on top of a solid color background, 13389 * and needs to draw fading edges. Returning a non-zero color enables the view system to 13390 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 13391 * should be set to 0xFF. 13392 * 13393 * @see #setVerticalFadingEdgeEnabled(boolean) 13394 * @see #setHorizontalFadingEdgeEnabled(boolean) 13395 * 13396 * @return The known solid color background for this view, or 0 if the color may vary 13397 */ 13398 @ViewDebug.ExportedProperty(category = "drawing") 13399 public int getSolidColor() { 13400 return 0; 13401 } 13402 13403 /** 13404 * Build a human readable string representation of the specified view flags. 13405 * 13406 * @param flags the view flags to convert to a string 13407 * @return a String representing the supplied flags 13408 */ 13409 private static String printFlags(int flags) { 13410 String output = ""; 13411 int numFlags = 0; 13412 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 13413 output += "TAKES_FOCUS"; 13414 numFlags++; 13415 } 13416 13417 switch (flags & VISIBILITY_MASK) { 13418 case INVISIBLE: 13419 if (numFlags > 0) { 13420 output += " "; 13421 } 13422 output += "INVISIBLE"; 13423 // USELESS HERE numFlags++; 13424 break; 13425 case GONE: 13426 if (numFlags > 0) { 13427 output += " "; 13428 } 13429 output += "GONE"; 13430 // USELESS HERE numFlags++; 13431 break; 13432 default: 13433 break; 13434 } 13435 return output; 13436 } 13437 13438 /** 13439 * Build a human readable string representation of the specified private 13440 * view flags. 13441 * 13442 * @param privateFlags the private view flags to convert to a string 13443 * @return a String representing the supplied flags 13444 */ 13445 private static String printPrivateFlags(int privateFlags) { 13446 String output = ""; 13447 int numFlags = 0; 13448 13449 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 13450 output += "WANTS_FOCUS"; 13451 numFlags++; 13452 } 13453 13454 if ((privateFlags & FOCUSED) == FOCUSED) { 13455 if (numFlags > 0) { 13456 output += " "; 13457 } 13458 output += "FOCUSED"; 13459 numFlags++; 13460 } 13461 13462 if ((privateFlags & SELECTED) == SELECTED) { 13463 if (numFlags > 0) { 13464 output += " "; 13465 } 13466 output += "SELECTED"; 13467 numFlags++; 13468 } 13469 13470 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 13471 if (numFlags > 0) { 13472 output += " "; 13473 } 13474 output += "IS_ROOT_NAMESPACE"; 13475 numFlags++; 13476 } 13477 13478 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 13479 if (numFlags > 0) { 13480 output += " "; 13481 } 13482 output += "HAS_BOUNDS"; 13483 numFlags++; 13484 } 13485 13486 if ((privateFlags & DRAWN) == DRAWN) { 13487 if (numFlags > 0) { 13488 output += " "; 13489 } 13490 output += "DRAWN"; 13491 // USELESS HERE numFlags++; 13492 } 13493 return output; 13494 } 13495 13496 /** 13497 * <p>Indicates whether or not this view's layout will be requested during 13498 * the next hierarchy layout pass.</p> 13499 * 13500 * @return true if the layout will be forced during next layout pass 13501 */ 13502 public boolean isLayoutRequested() { 13503 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 13504 } 13505 13506 /** 13507 * Assign a size and position to a view and all of its 13508 * descendants 13509 * 13510 * <p>This is the second phase of the layout mechanism. 13511 * (The first is measuring). In this phase, each parent calls 13512 * layout on all of its children to position them. 13513 * This is typically done using the child measurements 13514 * that were stored in the measure pass().</p> 13515 * 13516 * <p>Derived classes should not override this method. 13517 * Derived classes with children should override 13518 * onLayout. In that method, they should 13519 * call layout on each of their children.</p> 13520 * 13521 * @param l Left position, relative to parent 13522 * @param t Top position, relative to parent 13523 * @param r Right position, relative to parent 13524 * @param b Bottom position, relative to parent 13525 */ 13526 @SuppressWarnings({"unchecked"}) 13527 public void layout(int l, int t, int r, int b) { 13528 int oldL = mLeft; 13529 int oldT = mTop; 13530 int oldB = mBottom; 13531 int oldR = mRight; 13532 boolean changed = setFrame(l, t, r, b); 13533 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 13534 if (ViewDebug.TRACE_HIERARCHY) { 13535 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 13536 } 13537 13538 onLayout(changed, l, t, r, b); 13539 mPrivateFlags &= ~LAYOUT_REQUIRED; 13540 13541 ListenerInfo li = mListenerInfo; 13542 if (li != null && li.mOnLayoutChangeListeners != null) { 13543 ArrayList<OnLayoutChangeListener> listenersCopy = 13544 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 13545 int numListeners = listenersCopy.size(); 13546 for (int i = 0; i < numListeners; ++i) { 13547 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 13548 } 13549 } 13550 } 13551 mPrivateFlags &= ~FORCE_LAYOUT; 13552 } 13553 13554 /** 13555 * Called from layout when this view should 13556 * assign a size and position to each of its children. 13557 * 13558 * Derived classes with children should override 13559 * this method and call layout on each of 13560 * their children. 13561 * @param changed This is a new size or position for this view 13562 * @param left Left position, relative to parent 13563 * @param top Top position, relative to parent 13564 * @param right Right position, relative to parent 13565 * @param bottom Bottom position, relative to parent 13566 */ 13567 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 13568 } 13569 13570 /** 13571 * Assign a size and position to this view. 13572 * 13573 * This is called from layout. 13574 * 13575 * @param left Left position, relative to parent 13576 * @param top Top position, relative to parent 13577 * @param right Right position, relative to parent 13578 * @param bottom Bottom position, relative to parent 13579 * @return true if the new size and position are different than the 13580 * previous ones 13581 * {@hide} 13582 */ 13583 protected boolean setFrame(int left, int top, int right, int bottom) { 13584 boolean changed = false; 13585 13586 if (DBG) { 13587 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 13588 + right + "," + bottom + ")"); 13589 } 13590 13591 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 13592 changed = true; 13593 13594 // Remember our drawn bit 13595 int drawn = mPrivateFlags & DRAWN; 13596 13597 int oldWidth = mRight - mLeft; 13598 int oldHeight = mBottom - mTop; 13599 int newWidth = right - left; 13600 int newHeight = bottom - top; 13601 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 13602 13603 // Invalidate our old position 13604 invalidate(sizeChanged); 13605 13606 mLeft = left; 13607 mTop = top; 13608 mRight = right; 13609 mBottom = bottom; 13610 if (mDisplayList != null) { 13611 mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 13612 } 13613 13614 mPrivateFlags |= HAS_BOUNDS; 13615 13616 13617 if (sizeChanged) { 13618 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 13619 // A change in dimension means an auto-centered pivot point changes, too 13620 if (mTransformationInfo != null) { 13621 mTransformationInfo.mMatrixDirty = true; 13622 } 13623 } 13624 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 13625 } 13626 13627 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 13628 // If we are visible, force the DRAWN bit to on so that 13629 // this invalidate will go through (at least to our parent). 13630 // This is because someone may have invalidated this view 13631 // before this call to setFrame came in, thereby clearing 13632 // the DRAWN bit. 13633 mPrivateFlags |= DRAWN; 13634 invalidate(sizeChanged); 13635 // parent display list may need to be recreated based on a change in the bounds 13636 // of any child 13637 invalidateParentCaches(); 13638 } 13639 13640 // Reset drawn bit to original value (invalidate turns it off) 13641 mPrivateFlags |= drawn; 13642 13643 mBackgroundSizeChanged = true; 13644 } 13645 return changed; 13646 } 13647 13648 /** 13649 * Finalize inflating a view from XML. This is called as the last phase 13650 * of inflation, after all child views have been added. 13651 * 13652 * <p>Even if the subclass overrides onFinishInflate, they should always be 13653 * sure to call the super method, so that we get called. 13654 */ 13655 protected void onFinishInflate() { 13656 } 13657 13658 /** 13659 * Returns the resources associated with this view. 13660 * 13661 * @return Resources object. 13662 */ 13663 public Resources getResources() { 13664 return mResources; 13665 } 13666 13667 /** 13668 * Invalidates the specified Drawable. 13669 * 13670 * @param drawable the drawable to invalidate 13671 */ 13672 public void invalidateDrawable(Drawable drawable) { 13673 if (verifyDrawable(drawable)) { 13674 final Rect dirty = drawable.getBounds(); 13675 final int scrollX = mScrollX; 13676 final int scrollY = mScrollY; 13677 13678 invalidate(dirty.left + scrollX, dirty.top + scrollY, 13679 dirty.right + scrollX, dirty.bottom + scrollY); 13680 } 13681 } 13682 13683 /** 13684 * Schedules an action on a drawable to occur at a specified time. 13685 * 13686 * @param who the recipient of the action 13687 * @param what the action to run on the drawable 13688 * @param when the time at which the action must occur. Uses the 13689 * {@link SystemClock#uptimeMillis} timebase. 13690 */ 13691 public void scheduleDrawable(Drawable who, Runnable what, long when) { 13692 if (verifyDrawable(who) && what != null) { 13693 final long delay = when - SystemClock.uptimeMillis(); 13694 if (mAttachInfo != null) { 13695 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 13696 Choreographer.CALLBACK_ANIMATION, what, who, 13697 Choreographer.subtractFrameDelay(delay)); 13698 } else { 13699 ViewRootImpl.getRunQueue().postDelayed(what, delay); 13700 } 13701 } 13702 } 13703 13704 /** 13705 * Cancels a scheduled action on a drawable. 13706 * 13707 * @param who the recipient of the action 13708 * @param what the action to cancel 13709 */ 13710 public void unscheduleDrawable(Drawable who, Runnable what) { 13711 if (verifyDrawable(who) && what != null) { 13712 if (mAttachInfo != null) { 13713 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 13714 Choreographer.CALLBACK_ANIMATION, what, who); 13715 } else { 13716 ViewRootImpl.getRunQueue().removeCallbacks(what); 13717 } 13718 } 13719 } 13720 13721 /** 13722 * Unschedule any events associated with the given Drawable. This can be 13723 * used when selecting a new Drawable into a view, so that the previous 13724 * one is completely unscheduled. 13725 * 13726 * @param who The Drawable to unschedule. 13727 * 13728 * @see #drawableStateChanged 13729 */ 13730 public void unscheduleDrawable(Drawable who) { 13731 if (mAttachInfo != null && who != null) { 13732 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 13733 Choreographer.CALLBACK_ANIMATION, null, who); 13734 } 13735 } 13736 13737 /** 13738 * Return the layout direction of a given Drawable. 13739 * 13740 * @param who the Drawable to query 13741 * @hide 13742 */ 13743 public int getResolvedLayoutDirection(Drawable who) { 13744 return (who == mBackground) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT; 13745 } 13746 13747 /** 13748 * If your view subclass is displaying its own Drawable objects, it should 13749 * override this function and return true for any Drawable it is 13750 * displaying. This allows animations for those drawables to be 13751 * scheduled. 13752 * 13753 * <p>Be sure to call through to the super class when overriding this 13754 * function. 13755 * 13756 * @param who The Drawable to verify. Return true if it is one you are 13757 * displaying, else return the result of calling through to the 13758 * super class. 13759 * 13760 * @return boolean If true than the Drawable is being displayed in the 13761 * view; else false and it is not allowed to animate. 13762 * 13763 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 13764 * @see #drawableStateChanged() 13765 */ 13766 protected boolean verifyDrawable(Drawable who) { 13767 return who == mBackground; 13768 } 13769 13770 /** 13771 * This function is called whenever the state of the view changes in such 13772 * a way that it impacts the state of drawables being shown. 13773 * 13774 * <p>Be sure to call through to the superclass when overriding this 13775 * function. 13776 * 13777 * @see Drawable#setState(int[]) 13778 */ 13779 protected void drawableStateChanged() { 13780 Drawable d = mBackground; 13781 if (d != null && d.isStateful()) { 13782 d.setState(getDrawableState()); 13783 } 13784 } 13785 13786 /** 13787 * Call this to force a view to update its drawable state. This will cause 13788 * drawableStateChanged to be called on this view. Views that are interested 13789 * in the new state should call getDrawableState. 13790 * 13791 * @see #drawableStateChanged 13792 * @see #getDrawableState 13793 */ 13794 public void refreshDrawableState() { 13795 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 13796 drawableStateChanged(); 13797 13798 ViewParent parent = mParent; 13799 if (parent != null) { 13800 parent.childDrawableStateChanged(this); 13801 } 13802 } 13803 13804 /** 13805 * Return an array of resource IDs of the drawable states representing the 13806 * current state of the view. 13807 * 13808 * @return The current drawable state 13809 * 13810 * @see Drawable#setState(int[]) 13811 * @see #drawableStateChanged() 13812 * @see #onCreateDrawableState(int) 13813 */ 13814 public final int[] getDrawableState() { 13815 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 13816 return mDrawableState; 13817 } else { 13818 mDrawableState = onCreateDrawableState(0); 13819 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 13820 return mDrawableState; 13821 } 13822 } 13823 13824 /** 13825 * Generate the new {@link android.graphics.drawable.Drawable} state for 13826 * this view. This is called by the view 13827 * system when the cached Drawable state is determined to be invalid. To 13828 * retrieve the current state, you should use {@link #getDrawableState}. 13829 * 13830 * @param extraSpace if non-zero, this is the number of extra entries you 13831 * would like in the returned array in which you can place your own 13832 * states. 13833 * 13834 * @return Returns an array holding the current {@link Drawable} state of 13835 * the view. 13836 * 13837 * @see #mergeDrawableStates(int[], int[]) 13838 */ 13839 protected int[] onCreateDrawableState(int extraSpace) { 13840 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 13841 mParent instanceof View) { 13842 return ((View) mParent).onCreateDrawableState(extraSpace); 13843 } 13844 13845 int[] drawableState; 13846 13847 int privateFlags = mPrivateFlags; 13848 13849 int viewStateIndex = 0; 13850 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 13851 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 13852 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 13853 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 13854 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 13855 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 13856 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 13857 HardwareRenderer.isAvailable()) { 13858 // This is set if HW acceleration is requested, even if the current 13859 // process doesn't allow it. This is just to allow app preview 13860 // windows to better match their app. 13861 viewStateIndex |= VIEW_STATE_ACCELERATED; 13862 } 13863 if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 13864 13865 final int privateFlags2 = mPrivateFlags2; 13866 if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 13867 if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 13868 13869 drawableState = VIEW_STATE_SETS[viewStateIndex]; 13870 13871 //noinspection ConstantIfStatement 13872 if (false) { 13873 Log.i("View", "drawableStateIndex=" + viewStateIndex); 13874 Log.i("View", toString() 13875 + " pressed=" + ((privateFlags & PRESSED) != 0) 13876 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 13877 + " fo=" + hasFocus() 13878 + " sl=" + ((privateFlags & SELECTED) != 0) 13879 + " wf=" + hasWindowFocus() 13880 + ": " + Arrays.toString(drawableState)); 13881 } 13882 13883 if (extraSpace == 0) { 13884 return drawableState; 13885 } 13886 13887 final int[] fullState; 13888 if (drawableState != null) { 13889 fullState = new int[drawableState.length + extraSpace]; 13890 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 13891 } else { 13892 fullState = new int[extraSpace]; 13893 } 13894 13895 return fullState; 13896 } 13897 13898 /** 13899 * Merge your own state values in <var>additionalState</var> into the base 13900 * state values <var>baseState</var> that were returned by 13901 * {@link #onCreateDrawableState(int)}. 13902 * 13903 * @param baseState The base state values returned by 13904 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 13905 * own additional state values. 13906 * 13907 * @param additionalState The additional state values you would like 13908 * added to <var>baseState</var>; this array is not modified. 13909 * 13910 * @return As a convenience, the <var>baseState</var> array you originally 13911 * passed into the function is returned. 13912 * 13913 * @see #onCreateDrawableState(int) 13914 */ 13915 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 13916 final int N = baseState.length; 13917 int i = N - 1; 13918 while (i >= 0 && baseState[i] == 0) { 13919 i--; 13920 } 13921 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 13922 return baseState; 13923 } 13924 13925 /** 13926 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 13927 * on all Drawable objects associated with this view. 13928 */ 13929 public void jumpDrawablesToCurrentState() { 13930 if (mBackground != null) { 13931 mBackground.jumpToCurrentState(); 13932 } 13933 } 13934 13935 /** 13936 * Sets the background color for this view. 13937 * @param color the color of the background 13938 */ 13939 @RemotableViewMethod 13940 public void setBackgroundColor(int color) { 13941 if (mBackground instanceof ColorDrawable) { 13942 ((ColorDrawable) mBackground).setColor(color); 13943 } else { 13944 setBackground(new ColorDrawable(color)); 13945 } 13946 } 13947 13948 /** 13949 * Set the background to a given resource. The resource should refer to 13950 * a Drawable object or 0 to remove the background. 13951 * @param resid The identifier of the resource. 13952 * 13953 * @attr ref android.R.styleable#View_background 13954 */ 13955 @RemotableViewMethod 13956 public void setBackgroundResource(int resid) { 13957 if (resid != 0 && resid == mBackgroundResource) { 13958 return; 13959 } 13960 13961 Drawable d= null; 13962 if (resid != 0) { 13963 d = mResources.getDrawable(resid); 13964 } 13965 setBackground(d); 13966 13967 mBackgroundResource = resid; 13968 } 13969 13970 /** 13971 * Set the background to a given Drawable, or remove the background. If the 13972 * background has padding, this View's padding is set to the background's 13973 * padding. However, when a background is removed, this View's padding isn't 13974 * touched. If setting the padding is desired, please use 13975 * {@link #setPadding(int, int, int, int)}. 13976 * 13977 * @param background The Drawable to use as the background, or null to remove the 13978 * background 13979 */ 13980 public void setBackground(Drawable background) { 13981 //noinspection deprecation 13982 setBackgroundDrawable(background); 13983 } 13984 13985 /** 13986 * @deprecated use {@link #setBackground(Drawable)} instead 13987 */ 13988 @Deprecated 13989 public void setBackgroundDrawable(Drawable background) { 13990 if (background == mBackground) { 13991 return; 13992 } 13993 13994 boolean requestLayout = false; 13995 13996 mBackgroundResource = 0; 13997 13998 /* 13999 * Regardless of whether we're setting a new background or not, we want 14000 * to clear the previous drawable. 14001 */ 14002 if (mBackground != null) { 14003 mBackground.setCallback(null); 14004 unscheduleDrawable(mBackground); 14005 } 14006 14007 if (background != null) { 14008 Rect padding = sThreadLocal.get(); 14009 if (padding == null) { 14010 padding = new Rect(); 14011 sThreadLocal.set(padding); 14012 } 14013 if (background.getPadding(padding)) { 14014 switch (background.getResolvedLayoutDirectionSelf()) { 14015 case LAYOUT_DIRECTION_RTL: 14016 setPadding(padding.right, padding.top, padding.left, padding.bottom); 14017 break; 14018 case LAYOUT_DIRECTION_LTR: 14019 default: 14020 setPadding(padding.left, padding.top, padding.right, padding.bottom); 14021 } 14022 } 14023 14024 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 14025 // if it has a different minimum size, we should layout again 14026 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 14027 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 14028 requestLayout = true; 14029 } 14030 14031 background.setCallback(this); 14032 if (background.isStateful()) { 14033 background.setState(getDrawableState()); 14034 } 14035 background.setVisible(getVisibility() == VISIBLE, false); 14036 mBackground = background; 14037 14038 if ((mPrivateFlags & SKIP_DRAW) != 0) { 14039 mPrivateFlags &= ~SKIP_DRAW; 14040 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 14041 requestLayout = true; 14042 } 14043 } else { 14044 /* Remove the background */ 14045 mBackground = null; 14046 14047 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 14048 /* 14049 * This view ONLY drew the background before and we're removing 14050 * the background, so now it won't draw anything 14051 * (hence we SKIP_DRAW) 14052 */ 14053 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 14054 mPrivateFlags |= SKIP_DRAW; 14055 } 14056 14057 /* 14058 * When the background is set, we try to apply its padding to this 14059 * View. When the background is removed, we don't touch this View's 14060 * padding. This is noted in the Javadocs. Hence, we don't need to 14061 * requestLayout(), the invalidate() below is sufficient. 14062 */ 14063 14064 // The old background's minimum size could have affected this 14065 // View's layout, so let's requestLayout 14066 requestLayout = true; 14067 } 14068 14069 computeOpaqueFlags(); 14070 14071 if (requestLayout) { 14072 requestLayout(); 14073 } 14074 14075 mBackgroundSizeChanged = true; 14076 invalidate(true); 14077 } 14078 14079 /** 14080 * Gets the background drawable 14081 * 14082 * @return The drawable used as the background for this view, if any. 14083 * 14084 * @see #setBackground(Drawable) 14085 * 14086 * @attr ref android.R.styleable#View_background 14087 */ 14088 public Drawable getBackground() { 14089 return mBackground; 14090 } 14091 14092 /** 14093 * Sets the padding. The view may add on the space required to display 14094 * the scrollbars, depending on the style and visibility of the scrollbars. 14095 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 14096 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 14097 * from the values set in this call. 14098 * 14099 * @attr ref android.R.styleable#View_padding 14100 * @attr ref android.R.styleable#View_paddingBottom 14101 * @attr ref android.R.styleable#View_paddingLeft 14102 * @attr ref android.R.styleable#View_paddingRight 14103 * @attr ref android.R.styleable#View_paddingTop 14104 * @param left the left padding in pixels 14105 * @param top the top padding in pixels 14106 * @param right the right padding in pixels 14107 * @param bottom the bottom padding in pixels 14108 */ 14109 public void setPadding(int left, int top, int right, int bottom) { 14110 mUserPaddingStart = -1; 14111 mUserPaddingEnd = -1; 14112 mUserPaddingRelative = false; 14113 14114 internalSetPadding(left, top, right, bottom); 14115 } 14116 14117 private void internalSetPadding(int left, int top, int right, int bottom) { 14118 mUserPaddingLeft = left; 14119 mUserPaddingRight = right; 14120 mUserPaddingBottom = bottom; 14121 14122 final int viewFlags = mViewFlags; 14123 boolean changed = false; 14124 14125 // Common case is there are no scroll bars. 14126 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 14127 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 14128 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 14129 ? 0 : getVerticalScrollbarWidth(); 14130 switch (mVerticalScrollbarPosition) { 14131 case SCROLLBAR_POSITION_DEFAULT: 14132 if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 14133 left += offset; 14134 } else { 14135 right += offset; 14136 } 14137 break; 14138 case SCROLLBAR_POSITION_RIGHT: 14139 right += offset; 14140 break; 14141 case SCROLLBAR_POSITION_LEFT: 14142 left += offset; 14143 break; 14144 } 14145 } 14146 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 14147 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 14148 ? 0 : getHorizontalScrollbarHeight(); 14149 } 14150 } 14151 14152 if (mPaddingLeft != left) { 14153 changed = true; 14154 mPaddingLeft = left; 14155 } 14156 if (mPaddingTop != top) { 14157 changed = true; 14158 mPaddingTop = top; 14159 } 14160 if (mPaddingRight != right) { 14161 changed = true; 14162 mPaddingRight = right; 14163 } 14164 if (mPaddingBottom != bottom) { 14165 changed = true; 14166 mPaddingBottom = bottom; 14167 } 14168 14169 if (changed) { 14170 requestLayout(); 14171 } 14172 } 14173 14174 /** 14175 * Sets the relative padding. The view may add on the space required to display 14176 * the scrollbars, depending on the style and visibility of the scrollbars. 14177 * from the values set in this call. 14178 * 14179 * @param start the start padding in pixels 14180 * @param top the top padding in pixels 14181 * @param end the end padding in pixels 14182 * @param bottom the bottom padding in pixels 14183 * @hide 14184 */ 14185 public void setPaddingRelative(int start, int top, int end, int bottom) { 14186 mUserPaddingStart = start; 14187 mUserPaddingEnd = end; 14188 mUserPaddingRelative = true; 14189 14190 switch(getResolvedLayoutDirection()) { 14191 case LAYOUT_DIRECTION_RTL: 14192 internalSetPadding(end, top, start, bottom); 14193 break; 14194 case LAYOUT_DIRECTION_LTR: 14195 default: 14196 internalSetPadding(start, top, end, bottom); 14197 } 14198 } 14199 14200 /** 14201 * Returns the top padding of this view. 14202 * 14203 * @return the top padding in pixels 14204 */ 14205 public int getPaddingTop() { 14206 return mPaddingTop; 14207 } 14208 14209 /** 14210 * Returns the bottom padding of this view. If there are inset and enabled 14211 * scrollbars, this value may include the space required to display the 14212 * scrollbars as well. 14213 * 14214 * @return the bottom padding in pixels 14215 */ 14216 public int getPaddingBottom() { 14217 return mPaddingBottom; 14218 } 14219 14220 /** 14221 * Returns the left padding of this view. If there are inset and enabled 14222 * scrollbars, this value may include the space required to display the 14223 * scrollbars as well. 14224 * 14225 * @return the left padding in pixels 14226 */ 14227 public int getPaddingLeft() { 14228 return mPaddingLeft; 14229 } 14230 14231 /** 14232 * Returns the start padding of this view depending on its resolved layout direction. 14233 * If there are inset and enabled scrollbars, this value may include the space 14234 * required to display the scrollbars as well. 14235 * 14236 * @return the start padding in pixels 14237 * @hide 14238 */ 14239 public int getPaddingStart() { 14240 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 14241 mPaddingRight : mPaddingLeft; 14242 } 14243 14244 /** 14245 * Returns the right padding of this view. If there are inset and enabled 14246 * scrollbars, this value may include the space required to display the 14247 * scrollbars as well. 14248 * 14249 * @return the right padding in pixels 14250 */ 14251 public int getPaddingRight() { 14252 return mPaddingRight; 14253 } 14254 14255 /** 14256 * Returns the end padding of this view depending on its resolved layout direction. 14257 * If there are inset and enabled scrollbars, this value may include the space 14258 * required to display the scrollbars as well. 14259 * 14260 * @return the end padding in pixels 14261 * @hide 14262 */ 14263 public int getPaddingEnd() { 14264 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 14265 mPaddingLeft : mPaddingRight; 14266 } 14267 14268 /** 14269 * Return if the padding as been set thru relative values 14270 * {@link #setPaddingRelative(int, int, int, int)} 14271 * 14272 * @return true if the padding is relative or false if it is not. 14273 * @hide 14274 */ 14275 public boolean isPaddingRelative() { 14276 return mUserPaddingRelative; 14277 } 14278 14279 /** 14280 * @hide 14281 */ 14282 public Insets getOpticalInsets() { 14283 if (mLayoutInsets == null) { 14284 mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets(); 14285 } 14286 return mLayoutInsets; 14287 } 14288 14289 /** 14290 * @hide 14291 */ 14292 public void setLayoutInsets(Insets layoutInsets) { 14293 mLayoutInsets = layoutInsets; 14294 } 14295 14296 /** 14297 * Changes the selection state of this view. A view can be selected or not. 14298 * Note that selection is not the same as focus. Views are typically 14299 * selected in the context of an AdapterView like ListView or GridView; 14300 * the selected view is the view that is highlighted. 14301 * 14302 * @param selected true if the view must be selected, false otherwise 14303 */ 14304 public void setSelected(boolean selected) { 14305 if (((mPrivateFlags & SELECTED) != 0) != selected) { 14306 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 14307 if (!selected) resetPressedState(); 14308 invalidate(true); 14309 refreshDrawableState(); 14310 dispatchSetSelected(selected); 14311 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 14312 notifyAccessibilityStateChanged(); 14313 } 14314 } 14315 } 14316 14317 /** 14318 * Dispatch setSelected to all of this View's children. 14319 * 14320 * @see #setSelected(boolean) 14321 * 14322 * @param selected The new selected state 14323 */ 14324 protected void dispatchSetSelected(boolean selected) { 14325 } 14326 14327 /** 14328 * Indicates the selection state of this view. 14329 * 14330 * @return true if the view is selected, false otherwise 14331 */ 14332 @ViewDebug.ExportedProperty 14333 public boolean isSelected() { 14334 return (mPrivateFlags & SELECTED) != 0; 14335 } 14336 14337 /** 14338 * Changes the activated state of this view. A view can be activated or not. 14339 * Note that activation is not the same as selection. Selection is 14340 * a transient property, representing the view (hierarchy) the user is 14341 * currently interacting with. Activation is a longer-term state that the 14342 * user can move views in and out of. For example, in a list view with 14343 * single or multiple selection enabled, the views in the current selection 14344 * set are activated. (Um, yeah, we are deeply sorry about the terminology 14345 * here.) The activated state is propagated down to children of the view it 14346 * is set on. 14347 * 14348 * @param activated true if the view must be activated, false otherwise 14349 */ 14350 public void setActivated(boolean activated) { 14351 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 14352 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 14353 invalidate(true); 14354 refreshDrawableState(); 14355 dispatchSetActivated(activated); 14356 } 14357 } 14358 14359 /** 14360 * Dispatch setActivated to all of this View's children. 14361 * 14362 * @see #setActivated(boolean) 14363 * 14364 * @param activated The new activated state 14365 */ 14366 protected void dispatchSetActivated(boolean activated) { 14367 } 14368 14369 /** 14370 * Indicates the activation state of this view. 14371 * 14372 * @return true if the view is activated, false otherwise 14373 */ 14374 @ViewDebug.ExportedProperty 14375 public boolean isActivated() { 14376 return (mPrivateFlags & ACTIVATED) != 0; 14377 } 14378 14379 /** 14380 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 14381 * observer can be used to get notifications when global events, like 14382 * layout, happen. 14383 * 14384 * The returned ViewTreeObserver observer is not guaranteed to remain 14385 * valid for the lifetime of this View. If the caller of this method keeps 14386 * a long-lived reference to ViewTreeObserver, it should always check for 14387 * the return value of {@link ViewTreeObserver#isAlive()}. 14388 * 14389 * @return The ViewTreeObserver for this view's hierarchy. 14390 */ 14391 public ViewTreeObserver getViewTreeObserver() { 14392 if (mAttachInfo != null) { 14393 return mAttachInfo.mTreeObserver; 14394 } 14395 if (mFloatingTreeObserver == null) { 14396 mFloatingTreeObserver = new ViewTreeObserver(); 14397 } 14398 return mFloatingTreeObserver; 14399 } 14400 14401 /** 14402 * <p>Finds the topmost view in the current view hierarchy.</p> 14403 * 14404 * @return the topmost view containing this view 14405 */ 14406 public View getRootView() { 14407 if (mAttachInfo != null) { 14408 final View v = mAttachInfo.mRootView; 14409 if (v != null) { 14410 return v; 14411 } 14412 } 14413 14414 View parent = this; 14415 14416 while (parent.mParent != null && parent.mParent instanceof View) { 14417 parent = (View) parent.mParent; 14418 } 14419 14420 return parent; 14421 } 14422 14423 /** 14424 * <p>Computes the coordinates of this view on the screen. The argument 14425 * must be an array of two integers. After the method returns, the array 14426 * contains the x and y location in that order.</p> 14427 * 14428 * @param location an array of two integers in which to hold the coordinates 14429 */ 14430 public void getLocationOnScreen(int[] location) { 14431 getLocationInWindow(location); 14432 14433 final AttachInfo info = mAttachInfo; 14434 if (info != null) { 14435 location[0] += info.mWindowLeft; 14436 location[1] += info.mWindowTop; 14437 } 14438 } 14439 14440 /** 14441 * <p>Computes the coordinates of this view in its window. The argument 14442 * must be an array of two integers. After the method returns, the array 14443 * contains the x and y location in that order.</p> 14444 * 14445 * @param location an array of two integers in which to hold the coordinates 14446 */ 14447 public void getLocationInWindow(int[] location) { 14448 if (location == null || location.length < 2) { 14449 throw new IllegalArgumentException("location must be an array of two integers"); 14450 } 14451 14452 if (mAttachInfo == null) { 14453 // When the view is not attached to a window, this method does not make sense 14454 location[0] = location[1] = 0; 14455 return; 14456 } 14457 14458 float[] position = mAttachInfo.mTmpTransformLocation; 14459 position[0] = position[1] = 0.0f; 14460 14461 if (!hasIdentityMatrix()) { 14462 getMatrix().mapPoints(position); 14463 } 14464 14465 position[0] += mLeft; 14466 position[1] += mTop; 14467 14468 ViewParent viewParent = mParent; 14469 while (viewParent instanceof View) { 14470 final View view = (View) viewParent; 14471 14472 position[0] -= view.mScrollX; 14473 position[1] -= view.mScrollY; 14474 14475 if (!view.hasIdentityMatrix()) { 14476 view.getMatrix().mapPoints(position); 14477 } 14478 14479 position[0] += view.mLeft; 14480 position[1] += view.mTop; 14481 14482 viewParent = view.mParent; 14483 } 14484 14485 if (viewParent instanceof ViewRootImpl) { 14486 // *cough* 14487 final ViewRootImpl vr = (ViewRootImpl) viewParent; 14488 position[1] -= vr.mCurScrollY; 14489 } 14490 14491 location[0] = (int) (position[0] + 0.5f); 14492 location[1] = (int) (position[1] + 0.5f); 14493 } 14494 14495 /** 14496 * {@hide} 14497 * @param id the id of the view to be found 14498 * @return the view of the specified id, null if cannot be found 14499 */ 14500 protected View findViewTraversal(int id) { 14501 if (id == mID) { 14502 return this; 14503 } 14504 return null; 14505 } 14506 14507 /** 14508 * {@hide} 14509 * @param tag the tag of the view to be found 14510 * @return the view of specified tag, null if cannot be found 14511 */ 14512 protected View findViewWithTagTraversal(Object tag) { 14513 if (tag != null && tag.equals(mTag)) { 14514 return this; 14515 } 14516 return null; 14517 } 14518 14519 /** 14520 * {@hide} 14521 * @param predicate The predicate to evaluate. 14522 * @param childToSkip If not null, ignores this child during the recursive traversal. 14523 * @return The first view that matches the predicate or null. 14524 */ 14525 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 14526 if (predicate.apply(this)) { 14527 return this; 14528 } 14529 return null; 14530 } 14531 14532 /** 14533 * Look for a child view with the given id. If this view has the given 14534 * id, return this view. 14535 * 14536 * @param id The id to search for. 14537 * @return The view that has the given id in the hierarchy or null 14538 */ 14539 public final View findViewById(int id) { 14540 if (id < 0) { 14541 return null; 14542 } 14543 return findViewTraversal(id); 14544 } 14545 14546 /** 14547 * Finds a view by its unuque and stable accessibility id. 14548 * 14549 * @param accessibilityId The searched accessibility id. 14550 * @return The found view. 14551 */ 14552 final View findViewByAccessibilityId(int accessibilityId) { 14553 if (accessibilityId < 0) { 14554 return null; 14555 } 14556 return findViewByAccessibilityIdTraversal(accessibilityId); 14557 } 14558 14559 /** 14560 * Performs the traversal to find a view by its unuque and stable accessibility id. 14561 * 14562 * <strong>Note:</strong>This method does not stop at the root namespace 14563 * boundary since the user can touch the screen at an arbitrary location 14564 * potentially crossing the root namespace bounday which will send an 14565 * accessibility event to accessibility services and they should be able 14566 * to obtain the event source. Also accessibility ids are guaranteed to be 14567 * unique in the window. 14568 * 14569 * @param accessibilityId The accessibility id. 14570 * @return The found view. 14571 */ 14572 View findViewByAccessibilityIdTraversal(int accessibilityId) { 14573 if (getAccessibilityViewId() == accessibilityId) { 14574 return this; 14575 } 14576 return null; 14577 } 14578 14579 /** 14580 * Look for a child view with the given tag. If this view has the given 14581 * tag, return this view. 14582 * 14583 * @param tag The tag to search for, using "tag.equals(getTag())". 14584 * @return The View that has the given tag in the hierarchy or null 14585 */ 14586 public final View findViewWithTag(Object tag) { 14587 if (tag == null) { 14588 return null; 14589 } 14590 return findViewWithTagTraversal(tag); 14591 } 14592 14593 /** 14594 * {@hide} 14595 * Look for a child view that matches the specified predicate. 14596 * If this view matches the predicate, return this view. 14597 * 14598 * @param predicate The predicate to evaluate. 14599 * @return The first view that matches the predicate or null. 14600 */ 14601 public final View findViewByPredicate(Predicate<View> predicate) { 14602 return findViewByPredicateTraversal(predicate, null); 14603 } 14604 14605 /** 14606 * {@hide} 14607 * Look for a child view that matches the specified predicate, 14608 * starting with the specified view and its descendents and then 14609 * recusively searching the ancestors and siblings of that view 14610 * until this view is reached. 14611 * 14612 * This method is useful in cases where the predicate does not match 14613 * a single unique view (perhaps multiple views use the same id) 14614 * and we are trying to find the view that is "closest" in scope to the 14615 * starting view. 14616 * 14617 * @param start The view to start from. 14618 * @param predicate The predicate to evaluate. 14619 * @return The first view that matches the predicate or null. 14620 */ 14621 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 14622 View childToSkip = null; 14623 for (;;) { 14624 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 14625 if (view != null || start == this) { 14626 return view; 14627 } 14628 14629 ViewParent parent = start.getParent(); 14630 if (parent == null || !(parent instanceof View)) { 14631 return null; 14632 } 14633 14634 childToSkip = start; 14635 start = (View) parent; 14636 } 14637 } 14638 14639 /** 14640 * Sets the identifier for this view. The identifier does not have to be 14641 * unique in this view's hierarchy. The identifier should be a positive 14642 * number. 14643 * 14644 * @see #NO_ID 14645 * @see #getId() 14646 * @see #findViewById(int) 14647 * 14648 * @param id a number used to identify the view 14649 * 14650 * @attr ref android.R.styleable#View_id 14651 */ 14652 public void setId(int id) { 14653 mID = id; 14654 } 14655 14656 /** 14657 * {@hide} 14658 * 14659 * @param isRoot true if the view belongs to the root namespace, false 14660 * otherwise 14661 */ 14662 public void setIsRootNamespace(boolean isRoot) { 14663 if (isRoot) { 14664 mPrivateFlags |= IS_ROOT_NAMESPACE; 14665 } else { 14666 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 14667 } 14668 } 14669 14670 /** 14671 * {@hide} 14672 * 14673 * @return true if the view belongs to the root namespace, false otherwise 14674 */ 14675 public boolean isRootNamespace() { 14676 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 14677 } 14678 14679 /** 14680 * Returns this view's identifier. 14681 * 14682 * @return a positive integer used to identify the view or {@link #NO_ID} 14683 * if the view has no ID 14684 * 14685 * @see #setId(int) 14686 * @see #findViewById(int) 14687 * @attr ref android.R.styleable#View_id 14688 */ 14689 @ViewDebug.CapturedViewProperty 14690 public int getId() { 14691 return mID; 14692 } 14693 14694 /** 14695 * Returns this view's tag. 14696 * 14697 * @return the Object stored in this view as a tag 14698 * 14699 * @see #setTag(Object) 14700 * @see #getTag(int) 14701 */ 14702 @ViewDebug.ExportedProperty 14703 public Object getTag() { 14704 return mTag; 14705 } 14706 14707 /** 14708 * Sets the tag associated with this view. A tag can be used to mark 14709 * a view in its hierarchy and does not have to be unique within the 14710 * hierarchy. Tags can also be used to store data within a view without 14711 * resorting to another data structure. 14712 * 14713 * @param tag an Object to tag the view with 14714 * 14715 * @see #getTag() 14716 * @see #setTag(int, Object) 14717 */ 14718 public void setTag(final Object tag) { 14719 mTag = tag; 14720 } 14721 14722 /** 14723 * Returns the tag associated with this view and the specified key. 14724 * 14725 * @param key The key identifying the tag 14726 * 14727 * @return the Object stored in this view as a tag 14728 * 14729 * @see #setTag(int, Object) 14730 * @see #getTag() 14731 */ 14732 public Object getTag(int key) { 14733 if (mKeyedTags != null) return mKeyedTags.get(key); 14734 return null; 14735 } 14736 14737 /** 14738 * Sets a tag associated with this view and a key. A tag can be used 14739 * to mark a view in its hierarchy and does not have to be unique within 14740 * the hierarchy. Tags can also be used to store data within a view 14741 * without resorting to another data structure. 14742 * 14743 * The specified key should be an id declared in the resources of the 14744 * application to ensure it is unique (see the <a 14745 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 14746 * Keys identified as belonging to 14747 * the Android framework or not associated with any package will cause 14748 * an {@link IllegalArgumentException} to be thrown. 14749 * 14750 * @param key The key identifying the tag 14751 * @param tag An Object to tag the view with 14752 * 14753 * @throws IllegalArgumentException If they specified key is not valid 14754 * 14755 * @see #setTag(Object) 14756 * @see #getTag(int) 14757 */ 14758 public void setTag(int key, final Object tag) { 14759 // If the package id is 0x00 or 0x01, it's either an undefined package 14760 // or a framework id 14761 if ((key >>> 24) < 2) { 14762 throw new IllegalArgumentException("The key must be an application-specific " 14763 + "resource id."); 14764 } 14765 14766 setKeyedTag(key, tag); 14767 } 14768 14769 /** 14770 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 14771 * framework id. 14772 * 14773 * @hide 14774 */ 14775 public void setTagInternal(int key, Object tag) { 14776 if ((key >>> 24) != 0x1) { 14777 throw new IllegalArgumentException("The key must be a framework-specific " 14778 + "resource id."); 14779 } 14780 14781 setKeyedTag(key, tag); 14782 } 14783 14784 private void setKeyedTag(int key, Object tag) { 14785 if (mKeyedTags == null) { 14786 mKeyedTags = new SparseArray<Object>(); 14787 } 14788 14789 mKeyedTags.put(key, tag); 14790 } 14791 14792 /** 14793 * @param consistency The type of consistency. See ViewDebug for more information. 14794 * 14795 * @hide 14796 */ 14797 protected boolean dispatchConsistencyCheck(int consistency) { 14798 return onConsistencyCheck(consistency); 14799 } 14800 14801 /** 14802 * Method that subclasses should implement to check their consistency. The type of 14803 * consistency check is indicated by the bit field passed as a parameter. 14804 * 14805 * @param consistency The type of consistency. See ViewDebug for more information. 14806 * 14807 * @throws IllegalStateException if the view is in an inconsistent state. 14808 * 14809 * @hide 14810 */ 14811 protected boolean onConsistencyCheck(int consistency) { 14812 boolean result = true; 14813 14814 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 14815 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 14816 14817 if (checkLayout) { 14818 if (getParent() == null) { 14819 result = false; 14820 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 14821 "View " + this + " does not have a parent."); 14822 } 14823 14824 if (mAttachInfo == null) { 14825 result = false; 14826 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 14827 "View " + this + " is not attached to a window."); 14828 } 14829 } 14830 14831 if (checkDrawing) { 14832 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 14833 // from their draw() method 14834 14835 if ((mPrivateFlags & DRAWN) != DRAWN && 14836 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 14837 result = false; 14838 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 14839 "View " + this + " was invalidated but its drawing cache is valid."); 14840 } 14841 } 14842 14843 return result; 14844 } 14845 14846 /** 14847 * Prints information about this view in the log output, with the tag 14848 * {@link #VIEW_LOG_TAG}. 14849 * 14850 * @hide 14851 */ 14852 public void debug() { 14853 debug(0); 14854 } 14855 14856 /** 14857 * Prints information about this view in the log output, with the tag 14858 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 14859 * indentation defined by the <code>depth</code>. 14860 * 14861 * @param depth the indentation level 14862 * 14863 * @hide 14864 */ 14865 protected void debug(int depth) { 14866 String output = debugIndent(depth - 1); 14867 14868 output += "+ " + this; 14869 int id = getId(); 14870 if (id != -1) { 14871 output += " (id=" + id + ")"; 14872 } 14873 Object tag = getTag(); 14874 if (tag != null) { 14875 output += " (tag=" + tag + ")"; 14876 } 14877 Log.d(VIEW_LOG_TAG, output); 14878 14879 if ((mPrivateFlags & FOCUSED) != 0) { 14880 output = debugIndent(depth) + " FOCUSED"; 14881 Log.d(VIEW_LOG_TAG, output); 14882 } 14883 14884 output = debugIndent(depth); 14885 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 14886 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 14887 + "} "; 14888 Log.d(VIEW_LOG_TAG, output); 14889 14890 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 14891 || mPaddingBottom != 0) { 14892 output = debugIndent(depth); 14893 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 14894 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 14895 Log.d(VIEW_LOG_TAG, output); 14896 } 14897 14898 output = debugIndent(depth); 14899 output += "mMeasureWidth=" + mMeasuredWidth + 14900 " mMeasureHeight=" + mMeasuredHeight; 14901 Log.d(VIEW_LOG_TAG, output); 14902 14903 output = debugIndent(depth); 14904 if (mLayoutParams == null) { 14905 output += "BAD! no layout params"; 14906 } else { 14907 output = mLayoutParams.debug(output); 14908 } 14909 Log.d(VIEW_LOG_TAG, output); 14910 14911 output = debugIndent(depth); 14912 output += "flags={"; 14913 output += View.printFlags(mViewFlags); 14914 output += "}"; 14915 Log.d(VIEW_LOG_TAG, output); 14916 14917 output = debugIndent(depth); 14918 output += "privateFlags={"; 14919 output += View.printPrivateFlags(mPrivateFlags); 14920 output += "}"; 14921 Log.d(VIEW_LOG_TAG, output); 14922 } 14923 14924 /** 14925 * Creates a string of whitespaces used for indentation. 14926 * 14927 * @param depth the indentation level 14928 * @return a String containing (depth * 2 + 3) * 2 white spaces 14929 * 14930 * @hide 14931 */ 14932 protected static String debugIndent(int depth) { 14933 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 14934 for (int i = 0; i < (depth * 2) + 3; i++) { 14935 spaces.append(' ').append(' '); 14936 } 14937 return spaces.toString(); 14938 } 14939 14940 /** 14941 * <p>Return the offset of the widget's text baseline from the widget's top 14942 * boundary. If this widget does not support baseline alignment, this 14943 * method returns -1. </p> 14944 * 14945 * @return the offset of the baseline within the widget's bounds or -1 14946 * if baseline alignment is not supported 14947 */ 14948 @ViewDebug.ExportedProperty(category = "layout") 14949 public int getBaseline() { 14950 return -1; 14951 } 14952 14953 /** 14954 * Call this when something has changed which has invalidated the 14955 * layout of this view. This will schedule a layout pass of the view 14956 * tree. 14957 */ 14958 public void requestLayout() { 14959 if (ViewDebug.TRACE_HIERARCHY) { 14960 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 14961 } 14962 14963 mPrivateFlags |= FORCE_LAYOUT; 14964 mPrivateFlags |= INVALIDATED; 14965 14966 if (mLayoutParams != null) { 14967 mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection()); 14968 } 14969 14970 if (mParent != null && !mParent.isLayoutRequested()) { 14971 mParent.requestLayout(); 14972 } 14973 } 14974 14975 /** 14976 * Forces this view to be laid out during the next layout pass. 14977 * This method does not call requestLayout() or forceLayout() 14978 * on the parent. 14979 */ 14980 public void forceLayout() { 14981 mPrivateFlags |= FORCE_LAYOUT; 14982 mPrivateFlags |= INVALIDATED; 14983 } 14984 14985 /** 14986 * <p> 14987 * This is called to find out how big a view should be. The parent 14988 * supplies constraint information in the width and height parameters. 14989 * </p> 14990 * 14991 * <p> 14992 * The actual measurement work of a view is performed in 14993 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 14994 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 14995 * </p> 14996 * 14997 * 14998 * @param widthMeasureSpec Horizontal space requirements as imposed by the 14999 * parent 15000 * @param heightMeasureSpec Vertical space requirements as imposed by the 15001 * parent 15002 * 15003 * @see #onMeasure(int, int) 15004 */ 15005 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 15006 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 15007 widthMeasureSpec != mOldWidthMeasureSpec || 15008 heightMeasureSpec != mOldHeightMeasureSpec) { 15009 15010 // first clears the measured dimension flag 15011 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 15012 15013 if (ViewDebug.TRACE_HIERARCHY) { 15014 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 15015 } 15016 15017 // measure ourselves, this should set the measured dimension flag back 15018 onMeasure(widthMeasureSpec, heightMeasureSpec); 15019 15020 // flag not set, setMeasuredDimension() was not invoked, we raise 15021 // an exception to warn the developer 15022 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 15023 throw new IllegalStateException("onMeasure() did not set the" 15024 + " measured dimension by calling" 15025 + " setMeasuredDimension()"); 15026 } 15027 15028 mPrivateFlags |= LAYOUT_REQUIRED; 15029 } 15030 15031 mOldWidthMeasureSpec = widthMeasureSpec; 15032 mOldHeightMeasureSpec = heightMeasureSpec; 15033 } 15034 15035 /** 15036 * <p> 15037 * Measure the view and its content to determine the measured width and the 15038 * measured height. This method is invoked by {@link #measure(int, int)} and 15039 * should be overriden by subclasses to provide accurate and efficient 15040 * measurement of their contents. 15041 * </p> 15042 * 15043 * <p> 15044 * <strong>CONTRACT:</strong> When overriding this method, you 15045 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 15046 * measured width and height of this view. Failure to do so will trigger an 15047 * <code>IllegalStateException</code>, thrown by 15048 * {@link #measure(int, int)}. Calling the superclass' 15049 * {@link #onMeasure(int, int)} is a valid use. 15050 * </p> 15051 * 15052 * <p> 15053 * The base class implementation of measure defaults to the background size, 15054 * unless a larger size is allowed by the MeasureSpec. Subclasses should 15055 * override {@link #onMeasure(int, int)} to provide better measurements of 15056 * their content. 15057 * </p> 15058 * 15059 * <p> 15060 * If this method is overridden, it is the subclass's responsibility to make 15061 * sure the measured height and width are at least the view's minimum height 15062 * and width ({@link #getSuggestedMinimumHeight()} and 15063 * {@link #getSuggestedMinimumWidth()}). 15064 * </p> 15065 * 15066 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 15067 * The requirements are encoded with 15068 * {@link android.view.View.MeasureSpec}. 15069 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 15070 * The requirements are encoded with 15071 * {@link android.view.View.MeasureSpec}. 15072 * 15073 * @see #getMeasuredWidth() 15074 * @see #getMeasuredHeight() 15075 * @see #setMeasuredDimension(int, int) 15076 * @see #getSuggestedMinimumHeight() 15077 * @see #getSuggestedMinimumWidth() 15078 * @see android.view.View.MeasureSpec#getMode(int) 15079 * @see android.view.View.MeasureSpec#getSize(int) 15080 */ 15081 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 15082 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 15083 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 15084 } 15085 15086 /** 15087 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 15088 * measured width and measured height. Failing to do so will trigger an 15089 * exception at measurement time.</p> 15090 * 15091 * @param measuredWidth The measured width of this view. May be a complex 15092 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 15093 * {@link #MEASURED_STATE_TOO_SMALL}. 15094 * @param measuredHeight The measured height of this view. May be a complex 15095 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 15096 * {@link #MEASURED_STATE_TOO_SMALL}. 15097 */ 15098 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 15099 mMeasuredWidth = measuredWidth; 15100 mMeasuredHeight = measuredHeight; 15101 15102 mPrivateFlags |= MEASURED_DIMENSION_SET; 15103 } 15104 15105 /** 15106 * Merge two states as returned by {@link #getMeasuredState()}. 15107 * @param curState The current state as returned from a view or the result 15108 * of combining multiple views. 15109 * @param newState The new view state to combine. 15110 * @return Returns a new integer reflecting the combination of the two 15111 * states. 15112 */ 15113 public static int combineMeasuredStates(int curState, int newState) { 15114 return curState | newState; 15115 } 15116 15117 /** 15118 * Version of {@link #resolveSizeAndState(int, int, int)} 15119 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 15120 */ 15121 public static int resolveSize(int size, int measureSpec) { 15122 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 15123 } 15124 15125 /** 15126 * Utility to reconcile a desired size and state, with constraints imposed 15127 * by a MeasureSpec. Will take the desired size, unless a different size 15128 * is imposed by the constraints. The returned value is a compound integer, 15129 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 15130 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 15131 * size is smaller than the size the view wants to be. 15132 * 15133 * @param size How big the view wants to be 15134 * @param measureSpec Constraints imposed by the parent 15135 * @return Size information bit mask as defined by 15136 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 15137 */ 15138 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 15139 int result = size; 15140 int specMode = MeasureSpec.getMode(measureSpec); 15141 int specSize = MeasureSpec.getSize(measureSpec); 15142 switch (specMode) { 15143 case MeasureSpec.UNSPECIFIED: 15144 result = size; 15145 break; 15146 case MeasureSpec.AT_MOST: 15147 if (specSize < size) { 15148 result = specSize | MEASURED_STATE_TOO_SMALL; 15149 } else { 15150 result = size; 15151 } 15152 break; 15153 case MeasureSpec.EXACTLY: 15154 result = specSize; 15155 break; 15156 } 15157 return result | (childMeasuredState&MEASURED_STATE_MASK); 15158 } 15159 15160 /** 15161 * Utility to return a default size. Uses the supplied size if the 15162 * MeasureSpec imposed no constraints. Will get larger if allowed 15163 * by the MeasureSpec. 15164 * 15165 * @param size Default size for this view 15166 * @param measureSpec Constraints imposed by the parent 15167 * @return The size this view should be. 15168 */ 15169 public static int getDefaultSize(int size, int measureSpec) { 15170 int result = size; 15171 int specMode = MeasureSpec.getMode(measureSpec); 15172 int specSize = MeasureSpec.getSize(measureSpec); 15173 15174 switch (specMode) { 15175 case MeasureSpec.UNSPECIFIED: 15176 result = size; 15177 break; 15178 case MeasureSpec.AT_MOST: 15179 case MeasureSpec.EXACTLY: 15180 result = specSize; 15181 break; 15182 } 15183 return result; 15184 } 15185 15186 /** 15187 * Returns the suggested minimum height that the view should use. This 15188 * returns the maximum of the view's minimum height 15189 * and the background's minimum height 15190 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 15191 * <p> 15192 * When being used in {@link #onMeasure(int, int)}, the caller should still 15193 * ensure the returned height is within the requirements of the parent. 15194 * 15195 * @return The suggested minimum height of the view. 15196 */ 15197 protected int getSuggestedMinimumHeight() { 15198 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 15199 15200 } 15201 15202 /** 15203 * Returns the suggested minimum width that the view should use. This 15204 * returns the maximum of the view's minimum width) 15205 * and the background's minimum width 15206 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 15207 * <p> 15208 * When being used in {@link #onMeasure(int, int)}, the caller should still 15209 * ensure the returned width is within the requirements of the parent. 15210 * 15211 * @return The suggested minimum width of the view. 15212 */ 15213 protected int getSuggestedMinimumWidth() { 15214 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 15215 } 15216 15217 /** 15218 * Returns the minimum height of the view. 15219 * 15220 * @return the minimum height the view will try to be. 15221 * 15222 * @see #setMinimumHeight(int) 15223 * 15224 * @attr ref android.R.styleable#View_minHeight 15225 */ 15226 public int getMinimumHeight() { 15227 return mMinHeight; 15228 } 15229 15230 /** 15231 * Sets the minimum height of the view. It is not guaranteed the view will 15232 * be able to achieve this minimum height (for example, if its parent layout 15233 * constrains it with less available height). 15234 * 15235 * @param minHeight The minimum height the view will try to be. 15236 * 15237 * @see #getMinimumHeight() 15238 * 15239 * @attr ref android.R.styleable#View_minHeight 15240 */ 15241 public void setMinimumHeight(int minHeight) { 15242 mMinHeight = minHeight; 15243 requestLayout(); 15244 } 15245 15246 /** 15247 * Returns the minimum width of the view. 15248 * 15249 * @return the minimum width the view will try to be. 15250 * 15251 * @see #setMinimumWidth(int) 15252 * 15253 * @attr ref android.R.styleable#View_minWidth 15254 */ 15255 public int getMinimumWidth() { 15256 return mMinWidth; 15257 } 15258 15259 /** 15260 * Sets the minimum width of the view. It is not guaranteed the view will 15261 * be able to achieve this minimum width (for example, if its parent layout 15262 * constrains it with less available width). 15263 * 15264 * @param minWidth The minimum width the view will try to be. 15265 * 15266 * @see #getMinimumWidth() 15267 * 15268 * @attr ref android.R.styleable#View_minWidth 15269 */ 15270 public void setMinimumWidth(int minWidth) { 15271 mMinWidth = minWidth; 15272 requestLayout(); 15273 15274 } 15275 15276 /** 15277 * Get the animation currently associated with this view. 15278 * 15279 * @return The animation that is currently playing or 15280 * scheduled to play for this view. 15281 */ 15282 public Animation getAnimation() { 15283 return mCurrentAnimation; 15284 } 15285 15286 /** 15287 * Start the specified animation now. 15288 * 15289 * @param animation the animation to start now 15290 */ 15291 public void startAnimation(Animation animation) { 15292 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 15293 setAnimation(animation); 15294 invalidateParentCaches(); 15295 invalidate(true); 15296 } 15297 15298 /** 15299 * Cancels any animations for this view. 15300 */ 15301 public void clearAnimation() { 15302 if (mCurrentAnimation != null) { 15303 mCurrentAnimation.detach(); 15304 } 15305 mCurrentAnimation = null; 15306 invalidateParentIfNeeded(); 15307 } 15308 15309 /** 15310 * Sets the next animation to play for this view. 15311 * If you want the animation to play immediately, use 15312 * startAnimation. This method provides allows fine-grained 15313 * control over the start time and invalidation, but you 15314 * must make sure that 1) the animation has a start time set, and 15315 * 2) the view will be invalidated when the animation is supposed to 15316 * start. 15317 * 15318 * @param animation The next animation, or null. 15319 */ 15320 public void setAnimation(Animation animation) { 15321 mCurrentAnimation = animation; 15322 15323 if (animation != null) { 15324 // If the screen is off assume the animation start time is now instead of 15325 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 15326 // would cause the animation to start when the screen turns back on 15327 if (mAttachInfo != null && !mAttachInfo.mScreenOn && 15328 animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 15329 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 15330 } 15331 animation.reset(); 15332 } 15333 } 15334 15335 /** 15336 * Invoked by a parent ViewGroup to notify the start of the animation 15337 * currently associated with this view. If you override this method, 15338 * always call super.onAnimationStart(); 15339 * 15340 * @see #setAnimation(android.view.animation.Animation) 15341 * @see #getAnimation() 15342 */ 15343 protected void onAnimationStart() { 15344 mPrivateFlags |= ANIMATION_STARTED; 15345 } 15346 15347 /** 15348 * Invoked by a parent ViewGroup to notify the end of the animation 15349 * currently associated with this view. If you override this method, 15350 * always call super.onAnimationEnd(); 15351 * 15352 * @see #setAnimation(android.view.animation.Animation) 15353 * @see #getAnimation() 15354 */ 15355 protected void onAnimationEnd() { 15356 mPrivateFlags &= ~ANIMATION_STARTED; 15357 } 15358 15359 /** 15360 * Invoked if there is a Transform that involves alpha. Subclass that can 15361 * draw themselves with the specified alpha should return true, and then 15362 * respect that alpha when their onDraw() is called. If this returns false 15363 * then the view may be redirected to draw into an offscreen buffer to 15364 * fulfill the request, which will look fine, but may be slower than if the 15365 * subclass handles it internally. The default implementation returns false. 15366 * 15367 * @param alpha The alpha (0..255) to apply to the view's drawing 15368 * @return true if the view can draw with the specified alpha. 15369 */ 15370 protected boolean onSetAlpha(int alpha) { 15371 return false; 15372 } 15373 15374 /** 15375 * This is used by the RootView to perform an optimization when 15376 * the view hierarchy contains one or several SurfaceView. 15377 * SurfaceView is always considered transparent, but its children are not, 15378 * therefore all View objects remove themselves from the global transparent 15379 * region (passed as a parameter to this function). 15380 * 15381 * @param region The transparent region for this ViewAncestor (window). 15382 * 15383 * @return Returns true if the effective visibility of the view at this 15384 * point is opaque, regardless of the transparent region; returns false 15385 * if it is possible for underlying windows to be seen behind the view. 15386 * 15387 * {@hide} 15388 */ 15389 public boolean gatherTransparentRegion(Region region) { 15390 final AttachInfo attachInfo = mAttachInfo; 15391 if (region != null && attachInfo != null) { 15392 final int pflags = mPrivateFlags; 15393 if ((pflags & SKIP_DRAW) == 0) { 15394 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 15395 // remove it from the transparent region. 15396 final int[] location = attachInfo.mTransparentLocation; 15397 getLocationInWindow(location); 15398 region.op(location[0], location[1], location[0] + mRight - mLeft, 15399 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 15400 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 15401 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 15402 // exists, so we remove the background drawable's non-transparent 15403 // parts from this transparent region. 15404 applyDrawableToTransparentRegion(mBackground, region); 15405 } 15406 } 15407 return true; 15408 } 15409 15410 /** 15411 * Play a sound effect for this view. 15412 * 15413 * <p>The framework will play sound effects for some built in actions, such as 15414 * clicking, but you may wish to play these effects in your widget, 15415 * for instance, for internal navigation. 15416 * 15417 * <p>The sound effect will only be played if sound effects are enabled by the user, and 15418 * {@link #isSoundEffectsEnabled()} is true. 15419 * 15420 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 15421 */ 15422 public void playSoundEffect(int soundConstant) { 15423 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 15424 return; 15425 } 15426 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 15427 } 15428 15429 /** 15430 * BZZZTT!!1! 15431 * 15432 * <p>Provide haptic feedback to the user for this view. 15433 * 15434 * <p>The framework will provide haptic feedback for some built in actions, 15435 * such as long presses, but you may wish to provide feedback for your 15436 * own widget. 15437 * 15438 * <p>The feedback will only be performed if 15439 * {@link #isHapticFeedbackEnabled()} is true. 15440 * 15441 * @param feedbackConstant One of the constants defined in 15442 * {@link HapticFeedbackConstants} 15443 */ 15444 public boolean performHapticFeedback(int feedbackConstant) { 15445 return performHapticFeedback(feedbackConstant, 0); 15446 } 15447 15448 /** 15449 * BZZZTT!!1! 15450 * 15451 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 15452 * 15453 * @param feedbackConstant One of the constants defined in 15454 * {@link HapticFeedbackConstants} 15455 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 15456 */ 15457 public boolean performHapticFeedback(int feedbackConstant, int flags) { 15458 if (mAttachInfo == null) { 15459 return false; 15460 } 15461 //noinspection SimplifiableIfStatement 15462 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 15463 && !isHapticFeedbackEnabled()) { 15464 return false; 15465 } 15466 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 15467 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 15468 } 15469 15470 /** 15471 * Request that the visibility of the status bar or other screen/window 15472 * decorations be changed. 15473 * 15474 * <p>This method is used to put the over device UI into temporary modes 15475 * where the user's attention is focused more on the application content, 15476 * by dimming or hiding surrounding system affordances. This is typically 15477 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 15478 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 15479 * to be placed behind the action bar (and with these flags other system 15480 * affordances) so that smooth transitions between hiding and showing them 15481 * can be done. 15482 * 15483 * <p>Two representative examples of the use of system UI visibility is 15484 * implementing a content browsing application (like a magazine reader) 15485 * and a video playing application. 15486 * 15487 * <p>The first code shows a typical implementation of a View in a content 15488 * browsing application. In this implementation, the application goes 15489 * into a content-oriented mode by hiding the status bar and action bar, 15490 * and putting the navigation elements into lights out mode. The user can 15491 * then interact with content while in this mode. Such an application should 15492 * provide an easy way for the user to toggle out of the mode (such as to 15493 * check information in the status bar or access notifications). In the 15494 * implementation here, this is done simply by tapping on the content. 15495 * 15496 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 15497 * content} 15498 * 15499 * <p>This second code sample shows a typical implementation of a View 15500 * in a video playing application. In this situation, while the video is 15501 * playing the application would like to go into a complete full-screen mode, 15502 * to use as much of the display as possible for the video. When in this state 15503 * the user can not interact with the application; the system intercepts 15504 * touching on the screen to pop the UI out of full screen mode. See 15505 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 15506 * 15507 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 15508 * content} 15509 * 15510 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 15511 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 15512 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 15513 * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}. 15514 */ 15515 public void setSystemUiVisibility(int visibility) { 15516 if (visibility != mSystemUiVisibility) { 15517 mSystemUiVisibility = visibility; 15518 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 15519 mParent.recomputeViewAttributes(this); 15520 } 15521 } 15522 } 15523 15524 /** 15525 * Returns the last {@link #setSystemUiVisibility(int) that this view has requested. 15526 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 15527 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 15528 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 15529 * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}. 15530 */ 15531 public int getSystemUiVisibility() { 15532 return mSystemUiVisibility; 15533 } 15534 15535 /** 15536 * Returns the current system UI visibility that is currently set for 15537 * the entire window. This is the combination of the 15538 * {@link #setSystemUiVisibility(int)} values supplied by all of the 15539 * views in the window. 15540 */ 15541 public int getWindowSystemUiVisibility() { 15542 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 15543 } 15544 15545 /** 15546 * Override to find out when the window's requested system UI visibility 15547 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 15548 * This is different from the callbacks recieved through 15549 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 15550 * in that this is only telling you about the local request of the window, 15551 * not the actual values applied by the system. 15552 */ 15553 public void onWindowSystemUiVisibilityChanged(int visible) { 15554 } 15555 15556 /** 15557 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 15558 * the view hierarchy. 15559 */ 15560 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 15561 onWindowSystemUiVisibilityChanged(visible); 15562 } 15563 15564 /** 15565 * Set a listener to receive callbacks when the visibility of the system bar changes. 15566 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 15567 */ 15568 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 15569 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 15570 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 15571 mParent.recomputeViewAttributes(this); 15572 } 15573 } 15574 15575 /** 15576 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 15577 * the view hierarchy. 15578 */ 15579 public void dispatchSystemUiVisibilityChanged(int visibility) { 15580 ListenerInfo li = mListenerInfo; 15581 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 15582 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 15583 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 15584 } 15585 } 15586 15587 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 15588 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 15589 if (val != mSystemUiVisibility) { 15590 setSystemUiVisibility(val); 15591 return true; 15592 } 15593 return false; 15594 } 15595 15596 /** @hide */ 15597 public void setDisabledSystemUiVisibility(int flags) { 15598 if (mAttachInfo != null) { 15599 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 15600 mAttachInfo.mDisabledSystemUiVisibility = flags; 15601 if (mParent != null) { 15602 mParent.recomputeViewAttributes(this); 15603 } 15604 } 15605 } 15606 } 15607 15608 /** 15609 * Creates an image that the system displays during the drag and drop 15610 * operation. This is called a "drag shadow". The default implementation 15611 * for a DragShadowBuilder based on a View returns an image that has exactly the same 15612 * appearance as the given View. The default also positions the center of the drag shadow 15613 * directly under the touch point. If no View is provided (the constructor with no parameters 15614 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 15615 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 15616 * default is an invisible drag shadow. 15617 * <p> 15618 * You are not required to use the View you provide to the constructor as the basis of the 15619 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 15620 * anything you want as the drag shadow. 15621 * </p> 15622 * <p> 15623 * You pass a DragShadowBuilder object to the system when you start the drag. The system 15624 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 15625 * size and position of the drag shadow. It uses this data to construct a 15626 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 15627 * so that your application can draw the shadow image in the Canvas. 15628 * </p> 15629 * 15630 * <div class="special reference"> 15631 * <h3>Developer Guides</h3> 15632 * <p>For a guide to implementing drag and drop features, read the 15633 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 15634 * </div> 15635 */ 15636 public static class DragShadowBuilder { 15637 private final WeakReference<View> mView; 15638 15639 /** 15640 * Constructs a shadow image builder based on a View. By default, the resulting drag 15641 * shadow will have the same appearance and dimensions as the View, with the touch point 15642 * over the center of the View. 15643 * @param view A View. Any View in scope can be used. 15644 */ 15645 public DragShadowBuilder(View view) { 15646 mView = new WeakReference<View>(view); 15647 } 15648 15649 /** 15650 * Construct a shadow builder object with no associated View. This 15651 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 15652 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 15653 * to supply the drag shadow's dimensions and appearance without 15654 * reference to any View object. If they are not overridden, then the result is an 15655 * invisible drag shadow. 15656 */ 15657 public DragShadowBuilder() { 15658 mView = new WeakReference<View>(null); 15659 } 15660 15661 /** 15662 * Returns the View object that had been passed to the 15663 * {@link #View.DragShadowBuilder(View)} 15664 * constructor. If that View parameter was {@code null} or if the 15665 * {@link #View.DragShadowBuilder()} 15666 * constructor was used to instantiate the builder object, this method will return 15667 * null. 15668 * 15669 * @return The View object associate with this builder object. 15670 */ 15671 @SuppressWarnings({"JavadocReference"}) 15672 final public View getView() { 15673 return mView.get(); 15674 } 15675 15676 /** 15677 * Provides the metrics for the shadow image. These include the dimensions of 15678 * the shadow image, and the point within that shadow that should 15679 * be centered under the touch location while dragging. 15680 * <p> 15681 * The default implementation sets the dimensions of the shadow to be the 15682 * same as the dimensions of the View itself and centers the shadow under 15683 * the touch point. 15684 * </p> 15685 * 15686 * @param shadowSize A {@link android.graphics.Point} containing the width and height 15687 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 15688 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 15689 * image. 15690 * 15691 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 15692 * shadow image that should be underneath the touch point during the drag and drop 15693 * operation. Your application must set {@link android.graphics.Point#x} to the 15694 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 15695 */ 15696 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 15697 final View view = mView.get(); 15698 if (view != null) { 15699 shadowSize.set(view.getWidth(), view.getHeight()); 15700 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 15701 } else { 15702 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 15703 } 15704 } 15705 15706 /** 15707 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 15708 * based on the dimensions it received from the 15709 * {@link #onProvideShadowMetrics(Point, Point)} callback. 15710 * 15711 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 15712 */ 15713 public void onDrawShadow(Canvas canvas) { 15714 final View view = mView.get(); 15715 if (view != null) { 15716 view.draw(canvas); 15717 } else { 15718 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 15719 } 15720 } 15721 } 15722 15723 /** 15724 * Starts a drag and drop operation. When your application calls this method, it passes a 15725 * {@link android.view.View.DragShadowBuilder} object to the system. The 15726 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 15727 * to get metrics for the drag shadow, and then calls the object's 15728 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 15729 * <p> 15730 * Once the system has the drag shadow, it begins the drag and drop operation by sending 15731 * drag events to all the View objects in your application that are currently visible. It does 15732 * this either by calling the View object's drag listener (an implementation of 15733 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 15734 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 15735 * Both are passed a {@link android.view.DragEvent} object that has a 15736 * {@link android.view.DragEvent#getAction()} value of 15737 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 15738 * </p> 15739 * <p> 15740 * Your application can invoke startDrag() on any attached View object. The View object does not 15741 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 15742 * be related to the View the user selected for dragging. 15743 * </p> 15744 * @param data A {@link android.content.ClipData} object pointing to the data to be 15745 * transferred by the drag and drop operation. 15746 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 15747 * drag shadow. 15748 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 15749 * drop operation. This Object is put into every DragEvent object sent by the system during the 15750 * current drag. 15751 * <p> 15752 * myLocalState is a lightweight mechanism for the sending information from the dragged View 15753 * to the target Views. For example, it can contain flags that differentiate between a 15754 * a copy operation and a move operation. 15755 * </p> 15756 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 15757 * so the parameter should be set to 0. 15758 * @return {@code true} if the method completes successfully, or 15759 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 15760 * do a drag, and so no drag operation is in progress. 15761 */ 15762 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 15763 Object myLocalState, int flags) { 15764 if (ViewDebug.DEBUG_DRAG) { 15765 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 15766 } 15767 boolean okay = false; 15768 15769 Point shadowSize = new Point(); 15770 Point shadowTouchPoint = new Point(); 15771 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 15772 15773 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 15774 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 15775 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 15776 } 15777 15778 if (ViewDebug.DEBUG_DRAG) { 15779 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 15780 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 15781 } 15782 Surface surface = new Surface(); 15783 try { 15784 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 15785 flags, shadowSize.x, shadowSize.y, surface); 15786 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 15787 + " surface=" + surface); 15788 if (token != null) { 15789 Canvas canvas = surface.lockCanvas(null); 15790 try { 15791 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 15792 shadowBuilder.onDrawShadow(canvas); 15793 } finally { 15794 surface.unlockCanvasAndPost(canvas); 15795 } 15796 15797 final ViewRootImpl root = getViewRootImpl(); 15798 15799 // Cache the local state object for delivery with DragEvents 15800 root.setLocalDragState(myLocalState); 15801 15802 // repurpose 'shadowSize' for the last touch point 15803 root.getLastTouchPoint(shadowSize); 15804 15805 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 15806 shadowSize.x, shadowSize.y, 15807 shadowTouchPoint.x, shadowTouchPoint.y, data); 15808 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 15809 15810 // Off and running! Release our local surface instance; the drag 15811 // shadow surface is now managed by the system process. 15812 surface.release(); 15813 } 15814 } catch (Exception e) { 15815 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 15816 surface.destroy(); 15817 } 15818 15819 return okay; 15820 } 15821 15822 /** 15823 * Handles drag events sent by the system following a call to 15824 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 15825 *<p> 15826 * When the system calls this method, it passes a 15827 * {@link android.view.DragEvent} object. A call to 15828 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 15829 * in DragEvent. The method uses these to determine what is happening in the drag and drop 15830 * operation. 15831 * @param event The {@link android.view.DragEvent} sent by the system. 15832 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 15833 * in DragEvent, indicating the type of drag event represented by this object. 15834 * @return {@code true} if the method was successful, otherwise {@code false}. 15835 * <p> 15836 * The method should return {@code true} in response to an action type of 15837 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 15838 * operation. 15839 * </p> 15840 * <p> 15841 * The method should also return {@code true} in response to an action type of 15842 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 15843 * {@code false} if it didn't. 15844 * </p> 15845 */ 15846 public boolean onDragEvent(DragEvent event) { 15847 return false; 15848 } 15849 15850 /** 15851 * Detects if this View is enabled and has a drag event listener. 15852 * If both are true, then it calls the drag event listener with the 15853 * {@link android.view.DragEvent} it received. If the drag event listener returns 15854 * {@code true}, then dispatchDragEvent() returns {@code true}. 15855 * <p> 15856 * For all other cases, the method calls the 15857 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 15858 * method and returns its result. 15859 * </p> 15860 * <p> 15861 * This ensures that a drag event is always consumed, even if the View does not have a drag 15862 * event listener. However, if the View has a listener and the listener returns true, then 15863 * onDragEvent() is not called. 15864 * </p> 15865 */ 15866 public boolean dispatchDragEvent(DragEvent event) { 15867 //noinspection SimplifiableIfStatement 15868 ListenerInfo li = mListenerInfo; 15869 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 15870 && li.mOnDragListener.onDrag(this, event)) { 15871 return true; 15872 } 15873 return onDragEvent(event); 15874 } 15875 15876 boolean canAcceptDrag() { 15877 return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0; 15878 } 15879 15880 /** 15881 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 15882 * it is ever exposed at all. 15883 * @hide 15884 */ 15885 public void onCloseSystemDialogs(String reason) { 15886 } 15887 15888 /** 15889 * Given a Drawable whose bounds have been set to draw into this view, 15890 * update a Region being computed for 15891 * {@link #gatherTransparentRegion(android.graphics.Region)} so 15892 * that any non-transparent parts of the Drawable are removed from the 15893 * given transparent region. 15894 * 15895 * @param dr The Drawable whose transparency is to be applied to the region. 15896 * @param region A Region holding the current transparency information, 15897 * where any parts of the region that are set are considered to be 15898 * transparent. On return, this region will be modified to have the 15899 * transparency information reduced by the corresponding parts of the 15900 * Drawable that are not transparent. 15901 * {@hide} 15902 */ 15903 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 15904 if (DBG) { 15905 Log.i("View", "Getting transparent region for: " + this); 15906 } 15907 final Region r = dr.getTransparentRegion(); 15908 final Rect db = dr.getBounds(); 15909 final AttachInfo attachInfo = mAttachInfo; 15910 if (r != null && attachInfo != null) { 15911 final int w = getRight()-getLeft(); 15912 final int h = getBottom()-getTop(); 15913 if (db.left > 0) { 15914 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 15915 r.op(0, 0, db.left, h, Region.Op.UNION); 15916 } 15917 if (db.right < w) { 15918 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 15919 r.op(db.right, 0, w, h, Region.Op.UNION); 15920 } 15921 if (db.top > 0) { 15922 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 15923 r.op(0, 0, w, db.top, Region.Op.UNION); 15924 } 15925 if (db.bottom < h) { 15926 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 15927 r.op(0, db.bottom, w, h, Region.Op.UNION); 15928 } 15929 final int[] location = attachInfo.mTransparentLocation; 15930 getLocationInWindow(location); 15931 r.translate(location[0], location[1]); 15932 region.op(r, Region.Op.INTERSECT); 15933 } else { 15934 region.op(db, Region.Op.DIFFERENCE); 15935 } 15936 } 15937 15938 private void checkForLongClick(int delayOffset) { 15939 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 15940 mHasPerformedLongPress = false; 15941 15942 if (mPendingCheckForLongPress == null) { 15943 mPendingCheckForLongPress = new CheckForLongPress(); 15944 } 15945 mPendingCheckForLongPress.rememberWindowAttachCount(); 15946 postDelayed(mPendingCheckForLongPress, 15947 ViewConfiguration.getLongPressTimeout() - delayOffset); 15948 } 15949 } 15950 15951 /** 15952 * Inflate a view from an XML resource. This convenience method wraps the {@link 15953 * LayoutInflater} class, which provides a full range of options for view inflation. 15954 * 15955 * @param context The Context object for your activity or application. 15956 * @param resource The resource ID to inflate 15957 * @param root A view group that will be the parent. Used to properly inflate the 15958 * layout_* parameters. 15959 * @see LayoutInflater 15960 */ 15961 public static View inflate(Context context, int resource, ViewGroup root) { 15962 LayoutInflater factory = LayoutInflater.from(context); 15963 return factory.inflate(resource, root); 15964 } 15965 15966 /** 15967 * Scroll the view with standard behavior for scrolling beyond the normal 15968 * content boundaries. Views that call this method should override 15969 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 15970 * results of an over-scroll operation. 15971 * 15972 * Views can use this method to handle any touch or fling-based scrolling. 15973 * 15974 * @param deltaX Change in X in pixels 15975 * @param deltaY Change in Y in pixels 15976 * @param scrollX Current X scroll value in pixels before applying deltaX 15977 * @param scrollY Current Y scroll value in pixels before applying deltaY 15978 * @param scrollRangeX Maximum content scroll range along the X axis 15979 * @param scrollRangeY Maximum content scroll range along the Y axis 15980 * @param maxOverScrollX Number of pixels to overscroll by in either direction 15981 * along the X axis. 15982 * @param maxOverScrollY Number of pixels to overscroll by in either direction 15983 * along the Y axis. 15984 * @param isTouchEvent true if this scroll operation is the result of a touch event. 15985 * @return true if scrolling was clamped to an over-scroll boundary along either 15986 * axis, false otherwise. 15987 */ 15988 @SuppressWarnings({"UnusedParameters"}) 15989 protected boolean overScrollBy(int deltaX, int deltaY, 15990 int scrollX, int scrollY, 15991 int scrollRangeX, int scrollRangeY, 15992 int maxOverScrollX, int maxOverScrollY, 15993 boolean isTouchEvent) { 15994 final int overScrollMode = mOverScrollMode; 15995 final boolean canScrollHorizontal = 15996 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 15997 final boolean canScrollVertical = 15998 computeVerticalScrollRange() > computeVerticalScrollExtent(); 15999 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 16000 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 16001 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 16002 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 16003 16004 int newScrollX = scrollX + deltaX; 16005 if (!overScrollHorizontal) { 16006 maxOverScrollX = 0; 16007 } 16008 16009 int newScrollY = scrollY + deltaY; 16010 if (!overScrollVertical) { 16011 maxOverScrollY = 0; 16012 } 16013 16014 // Clamp values if at the limits and record 16015 final int left = -maxOverScrollX; 16016 final int right = maxOverScrollX + scrollRangeX; 16017 final int top = -maxOverScrollY; 16018 final int bottom = maxOverScrollY + scrollRangeY; 16019 16020 boolean clampedX = false; 16021 if (newScrollX > right) { 16022 newScrollX = right; 16023 clampedX = true; 16024 } else if (newScrollX < left) { 16025 newScrollX = left; 16026 clampedX = true; 16027 } 16028 16029 boolean clampedY = false; 16030 if (newScrollY > bottom) { 16031 newScrollY = bottom; 16032 clampedY = true; 16033 } else if (newScrollY < top) { 16034 newScrollY = top; 16035 clampedY = true; 16036 } 16037 16038 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 16039 16040 return clampedX || clampedY; 16041 } 16042 16043 /** 16044 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 16045 * respond to the results of an over-scroll operation. 16046 * 16047 * @param scrollX New X scroll value in pixels 16048 * @param scrollY New Y scroll value in pixels 16049 * @param clampedX True if scrollX was clamped to an over-scroll boundary 16050 * @param clampedY True if scrollY was clamped to an over-scroll boundary 16051 */ 16052 protected void onOverScrolled(int scrollX, int scrollY, 16053 boolean clampedX, boolean clampedY) { 16054 // Intentionally empty. 16055 } 16056 16057 /** 16058 * Returns the over-scroll mode for this view. The result will be 16059 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 16060 * (allow over-scrolling only if the view content is larger than the container), 16061 * or {@link #OVER_SCROLL_NEVER}. 16062 * 16063 * @return This view's over-scroll mode. 16064 */ 16065 public int getOverScrollMode() { 16066 return mOverScrollMode; 16067 } 16068 16069 /** 16070 * Set the over-scroll mode for this view. Valid over-scroll modes are 16071 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 16072 * (allow over-scrolling only if the view content is larger than the container), 16073 * or {@link #OVER_SCROLL_NEVER}. 16074 * 16075 * Setting the over-scroll mode of a view will have an effect only if the 16076 * view is capable of scrolling. 16077 * 16078 * @param overScrollMode The new over-scroll mode for this view. 16079 */ 16080 public void setOverScrollMode(int overScrollMode) { 16081 if (overScrollMode != OVER_SCROLL_ALWAYS && 16082 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 16083 overScrollMode != OVER_SCROLL_NEVER) { 16084 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 16085 } 16086 mOverScrollMode = overScrollMode; 16087 } 16088 16089 /** 16090 * Gets a scale factor that determines the distance the view should scroll 16091 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 16092 * @return The vertical scroll scale factor. 16093 * @hide 16094 */ 16095 protected float getVerticalScrollFactor() { 16096 if (mVerticalScrollFactor == 0) { 16097 TypedValue outValue = new TypedValue(); 16098 if (!mContext.getTheme().resolveAttribute( 16099 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 16100 throw new IllegalStateException( 16101 "Expected theme to define listPreferredItemHeight."); 16102 } 16103 mVerticalScrollFactor = outValue.getDimension( 16104 mContext.getResources().getDisplayMetrics()); 16105 } 16106 return mVerticalScrollFactor; 16107 } 16108 16109 /** 16110 * Gets a scale factor that determines the distance the view should scroll 16111 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 16112 * @return The horizontal scroll scale factor. 16113 * @hide 16114 */ 16115 protected float getHorizontalScrollFactor() { 16116 // TODO: Should use something else. 16117 return getVerticalScrollFactor(); 16118 } 16119 16120 /** 16121 * Return the value specifying the text direction or policy that was set with 16122 * {@link #setTextDirection(int)}. 16123 * 16124 * @return the defined text direction. It can be one of: 16125 * 16126 * {@link #TEXT_DIRECTION_INHERIT}, 16127 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16128 * {@link #TEXT_DIRECTION_ANY_RTL}, 16129 * {@link #TEXT_DIRECTION_LTR}, 16130 * {@link #TEXT_DIRECTION_RTL}, 16131 * {@link #TEXT_DIRECTION_LOCALE} 16132 * @hide 16133 */ 16134 @ViewDebug.ExportedProperty(category = "text", mapping = { 16135 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 16136 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 16137 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 16138 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 16139 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 16140 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 16141 }) 16142 public int getTextDirection() { 16143 return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT; 16144 } 16145 16146 /** 16147 * Set the text direction. 16148 * 16149 * @param textDirection the direction to set. Should be one of: 16150 * 16151 * {@link #TEXT_DIRECTION_INHERIT}, 16152 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16153 * {@link #TEXT_DIRECTION_ANY_RTL}, 16154 * {@link #TEXT_DIRECTION_LTR}, 16155 * {@link #TEXT_DIRECTION_RTL}, 16156 * {@link #TEXT_DIRECTION_LOCALE} 16157 * @hide 16158 */ 16159 public void setTextDirection(int textDirection) { 16160 if (getTextDirection() != textDirection) { 16161 // Reset the current text direction and the resolved one 16162 mPrivateFlags2 &= ~TEXT_DIRECTION_MASK; 16163 resetResolvedTextDirection(); 16164 // Set the new text direction 16165 mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK); 16166 // Refresh 16167 requestLayout(); 16168 invalidate(true); 16169 } 16170 } 16171 16172 /** 16173 * Return the resolved text direction. 16174 * 16175 * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches 16176 * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds 16177 * up the parent chain of the view. if there is no parent, then it will return the default 16178 * {@link #TEXT_DIRECTION_FIRST_STRONG}. 16179 * 16180 * @return the resolved text direction. Returns one of: 16181 * 16182 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16183 * {@link #TEXT_DIRECTION_ANY_RTL}, 16184 * {@link #TEXT_DIRECTION_LTR}, 16185 * {@link #TEXT_DIRECTION_RTL}, 16186 * {@link #TEXT_DIRECTION_LOCALE} 16187 * @hide 16188 */ 16189 public int getResolvedTextDirection() { 16190 // The text direction will be resolved only if needed 16191 if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) { 16192 resolveTextDirection(); 16193 } 16194 return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 16195 } 16196 16197 /** 16198 * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when 16199 * resolution is done. 16200 * @hide 16201 */ 16202 public void resolveTextDirection() { 16203 // Reset any previous text direction resolution 16204 mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK); 16205 16206 if (hasRtlSupport()) { 16207 // Set resolved text direction flag depending on text direction flag 16208 final int textDirection = getTextDirection(); 16209 switch(textDirection) { 16210 case TEXT_DIRECTION_INHERIT: 16211 if (canResolveTextDirection()) { 16212 ViewGroup viewGroup = ((ViewGroup) mParent); 16213 16214 // Set current resolved direction to the same value as the parent's one 16215 final int parentResolvedDirection = viewGroup.getResolvedTextDirection(); 16216 switch (parentResolvedDirection) { 16217 case TEXT_DIRECTION_FIRST_STRONG: 16218 case TEXT_DIRECTION_ANY_RTL: 16219 case TEXT_DIRECTION_LTR: 16220 case TEXT_DIRECTION_RTL: 16221 case TEXT_DIRECTION_LOCALE: 16222 mPrivateFlags2 |= 16223 (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 16224 break; 16225 default: 16226 // Default resolved direction is "first strong" heuristic 16227 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT; 16228 } 16229 } else { 16230 // We cannot do the resolution if there is no parent, so use the default one 16231 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT; 16232 } 16233 break; 16234 case TEXT_DIRECTION_FIRST_STRONG: 16235 case TEXT_DIRECTION_ANY_RTL: 16236 case TEXT_DIRECTION_LTR: 16237 case TEXT_DIRECTION_RTL: 16238 case TEXT_DIRECTION_LOCALE: 16239 // Resolved direction is the same as text direction 16240 mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 16241 break; 16242 default: 16243 // Default resolved direction is "first strong" heuristic 16244 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT; 16245 } 16246 } else { 16247 // Default resolved direction is "first strong" heuristic 16248 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT; 16249 } 16250 16251 // Set to resolved 16252 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED; 16253 onResolvedTextDirectionChanged(); 16254 } 16255 16256 /** 16257 * Called when text direction has been resolved. Subclasses that care about text direction 16258 * resolution should override this method. 16259 * 16260 * The default implementation does nothing. 16261 * @hide 16262 */ 16263 public void onResolvedTextDirectionChanged() { 16264 } 16265 16266 /** 16267 * Check if text direction resolution can be done. 16268 * 16269 * @return true if text direction resolution can be done otherwise return false. 16270 * @hide 16271 */ 16272 public boolean canResolveTextDirection() { 16273 switch (getTextDirection()) { 16274 case TEXT_DIRECTION_INHERIT: 16275 return (mParent != null) && (mParent instanceof ViewGroup); 16276 default: 16277 return true; 16278 } 16279 } 16280 16281 /** 16282 * Reset resolved text direction. Text direction can be resolved with a call to 16283 * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when 16284 * reset is done. 16285 * @hide 16286 */ 16287 public void resetResolvedTextDirection() { 16288 mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK); 16289 onResolvedTextDirectionReset(); 16290 } 16291 16292 /** 16293 * Called when text direction is reset. Subclasses that care about text direction reset should 16294 * override this method and do a reset of the text direction of their children. The default 16295 * implementation does nothing. 16296 * @hide 16297 */ 16298 public void onResolvedTextDirectionReset() { 16299 } 16300 16301 /** 16302 * Return the value specifying the text alignment or policy that was set with 16303 * {@link #setTextAlignment(int)}. 16304 * 16305 * @return the defined text alignment. It can be one of: 16306 * 16307 * {@link #TEXT_ALIGNMENT_INHERIT}, 16308 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16309 * {@link #TEXT_ALIGNMENT_CENTER}, 16310 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16311 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16312 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16313 * {@link #TEXT_ALIGNMENT_VIEW_END} 16314 * @hide 16315 */ 16316 @ViewDebug.ExportedProperty(category = "text", mapping = { 16317 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 16318 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 16319 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 16320 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 16321 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 16322 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 16323 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 16324 }) 16325 public int getTextAlignment() { 16326 return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT; 16327 } 16328 16329 /** 16330 * Set the text alignment. 16331 * 16332 * @param textAlignment The text alignment to set. Should be one of 16333 * 16334 * {@link #TEXT_ALIGNMENT_INHERIT}, 16335 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16336 * {@link #TEXT_ALIGNMENT_CENTER}, 16337 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16338 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16339 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16340 * {@link #TEXT_ALIGNMENT_VIEW_END} 16341 * 16342 * @attr ref android.R.styleable#View_textAlignment 16343 * @hide 16344 */ 16345 public void setTextAlignment(int textAlignment) { 16346 if (textAlignment != getTextAlignment()) { 16347 // Reset the current and resolved text alignment 16348 mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK; 16349 resetResolvedTextAlignment(); 16350 // Set the new text alignment 16351 mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK); 16352 // Refresh 16353 requestLayout(); 16354 invalidate(true); 16355 } 16356 } 16357 16358 /** 16359 * Return the resolved text alignment. 16360 * 16361 * The resolved text alignment. This needs resolution if the value is 16362 * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)} if it is 16363 * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view. 16364 * 16365 * @return the resolved text alignment. Returns one of: 16366 * 16367 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16368 * {@link #TEXT_ALIGNMENT_CENTER}, 16369 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16370 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16371 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16372 * {@link #TEXT_ALIGNMENT_VIEW_END} 16373 * @hide 16374 */ 16375 @ViewDebug.ExportedProperty(category = "text", mapping = { 16376 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 16377 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 16378 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 16379 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 16380 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 16381 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 16382 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 16383 }) 16384 public int getResolvedTextAlignment() { 16385 // If text alignment is not resolved, then resolve it 16386 if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) { 16387 resolveTextAlignment(); 16388 } 16389 return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 16390 } 16391 16392 /** 16393 * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when 16394 * resolution is done. 16395 * @hide 16396 */ 16397 public void resolveTextAlignment() { 16398 // Reset any previous text alignment resolution 16399 mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK); 16400 16401 if (hasRtlSupport()) { 16402 // Set resolved text alignment flag depending on text alignment flag 16403 final int textAlignment = getTextAlignment(); 16404 switch (textAlignment) { 16405 case TEXT_ALIGNMENT_INHERIT: 16406 // Check if we can resolve the text alignment 16407 if (canResolveLayoutDirection() && mParent instanceof View) { 16408 View view = (View) mParent; 16409 16410 final int parentResolvedTextAlignment = view.getResolvedTextAlignment(); 16411 switch (parentResolvedTextAlignment) { 16412 case TEXT_ALIGNMENT_GRAVITY: 16413 case TEXT_ALIGNMENT_TEXT_START: 16414 case TEXT_ALIGNMENT_TEXT_END: 16415 case TEXT_ALIGNMENT_CENTER: 16416 case TEXT_ALIGNMENT_VIEW_START: 16417 case TEXT_ALIGNMENT_VIEW_END: 16418 // Resolved text alignment is the same as the parent resolved 16419 // text alignment 16420 mPrivateFlags2 |= 16421 (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 16422 break; 16423 default: 16424 // Use default resolved text alignment 16425 mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16426 } 16427 } 16428 else { 16429 // We cannot do the resolution if there is no parent so use the default 16430 mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16431 } 16432 break; 16433 case TEXT_ALIGNMENT_GRAVITY: 16434 case TEXT_ALIGNMENT_TEXT_START: 16435 case TEXT_ALIGNMENT_TEXT_END: 16436 case TEXT_ALIGNMENT_CENTER: 16437 case TEXT_ALIGNMENT_VIEW_START: 16438 case TEXT_ALIGNMENT_VIEW_END: 16439 // Resolved text alignment is the same as text alignment 16440 mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 16441 break; 16442 default: 16443 // Use default resolved text alignment 16444 mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16445 } 16446 } else { 16447 // Use default resolved text alignment 16448 mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16449 } 16450 16451 // Set the resolved 16452 mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED; 16453 onResolvedTextAlignmentChanged(); 16454 } 16455 16456 /** 16457 * Check if text alignment resolution can be done. 16458 * 16459 * @return true if text alignment resolution can be done otherwise return false. 16460 * @hide 16461 */ 16462 public boolean canResolveTextAlignment() { 16463 switch (getTextAlignment()) { 16464 case TEXT_DIRECTION_INHERIT: 16465 return (mParent != null); 16466 default: 16467 return true; 16468 } 16469 } 16470 16471 /** 16472 * Called when text alignment has been resolved. Subclasses that care about text alignment 16473 * resolution should override this method. 16474 * 16475 * The default implementation does nothing. 16476 * @hide 16477 */ 16478 public void onResolvedTextAlignmentChanged() { 16479 } 16480 16481 /** 16482 * Reset resolved text alignment. Text alignment can be resolved with a call to 16483 * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when 16484 * reset is done. 16485 * @hide 16486 */ 16487 public void resetResolvedTextAlignment() { 16488 // Reset any previous text alignment resolution 16489 mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK); 16490 onResolvedTextAlignmentReset(); 16491 } 16492 16493 /** 16494 * Called when text alignment is reset. Subclasses that care about text alignment reset should 16495 * override this method and do a reset of the text alignment of their children. The default 16496 * implementation does nothing. 16497 * @hide 16498 */ 16499 public void onResolvedTextAlignmentReset() { 16500 } 16501 16502 // 16503 // Properties 16504 // 16505 /** 16506 * A Property wrapper around the <code>alpha</code> functionality handled by the 16507 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 16508 */ 16509 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 16510 @Override 16511 public void setValue(View object, float value) { 16512 object.setAlpha(value); 16513 } 16514 16515 @Override 16516 public Float get(View object) { 16517 return object.getAlpha(); 16518 } 16519 }; 16520 16521 /** 16522 * A Property wrapper around the <code>translationX</code> functionality handled by the 16523 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 16524 */ 16525 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 16526 @Override 16527 public void setValue(View object, float value) { 16528 object.setTranslationX(value); 16529 } 16530 16531 @Override 16532 public Float get(View object) { 16533 return object.getTranslationX(); 16534 } 16535 }; 16536 16537 /** 16538 * A Property wrapper around the <code>translationY</code> functionality handled by the 16539 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 16540 */ 16541 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 16542 @Override 16543 public void setValue(View object, float value) { 16544 object.setTranslationY(value); 16545 } 16546 16547 @Override 16548 public Float get(View object) { 16549 return object.getTranslationY(); 16550 } 16551 }; 16552 16553 /** 16554 * A Property wrapper around the <code>x</code> functionality handled by the 16555 * {@link View#setX(float)} and {@link View#getX()} methods. 16556 */ 16557 public static final Property<View, Float> X = new FloatProperty<View>("x") { 16558 @Override 16559 public void setValue(View object, float value) { 16560 object.setX(value); 16561 } 16562 16563 @Override 16564 public Float get(View object) { 16565 return object.getX(); 16566 } 16567 }; 16568 16569 /** 16570 * A Property wrapper around the <code>y</code> functionality handled by the 16571 * {@link View#setY(float)} and {@link View#getY()} methods. 16572 */ 16573 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 16574 @Override 16575 public void setValue(View object, float value) { 16576 object.setY(value); 16577 } 16578 16579 @Override 16580 public Float get(View object) { 16581 return object.getY(); 16582 } 16583 }; 16584 16585 /** 16586 * A Property wrapper around the <code>rotation</code> functionality handled by the 16587 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 16588 */ 16589 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 16590 @Override 16591 public void setValue(View object, float value) { 16592 object.setRotation(value); 16593 } 16594 16595 @Override 16596 public Float get(View object) { 16597 return object.getRotation(); 16598 } 16599 }; 16600 16601 /** 16602 * A Property wrapper around the <code>rotationX</code> functionality handled by the 16603 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 16604 */ 16605 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 16606 @Override 16607 public void setValue(View object, float value) { 16608 object.setRotationX(value); 16609 } 16610 16611 @Override 16612 public Float get(View object) { 16613 return object.getRotationX(); 16614 } 16615 }; 16616 16617 /** 16618 * A Property wrapper around the <code>rotationY</code> functionality handled by the 16619 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 16620 */ 16621 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 16622 @Override 16623 public void setValue(View object, float value) { 16624 object.setRotationY(value); 16625 } 16626 16627 @Override 16628 public Float get(View object) { 16629 return object.getRotationY(); 16630 } 16631 }; 16632 16633 /** 16634 * A Property wrapper around the <code>scaleX</code> functionality handled by the 16635 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 16636 */ 16637 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 16638 @Override 16639 public void setValue(View object, float value) { 16640 object.setScaleX(value); 16641 } 16642 16643 @Override 16644 public Float get(View object) { 16645 return object.getScaleX(); 16646 } 16647 }; 16648 16649 /** 16650 * A Property wrapper around the <code>scaleY</code> functionality handled by the 16651 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 16652 */ 16653 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 16654 @Override 16655 public void setValue(View object, float value) { 16656 object.setScaleY(value); 16657 } 16658 16659 @Override 16660 public Float get(View object) { 16661 return object.getScaleY(); 16662 } 16663 }; 16664 16665 /** 16666 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 16667 * Each MeasureSpec represents a requirement for either the width or the height. 16668 * A MeasureSpec is comprised of a size and a mode. There are three possible 16669 * modes: 16670 * <dl> 16671 * <dt>UNSPECIFIED</dt> 16672 * <dd> 16673 * The parent has not imposed any constraint on the child. It can be whatever size 16674 * it wants. 16675 * </dd> 16676 * 16677 * <dt>EXACTLY</dt> 16678 * <dd> 16679 * The parent has determined an exact size for the child. The child is going to be 16680 * given those bounds regardless of how big it wants to be. 16681 * </dd> 16682 * 16683 * <dt>AT_MOST</dt> 16684 * <dd> 16685 * The child can be as large as it wants up to the specified size. 16686 * </dd> 16687 * </dl> 16688 * 16689 * MeasureSpecs are implemented as ints to reduce object allocation. This class 16690 * is provided to pack and unpack the <size, mode> tuple into the int. 16691 */ 16692 public static class MeasureSpec { 16693 private static final int MODE_SHIFT = 30; 16694 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 16695 16696 /** 16697 * Measure specification mode: The parent has not imposed any constraint 16698 * on the child. It can be whatever size it wants. 16699 */ 16700 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 16701 16702 /** 16703 * Measure specification mode: The parent has determined an exact size 16704 * for the child. The child is going to be given those bounds regardless 16705 * of how big it wants to be. 16706 */ 16707 public static final int EXACTLY = 1 << MODE_SHIFT; 16708 16709 /** 16710 * Measure specification mode: The child can be as large as it wants up 16711 * to the specified size. 16712 */ 16713 public static final int AT_MOST = 2 << MODE_SHIFT; 16714 16715 /** 16716 * Creates a measure specification based on the supplied size and mode. 16717 * 16718 * The mode must always be one of the following: 16719 * <ul> 16720 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 16721 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 16722 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 16723 * </ul> 16724 * 16725 * @param size the size of the measure specification 16726 * @param mode the mode of the measure specification 16727 * @return the measure specification based on size and mode 16728 */ 16729 public static int makeMeasureSpec(int size, int mode) { 16730 return size + mode; 16731 } 16732 16733 /** 16734 * Extracts the mode from the supplied measure specification. 16735 * 16736 * @param measureSpec the measure specification to extract the mode from 16737 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 16738 * {@link android.view.View.MeasureSpec#AT_MOST} or 16739 * {@link android.view.View.MeasureSpec#EXACTLY} 16740 */ 16741 public static int getMode(int measureSpec) { 16742 return (measureSpec & MODE_MASK); 16743 } 16744 16745 /** 16746 * Extracts the size from the supplied measure specification. 16747 * 16748 * @param measureSpec the measure specification to extract the size from 16749 * @return the size in pixels defined in the supplied measure specification 16750 */ 16751 public static int getSize(int measureSpec) { 16752 return (measureSpec & ~MODE_MASK); 16753 } 16754 16755 /** 16756 * Returns a String representation of the specified measure 16757 * specification. 16758 * 16759 * @param measureSpec the measure specification to convert to a String 16760 * @return a String with the following format: "MeasureSpec: MODE SIZE" 16761 */ 16762 public static String toString(int measureSpec) { 16763 int mode = getMode(measureSpec); 16764 int size = getSize(measureSpec); 16765 16766 StringBuilder sb = new StringBuilder("MeasureSpec: "); 16767 16768 if (mode == UNSPECIFIED) 16769 sb.append("UNSPECIFIED "); 16770 else if (mode == EXACTLY) 16771 sb.append("EXACTLY "); 16772 else if (mode == AT_MOST) 16773 sb.append("AT_MOST "); 16774 else 16775 sb.append(mode).append(" "); 16776 16777 sb.append(size); 16778 return sb.toString(); 16779 } 16780 } 16781 16782 class CheckForLongPress implements Runnable { 16783 16784 private int mOriginalWindowAttachCount; 16785 16786 public void run() { 16787 if (isPressed() && (mParent != null) 16788 && mOriginalWindowAttachCount == mWindowAttachCount) { 16789 if (performLongClick()) { 16790 mHasPerformedLongPress = true; 16791 } 16792 } 16793 } 16794 16795 public void rememberWindowAttachCount() { 16796 mOriginalWindowAttachCount = mWindowAttachCount; 16797 } 16798 } 16799 16800 private final class CheckForTap implements Runnable { 16801 public void run() { 16802 mPrivateFlags &= ~PREPRESSED; 16803 setPressed(true); 16804 checkForLongClick(ViewConfiguration.getTapTimeout()); 16805 } 16806 } 16807 16808 private final class PerformClick implements Runnable { 16809 public void run() { 16810 performClick(); 16811 } 16812 } 16813 16814 /** @hide */ 16815 public void hackTurnOffWindowResizeAnim(boolean off) { 16816 mAttachInfo.mTurnOffWindowResizeAnim = off; 16817 } 16818 16819 /** 16820 * This method returns a ViewPropertyAnimator object, which can be used to animate 16821 * specific properties on this View. 16822 * 16823 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 16824 */ 16825 public ViewPropertyAnimator animate() { 16826 if (mAnimator == null) { 16827 mAnimator = new ViewPropertyAnimator(this); 16828 } 16829 return mAnimator; 16830 } 16831 16832 /** 16833 * Interface definition for a callback to be invoked when a key event is 16834 * dispatched to this view. The callback will be invoked before the key 16835 * event is given to the view. 16836 */ 16837 public interface OnKeyListener { 16838 /** 16839 * Called when a key is dispatched to a view. This allows listeners to 16840 * get a chance to respond before the target view. 16841 * 16842 * @param v The view the key has been dispatched to. 16843 * @param keyCode The code for the physical key that was pressed 16844 * @param event The KeyEvent object containing full information about 16845 * the event. 16846 * @return True if the listener has consumed the event, false otherwise. 16847 */ 16848 boolean onKey(View v, int keyCode, KeyEvent event); 16849 } 16850 16851 /** 16852 * Interface definition for a callback to be invoked when a touch event is 16853 * dispatched to this view. The callback will be invoked before the touch 16854 * event is given to the view. 16855 */ 16856 public interface OnTouchListener { 16857 /** 16858 * Called when a touch event is dispatched to a view. This allows listeners to 16859 * get a chance to respond before the target view. 16860 * 16861 * @param v The view the touch event has been dispatched to. 16862 * @param event The MotionEvent object containing full information about 16863 * the event. 16864 * @return True if the listener has consumed the event, false otherwise. 16865 */ 16866 boolean onTouch(View v, MotionEvent event); 16867 } 16868 16869 /** 16870 * Interface definition for a callback to be invoked when a hover event is 16871 * dispatched to this view. The callback will be invoked before the hover 16872 * event is given to the view. 16873 */ 16874 public interface OnHoverListener { 16875 /** 16876 * Called when a hover event is dispatched to a view. This allows listeners to 16877 * get a chance to respond before the target view. 16878 * 16879 * @param v The view the hover event has been dispatched to. 16880 * @param event The MotionEvent object containing full information about 16881 * the event. 16882 * @return True if the listener has consumed the event, false otherwise. 16883 */ 16884 boolean onHover(View v, MotionEvent event); 16885 } 16886 16887 /** 16888 * Interface definition for a callback to be invoked when a generic motion event is 16889 * dispatched to this view. The callback will be invoked before the generic motion 16890 * event is given to the view. 16891 */ 16892 public interface OnGenericMotionListener { 16893 /** 16894 * Called when a generic motion event is dispatched to a view. This allows listeners to 16895 * get a chance to respond before the target view. 16896 * 16897 * @param v The view the generic motion event has been dispatched to. 16898 * @param event The MotionEvent object containing full information about 16899 * the event. 16900 * @return True if the listener has consumed the event, false otherwise. 16901 */ 16902 boolean onGenericMotion(View v, MotionEvent event); 16903 } 16904 16905 /** 16906 * Interface definition for a callback to be invoked when a view has been clicked and held. 16907 */ 16908 public interface OnLongClickListener { 16909 /** 16910 * Called when a view has been clicked and held. 16911 * 16912 * @param v The view that was clicked and held. 16913 * 16914 * @return true if the callback consumed the long click, false otherwise. 16915 */ 16916 boolean onLongClick(View v); 16917 } 16918 16919 /** 16920 * Interface definition for a callback to be invoked when a drag is being dispatched 16921 * to this view. The callback will be invoked before the hosting view's own 16922 * onDrag(event) method. If the listener wants to fall back to the hosting view's 16923 * onDrag(event) behavior, it should return 'false' from this callback. 16924 * 16925 * <div class="special reference"> 16926 * <h3>Developer Guides</h3> 16927 * <p>For a guide to implementing drag and drop features, read the 16928 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 16929 * </div> 16930 */ 16931 public interface OnDragListener { 16932 /** 16933 * Called when a drag event is dispatched to a view. This allows listeners 16934 * to get a chance to override base View behavior. 16935 * 16936 * @param v The View that received the drag event. 16937 * @param event The {@link android.view.DragEvent} object for the drag event. 16938 * @return {@code true} if the drag event was handled successfully, or {@code false} 16939 * if the drag event was not handled. Note that {@code false} will trigger the View 16940 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 16941 */ 16942 boolean onDrag(View v, DragEvent event); 16943 } 16944 16945 /** 16946 * Interface definition for a callback to be invoked when the focus state of 16947 * a view changed. 16948 */ 16949 public interface OnFocusChangeListener { 16950 /** 16951 * Called when the focus state of a view has changed. 16952 * 16953 * @param v The view whose state has changed. 16954 * @param hasFocus The new focus state of v. 16955 */ 16956 void onFocusChange(View v, boolean hasFocus); 16957 } 16958 16959 /** 16960 * Interface definition for a callback to be invoked when a view is clicked. 16961 */ 16962 public interface OnClickListener { 16963 /** 16964 * Called when a view has been clicked. 16965 * 16966 * @param v The view that was clicked. 16967 */ 16968 void onClick(View v); 16969 } 16970 16971 /** 16972 * Interface definition for a callback to be invoked when the context menu 16973 * for this view is being built. 16974 */ 16975 public interface OnCreateContextMenuListener { 16976 /** 16977 * Called when the context menu for this view is being built. It is not 16978 * safe to hold onto the menu after this method returns. 16979 * 16980 * @param menu The context menu that is being built 16981 * @param v The view for which the context menu is being built 16982 * @param menuInfo Extra information about the item for which the 16983 * context menu should be shown. This information will vary 16984 * depending on the class of v. 16985 */ 16986 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 16987 } 16988 16989 /** 16990 * Interface definition for a callback to be invoked when the status bar changes 16991 * visibility. This reports <strong>global</strong> changes to the system UI 16992 * state, not what the application is requesting. 16993 * 16994 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 16995 */ 16996 public interface OnSystemUiVisibilityChangeListener { 16997 /** 16998 * Called when the status bar changes visibility because of a call to 16999 * {@link View#setSystemUiVisibility(int)}. 17000 * 17001 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17002 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 17003 * This tells you the <strong>global</strong> state of these UI visibility 17004 * flags, not what your app is currently applying. 17005 */ 17006 public void onSystemUiVisibilityChange(int visibility); 17007 } 17008 17009 /** 17010 * Interface definition for a callback to be invoked when this view is attached 17011 * or detached from its window. 17012 */ 17013 public interface OnAttachStateChangeListener { 17014 /** 17015 * Called when the view is attached to a window. 17016 * @param v The view that was attached 17017 */ 17018 public void onViewAttachedToWindow(View v); 17019 /** 17020 * Called when the view is detached from a window. 17021 * @param v The view that was detached 17022 */ 17023 public void onViewDetachedFromWindow(View v); 17024 } 17025 17026 private final class UnsetPressedState implements Runnable { 17027 public void run() { 17028 setPressed(false); 17029 } 17030 } 17031 17032 /** 17033 * Base class for derived classes that want to save and restore their own 17034 * state in {@link android.view.View#onSaveInstanceState()}. 17035 */ 17036 public static class BaseSavedState extends AbsSavedState { 17037 /** 17038 * Constructor used when reading from a parcel. Reads the state of the superclass. 17039 * 17040 * @param source 17041 */ 17042 public BaseSavedState(Parcel source) { 17043 super(source); 17044 } 17045 17046 /** 17047 * Constructor called by derived classes when creating their SavedState objects 17048 * 17049 * @param superState The state of the superclass of this view 17050 */ 17051 public BaseSavedState(Parcelable superState) { 17052 super(superState); 17053 } 17054 17055 public static final Parcelable.Creator<BaseSavedState> CREATOR = 17056 new Parcelable.Creator<BaseSavedState>() { 17057 public BaseSavedState createFromParcel(Parcel in) { 17058 return new BaseSavedState(in); 17059 } 17060 17061 public BaseSavedState[] newArray(int size) { 17062 return new BaseSavedState[size]; 17063 } 17064 }; 17065 } 17066 17067 /** 17068 * A set of information given to a view when it is attached to its parent 17069 * window. 17070 */ 17071 static class AttachInfo { 17072 interface Callbacks { 17073 void playSoundEffect(int effectId); 17074 boolean performHapticFeedback(int effectId, boolean always); 17075 } 17076 17077 /** 17078 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 17079 * to a Handler. This class contains the target (View) to invalidate and 17080 * the coordinates of the dirty rectangle. 17081 * 17082 * For performance purposes, this class also implements a pool of up to 17083 * POOL_LIMIT objects that get reused. This reduces memory allocations 17084 * whenever possible. 17085 */ 17086 static class InvalidateInfo implements Poolable<InvalidateInfo> { 17087 private static final int POOL_LIMIT = 10; 17088 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 17089 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 17090 public InvalidateInfo newInstance() { 17091 return new InvalidateInfo(); 17092 } 17093 17094 public void onAcquired(InvalidateInfo element) { 17095 } 17096 17097 public void onReleased(InvalidateInfo element) { 17098 element.target = null; 17099 } 17100 }, POOL_LIMIT) 17101 ); 17102 17103 private InvalidateInfo mNext; 17104 private boolean mIsPooled; 17105 17106 View target; 17107 17108 int left; 17109 int top; 17110 int right; 17111 int bottom; 17112 17113 public void setNextPoolable(InvalidateInfo element) { 17114 mNext = element; 17115 } 17116 17117 public InvalidateInfo getNextPoolable() { 17118 return mNext; 17119 } 17120 17121 static InvalidateInfo acquire() { 17122 return sPool.acquire(); 17123 } 17124 17125 void release() { 17126 sPool.release(this); 17127 } 17128 17129 public boolean isPooled() { 17130 return mIsPooled; 17131 } 17132 17133 public void setPooled(boolean isPooled) { 17134 mIsPooled = isPooled; 17135 } 17136 } 17137 17138 final IWindowSession mSession; 17139 17140 final IWindow mWindow; 17141 17142 final IBinder mWindowToken; 17143 17144 final Callbacks mRootCallbacks; 17145 17146 HardwareCanvas mHardwareCanvas; 17147 17148 /** 17149 * The top view of the hierarchy. 17150 */ 17151 View mRootView; 17152 17153 IBinder mPanelParentWindowToken; 17154 Surface mSurface; 17155 17156 boolean mHardwareAccelerated; 17157 boolean mHardwareAccelerationRequested; 17158 HardwareRenderer mHardwareRenderer; 17159 17160 boolean mScreenOn; 17161 17162 /** 17163 * Scale factor used by the compatibility mode 17164 */ 17165 float mApplicationScale; 17166 17167 /** 17168 * Indicates whether the application is in compatibility mode 17169 */ 17170 boolean mScalingRequired; 17171 17172 /** 17173 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 17174 */ 17175 boolean mTurnOffWindowResizeAnim; 17176 17177 /** 17178 * Left position of this view's window 17179 */ 17180 int mWindowLeft; 17181 17182 /** 17183 * Top position of this view's window 17184 */ 17185 int mWindowTop; 17186 17187 /** 17188 * Indicates whether views need to use 32-bit drawing caches 17189 */ 17190 boolean mUse32BitDrawingCache; 17191 17192 /** 17193 * For windows that are full-screen but using insets to layout inside 17194 * of the screen decorations, these are the current insets for the 17195 * content of the window. 17196 */ 17197 final Rect mContentInsets = new Rect(); 17198 17199 /** 17200 * For windows that are full-screen but using insets to layout inside 17201 * of the screen decorations, these are the current insets for the 17202 * actual visible parts of the window. 17203 */ 17204 final Rect mVisibleInsets = new Rect(); 17205 17206 /** 17207 * The internal insets given by this window. This value is 17208 * supplied by the client (through 17209 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 17210 * be given to the window manager when changed to be used in laying 17211 * out windows behind it. 17212 */ 17213 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 17214 = new ViewTreeObserver.InternalInsetsInfo(); 17215 17216 /** 17217 * All views in the window's hierarchy that serve as scroll containers, 17218 * used to determine if the window can be resized or must be panned 17219 * to adjust for a soft input area. 17220 */ 17221 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 17222 17223 final KeyEvent.DispatcherState mKeyDispatchState 17224 = new KeyEvent.DispatcherState(); 17225 17226 /** 17227 * Indicates whether the view's window currently has the focus. 17228 */ 17229 boolean mHasWindowFocus; 17230 17231 /** 17232 * The current visibility of the window. 17233 */ 17234 int mWindowVisibility; 17235 17236 /** 17237 * Indicates the time at which drawing started to occur. 17238 */ 17239 long mDrawingTime; 17240 17241 /** 17242 * Indicates whether or not ignoring the DIRTY_MASK flags. 17243 */ 17244 boolean mIgnoreDirtyState; 17245 17246 /** 17247 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 17248 * to avoid clearing that flag prematurely. 17249 */ 17250 boolean mSetIgnoreDirtyState = false; 17251 17252 /** 17253 * Indicates whether the view's window is currently in touch mode. 17254 */ 17255 boolean mInTouchMode; 17256 17257 /** 17258 * Indicates that ViewAncestor should trigger a global layout change 17259 * the next time it performs a traversal 17260 */ 17261 boolean mRecomputeGlobalAttributes; 17262 17263 /** 17264 * Always report new attributes at next traversal. 17265 */ 17266 boolean mForceReportNewAttributes; 17267 17268 /** 17269 * Set during a traveral if any views want to keep the screen on. 17270 */ 17271 boolean mKeepScreenOn; 17272 17273 /** 17274 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 17275 */ 17276 int mSystemUiVisibility; 17277 17278 /** 17279 * Hack to force certain system UI visibility flags to be cleared. 17280 */ 17281 int mDisabledSystemUiVisibility; 17282 17283 /** 17284 * Last global system UI visibility reported by the window manager. 17285 */ 17286 int mGlobalSystemUiVisibility; 17287 17288 /** 17289 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 17290 * attached. 17291 */ 17292 boolean mHasSystemUiListeners; 17293 17294 /** 17295 * Set if the visibility of any views has changed. 17296 */ 17297 boolean mViewVisibilityChanged; 17298 17299 /** 17300 * Set to true if a view has been scrolled. 17301 */ 17302 boolean mViewScrollChanged; 17303 17304 /** 17305 * Global to the view hierarchy used as a temporary for dealing with 17306 * x/y points in the transparent region computations. 17307 */ 17308 final int[] mTransparentLocation = new int[2]; 17309 17310 /** 17311 * Global to the view hierarchy used as a temporary for dealing with 17312 * x/y points in the ViewGroup.invalidateChild implementation. 17313 */ 17314 final int[] mInvalidateChildLocation = new int[2]; 17315 17316 17317 /** 17318 * Global to the view hierarchy used as a temporary for dealing with 17319 * x/y location when view is transformed. 17320 */ 17321 final float[] mTmpTransformLocation = new float[2]; 17322 17323 /** 17324 * The view tree observer used to dispatch global events like 17325 * layout, pre-draw, touch mode change, etc. 17326 */ 17327 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 17328 17329 /** 17330 * A Canvas used by the view hierarchy to perform bitmap caching. 17331 */ 17332 Canvas mCanvas; 17333 17334 /** 17335 * The view root impl. 17336 */ 17337 final ViewRootImpl mViewRootImpl; 17338 17339 /** 17340 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 17341 * handler can be used to pump events in the UI events queue. 17342 */ 17343 final Handler mHandler; 17344 17345 /** 17346 * Temporary for use in computing invalidate rectangles while 17347 * calling up the hierarchy. 17348 */ 17349 final Rect mTmpInvalRect = new Rect(); 17350 17351 /** 17352 * Temporary for use in computing hit areas with transformed views 17353 */ 17354 final RectF mTmpTransformRect = new RectF(); 17355 17356 /** 17357 * Temporary list for use in collecting focusable descendents of a view. 17358 */ 17359 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 17360 17361 /** 17362 * The id of the window for accessibility purposes. 17363 */ 17364 int mAccessibilityWindowId = View.NO_ID; 17365 17366 /** 17367 * Whether to ingore not exposed for accessibility Views when 17368 * reporting the view tree to accessibility services. 17369 */ 17370 boolean mIncludeNotImportantViews; 17371 17372 /** 17373 * The drawable for highlighting accessibility focus. 17374 */ 17375 Drawable mAccessibilityFocusDrawable; 17376 17377 /** 17378 * Show where the margins, bounds and layout bounds are for each view. 17379 */ 17380 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 17381 17382 /** 17383 * Point used to compute visible regions. 17384 */ 17385 final Point mPoint = new Point(); 17386 17387 /** 17388 * Creates a new set of attachment information with the specified 17389 * events handler and thread. 17390 * 17391 * @param handler the events handler the view must use 17392 */ 17393 AttachInfo(IWindowSession session, IWindow window, 17394 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 17395 mSession = session; 17396 mWindow = window; 17397 mWindowToken = window.asBinder(); 17398 mViewRootImpl = viewRootImpl; 17399 mHandler = handler; 17400 mRootCallbacks = effectPlayer; 17401 } 17402 } 17403 17404 /** 17405 * <p>ScrollabilityCache holds various fields used by a View when scrolling 17406 * is supported. This avoids keeping too many unused fields in most 17407 * instances of View.</p> 17408 */ 17409 private static class ScrollabilityCache implements Runnable { 17410 17411 /** 17412 * Scrollbars are not visible 17413 */ 17414 public static final int OFF = 0; 17415 17416 /** 17417 * Scrollbars are visible 17418 */ 17419 public static final int ON = 1; 17420 17421 /** 17422 * Scrollbars are fading away 17423 */ 17424 public static final int FADING = 2; 17425 17426 public boolean fadeScrollBars; 17427 17428 public int fadingEdgeLength; 17429 public int scrollBarDefaultDelayBeforeFade; 17430 public int scrollBarFadeDuration; 17431 17432 public int scrollBarSize; 17433 public ScrollBarDrawable scrollBar; 17434 public float[] interpolatorValues; 17435 public View host; 17436 17437 public final Paint paint; 17438 public final Matrix matrix; 17439 public Shader shader; 17440 17441 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 17442 17443 private static final float[] OPAQUE = { 255 }; 17444 private static final float[] TRANSPARENT = { 0.0f }; 17445 17446 /** 17447 * When fading should start. This time moves into the future every time 17448 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 17449 */ 17450 public long fadeStartTime; 17451 17452 17453 /** 17454 * The current state of the scrollbars: ON, OFF, or FADING 17455 */ 17456 public int state = OFF; 17457 17458 private int mLastColor; 17459 17460 public ScrollabilityCache(ViewConfiguration configuration, View host) { 17461 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 17462 scrollBarSize = configuration.getScaledScrollBarSize(); 17463 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 17464 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 17465 17466 paint = new Paint(); 17467 matrix = new Matrix(); 17468 // use use a height of 1, and then wack the matrix each time we 17469 // actually use it. 17470 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 17471 17472 paint.setShader(shader); 17473 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 17474 this.host = host; 17475 } 17476 17477 public void setFadeColor(int color) { 17478 if (color != 0 && color != mLastColor) { 17479 mLastColor = color; 17480 color |= 0xFF000000; 17481 17482 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 17483 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 17484 17485 paint.setShader(shader); 17486 // Restore the default transfer mode (src_over) 17487 paint.setXfermode(null); 17488 } 17489 } 17490 17491 public void run() { 17492 long now = AnimationUtils.currentAnimationTimeMillis(); 17493 if (now >= fadeStartTime) { 17494 17495 // the animation fades the scrollbars out by changing 17496 // the opacity (alpha) from fully opaque to fully 17497 // transparent 17498 int nextFrame = (int) now; 17499 int framesCount = 0; 17500 17501 Interpolator interpolator = scrollBarInterpolator; 17502 17503 // Start opaque 17504 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 17505 17506 // End transparent 17507 nextFrame += scrollBarFadeDuration; 17508 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 17509 17510 state = FADING; 17511 17512 // Kick off the fade animation 17513 host.invalidate(true); 17514 } 17515 } 17516 } 17517 17518 /** 17519 * Resuable callback for sending 17520 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 17521 */ 17522 private class SendViewScrolledAccessibilityEvent implements Runnable { 17523 public volatile boolean mIsPending; 17524 17525 public void run() { 17526 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 17527 mIsPending = false; 17528 } 17529 } 17530 17531 /** 17532 * <p> 17533 * This class represents a delegate that can be registered in a {@link View} 17534 * to enhance accessibility support via composition rather via inheritance. 17535 * It is specifically targeted to widget developers that extend basic View 17536 * classes i.e. classes in package android.view, that would like their 17537 * applications to be backwards compatible. 17538 * </p> 17539 * <div class="special reference"> 17540 * <h3>Developer Guides</h3> 17541 * <p>For more information about making applications accessible, read the 17542 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 17543 * developer guide.</p> 17544 * </div> 17545 * <p> 17546 * A scenario in which a developer would like to use an accessibility delegate 17547 * is overriding a method introduced in a later API version then the minimal API 17548 * version supported by the application. For example, the method 17549 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 17550 * in API version 4 when the accessibility APIs were first introduced. If a 17551 * developer would like his application to run on API version 4 devices (assuming 17552 * all other APIs used by the application are version 4 or lower) and take advantage 17553 * of this method, instead of overriding the method which would break the application's 17554 * backwards compatibility, he can override the corresponding method in this 17555 * delegate and register the delegate in the target View if the API version of 17556 * the system is high enough i.e. the API version is same or higher to the API 17557 * version that introduced 17558 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 17559 * </p> 17560 * <p> 17561 * Here is an example implementation: 17562 * </p> 17563 * <code><pre><p> 17564 * if (Build.VERSION.SDK_INT >= 14) { 17565 * // If the API version is equal of higher than the version in 17566 * // which onInitializeAccessibilityNodeInfo was introduced we 17567 * // register a delegate with a customized implementation. 17568 * View view = findViewById(R.id.view_id); 17569 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 17570 * public void onInitializeAccessibilityNodeInfo(View host, 17571 * AccessibilityNodeInfo info) { 17572 * // Let the default implementation populate the info. 17573 * super.onInitializeAccessibilityNodeInfo(host, info); 17574 * // Set some other information. 17575 * info.setEnabled(host.isEnabled()); 17576 * } 17577 * }); 17578 * } 17579 * </code></pre></p> 17580 * <p> 17581 * This delegate contains methods that correspond to the accessibility methods 17582 * in View. If a delegate has been specified the implementation in View hands 17583 * off handling to the corresponding method in this delegate. The default 17584 * implementation the delegate methods behaves exactly as the corresponding 17585 * method in View for the case of no accessibility delegate been set. Hence, 17586 * to customize the behavior of a View method, clients can override only the 17587 * corresponding delegate method without altering the behavior of the rest 17588 * accessibility related methods of the host view. 17589 * </p> 17590 */ 17591 public static class AccessibilityDelegate { 17592 17593 /** 17594 * Sends an accessibility event of the given type. If accessibility is not 17595 * enabled this method has no effect. 17596 * <p> 17597 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 17598 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 17599 * been set. 17600 * </p> 17601 * 17602 * @param host The View hosting the delegate. 17603 * @param eventType The type of the event to send. 17604 * 17605 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 17606 */ 17607 public void sendAccessibilityEvent(View host, int eventType) { 17608 host.sendAccessibilityEventInternal(eventType); 17609 } 17610 17611 /** 17612 * Performs the specified accessibility action on the view. For 17613 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 17614 * <p> 17615 * The default implementation behaves as 17616 * {@link View#performAccessibilityAction(int, Bundle) 17617 * View#performAccessibilityAction(int, Bundle)} for the case of 17618 * no accessibility delegate been set. 17619 * </p> 17620 * 17621 * @param action The action to perform. 17622 * @return Whether the action was performed. 17623 * 17624 * @see View#performAccessibilityAction(int, Bundle) 17625 * View#performAccessibilityAction(int, Bundle) 17626 */ 17627 public boolean performAccessibilityAction(View host, int action, Bundle args) { 17628 return host.performAccessibilityActionInternal(action, args); 17629 } 17630 17631 /** 17632 * Sends an accessibility event. This method behaves exactly as 17633 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 17634 * empty {@link AccessibilityEvent} and does not perform a check whether 17635 * accessibility is enabled. 17636 * <p> 17637 * The default implementation behaves as 17638 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 17639 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 17640 * the case of no accessibility delegate been set. 17641 * </p> 17642 * 17643 * @param host The View hosting the delegate. 17644 * @param event The event to send. 17645 * 17646 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 17647 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 17648 */ 17649 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 17650 host.sendAccessibilityEventUncheckedInternal(event); 17651 } 17652 17653 /** 17654 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 17655 * to its children for adding their text content to the event. 17656 * <p> 17657 * The default implementation behaves as 17658 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 17659 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 17660 * the case of no accessibility delegate been set. 17661 * </p> 17662 * 17663 * @param host The View hosting the delegate. 17664 * @param event The event. 17665 * @return True if the event population was completed. 17666 * 17667 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 17668 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 17669 */ 17670 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 17671 return host.dispatchPopulateAccessibilityEventInternal(event); 17672 } 17673 17674 /** 17675 * Gives a chance to the host View to populate the accessibility event with its 17676 * text content. 17677 * <p> 17678 * The default implementation behaves as 17679 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 17680 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 17681 * the case of no accessibility delegate been set. 17682 * </p> 17683 * 17684 * @param host The View hosting the delegate. 17685 * @param event The accessibility event which to populate. 17686 * 17687 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 17688 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 17689 */ 17690 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 17691 host.onPopulateAccessibilityEventInternal(event); 17692 } 17693 17694 /** 17695 * Initializes an {@link AccessibilityEvent} with information about the 17696 * the host View which is the event source. 17697 * <p> 17698 * The default implementation behaves as 17699 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 17700 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 17701 * the case of no accessibility delegate been set. 17702 * </p> 17703 * 17704 * @param host The View hosting the delegate. 17705 * @param event The event to initialize. 17706 * 17707 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 17708 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 17709 */ 17710 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 17711 host.onInitializeAccessibilityEventInternal(event); 17712 } 17713 17714 /** 17715 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 17716 * <p> 17717 * The default implementation behaves as 17718 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 17719 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 17720 * the case of no accessibility delegate been set. 17721 * </p> 17722 * 17723 * @param host The View hosting the delegate. 17724 * @param info The instance to initialize. 17725 * 17726 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 17727 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 17728 */ 17729 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 17730 host.onInitializeAccessibilityNodeInfoInternal(info); 17731 } 17732 17733 /** 17734 * Called when a child of the host View has requested sending an 17735 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 17736 * to augment the event. 17737 * <p> 17738 * The default implementation behaves as 17739 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 17740 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 17741 * the case of no accessibility delegate been set. 17742 * </p> 17743 * 17744 * @param host The View hosting the delegate. 17745 * @param child The child which requests sending the event. 17746 * @param event The event to be sent. 17747 * @return True if the event should be sent 17748 * 17749 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 17750 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 17751 */ 17752 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 17753 AccessibilityEvent event) { 17754 return host.onRequestSendAccessibilityEventInternal(child, event); 17755 } 17756 17757 /** 17758 * Gets the provider for managing a virtual view hierarchy rooted at this View 17759 * and reported to {@link android.accessibilityservice.AccessibilityService}s 17760 * that explore the window content. 17761 * <p> 17762 * The default implementation behaves as 17763 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 17764 * the case of no accessibility delegate been set. 17765 * </p> 17766 * 17767 * @return The provider. 17768 * 17769 * @see AccessibilityNodeProvider 17770 */ 17771 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 17772 return null; 17773 } 17774 } 17775} 17776