View.java revision 678e0adbdbac5fa3f25ca8371fdff1b3182f67e9
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 com.android.internal.R; 20import com.android.internal.util.Predicate; 21import com.android.internal.view.menu.MenuBuilder; 22 23import android.content.ClipData; 24import android.content.Context; 25import android.content.res.Configuration; 26import android.content.res.Resources; 27import android.content.res.TypedArray; 28import android.graphics.Bitmap; 29import android.graphics.Camera; 30import android.graphics.Canvas; 31import android.graphics.Interpolator; 32import android.graphics.LinearGradient; 33import android.graphics.Matrix; 34import android.graphics.Paint; 35import android.graphics.PixelFormat; 36import android.graphics.Point; 37import android.graphics.PorterDuff; 38import android.graphics.PorterDuffXfermode; 39import android.graphics.Rect; 40import android.graphics.RectF; 41import android.graphics.Region; 42import android.graphics.Shader; 43import android.graphics.drawable.ColorDrawable; 44import android.graphics.drawable.Drawable; 45import android.os.Handler; 46import android.os.IBinder; 47import android.os.Message; 48import android.os.Parcel; 49import android.os.Parcelable; 50import android.os.RemoteException; 51import android.os.SystemClock; 52import android.os.SystemProperties; 53import android.util.AttributeSet; 54import android.util.Log; 55import android.util.Pool; 56import android.util.Poolable; 57import android.util.PoolableManager; 58import android.util.Pools; 59import android.util.SparseArray; 60import android.view.ContextMenu.ContextMenuInfo; 61import android.view.accessibility.AccessibilityEvent; 62import android.view.accessibility.AccessibilityEventSource; 63import android.view.accessibility.AccessibilityManager; 64import android.view.animation.Animation; 65import android.view.animation.AnimationUtils; 66import android.view.inputmethod.EditorInfo; 67import android.view.inputmethod.InputConnection; 68import android.view.inputmethod.InputMethodManager; 69import android.widget.ScrollBarDrawable; 70 71import java.lang.ref.WeakReference; 72import java.lang.reflect.InvocationTargetException; 73import java.lang.reflect.Method; 74import java.util.ArrayList; 75import java.util.Arrays; 76import java.util.List; 77import java.util.WeakHashMap; 78 79/** 80 * <p> 81 * This class represents the basic building block for user interface components. A View 82 * occupies a rectangular area on the screen and is responsible for drawing and 83 * event handling. View is the base class for <em>widgets</em>, which are 84 * used to create interactive UI components (buttons, text fields, etc.). The 85 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 86 * are invisible containers that hold other Views (or other ViewGroups) and define 87 * their layout properties. 88 * </p> 89 * 90 * <div class="special"> 91 * <p>For an introduction to using this class to develop your 92 * application's user interface, read the Developer Guide documentation on 93 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics 94 * include: 95 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a> 96 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a> 97 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a> 98 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a> 99 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a> 100 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a> 101 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a> 102 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>. 103 * </p> 104 * </div> 105 * 106 * <a name="Using"></a> 107 * <h3>Using Views</h3> 108 * <p> 109 * All of the views in a window are arranged in a single tree. You can add views 110 * either from code or by specifying a tree of views in one or more XML layout 111 * files. There are many specialized subclasses of views that act as controls or 112 * are capable of displaying text, images, or other content. 113 * </p> 114 * <p> 115 * Once you have created a tree of views, there are typically a few types of 116 * common operations you may wish to perform: 117 * <ul> 118 * <li><strong>Set properties:</strong> for example setting the text of a 119 * {@link android.widget.TextView}. The available properties and the methods 120 * that set them will vary among the different subclasses of views. Note that 121 * properties that are known at build time can be set in the XML layout 122 * files.</li> 123 * <li><strong>Set focus:</strong> The framework will handled moving focus in 124 * response to user input. To force focus to a specific view, call 125 * {@link #requestFocus}.</li> 126 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 127 * that will be notified when something interesting happens to the view. For 128 * example, all views will let you set a listener to be notified when the view 129 * gains or loses focus. You can register such a listener using 130 * {@link #setOnFocusChangeListener}. Other view subclasses offer more 131 * specialized listeners. For example, a Button exposes a listener to notify 132 * clients when the button is clicked.</li> 133 * <li><strong>Set visibility:</strong> You can hide or show views using 134 * {@link #setVisibility}.</li> 135 * </ul> 136 * </p> 137 * <p><em> 138 * Note: The Android framework is responsible for measuring, laying out and 139 * drawing views. You should not call methods that perform these actions on 140 * views yourself unless you are actually implementing a 141 * {@link android.view.ViewGroup}. 142 * </em></p> 143 * 144 * <a name="Lifecycle"></a> 145 * <h3>Implementing a Custom View</h3> 146 * 147 * <p> 148 * To implement a custom view, you will usually begin by providing overrides for 149 * some of the standard methods that the framework calls on all views. You do 150 * not need to override all of these methods. In fact, you can start by just 151 * overriding {@link #onDraw(android.graphics.Canvas)}. 152 * <table border="2" width="85%" align="center" cellpadding="5"> 153 * <thead> 154 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 155 * </thead> 156 * 157 * <tbody> 158 * <tr> 159 * <td rowspan="2">Creation</td> 160 * <td>Constructors</td> 161 * <td>There is a form of the constructor that are called when the view 162 * is created from code and a form that is called when the view is 163 * inflated from a layout file. The second form should parse and apply 164 * any attributes defined in the layout file. 165 * </td> 166 * </tr> 167 * <tr> 168 * <td><code>{@link #onFinishInflate()}</code></td> 169 * <td>Called after a view and all of its children has been inflated 170 * from XML.</td> 171 * </tr> 172 * 173 * <tr> 174 * <td rowspan="3">Layout</td> 175 * <td><code>{@link #onMeasure}</code></td> 176 * <td>Called to determine the size requirements for this view and all 177 * of its children. 178 * </td> 179 * </tr> 180 * <tr> 181 * <td><code>{@link #onLayout}</code></td> 182 * <td>Called when this view should assign a size and position to all 183 * of its children. 184 * </td> 185 * </tr> 186 * <tr> 187 * <td><code>{@link #onSizeChanged}</code></td> 188 * <td>Called when the size of this view has changed. 189 * </td> 190 * </tr> 191 * 192 * <tr> 193 * <td>Drawing</td> 194 * <td><code>{@link #onDraw}</code></td> 195 * <td>Called when the view should render its content. 196 * </td> 197 * </tr> 198 * 199 * <tr> 200 * <td rowspan="4">Event processing</td> 201 * <td><code>{@link #onKeyDown}</code></td> 202 * <td>Called when a new key event occurs. 203 * </td> 204 * </tr> 205 * <tr> 206 * <td><code>{@link #onKeyUp}</code></td> 207 * <td>Called when a key up event occurs. 208 * </td> 209 * </tr> 210 * <tr> 211 * <td><code>{@link #onTrackballEvent}</code></td> 212 * <td>Called when a trackball motion event occurs. 213 * </td> 214 * </tr> 215 * <tr> 216 * <td><code>{@link #onTouchEvent}</code></td> 217 * <td>Called when a touch screen motion event occurs. 218 * </td> 219 * </tr> 220 * 221 * <tr> 222 * <td rowspan="2">Focus</td> 223 * <td><code>{@link #onFocusChanged}</code></td> 224 * <td>Called when the view gains or loses focus. 225 * </td> 226 * </tr> 227 * 228 * <tr> 229 * <td><code>{@link #onWindowFocusChanged}</code></td> 230 * <td>Called when the window containing the view gains or loses focus. 231 * </td> 232 * </tr> 233 * 234 * <tr> 235 * <td rowspan="3">Attaching</td> 236 * <td><code>{@link #onAttachedToWindow()}</code></td> 237 * <td>Called when the view is attached to a window. 238 * </td> 239 * </tr> 240 * 241 * <tr> 242 * <td><code>{@link #onDetachedFromWindow}</code></td> 243 * <td>Called when the view is detached from its window. 244 * </td> 245 * </tr> 246 * 247 * <tr> 248 * <td><code>{@link #onWindowVisibilityChanged}</code></td> 249 * <td>Called when the visibility of the window containing the view 250 * has changed. 251 * </td> 252 * </tr> 253 * </tbody> 254 * 255 * </table> 256 * </p> 257 * 258 * <a name="IDs"></a> 259 * <h3>IDs</h3> 260 * Views may have an integer id associated with them. These ids are typically 261 * assigned in the layout XML files, and are used to find specific views within 262 * the view tree. A common pattern is to: 263 * <ul> 264 * <li>Define a Button in the layout file and assign it a unique ID. 265 * <pre> 266 * <Button 267 * android:id="@+id/my_button" 268 * android:layout_width="wrap_content" 269 * android:layout_height="wrap_content" 270 * android:text="@string/my_button_text"/> 271 * </pre></li> 272 * <li>From the onCreate method of an Activity, find the Button 273 * <pre class="prettyprint"> 274 * Button myButton = (Button) findViewById(R.id.my_button); 275 * </pre></li> 276 * </ul> 277 * <p> 278 * View IDs need not be unique throughout the tree, but it is good practice to 279 * ensure that they are at least unique within the part of the tree you are 280 * searching. 281 * </p> 282 * 283 * <a name="Position"></a> 284 * <h3>Position</h3> 285 * <p> 286 * The geometry of a view is that of a rectangle. A view has a location, 287 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 288 * two dimensions, expressed as a width and a height. The unit for location 289 * and dimensions is the pixel. 290 * </p> 291 * 292 * <p> 293 * It is possible to retrieve the location of a view by invoking the methods 294 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 295 * coordinate of the rectangle representing the view. The latter returns the 296 * top, or Y, coordinate of the rectangle representing the view. These methods 297 * both return the location of the view relative to its parent. For instance, 298 * when getLeft() returns 20, that means the view is located 20 pixels to the 299 * right of the left edge of its direct parent. 300 * </p> 301 * 302 * <p> 303 * In addition, several convenience methods are offered to avoid unnecessary 304 * computations, namely {@link #getRight()} and {@link #getBottom()}. 305 * These methods return the coordinates of the right and bottom edges of the 306 * rectangle representing the view. For instance, calling {@link #getRight()} 307 * is similar to the following computation: <code>getLeft() + getWidth()</code> 308 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 309 * </p> 310 * 311 * <a name="SizePaddingMargins"></a> 312 * <h3>Size, padding and margins</h3> 313 * <p> 314 * The size of a view is expressed with a width and a height. A view actually 315 * possess two pairs of width and height values. 316 * </p> 317 * 318 * <p> 319 * The first pair is known as <em>measured width</em> and 320 * <em>measured height</em>. These dimensions define how big a view wants to be 321 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 322 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 323 * and {@link #getMeasuredHeight()}. 324 * </p> 325 * 326 * <p> 327 * The second pair is simply known as <em>width</em> and <em>height</em>, or 328 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 329 * dimensions define the actual size of the view on screen, at drawing time and 330 * after layout. These values may, but do not have to, be different from the 331 * measured width and height. The width and height can be obtained by calling 332 * {@link #getWidth()} and {@link #getHeight()}. 333 * </p> 334 * 335 * <p> 336 * To measure its dimensions, a view takes into account its padding. The padding 337 * is expressed in pixels for the left, top, right and bottom parts of the view. 338 * Padding can be used to offset the content of the view by a specific amount of 339 * pixels. For instance, a left padding of 2 will push the view's content by 340 * 2 pixels to the right of the left edge. Padding can be set using the 341 * {@link #setPadding(int, int, int, int)} method and queried by calling 342 * {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 343 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}. 344 * </p> 345 * 346 * <p> 347 * Even though a view can define a padding, it does not provide any support for 348 * margins. However, view groups provide such a support. Refer to 349 * {@link android.view.ViewGroup} and 350 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 351 * </p> 352 * 353 * <a name="Layout"></a> 354 * <h3>Layout</h3> 355 * <p> 356 * Layout is a two pass process: a measure pass and a layout pass. The measuring 357 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 358 * of the view tree. Each view pushes dimension specifications down the tree 359 * during the recursion. At the end of the measure pass, every view has stored 360 * its measurements. The second pass happens in 361 * {@link #layout(int,int,int,int)} and is also top-down. During 362 * this pass each parent is responsible for positioning all of its children 363 * using the sizes computed in the measure pass. 364 * </p> 365 * 366 * <p> 367 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 368 * {@link #getMeasuredHeight()} values must be set, along with those for all of 369 * that view's descendants. A view's measured width and measured height values 370 * must respect the constraints imposed by the view's parents. This guarantees 371 * that at the end of the measure pass, all parents accept all of their 372 * children's measurements. A parent view may call measure() more than once on 373 * its children. For example, the parent may measure each child once with 374 * unspecified dimensions to find out how big they want to be, then call 375 * measure() on them again with actual numbers if the sum of all the children's 376 * unconstrained sizes is too big or too small. 377 * </p> 378 * 379 * <p> 380 * The measure pass uses two classes to communicate dimensions. The 381 * {@link MeasureSpec} class is used by views to tell their parents how they 382 * want to be measured and positioned. The base LayoutParams class just 383 * describes how big the view wants to be for both width and height. For each 384 * dimension, it can specify one of: 385 * <ul> 386 * <li> an exact number 387 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 388 * (minus padding) 389 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 390 * enclose its content (plus padding). 391 * </ul> 392 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 393 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 394 * an X and Y value. 395 * </p> 396 * 397 * <p> 398 * MeasureSpecs are used to push requirements down the tree from parent to 399 * child. A MeasureSpec can be in one of three modes: 400 * <ul> 401 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 402 * of a child view. For example, a LinearLayout may call measure() on its child 403 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 404 * tall the child view wants to be given a width of 240 pixels. 405 * <li>EXACTLY: This is used by the parent to impose an exact size on the 406 * child. The child must use this size, and guarantee that all of its 407 * descendants will fit within this size. 408 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 409 * child. The child must gurantee that it and all of its descendants will fit 410 * within this size. 411 * </ul> 412 * </p> 413 * 414 * <p> 415 * To intiate a layout, call {@link #requestLayout}. This method is typically 416 * called by a view on itself when it believes that is can no longer fit within 417 * its current bounds. 418 * </p> 419 * 420 * <a name="Drawing"></a> 421 * <h3>Drawing</h3> 422 * <p> 423 * Drawing is handled by walking the tree and rendering each view that 424 * intersects the the invalid region. Because the tree is traversed in-order, 425 * this means that parents will draw before (i.e., behind) their children, with 426 * siblings drawn in the order they appear in the tree. 427 * If you set a background drawable for a View, then the View will draw it for you 428 * before calling back to its <code>onDraw()</code> method. 429 * </p> 430 * 431 * <p> 432 * Note that the framework will not draw views that are not in the invalid region. 433 * </p> 434 * 435 * <p> 436 * To force a view to draw, call {@link #invalidate()}. 437 * </p> 438 * 439 * <a name="EventHandlingThreading"></a> 440 * <h3>Event Handling and Threading</h3> 441 * <p> 442 * The basic cycle of a view is as follows: 443 * <ol> 444 * <li>An event comes in and is dispatched to the appropriate view. The view 445 * handles the event and notifies any listeners.</li> 446 * <li>If in the course of processing the event, the view's bounds may need 447 * to be changed, the view will call {@link #requestLayout()}.</li> 448 * <li>Similarly, if in the course of processing the event the view's appearance 449 * may need to be changed, the view will call {@link #invalidate()}.</li> 450 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 451 * the framework will take care of measuring, laying out, and drawing the tree 452 * as appropriate.</li> 453 * </ol> 454 * </p> 455 * 456 * <p><em>Note: The entire view tree is single threaded. You must always be on 457 * the UI thread when calling any method on any view.</em> 458 * If you are doing work on other threads and want to update the state of a view 459 * from that thread, you should use a {@link Handler}. 460 * </p> 461 * 462 * <a name="FocusHandling"></a> 463 * <h3>Focus Handling</h3> 464 * <p> 465 * The framework will handle routine focus movement in response to user input. 466 * This includes changing the focus as views are removed or hidden, or as new 467 * views become available. Views indicate their willingness to take focus 468 * through the {@link #isFocusable} method. To change whether a view can take 469 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 470 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 471 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 472 * </p> 473 * <p> 474 * Focus movement is based on an algorithm which finds the nearest neighbor in a 475 * given direction. In rare cases, the default algorithm may not match the 476 * intended behavior of the developer. In these situations, you can provide 477 * explicit overrides by using these XML attributes in the layout file: 478 * <pre> 479 * nextFocusDown 480 * nextFocusLeft 481 * nextFocusRight 482 * nextFocusUp 483 * </pre> 484 * </p> 485 * 486 * 487 * <p> 488 * To get a particular view to take focus, call {@link #requestFocus()}. 489 * </p> 490 * 491 * <a name="TouchMode"></a> 492 * <h3>Touch Mode</h3> 493 * <p> 494 * When a user is navigating a user interface via directional keys such as a D-pad, it is 495 * necessary to give focus to actionable items such as buttons so the user can see 496 * what will take input. If the device has touch capabilities, however, and the user 497 * begins interacting with the interface by touching it, it is no longer necessary to 498 * always highlight, or give focus to, a particular view. This motivates a mode 499 * for interaction named 'touch mode'. 500 * </p> 501 * <p> 502 * For a touch capable device, once the user touches the screen, the device 503 * will enter touch mode. From this point onward, only views for which 504 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 505 * Other views that are touchable, like buttons, will not take focus when touched; they will 506 * only fire the on click listeners. 507 * </p> 508 * <p> 509 * Any time a user hits a directional key, such as a D-pad direction, the view device will 510 * exit touch mode, and find a view to take focus, so that the user may resume interacting 511 * with the user interface without touching the screen again. 512 * </p> 513 * <p> 514 * The touch mode state is maintained across {@link android.app.Activity}s. Call 515 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 516 * </p> 517 * 518 * <a name="Scrolling"></a> 519 * <h3>Scrolling</h3> 520 * <p> 521 * The framework provides basic support for views that wish to internally 522 * scroll their content. This includes keeping track of the X and Y scroll 523 * offset as well as mechanisms for drawing scrollbars. See 524 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 525 * {@link #awakenScrollBars()} for more details. 526 * </p> 527 * 528 * <a name="Tags"></a> 529 * <h3>Tags</h3> 530 * <p> 531 * Unlike IDs, tags are not used to identify views. Tags are essentially an 532 * extra piece of information that can be associated with a view. They are most 533 * often used as a convenience to store data related to views in the views 534 * themselves rather than by putting them in a separate structure. 535 * </p> 536 * 537 * <a name="Animation"></a> 538 * <h3>Animation</h3> 539 * <p> 540 * You can attach an {@link Animation} object to a view using 541 * {@link #setAnimation(Animation)} or 542 * {@link #startAnimation(Animation)}. The animation can alter the scale, 543 * rotation, translation and alpha of a view over time. If the animation is 544 * attached to a view that has children, the animation will affect the entire 545 * subtree rooted by that node. When an animation is started, the framework will 546 * take care of redrawing the appropriate views until the animation completes. 547 * </p> 548 * <p> 549 * Starting with Android 3.0, the preferred way of animating views is to use the 550 * {@link android.animation} package APIs. 551 * </p> 552 * 553 * <a name="Security"></a> 554 * <h3>Security</h3> 555 * <p> 556 * Sometimes it is essential that an application be able to verify that an action 557 * is being performed with the full knowledge and consent of the user, such as 558 * granting a permission request, making a purchase or clicking on an advertisement. 559 * Unfortunately, a malicious application could try to spoof the user into 560 * performing these actions, unaware, by concealing the intended purpose of the view. 561 * As a remedy, the framework offers a touch filtering mechanism that can be used to 562 * improve the security of views that provide access to sensitive functionality. 563 * </p><p> 564 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the 565 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 566 * will discard touches that are received whenever the view's window is obscured by 567 * another visible window. As a result, the view will not receive touches whenever a 568 * toast, dialog or other window appears above the view's window. 569 * </p><p> 570 * For more fine-grained control over security, consider overriding the 571 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy. 572 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 573 * </p> 574 * 575 * @attr ref android.R.styleable#View_alpha 576 * @attr ref android.R.styleable#View_background 577 * @attr ref android.R.styleable#View_clickable 578 * @attr ref android.R.styleable#View_contentDescription 579 * @attr ref android.R.styleable#View_drawingCacheQuality 580 * @attr ref android.R.styleable#View_duplicateParentState 581 * @attr ref android.R.styleable#View_id 582 * @attr ref android.R.styleable#View_fadingEdge 583 * @attr ref android.R.styleable#View_fadingEdgeLength 584 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 585 * @attr ref android.R.styleable#View_fitsSystemWindows 586 * @attr ref android.R.styleable#View_isScrollContainer 587 * @attr ref android.R.styleable#View_focusable 588 * @attr ref android.R.styleable#View_focusableInTouchMode 589 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 590 * @attr ref android.R.styleable#View_keepScreenOn 591 * @attr ref android.R.styleable#View_layerType 592 * @attr ref android.R.styleable#View_longClickable 593 * @attr ref android.R.styleable#View_minHeight 594 * @attr ref android.R.styleable#View_minWidth 595 * @attr ref android.R.styleable#View_nextFocusDown 596 * @attr ref android.R.styleable#View_nextFocusLeft 597 * @attr ref android.R.styleable#View_nextFocusRight 598 * @attr ref android.R.styleable#View_nextFocusUp 599 * @attr ref android.R.styleable#View_onClick 600 * @attr ref android.R.styleable#View_padding 601 * @attr ref android.R.styleable#View_paddingBottom 602 * @attr ref android.R.styleable#View_paddingLeft 603 * @attr ref android.R.styleable#View_paddingRight 604 * @attr ref android.R.styleable#View_paddingTop 605 * @attr ref android.R.styleable#View_saveEnabled 606 * @attr ref android.R.styleable#View_rotation 607 * @attr ref android.R.styleable#View_rotationX 608 * @attr ref android.R.styleable#View_rotationY 609 * @attr ref android.R.styleable#View_scaleX 610 * @attr ref android.R.styleable#View_scaleY 611 * @attr ref android.R.styleable#View_scrollX 612 * @attr ref android.R.styleable#View_scrollY 613 * @attr ref android.R.styleable#View_scrollbarSize 614 * @attr ref android.R.styleable#View_scrollbarStyle 615 * @attr ref android.R.styleable#View_scrollbars 616 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 617 * @attr ref android.R.styleable#View_scrollbarFadeDuration 618 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 619 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 620 * @attr ref android.R.styleable#View_scrollbarThumbVertical 621 * @attr ref android.R.styleable#View_scrollbarTrackVertical 622 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 623 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 624 * @attr ref android.R.styleable#View_soundEffectsEnabled 625 * @attr ref android.R.styleable#View_tag 626 * @attr ref android.R.styleable#View_transformPivotX 627 * @attr ref android.R.styleable#View_transformPivotY 628 * @attr ref android.R.styleable#View_translationX 629 * @attr ref android.R.styleable#View_translationY 630 * @attr ref android.R.styleable#View_visibility 631 * 632 * @see android.view.ViewGroup 633 */ 634public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource { 635 private static final boolean DBG = false; 636 637 /** 638 * The logging tag used by this class with android.util.Log. 639 */ 640 protected static final String VIEW_LOG_TAG = "View"; 641 642 /** 643 * Used to mark a View that has no ID. 644 */ 645 public static final int NO_ID = -1; 646 647 /** 648 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 649 * calling setFlags. 650 */ 651 private static final int NOT_FOCUSABLE = 0x00000000; 652 653 /** 654 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 655 * setFlags. 656 */ 657 private static final int FOCUSABLE = 0x00000001; 658 659 /** 660 * Mask for use with setFlags indicating bits used for focus. 661 */ 662 private static final int FOCUSABLE_MASK = 0x00000001; 663 664 /** 665 * This view will adjust its padding to fit sytem windows (e.g. status bar) 666 */ 667 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 668 669 /** 670 * This view is visible. Use with {@link #setVisibility}. 671 */ 672 public static final int VISIBLE = 0x00000000; 673 674 /** 675 * This view is invisible, but it still takes up space for layout purposes. 676 * Use with {@link #setVisibility}. 677 */ 678 public static final int INVISIBLE = 0x00000004; 679 680 /** 681 * This view is invisible, and it doesn't take any space for layout 682 * purposes. Use with {@link #setVisibility}. 683 */ 684 public static final int GONE = 0x00000008; 685 686 /** 687 * Mask for use with setFlags indicating bits used for visibility. 688 * {@hide} 689 */ 690 static final int VISIBILITY_MASK = 0x0000000C; 691 692 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 693 694 /** 695 * This view is enabled. Intrepretation varies by subclass. 696 * Use with ENABLED_MASK when calling setFlags. 697 * {@hide} 698 */ 699 static final int ENABLED = 0x00000000; 700 701 /** 702 * This view is disabled. Intrepretation varies by subclass. 703 * Use with ENABLED_MASK when calling setFlags. 704 * {@hide} 705 */ 706 static final int DISABLED = 0x00000020; 707 708 /** 709 * Mask for use with setFlags indicating bits used for indicating whether 710 * this view is enabled 711 * {@hide} 712 */ 713 static final int ENABLED_MASK = 0x00000020; 714 715 /** 716 * This view won't draw. {@link #onDraw} won't be called and further 717 * optimizations 718 * will be performed. It is okay to have this flag set and a background. 719 * Use with DRAW_MASK when calling setFlags. 720 * {@hide} 721 */ 722 static final int WILL_NOT_DRAW = 0x00000080; 723 724 /** 725 * Mask for use with setFlags indicating bits used for indicating whether 726 * this view is will draw 727 * {@hide} 728 */ 729 static final int DRAW_MASK = 0x00000080; 730 731 /** 732 * <p>This view doesn't show scrollbars.</p> 733 * {@hide} 734 */ 735 static final int SCROLLBARS_NONE = 0x00000000; 736 737 /** 738 * <p>This view shows horizontal scrollbars.</p> 739 * {@hide} 740 */ 741 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 742 743 /** 744 * <p>This view shows vertical scrollbars.</p> 745 * {@hide} 746 */ 747 static final int SCROLLBARS_VERTICAL = 0x00000200; 748 749 /** 750 * <p>Mask for use with setFlags indicating bits used for indicating which 751 * scrollbars are enabled.</p> 752 * {@hide} 753 */ 754 static final int SCROLLBARS_MASK = 0x00000300; 755 756 /** 757 * Indicates that the view should filter touches when its window is obscured. 758 * Refer to the class comments for more information about this security feature. 759 * {@hide} 760 */ 761 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 762 763 // note flag value 0x00000800 is now available for next flags... 764 765 /** 766 * <p>This view doesn't show fading edges.</p> 767 * {@hide} 768 */ 769 static final int FADING_EDGE_NONE = 0x00000000; 770 771 /** 772 * <p>This view shows horizontal fading edges.</p> 773 * {@hide} 774 */ 775 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 776 777 /** 778 * <p>This view shows vertical fading edges.</p> 779 * {@hide} 780 */ 781 static final int FADING_EDGE_VERTICAL = 0x00002000; 782 783 /** 784 * <p>Mask for use with setFlags indicating bits used for indicating which 785 * fading edges are enabled.</p> 786 * {@hide} 787 */ 788 static final int FADING_EDGE_MASK = 0x00003000; 789 790 /** 791 * <p>Indicates this view can be clicked. When clickable, a View reacts 792 * to clicks by notifying the OnClickListener.<p> 793 * {@hide} 794 */ 795 static final int CLICKABLE = 0x00004000; 796 797 /** 798 * <p>Indicates this view is caching its drawing into a bitmap.</p> 799 * {@hide} 800 */ 801 static final int DRAWING_CACHE_ENABLED = 0x00008000; 802 803 /** 804 * <p>Indicates that no icicle should be saved for this view.<p> 805 * {@hide} 806 */ 807 static final int SAVE_DISABLED = 0x000010000; 808 809 /** 810 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 811 * property.</p> 812 * {@hide} 813 */ 814 static final int SAVE_DISABLED_MASK = 0x000010000; 815 816 /** 817 * <p>Indicates that no drawing cache should ever be created for this view.<p> 818 * {@hide} 819 */ 820 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 821 822 /** 823 * <p>Indicates this view can take / keep focus when int touch mode.</p> 824 * {@hide} 825 */ 826 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 827 828 /** 829 * <p>Enables low quality mode for the drawing cache.</p> 830 */ 831 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 832 833 /** 834 * <p>Enables high quality mode for the drawing cache.</p> 835 */ 836 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 837 838 /** 839 * <p>Enables automatic quality mode for the drawing cache.</p> 840 */ 841 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 842 843 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 844 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 845 }; 846 847 /** 848 * <p>Mask for use with setFlags indicating bits used for the cache 849 * quality property.</p> 850 * {@hide} 851 */ 852 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 853 854 /** 855 * <p> 856 * Indicates this view can be long clicked. When long clickable, a View 857 * reacts to long clicks by notifying the OnLongClickListener or showing a 858 * context menu. 859 * </p> 860 * {@hide} 861 */ 862 static final int LONG_CLICKABLE = 0x00200000; 863 864 /** 865 * <p>Indicates that this view gets its drawable states from its direct parent 866 * and ignores its original internal states.</p> 867 * 868 * @hide 869 */ 870 static final int DUPLICATE_PARENT_STATE = 0x00400000; 871 872 /** 873 * The scrollbar style to display the scrollbars inside the content area, 874 * without increasing the padding. The scrollbars will be overlaid with 875 * translucency on the view's content. 876 */ 877 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 878 879 /** 880 * The scrollbar style to display the scrollbars inside the padded area, 881 * increasing the padding of the view. The scrollbars will not overlap the 882 * content area of the view. 883 */ 884 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 885 886 /** 887 * The scrollbar style to display the scrollbars at the edge of the view, 888 * without increasing the padding. The scrollbars will be overlaid with 889 * translucency. 890 */ 891 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 892 893 /** 894 * The scrollbar style to display the scrollbars at the edge of the view, 895 * increasing the padding of the view. The scrollbars will only overlap the 896 * background, if any. 897 */ 898 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 899 900 /** 901 * Mask to check if the scrollbar style is overlay or inset. 902 * {@hide} 903 */ 904 static final int SCROLLBARS_INSET_MASK = 0x01000000; 905 906 /** 907 * Mask to check if the scrollbar style is inside or outside. 908 * {@hide} 909 */ 910 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 911 912 /** 913 * Mask for scrollbar style. 914 * {@hide} 915 */ 916 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 917 918 /** 919 * View flag indicating that the screen should remain on while the 920 * window containing this view is visible to the user. This effectively 921 * takes care of automatically setting the WindowManager's 922 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 923 */ 924 public static final int KEEP_SCREEN_ON = 0x04000000; 925 926 /** 927 * View flag indicating whether this view should have sound effects enabled 928 * for events such as clicking and touching. 929 */ 930 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 931 932 /** 933 * View flag indicating whether this view should have haptic feedback 934 * enabled for events such as long presses. 935 */ 936 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 937 938 /** 939 * <p>Indicates that the view hierarchy should stop saving state when 940 * it reaches this view. If state saving is initiated immediately at 941 * the view, it will be allowed. 942 * {@hide} 943 */ 944 static final int PARENT_SAVE_DISABLED = 0x20000000; 945 946 /** 947 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 948 * {@hide} 949 */ 950 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 951 952 /** 953 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 954 * should add all focusable Views regardless if they are focusable in touch mode. 955 */ 956 public static final int FOCUSABLES_ALL = 0x00000000; 957 958 /** 959 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 960 * should add only Views focusable in touch mode. 961 */ 962 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 963 964 /** 965 * Use with {@link #focusSearch}. Move focus to the previous selectable 966 * item. 967 */ 968 public static final int FOCUS_BACKWARD = 0x00000001; 969 970 /** 971 * Use with {@link #focusSearch}. Move focus to the next selectable 972 * item. 973 */ 974 public static final int FOCUS_FORWARD = 0x00000002; 975 976 /** 977 * Use with {@link #focusSearch}. Move focus to the left. 978 */ 979 public static final int FOCUS_LEFT = 0x00000011; 980 981 /** 982 * Use with {@link #focusSearch}. Move focus up. 983 */ 984 public static final int FOCUS_UP = 0x00000021; 985 986 /** 987 * Use with {@link #focusSearch}. Move focus to the right. 988 */ 989 public static final int FOCUS_RIGHT = 0x00000042; 990 991 /** 992 * Use with {@link #focusSearch}. Move focus down. 993 */ 994 public static final int FOCUS_DOWN = 0x00000082; 995 996 /** 997 * Bits of {@link #getMeasuredWidthAndState()} and 998 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 999 */ 1000 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1001 1002 /** 1003 * Bits of {@link #getMeasuredWidthAndState()} and 1004 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1005 */ 1006 public static final int MEASURED_STATE_MASK = 0xff000000; 1007 1008 /** 1009 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1010 * for functions that combine both width and height into a single int, 1011 * such as {@link #getMeasuredState()} and the childState argument of 1012 * {@link #resolveSizeAndState(int, int, int)}. 1013 */ 1014 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1015 1016 /** 1017 * Bit of {@link #getMeasuredWidthAndState()} and 1018 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1019 * is smaller that the space the view would like to have. 1020 */ 1021 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1022 1023 /** 1024 * Base View state sets 1025 */ 1026 // Singles 1027 /** 1028 * Indicates the view has no states set. States are used with 1029 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1030 * view depending on its state. 1031 * 1032 * @see android.graphics.drawable.Drawable 1033 * @see #getDrawableState() 1034 */ 1035 protected static final int[] EMPTY_STATE_SET; 1036 /** 1037 * Indicates the view is enabled. States are used with 1038 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1039 * view depending on its state. 1040 * 1041 * @see android.graphics.drawable.Drawable 1042 * @see #getDrawableState() 1043 */ 1044 protected static final int[] ENABLED_STATE_SET; 1045 /** 1046 * Indicates the view is focused. States are used with 1047 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1048 * view depending on its state. 1049 * 1050 * @see android.graphics.drawable.Drawable 1051 * @see #getDrawableState() 1052 */ 1053 protected static final int[] FOCUSED_STATE_SET; 1054 /** 1055 * Indicates the view is selected. States are used with 1056 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1057 * view depending on its state. 1058 * 1059 * @see android.graphics.drawable.Drawable 1060 * @see #getDrawableState() 1061 */ 1062 protected static final int[] SELECTED_STATE_SET; 1063 /** 1064 * Indicates the view is pressed. States are used with 1065 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1066 * view depending on its state. 1067 * 1068 * @see android.graphics.drawable.Drawable 1069 * @see #getDrawableState() 1070 * @hide 1071 */ 1072 protected static final int[] PRESSED_STATE_SET; 1073 /** 1074 * Indicates the view's window has focus. States are used with 1075 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1076 * view depending on its state. 1077 * 1078 * @see android.graphics.drawable.Drawable 1079 * @see #getDrawableState() 1080 */ 1081 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1082 // Doubles 1083 /** 1084 * Indicates the view is enabled and has the focus. 1085 * 1086 * @see #ENABLED_STATE_SET 1087 * @see #FOCUSED_STATE_SET 1088 */ 1089 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1090 /** 1091 * Indicates the view is enabled and selected. 1092 * 1093 * @see #ENABLED_STATE_SET 1094 * @see #SELECTED_STATE_SET 1095 */ 1096 protected static final int[] ENABLED_SELECTED_STATE_SET; 1097 /** 1098 * Indicates the view is enabled and that its window has focus. 1099 * 1100 * @see #ENABLED_STATE_SET 1101 * @see #WINDOW_FOCUSED_STATE_SET 1102 */ 1103 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1104 /** 1105 * Indicates the view is focused and selected. 1106 * 1107 * @see #FOCUSED_STATE_SET 1108 * @see #SELECTED_STATE_SET 1109 */ 1110 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1111 /** 1112 * Indicates the view has the focus and that its window has the focus. 1113 * 1114 * @see #FOCUSED_STATE_SET 1115 * @see #WINDOW_FOCUSED_STATE_SET 1116 */ 1117 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1118 /** 1119 * Indicates the view is selected and that its window has the focus. 1120 * 1121 * @see #SELECTED_STATE_SET 1122 * @see #WINDOW_FOCUSED_STATE_SET 1123 */ 1124 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1125 // Triples 1126 /** 1127 * Indicates the view is enabled, focused and selected. 1128 * 1129 * @see #ENABLED_STATE_SET 1130 * @see #FOCUSED_STATE_SET 1131 * @see #SELECTED_STATE_SET 1132 */ 1133 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1134 /** 1135 * Indicates the view is enabled, focused and its window has the focus. 1136 * 1137 * @see #ENABLED_STATE_SET 1138 * @see #FOCUSED_STATE_SET 1139 * @see #WINDOW_FOCUSED_STATE_SET 1140 */ 1141 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1142 /** 1143 * Indicates the view is enabled, selected and its window has the focus. 1144 * 1145 * @see #ENABLED_STATE_SET 1146 * @see #SELECTED_STATE_SET 1147 * @see #WINDOW_FOCUSED_STATE_SET 1148 */ 1149 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1150 /** 1151 * Indicates the view is focused, selected and its window has the focus. 1152 * 1153 * @see #FOCUSED_STATE_SET 1154 * @see #SELECTED_STATE_SET 1155 * @see #WINDOW_FOCUSED_STATE_SET 1156 */ 1157 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1158 /** 1159 * Indicates the view is enabled, focused, selected and its window 1160 * has the focus. 1161 * 1162 * @see #ENABLED_STATE_SET 1163 * @see #FOCUSED_STATE_SET 1164 * @see #SELECTED_STATE_SET 1165 * @see #WINDOW_FOCUSED_STATE_SET 1166 */ 1167 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1168 /** 1169 * Indicates the view is pressed and its window has the focus. 1170 * 1171 * @see #PRESSED_STATE_SET 1172 * @see #WINDOW_FOCUSED_STATE_SET 1173 */ 1174 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1175 /** 1176 * Indicates the view is pressed and selected. 1177 * 1178 * @see #PRESSED_STATE_SET 1179 * @see #SELECTED_STATE_SET 1180 */ 1181 protected static final int[] PRESSED_SELECTED_STATE_SET; 1182 /** 1183 * Indicates the view is pressed, selected and its window has the focus. 1184 * 1185 * @see #PRESSED_STATE_SET 1186 * @see #SELECTED_STATE_SET 1187 * @see #WINDOW_FOCUSED_STATE_SET 1188 */ 1189 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1190 /** 1191 * Indicates the view is pressed and focused. 1192 * 1193 * @see #PRESSED_STATE_SET 1194 * @see #FOCUSED_STATE_SET 1195 */ 1196 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1197 /** 1198 * Indicates the view is pressed, focused and its window has the focus. 1199 * 1200 * @see #PRESSED_STATE_SET 1201 * @see #FOCUSED_STATE_SET 1202 * @see #WINDOW_FOCUSED_STATE_SET 1203 */ 1204 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1205 /** 1206 * Indicates the view is pressed, focused and selected. 1207 * 1208 * @see #PRESSED_STATE_SET 1209 * @see #SELECTED_STATE_SET 1210 * @see #FOCUSED_STATE_SET 1211 */ 1212 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1213 /** 1214 * Indicates the view is pressed, focused, selected and its window has the focus. 1215 * 1216 * @see #PRESSED_STATE_SET 1217 * @see #FOCUSED_STATE_SET 1218 * @see #SELECTED_STATE_SET 1219 * @see #WINDOW_FOCUSED_STATE_SET 1220 */ 1221 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1222 /** 1223 * Indicates the view is pressed and enabled. 1224 * 1225 * @see #PRESSED_STATE_SET 1226 * @see #ENABLED_STATE_SET 1227 */ 1228 protected static final int[] PRESSED_ENABLED_STATE_SET; 1229 /** 1230 * Indicates the view is pressed, enabled and its window has the focus. 1231 * 1232 * @see #PRESSED_STATE_SET 1233 * @see #ENABLED_STATE_SET 1234 * @see #WINDOW_FOCUSED_STATE_SET 1235 */ 1236 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1237 /** 1238 * Indicates the view is pressed, enabled and selected. 1239 * 1240 * @see #PRESSED_STATE_SET 1241 * @see #ENABLED_STATE_SET 1242 * @see #SELECTED_STATE_SET 1243 */ 1244 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1245 /** 1246 * Indicates the view is pressed, enabled, selected and its window has the 1247 * focus. 1248 * 1249 * @see #PRESSED_STATE_SET 1250 * @see #ENABLED_STATE_SET 1251 * @see #SELECTED_STATE_SET 1252 * @see #WINDOW_FOCUSED_STATE_SET 1253 */ 1254 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1255 /** 1256 * Indicates the view is pressed, enabled and focused. 1257 * 1258 * @see #PRESSED_STATE_SET 1259 * @see #ENABLED_STATE_SET 1260 * @see #FOCUSED_STATE_SET 1261 */ 1262 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1263 /** 1264 * Indicates the view is pressed, enabled, focused and its window has the 1265 * focus. 1266 * 1267 * @see #PRESSED_STATE_SET 1268 * @see #ENABLED_STATE_SET 1269 * @see #FOCUSED_STATE_SET 1270 * @see #WINDOW_FOCUSED_STATE_SET 1271 */ 1272 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1273 /** 1274 * Indicates the view is pressed, enabled, focused and selected. 1275 * 1276 * @see #PRESSED_STATE_SET 1277 * @see #ENABLED_STATE_SET 1278 * @see #SELECTED_STATE_SET 1279 * @see #FOCUSED_STATE_SET 1280 */ 1281 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1282 /** 1283 * Indicates the view is pressed, enabled, focused, selected and its window 1284 * has the focus. 1285 * 1286 * @see #PRESSED_STATE_SET 1287 * @see #ENABLED_STATE_SET 1288 * @see #SELECTED_STATE_SET 1289 * @see #FOCUSED_STATE_SET 1290 * @see #WINDOW_FOCUSED_STATE_SET 1291 */ 1292 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1293 1294 /** 1295 * The order here is very important to {@link #getDrawableState()} 1296 */ 1297 private static final int[][] VIEW_STATE_SETS; 1298 1299 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1300 static final int VIEW_STATE_SELECTED = 1 << 1; 1301 static final int VIEW_STATE_FOCUSED = 1 << 2; 1302 static final int VIEW_STATE_ENABLED = 1 << 3; 1303 static final int VIEW_STATE_PRESSED = 1 << 4; 1304 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1305 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1306 1307 static final int[] VIEW_STATE_IDS = new int[] { 1308 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1309 R.attr.state_selected, VIEW_STATE_SELECTED, 1310 R.attr.state_focused, VIEW_STATE_FOCUSED, 1311 R.attr.state_enabled, VIEW_STATE_ENABLED, 1312 R.attr.state_pressed, VIEW_STATE_PRESSED, 1313 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1314 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1315 }; 1316 1317 static { 1318 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1319 throw new IllegalStateException( 1320 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1321 } 1322 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1323 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1324 int viewState = R.styleable.ViewDrawableStates[i]; 1325 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1326 if (VIEW_STATE_IDS[j] == viewState) { 1327 orderedIds[i * 2] = viewState; 1328 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1329 } 1330 } 1331 } 1332 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1333 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1334 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1335 int numBits = Integer.bitCount(i); 1336 int[] set = new int[numBits]; 1337 int pos = 0; 1338 for (int j = 0; j < orderedIds.length; j += 2) { 1339 if ((i & orderedIds[j+1]) != 0) { 1340 set[pos++] = orderedIds[j]; 1341 } 1342 } 1343 VIEW_STATE_SETS[i] = set; 1344 } 1345 1346 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1347 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1348 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1349 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1350 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1351 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1352 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1353 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1354 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1355 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1356 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1357 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1358 | VIEW_STATE_FOCUSED]; 1359 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1360 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1361 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1362 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1363 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1364 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1365 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1366 | VIEW_STATE_ENABLED]; 1367 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1368 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1369 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1370 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1371 | VIEW_STATE_ENABLED]; 1372 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1373 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1374 | VIEW_STATE_ENABLED]; 1375 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1376 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1377 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1378 1379 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1380 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1381 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1382 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1383 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1384 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1385 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1386 | VIEW_STATE_PRESSED]; 1387 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1388 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1389 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1390 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1391 | VIEW_STATE_PRESSED]; 1392 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1393 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1394 | VIEW_STATE_PRESSED]; 1395 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1396 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1397 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1398 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1399 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1400 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1401 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1402 | VIEW_STATE_PRESSED]; 1403 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1404 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1405 | VIEW_STATE_PRESSED]; 1406 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1407 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1408 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1409 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1410 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1411 | VIEW_STATE_PRESSED]; 1412 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1413 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1414 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1415 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1416 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1417 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1418 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1419 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1420 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1421 | VIEW_STATE_PRESSED]; 1422 } 1423 1424 /** 1425 * Used by views that contain lists of items. This state indicates that 1426 * the view is showing the last item. 1427 * @hide 1428 */ 1429 protected static final int[] LAST_STATE_SET = {R.attr.state_last}; 1430 /** 1431 * Used by views that contain lists of items. This state indicates that 1432 * the view is showing the first item. 1433 * @hide 1434 */ 1435 protected static final int[] FIRST_STATE_SET = {R.attr.state_first}; 1436 /** 1437 * Used by views that contain lists of items. This state indicates that 1438 * the view is showing the middle item. 1439 * @hide 1440 */ 1441 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle}; 1442 /** 1443 * Used by views that contain lists of items. This state indicates that 1444 * the view is showing only one item. 1445 * @hide 1446 */ 1447 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single}; 1448 /** 1449 * Used by views that contain lists of items. This state indicates that 1450 * the view is pressed and showing the last item. 1451 * @hide 1452 */ 1453 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed}; 1454 /** 1455 * Used by views that contain lists of items. This state indicates that 1456 * the view is pressed and showing the first item. 1457 * @hide 1458 */ 1459 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed}; 1460 /** 1461 * Used by views that contain lists of items. This state indicates that 1462 * the view is pressed and showing the middle item. 1463 * @hide 1464 */ 1465 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed}; 1466 /** 1467 * Used by views that contain lists of items. This state indicates that 1468 * the view is pressed and showing only one item. 1469 * @hide 1470 */ 1471 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed}; 1472 1473 /** 1474 * Temporary Rect currently for use in setBackground(). This will probably 1475 * be extended in the future to hold our own class with more than just 1476 * a Rect. :) 1477 */ 1478 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1479 1480 /** 1481 * Map used to store views' tags. 1482 */ 1483 private static WeakHashMap<View, SparseArray<Object>> sTags; 1484 1485 /** 1486 * Lock used to access sTags. 1487 */ 1488 private static final Object sTagsLock = new Object(); 1489 1490 /** 1491 * The animation currently associated with this view. 1492 * @hide 1493 */ 1494 protected Animation mCurrentAnimation = null; 1495 1496 /** 1497 * Width as measured during measure pass. 1498 * {@hide} 1499 */ 1500 @ViewDebug.ExportedProperty(category = "measurement") 1501 /*package*/ int mMeasuredWidth; 1502 1503 /** 1504 * Height as measured during measure pass. 1505 * {@hide} 1506 */ 1507 @ViewDebug.ExportedProperty(category = "measurement") 1508 /*package*/ int mMeasuredHeight; 1509 1510 /** 1511 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1512 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1513 * its display list. This flag, used only when hw accelerated, allows us to clear the 1514 * flag while retaining this information until it's needed (at getDisplayList() time and 1515 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1516 * 1517 * {@hide} 1518 */ 1519 boolean mRecreateDisplayList = false; 1520 1521 /** 1522 * The view's identifier. 1523 * {@hide} 1524 * 1525 * @see #setId(int) 1526 * @see #getId() 1527 */ 1528 @ViewDebug.ExportedProperty(resolveId = true) 1529 int mID = NO_ID; 1530 1531 /** 1532 * The view's tag. 1533 * {@hide} 1534 * 1535 * @see #setTag(Object) 1536 * @see #getTag() 1537 */ 1538 protected Object mTag; 1539 1540 // for mPrivateFlags: 1541 /** {@hide} */ 1542 static final int WANTS_FOCUS = 0x00000001; 1543 /** {@hide} */ 1544 static final int FOCUSED = 0x00000002; 1545 /** {@hide} */ 1546 static final int SELECTED = 0x00000004; 1547 /** {@hide} */ 1548 static final int IS_ROOT_NAMESPACE = 0x00000008; 1549 /** {@hide} */ 1550 static final int HAS_BOUNDS = 0x00000010; 1551 /** {@hide} */ 1552 static final int DRAWN = 0x00000020; 1553 /** 1554 * When this flag is set, this view is running an animation on behalf of its 1555 * children and should therefore not cancel invalidate requests, even if they 1556 * lie outside of this view's bounds. 1557 * 1558 * {@hide} 1559 */ 1560 static final int DRAW_ANIMATION = 0x00000040; 1561 /** {@hide} */ 1562 static final int SKIP_DRAW = 0x00000080; 1563 /** {@hide} */ 1564 static final int ONLY_DRAWS_BACKGROUND = 0x00000100; 1565 /** {@hide} */ 1566 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1567 /** {@hide} */ 1568 static final int DRAWABLE_STATE_DIRTY = 0x00000400; 1569 /** {@hide} */ 1570 static final int MEASURED_DIMENSION_SET = 0x00000800; 1571 /** {@hide} */ 1572 static final int FORCE_LAYOUT = 0x00001000; 1573 /** {@hide} */ 1574 static final int LAYOUT_REQUIRED = 0x00002000; 1575 1576 private static final int PRESSED = 0x00004000; 1577 1578 /** {@hide} */ 1579 static final int DRAWING_CACHE_VALID = 0x00008000; 1580 /** 1581 * Flag used to indicate that this view should be drawn once more (and only once 1582 * more) after its animation has completed. 1583 * {@hide} 1584 */ 1585 static final int ANIMATION_STARTED = 0x00010000; 1586 1587 private static final int SAVE_STATE_CALLED = 0x00020000; 1588 1589 /** 1590 * Indicates that the View returned true when onSetAlpha() was called and that 1591 * the alpha must be restored. 1592 * {@hide} 1593 */ 1594 static final int ALPHA_SET = 0x00040000; 1595 1596 /** 1597 * Set by {@link #setScrollContainer(boolean)}. 1598 */ 1599 static final int SCROLL_CONTAINER = 0x00080000; 1600 1601 /** 1602 * Set by {@link #setScrollContainer(boolean)}. 1603 */ 1604 static final int SCROLL_CONTAINER_ADDED = 0x00100000; 1605 1606 /** 1607 * View flag indicating whether this view was invalidated (fully or partially.) 1608 * 1609 * @hide 1610 */ 1611 static final int DIRTY = 0x00200000; 1612 1613 /** 1614 * View flag indicating whether this view was invalidated by an opaque 1615 * invalidate request. 1616 * 1617 * @hide 1618 */ 1619 static final int DIRTY_OPAQUE = 0x00400000; 1620 1621 /** 1622 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}. 1623 * 1624 * @hide 1625 */ 1626 static final int DIRTY_MASK = 0x00600000; 1627 1628 /** 1629 * Indicates whether the background is opaque. 1630 * 1631 * @hide 1632 */ 1633 static final int OPAQUE_BACKGROUND = 0x00800000; 1634 1635 /** 1636 * Indicates whether the scrollbars are opaque. 1637 * 1638 * @hide 1639 */ 1640 static final int OPAQUE_SCROLLBARS = 0x01000000; 1641 1642 /** 1643 * Indicates whether the view is opaque. 1644 * 1645 * @hide 1646 */ 1647 static final int OPAQUE_MASK = 0x01800000; 1648 1649 /** 1650 * Indicates a prepressed state; 1651 * the short time between ACTION_DOWN and recognizing 1652 * a 'real' press. Prepressed is used to recognize quick taps 1653 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1654 * 1655 * @hide 1656 */ 1657 private static final int PREPRESSED = 0x02000000; 1658 1659 /** 1660 * Indicates whether the view is temporarily detached. 1661 * 1662 * @hide 1663 */ 1664 static final int CANCEL_NEXT_UP_EVENT = 0x04000000; 1665 1666 /** 1667 * Indicates that we should awaken scroll bars once attached 1668 * 1669 * @hide 1670 */ 1671 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1672 1673 /** 1674 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1675 * for transform operations 1676 * 1677 * @hide 1678 */ 1679 private static final int PIVOT_EXPLICITLY_SET = 0x20000000; 1680 1681 /** {@hide} */ 1682 static final int ACTIVATED = 0x40000000; 1683 1684 /** 1685 * Indicates that this view was specifically invalidated, not just dirtied because some 1686 * child view was invalidated. The flag is used to determine when we need to recreate 1687 * a view's display list (as opposed to just returning a reference to its existing 1688 * display list). 1689 * 1690 * @hide 1691 */ 1692 static final int INVALIDATED = 0x80000000; 1693 1694 /** 1695 * Always allow a user to over-scroll this view, provided it is a 1696 * view that can scroll. 1697 * 1698 * @see #getOverScrollMode() 1699 * @see #setOverScrollMode(int) 1700 */ 1701 public static final int OVER_SCROLL_ALWAYS = 0; 1702 1703 /** 1704 * Allow a user to over-scroll this view only if the content is large 1705 * enough to meaningfully scroll, provided it is a view that can scroll. 1706 * 1707 * @see #getOverScrollMode() 1708 * @see #setOverScrollMode(int) 1709 */ 1710 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 1711 1712 /** 1713 * Never allow a user to over-scroll this view. 1714 * 1715 * @see #getOverScrollMode() 1716 * @see #setOverScrollMode(int) 1717 */ 1718 public static final int OVER_SCROLL_NEVER = 2; 1719 1720 /** 1721 * View has requested the status bar to be visible (the default). 1722 * 1723 * @see #setSystemUiVisibility(int) 1724 */ 1725 public static final int STATUS_BAR_VISIBLE = 0; 1726 1727 /** 1728 * View has requested the status bar to be visible (the default). 1729 * 1730 * @see #setSystemUiVisibility(int) 1731 */ 1732 public static final int STATUS_BAR_HIDDEN = 0x00000001; 1733 1734 /** 1735 * Controls the over-scroll mode for this view. 1736 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 1737 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 1738 * and {@link #OVER_SCROLL_NEVER}. 1739 */ 1740 private int mOverScrollMode; 1741 1742 /** 1743 * The parent this view is attached to. 1744 * {@hide} 1745 * 1746 * @see #getParent() 1747 */ 1748 protected ViewParent mParent; 1749 1750 /** 1751 * {@hide} 1752 */ 1753 AttachInfo mAttachInfo; 1754 1755 /** 1756 * {@hide} 1757 */ 1758 @ViewDebug.ExportedProperty(flagMapping = { 1759 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT, 1760 name = "FORCE_LAYOUT"), 1761 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED, 1762 name = "LAYOUT_REQUIRED"), 1763 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID, 1764 name = "DRAWING_CACHE_INVALID", outputIf = false), 1765 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true), 1766 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false), 1767 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 1768 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY") 1769 }) 1770 int mPrivateFlags; 1771 1772 /** 1773 * This view's request for the visibility of the status bar. 1774 * @hide 1775 */ 1776 int mSystemUiVisibility; 1777 1778 /** 1779 * Count of how many windows this view has been attached to. 1780 */ 1781 int mWindowAttachCount; 1782 1783 /** 1784 * The layout parameters associated with this view and used by the parent 1785 * {@link android.view.ViewGroup} to determine how this view should be 1786 * laid out. 1787 * {@hide} 1788 */ 1789 protected ViewGroup.LayoutParams mLayoutParams; 1790 1791 /** 1792 * The view flags hold various views states. 1793 * {@hide} 1794 */ 1795 @ViewDebug.ExportedProperty 1796 int mViewFlags; 1797 1798 /** 1799 * The transform matrix for the View. This transform is calculated internally 1800 * based on the rotation, scaleX, and scaleY properties. The identity matrix 1801 * is used by default. Do *not* use this variable directly; instead call 1802 * getMatrix(), which will automatically recalculate the matrix if necessary 1803 * to get the correct matrix based on the latest rotation and scale properties. 1804 */ 1805 private final Matrix mMatrix = new Matrix(); 1806 1807 /** 1808 * The transform matrix for the View. This transform is calculated internally 1809 * based on the rotation, scaleX, and scaleY properties. The identity matrix 1810 * is used by default. Do *not* use this variable directly; instead call 1811 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 1812 * to get the correct matrix based on the latest rotation and scale properties. 1813 */ 1814 private Matrix mInverseMatrix; 1815 1816 /** 1817 * An internal variable that tracks whether we need to recalculate the 1818 * transform matrix, based on whether the rotation or scaleX/Y properties 1819 * have changed since the matrix was last calculated. 1820 */ 1821 private boolean mMatrixDirty = false; 1822 1823 /** 1824 * An internal variable that tracks whether we need to recalculate the 1825 * transform matrix, based on whether the rotation or scaleX/Y properties 1826 * have changed since the matrix was last calculated. 1827 */ 1828 private boolean mInverseMatrixDirty = true; 1829 1830 /** 1831 * A variable that tracks whether we need to recalculate the 1832 * transform matrix, based on whether the rotation or scaleX/Y properties 1833 * have changed since the matrix was last calculated. This variable 1834 * is only valid after a call to updateMatrix() or to a function that 1835 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 1836 */ 1837 private boolean mMatrixIsIdentity = true; 1838 1839 /** 1840 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 1841 */ 1842 private Camera mCamera = null; 1843 1844 /** 1845 * This matrix is used when computing the matrix for 3D rotations. 1846 */ 1847 private Matrix matrix3D = null; 1848 1849 /** 1850 * These prev values are used to recalculate a centered pivot point when necessary. The 1851 * pivot point is only used in matrix operations (when rotation, scale, or translation are 1852 * set), so thes values are only used then as well. 1853 */ 1854 private int mPrevWidth = -1; 1855 private int mPrevHeight = -1; 1856 1857 private boolean mLastIsOpaque; 1858 1859 /** 1860 * Convenience value to check for float values that are close enough to zero to be considered 1861 * zero. 1862 */ 1863 private static final float NONZERO_EPSILON = .001f; 1864 1865 /** 1866 * The degrees rotation around the vertical axis through the pivot point. 1867 */ 1868 @ViewDebug.ExportedProperty 1869 private float mRotationY = 0f; 1870 1871 /** 1872 * The degrees rotation around the horizontal axis through the pivot point. 1873 */ 1874 @ViewDebug.ExportedProperty 1875 private float mRotationX = 0f; 1876 1877 /** 1878 * The degrees rotation around the pivot point. 1879 */ 1880 @ViewDebug.ExportedProperty 1881 private float mRotation = 0f; 1882 1883 /** 1884 * The amount of translation of the object away from its left property (post-layout). 1885 */ 1886 @ViewDebug.ExportedProperty 1887 private float mTranslationX = 0f; 1888 1889 /** 1890 * The amount of translation of the object away from its top property (post-layout). 1891 */ 1892 @ViewDebug.ExportedProperty 1893 private float mTranslationY = 0f; 1894 1895 /** 1896 * The amount of scale in the x direction around the pivot point. A 1897 * value of 1 means no scaling is applied. 1898 */ 1899 @ViewDebug.ExportedProperty 1900 private float mScaleX = 1f; 1901 1902 /** 1903 * The amount of scale in the y direction around the pivot point. A 1904 * value of 1 means no scaling is applied. 1905 */ 1906 @ViewDebug.ExportedProperty 1907 private float mScaleY = 1f; 1908 1909 /** 1910 * The amount of scale in the x direction around the pivot point. A 1911 * value of 1 means no scaling is applied. 1912 */ 1913 @ViewDebug.ExportedProperty 1914 private float mPivotX = 0f; 1915 1916 /** 1917 * The amount of scale in the y direction around the pivot point. A 1918 * value of 1 means no scaling is applied. 1919 */ 1920 @ViewDebug.ExportedProperty 1921 private float mPivotY = 0f; 1922 1923 /** 1924 * The opacity of the View. This is a value from 0 to 1, where 0 means 1925 * completely transparent and 1 means completely opaque. 1926 */ 1927 @ViewDebug.ExportedProperty 1928 private float mAlpha = 1f; 1929 1930 /** 1931 * The distance in pixels from the left edge of this view's parent 1932 * to the left edge of this view. 1933 * {@hide} 1934 */ 1935 @ViewDebug.ExportedProperty(category = "layout") 1936 protected int mLeft; 1937 /** 1938 * The distance in pixels from the left edge of this view's parent 1939 * to the right edge of this view. 1940 * {@hide} 1941 */ 1942 @ViewDebug.ExportedProperty(category = "layout") 1943 protected int mRight; 1944 /** 1945 * The distance in pixels from the top edge of this view's parent 1946 * to the top edge of this view. 1947 * {@hide} 1948 */ 1949 @ViewDebug.ExportedProperty(category = "layout") 1950 protected int mTop; 1951 /** 1952 * The distance in pixels from the top edge of this view's parent 1953 * to the bottom edge of this view. 1954 * {@hide} 1955 */ 1956 @ViewDebug.ExportedProperty(category = "layout") 1957 protected int mBottom; 1958 1959 /** 1960 * The offset, in pixels, by which the content of this view is scrolled 1961 * horizontally. 1962 * {@hide} 1963 */ 1964 @ViewDebug.ExportedProperty(category = "scrolling") 1965 protected int mScrollX; 1966 /** 1967 * The offset, in pixels, by which the content of this view is scrolled 1968 * vertically. 1969 * {@hide} 1970 */ 1971 @ViewDebug.ExportedProperty(category = "scrolling") 1972 protected int mScrollY; 1973 1974 /** 1975 * The left padding in pixels, that is the distance in pixels between the 1976 * left edge of this view and the left edge of its content. 1977 * {@hide} 1978 */ 1979 @ViewDebug.ExportedProperty(category = "padding") 1980 protected int mPaddingLeft; 1981 /** 1982 * The right padding in pixels, that is the distance in pixels between the 1983 * right edge of this view and the right edge of its content. 1984 * {@hide} 1985 */ 1986 @ViewDebug.ExportedProperty(category = "padding") 1987 protected int mPaddingRight; 1988 /** 1989 * The top padding in pixels, that is the distance in pixels between the 1990 * top edge of this view and the top edge of its content. 1991 * {@hide} 1992 */ 1993 @ViewDebug.ExportedProperty(category = "padding") 1994 protected int mPaddingTop; 1995 /** 1996 * The bottom padding in pixels, that is the distance in pixels between the 1997 * bottom edge of this view and the bottom edge of its content. 1998 * {@hide} 1999 */ 2000 @ViewDebug.ExportedProperty(category = "padding") 2001 protected int mPaddingBottom; 2002 2003 /** 2004 * Briefly describes the view and is primarily used for accessibility support. 2005 */ 2006 private CharSequence mContentDescription; 2007 2008 /** 2009 * Cache the paddingRight set by the user to append to the scrollbar's size. 2010 */ 2011 @ViewDebug.ExportedProperty(category = "padding") 2012 int mUserPaddingRight; 2013 2014 /** 2015 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2016 */ 2017 @ViewDebug.ExportedProperty(category = "padding") 2018 int mUserPaddingBottom; 2019 2020 /** 2021 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2022 */ 2023 @ViewDebug.ExportedProperty(category = "padding") 2024 int mUserPaddingLeft; 2025 2026 /** 2027 * @hide 2028 */ 2029 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2030 /** 2031 * @hide 2032 */ 2033 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2034 2035 private Resources mResources = null; 2036 2037 private Drawable mBGDrawable; 2038 2039 private int mBackgroundResource; 2040 private boolean mBackgroundSizeChanged; 2041 2042 /** 2043 * Listener used to dispatch focus change events. 2044 * This field should be made private, so it is hidden from the SDK. 2045 * {@hide} 2046 */ 2047 protected OnFocusChangeListener mOnFocusChangeListener; 2048 2049 /** 2050 * Listeners for layout change events. 2051 */ 2052 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2053 2054 /** 2055 * Listener used to dispatch click events. 2056 * This field should be made private, so it is hidden from the SDK. 2057 * {@hide} 2058 */ 2059 protected OnClickListener mOnClickListener; 2060 2061 /** 2062 * Listener used to dispatch long click events. 2063 * This field should be made private, so it is hidden from the SDK. 2064 * {@hide} 2065 */ 2066 protected OnLongClickListener mOnLongClickListener; 2067 2068 /** 2069 * Listener used to build the context menu. 2070 * This field should be made private, so it is hidden from the SDK. 2071 * {@hide} 2072 */ 2073 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2074 2075 private OnKeyListener mOnKeyListener; 2076 2077 private OnTouchListener mOnTouchListener; 2078 2079 private OnDragListener mOnDragListener; 2080 2081 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2082 2083 /** 2084 * The application environment this view lives in. 2085 * This field should be made private, so it is hidden from the SDK. 2086 * {@hide} 2087 */ 2088 protected Context mContext; 2089 2090 private ScrollabilityCache mScrollCache; 2091 2092 private int[] mDrawableState = null; 2093 2094 private Bitmap mDrawingCache; 2095 private Bitmap mUnscaledDrawingCache; 2096 private DisplayList mDisplayList; 2097 private HardwareLayer mHardwareLayer; 2098 2099 /** 2100 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2101 * the user may specify which view to go to next. 2102 */ 2103 private int mNextFocusLeftId = View.NO_ID; 2104 2105 /** 2106 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2107 * the user may specify which view to go to next. 2108 */ 2109 private int mNextFocusRightId = View.NO_ID; 2110 2111 /** 2112 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2113 * the user may specify which view to go to next. 2114 */ 2115 private int mNextFocusUpId = View.NO_ID; 2116 2117 /** 2118 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2119 * the user may specify which view to go to next. 2120 */ 2121 private int mNextFocusDownId = View.NO_ID; 2122 2123 /** 2124 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 2125 * the user may specify which view to go to next. 2126 */ 2127 int mNextFocusForwardId = View.NO_ID; 2128 2129 private CheckForLongPress mPendingCheckForLongPress; 2130 private CheckForTap mPendingCheckForTap = null; 2131 private PerformClick mPerformClick; 2132 2133 private UnsetPressedState mUnsetPressedState; 2134 2135 /** 2136 * Whether the long press's action has been invoked. The tap's action is invoked on the 2137 * up event while a long press is invoked as soon as the long press duration is reached, so 2138 * a long press could be performed before the tap is checked, in which case the tap's action 2139 * should not be invoked. 2140 */ 2141 private boolean mHasPerformedLongPress; 2142 2143 /** 2144 * The minimum height of the view. We'll try our best to have the height 2145 * of this view to at least this amount. 2146 */ 2147 @ViewDebug.ExportedProperty(category = "measurement") 2148 private int mMinHeight; 2149 2150 /** 2151 * The minimum width of the view. We'll try our best to have the width 2152 * of this view to at least this amount. 2153 */ 2154 @ViewDebug.ExportedProperty(category = "measurement") 2155 private int mMinWidth; 2156 2157 /** 2158 * The delegate to handle touch events that are physically in this view 2159 * but should be handled by another view. 2160 */ 2161 private TouchDelegate mTouchDelegate = null; 2162 2163 /** 2164 * Solid color to use as a background when creating the drawing cache. Enables 2165 * the cache to use 16 bit bitmaps instead of 32 bit. 2166 */ 2167 private int mDrawingCacheBackgroundColor = 0; 2168 2169 /** 2170 * Special tree observer used when mAttachInfo is null. 2171 */ 2172 private ViewTreeObserver mFloatingTreeObserver; 2173 2174 /** 2175 * Cache the touch slop from the context that created the view. 2176 */ 2177 private int mTouchSlop; 2178 2179 /** 2180 * Cache drag/drop state 2181 * 2182 */ 2183 boolean mCanAcceptDrop; 2184 2185 /** 2186 * Flag indicating that a drag can cross window boundaries 2187 * @hide 2188 */ 2189 public static final int DRAG_FLAG_GLOBAL = 1; 2190 2191 /** 2192 * Position of the vertical scroll bar. 2193 */ 2194 private int mVerticalScrollbarPosition; 2195 2196 /** 2197 * Position the scroll bar at the default position as determined by the system. 2198 */ 2199 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 2200 2201 /** 2202 * Position the scroll bar along the left edge. 2203 */ 2204 public static final int SCROLLBAR_POSITION_LEFT = 1; 2205 2206 /** 2207 * Position the scroll bar along the right edge. 2208 */ 2209 public static final int SCROLLBAR_POSITION_RIGHT = 2; 2210 2211 /** 2212 * Indicates that the view does not have a layer. 2213 * 2214 * @see #getLayerType() 2215 * @see #setLayerType(int, android.graphics.Paint) 2216 * @see #LAYER_TYPE_SOFTWARE 2217 * @see #LAYER_TYPE_HARDWARE 2218 */ 2219 public static final int LAYER_TYPE_NONE = 0; 2220 2221 /** 2222 * <p>Indicates that the view has a software layer. A software layer is backed 2223 * by a bitmap and causes the view to be rendered using Android's software 2224 * rendering pipeline, even if hardware acceleration is enabled.</p> 2225 * 2226 * <p>Software layers have various usages:</p> 2227 * <p>When the application is not using hardware acceleration, a software layer 2228 * is useful to apply a specific color filter and/or blending mode and/or 2229 * translucency to a view and all its children.</p> 2230 * <p>When the application is using hardware acceleration, a software layer 2231 * is useful to render drawing primitives not supported by the hardware 2232 * accelerated pipeline. It can also be used to cache a complex view tree 2233 * into a texture and reduce the complexity of drawing operations. For instance, 2234 * when animating a complex view tree with a translation, a software layer can 2235 * be used to render the view tree only once.</p> 2236 * <p>Software layers should be avoided when the affected view tree updates 2237 * often. Every update will require to re-render the software layer, which can 2238 * potentially be slow (particularly when hardware acceleration is turned on 2239 * since the layer will have to be uploaded into a hardware texture after every 2240 * update.)</p> 2241 * 2242 * @see #getLayerType() 2243 * @see #setLayerType(int, android.graphics.Paint) 2244 * @see #LAYER_TYPE_NONE 2245 * @see #LAYER_TYPE_HARDWARE 2246 */ 2247 public static final int LAYER_TYPE_SOFTWARE = 1; 2248 2249 /** 2250 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 2251 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 2252 * OpenGL hardware) and causes the view to be rendered using Android's hardware 2253 * rendering pipeline, but only if hardware acceleration is turned on for the 2254 * view hierarchy. When hardware acceleration is turned off, hardware layers 2255 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 2256 * 2257 * <p>A hardware layer is useful to apply a specific color filter and/or 2258 * blending mode and/or translucency to a view and all its children.</p> 2259 * <p>A hardware layer can be used to cache a complex view tree into a 2260 * texture and reduce the complexity of drawing operations. For instance, 2261 * when animating a complex view tree with a translation, a hardware layer can 2262 * be used to render the view tree only once.</p> 2263 * <p>A hardware layer can also be used to increase the rendering quality when 2264 * rotation transformations are applied on a view. It can also be used to 2265 * prevent potential clipping issues when applying 3D transforms on a view.</p> 2266 * 2267 * @see #getLayerType() 2268 * @see #setLayerType(int, android.graphics.Paint) 2269 * @see #LAYER_TYPE_NONE 2270 * @see #LAYER_TYPE_SOFTWARE 2271 */ 2272 public static final int LAYER_TYPE_HARDWARE = 2; 2273 2274 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 2275 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 2276 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 2277 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 2278 }) 2279 int mLayerType = LAYER_TYPE_NONE; 2280 Paint mLayerPaint; 2281 2282 /** 2283 * Simple constructor to use when creating a view from code. 2284 * 2285 * @param context The Context the view is running in, through which it can 2286 * access the current theme, resources, etc. 2287 */ 2288 public View(Context context) { 2289 mContext = context; 2290 mResources = context != null ? context.getResources() : null; 2291 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 2292 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 2293 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 2294 } 2295 2296 /** 2297 * Constructor that is called when inflating a view from XML. This is called 2298 * when a view is being constructed from an XML file, supplying attributes 2299 * that were specified in the XML file. This version uses a default style of 2300 * 0, so the only attribute values applied are those in the Context's Theme 2301 * and the given AttributeSet. 2302 * 2303 * <p> 2304 * The method onFinishInflate() will be called after all children have been 2305 * added. 2306 * 2307 * @param context The Context the view is running in, through which it can 2308 * access the current theme, resources, etc. 2309 * @param attrs The attributes of the XML tag that is inflating the view. 2310 * @see #View(Context, AttributeSet, int) 2311 */ 2312 public View(Context context, AttributeSet attrs) { 2313 this(context, attrs, 0); 2314 } 2315 2316 /** 2317 * Perform inflation from XML and apply a class-specific base style. This 2318 * constructor of View allows subclasses to use their own base style when 2319 * they are inflating. For example, a Button class's constructor would call 2320 * this version of the super class constructor and supply 2321 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 2322 * the theme's button style to modify all of the base view attributes (in 2323 * particular its background) as well as the Button class's attributes. 2324 * 2325 * @param context The Context the view is running in, through which it can 2326 * access the current theme, resources, etc. 2327 * @param attrs The attributes of the XML tag that is inflating the view. 2328 * @param defStyle The default style to apply to this view. If 0, no style 2329 * will be applied (beyond what is included in the theme). This may 2330 * either be an attribute resource, whose value will be retrieved 2331 * from the current theme, or an explicit style resource. 2332 * @see #View(Context, AttributeSet) 2333 */ 2334 public View(Context context, AttributeSet attrs, int defStyle) { 2335 this(context); 2336 2337 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 2338 defStyle, 0); 2339 2340 Drawable background = null; 2341 2342 int leftPadding = -1; 2343 int topPadding = -1; 2344 int rightPadding = -1; 2345 int bottomPadding = -1; 2346 2347 int padding = -1; 2348 2349 int viewFlagValues = 0; 2350 int viewFlagMasks = 0; 2351 2352 boolean setScrollContainer = false; 2353 2354 int x = 0; 2355 int y = 0; 2356 2357 float tx = 0; 2358 float ty = 0; 2359 float rotation = 0; 2360 float rotationX = 0; 2361 float rotationY = 0; 2362 float sx = 1f; 2363 float sy = 1f; 2364 boolean transformSet = false; 2365 2366 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 2367 2368 int overScrollMode = mOverScrollMode; 2369 final int N = a.getIndexCount(); 2370 for (int i = 0; i < N; i++) { 2371 int attr = a.getIndex(i); 2372 switch (attr) { 2373 case com.android.internal.R.styleable.View_background: 2374 background = a.getDrawable(attr); 2375 break; 2376 case com.android.internal.R.styleable.View_padding: 2377 padding = a.getDimensionPixelSize(attr, -1); 2378 break; 2379 case com.android.internal.R.styleable.View_paddingLeft: 2380 leftPadding = a.getDimensionPixelSize(attr, -1); 2381 break; 2382 case com.android.internal.R.styleable.View_paddingTop: 2383 topPadding = a.getDimensionPixelSize(attr, -1); 2384 break; 2385 case com.android.internal.R.styleable.View_paddingRight: 2386 rightPadding = a.getDimensionPixelSize(attr, -1); 2387 break; 2388 case com.android.internal.R.styleable.View_paddingBottom: 2389 bottomPadding = a.getDimensionPixelSize(attr, -1); 2390 break; 2391 case com.android.internal.R.styleable.View_scrollX: 2392 x = a.getDimensionPixelOffset(attr, 0); 2393 break; 2394 case com.android.internal.R.styleable.View_scrollY: 2395 y = a.getDimensionPixelOffset(attr, 0); 2396 break; 2397 case com.android.internal.R.styleable.View_alpha: 2398 setAlpha(a.getFloat(attr, 1f)); 2399 break; 2400 case com.android.internal.R.styleable.View_transformPivotX: 2401 setPivotX(a.getDimensionPixelOffset(attr, 0)); 2402 break; 2403 case com.android.internal.R.styleable.View_transformPivotY: 2404 setPivotY(a.getDimensionPixelOffset(attr, 0)); 2405 break; 2406 case com.android.internal.R.styleable.View_translationX: 2407 tx = a.getDimensionPixelOffset(attr, 0); 2408 transformSet = true; 2409 break; 2410 case com.android.internal.R.styleable.View_translationY: 2411 ty = a.getDimensionPixelOffset(attr, 0); 2412 transformSet = true; 2413 break; 2414 case com.android.internal.R.styleable.View_rotation: 2415 rotation = a.getFloat(attr, 0); 2416 transformSet = true; 2417 break; 2418 case com.android.internal.R.styleable.View_rotationX: 2419 rotationX = a.getFloat(attr, 0); 2420 transformSet = true; 2421 break; 2422 case com.android.internal.R.styleable.View_rotationY: 2423 rotationY = a.getFloat(attr, 0); 2424 transformSet = true; 2425 break; 2426 case com.android.internal.R.styleable.View_scaleX: 2427 sx = a.getFloat(attr, 1f); 2428 transformSet = true; 2429 break; 2430 case com.android.internal.R.styleable.View_scaleY: 2431 sy = a.getFloat(attr, 1f); 2432 transformSet = true; 2433 break; 2434 case com.android.internal.R.styleable.View_id: 2435 mID = a.getResourceId(attr, NO_ID); 2436 break; 2437 case com.android.internal.R.styleable.View_tag: 2438 mTag = a.getText(attr); 2439 break; 2440 case com.android.internal.R.styleable.View_fitsSystemWindows: 2441 if (a.getBoolean(attr, false)) { 2442 viewFlagValues |= FITS_SYSTEM_WINDOWS; 2443 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 2444 } 2445 break; 2446 case com.android.internal.R.styleable.View_focusable: 2447 if (a.getBoolean(attr, false)) { 2448 viewFlagValues |= FOCUSABLE; 2449 viewFlagMasks |= FOCUSABLE_MASK; 2450 } 2451 break; 2452 case com.android.internal.R.styleable.View_focusableInTouchMode: 2453 if (a.getBoolean(attr, false)) { 2454 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 2455 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 2456 } 2457 break; 2458 case com.android.internal.R.styleable.View_clickable: 2459 if (a.getBoolean(attr, false)) { 2460 viewFlagValues |= CLICKABLE; 2461 viewFlagMasks |= CLICKABLE; 2462 } 2463 break; 2464 case com.android.internal.R.styleable.View_longClickable: 2465 if (a.getBoolean(attr, false)) { 2466 viewFlagValues |= LONG_CLICKABLE; 2467 viewFlagMasks |= LONG_CLICKABLE; 2468 } 2469 break; 2470 case com.android.internal.R.styleable.View_saveEnabled: 2471 if (!a.getBoolean(attr, true)) { 2472 viewFlagValues |= SAVE_DISABLED; 2473 viewFlagMasks |= SAVE_DISABLED_MASK; 2474 } 2475 break; 2476 case com.android.internal.R.styleable.View_duplicateParentState: 2477 if (a.getBoolean(attr, false)) { 2478 viewFlagValues |= DUPLICATE_PARENT_STATE; 2479 viewFlagMasks |= DUPLICATE_PARENT_STATE; 2480 } 2481 break; 2482 case com.android.internal.R.styleable.View_visibility: 2483 final int visibility = a.getInt(attr, 0); 2484 if (visibility != 0) { 2485 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 2486 viewFlagMasks |= VISIBILITY_MASK; 2487 } 2488 break; 2489 case com.android.internal.R.styleable.View_drawingCacheQuality: 2490 final int cacheQuality = a.getInt(attr, 0); 2491 if (cacheQuality != 0) { 2492 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 2493 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 2494 } 2495 break; 2496 case com.android.internal.R.styleable.View_contentDescription: 2497 mContentDescription = a.getString(attr); 2498 break; 2499 case com.android.internal.R.styleable.View_soundEffectsEnabled: 2500 if (!a.getBoolean(attr, true)) { 2501 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 2502 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 2503 } 2504 break; 2505 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 2506 if (!a.getBoolean(attr, true)) { 2507 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 2508 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 2509 } 2510 break; 2511 case R.styleable.View_scrollbars: 2512 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 2513 if (scrollbars != SCROLLBARS_NONE) { 2514 viewFlagValues |= scrollbars; 2515 viewFlagMasks |= SCROLLBARS_MASK; 2516 initializeScrollbars(a); 2517 } 2518 break; 2519 case R.styleable.View_fadingEdge: 2520 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 2521 if (fadingEdge != FADING_EDGE_NONE) { 2522 viewFlagValues |= fadingEdge; 2523 viewFlagMasks |= FADING_EDGE_MASK; 2524 initializeFadingEdge(a); 2525 } 2526 break; 2527 case R.styleable.View_scrollbarStyle: 2528 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 2529 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 2530 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 2531 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 2532 } 2533 break; 2534 case R.styleable.View_isScrollContainer: 2535 setScrollContainer = true; 2536 if (a.getBoolean(attr, false)) { 2537 setScrollContainer(true); 2538 } 2539 break; 2540 case com.android.internal.R.styleable.View_keepScreenOn: 2541 if (a.getBoolean(attr, false)) { 2542 viewFlagValues |= KEEP_SCREEN_ON; 2543 viewFlagMasks |= KEEP_SCREEN_ON; 2544 } 2545 break; 2546 case R.styleable.View_filterTouchesWhenObscured: 2547 if (a.getBoolean(attr, false)) { 2548 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 2549 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 2550 } 2551 break; 2552 case R.styleable.View_nextFocusLeft: 2553 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 2554 break; 2555 case R.styleable.View_nextFocusRight: 2556 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 2557 break; 2558 case R.styleable.View_nextFocusUp: 2559 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 2560 break; 2561 case R.styleable.View_nextFocusDown: 2562 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 2563 break; 2564 case R.styleable.View_nextFocusForward: 2565 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 2566 break; 2567 case R.styleable.View_minWidth: 2568 mMinWidth = a.getDimensionPixelSize(attr, 0); 2569 break; 2570 case R.styleable.View_minHeight: 2571 mMinHeight = a.getDimensionPixelSize(attr, 0); 2572 break; 2573 case R.styleable.View_onClick: 2574 if (context.isRestricted()) { 2575 throw new IllegalStateException("The android:onClick attribute cannot " 2576 + "be used within a restricted context"); 2577 } 2578 2579 final String handlerName = a.getString(attr); 2580 if (handlerName != null) { 2581 setOnClickListener(new OnClickListener() { 2582 private Method mHandler; 2583 2584 public void onClick(View v) { 2585 if (mHandler == null) { 2586 try { 2587 mHandler = getContext().getClass().getMethod(handlerName, 2588 View.class); 2589 } catch (NoSuchMethodException e) { 2590 int id = getId(); 2591 String idText = id == NO_ID ? "" : " with id '" 2592 + getContext().getResources().getResourceEntryName( 2593 id) + "'"; 2594 throw new IllegalStateException("Could not find a method " + 2595 handlerName + "(View) in the activity " 2596 + getContext().getClass() + " for onClick handler" 2597 + " on view " + View.this.getClass() + idText, e); 2598 } 2599 } 2600 2601 try { 2602 mHandler.invoke(getContext(), View.this); 2603 } catch (IllegalAccessException e) { 2604 throw new IllegalStateException("Could not execute non " 2605 + "public method of the activity", e); 2606 } catch (InvocationTargetException e) { 2607 throw new IllegalStateException("Could not execute " 2608 + "method of the activity", e); 2609 } 2610 } 2611 }); 2612 } 2613 break; 2614 case R.styleable.View_overScrollMode: 2615 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 2616 break; 2617 case R.styleable.View_verticalScrollbarPosition: 2618 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 2619 break; 2620 case R.styleable.View_layerType: 2621 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 2622 break; 2623 } 2624 } 2625 2626 setOverScrollMode(overScrollMode); 2627 2628 if (background != null) { 2629 setBackgroundDrawable(background); 2630 } 2631 2632 if (padding >= 0) { 2633 leftPadding = padding; 2634 topPadding = padding; 2635 rightPadding = padding; 2636 bottomPadding = padding; 2637 } 2638 2639 // If the user specified the padding (either with android:padding or 2640 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 2641 // use the default padding or the padding from the background drawable 2642 // (stored at this point in mPadding*) 2643 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft, 2644 topPadding >= 0 ? topPadding : mPaddingTop, 2645 rightPadding >= 0 ? rightPadding : mPaddingRight, 2646 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 2647 2648 if (viewFlagMasks != 0) { 2649 setFlags(viewFlagValues, viewFlagMasks); 2650 } 2651 2652 // Needs to be called after mViewFlags is set 2653 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 2654 recomputePadding(); 2655 } 2656 2657 if (x != 0 || y != 0) { 2658 scrollTo(x, y); 2659 } 2660 2661 if (transformSet) { 2662 setTranslationX(tx); 2663 setTranslationY(ty); 2664 setRotation(rotation); 2665 setRotationX(rotationX); 2666 setRotationY(rotationY); 2667 setScaleX(sx); 2668 setScaleY(sy); 2669 } 2670 2671 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 2672 setScrollContainer(true); 2673 } 2674 2675 computeOpaqueFlags(); 2676 2677 a.recycle(); 2678 } 2679 2680 /** 2681 * Non-public constructor for use in testing 2682 */ 2683 View() { 2684 } 2685 2686 /** 2687 * <p> 2688 * Initializes the fading edges from a given set of styled attributes. This 2689 * method should be called by subclasses that need fading edges and when an 2690 * instance of these subclasses is created programmatically rather than 2691 * being inflated from XML. This method is automatically called when the XML 2692 * is inflated. 2693 * </p> 2694 * 2695 * @param a the styled attributes set to initialize the fading edges from 2696 */ 2697 protected void initializeFadingEdge(TypedArray a) { 2698 initScrollCache(); 2699 2700 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 2701 R.styleable.View_fadingEdgeLength, 2702 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 2703 } 2704 2705 /** 2706 * Returns the size of the vertical faded edges used to indicate that more 2707 * content in this view is visible. 2708 * 2709 * @return The size in pixels of the vertical faded edge or 0 if vertical 2710 * faded edges are not enabled for this view. 2711 * @attr ref android.R.styleable#View_fadingEdgeLength 2712 */ 2713 public int getVerticalFadingEdgeLength() { 2714 if (isVerticalFadingEdgeEnabled()) { 2715 ScrollabilityCache cache = mScrollCache; 2716 if (cache != null) { 2717 return cache.fadingEdgeLength; 2718 } 2719 } 2720 return 0; 2721 } 2722 2723 /** 2724 * Set the size of the faded edge used to indicate that more content in this 2725 * view is available. Will not change whether the fading edge is enabled; use 2726 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled} 2727 * to enable the fading edge for the vertical or horizontal fading edges. 2728 * 2729 * @param length The size in pixels of the faded edge used to indicate that more 2730 * content in this view is visible. 2731 */ 2732 public void setFadingEdgeLength(int length) { 2733 initScrollCache(); 2734 mScrollCache.fadingEdgeLength = length; 2735 } 2736 2737 /** 2738 * Returns the size of the horizontal faded edges used to indicate that more 2739 * content in this view is visible. 2740 * 2741 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 2742 * faded edges are not enabled for this view. 2743 * @attr ref android.R.styleable#View_fadingEdgeLength 2744 */ 2745 public int getHorizontalFadingEdgeLength() { 2746 if (isHorizontalFadingEdgeEnabled()) { 2747 ScrollabilityCache cache = mScrollCache; 2748 if (cache != null) { 2749 return cache.fadingEdgeLength; 2750 } 2751 } 2752 return 0; 2753 } 2754 2755 /** 2756 * Returns the width of the vertical scrollbar. 2757 * 2758 * @return The width in pixels of the vertical scrollbar or 0 if there 2759 * is no vertical scrollbar. 2760 */ 2761 public int getVerticalScrollbarWidth() { 2762 ScrollabilityCache cache = mScrollCache; 2763 if (cache != null) { 2764 ScrollBarDrawable scrollBar = cache.scrollBar; 2765 if (scrollBar != null) { 2766 int size = scrollBar.getSize(true); 2767 if (size <= 0) { 2768 size = cache.scrollBarSize; 2769 } 2770 return size; 2771 } 2772 return 0; 2773 } 2774 return 0; 2775 } 2776 2777 /** 2778 * Returns the height of the horizontal scrollbar. 2779 * 2780 * @return The height in pixels of the horizontal scrollbar or 0 if 2781 * there is no horizontal scrollbar. 2782 */ 2783 protected int getHorizontalScrollbarHeight() { 2784 ScrollabilityCache cache = mScrollCache; 2785 if (cache != null) { 2786 ScrollBarDrawable scrollBar = cache.scrollBar; 2787 if (scrollBar != null) { 2788 int size = scrollBar.getSize(false); 2789 if (size <= 0) { 2790 size = cache.scrollBarSize; 2791 } 2792 return size; 2793 } 2794 return 0; 2795 } 2796 return 0; 2797 } 2798 2799 /** 2800 * <p> 2801 * Initializes the scrollbars from a given set of styled attributes. This 2802 * method should be called by subclasses that need scrollbars and when an 2803 * instance of these subclasses is created programmatically rather than 2804 * being inflated from XML. This method is automatically called when the XML 2805 * is inflated. 2806 * </p> 2807 * 2808 * @param a the styled attributes set to initialize the scrollbars from 2809 */ 2810 protected void initializeScrollbars(TypedArray a) { 2811 initScrollCache(); 2812 2813 final ScrollabilityCache scrollabilityCache = mScrollCache; 2814 2815 if (scrollabilityCache.scrollBar == null) { 2816 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 2817 } 2818 2819 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 2820 2821 if (!fadeScrollbars) { 2822 scrollabilityCache.state = ScrollabilityCache.ON; 2823 } 2824 scrollabilityCache.fadeScrollBars = fadeScrollbars; 2825 2826 2827 scrollabilityCache.scrollBarFadeDuration = a.getInt( 2828 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 2829 .getScrollBarFadeDuration()); 2830 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 2831 R.styleable.View_scrollbarDefaultDelayBeforeFade, 2832 ViewConfiguration.getScrollDefaultDelay()); 2833 2834 2835 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 2836 com.android.internal.R.styleable.View_scrollbarSize, 2837 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 2838 2839 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 2840 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 2841 2842 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 2843 if (thumb != null) { 2844 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 2845 } 2846 2847 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 2848 false); 2849 if (alwaysDraw) { 2850 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 2851 } 2852 2853 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 2854 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 2855 2856 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 2857 if (thumb != null) { 2858 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 2859 } 2860 2861 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 2862 false); 2863 if (alwaysDraw) { 2864 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 2865 } 2866 2867 // Re-apply user/background padding so that scrollbar(s) get added 2868 recomputePadding(); 2869 } 2870 2871 /** 2872 * <p> 2873 * Initalizes the scrollability cache if necessary. 2874 * </p> 2875 */ 2876 private void initScrollCache() { 2877 if (mScrollCache == null) { 2878 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 2879 } 2880 } 2881 2882 /** 2883 * Set the position of the vertical scroll bar. Should be one of 2884 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 2885 * {@link #SCROLLBAR_POSITION_RIGHT}. 2886 * 2887 * @param position Where the vertical scroll bar should be positioned. 2888 */ 2889 public void setVerticalScrollbarPosition(int position) { 2890 if (mVerticalScrollbarPosition != position) { 2891 mVerticalScrollbarPosition = position; 2892 computeOpaqueFlags(); 2893 recomputePadding(); 2894 } 2895 } 2896 2897 /** 2898 * @return The position where the vertical scroll bar will show, if applicable. 2899 * @see #setVerticalScrollbarPosition(int) 2900 */ 2901 public int getVerticalScrollbarPosition() { 2902 return mVerticalScrollbarPosition; 2903 } 2904 2905 /** 2906 * Register a callback to be invoked when focus of this view changed. 2907 * 2908 * @param l The callback that will run. 2909 */ 2910 public void setOnFocusChangeListener(OnFocusChangeListener l) { 2911 mOnFocusChangeListener = l; 2912 } 2913 2914 /** 2915 * Add a listener that will be called when the bounds of the view change due to 2916 * layout processing. 2917 * 2918 * @param listener The listener that will be called when layout bounds change. 2919 */ 2920 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 2921 if (mOnLayoutChangeListeners == null) { 2922 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 2923 } 2924 mOnLayoutChangeListeners.add(listener); 2925 } 2926 2927 /** 2928 * Remove a listener for layout changes. 2929 * 2930 * @param listener The listener for layout bounds change. 2931 */ 2932 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 2933 if (mOnLayoutChangeListeners == null) { 2934 return; 2935 } 2936 mOnLayoutChangeListeners.remove(listener); 2937 } 2938 2939 /** 2940 * Returns the focus-change callback registered for this view. 2941 * 2942 * @return The callback, or null if one is not registered. 2943 */ 2944 public OnFocusChangeListener getOnFocusChangeListener() { 2945 return mOnFocusChangeListener; 2946 } 2947 2948 /** 2949 * Register a callback to be invoked when this view is clicked. If this view is not 2950 * clickable, it becomes clickable. 2951 * 2952 * @param l The callback that will run 2953 * 2954 * @see #setClickable(boolean) 2955 */ 2956 public void setOnClickListener(OnClickListener l) { 2957 if (!isClickable()) { 2958 setClickable(true); 2959 } 2960 mOnClickListener = l; 2961 } 2962 2963 /** 2964 * Register a callback to be invoked when this view is clicked and held. If this view is not 2965 * long clickable, it becomes long clickable. 2966 * 2967 * @param l The callback that will run 2968 * 2969 * @see #setLongClickable(boolean) 2970 */ 2971 public void setOnLongClickListener(OnLongClickListener l) { 2972 if (!isLongClickable()) { 2973 setLongClickable(true); 2974 } 2975 mOnLongClickListener = l; 2976 } 2977 2978 /** 2979 * Register a callback to be invoked when the context menu for this view is 2980 * being built. If this view is not long clickable, it becomes long clickable. 2981 * 2982 * @param l The callback that will run 2983 * 2984 */ 2985 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 2986 if (!isLongClickable()) { 2987 setLongClickable(true); 2988 } 2989 mOnCreateContextMenuListener = l; 2990 } 2991 2992 /** 2993 * Call this view's OnClickListener, if it is defined. 2994 * 2995 * @return True there was an assigned OnClickListener that was called, false 2996 * otherwise is returned. 2997 */ 2998 public boolean performClick() { 2999 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 3000 3001 if (mOnClickListener != null) { 3002 playSoundEffect(SoundEffectConstants.CLICK); 3003 mOnClickListener.onClick(this); 3004 return true; 3005 } 3006 3007 return false; 3008 } 3009 3010 /** 3011 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 3012 * OnLongClickListener did not consume the event. 3013 * 3014 * @return True if one of the above receivers consumed the event, false otherwise. 3015 */ 3016 public boolean performLongClick() { 3017 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 3018 3019 boolean handled = false; 3020 if (mOnLongClickListener != null) { 3021 handled = mOnLongClickListener.onLongClick(View.this); 3022 } 3023 if (!handled) { 3024 handled = showContextMenu(); 3025 } 3026 if (handled) { 3027 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 3028 } 3029 return handled; 3030 } 3031 3032 /** 3033 * Bring up the context menu for this view. 3034 * 3035 * @return Whether a context menu was displayed. 3036 */ 3037 public boolean showContextMenu() { 3038 return getParent().showContextMenuForChild(this); 3039 } 3040 3041 /** 3042 * Start an action mode. 3043 * 3044 * @param callback Callback that will control the lifecycle of the action mode 3045 * @return The new action mode if it is started, null otherwise 3046 * 3047 * @see ActionMode 3048 */ 3049 public ActionMode startActionMode(ActionMode.Callback callback) { 3050 return getParent().startActionModeForChild(this, callback); 3051 } 3052 3053 /** 3054 * Register a callback to be invoked when a key is pressed in this view. 3055 * @param l the key listener to attach to this view 3056 */ 3057 public void setOnKeyListener(OnKeyListener l) { 3058 mOnKeyListener = l; 3059 } 3060 3061 /** 3062 * Register a callback to be invoked when a touch event is sent to this view. 3063 * @param l the touch listener to attach to this view 3064 */ 3065 public void setOnTouchListener(OnTouchListener l) { 3066 mOnTouchListener = l; 3067 } 3068 3069 /** 3070 * Register a callback to be invoked when a drag event is sent to this view. 3071 * @param l The drag listener to attach to this view 3072 */ 3073 public void setOnDragListener(OnDragListener l) { 3074 mOnDragListener = l; 3075 } 3076 3077 /** 3078 * Give this view focus. This will cause {@link #onFocusChanged} to be called. 3079 * 3080 * Note: this does not check whether this {@link View} should get focus, it just 3081 * gives it focus no matter what. It should only be called internally by framework 3082 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 3083 * 3084 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN, 3085 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which 3086 * focus moved when requestFocus() is called. It may not always 3087 * apply, in which case use the default View.FOCUS_DOWN. 3088 * @param previouslyFocusedRect The rectangle of the view that had focus 3089 * prior in this View's coordinate system. 3090 */ 3091 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 3092 if (DBG) { 3093 System.out.println(this + " requestFocus()"); 3094 } 3095 3096 if ((mPrivateFlags & FOCUSED) == 0) { 3097 mPrivateFlags |= FOCUSED; 3098 3099 if (mParent != null) { 3100 mParent.requestChildFocus(this, this); 3101 } 3102 3103 onFocusChanged(true, direction, previouslyFocusedRect); 3104 refreshDrawableState(); 3105 } 3106 } 3107 3108 /** 3109 * Request that a rectangle of this view be visible on the screen, 3110 * scrolling if necessary just enough. 3111 * 3112 * <p>A View should call this if it maintains some notion of which part 3113 * of its content is interesting. For example, a text editing view 3114 * should call this when its cursor moves. 3115 * 3116 * @param rectangle The rectangle. 3117 * @return Whether any parent scrolled. 3118 */ 3119 public boolean requestRectangleOnScreen(Rect rectangle) { 3120 return requestRectangleOnScreen(rectangle, false); 3121 } 3122 3123 /** 3124 * Request that a rectangle of this view be visible on the screen, 3125 * scrolling if necessary just enough. 3126 * 3127 * <p>A View should call this if it maintains some notion of which part 3128 * of its content is interesting. For example, a text editing view 3129 * should call this when its cursor moves. 3130 * 3131 * <p>When <code>immediate</code> is set to true, scrolling will not be 3132 * animated. 3133 * 3134 * @param rectangle The rectangle. 3135 * @param immediate True to forbid animated scrolling, false otherwise 3136 * @return Whether any parent scrolled. 3137 */ 3138 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 3139 View child = this; 3140 ViewParent parent = mParent; 3141 boolean scrolled = false; 3142 while (parent != null) { 3143 scrolled |= parent.requestChildRectangleOnScreen(child, 3144 rectangle, immediate); 3145 3146 // offset rect so next call has the rectangle in the 3147 // coordinate system of its direct child. 3148 rectangle.offset(child.getLeft(), child.getTop()); 3149 rectangle.offset(-child.getScrollX(), -child.getScrollY()); 3150 3151 if (!(parent instanceof View)) { 3152 break; 3153 } 3154 3155 child = (View) parent; 3156 parent = child.getParent(); 3157 } 3158 return scrolled; 3159 } 3160 3161 /** 3162 * Called when this view wants to give up focus. This will cause 3163 * {@link #onFocusChanged} to be called. 3164 */ 3165 public void clearFocus() { 3166 if (DBG) { 3167 System.out.println(this + " clearFocus()"); 3168 } 3169 3170 if ((mPrivateFlags & FOCUSED) != 0) { 3171 mPrivateFlags &= ~FOCUSED; 3172 3173 if (mParent != null) { 3174 mParent.clearChildFocus(this); 3175 } 3176 3177 onFocusChanged(false, 0, null); 3178 refreshDrawableState(); 3179 } 3180 } 3181 3182 /** 3183 * Called to clear the focus of a view that is about to be removed. 3184 * Doesn't call clearChildFocus, which prevents this view from taking 3185 * focus again before it has been removed from the parent 3186 */ 3187 void clearFocusForRemoval() { 3188 if ((mPrivateFlags & FOCUSED) != 0) { 3189 mPrivateFlags &= ~FOCUSED; 3190 3191 onFocusChanged(false, 0, null); 3192 refreshDrawableState(); 3193 } 3194 } 3195 3196 /** 3197 * Called internally by the view system when a new view is getting focus. 3198 * This is what clears the old focus. 3199 */ 3200 void unFocus() { 3201 if (DBG) { 3202 System.out.println(this + " unFocus()"); 3203 } 3204 3205 if ((mPrivateFlags & FOCUSED) != 0) { 3206 mPrivateFlags &= ~FOCUSED; 3207 3208 onFocusChanged(false, 0, null); 3209 refreshDrawableState(); 3210 } 3211 } 3212 3213 /** 3214 * Returns true if this view has focus iteself, or is the ancestor of the 3215 * view that has focus. 3216 * 3217 * @return True if this view has or contains focus, false otherwise. 3218 */ 3219 @ViewDebug.ExportedProperty(category = "focus") 3220 public boolean hasFocus() { 3221 return (mPrivateFlags & FOCUSED) != 0; 3222 } 3223 3224 /** 3225 * Returns true if this view is focusable or if it contains a reachable View 3226 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 3227 * is a View whose parents do not block descendants focus. 3228 * 3229 * Only {@link #VISIBLE} views are considered focusable. 3230 * 3231 * @return True if the view is focusable or if the view contains a focusable 3232 * View, false otherwise. 3233 * 3234 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 3235 */ 3236 public boolean hasFocusable() { 3237 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 3238 } 3239 3240 /** 3241 * Called by the view system when the focus state of this view changes. 3242 * When the focus change event is caused by directional navigation, direction 3243 * and previouslyFocusedRect provide insight into where the focus is coming from. 3244 * When overriding, be sure to call up through to the super class so that 3245 * the standard focus handling will occur. 3246 * 3247 * @param gainFocus True if the View has focus; false otherwise. 3248 * @param direction The direction focus has moved when requestFocus() 3249 * is called to give this view focus. Values are 3250 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 3251 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 3252 * It may not always apply, in which case use the default. 3253 * @param previouslyFocusedRect The rectangle, in this view's coordinate 3254 * system, of the previously focused view. If applicable, this will be 3255 * passed in as finer grained information about where the focus is coming 3256 * from (in addition to direction). Will be <code>null</code> otherwise. 3257 */ 3258 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 3259 if (gainFocus) { 3260 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 3261 } 3262 3263 InputMethodManager imm = InputMethodManager.peekInstance(); 3264 if (!gainFocus) { 3265 if (isPressed()) { 3266 setPressed(false); 3267 } 3268 if (imm != null && mAttachInfo != null 3269 && mAttachInfo.mHasWindowFocus) { 3270 imm.focusOut(this); 3271 } 3272 onFocusLost(); 3273 } else if (imm != null && mAttachInfo != null 3274 && mAttachInfo.mHasWindowFocus) { 3275 imm.focusIn(this); 3276 } 3277 3278 invalidate(true); 3279 if (mOnFocusChangeListener != null) { 3280 mOnFocusChangeListener.onFocusChange(this, gainFocus); 3281 } 3282 3283 if (mAttachInfo != null) { 3284 mAttachInfo.mKeyDispatchState.reset(this); 3285 } 3286 } 3287 3288 /** 3289 * {@inheritDoc} 3290 */ 3291 public void sendAccessibilityEvent(int eventType) { 3292 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 3293 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 3294 } 3295 } 3296 3297 /** 3298 * {@inheritDoc} 3299 */ 3300 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 3301 if (!isShown()) { 3302 return; 3303 } 3304 event.setClassName(getClass().getName()); 3305 event.setPackageName(getContext().getPackageName()); 3306 event.setEnabled(isEnabled()); 3307 event.setContentDescription(mContentDescription); 3308 3309 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) { 3310 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList; 3311 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 3312 event.setItemCount(focusablesTempList.size()); 3313 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 3314 focusablesTempList.clear(); 3315 } 3316 3317 dispatchPopulateAccessibilityEvent(event); 3318 3319 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event); 3320 } 3321 3322 /** 3323 * Dispatches an {@link AccessibilityEvent} to the {@link View} children 3324 * to be populated. 3325 * 3326 * @param event The event. 3327 * 3328 * @return True if the event population was completed. 3329 */ 3330 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 3331 return false; 3332 } 3333 3334 /** 3335 * Gets the {@link View} description. It briefly describes the view and is 3336 * primarily used for accessibility support. Set this property to enable 3337 * better accessibility support for your application. This is especially 3338 * true for views that do not have textual representation (For example, 3339 * ImageButton). 3340 * 3341 * @return The content descriptiopn. 3342 * 3343 * @attr ref android.R.styleable#View_contentDescription 3344 */ 3345 public CharSequence getContentDescription() { 3346 return mContentDescription; 3347 } 3348 3349 /** 3350 * Sets the {@link View} description. It briefly describes the view and is 3351 * primarily used for accessibility support. Set this property to enable 3352 * better accessibility support for your application. This is especially 3353 * true for views that do not have textual representation (For example, 3354 * ImageButton). 3355 * 3356 * @param contentDescription The content description. 3357 * 3358 * @attr ref android.R.styleable#View_contentDescription 3359 */ 3360 public void setContentDescription(CharSequence contentDescription) { 3361 mContentDescription = contentDescription; 3362 } 3363 3364 /** 3365 * Invoked whenever this view loses focus, either by losing window focus or by losing 3366 * focus within its window. This method can be used to clear any state tied to the 3367 * focus. For instance, if a button is held pressed with the trackball and the window 3368 * loses focus, this method can be used to cancel the press. 3369 * 3370 * Subclasses of View overriding this method should always call super.onFocusLost(). 3371 * 3372 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 3373 * @see #onWindowFocusChanged(boolean) 3374 * 3375 * @hide pending API council approval 3376 */ 3377 protected void onFocusLost() { 3378 resetPressedState(); 3379 } 3380 3381 private void resetPressedState() { 3382 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 3383 return; 3384 } 3385 3386 if (isPressed()) { 3387 setPressed(false); 3388 3389 if (!mHasPerformedLongPress) { 3390 removeLongPressCallback(); 3391 } 3392 } 3393 } 3394 3395 /** 3396 * Returns true if this view has focus 3397 * 3398 * @return True if this view has focus, false otherwise. 3399 */ 3400 @ViewDebug.ExportedProperty(category = "focus") 3401 public boolean isFocused() { 3402 return (mPrivateFlags & FOCUSED) != 0; 3403 } 3404 3405 /** 3406 * Find the view in the hierarchy rooted at this view that currently has 3407 * focus. 3408 * 3409 * @return The view that currently has focus, or null if no focused view can 3410 * be found. 3411 */ 3412 public View findFocus() { 3413 return (mPrivateFlags & FOCUSED) != 0 ? this : null; 3414 } 3415 3416 /** 3417 * Change whether this view is one of the set of scrollable containers in 3418 * its window. This will be used to determine whether the window can 3419 * resize or must pan when a soft input area is open -- scrollable 3420 * containers allow the window to use resize mode since the container 3421 * will appropriately shrink. 3422 */ 3423 public void setScrollContainer(boolean isScrollContainer) { 3424 if (isScrollContainer) { 3425 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) { 3426 mAttachInfo.mScrollContainers.add(this); 3427 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 3428 } 3429 mPrivateFlags |= SCROLL_CONTAINER; 3430 } else { 3431 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 3432 mAttachInfo.mScrollContainers.remove(this); 3433 } 3434 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED); 3435 } 3436 } 3437 3438 /** 3439 * Returns the quality of the drawing cache. 3440 * 3441 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 3442 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 3443 * 3444 * @see #setDrawingCacheQuality(int) 3445 * @see #setDrawingCacheEnabled(boolean) 3446 * @see #isDrawingCacheEnabled() 3447 * 3448 * @attr ref android.R.styleable#View_drawingCacheQuality 3449 */ 3450 public int getDrawingCacheQuality() { 3451 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 3452 } 3453 3454 /** 3455 * Set the drawing cache quality of this view. This value is used only when the 3456 * drawing cache is enabled 3457 * 3458 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 3459 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 3460 * 3461 * @see #getDrawingCacheQuality() 3462 * @see #setDrawingCacheEnabled(boolean) 3463 * @see #isDrawingCacheEnabled() 3464 * 3465 * @attr ref android.R.styleable#View_drawingCacheQuality 3466 */ 3467 public void setDrawingCacheQuality(int quality) { 3468 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 3469 } 3470 3471 /** 3472 * Returns whether the screen should remain on, corresponding to the current 3473 * value of {@link #KEEP_SCREEN_ON}. 3474 * 3475 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 3476 * 3477 * @see #setKeepScreenOn(boolean) 3478 * 3479 * @attr ref android.R.styleable#View_keepScreenOn 3480 */ 3481 public boolean getKeepScreenOn() { 3482 return (mViewFlags & KEEP_SCREEN_ON) != 0; 3483 } 3484 3485 /** 3486 * Controls whether the screen should remain on, modifying the 3487 * value of {@link #KEEP_SCREEN_ON}. 3488 * 3489 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 3490 * 3491 * @see #getKeepScreenOn() 3492 * 3493 * @attr ref android.R.styleable#View_keepScreenOn 3494 */ 3495 public void setKeepScreenOn(boolean keepScreenOn) { 3496 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 3497 } 3498 3499 /** 3500 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 3501 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 3502 * 3503 * @attr ref android.R.styleable#View_nextFocusLeft 3504 */ 3505 public int getNextFocusLeftId() { 3506 return mNextFocusLeftId; 3507 } 3508 3509 /** 3510 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 3511 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 3512 * decide automatically. 3513 * 3514 * @attr ref android.R.styleable#View_nextFocusLeft 3515 */ 3516 public void setNextFocusLeftId(int nextFocusLeftId) { 3517 mNextFocusLeftId = nextFocusLeftId; 3518 } 3519 3520 /** 3521 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 3522 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 3523 * 3524 * @attr ref android.R.styleable#View_nextFocusRight 3525 */ 3526 public int getNextFocusRightId() { 3527 return mNextFocusRightId; 3528 } 3529 3530 /** 3531 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 3532 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 3533 * decide automatically. 3534 * 3535 * @attr ref android.R.styleable#View_nextFocusRight 3536 */ 3537 public void setNextFocusRightId(int nextFocusRightId) { 3538 mNextFocusRightId = nextFocusRightId; 3539 } 3540 3541 /** 3542 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 3543 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 3544 * 3545 * @attr ref android.R.styleable#View_nextFocusUp 3546 */ 3547 public int getNextFocusUpId() { 3548 return mNextFocusUpId; 3549 } 3550 3551 /** 3552 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 3553 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 3554 * decide automatically. 3555 * 3556 * @attr ref android.R.styleable#View_nextFocusUp 3557 */ 3558 public void setNextFocusUpId(int nextFocusUpId) { 3559 mNextFocusUpId = nextFocusUpId; 3560 } 3561 3562 /** 3563 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 3564 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 3565 * 3566 * @attr ref android.R.styleable#View_nextFocusDown 3567 */ 3568 public int getNextFocusDownId() { 3569 return mNextFocusDownId; 3570 } 3571 3572 /** 3573 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 3574 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 3575 * decide automatically. 3576 * 3577 * @attr ref android.R.styleable#View_nextFocusDown 3578 */ 3579 public void setNextFocusDownId(int nextFocusDownId) { 3580 mNextFocusDownId = nextFocusDownId; 3581 } 3582 3583 /** 3584 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 3585 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 3586 * 3587 * @attr ref android.R.styleable#View_nextFocusForward 3588 */ 3589 public int getNextFocusForwardId() { 3590 return mNextFocusForwardId; 3591 } 3592 3593 /** 3594 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 3595 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 3596 * decide automatically. 3597 * 3598 * @attr ref android.R.styleable#View_nextFocusForward 3599 */ 3600 public void setNextFocusForwardId(int nextFocusForwardId) { 3601 mNextFocusForwardId = nextFocusForwardId; 3602 } 3603 3604 /** 3605 * Returns the visibility of this view and all of its ancestors 3606 * 3607 * @return True if this view and all of its ancestors are {@link #VISIBLE} 3608 */ 3609 public boolean isShown() { 3610 View current = this; 3611 //noinspection ConstantConditions 3612 do { 3613 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 3614 return false; 3615 } 3616 ViewParent parent = current.mParent; 3617 if (parent == null) { 3618 return false; // We are not attached to the view root 3619 } 3620 if (!(parent instanceof View)) { 3621 return true; 3622 } 3623 current = (View) parent; 3624 } while (current != null); 3625 3626 return false; 3627 } 3628 3629 /** 3630 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag 3631 * is set 3632 * 3633 * @param insets Insets for system windows 3634 * 3635 * @return True if this view applied the insets, false otherwise 3636 */ 3637 protected boolean fitSystemWindows(Rect insets) { 3638 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 3639 mPaddingLeft = insets.left; 3640 mPaddingTop = insets.top; 3641 mPaddingRight = insets.right; 3642 mPaddingBottom = insets.bottom; 3643 requestLayout(); 3644 return true; 3645 } 3646 return false; 3647 } 3648 3649 /** 3650 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set. 3651 * @return True if window has FITS_SYSTEM_WINDOWS set 3652 * 3653 * @hide 3654 */ 3655 public boolean isFitsSystemWindowsFlagSet() { 3656 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 3657 } 3658 3659 /** 3660 * Returns the visibility status for this view. 3661 * 3662 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 3663 * @attr ref android.R.styleable#View_visibility 3664 */ 3665 @ViewDebug.ExportedProperty(mapping = { 3666 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 3667 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 3668 @ViewDebug.IntToString(from = GONE, to = "GONE") 3669 }) 3670 public int getVisibility() { 3671 return mViewFlags & VISIBILITY_MASK; 3672 } 3673 3674 /** 3675 * Set the enabled state of this view. 3676 * 3677 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 3678 * @attr ref android.R.styleable#View_visibility 3679 */ 3680 @RemotableViewMethod 3681 public void setVisibility(int visibility) { 3682 setFlags(visibility, VISIBILITY_MASK); 3683 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); 3684 } 3685 3686 /** 3687 * Returns the enabled status for this view. The interpretation of the 3688 * enabled state varies by subclass. 3689 * 3690 * @return True if this view is enabled, false otherwise. 3691 */ 3692 @ViewDebug.ExportedProperty 3693 public boolean isEnabled() { 3694 return (mViewFlags & ENABLED_MASK) == ENABLED; 3695 } 3696 3697 /** 3698 * Set the enabled state of this view. The interpretation of the enabled 3699 * state varies by subclass. 3700 * 3701 * @param enabled True if this view is enabled, false otherwise. 3702 */ 3703 @RemotableViewMethod 3704 public void setEnabled(boolean enabled) { 3705 if (enabled == isEnabled()) return; 3706 3707 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 3708 3709 /* 3710 * The View most likely has to change its appearance, so refresh 3711 * the drawable state. 3712 */ 3713 refreshDrawableState(); 3714 3715 // Invalidate too, since the default behavior for views is to be 3716 // be drawn at 50% alpha rather than to change the drawable. 3717 invalidate(true); 3718 } 3719 3720 /** 3721 * Set whether this view can receive the focus. 3722 * 3723 * Setting this to false will also ensure that this view is not focusable 3724 * in touch mode. 3725 * 3726 * @param focusable If true, this view can receive the focus. 3727 * 3728 * @see #setFocusableInTouchMode(boolean) 3729 * @attr ref android.R.styleable#View_focusable 3730 */ 3731 public void setFocusable(boolean focusable) { 3732 if (!focusable) { 3733 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 3734 } 3735 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 3736 } 3737 3738 /** 3739 * Set whether this view can receive focus while in touch mode. 3740 * 3741 * Setting this to true will also ensure that this view is focusable. 3742 * 3743 * @param focusableInTouchMode If true, this view can receive the focus while 3744 * in touch mode. 3745 * 3746 * @see #setFocusable(boolean) 3747 * @attr ref android.R.styleable#View_focusableInTouchMode 3748 */ 3749 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 3750 // Focusable in touch mode should always be set before the focusable flag 3751 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 3752 // which, in touch mode, will not successfully request focus on this view 3753 // because the focusable in touch mode flag is not set 3754 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 3755 if (focusableInTouchMode) { 3756 setFlags(FOCUSABLE, FOCUSABLE_MASK); 3757 } 3758 } 3759 3760 /** 3761 * Set whether this view should have sound effects enabled for events such as 3762 * clicking and touching. 3763 * 3764 * <p>You may wish to disable sound effects for a view if you already play sounds, 3765 * for instance, a dial key that plays dtmf tones. 3766 * 3767 * @param soundEffectsEnabled whether sound effects are enabled for this view. 3768 * @see #isSoundEffectsEnabled() 3769 * @see #playSoundEffect(int) 3770 * @attr ref android.R.styleable#View_soundEffectsEnabled 3771 */ 3772 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 3773 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 3774 } 3775 3776 /** 3777 * @return whether this view should have sound effects enabled for events such as 3778 * clicking and touching. 3779 * 3780 * @see #setSoundEffectsEnabled(boolean) 3781 * @see #playSoundEffect(int) 3782 * @attr ref android.R.styleable#View_soundEffectsEnabled 3783 */ 3784 @ViewDebug.ExportedProperty 3785 public boolean isSoundEffectsEnabled() { 3786 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 3787 } 3788 3789 /** 3790 * Set whether this view should have haptic feedback for events such as 3791 * long presses. 3792 * 3793 * <p>You may wish to disable haptic feedback if your view already controls 3794 * its own haptic feedback. 3795 * 3796 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 3797 * @see #isHapticFeedbackEnabled() 3798 * @see #performHapticFeedback(int) 3799 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 3800 */ 3801 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 3802 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 3803 } 3804 3805 /** 3806 * @return whether this view should have haptic feedback enabled for events 3807 * long presses. 3808 * 3809 * @see #setHapticFeedbackEnabled(boolean) 3810 * @see #performHapticFeedback(int) 3811 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 3812 */ 3813 @ViewDebug.ExportedProperty 3814 public boolean isHapticFeedbackEnabled() { 3815 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 3816 } 3817 3818 /** 3819 * If this view doesn't do any drawing on its own, set this flag to 3820 * allow further optimizations. By default, this flag is not set on 3821 * View, but could be set on some View subclasses such as ViewGroup. 3822 * 3823 * Typically, if you override {@link #onDraw} you should clear this flag. 3824 * 3825 * @param willNotDraw whether or not this View draw on its own 3826 */ 3827 public void setWillNotDraw(boolean willNotDraw) { 3828 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 3829 } 3830 3831 /** 3832 * Returns whether or not this View draws on its own. 3833 * 3834 * @return true if this view has nothing to draw, false otherwise 3835 */ 3836 @ViewDebug.ExportedProperty(category = "drawing") 3837 public boolean willNotDraw() { 3838 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 3839 } 3840 3841 /** 3842 * When a View's drawing cache is enabled, drawing is redirected to an 3843 * offscreen bitmap. Some views, like an ImageView, must be able to 3844 * bypass this mechanism if they already draw a single bitmap, to avoid 3845 * unnecessary usage of the memory. 3846 * 3847 * @param willNotCacheDrawing true if this view does not cache its 3848 * drawing, false otherwise 3849 */ 3850 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 3851 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 3852 } 3853 3854 /** 3855 * Returns whether or not this View can cache its drawing or not. 3856 * 3857 * @return true if this view does not cache its drawing, false otherwise 3858 */ 3859 @ViewDebug.ExportedProperty(category = "drawing") 3860 public boolean willNotCacheDrawing() { 3861 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 3862 } 3863 3864 /** 3865 * Indicates whether this view reacts to click events or not. 3866 * 3867 * @return true if the view is clickable, false otherwise 3868 * 3869 * @see #setClickable(boolean) 3870 * @attr ref android.R.styleable#View_clickable 3871 */ 3872 @ViewDebug.ExportedProperty 3873 public boolean isClickable() { 3874 return (mViewFlags & CLICKABLE) == CLICKABLE; 3875 } 3876 3877 /** 3878 * Enables or disables click events for this view. When a view 3879 * is clickable it will change its state to "pressed" on every click. 3880 * Subclasses should set the view clickable to visually react to 3881 * user's clicks. 3882 * 3883 * @param clickable true to make the view clickable, false otherwise 3884 * 3885 * @see #isClickable() 3886 * @attr ref android.R.styleable#View_clickable 3887 */ 3888 public void setClickable(boolean clickable) { 3889 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 3890 } 3891 3892 /** 3893 * Indicates whether this view reacts to long click events or not. 3894 * 3895 * @return true if the view is long clickable, false otherwise 3896 * 3897 * @see #setLongClickable(boolean) 3898 * @attr ref android.R.styleable#View_longClickable 3899 */ 3900 public boolean isLongClickable() { 3901 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 3902 } 3903 3904 /** 3905 * Enables or disables long click events for this view. When a view is long 3906 * clickable it reacts to the user holding down the button for a longer 3907 * duration than a tap. This event can either launch the listener or a 3908 * context menu. 3909 * 3910 * @param longClickable true to make the view long clickable, false otherwise 3911 * @see #isLongClickable() 3912 * @attr ref android.R.styleable#View_longClickable 3913 */ 3914 public void setLongClickable(boolean longClickable) { 3915 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 3916 } 3917 3918 /** 3919 * Sets the pressed state for this view. 3920 * 3921 * @see #isClickable() 3922 * @see #setClickable(boolean) 3923 * 3924 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 3925 * the View's internal state from a previously set "pressed" state. 3926 */ 3927 public void setPressed(boolean pressed) { 3928 if (pressed) { 3929 mPrivateFlags |= PRESSED; 3930 } else { 3931 mPrivateFlags &= ~PRESSED; 3932 } 3933 refreshDrawableState(); 3934 dispatchSetPressed(pressed); 3935 } 3936 3937 /** 3938 * Dispatch setPressed to all of this View's children. 3939 * 3940 * @see #setPressed(boolean) 3941 * 3942 * @param pressed The new pressed state 3943 */ 3944 protected void dispatchSetPressed(boolean pressed) { 3945 } 3946 3947 /** 3948 * Indicates whether the view is currently in pressed state. Unless 3949 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 3950 * the pressed state. 3951 * 3952 * @see #setPressed 3953 * @see #isClickable() 3954 * @see #setClickable(boolean) 3955 * 3956 * @return true if the view is currently pressed, false otherwise 3957 */ 3958 public boolean isPressed() { 3959 return (mPrivateFlags & PRESSED) == PRESSED; 3960 } 3961 3962 /** 3963 * Indicates whether this view will save its state (that is, 3964 * whether its {@link #onSaveInstanceState} method will be called). 3965 * 3966 * @return Returns true if the view state saving is enabled, else false. 3967 * 3968 * @see #setSaveEnabled(boolean) 3969 * @attr ref android.R.styleable#View_saveEnabled 3970 */ 3971 public boolean isSaveEnabled() { 3972 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 3973 } 3974 3975 /** 3976 * Controls whether the saving of this view's state is 3977 * enabled (that is, whether its {@link #onSaveInstanceState} method 3978 * will be called). Note that even if freezing is enabled, the 3979 * view still must have an id assigned to it (via {@link #setId setId()}) 3980 * for its state to be saved. This flag can only disable the 3981 * saving of this view; any child views may still have their state saved. 3982 * 3983 * @param enabled Set to false to <em>disable</em> state saving, or true 3984 * (the default) to allow it. 3985 * 3986 * @see #isSaveEnabled() 3987 * @see #setId(int) 3988 * @see #onSaveInstanceState() 3989 * @attr ref android.R.styleable#View_saveEnabled 3990 */ 3991 public void setSaveEnabled(boolean enabled) { 3992 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 3993 } 3994 3995 /** 3996 * Gets whether the framework should discard touches when the view's 3997 * window is obscured by another visible window. 3998 * Refer to the {@link View} security documentation for more details. 3999 * 4000 * @return True if touch filtering is enabled. 4001 * 4002 * @see #setFilterTouchesWhenObscured(boolean) 4003 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4004 */ 4005 @ViewDebug.ExportedProperty 4006 public boolean getFilterTouchesWhenObscured() { 4007 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 4008 } 4009 4010 /** 4011 * Sets whether the framework should discard touches when the view's 4012 * window is obscured by another visible window. 4013 * Refer to the {@link View} security documentation for more details. 4014 * 4015 * @param enabled True if touch filtering should be enabled. 4016 * 4017 * @see #getFilterTouchesWhenObscured 4018 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4019 */ 4020 public void setFilterTouchesWhenObscured(boolean enabled) { 4021 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 4022 FILTER_TOUCHES_WHEN_OBSCURED); 4023 } 4024 4025 /** 4026 * Indicates whether the entire hierarchy under this view will save its 4027 * state when a state saving traversal occurs from its parent. The default 4028 * is true; if false, these views will not be saved unless 4029 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4030 * 4031 * @return Returns true if the view state saving from parent is enabled, else false. 4032 * 4033 * @see #setSaveFromParentEnabled(boolean) 4034 */ 4035 public boolean isSaveFromParentEnabled() { 4036 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 4037 } 4038 4039 /** 4040 * Controls whether the entire hierarchy under this view will save its 4041 * state when a state saving traversal occurs from its parent. The default 4042 * is true; if false, these views will not be saved unless 4043 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4044 * 4045 * @param enabled Set to false to <em>disable</em> state saving, or true 4046 * (the default) to allow it. 4047 * 4048 * @see #isSaveFromParentEnabled() 4049 * @see #setId(int) 4050 * @see #onSaveInstanceState() 4051 */ 4052 public void setSaveFromParentEnabled(boolean enabled) { 4053 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 4054 } 4055 4056 4057 /** 4058 * Returns whether this View is able to take focus. 4059 * 4060 * @return True if this view can take focus, or false otherwise. 4061 * @attr ref android.R.styleable#View_focusable 4062 */ 4063 @ViewDebug.ExportedProperty(category = "focus") 4064 public final boolean isFocusable() { 4065 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 4066 } 4067 4068 /** 4069 * When a view is focusable, it may not want to take focus when in touch mode. 4070 * For example, a button would like focus when the user is navigating via a D-pad 4071 * so that the user can click on it, but once the user starts touching the screen, 4072 * the button shouldn't take focus 4073 * @return Whether the view is focusable in touch mode. 4074 * @attr ref android.R.styleable#View_focusableInTouchMode 4075 */ 4076 @ViewDebug.ExportedProperty 4077 public final boolean isFocusableInTouchMode() { 4078 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 4079 } 4080 4081 /** 4082 * Find the nearest view in the specified direction that can take focus. 4083 * This does not actually give focus to that view. 4084 * 4085 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4086 * 4087 * @return The nearest focusable in the specified direction, or null if none 4088 * can be found. 4089 */ 4090 public View focusSearch(int direction) { 4091 if (mParent != null) { 4092 return mParent.focusSearch(this, direction); 4093 } else { 4094 return null; 4095 } 4096 } 4097 4098 /** 4099 * This method is the last chance for the focused view and its ancestors to 4100 * respond to an arrow key. This is called when the focused view did not 4101 * consume the key internally, nor could the view system find a new view in 4102 * the requested direction to give focus to. 4103 * 4104 * @param focused The currently focused view. 4105 * @param direction The direction focus wants to move. One of FOCUS_UP, 4106 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 4107 * @return True if the this view consumed this unhandled move. 4108 */ 4109 public boolean dispatchUnhandledMove(View focused, int direction) { 4110 return false; 4111 } 4112 4113 /** 4114 * If a user manually specified the next view id for a particular direction, 4115 * use the root to look up the view. 4116 * @param root The root view of the hierarchy containing this view. 4117 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 4118 * or FOCUS_BACKWARD. 4119 * @return The user specified next view, or null if there is none. 4120 */ 4121 View findUserSetNextFocus(View root, int direction) { 4122 switch (direction) { 4123 case FOCUS_LEFT: 4124 if (mNextFocusLeftId == View.NO_ID) return null; 4125 return findViewShouldExist(root, mNextFocusLeftId); 4126 case FOCUS_RIGHT: 4127 if (mNextFocusRightId == View.NO_ID) return null; 4128 return findViewShouldExist(root, mNextFocusRightId); 4129 case FOCUS_UP: 4130 if (mNextFocusUpId == View.NO_ID) return null; 4131 return findViewShouldExist(root, mNextFocusUpId); 4132 case FOCUS_DOWN: 4133 if (mNextFocusDownId == View.NO_ID) return null; 4134 return findViewShouldExist(root, mNextFocusDownId); 4135 case FOCUS_FORWARD: 4136 if (mNextFocusForwardId == View.NO_ID) return null; 4137 return findViewShouldExist(root, mNextFocusForwardId); 4138 case FOCUS_BACKWARD: { 4139 final int id = mID; 4140 return root.findViewByPredicate(new Predicate<View>() { 4141 @Override 4142 public boolean apply(View t) { 4143 return t.mNextFocusForwardId == id; 4144 } 4145 }); 4146 } 4147 } 4148 return null; 4149 } 4150 4151 private static View findViewShouldExist(View root, int childViewId) { 4152 View result = root.findViewById(childViewId); 4153 if (result == null) { 4154 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified " 4155 + "by user for id " + childViewId); 4156 } 4157 return result; 4158 } 4159 4160 /** 4161 * Find and return all focusable views that are descendants of this view, 4162 * possibly including this view if it is focusable itself. 4163 * 4164 * @param direction The direction of the focus 4165 * @return A list of focusable views 4166 */ 4167 public ArrayList<View> getFocusables(int direction) { 4168 ArrayList<View> result = new ArrayList<View>(24); 4169 addFocusables(result, direction); 4170 return result; 4171 } 4172 4173 /** 4174 * Add any focusable views that are descendants of this view (possibly 4175 * including this view if it is focusable itself) to views. If we are in touch mode, 4176 * only add views that are also focusable in touch mode. 4177 * 4178 * @param views Focusable views found so far 4179 * @param direction The direction of the focus 4180 */ 4181 public void addFocusables(ArrayList<View> views, int direction) { 4182 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 4183 } 4184 4185 /** 4186 * Adds any focusable views that are descendants of this view (possibly 4187 * including this view if it is focusable itself) to views. This method 4188 * adds all focusable views regardless if we are in touch mode or 4189 * only views focusable in touch mode if we are in touch mode depending on 4190 * the focusable mode paramater. 4191 * 4192 * @param views Focusable views found so far or null if all we are interested is 4193 * the number of focusables. 4194 * @param direction The direction of the focus. 4195 * @param focusableMode The type of focusables to be added. 4196 * 4197 * @see #FOCUSABLES_ALL 4198 * @see #FOCUSABLES_TOUCH_MODE 4199 */ 4200 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 4201 if (!isFocusable()) { 4202 return; 4203 } 4204 4205 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 4206 isInTouchMode() && !isFocusableInTouchMode()) { 4207 return; 4208 } 4209 4210 if (views != null) { 4211 views.add(this); 4212 } 4213 } 4214 4215 /** 4216 * Find and return all touchable views that are descendants of this view, 4217 * possibly including this view if it is touchable itself. 4218 * 4219 * @return A list of touchable views 4220 */ 4221 public ArrayList<View> getTouchables() { 4222 ArrayList<View> result = new ArrayList<View>(); 4223 addTouchables(result); 4224 return result; 4225 } 4226 4227 /** 4228 * Add any touchable views that are descendants of this view (possibly 4229 * including this view if it is touchable itself) to views. 4230 * 4231 * @param views Touchable views found so far 4232 */ 4233 public void addTouchables(ArrayList<View> views) { 4234 final int viewFlags = mViewFlags; 4235 4236 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 4237 && (viewFlags & ENABLED_MASK) == ENABLED) { 4238 views.add(this); 4239 } 4240 } 4241 4242 /** 4243 * Call this to try to give focus to a specific view or to one of its 4244 * descendants. 4245 * 4246 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false), 4247 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode}) 4248 * while the device is in touch mode. 4249 * 4250 * See also {@link #focusSearch}, which is what you call to say that you 4251 * have focus, and you want your parent to look for the next one. 4252 * 4253 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 4254 * {@link #FOCUS_DOWN} and <code>null</code>. 4255 * 4256 * @return Whether this view or one of its descendants actually took focus. 4257 */ 4258 public final boolean requestFocus() { 4259 return requestFocus(View.FOCUS_DOWN); 4260 } 4261 4262 4263 /** 4264 * Call this to try to give focus to a specific view or to one of its 4265 * descendants and give it a hint about what direction focus is heading. 4266 * 4267 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false), 4268 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode}) 4269 * while the device is in touch mode. 4270 * 4271 * See also {@link #focusSearch}, which is what you call to say that you 4272 * have focus, and you want your parent to look for the next one. 4273 * 4274 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 4275 * <code>null</code> set for the previously focused rectangle. 4276 * 4277 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4278 * @return Whether this view or one of its descendants actually took focus. 4279 */ 4280 public final boolean requestFocus(int direction) { 4281 return requestFocus(direction, null); 4282 } 4283 4284 /** 4285 * Call this to try to give focus to a specific view or to one of its descendants 4286 * and give it hints about the direction and a specific rectangle that the focus 4287 * is coming from. The rectangle can help give larger views a finer grained hint 4288 * about where focus is coming from, and therefore, where to show selection, or 4289 * forward focus change internally. 4290 * 4291 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false), 4292 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode}) 4293 * while the device is in touch mode. 4294 * 4295 * A View will not take focus if it is not visible. 4296 * 4297 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()} 4298 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 4299 * 4300 * See also {@link #focusSearch}, which is what you call to say that you 4301 * have focus, and you want your parent to look for the next one. 4302 * 4303 * You may wish to override this method if your custom {@link View} has an internal 4304 * {@link View} that it wishes to forward the request to. 4305 * 4306 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4307 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 4308 * to give a finer grained hint about where focus is coming from. May be null 4309 * if there is no hint. 4310 * @return Whether this view or one of its descendants actually took focus. 4311 */ 4312 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 4313 // need to be focusable 4314 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 4315 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 4316 return false; 4317 } 4318 4319 // need to be focusable in touch mode if in touch mode 4320 if (isInTouchMode() && 4321 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 4322 return false; 4323 } 4324 4325 // need to not have any parents blocking us 4326 if (hasAncestorThatBlocksDescendantFocus()) { 4327 return false; 4328 } 4329 4330 handleFocusGainInternal(direction, previouslyFocusedRect); 4331 return true; 4332 } 4333 4334 /** Gets the ViewRoot, or null if not attached. */ 4335 /*package*/ ViewRoot getViewRoot() { 4336 View root = getRootView(); 4337 return root != null ? (ViewRoot)root.getParent() : null; 4338 } 4339 4340 /** 4341 * Call this to try to give focus to a specific view or to one of its descendants. This is a 4342 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 4343 * touch mode to request focus when they are touched. 4344 * 4345 * @return Whether this view or one of its descendants actually took focus. 4346 * 4347 * @see #isInTouchMode() 4348 * 4349 */ 4350 public final boolean requestFocusFromTouch() { 4351 // Leave touch mode if we need to 4352 if (isInTouchMode()) { 4353 ViewRoot viewRoot = getViewRoot(); 4354 if (viewRoot != null) { 4355 viewRoot.ensureTouchMode(false); 4356 } 4357 } 4358 return requestFocus(View.FOCUS_DOWN); 4359 } 4360 4361 /** 4362 * @return Whether any ancestor of this view blocks descendant focus. 4363 */ 4364 private boolean hasAncestorThatBlocksDescendantFocus() { 4365 ViewParent ancestor = mParent; 4366 while (ancestor instanceof ViewGroup) { 4367 final ViewGroup vgAncestor = (ViewGroup) ancestor; 4368 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 4369 return true; 4370 } else { 4371 ancestor = vgAncestor.getParent(); 4372 } 4373 } 4374 return false; 4375 } 4376 4377 /** 4378 * @hide 4379 */ 4380 public void dispatchStartTemporaryDetach() { 4381 onStartTemporaryDetach(); 4382 } 4383 4384 /** 4385 * This is called when a container is going to temporarily detach a child, with 4386 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 4387 * It will either be followed by {@link #onFinishTemporaryDetach()} or 4388 * {@link #onDetachedFromWindow()} when the container is done. 4389 */ 4390 public void onStartTemporaryDetach() { 4391 removeUnsetPressCallback(); 4392 mPrivateFlags |= CANCEL_NEXT_UP_EVENT; 4393 } 4394 4395 /** 4396 * @hide 4397 */ 4398 public void dispatchFinishTemporaryDetach() { 4399 onFinishTemporaryDetach(); 4400 } 4401 4402 /** 4403 * Called after {@link #onStartTemporaryDetach} when the container is done 4404 * changing the view. 4405 */ 4406 public void onFinishTemporaryDetach() { 4407 } 4408 4409 /** 4410 * capture information of this view for later analysis: developement only 4411 * check dynamic switch to make sure we only dump view 4412 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set 4413 */ 4414 private static void captureViewInfo(String subTag, View v) { 4415 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) { 4416 return; 4417 } 4418 ViewDebug.dumpCapturedView(subTag, v); 4419 } 4420 4421 /** 4422 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 4423 * for this view's window. Returns null if the view is not currently attached 4424 * to the window. Normally you will not need to use this directly, but 4425 * just use the standard high-level event callbacks like {@link #onKeyDown}. 4426 */ 4427 public KeyEvent.DispatcherState getKeyDispatcherState() { 4428 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 4429 } 4430 4431 /** 4432 * Dispatch a key event before it is processed by any input method 4433 * associated with the view hierarchy. This can be used to intercept 4434 * key events in special situations before the IME consumes them; a 4435 * typical example would be handling the BACK key to update the application's 4436 * UI instead of allowing the IME to see it and close itself. 4437 * 4438 * @param event The key event to be dispatched. 4439 * @return True if the event was handled, false otherwise. 4440 */ 4441 public boolean dispatchKeyEventPreIme(KeyEvent event) { 4442 return onKeyPreIme(event.getKeyCode(), event); 4443 } 4444 4445 /** 4446 * Dispatch a key event to the next view on the focus path. This path runs 4447 * from the top of the view tree down to the currently focused view. If this 4448 * view has focus, it will dispatch to itself. Otherwise it will dispatch 4449 * the next node down the focus path. This method also fires any key 4450 * listeners. 4451 * 4452 * @param event The key event to be dispatched. 4453 * @return True if the event was handled, false otherwise. 4454 */ 4455 public boolean dispatchKeyEvent(KeyEvent event) { 4456 // If any attached key listener a first crack at the event. 4457 4458 //noinspection SimplifiableIfStatement,deprecation 4459 if (android.util.Config.LOGV) { 4460 captureViewInfo("captureViewKeyEvent", this); 4461 } 4462 4463 //noinspection SimplifiableIfStatement 4464 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 4465 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 4466 return true; 4467 } 4468 4469 return event.dispatch(this, mAttachInfo != null 4470 ? mAttachInfo.mKeyDispatchState : null, this); 4471 } 4472 4473 /** 4474 * Dispatches a key shortcut event. 4475 * 4476 * @param event The key event to be dispatched. 4477 * @return True if the event was handled by the view, false otherwise. 4478 */ 4479 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 4480 return onKeyShortcut(event.getKeyCode(), event); 4481 } 4482 4483 /** 4484 * Pass the touch screen motion event down to the target view, or this 4485 * view if it is the target. 4486 * 4487 * @param event The motion event to be dispatched. 4488 * @return True if the event was handled by the view, false otherwise. 4489 */ 4490 public boolean dispatchTouchEvent(MotionEvent event) { 4491 if (!onFilterTouchEventForSecurity(event)) { 4492 return false; 4493 } 4494 4495 //noinspection SimplifiableIfStatement 4496 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && 4497 mOnTouchListener.onTouch(this, event)) { 4498 return true; 4499 } 4500 return onTouchEvent(event); 4501 } 4502 4503 /** 4504 * Filter the touch event to apply security policies. 4505 * 4506 * @param event The motion event to be filtered. 4507 * @return True if the event should be dispatched, false if the event should be dropped. 4508 * 4509 * @see #getFilterTouchesWhenObscured 4510 */ 4511 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 4512 //noinspection RedundantIfStatement 4513 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 4514 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 4515 // Window is obscured, drop this touch. 4516 return false; 4517 } 4518 return true; 4519 } 4520 4521 /** 4522 * Pass a trackball motion event down to the focused view. 4523 * 4524 * @param event The motion event to be dispatched. 4525 * @return True if the event was handled by the view, false otherwise. 4526 */ 4527 public boolean dispatchTrackballEvent(MotionEvent event) { 4528 //Log.i("view", "view=" + this + ", " + event.toString()); 4529 return onTrackballEvent(event); 4530 } 4531 4532 /** 4533 * Called when the window containing this view gains or loses window focus. 4534 * ViewGroups should override to route to their children. 4535 * 4536 * @param hasFocus True if the window containing this view now has focus, 4537 * false otherwise. 4538 */ 4539 public void dispatchWindowFocusChanged(boolean hasFocus) { 4540 onWindowFocusChanged(hasFocus); 4541 } 4542 4543 /** 4544 * Called when the window containing this view gains or loses focus. Note 4545 * that this is separate from view focus: to receive key events, both 4546 * your view and its window must have focus. If a window is displayed 4547 * on top of yours that takes input focus, then your own window will lose 4548 * focus but the view focus will remain unchanged. 4549 * 4550 * @param hasWindowFocus True if the window containing this view now has 4551 * focus, false otherwise. 4552 */ 4553 public void onWindowFocusChanged(boolean hasWindowFocus) { 4554 InputMethodManager imm = InputMethodManager.peekInstance(); 4555 if (!hasWindowFocus) { 4556 if (isPressed()) { 4557 setPressed(false); 4558 } 4559 if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 4560 imm.focusOut(this); 4561 } 4562 removeLongPressCallback(); 4563 removeTapCallback(); 4564 onFocusLost(); 4565 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 4566 imm.focusIn(this); 4567 } 4568 refreshDrawableState(); 4569 } 4570 4571 /** 4572 * Returns true if this view is in a window that currently has window focus. 4573 * Note that this is not the same as the view itself having focus. 4574 * 4575 * @return True if this view is in a window that currently has window focus. 4576 */ 4577 public boolean hasWindowFocus() { 4578 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 4579 } 4580 4581 /** 4582 * Dispatch a view visibility change down the view hierarchy. 4583 * ViewGroups should override to route to their children. 4584 * @param changedView The view whose visibility changed. Could be 'this' or 4585 * an ancestor view. 4586 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 4587 * {@link #INVISIBLE} or {@link #GONE}. 4588 */ 4589 protected void dispatchVisibilityChanged(View changedView, int visibility) { 4590 onVisibilityChanged(changedView, visibility); 4591 } 4592 4593 /** 4594 * Called when the visibility of the view or an ancestor of the view is changed. 4595 * @param changedView The view whose visibility changed. Could be 'this' or 4596 * an ancestor view. 4597 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 4598 * {@link #INVISIBLE} or {@link #GONE}. 4599 */ 4600 protected void onVisibilityChanged(View changedView, int visibility) { 4601 if (visibility == VISIBLE) { 4602 if (mAttachInfo != null) { 4603 initialAwakenScrollBars(); 4604 } else { 4605 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH; 4606 } 4607 } 4608 } 4609 4610 /** 4611 * Dispatch a hint about whether this view is displayed. For instance, when 4612 * a View moves out of the screen, it might receives a display hint indicating 4613 * the view is not displayed. Applications should not <em>rely</em> on this hint 4614 * as there is no guarantee that they will receive one. 4615 * 4616 * @param hint A hint about whether or not this view is displayed: 4617 * {@link #VISIBLE} or {@link #INVISIBLE}. 4618 */ 4619 public void dispatchDisplayHint(int hint) { 4620 onDisplayHint(hint); 4621 } 4622 4623 /** 4624 * Gives this view a hint about whether is displayed or not. For instance, when 4625 * a View moves out of the screen, it might receives a display hint indicating 4626 * the view is not displayed. Applications should not <em>rely</em> on this hint 4627 * as there is no guarantee that they will receive one. 4628 * 4629 * @param hint A hint about whether or not this view is displayed: 4630 * {@link #VISIBLE} or {@link #INVISIBLE}. 4631 */ 4632 protected void onDisplayHint(int hint) { 4633 } 4634 4635 /** 4636 * Dispatch a window visibility change down the view hierarchy. 4637 * ViewGroups should override to route to their children. 4638 * 4639 * @param visibility The new visibility of the window. 4640 * 4641 * @see #onWindowVisibilityChanged 4642 */ 4643 public void dispatchWindowVisibilityChanged(int visibility) { 4644 onWindowVisibilityChanged(visibility); 4645 } 4646 4647 /** 4648 * Called when the window containing has change its visibility 4649 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 4650 * that this tells you whether or not your window is being made visible 4651 * to the window manager; this does <em>not</em> tell you whether or not 4652 * your window is obscured by other windows on the screen, even if it 4653 * is itself visible. 4654 * 4655 * @param visibility The new visibility of the window. 4656 */ 4657 protected void onWindowVisibilityChanged(int visibility) { 4658 if (visibility == VISIBLE) { 4659 initialAwakenScrollBars(); 4660 } 4661 } 4662 4663 /** 4664 * Returns the current visibility of the window this view is attached to 4665 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 4666 * 4667 * @return Returns the current visibility of the view's window. 4668 */ 4669 public int getWindowVisibility() { 4670 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 4671 } 4672 4673 /** 4674 * Retrieve the overall visible display size in which the window this view is 4675 * attached to has been positioned in. This takes into account screen 4676 * decorations above the window, for both cases where the window itself 4677 * is being position inside of them or the window is being placed under 4678 * then and covered insets are used for the window to position its content 4679 * inside. In effect, this tells you the available area where content can 4680 * be placed and remain visible to users. 4681 * 4682 * <p>This function requires an IPC back to the window manager to retrieve 4683 * the requested information, so should not be used in performance critical 4684 * code like drawing. 4685 * 4686 * @param outRect Filled in with the visible display frame. If the view 4687 * is not attached to a window, this is simply the raw display size. 4688 */ 4689 public void getWindowVisibleDisplayFrame(Rect outRect) { 4690 if (mAttachInfo != null) { 4691 try { 4692 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 4693 } catch (RemoteException e) { 4694 return; 4695 } 4696 // XXX This is really broken, and probably all needs to be done 4697 // in the window manager, and we need to know more about whether 4698 // we want the area behind or in front of the IME. 4699 final Rect insets = mAttachInfo.mVisibleInsets; 4700 outRect.left += insets.left; 4701 outRect.top += insets.top; 4702 outRect.right -= insets.right; 4703 outRect.bottom -= insets.bottom; 4704 return; 4705 } 4706 Display d = WindowManagerImpl.getDefault().getDefaultDisplay(); 4707 outRect.set(0, 0, d.getWidth(), d.getHeight()); 4708 } 4709 4710 /** 4711 * Dispatch a notification about a resource configuration change down 4712 * the view hierarchy. 4713 * ViewGroups should override to route to their children. 4714 * 4715 * @param newConfig The new resource configuration. 4716 * 4717 * @see #onConfigurationChanged 4718 */ 4719 public void dispatchConfigurationChanged(Configuration newConfig) { 4720 onConfigurationChanged(newConfig); 4721 } 4722 4723 /** 4724 * Called when the current configuration of the resources being used 4725 * by the application have changed. You can use this to decide when 4726 * to reload resources that can changed based on orientation and other 4727 * configuration characterstics. You only need to use this if you are 4728 * not relying on the normal {@link android.app.Activity} mechanism of 4729 * recreating the activity instance upon a configuration change. 4730 * 4731 * @param newConfig The new resource configuration. 4732 */ 4733 protected void onConfigurationChanged(Configuration newConfig) { 4734 } 4735 4736 /** 4737 * Private function to aggregate all per-view attributes in to the view 4738 * root. 4739 */ 4740 void dispatchCollectViewAttributes(int visibility) { 4741 performCollectViewAttributes(visibility); 4742 } 4743 4744 void performCollectViewAttributes(int visibility) { 4745 if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) { 4746 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 4747 mAttachInfo.mKeepScreenOn = true; 4748 } 4749 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility; 4750 if (mOnSystemUiVisibilityChangeListener != null) { 4751 mAttachInfo.mHasSystemUiListeners = true; 4752 } 4753 } 4754 } 4755 4756 void needGlobalAttributesUpdate(boolean force) { 4757 final AttachInfo ai = mAttachInfo; 4758 if (ai != null) { 4759 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 4760 || ai.mHasSystemUiListeners) { 4761 ai.mRecomputeGlobalAttributes = true; 4762 } 4763 } 4764 } 4765 4766 /** 4767 * Returns whether the device is currently in touch mode. Touch mode is entered 4768 * once the user begins interacting with the device by touch, and affects various 4769 * things like whether focus is always visible to the user. 4770 * 4771 * @return Whether the device is in touch mode. 4772 */ 4773 @ViewDebug.ExportedProperty 4774 public boolean isInTouchMode() { 4775 if (mAttachInfo != null) { 4776 return mAttachInfo.mInTouchMode; 4777 } else { 4778 return ViewRoot.isInTouchMode(); 4779 } 4780 } 4781 4782 /** 4783 * Returns the context the view is running in, through which it can 4784 * access the current theme, resources, etc. 4785 * 4786 * @return The view's Context. 4787 */ 4788 @ViewDebug.CapturedViewProperty 4789 public final Context getContext() { 4790 return mContext; 4791 } 4792 4793 /** 4794 * Handle a key event before it is processed by any input method 4795 * associated with the view hierarchy. This can be used to intercept 4796 * key events in special situations before the IME consumes them; a 4797 * typical example would be handling the BACK key to update the application's 4798 * UI instead of allowing the IME to see it and close itself. 4799 * 4800 * @param keyCode The value in event.getKeyCode(). 4801 * @param event Description of the key event. 4802 * @return If you handled the event, return true. If you want to allow the 4803 * event to be handled by the next receiver, return false. 4804 */ 4805 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 4806 return false; 4807 } 4808 4809 /** 4810 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 4811 * KeyEvent.Callback.onKeyDown()}: perform press of the view 4812 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 4813 * is released, if the view is enabled and clickable. 4814 * 4815 * @param keyCode A key code that represents the button pressed, from 4816 * {@link android.view.KeyEvent}. 4817 * @param event The KeyEvent object that defines the button action. 4818 */ 4819 public boolean onKeyDown(int keyCode, KeyEvent event) { 4820 boolean result = false; 4821 4822 switch (keyCode) { 4823 case KeyEvent.KEYCODE_DPAD_CENTER: 4824 case KeyEvent.KEYCODE_ENTER: { 4825 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 4826 return true; 4827 } 4828 // Long clickable items don't necessarily have to be clickable 4829 if (((mViewFlags & CLICKABLE) == CLICKABLE || 4830 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 4831 (event.getRepeatCount() == 0)) { 4832 setPressed(true); 4833 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 4834 postCheckForLongClick(0); 4835 } 4836 return true; 4837 } 4838 break; 4839 } 4840 } 4841 return result; 4842 } 4843 4844 /** 4845 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 4846 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 4847 * the event). 4848 */ 4849 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 4850 return false; 4851 } 4852 4853 /** 4854 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 4855 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 4856 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 4857 * {@link KeyEvent#KEYCODE_ENTER} is released. 4858 * 4859 * @param keyCode A key code that represents the button pressed, from 4860 * {@link android.view.KeyEvent}. 4861 * @param event The KeyEvent object that defines the button action. 4862 */ 4863 public boolean onKeyUp(int keyCode, KeyEvent event) { 4864 boolean result = false; 4865 4866 switch (keyCode) { 4867 case KeyEvent.KEYCODE_DPAD_CENTER: 4868 case KeyEvent.KEYCODE_ENTER: { 4869 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 4870 return true; 4871 } 4872 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 4873 setPressed(false); 4874 4875 if (!mHasPerformedLongPress) { 4876 // This is a tap, so remove the longpress check 4877 removeLongPressCallback(); 4878 4879 result = performClick(); 4880 } 4881 } 4882 break; 4883 } 4884 } 4885 return result; 4886 } 4887 4888 /** 4889 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 4890 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 4891 * the event). 4892 * 4893 * @param keyCode A key code that represents the button pressed, from 4894 * {@link android.view.KeyEvent}. 4895 * @param repeatCount The number of times the action was made. 4896 * @param event The KeyEvent object that defines the button action. 4897 */ 4898 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 4899 return false; 4900 } 4901 4902 /** 4903 * Called on the focused view when a key shortcut event is not handled. 4904 * Override this method to implement local key shortcuts for the View. 4905 * Key shortcuts can also be implemented by setting the 4906 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 4907 * 4908 * @param keyCode The value in event.getKeyCode(). 4909 * @param event Description of the key event. 4910 * @return If you handled the event, return true. If you want to allow the 4911 * event to be handled by the next receiver, return false. 4912 */ 4913 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 4914 return false; 4915 } 4916 4917 /** 4918 * Check whether the called view is a text editor, in which case it 4919 * would make sense to automatically display a soft input window for 4920 * it. Subclasses should override this if they implement 4921 * {@link #onCreateInputConnection(EditorInfo)} to return true if 4922 * a call on that method would return a non-null InputConnection, and 4923 * they are really a first-class editor that the user would normally 4924 * start typing on when the go into a window containing your view. 4925 * 4926 * <p>The default implementation always returns false. This does 4927 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 4928 * will not be called or the user can not otherwise perform edits on your 4929 * view; it is just a hint to the system that this is not the primary 4930 * purpose of this view. 4931 * 4932 * @return Returns true if this view is a text editor, else false. 4933 */ 4934 public boolean onCheckIsTextEditor() { 4935 return false; 4936 } 4937 4938 /** 4939 * Create a new InputConnection for an InputMethod to interact 4940 * with the view. The default implementation returns null, since it doesn't 4941 * support input methods. You can override this to implement such support. 4942 * This is only needed for views that take focus and text input. 4943 * 4944 * <p>When implementing this, you probably also want to implement 4945 * {@link #onCheckIsTextEditor()} to indicate you will return a 4946 * non-null InputConnection. 4947 * 4948 * @param outAttrs Fill in with attribute information about the connection. 4949 */ 4950 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 4951 return null; 4952 } 4953 4954 /** 4955 * Called by the {@link android.view.inputmethod.InputMethodManager} 4956 * when a view who is not the current 4957 * input connection target is trying to make a call on the manager. The 4958 * default implementation returns false; you can override this to return 4959 * true for certain views if you are performing InputConnection proxying 4960 * to them. 4961 * @param view The View that is making the InputMethodManager call. 4962 * @return Return true to allow the call, false to reject. 4963 */ 4964 public boolean checkInputConnectionProxy(View view) { 4965 return false; 4966 } 4967 4968 /** 4969 * Show the context menu for this view. It is not safe to hold on to the 4970 * menu after returning from this method. 4971 * 4972 * You should normally not overload this method. Overload 4973 * {@link #onCreateContextMenu(ContextMenu)} or define an 4974 * {@link OnCreateContextMenuListener} to add items to the context menu. 4975 * 4976 * @param menu The context menu to populate 4977 */ 4978 public void createContextMenu(ContextMenu menu) { 4979 ContextMenuInfo menuInfo = getContextMenuInfo(); 4980 4981 // Sets the current menu info so all items added to menu will have 4982 // my extra info set. 4983 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 4984 4985 onCreateContextMenu(menu); 4986 if (mOnCreateContextMenuListener != null) { 4987 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 4988 } 4989 4990 // Clear the extra information so subsequent items that aren't mine don't 4991 // have my extra info. 4992 ((MenuBuilder)menu).setCurrentMenuInfo(null); 4993 4994 if (mParent != null) { 4995 mParent.createContextMenu(menu); 4996 } 4997 } 4998 4999 /** 5000 * Views should implement this if they have extra information to associate 5001 * with the context menu. The return result is supplied as a parameter to 5002 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 5003 * callback. 5004 * 5005 * @return Extra information about the item for which the context menu 5006 * should be shown. This information will vary across different 5007 * subclasses of View. 5008 */ 5009 protected ContextMenuInfo getContextMenuInfo() { 5010 return null; 5011 } 5012 5013 /** 5014 * Views should implement this if the view itself is going to add items to 5015 * the context menu. 5016 * 5017 * @param menu the context menu to populate 5018 */ 5019 protected void onCreateContextMenu(ContextMenu menu) { 5020 } 5021 5022 /** 5023 * Implement this method to handle trackball motion events. The 5024 * <em>relative</em> movement of the trackball since the last event 5025 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 5026 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 5027 * that a movement of 1 corresponds to the user pressing one DPAD key (so 5028 * they will often be fractional values, representing the more fine-grained 5029 * movement information available from a trackball). 5030 * 5031 * @param event The motion event. 5032 * @return True if the event was handled, false otherwise. 5033 */ 5034 public boolean onTrackballEvent(MotionEvent event) { 5035 return false; 5036 } 5037 5038 /** 5039 * Implement this method to handle touch screen motion events. 5040 * 5041 * @param event The motion event. 5042 * @return True if the event was handled, false otherwise. 5043 */ 5044 public boolean onTouchEvent(MotionEvent event) { 5045 final int viewFlags = mViewFlags; 5046 5047 if ((viewFlags & ENABLED_MASK) == DISABLED) { 5048 // A disabled view that is clickable still consumes the touch 5049 // events, it just doesn't respond to them. 5050 return (((viewFlags & CLICKABLE) == CLICKABLE || 5051 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 5052 } 5053 5054 if (mTouchDelegate != null) { 5055 if (mTouchDelegate.onTouchEvent(event)) { 5056 return true; 5057 } 5058 } 5059 5060 if (((viewFlags & CLICKABLE) == CLICKABLE || 5061 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 5062 switch (event.getAction()) { 5063 case MotionEvent.ACTION_UP: 5064 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; 5065 if ((mPrivateFlags & PRESSED) != 0 || prepressed) { 5066 // take focus if we don't have it already and we should in 5067 // touch mode. 5068 boolean focusTaken = false; 5069 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 5070 focusTaken = requestFocus(); 5071 } 5072 5073 if (prepressed) { 5074 // The button is being released before we actually 5075 // showed it as pressed. Make it show the pressed 5076 // state now (before scheduling the click) to ensure 5077 // the user sees it. 5078 mPrivateFlags |= PRESSED; 5079 refreshDrawableState(); 5080 } 5081 5082 if (!mHasPerformedLongPress) { 5083 // This is a tap, so remove the longpress check 5084 removeLongPressCallback(); 5085 5086 // Only perform take click actions if we were in the pressed state 5087 if (!focusTaken) { 5088 // Use a Runnable and post this rather than calling 5089 // performClick directly. This lets other visual state 5090 // of the view update before click actions start. 5091 if (mPerformClick == null) { 5092 mPerformClick = new PerformClick(); 5093 } 5094 if (!post(mPerformClick)) { 5095 performClick(); 5096 } 5097 } 5098 } 5099 5100 if (mUnsetPressedState == null) { 5101 mUnsetPressedState = new UnsetPressedState(); 5102 } 5103 5104 if (prepressed) { 5105 postDelayed(mUnsetPressedState, 5106 ViewConfiguration.getPressedStateDuration()); 5107 } else if (!post(mUnsetPressedState)) { 5108 // If the post failed, unpress right now 5109 mUnsetPressedState.run(); 5110 } 5111 removeTapCallback(); 5112 } 5113 break; 5114 5115 case MotionEvent.ACTION_DOWN: 5116 if (mPendingCheckForTap == null) { 5117 mPendingCheckForTap = new CheckForTap(); 5118 } 5119 mPrivateFlags |= PREPRESSED; 5120 mHasPerformedLongPress = false; 5121 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 5122 break; 5123 5124 case MotionEvent.ACTION_CANCEL: 5125 mPrivateFlags &= ~PRESSED; 5126 refreshDrawableState(); 5127 removeTapCallback(); 5128 break; 5129 5130 case MotionEvent.ACTION_MOVE: 5131 final int x = (int) event.getX(); 5132 final int y = (int) event.getY(); 5133 5134 // Be lenient about moving outside of buttons 5135 if (!pointInView(x, y, mTouchSlop)) { 5136 // Outside button 5137 removeTapCallback(); 5138 if ((mPrivateFlags & PRESSED) != 0) { 5139 // Remove any future long press/tap checks 5140 removeLongPressCallback(); 5141 5142 // Need to switch from pressed to not pressed 5143 mPrivateFlags &= ~PRESSED; 5144 refreshDrawableState(); 5145 } 5146 } 5147 break; 5148 } 5149 return true; 5150 } 5151 5152 return false; 5153 } 5154 5155 /** 5156 * Remove the longpress detection timer. 5157 */ 5158 private void removeLongPressCallback() { 5159 if (mPendingCheckForLongPress != null) { 5160 removeCallbacks(mPendingCheckForLongPress); 5161 } 5162 } 5163 5164 /** 5165 * Remove the pending click action 5166 */ 5167 private void removePerformClickCallback() { 5168 if (mPerformClick != null) { 5169 removeCallbacks(mPerformClick); 5170 } 5171 } 5172 5173 /** 5174 * Remove the prepress detection timer. 5175 */ 5176 private void removeUnsetPressCallback() { 5177 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) { 5178 setPressed(false); 5179 removeCallbacks(mUnsetPressedState); 5180 } 5181 } 5182 5183 /** 5184 * Remove the tap detection timer. 5185 */ 5186 private void removeTapCallback() { 5187 if (mPendingCheckForTap != null) { 5188 mPrivateFlags &= ~PREPRESSED; 5189 removeCallbacks(mPendingCheckForTap); 5190 } 5191 } 5192 5193 /** 5194 * Cancels a pending long press. Your subclass can use this if you 5195 * want the context menu to come up if the user presses and holds 5196 * at the same place, but you don't want it to come up if they press 5197 * and then move around enough to cause scrolling. 5198 */ 5199 public void cancelLongPress() { 5200 removeLongPressCallback(); 5201 5202 /* 5203 * The prepressed state handled by the tap callback is a display 5204 * construct, but the tap callback will post a long press callback 5205 * less its own timeout. Remove it here. 5206 */ 5207 removeTapCallback(); 5208 } 5209 5210 /** 5211 * Sets the TouchDelegate for this View. 5212 */ 5213 public void setTouchDelegate(TouchDelegate delegate) { 5214 mTouchDelegate = delegate; 5215 } 5216 5217 /** 5218 * Gets the TouchDelegate for this View. 5219 */ 5220 public TouchDelegate getTouchDelegate() { 5221 return mTouchDelegate; 5222 } 5223 5224 /** 5225 * Set flags controlling behavior of this view. 5226 * 5227 * @param flags Constant indicating the value which should be set 5228 * @param mask Constant indicating the bit range that should be changed 5229 */ 5230 void setFlags(int flags, int mask) { 5231 int old = mViewFlags; 5232 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 5233 5234 int changed = mViewFlags ^ old; 5235 if (changed == 0) { 5236 return; 5237 } 5238 int privateFlags = mPrivateFlags; 5239 5240 /* Check if the FOCUSABLE bit has changed */ 5241 if (((changed & FOCUSABLE_MASK) != 0) && 5242 ((privateFlags & HAS_BOUNDS) !=0)) { 5243 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 5244 && ((privateFlags & FOCUSED) != 0)) { 5245 /* Give up focus if we are no longer focusable */ 5246 clearFocus(); 5247 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 5248 && ((privateFlags & FOCUSED) == 0)) { 5249 /* 5250 * Tell the view system that we are now available to take focus 5251 * if no one else already has it. 5252 */ 5253 if (mParent != null) mParent.focusableViewAvailable(this); 5254 } 5255 } 5256 5257 if ((flags & VISIBILITY_MASK) == VISIBLE) { 5258 if ((changed & VISIBILITY_MASK) != 0) { 5259 /* 5260 * If this view is becoming visible, set the DRAWN flag so that 5261 * the next invalidate() will not be skipped. 5262 */ 5263 mPrivateFlags |= DRAWN; 5264 5265 needGlobalAttributesUpdate(true); 5266 5267 // a view becoming visible is worth notifying the parent 5268 // about in case nothing has focus. even if this specific view 5269 // isn't focusable, it may contain something that is, so let 5270 // the root view try to give this focus if nothing else does. 5271 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 5272 mParent.focusableViewAvailable(this); 5273 } 5274 } 5275 } 5276 5277 /* Check if the GONE bit has changed */ 5278 if ((changed & GONE) != 0) { 5279 needGlobalAttributesUpdate(false); 5280 requestLayout(); 5281 invalidate(true); 5282 5283 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 5284 if (hasFocus()) clearFocus(); 5285 destroyDrawingCache(); 5286 } 5287 if (mAttachInfo != null) { 5288 mAttachInfo.mViewVisibilityChanged = true; 5289 } 5290 } 5291 5292 /* Check if the VISIBLE bit has changed */ 5293 if ((changed & INVISIBLE) != 0) { 5294 needGlobalAttributesUpdate(false); 5295 invalidate(true); 5296 5297 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 5298 // root view becoming invisible shouldn't clear focus 5299 if (getRootView() != this) { 5300 clearFocus(); 5301 } 5302 } 5303 if (mAttachInfo != null) { 5304 mAttachInfo.mViewVisibilityChanged = true; 5305 } 5306 } 5307 5308 if ((changed & VISIBILITY_MASK) != 0) { 5309 if (mParent instanceof ViewGroup) { 5310 ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK)); 5311 ((View) mParent).invalidate(true); 5312 } 5313 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 5314 } 5315 5316 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 5317 destroyDrawingCache(); 5318 } 5319 5320 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 5321 destroyDrawingCache(); 5322 mPrivateFlags &= ~DRAWING_CACHE_VALID; 5323 invalidateParentCaches(); 5324 } 5325 5326 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 5327 destroyDrawingCache(); 5328 mPrivateFlags &= ~DRAWING_CACHE_VALID; 5329 } 5330 5331 if ((changed & DRAW_MASK) != 0) { 5332 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 5333 if (mBGDrawable != null) { 5334 mPrivateFlags &= ~SKIP_DRAW; 5335 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 5336 } else { 5337 mPrivateFlags |= SKIP_DRAW; 5338 } 5339 } else { 5340 mPrivateFlags &= ~SKIP_DRAW; 5341 } 5342 requestLayout(); 5343 invalidate(true); 5344 } 5345 5346 if ((changed & KEEP_SCREEN_ON) != 0) { 5347 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 5348 mParent.recomputeViewAttributes(this); 5349 } 5350 } 5351 } 5352 5353 /** 5354 * Change the view's z order in the tree, so it's on top of other sibling 5355 * views 5356 */ 5357 public void bringToFront() { 5358 if (mParent != null) { 5359 mParent.bringChildToFront(this); 5360 } 5361 } 5362 5363 /** 5364 * This is called in response to an internal scroll in this view (i.e., the 5365 * view scrolled its own contents). This is typically as a result of 5366 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 5367 * called. 5368 * 5369 * @param l Current horizontal scroll origin. 5370 * @param t Current vertical scroll origin. 5371 * @param oldl Previous horizontal scroll origin. 5372 * @param oldt Previous vertical scroll origin. 5373 */ 5374 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 5375 mBackgroundSizeChanged = true; 5376 5377 final AttachInfo ai = mAttachInfo; 5378 if (ai != null) { 5379 ai.mViewScrollChanged = true; 5380 } 5381 } 5382 5383 /** 5384 * Interface definition for a callback to be invoked when the layout bounds of a view 5385 * changes due to layout processing. 5386 */ 5387 public interface OnLayoutChangeListener { 5388 /** 5389 * Called when the focus state of a view has changed. 5390 * 5391 * @param v The view whose state has changed. 5392 * @param left The new value of the view's left property. 5393 * @param top The new value of the view's top property. 5394 * @param right The new value of the view's right property. 5395 * @param bottom The new value of the view's bottom property. 5396 * @param oldLeft The previous value of the view's left property. 5397 * @param oldTop The previous value of the view's top property. 5398 * @param oldRight The previous value of the view's right property. 5399 * @param oldBottom The previous value of the view's bottom property. 5400 */ 5401 void onLayoutChange(View v, int left, int top, int right, int bottom, 5402 int oldLeft, int oldTop, int oldRight, int oldBottom); 5403 } 5404 5405 /** 5406 * This is called during layout when the size of this view has changed. If 5407 * you were just added to the view hierarchy, you're called with the old 5408 * values of 0. 5409 * 5410 * @param w Current width of this view. 5411 * @param h Current height of this view. 5412 * @param oldw Old width of this view. 5413 * @param oldh Old height of this view. 5414 */ 5415 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 5416 } 5417 5418 /** 5419 * Called by draw to draw the child views. This may be overridden 5420 * by derived classes to gain control just before its children are drawn 5421 * (but after its own view has been drawn). 5422 * @param canvas the canvas on which to draw the view 5423 */ 5424 protected void dispatchDraw(Canvas canvas) { 5425 } 5426 5427 /** 5428 * Gets the parent of this view. Note that the parent is a 5429 * ViewParent and not necessarily a View. 5430 * 5431 * @return Parent of this view. 5432 */ 5433 public final ViewParent getParent() { 5434 return mParent; 5435 } 5436 5437 /** 5438 * Return the scrolled left position of this view. This is the left edge of 5439 * the displayed part of your view. You do not need to draw any pixels 5440 * farther left, since those are outside of the frame of your view on 5441 * screen. 5442 * 5443 * @return The left edge of the displayed part of your view, in pixels. 5444 */ 5445 public final int getScrollX() { 5446 return mScrollX; 5447 } 5448 5449 /** 5450 * Return the scrolled top position of this view. This is the top edge of 5451 * the displayed part of your view. You do not need to draw any pixels above 5452 * it, since those are outside of the frame of your view on screen. 5453 * 5454 * @return The top edge of the displayed part of your view, in pixels. 5455 */ 5456 public final int getScrollY() { 5457 return mScrollY; 5458 } 5459 5460 /** 5461 * Return the width of the your view. 5462 * 5463 * @return The width of your view, in pixels. 5464 */ 5465 @ViewDebug.ExportedProperty(category = "layout") 5466 public final int getWidth() { 5467 return mRight - mLeft; 5468 } 5469 5470 /** 5471 * Return the height of your view. 5472 * 5473 * @return The height of your view, in pixels. 5474 */ 5475 @ViewDebug.ExportedProperty(category = "layout") 5476 public final int getHeight() { 5477 return mBottom - mTop; 5478 } 5479 5480 /** 5481 * Return the visible drawing bounds of your view. Fills in the output 5482 * rectangle with the values from getScrollX(), getScrollY(), 5483 * getWidth(), and getHeight(). 5484 * 5485 * @param outRect The (scrolled) drawing bounds of the view. 5486 */ 5487 public void getDrawingRect(Rect outRect) { 5488 outRect.left = mScrollX; 5489 outRect.top = mScrollY; 5490 outRect.right = mScrollX + (mRight - mLeft); 5491 outRect.bottom = mScrollY + (mBottom - mTop); 5492 } 5493 5494 /** 5495 * Like {@link #getMeasuredWidthAndState()}, but only returns the 5496 * raw width component (that is the result is masked by 5497 * {@link #MEASURED_SIZE_MASK}). 5498 * 5499 * @return The raw measured width of this view. 5500 */ 5501 public final int getMeasuredWidth() { 5502 return mMeasuredWidth & MEASURED_SIZE_MASK; 5503 } 5504 5505 /** 5506 * Return the full width measurement information for this view as computed 5507 * by the most recent call to {@link #measure}. This result is a bit mask 5508 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 5509 * This should be used during measurement and layout calculations only. Use 5510 * {@link #getWidth()} to see how wide a view is after layout. 5511 * 5512 * @return The measured width of this view as a bit mask. 5513 */ 5514 public final int getMeasuredWidthAndState() { 5515 return mMeasuredWidth; 5516 } 5517 5518 /** 5519 * Like {@link #getMeasuredHeightAndState()}, but only returns the 5520 * raw width component (that is the result is masked by 5521 * {@link #MEASURED_SIZE_MASK}). 5522 * 5523 * @return The raw measured height of this view. 5524 */ 5525 public final int getMeasuredHeight() { 5526 return mMeasuredHeight & MEASURED_SIZE_MASK; 5527 } 5528 5529 /** 5530 * Return the full height measurement information for this view as computed 5531 * by the most recent call to {@link #measure}. This result is a bit mask 5532 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 5533 * This should be used during measurement and layout calculations only. Use 5534 * {@link #getHeight()} to see how wide a view is after layout. 5535 * 5536 * @return The measured width of this view as a bit mask. 5537 */ 5538 public final int getMeasuredHeightAndState() { 5539 return mMeasuredHeight; 5540 } 5541 5542 /** 5543 * Return only the state bits of {@link #getMeasuredWidthAndState()} 5544 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 5545 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 5546 * and the height component is at the shifted bits 5547 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 5548 */ 5549 public final int getMeasuredState() { 5550 return (mMeasuredWidth&MEASURED_STATE_MASK) 5551 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 5552 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 5553 } 5554 5555 /** 5556 * The transform matrix of this view, which is calculated based on the current 5557 * roation, scale, and pivot properties. 5558 * 5559 * @see #getRotation() 5560 * @see #getScaleX() 5561 * @see #getScaleY() 5562 * @see #getPivotX() 5563 * @see #getPivotY() 5564 * @return The current transform matrix for the view 5565 */ 5566 public Matrix getMatrix() { 5567 updateMatrix(); 5568 return mMatrix; 5569 } 5570 5571 /** 5572 * Utility function to determine if the value is far enough away from zero to be 5573 * considered non-zero. 5574 * @param value A floating point value to check for zero-ness 5575 * @return whether the passed-in value is far enough away from zero to be considered non-zero 5576 */ 5577 private static boolean nonzero(float value) { 5578 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 5579 } 5580 5581 /** 5582 * Returns true if the transform matrix is the identity matrix. 5583 * Recomputes the matrix if necessary. 5584 * 5585 * @return True if the transform matrix is the identity matrix, false otherwise. 5586 */ 5587 final boolean hasIdentityMatrix() { 5588 updateMatrix(); 5589 return mMatrixIsIdentity; 5590 } 5591 5592 /** 5593 * Recomputes the transform matrix if necessary. 5594 */ 5595 private void updateMatrix() { 5596 if (mMatrixDirty) { 5597 // transform-related properties have changed since the last time someone 5598 // asked for the matrix; recalculate it with the current values 5599 5600 // Figure out if we need to update the pivot point 5601 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 5602 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) { 5603 mPrevWidth = mRight - mLeft; 5604 mPrevHeight = mBottom - mTop; 5605 mPivotX = mPrevWidth / 2f; 5606 mPivotY = mPrevHeight / 2f; 5607 } 5608 } 5609 mMatrix.reset(); 5610 if (!nonzero(mRotationX) && !nonzero(mRotationY)) { 5611 mMatrix.setTranslate(mTranslationX, mTranslationY); 5612 mMatrix.preRotate(mRotation, mPivotX, mPivotY); 5613 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY); 5614 } else { 5615 if (mCamera == null) { 5616 mCamera = new Camera(); 5617 matrix3D = new Matrix(); 5618 } 5619 mCamera.save(); 5620 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY); 5621 mCamera.rotateX(mRotationX); 5622 mCamera.rotateY(mRotationY); 5623 mCamera.rotateZ(-mRotation); 5624 mCamera.getMatrix(matrix3D); 5625 matrix3D.preTranslate(-mPivotX, -mPivotY); 5626 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY); 5627 mMatrix.postConcat(matrix3D); 5628 mCamera.restore(); 5629 } 5630 mMatrixDirty = false; 5631 mMatrixIsIdentity = mMatrix.isIdentity(); 5632 mInverseMatrixDirty = true; 5633 } 5634 } 5635 5636 /** 5637 * Utility method to retrieve the inverse of the current mMatrix property. 5638 * We cache the matrix to avoid recalculating it when transform properties 5639 * have not changed. 5640 * 5641 * @return The inverse of the current matrix of this view. 5642 */ 5643 final Matrix getInverseMatrix() { 5644 updateMatrix(); 5645 if (mInverseMatrixDirty) { 5646 if (mInverseMatrix == null) { 5647 mInverseMatrix = new Matrix(); 5648 } 5649 mMatrix.invert(mInverseMatrix); 5650 mInverseMatrixDirty = false; 5651 } 5652 return mInverseMatrix; 5653 } 5654 5655 /** 5656 * The degrees that the view is rotated around the pivot point. 5657 * 5658 * @see #getPivotX() 5659 * @see #getPivotY() 5660 * @return The degrees of rotation. 5661 */ 5662 public float getRotation() { 5663 return mRotation; 5664 } 5665 5666 /** 5667 * Sets the degrees that the view is rotated around the pivot point. Increasing values 5668 * result in clockwise rotation. 5669 * 5670 * @param rotation The degrees of rotation. 5671 * @see #getPivotX() 5672 * @see #getPivotY() 5673 * 5674 * @attr ref android.R.styleable#View_rotation 5675 */ 5676 public void setRotation(float rotation) { 5677 if (mRotation != rotation) { 5678 invalidateParentCaches(); 5679 // Double-invalidation is necessary to capture view's old and new areas 5680 invalidate(false); 5681 mRotation = rotation; 5682 mMatrixDirty = true; 5683 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 5684 invalidate(false); 5685 } 5686 } 5687 5688 /** 5689 * The degrees that the view is rotated around the vertical axis through the pivot point. 5690 * 5691 * @see #getPivotX() 5692 * @see #getPivotY() 5693 * @return The degrees of Y rotation. 5694 */ 5695 public float getRotationY() { 5696 return mRotationY; 5697 } 5698 5699 /** 5700 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 5701 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 5702 * down the y axis. 5703 * 5704 * @param rotationY The degrees of Y rotation. 5705 * @see #getPivotX() 5706 * @see #getPivotY() 5707 * 5708 * @attr ref android.R.styleable#View_rotationY 5709 */ 5710 public void setRotationY(float rotationY) { 5711 if (mRotationY != rotationY) { 5712 invalidateParentCaches(); 5713 // Double-invalidation is necessary to capture view's old and new areas 5714 invalidate(false); 5715 mRotationY = rotationY; 5716 mMatrixDirty = true; 5717 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 5718 invalidate(false); 5719 } 5720 } 5721 5722 /** 5723 * The degrees that the view is rotated around the horizontal axis through the pivot point. 5724 * 5725 * @see #getPivotX() 5726 * @see #getPivotY() 5727 * @return The degrees of X rotation. 5728 */ 5729 public float getRotationX() { 5730 return mRotationX; 5731 } 5732 5733 /** 5734 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 5735 * Increasing values result in clockwise rotation from the viewpoint of looking down the 5736 * x axis. 5737 * 5738 * @param rotationX The degrees of X rotation. 5739 * @see #getPivotX() 5740 * @see #getPivotY() 5741 * 5742 * @attr ref android.R.styleable#View_rotationX 5743 */ 5744 public void setRotationX(float rotationX) { 5745 if (mRotationX != rotationX) { 5746 invalidateParentCaches(); 5747 // Double-invalidation is necessary to capture view's old and new areas 5748 invalidate(false); 5749 mRotationX = rotationX; 5750 mMatrixDirty = true; 5751 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 5752 invalidate(false); 5753 } 5754 } 5755 5756 /** 5757 * The amount that the view is scaled in x around the pivot point, as a proportion of 5758 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 5759 * 5760 * <p>By default, this is 1.0f. 5761 * 5762 * @see #getPivotX() 5763 * @see #getPivotY() 5764 * @return The scaling factor. 5765 */ 5766 public float getScaleX() { 5767 return mScaleX; 5768 } 5769 5770 /** 5771 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 5772 * the view's unscaled width. A value of 1 means that no scaling is applied. 5773 * 5774 * @param scaleX The scaling factor. 5775 * @see #getPivotX() 5776 * @see #getPivotY() 5777 * 5778 * @attr ref android.R.styleable#View_scaleX 5779 */ 5780 public void setScaleX(float scaleX) { 5781 if (mScaleX != scaleX) { 5782 invalidateParentCaches(); 5783 // Double-invalidation is necessary to capture view's old and new areas 5784 invalidate(false); 5785 mScaleX = scaleX; 5786 mMatrixDirty = true; 5787 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 5788 invalidate(false); 5789 } 5790 } 5791 5792 /** 5793 * The amount that the view is scaled in y around the pivot point, as a proportion of 5794 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 5795 * 5796 * <p>By default, this is 1.0f. 5797 * 5798 * @see #getPivotX() 5799 * @see #getPivotY() 5800 * @return The scaling factor. 5801 */ 5802 public float getScaleY() { 5803 return mScaleY; 5804 } 5805 5806 /** 5807 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 5808 * the view's unscaled width. A value of 1 means that no scaling is applied. 5809 * 5810 * @param scaleY The scaling factor. 5811 * @see #getPivotX() 5812 * @see #getPivotY() 5813 * 5814 * @attr ref android.R.styleable#View_scaleY 5815 */ 5816 public void setScaleY(float scaleY) { 5817 if (mScaleY != scaleY) { 5818 invalidateParentCaches(); 5819 // Double-invalidation is necessary to capture view's old and new areas 5820 invalidate(false); 5821 mScaleY = scaleY; 5822 mMatrixDirty = true; 5823 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 5824 invalidate(false); 5825 } 5826 } 5827 5828 /** 5829 * The x location of the point around which the view is {@link #setRotation(float) rotated} 5830 * and {@link #setScaleX(float) scaled}. 5831 * 5832 * @see #getRotation() 5833 * @see #getScaleX() 5834 * @see #getScaleY() 5835 * @see #getPivotY() 5836 * @return The x location of the pivot point. 5837 */ 5838 public float getPivotX() { 5839 return mPivotX; 5840 } 5841 5842 /** 5843 * Sets the x location of the point around which the view is 5844 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 5845 * By default, the pivot point is centered on the object. 5846 * Setting this property disables this behavior and causes the view to use only the 5847 * explicitly set pivotX and pivotY values. 5848 * 5849 * @param pivotX The x location of the pivot point. 5850 * @see #getRotation() 5851 * @see #getScaleX() 5852 * @see #getScaleY() 5853 * @see #getPivotY() 5854 * 5855 * @attr ref android.R.styleable#View_transformPivotX 5856 */ 5857 public void setPivotX(float pivotX) { 5858 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 5859 if (mPivotX != pivotX) { 5860 invalidateParentCaches(); 5861 // Double-invalidation is necessary to capture view's old and new areas 5862 invalidate(false); 5863 mPivotX = pivotX; 5864 mMatrixDirty = true; 5865 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 5866 invalidate(false); 5867 } 5868 } 5869 5870 /** 5871 * The y location of the point around which the view is {@link #setRotation(float) rotated} 5872 * and {@link #setScaleY(float) scaled}. 5873 * 5874 * @see #getRotation() 5875 * @see #getScaleX() 5876 * @see #getScaleY() 5877 * @see #getPivotY() 5878 * @return The y location of the pivot point. 5879 */ 5880 public float getPivotY() { 5881 return mPivotY; 5882 } 5883 5884 /** 5885 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 5886 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 5887 * Setting this property disables this behavior and causes the view to use only the 5888 * explicitly set pivotX and pivotY values. 5889 * 5890 * @param pivotY The y location of the pivot point. 5891 * @see #getRotation() 5892 * @see #getScaleX() 5893 * @see #getScaleY() 5894 * @see #getPivotY() 5895 * 5896 * @attr ref android.R.styleable#View_transformPivotY 5897 */ 5898 public void setPivotY(float pivotY) { 5899 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 5900 if (mPivotY != pivotY) { 5901 invalidateParentCaches(); 5902 // Double-invalidation is necessary to capture view's old and new areas 5903 invalidate(false); 5904 mPivotY = pivotY; 5905 mMatrixDirty = true; 5906 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 5907 invalidate(false); 5908 } 5909 } 5910 5911 /** 5912 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 5913 * completely transparent and 1 means the view is completely opaque. 5914 * 5915 * <p>By default this is 1.0f. 5916 * @return The opacity of the view. 5917 */ 5918 public float getAlpha() { 5919 return mAlpha; 5920 } 5921 5922 /** 5923 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 5924 * completely transparent and 1 means the view is completely opaque.</p> 5925 * 5926 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 5927 * responsible for applying the opacity itself. Otherwise, calling this method is 5928 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 5929 * setting a hardware layer.</p> 5930 * 5931 * @param alpha The opacity of the view. 5932 * 5933 * @see #setLayerType(int, android.graphics.Paint) 5934 * 5935 * @attr ref android.R.styleable#View_alpha 5936 */ 5937 public void setAlpha(float alpha) { 5938 mAlpha = alpha; 5939 invalidateParentCaches(); 5940 if (onSetAlpha((int) (alpha * 255))) { 5941 mPrivateFlags |= ALPHA_SET; 5942 // subclass is handling alpha - don't optimize rendering cache invalidation 5943 invalidate(true); 5944 } else { 5945 mPrivateFlags &= ~ALPHA_SET; 5946 invalidate(false); 5947 } 5948 } 5949 5950 /** 5951 * Top position of this view relative to its parent. 5952 * 5953 * @return The top of this view, in pixels. 5954 */ 5955 @ViewDebug.CapturedViewProperty 5956 public final int getTop() { 5957 return mTop; 5958 } 5959 5960 /** 5961 * Sets the top position of this view relative to its parent. This method is meant to be called 5962 * by the layout system and should not generally be called otherwise, because the property 5963 * may be changed at any time by the layout. 5964 * 5965 * @param top The top of this view, in pixels. 5966 */ 5967 public final void setTop(int top) { 5968 if (top != mTop) { 5969 updateMatrix(); 5970 if (mMatrixIsIdentity) { 5971 final ViewParent p = mParent; 5972 if (p != null && mAttachInfo != null) { 5973 final Rect r = mAttachInfo.mTmpInvalRect; 5974 int minTop; 5975 int yLoc; 5976 if (top < mTop) { 5977 minTop = top; 5978 yLoc = top - mTop; 5979 } else { 5980 minTop = mTop; 5981 yLoc = 0; 5982 } 5983 r.set(0, yLoc, mRight - mLeft, mBottom - minTop); 5984 p.invalidateChild(this, r); 5985 } 5986 } else { 5987 // Double-invalidation is necessary to capture view's old and new areas 5988 invalidate(true); 5989 } 5990 5991 int width = mRight - mLeft; 5992 int oldHeight = mBottom - mTop; 5993 5994 mTop = top; 5995 5996 onSizeChanged(width, mBottom - mTop, width, oldHeight); 5997 5998 if (!mMatrixIsIdentity) { 5999 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6000 // A change in dimension means an auto-centered pivot point changes, too 6001 mMatrixDirty = true; 6002 } 6003 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6004 invalidate(true); 6005 } 6006 mBackgroundSizeChanged = true; 6007 invalidateParentIfNeeded(); 6008 } 6009 } 6010 6011 /** 6012 * Bottom position of this view relative to its parent. 6013 * 6014 * @return The bottom of this view, in pixels. 6015 */ 6016 @ViewDebug.CapturedViewProperty 6017 public final int getBottom() { 6018 return mBottom; 6019 } 6020 6021 /** 6022 * True if this view has changed since the last time being drawn. 6023 * 6024 * @return The dirty state of this view. 6025 */ 6026 public boolean isDirty() { 6027 return (mPrivateFlags & DIRTY_MASK) != 0; 6028 } 6029 6030 /** 6031 * Sets the bottom position of this view relative to its parent. This method is meant to be 6032 * called by the layout system and should not generally be called otherwise, because the 6033 * property may be changed at any time by the layout. 6034 * 6035 * @param bottom The bottom of this view, in pixels. 6036 */ 6037 public final void setBottom(int bottom) { 6038 if (bottom != mBottom) { 6039 updateMatrix(); 6040 if (mMatrixIsIdentity) { 6041 final ViewParent p = mParent; 6042 if (p != null && mAttachInfo != null) { 6043 final Rect r = mAttachInfo.mTmpInvalRect; 6044 int maxBottom; 6045 if (bottom < mBottom) { 6046 maxBottom = mBottom; 6047 } else { 6048 maxBottom = bottom; 6049 } 6050 r.set(0, 0, mRight - mLeft, maxBottom - mTop); 6051 p.invalidateChild(this, r); 6052 } 6053 } else { 6054 // Double-invalidation is necessary to capture view's old and new areas 6055 invalidate(true); 6056 } 6057 6058 int width = mRight - mLeft; 6059 int oldHeight = mBottom - mTop; 6060 6061 mBottom = bottom; 6062 6063 onSizeChanged(width, mBottom - mTop, width, oldHeight); 6064 6065 if (!mMatrixIsIdentity) { 6066 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6067 // A change in dimension means an auto-centered pivot point changes, too 6068 mMatrixDirty = true; 6069 } 6070 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6071 invalidate(true); 6072 } 6073 mBackgroundSizeChanged = true; 6074 invalidateParentIfNeeded(); 6075 } 6076 } 6077 6078 /** 6079 * Left position of this view relative to its parent. 6080 * 6081 * @return The left edge of this view, in pixels. 6082 */ 6083 @ViewDebug.CapturedViewProperty 6084 public final int getLeft() { 6085 return mLeft; 6086 } 6087 6088 /** 6089 * Sets the left position of this view relative to its parent. This method is meant to be called 6090 * by the layout system and should not generally be called otherwise, because the property 6091 * may be changed at any time by the layout. 6092 * 6093 * @param left The bottom of this view, in pixels. 6094 */ 6095 public final void setLeft(int left) { 6096 if (left != mLeft) { 6097 updateMatrix(); 6098 if (mMatrixIsIdentity) { 6099 final ViewParent p = mParent; 6100 if (p != null && mAttachInfo != null) { 6101 final Rect r = mAttachInfo.mTmpInvalRect; 6102 int minLeft; 6103 int xLoc; 6104 if (left < mLeft) { 6105 minLeft = left; 6106 xLoc = left - mLeft; 6107 } else { 6108 minLeft = mLeft; 6109 xLoc = 0; 6110 } 6111 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop); 6112 p.invalidateChild(this, r); 6113 } 6114 } else { 6115 // Double-invalidation is necessary to capture view's old and new areas 6116 invalidate(true); 6117 } 6118 6119 int oldWidth = mRight - mLeft; 6120 int height = mBottom - mTop; 6121 6122 mLeft = left; 6123 6124 onSizeChanged(mRight - mLeft, height, oldWidth, height); 6125 6126 if (!mMatrixIsIdentity) { 6127 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6128 // A change in dimension means an auto-centered pivot point changes, too 6129 mMatrixDirty = true; 6130 } 6131 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6132 invalidate(true); 6133 } 6134 mBackgroundSizeChanged = true; 6135 invalidateParentIfNeeded(); 6136 } 6137 } 6138 6139 /** 6140 * Right position of this view relative to its parent. 6141 * 6142 * @return The right edge of this view, in pixels. 6143 */ 6144 @ViewDebug.CapturedViewProperty 6145 public final int getRight() { 6146 return mRight; 6147 } 6148 6149 /** 6150 * Sets the right position of this view relative to its parent. This method is meant to be called 6151 * by the layout system and should not generally be called otherwise, because the property 6152 * may be changed at any time by the layout. 6153 * 6154 * @param right The bottom of this view, in pixels. 6155 */ 6156 public final void setRight(int right) { 6157 if (right != mRight) { 6158 updateMatrix(); 6159 if (mMatrixIsIdentity) { 6160 final ViewParent p = mParent; 6161 if (p != null && mAttachInfo != null) { 6162 final Rect r = mAttachInfo.mTmpInvalRect; 6163 int maxRight; 6164 if (right < mRight) { 6165 maxRight = mRight; 6166 } else { 6167 maxRight = right; 6168 } 6169 r.set(0, 0, maxRight - mLeft, mBottom - mTop); 6170 p.invalidateChild(this, r); 6171 } 6172 } else { 6173 // Double-invalidation is necessary to capture view's old and new areas 6174 invalidate(true); 6175 } 6176 6177 int oldWidth = mRight - mLeft; 6178 int height = mBottom - mTop; 6179 6180 mRight = right; 6181 6182 onSizeChanged(mRight - mLeft, height, oldWidth, height); 6183 6184 if (!mMatrixIsIdentity) { 6185 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6186 // A change in dimension means an auto-centered pivot point changes, too 6187 mMatrixDirty = true; 6188 } 6189 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6190 invalidate(true); 6191 } 6192 mBackgroundSizeChanged = true; 6193 invalidateParentIfNeeded(); 6194 } 6195 } 6196 6197 /** 6198 * The visual x position of this view, in pixels. This is equivalent to the 6199 * {@link #setTranslationX(float) translationX} property plus the current 6200 * {@link #getLeft() left} property. 6201 * 6202 * @return The visual x position of this view, in pixels. 6203 */ 6204 public float getX() { 6205 return mLeft + mTranslationX; 6206 } 6207 6208 /** 6209 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 6210 * {@link #setTranslationX(float) translationX} property to be the difference between 6211 * the x value passed in and the current {@link #getLeft() left} property. 6212 * 6213 * @param x The visual x position of this view, in pixels. 6214 */ 6215 public void setX(float x) { 6216 setTranslationX(x - mLeft); 6217 } 6218 6219 /** 6220 * The visual y position of this view, in pixels. This is equivalent to the 6221 * {@link #setTranslationY(float) translationY} property plus the current 6222 * {@link #getTop() top} property. 6223 * 6224 * @return The visual y position of this view, in pixels. 6225 */ 6226 public float getY() { 6227 return mTop + mTranslationY; 6228 } 6229 6230 /** 6231 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 6232 * {@link #setTranslationY(float) translationY} property to be the difference between 6233 * the y value passed in and the current {@link #getTop() top} property. 6234 * 6235 * @param y The visual y position of this view, in pixels. 6236 */ 6237 public void setY(float y) { 6238 setTranslationY(y - mTop); 6239 } 6240 6241 6242 /** 6243 * The horizontal location of this view relative to its {@link #getLeft() left} position. 6244 * This position is post-layout, in addition to wherever the object's 6245 * layout placed it. 6246 * 6247 * @return The horizontal position of this view relative to its left position, in pixels. 6248 */ 6249 public float getTranslationX() { 6250 return mTranslationX; 6251 } 6252 6253 /** 6254 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 6255 * This effectively positions the object post-layout, in addition to wherever the object's 6256 * layout placed it. 6257 * 6258 * @param translationX The horizontal position of this view relative to its left position, 6259 * in pixels. 6260 * 6261 * @attr ref android.R.styleable#View_translationX 6262 */ 6263 public void setTranslationX(float translationX) { 6264 if (mTranslationX != translationX) { 6265 invalidateParentCaches(); 6266 // Double-invalidation is necessary to capture view's old and new areas 6267 invalidate(false); 6268 mTranslationX = translationX; 6269 mMatrixDirty = true; 6270 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6271 invalidate(false); 6272 } 6273 } 6274 6275 /** 6276 * The horizontal location of this view relative to its {@link #getTop() top} position. 6277 * This position is post-layout, in addition to wherever the object's 6278 * layout placed it. 6279 * 6280 * @return The vertical position of this view relative to its top position, 6281 * in pixels. 6282 */ 6283 public float getTranslationY() { 6284 return mTranslationY; 6285 } 6286 6287 /** 6288 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 6289 * This effectively positions the object post-layout, in addition to wherever the object's 6290 * layout placed it. 6291 * 6292 * @param translationY The vertical position of this view relative to its top position, 6293 * in pixels. 6294 * 6295 * @attr ref android.R.styleable#View_translationY 6296 */ 6297 public void setTranslationY(float translationY) { 6298 if (mTranslationY != translationY) { 6299 invalidateParentCaches(); 6300 // Double-invalidation is necessary to capture view's old and new areas 6301 invalidate(false); 6302 mTranslationY = translationY; 6303 mMatrixDirty = true; 6304 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6305 invalidate(false); 6306 } 6307 } 6308 6309 /** 6310 * Hit rectangle in parent's coordinates 6311 * 6312 * @param outRect The hit rectangle of the view. 6313 */ 6314 public void getHitRect(Rect outRect) { 6315 updateMatrix(); 6316 if (mMatrixIsIdentity || mAttachInfo == null) { 6317 outRect.set(mLeft, mTop, mRight, mBottom); 6318 } else { 6319 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 6320 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY); 6321 mMatrix.mapRect(tmpRect); 6322 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 6323 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 6324 } 6325 } 6326 6327 /** 6328 * Determines whether the given point, in local coordinates is inside the view. 6329 */ 6330 /*package*/ final boolean pointInView(float localX, float localY) { 6331 return localX >= 0 && localX < (mRight - mLeft) 6332 && localY >= 0 && localY < (mBottom - mTop); 6333 } 6334 6335 /** 6336 * Utility method to determine whether the given point, in local coordinates, 6337 * is inside the view, where the area of the view is expanded by the slop factor. 6338 * This method is called while processing touch-move events to determine if the event 6339 * is still within the view. 6340 */ 6341 private boolean pointInView(float localX, float localY, float slop) { 6342 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 6343 localY < ((mBottom - mTop) + slop); 6344 } 6345 6346 /** 6347 * When a view has focus and the user navigates away from it, the next view is searched for 6348 * starting from the rectangle filled in by this method. 6349 * 6350 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your 6351 * view maintains some idea of internal selection, such as a cursor, or a selected row 6352 * or column, you should override this method and fill in a more specific rectangle. 6353 * 6354 * @param r The rectangle to fill in, in this view's coordinates. 6355 */ 6356 public void getFocusedRect(Rect r) { 6357 getDrawingRect(r); 6358 } 6359 6360 /** 6361 * If some part of this view is not clipped by any of its parents, then 6362 * return that area in r in global (root) coordinates. To convert r to local 6363 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x, 6364 * -globalOffset.y)) If the view is completely clipped or translated out, 6365 * return false. 6366 * 6367 * @param r If true is returned, r holds the global coordinates of the 6368 * visible portion of this view. 6369 * @param globalOffset If true is returned, globalOffset holds the dx,dy 6370 * between this view and its root. globalOffet may be null. 6371 * @return true if r is non-empty (i.e. part of the view is visible at the 6372 * root level. 6373 */ 6374 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 6375 int width = mRight - mLeft; 6376 int height = mBottom - mTop; 6377 if (width > 0 && height > 0) { 6378 r.set(0, 0, width, height); 6379 if (globalOffset != null) { 6380 globalOffset.set(-mScrollX, -mScrollY); 6381 } 6382 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 6383 } 6384 return false; 6385 } 6386 6387 public final boolean getGlobalVisibleRect(Rect r) { 6388 return getGlobalVisibleRect(r, null); 6389 } 6390 6391 public final boolean getLocalVisibleRect(Rect r) { 6392 Point offset = new Point(); 6393 if (getGlobalVisibleRect(r, offset)) { 6394 r.offset(-offset.x, -offset.y); // make r local 6395 return true; 6396 } 6397 return false; 6398 } 6399 6400 /** 6401 * Offset this view's vertical location by the specified number of pixels. 6402 * 6403 * @param offset the number of pixels to offset the view by 6404 */ 6405 public void offsetTopAndBottom(int offset) { 6406 if (offset != 0) { 6407 updateMatrix(); 6408 if (mMatrixIsIdentity) { 6409 final ViewParent p = mParent; 6410 if (p != null && mAttachInfo != null) { 6411 final Rect r = mAttachInfo.mTmpInvalRect; 6412 int minTop; 6413 int maxBottom; 6414 int yLoc; 6415 if (offset < 0) { 6416 minTop = mTop + offset; 6417 maxBottom = mBottom; 6418 yLoc = offset; 6419 } else { 6420 minTop = mTop; 6421 maxBottom = mBottom + offset; 6422 yLoc = 0; 6423 } 6424 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 6425 p.invalidateChild(this, r); 6426 } 6427 } else { 6428 invalidate(false); 6429 } 6430 6431 mTop += offset; 6432 mBottom += offset; 6433 6434 if (!mMatrixIsIdentity) { 6435 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6436 invalidate(false); 6437 } 6438 invalidateParentIfNeeded(); 6439 } 6440 } 6441 6442 /** 6443 * Offset this view's horizontal location by the specified amount of pixels. 6444 * 6445 * @param offset the numer of pixels to offset the view by 6446 */ 6447 public void offsetLeftAndRight(int offset) { 6448 if (offset != 0) { 6449 updateMatrix(); 6450 if (mMatrixIsIdentity) { 6451 final ViewParent p = mParent; 6452 if (p != null && mAttachInfo != null) { 6453 final Rect r = mAttachInfo.mTmpInvalRect; 6454 int minLeft; 6455 int maxRight; 6456 if (offset < 0) { 6457 minLeft = mLeft + offset; 6458 maxRight = mRight; 6459 } else { 6460 minLeft = mLeft; 6461 maxRight = mRight + offset; 6462 } 6463 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 6464 p.invalidateChild(this, r); 6465 } 6466 } else { 6467 invalidate(false); 6468 } 6469 6470 mLeft += offset; 6471 mRight += offset; 6472 6473 if (!mMatrixIsIdentity) { 6474 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6475 invalidate(false); 6476 } 6477 invalidateParentIfNeeded(); 6478 } 6479 } 6480 6481 /** 6482 * Get the LayoutParams associated with this view. All views should have 6483 * layout parameters. These supply parameters to the <i>parent</i> of this 6484 * view specifying how it should be arranged. There are many subclasses of 6485 * ViewGroup.LayoutParams, and these correspond to the different subclasses 6486 * of ViewGroup that are responsible for arranging their children. 6487 * @return The LayoutParams associated with this view 6488 */ 6489 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 6490 public ViewGroup.LayoutParams getLayoutParams() { 6491 return mLayoutParams; 6492 } 6493 6494 /** 6495 * Set the layout parameters associated with this view. These supply 6496 * parameters to the <i>parent</i> of this view specifying how it should be 6497 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 6498 * correspond to the different subclasses of ViewGroup that are responsible 6499 * for arranging their children. 6500 * 6501 * @param params the layout parameters for this view 6502 */ 6503 public void setLayoutParams(ViewGroup.LayoutParams params) { 6504 if (params == null) { 6505 throw new NullPointerException("params == null"); 6506 } 6507 mLayoutParams = params; 6508 requestLayout(); 6509 } 6510 6511 /** 6512 * Set the scrolled position of your view. This will cause a call to 6513 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6514 * invalidated. 6515 * @param x the x position to scroll to 6516 * @param y the y position to scroll to 6517 */ 6518 public void scrollTo(int x, int y) { 6519 if (mScrollX != x || mScrollY != y) { 6520 int oldX = mScrollX; 6521 int oldY = mScrollY; 6522 mScrollX = x; 6523 mScrollY = y; 6524 invalidateParentCaches(); 6525 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 6526 if (!awakenScrollBars()) { 6527 invalidate(true); 6528 } 6529 } 6530 } 6531 6532 /** 6533 * Move the scrolled position of your view. This will cause a call to 6534 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6535 * invalidated. 6536 * @param x the amount of pixels to scroll by horizontally 6537 * @param y the amount of pixels to scroll by vertically 6538 */ 6539 public void scrollBy(int x, int y) { 6540 scrollTo(mScrollX + x, mScrollY + y); 6541 } 6542 6543 /** 6544 * <p>Trigger the scrollbars to draw. When invoked this method starts an 6545 * animation to fade the scrollbars out after a default delay. If a subclass 6546 * provides animated scrolling, the start delay should equal the duration 6547 * of the scrolling animation.</p> 6548 * 6549 * <p>The animation starts only if at least one of the scrollbars is 6550 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 6551 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 6552 * this method returns true, and false otherwise. If the animation is 6553 * started, this method calls {@link #invalidate()}; in that case the 6554 * caller should not call {@link #invalidate()}.</p> 6555 * 6556 * <p>This method should be invoked every time a subclass directly updates 6557 * the scroll parameters.</p> 6558 * 6559 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 6560 * and {@link #scrollTo(int, int)}.</p> 6561 * 6562 * @return true if the animation is played, false otherwise 6563 * 6564 * @see #awakenScrollBars(int) 6565 * @see #scrollBy(int, int) 6566 * @see #scrollTo(int, int) 6567 * @see #isHorizontalScrollBarEnabled() 6568 * @see #isVerticalScrollBarEnabled() 6569 * @see #setHorizontalScrollBarEnabled(boolean) 6570 * @see #setVerticalScrollBarEnabled(boolean) 6571 */ 6572 protected boolean awakenScrollBars() { 6573 return mScrollCache != null && 6574 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 6575 } 6576 6577 /** 6578 * Trigger the scrollbars to draw. 6579 * This method differs from awakenScrollBars() only in its default duration. 6580 * initialAwakenScrollBars() will show the scroll bars for longer than 6581 * usual to give the user more of a chance to notice them. 6582 * 6583 * @return true if the animation is played, false otherwise. 6584 */ 6585 private boolean initialAwakenScrollBars() { 6586 return mScrollCache != null && 6587 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 6588 } 6589 6590 /** 6591 * <p> 6592 * Trigger the scrollbars to draw. When invoked this method starts an 6593 * animation to fade the scrollbars out after a fixed delay. If a subclass 6594 * provides animated scrolling, the start delay should equal the duration of 6595 * the scrolling animation. 6596 * </p> 6597 * 6598 * <p> 6599 * The animation starts only if at least one of the scrollbars is enabled, 6600 * as specified by {@link #isHorizontalScrollBarEnabled()} and 6601 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 6602 * this method returns true, and false otherwise. If the animation is 6603 * started, this method calls {@link #invalidate()}; in that case the caller 6604 * should not call {@link #invalidate()}. 6605 * </p> 6606 * 6607 * <p> 6608 * This method should be invoked everytime a subclass directly updates the 6609 * scroll parameters. 6610 * </p> 6611 * 6612 * @param startDelay the delay, in milliseconds, after which the animation 6613 * should start; when the delay is 0, the animation starts 6614 * immediately 6615 * @return true if the animation is played, false otherwise 6616 * 6617 * @see #scrollBy(int, int) 6618 * @see #scrollTo(int, int) 6619 * @see #isHorizontalScrollBarEnabled() 6620 * @see #isVerticalScrollBarEnabled() 6621 * @see #setHorizontalScrollBarEnabled(boolean) 6622 * @see #setVerticalScrollBarEnabled(boolean) 6623 */ 6624 protected boolean awakenScrollBars(int startDelay) { 6625 return awakenScrollBars(startDelay, true); 6626 } 6627 6628 /** 6629 * <p> 6630 * Trigger the scrollbars to draw. When invoked this method starts an 6631 * animation to fade the scrollbars out after a fixed delay. If a subclass 6632 * provides animated scrolling, the start delay should equal the duration of 6633 * the scrolling animation. 6634 * </p> 6635 * 6636 * <p> 6637 * The animation starts only if at least one of the scrollbars is enabled, 6638 * as specified by {@link #isHorizontalScrollBarEnabled()} and 6639 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 6640 * this method returns true, and false otherwise. If the animation is 6641 * started, this method calls {@link #invalidate()} if the invalidate parameter 6642 * is set to true; in that case the caller 6643 * should not call {@link #invalidate()}. 6644 * </p> 6645 * 6646 * <p> 6647 * This method should be invoked everytime a subclass directly updates the 6648 * scroll parameters. 6649 * </p> 6650 * 6651 * @param startDelay the delay, in milliseconds, after which the animation 6652 * should start; when the delay is 0, the animation starts 6653 * immediately 6654 * 6655 * @param invalidate Wheter this method should call invalidate 6656 * 6657 * @return true if the animation is played, false otherwise 6658 * 6659 * @see #scrollBy(int, int) 6660 * @see #scrollTo(int, int) 6661 * @see #isHorizontalScrollBarEnabled() 6662 * @see #isVerticalScrollBarEnabled() 6663 * @see #setHorizontalScrollBarEnabled(boolean) 6664 * @see #setVerticalScrollBarEnabled(boolean) 6665 */ 6666 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 6667 final ScrollabilityCache scrollCache = mScrollCache; 6668 6669 if (scrollCache == null || !scrollCache.fadeScrollBars) { 6670 return false; 6671 } 6672 6673 if (scrollCache.scrollBar == null) { 6674 scrollCache.scrollBar = new ScrollBarDrawable(); 6675 } 6676 6677 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 6678 6679 if (invalidate) { 6680 // Invalidate to show the scrollbars 6681 invalidate(true); 6682 } 6683 6684 if (scrollCache.state == ScrollabilityCache.OFF) { 6685 // FIXME: this is copied from WindowManagerService. 6686 // We should get this value from the system when it 6687 // is possible to do so. 6688 final int KEY_REPEAT_FIRST_DELAY = 750; 6689 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 6690 } 6691 6692 // Tell mScrollCache when we should start fading. This may 6693 // extend the fade start time if one was already scheduled 6694 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 6695 scrollCache.fadeStartTime = fadeStartTime; 6696 scrollCache.state = ScrollabilityCache.ON; 6697 6698 // Schedule our fader to run, unscheduling any old ones first 6699 if (mAttachInfo != null) { 6700 mAttachInfo.mHandler.removeCallbacks(scrollCache); 6701 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 6702 } 6703 6704 return true; 6705 } 6706 6707 return false; 6708 } 6709 6710 /** 6711 * Mark the the area defined by dirty as needing to be drawn. If the view is 6712 * visible, {@link #onDraw} will be called at some point in the future. 6713 * This must be called from a UI thread. To call from a non-UI thread, call 6714 * {@link #postInvalidate()}. 6715 * 6716 * WARNING: This method is destructive to dirty. 6717 * @param dirty the rectangle representing the bounds of the dirty region 6718 */ 6719 public void invalidate(Rect dirty) { 6720 if (ViewDebug.TRACE_HIERARCHY) { 6721 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 6722 } 6723 6724 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 6725 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 6726 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 6727 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6728 mPrivateFlags |= INVALIDATED; 6729 final ViewParent p = mParent; 6730 final AttachInfo ai = mAttachInfo; 6731 //noinspection PointlessBooleanExpression,ConstantConditions 6732 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 6733 if (p != null && ai != null && ai.mHardwareAccelerated) { 6734 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 6735 // with a null dirty rect, which tells the ViewRoot to redraw everything 6736 p.invalidateChild(this, null); 6737 return; 6738 } 6739 } 6740 if (p != null && ai != null) { 6741 final int scrollX = mScrollX; 6742 final int scrollY = mScrollY; 6743 final Rect r = ai.mTmpInvalRect; 6744 r.set(dirty.left - scrollX, dirty.top - scrollY, 6745 dirty.right - scrollX, dirty.bottom - scrollY); 6746 mParent.invalidateChild(this, r); 6747 } 6748 } 6749 } 6750 6751 /** 6752 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn. 6753 * The coordinates of the dirty rect are relative to the view. 6754 * If the view is visible, {@link #onDraw} will be called at some point 6755 * in the future. This must be called from a UI thread. To call 6756 * from a non-UI thread, call {@link #postInvalidate()}. 6757 * @param l the left position of the dirty region 6758 * @param t the top position of the dirty region 6759 * @param r the right position of the dirty region 6760 * @param b the bottom position of the dirty region 6761 */ 6762 public void invalidate(int l, int t, int r, int b) { 6763 if (ViewDebug.TRACE_HIERARCHY) { 6764 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 6765 } 6766 6767 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 6768 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 6769 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 6770 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6771 mPrivateFlags |= INVALIDATED; 6772 final ViewParent p = mParent; 6773 final AttachInfo ai = mAttachInfo; 6774 //noinspection PointlessBooleanExpression,ConstantConditions 6775 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 6776 if (p != null && ai != null && ai.mHardwareAccelerated) { 6777 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 6778 // with a null dirty rect, which tells the ViewRoot to redraw everything 6779 p.invalidateChild(this, null); 6780 return; 6781 } 6782 } 6783 if (p != null && ai != null && l < r && t < b) { 6784 final int scrollX = mScrollX; 6785 final int scrollY = mScrollY; 6786 final Rect tmpr = ai.mTmpInvalRect; 6787 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 6788 p.invalidateChild(this, tmpr); 6789 } 6790 } 6791 } 6792 6793 /** 6794 * Invalidate the whole view. If the view is visible, {@link #onDraw} will 6795 * be called at some point in the future. This must be called from a 6796 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 6797 */ 6798 public void invalidate() { 6799 invalidate(true); 6800 } 6801 6802 /** 6803 * This is where the invalidate() work actually happens. A full invalidate() 6804 * causes the drawing cache to be invalidated, but this function can be called with 6805 * invalidateCache set to false to skip that invalidation step for cases that do not 6806 * need it (for example, a component that remains at the same dimensions with the same 6807 * content). 6808 * 6809 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 6810 * well. This is usually true for a full invalidate, but may be set to false if the 6811 * View's contents or dimensions have not changed. 6812 */ 6813 private void invalidate(boolean invalidateCache) { 6814 if (ViewDebug.TRACE_HIERARCHY) { 6815 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 6816 } 6817 6818 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 6819 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) || 6820 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) { 6821 mLastIsOpaque = isOpaque(); 6822 mPrivateFlags &= ~DRAWN; 6823 if (invalidateCache) { 6824 mPrivateFlags |= INVALIDATED; 6825 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6826 } 6827 final AttachInfo ai = mAttachInfo; 6828 final ViewParent p = mParent; 6829 //noinspection PointlessBooleanExpression,ConstantConditions 6830 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 6831 if (p != null && ai != null && ai.mHardwareAccelerated) { 6832 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 6833 // with a null dirty rect, which tells the ViewRoot to redraw everything 6834 p.invalidateChild(this, null); 6835 return; 6836 } 6837 } 6838 6839 if (p != null && ai != null) { 6840 final Rect r = ai.mTmpInvalRect; 6841 r.set(0, 0, mRight - mLeft, mBottom - mTop); 6842 // Don't call invalidate -- we don't want to internally scroll 6843 // our own bounds 6844 p.invalidateChild(this, r); 6845 } 6846 } 6847 } 6848 6849 /** 6850 * Used to indicate that the parent of this view should clear its caches. This functionality 6851 * is used to force the parent to rebuild its display list (when hardware-accelerated), 6852 * which is necessary when various parent-managed properties of the view change, such as 6853 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 6854 * clears the parent caches and does not causes an invalidate event. 6855 * 6856 * @hide 6857 */ 6858 protected void invalidateParentCaches() { 6859 if (mParent instanceof View) { 6860 ((View) mParent).mPrivateFlags |= INVALIDATED; 6861 } 6862 } 6863 6864 /** 6865 * Used to indicate that the parent of this view should be invalidated. This functionality 6866 * is used to force the parent to rebuild its display list (when hardware-accelerated), 6867 * which is necessary when various parent-managed properties of the view change, such as 6868 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 6869 * an invalidation event to the parent. 6870 * 6871 * @hide 6872 */ 6873 protected void invalidateParentIfNeeded() { 6874 if (isHardwareAccelerated() && mParent instanceof View) { 6875 ((View) mParent).invalidate(true); 6876 } 6877 } 6878 6879 /** 6880 * Indicates whether this View is opaque. An opaque View guarantees that it will 6881 * draw all the pixels overlapping its bounds using a fully opaque color. 6882 * 6883 * Subclasses of View should override this method whenever possible to indicate 6884 * whether an instance is opaque. Opaque Views are treated in a special way by 6885 * the View hierarchy, possibly allowing it to perform optimizations during 6886 * invalidate/draw passes. 6887 * 6888 * @return True if this View is guaranteed to be fully opaque, false otherwise. 6889 */ 6890 @ViewDebug.ExportedProperty(category = "drawing") 6891 public boolean isOpaque() { 6892 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK && 6893 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD); 6894 } 6895 6896 /** 6897 * @hide 6898 */ 6899 protected void computeOpaqueFlags() { 6900 // Opaque if: 6901 // - Has a background 6902 // - Background is opaque 6903 // - Doesn't have scrollbars or scrollbars are inside overlay 6904 6905 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) { 6906 mPrivateFlags |= OPAQUE_BACKGROUND; 6907 } else { 6908 mPrivateFlags &= ~OPAQUE_BACKGROUND; 6909 } 6910 6911 final int flags = mViewFlags; 6912 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 6913 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 6914 mPrivateFlags |= OPAQUE_SCROLLBARS; 6915 } else { 6916 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 6917 } 6918 } 6919 6920 /** 6921 * @hide 6922 */ 6923 protected boolean hasOpaqueScrollbars() { 6924 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 6925 } 6926 6927 /** 6928 * @return A handler associated with the thread running the View. This 6929 * handler can be used to pump events in the UI events queue. 6930 */ 6931 public Handler getHandler() { 6932 if (mAttachInfo != null) { 6933 return mAttachInfo.mHandler; 6934 } 6935 return null; 6936 } 6937 6938 /** 6939 * Causes the Runnable to be added to the message queue. 6940 * The runnable will be run on the user interface thread. 6941 * 6942 * @param action The Runnable that will be executed. 6943 * 6944 * @return Returns true if the Runnable was successfully placed in to the 6945 * message queue. Returns false on failure, usually because the 6946 * looper processing the message queue is exiting. 6947 */ 6948 public boolean post(Runnable action) { 6949 Handler handler; 6950 if (mAttachInfo != null) { 6951 handler = mAttachInfo.mHandler; 6952 } else { 6953 // Assume that post will succeed later 6954 ViewRoot.getRunQueue().post(action); 6955 return true; 6956 } 6957 6958 return handler.post(action); 6959 } 6960 6961 /** 6962 * Causes the Runnable to be added to the message queue, to be run 6963 * after the specified amount of time elapses. 6964 * The runnable will be run on the user interface thread. 6965 * 6966 * @param action The Runnable that will be executed. 6967 * @param delayMillis The delay (in milliseconds) until the Runnable 6968 * will be executed. 6969 * 6970 * @return true if the Runnable was successfully placed in to the 6971 * message queue. Returns false on failure, usually because the 6972 * looper processing the message queue is exiting. Note that a 6973 * result of true does not mean the Runnable will be processed -- 6974 * if the looper is quit before the delivery time of the message 6975 * occurs then the message will be dropped. 6976 */ 6977 public boolean postDelayed(Runnable action, long delayMillis) { 6978 Handler handler; 6979 if (mAttachInfo != null) { 6980 handler = mAttachInfo.mHandler; 6981 } else { 6982 // Assume that post will succeed later 6983 ViewRoot.getRunQueue().postDelayed(action, delayMillis); 6984 return true; 6985 } 6986 6987 return handler.postDelayed(action, delayMillis); 6988 } 6989 6990 /** 6991 * Removes the specified Runnable from the message queue. 6992 * 6993 * @param action The Runnable to remove from the message handling queue 6994 * 6995 * @return true if this view could ask the Handler to remove the Runnable, 6996 * false otherwise. When the returned value is true, the Runnable 6997 * may or may not have been actually removed from the message queue 6998 * (for instance, if the Runnable was not in the queue already.) 6999 */ 7000 public boolean removeCallbacks(Runnable action) { 7001 Handler handler; 7002 if (mAttachInfo != null) { 7003 handler = mAttachInfo.mHandler; 7004 } else { 7005 // Assume that post will succeed later 7006 ViewRoot.getRunQueue().removeCallbacks(action); 7007 return true; 7008 } 7009 7010 handler.removeCallbacks(action); 7011 return true; 7012 } 7013 7014 /** 7015 * Cause an invalidate to happen on a subsequent cycle through the event loop. 7016 * Use this to invalidate the View from a non-UI thread. 7017 * 7018 * @see #invalidate() 7019 */ 7020 public void postInvalidate() { 7021 postInvalidateDelayed(0); 7022 } 7023 7024 /** 7025 * Cause an invalidate of the specified area to happen on a subsequent cycle 7026 * through the event loop. Use this to invalidate the View from a non-UI thread. 7027 * 7028 * @param left The left coordinate of the rectangle to invalidate. 7029 * @param top The top coordinate of the rectangle to invalidate. 7030 * @param right The right coordinate of the rectangle to invalidate. 7031 * @param bottom The bottom coordinate of the rectangle to invalidate. 7032 * 7033 * @see #invalidate(int, int, int, int) 7034 * @see #invalidate(Rect) 7035 */ 7036 public void postInvalidate(int left, int top, int right, int bottom) { 7037 postInvalidateDelayed(0, left, top, right, bottom); 7038 } 7039 7040 /** 7041 * Cause an invalidate to happen on a subsequent cycle through the event 7042 * loop. Waits for the specified amount of time. 7043 * 7044 * @param delayMilliseconds the duration in milliseconds to delay the 7045 * invalidation by 7046 */ 7047 public void postInvalidateDelayed(long delayMilliseconds) { 7048 // We try only with the AttachInfo because there's no point in invalidating 7049 // if we are not attached to our window 7050 if (mAttachInfo != null) { 7051 Message msg = Message.obtain(); 7052 msg.what = AttachInfo.INVALIDATE_MSG; 7053 msg.obj = this; 7054 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 7055 } 7056 } 7057 7058 /** 7059 * Cause an invalidate of the specified area to happen on a subsequent cycle 7060 * through the event loop. Waits for the specified amount of time. 7061 * 7062 * @param delayMilliseconds the duration in milliseconds to delay the 7063 * invalidation by 7064 * @param left The left coordinate of the rectangle to invalidate. 7065 * @param top The top coordinate of the rectangle to invalidate. 7066 * @param right The right coordinate of the rectangle to invalidate. 7067 * @param bottom The bottom coordinate of the rectangle to invalidate. 7068 */ 7069 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 7070 int right, int bottom) { 7071 7072 // We try only with the AttachInfo because there's no point in invalidating 7073 // if we are not attached to our window 7074 if (mAttachInfo != null) { 7075 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 7076 info.target = this; 7077 info.left = left; 7078 info.top = top; 7079 info.right = right; 7080 info.bottom = bottom; 7081 7082 final Message msg = Message.obtain(); 7083 msg.what = AttachInfo.INVALIDATE_RECT_MSG; 7084 msg.obj = info; 7085 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 7086 } 7087 } 7088 7089 /** 7090 * Called by a parent to request that a child update its values for mScrollX 7091 * and mScrollY if necessary. This will typically be done if the child is 7092 * animating a scroll using a {@link android.widget.Scroller Scroller} 7093 * object. 7094 */ 7095 public void computeScroll() { 7096 } 7097 7098 /** 7099 * <p>Indicate whether the horizontal edges are faded when the view is 7100 * scrolled horizontally.</p> 7101 * 7102 * @return true if the horizontal edges should are faded on scroll, false 7103 * otherwise 7104 * 7105 * @see #setHorizontalFadingEdgeEnabled(boolean) 7106 * @attr ref android.R.styleable#View_fadingEdge 7107 */ 7108 public boolean isHorizontalFadingEdgeEnabled() { 7109 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 7110 } 7111 7112 /** 7113 * <p>Define whether the horizontal edges should be faded when this view 7114 * is scrolled horizontally.</p> 7115 * 7116 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 7117 * be faded when the view is scrolled 7118 * horizontally 7119 * 7120 * @see #isHorizontalFadingEdgeEnabled() 7121 * @attr ref android.R.styleable#View_fadingEdge 7122 */ 7123 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 7124 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 7125 if (horizontalFadingEdgeEnabled) { 7126 initScrollCache(); 7127 } 7128 7129 mViewFlags ^= FADING_EDGE_HORIZONTAL; 7130 } 7131 } 7132 7133 /** 7134 * <p>Indicate whether the vertical edges are faded when the view is 7135 * scrolled horizontally.</p> 7136 * 7137 * @return true if the vertical edges should are faded on scroll, false 7138 * otherwise 7139 * 7140 * @see #setVerticalFadingEdgeEnabled(boolean) 7141 * @attr ref android.R.styleable#View_fadingEdge 7142 */ 7143 public boolean isVerticalFadingEdgeEnabled() { 7144 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 7145 } 7146 7147 /** 7148 * <p>Define whether the vertical edges should be faded when this view 7149 * is scrolled vertically.</p> 7150 * 7151 * @param verticalFadingEdgeEnabled true if the vertical edges should 7152 * be faded when the view is scrolled 7153 * vertically 7154 * 7155 * @see #isVerticalFadingEdgeEnabled() 7156 * @attr ref android.R.styleable#View_fadingEdge 7157 */ 7158 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 7159 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 7160 if (verticalFadingEdgeEnabled) { 7161 initScrollCache(); 7162 } 7163 7164 mViewFlags ^= FADING_EDGE_VERTICAL; 7165 } 7166 } 7167 7168 /** 7169 * Returns the strength, or intensity, of the top faded edge. The strength is 7170 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 7171 * returns 0.0 or 1.0 but no value in between. 7172 * 7173 * Subclasses should override this method to provide a smoother fade transition 7174 * when scrolling occurs. 7175 * 7176 * @return the intensity of the top fade as a float between 0.0f and 1.0f 7177 */ 7178 protected float getTopFadingEdgeStrength() { 7179 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 7180 } 7181 7182 /** 7183 * Returns the strength, or intensity, of the bottom faded edge. The strength is 7184 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 7185 * returns 0.0 or 1.0 but no value in between. 7186 * 7187 * Subclasses should override this method to provide a smoother fade transition 7188 * when scrolling occurs. 7189 * 7190 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 7191 */ 7192 protected float getBottomFadingEdgeStrength() { 7193 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 7194 computeVerticalScrollRange() ? 1.0f : 0.0f; 7195 } 7196 7197 /** 7198 * Returns the strength, or intensity, of the left faded edge. The strength is 7199 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 7200 * returns 0.0 or 1.0 but no value in between. 7201 * 7202 * Subclasses should override this method to provide a smoother fade transition 7203 * when scrolling occurs. 7204 * 7205 * @return the intensity of the left fade as a float between 0.0f and 1.0f 7206 */ 7207 protected float getLeftFadingEdgeStrength() { 7208 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 7209 } 7210 7211 /** 7212 * Returns the strength, or intensity, of the right faded edge. The strength is 7213 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 7214 * returns 0.0 or 1.0 but no value in between. 7215 * 7216 * Subclasses should override this method to provide a smoother fade transition 7217 * when scrolling occurs. 7218 * 7219 * @return the intensity of the right fade as a float between 0.0f and 1.0f 7220 */ 7221 protected float getRightFadingEdgeStrength() { 7222 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 7223 computeHorizontalScrollRange() ? 1.0f : 0.0f; 7224 } 7225 7226 /** 7227 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 7228 * scrollbar is not drawn by default.</p> 7229 * 7230 * @return true if the horizontal scrollbar should be painted, false 7231 * otherwise 7232 * 7233 * @see #setHorizontalScrollBarEnabled(boolean) 7234 */ 7235 public boolean isHorizontalScrollBarEnabled() { 7236 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 7237 } 7238 7239 /** 7240 * <p>Define whether the horizontal scrollbar should be drawn or not. The 7241 * scrollbar is not drawn by default.</p> 7242 * 7243 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 7244 * be painted 7245 * 7246 * @see #isHorizontalScrollBarEnabled() 7247 */ 7248 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 7249 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 7250 mViewFlags ^= SCROLLBARS_HORIZONTAL; 7251 computeOpaqueFlags(); 7252 recomputePadding(); 7253 } 7254 } 7255 7256 /** 7257 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 7258 * scrollbar is not drawn by default.</p> 7259 * 7260 * @return true if the vertical scrollbar should be painted, false 7261 * otherwise 7262 * 7263 * @see #setVerticalScrollBarEnabled(boolean) 7264 */ 7265 public boolean isVerticalScrollBarEnabled() { 7266 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 7267 } 7268 7269 /** 7270 * <p>Define whether the vertical scrollbar should be drawn or not. The 7271 * scrollbar is not drawn by default.</p> 7272 * 7273 * @param verticalScrollBarEnabled true if the vertical scrollbar should 7274 * be painted 7275 * 7276 * @see #isVerticalScrollBarEnabled() 7277 */ 7278 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 7279 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 7280 mViewFlags ^= SCROLLBARS_VERTICAL; 7281 computeOpaqueFlags(); 7282 recomputePadding(); 7283 } 7284 } 7285 7286 /** 7287 * @hide 7288 */ 7289 protected void recomputePadding() { 7290 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 7291 } 7292 7293 /** 7294 * Define whether scrollbars will fade when the view is not scrolling. 7295 * 7296 * @param fadeScrollbars wheter to enable fading 7297 * 7298 */ 7299 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 7300 initScrollCache(); 7301 final ScrollabilityCache scrollabilityCache = mScrollCache; 7302 scrollabilityCache.fadeScrollBars = fadeScrollbars; 7303 if (fadeScrollbars) { 7304 scrollabilityCache.state = ScrollabilityCache.OFF; 7305 } else { 7306 scrollabilityCache.state = ScrollabilityCache.ON; 7307 } 7308 } 7309 7310 /** 7311 * 7312 * Returns true if scrollbars will fade when this view is not scrolling 7313 * 7314 * @return true if scrollbar fading is enabled 7315 */ 7316 public boolean isScrollbarFadingEnabled() { 7317 return mScrollCache != null && mScrollCache.fadeScrollBars; 7318 } 7319 7320 /** 7321 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 7322 * inset. When inset, they add to the padding of the view. And the scrollbars 7323 * can be drawn inside the padding area or on the edge of the view. For example, 7324 * if a view has a background drawable and you want to draw the scrollbars 7325 * inside the padding specified by the drawable, you can use 7326 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 7327 * appear at the edge of the view, ignoring the padding, then you can use 7328 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 7329 * @param style the style of the scrollbars. Should be one of 7330 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 7331 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 7332 * @see #SCROLLBARS_INSIDE_OVERLAY 7333 * @see #SCROLLBARS_INSIDE_INSET 7334 * @see #SCROLLBARS_OUTSIDE_OVERLAY 7335 * @see #SCROLLBARS_OUTSIDE_INSET 7336 */ 7337 public void setScrollBarStyle(int style) { 7338 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 7339 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 7340 computeOpaqueFlags(); 7341 recomputePadding(); 7342 } 7343 } 7344 7345 /** 7346 * <p>Returns the current scrollbar style.</p> 7347 * @return the current scrollbar style 7348 * @see #SCROLLBARS_INSIDE_OVERLAY 7349 * @see #SCROLLBARS_INSIDE_INSET 7350 * @see #SCROLLBARS_OUTSIDE_OVERLAY 7351 * @see #SCROLLBARS_OUTSIDE_INSET 7352 */ 7353 public int getScrollBarStyle() { 7354 return mViewFlags & SCROLLBARS_STYLE_MASK; 7355 } 7356 7357 /** 7358 * <p>Compute the horizontal range that the horizontal scrollbar 7359 * represents.</p> 7360 * 7361 * <p>The range is expressed in arbitrary units that must be the same as the 7362 * units used by {@link #computeHorizontalScrollExtent()} and 7363 * {@link #computeHorizontalScrollOffset()}.</p> 7364 * 7365 * <p>The default range is the drawing width of this view.</p> 7366 * 7367 * @return the total horizontal range represented by the horizontal 7368 * scrollbar 7369 * 7370 * @see #computeHorizontalScrollExtent() 7371 * @see #computeHorizontalScrollOffset() 7372 * @see android.widget.ScrollBarDrawable 7373 */ 7374 protected int computeHorizontalScrollRange() { 7375 return getWidth(); 7376 } 7377 7378 /** 7379 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 7380 * within the horizontal range. This value is used to compute the position 7381 * of the thumb within the scrollbar's track.</p> 7382 * 7383 * <p>The range is expressed in arbitrary units that must be the same as the 7384 * units used by {@link #computeHorizontalScrollRange()} and 7385 * {@link #computeHorizontalScrollExtent()}.</p> 7386 * 7387 * <p>The default offset is the scroll offset of this view.</p> 7388 * 7389 * @return the horizontal offset of the scrollbar's thumb 7390 * 7391 * @see #computeHorizontalScrollRange() 7392 * @see #computeHorizontalScrollExtent() 7393 * @see android.widget.ScrollBarDrawable 7394 */ 7395 protected int computeHorizontalScrollOffset() { 7396 return mScrollX; 7397 } 7398 7399 /** 7400 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 7401 * within the horizontal range. This value is used to compute the length 7402 * of the thumb within the scrollbar's track.</p> 7403 * 7404 * <p>The range is expressed in arbitrary units that must be the same as the 7405 * units used by {@link #computeHorizontalScrollRange()} and 7406 * {@link #computeHorizontalScrollOffset()}.</p> 7407 * 7408 * <p>The default extent is the drawing width of this view.</p> 7409 * 7410 * @return the horizontal extent of the scrollbar's thumb 7411 * 7412 * @see #computeHorizontalScrollRange() 7413 * @see #computeHorizontalScrollOffset() 7414 * @see android.widget.ScrollBarDrawable 7415 */ 7416 protected int computeHorizontalScrollExtent() { 7417 return getWidth(); 7418 } 7419 7420 /** 7421 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 7422 * 7423 * <p>The range is expressed in arbitrary units that must be the same as the 7424 * units used by {@link #computeVerticalScrollExtent()} and 7425 * {@link #computeVerticalScrollOffset()}.</p> 7426 * 7427 * @return the total vertical range represented by the vertical scrollbar 7428 * 7429 * <p>The default range is the drawing height of this view.</p> 7430 * 7431 * @see #computeVerticalScrollExtent() 7432 * @see #computeVerticalScrollOffset() 7433 * @see android.widget.ScrollBarDrawable 7434 */ 7435 protected int computeVerticalScrollRange() { 7436 return getHeight(); 7437 } 7438 7439 /** 7440 * <p>Compute the vertical offset of the vertical scrollbar's thumb 7441 * within the horizontal range. This value is used to compute the position 7442 * of the thumb within the scrollbar's track.</p> 7443 * 7444 * <p>The range is expressed in arbitrary units that must be the same as the 7445 * units used by {@link #computeVerticalScrollRange()} and 7446 * {@link #computeVerticalScrollExtent()}.</p> 7447 * 7448 * <p>The default offset is the scroll offset of this view.</p> 7449 * 7450 * @return the vertical offset of the scrollbar's thumb 7451 * 7452 * @see #computeVerticalScrollRange() 7453 * @see #computeVerticalScrollExtent() 7454 * @see android.widget.ScrollBarDrawable 7455 */ 7456 protected int computeVerticalScrollOffset() { 7457 return mScrollY; 7458 } 7459 7460 /** 7461 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 7462 * within the vertical range. This value is used to compute the length 7463 * of the thumb within the scrollbar's track.</p> 7464 * 7465 * <p>The range is expressed in arbitrary units that must be the same as the 7466 * units used by {@link #computeVerticalScrollRange()} and 7467 * {@link #computeVerticalScrollOffset()}.</p> 7468 * 7469 * <p>The default extent is the drawing height of this view.</p> 7470 * 7471 * @return the vertical extent of the scrollbar's thumb 7472 * 7473 * @see #computeVerticalScrollRange() 7474 * @see #computeVerticalScrollOffset() 7475 * @see android.widget.ScrollBarDrawable 7476 */ 7477 protected int computeVerticalScrollExtent() { 7478 return getHeight(); 7479 } 7480 7481 /** 7482 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 7483 * scrollbars are painted only if they have been awakened first.</p> 7484 * 7485 * @param canvas the canvas on which to draw the scrollbars 7486 * 7487 * @see #awakenScrollBars(int) 7488 */ 7489 protected final void onDrawScrollBars(Canvas canvas) { 7490 // scrollbars are drawn only when the animation is running 7491 final ScrollabilityCache cache = mScrollCache; 7492 if (cache != null) { 7493 7494 int state = cache.state; 7495 7496 if (state == ScrollabilityCache.OFF) { 7497 return; 7498 } 7499 7500 boolean invalidate = false; 7501 7502 if (state == ScrollabilityCache.FADING) { 7503 // We're fading -- get our fade interpolation 7504 if (cache.interpolatorValues == null) { 7505 cache.interpolatorValues = new float[1]; 7506 } 7507 7508 float[] values = cache.interpolatorValues; 7509 7510 // Stops the animation if we're done 7511 if (cache.scrollBarInterpolator.timeToValues(values) == 7512 Interpolator.Result.FREEZE_END) { 7513 cache.state = ScrollabilityCache.OFF; 7514 } else { 7515 cache.scrollBar.setAlpha(Math.round(values[0])); 7516 } 7517 7518 // This will make the scroll bars inval themselves after 7519 // drawing. We only want this when we're fading so that 7520 // we prevent excessive redraws 7521 invalidate = true; 7522 } else { 7523 // We're just on -- but we may have been fading before so 7524 // reset alpha 7525 cache.scrollBar.setAlpha(255); 7526 } 7527 7528 7529 final int viewFlags = mViewFlags; 7530 7531 final boolean drawHorizontalScrollBar = 7532 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 7533 final boolean drawVerticalScrollBar = 7534 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 7535 && !isVerticalScrollBarHidden(); 7536 7537 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 7538 final int width = mRight - mLeft; 7539 final int height = mBottom - mTop; 7540 7541 final ScrollBarDrawable scrollBar = cache.scrollBar; 7542 int size = scrollBar.getSize(false); 7543 if (size <= 0) { 7544 size = cache.scrollBarSize; 7545 } 7546 7547 final int scrollX = mScrollX; 7548 final int scrollY = mScrollY; 7549 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 7550 7551 int left, top, right, bottom; 7552 7553 if (drawHorizontalScrollBar) { 7554 scrollBar.setParameters(computeHorizontalScrollRange(), 7555 computeHorizontalScrollOffset(), 7556 computeHorizontalScrollExtent(), false); 7557 final int verticalScrollBarGap = drawVerticalScrollBar ? 7558 getVerticalScrollbarWidth() : 0; 7559 top = scrollY + height - size - (mUserPaddingBottom & inside); 7560 left = scrollX + (mPaddingLeft & inside); 7561 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 7562 bottom = top + size; 7563 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 7564 if (invalidate) { 7565 invalidate(left, top, right, bottom); 7566 } 7567 } 7568 7569 if (drawVerticalScrollBar) { 7570 scrollBar.setParameters(computeVerticalScrollRange(), 7571 computeVerticalScrollOffset(), 7572 computeVerticalScrollExtent(), true); 7573 switch (mVerticalScrollbarPosition) { 7574 default: 7575 case SCROLLBAR_POSITION_DEFAULT: 7576 case SCROLLBAR_POSITION_RIGHT: 7577 left = scrollX + width - size - (mUserPaddingRight & inside); 7578 break; 7579 case SCROLLBAR_POSITION_LEFT: 7580 left = scrollX + (mUserPaddingLeft & inside); 7581 break; 7582 } 7583 top = scrollY + (mPaddingTop & inside); 7584 right = left + size; 7585 bottom = scrollY + height - (mUserPaddingBottom & inside); 7586 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 7587 if (invalidate) { 7588 invalidate(left, top, right, bottom); 7589 } 7590 } 7591 } 7592 } 7593 } 7594 7595 /** 7596 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 7597 * FastScroller is visible. 7598 * @return whether to temporarily hide the vertical scrollbar 7599 * @hide 7600 */ 7601 protected boolean isVerticalScrollBarHidden() { 7602 return false; 7603 } 7604 7605 /** 7606 * <p>Draw the horizontal scrollbar if 7607 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 7608 * 7609 * @param canvas the canvas on which to draw the scrollbar 7610 * @param scrollBar the scrollbar's drawable 7611 * 7612 * @see #isHorizontalScrollBarEnabled() 7613 * @see #computeHorizontalScrollRange() 7614 * @see #computeHorizontalScrollExtent() 7615 * @see #computeHorizontalScrollOffset() 7616 * @see android.widget.ScrollBarDrawable 7617 * @hide 7618 */ 7619 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 7620 int l, int t, int r, int b) { 7621 scrollBar.setBounds(l, t, r, b); 7622 scrollBar.draw(canvas); 7623 } 7624 7625 /** 7626 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 7627 * returns true.</p> 7628 * 7629 * @param canvas the canvas on which to draw the scrollbar 7630 * @param scrollBar the scrollbar's drawable 7631 * 7632 * @see #isVerticalScrollBarEnabled() 7633 * @see #computeVerticalScrollRange() 7634 * @see #computeVerticalScrollExtent() 7635 * @see #computeVerticalScrollOffset() 7636 * @see android.widget.ScrollBarDrawable 7637 * @hide 7638 */ 7639 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 7640 int l, int t, int r, int b) { 7641 scrollBar.setBounds(l, t, r, b); 7642 scrollBar.draw(canvas); 7643 } 7644 7645 /** 7646 * Implement this to do your drawing. 7647 * 7648 * @param canvas the canvas on which the background will be drawn 7649 */ 7650 protected void onDraw(Canvas canvas) { 7651 } 7652 7653 /* 7654 * Caller is responsible for calling requestLayout if necessary. 7655 * (This allows addViewInLayout to not request a new layout.) 7656 */ 7657 void assignParent(ViewParent parent) { 7658 if (mParent == null) { 7659 mParent = parent; 7660 } else if (parent == null) { 7661 mParent = null; 7662 } else { 7663 throw new RuntimeException("view " + this + " being added, but" 7664 + " it already has a parent"); 7665 } 7666 } 7667 7668 /** 7669 * This is called when the view is attached to a window. At this point it 7670 * has a Surface and will start drawing. Note that this function is 7671 * guaranteed to be called before {@link #onDraw}, however it may be called 7672 * any time before the first onDraw -- including before or after 7673 * {@link #onMeasure}. 7674 * 7675 * @see #onDetachedFromWindow() 7676 */ 7677 protected void onAttachedToWindow() { 7678 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 7679 mParent.requestTransparentRegion(this); 7680 } 7681 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 7682 initialAwakenScrollBars(); 7683 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH; 7684 } 7685 jumpDrawablesToCurrentState(); 7686 } 7687 7688 /** 7689 * This is called when the view is detached from a window. At this point it 7690 * no longer has a surface for drawing. 7691 * 7692 * @see #onAttachedToWindow() 7693 */ 7694 protected void onDetachedFromWindow() { 7695 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 7696 7697 removeUnsetPressCallback(); 7698 removeLongPressCallback(); 7699 removePerformClickCallback(); 7700 7701 destroyDrawingCache(); 7702 7703 if (mHardwareLayer != null) { 7704 mHardwareLayer.destroy(); 7705 mHardwareLayer = null; 7706 } 7707 7708 if (mDisplayList != null) { 7709 mDisplayList.invalidate(); 7710 } 7711 7712 if (mAttachInfo != null) { 7713 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this); 7714 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_RECT_MSG, this); 7715 } 7716 7717 mCurrentAnimation = null; 7718 } 7719 7720 /** 7721 * @return The number of times this view has been attached to a window 7722 */ 7723 protected int getWindowAttachCount() { 7724 return mWindowAttachCount; 7725 } 7726 7727 /** 7728 * Retrieve a unique token identifying the window this view is attached to. 7729 * @return Return the window's token for use in 7730 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 7731 */ 7732 public IBinder getWindowToken() { 7733 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 7734 } 7735 7736 /** 7737 * Retrieve a unique token identifying the top-level "real" window of 7738 * the window that this view is attached to. That is, this is like 7739 * {@link #getWindowToken}, except if the window this view in is a panel 7740 * window (attached to another containing window), then the token of 7741 * the containing window is returned instead. 7742 * 7743 * @return Returns the associated window token, either 7744 * {@link #getWindowToken()} or the containing window's token. 7745 */ 7746 public IBinder getApplicationWindowToken() { 7747 AttachInfo ai = mAttachInfo; 7748 if (ai != null) { 7749 IBinder appWindowToken = ai.mPanelParentWindowToken; 7750 if (appWindowToken == null) { 7751 appWindowToken = ai.mWindowToken; 7752 } 7753 return appWindowToken; 7754 } 7755 return null; 7756 } 7757 7758 /** 7759 * Retrieve private session object this view hierarchy is using to 7760 * communicate with the window manager. 7761 * @return the session object to communicate with the window manager 7762 */ 7763 /*package*/ IWindowSession getWindowSession() { 7764 return mAttachInfo != null ? mAttachInfo.mSession : null; 7765 } 7766 7767 /** 7768 * @param info the {@link android.view.View.AttachInfo} to associated with 7769 * this view 7770 */ 7771 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 7772 //System.out.println("Attached! " + this); 7773 mAttachInfo = info; 7774 mWindowAttachCount++; 7775 // We will need to evaluate the drawable state at least once. 7776 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 7777 if (mFloatingTreeObserver != null) { 7778 info.mTreeObserver.merge(mFloatingTreeObserver); 7779 mFloatingTreeObserver = null; 7780 } 7781 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 7782 mAttachInfo.mScrollContainers.add(this); 7783 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 7784 } 7785 performCollectViewAttributes(visibility); 7786 onAttachedToWindow(); 7787 int vis = info.mWindowVisibility; 7788 if (vis != GONE) { 7789 onWindowVisibilityChanged(vis); 7790 } 7791 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 7792 // If nobody has evaluated the drawable state yet, then do it now. 7793 refreshDrawableState(); 7794 } 7795 } 7796 7797 void dispatchDetachedFromWindow() { 7798 //System.out.println("Detached! " + this); 7799 AttachInfo info = mAttachInfo; 7800 if (info != null) { 7801 int vis = info.mWindowVisibility; 7802 if (vis != GONE) { 7803 onWindowVisibilityChanged(GONE); 7804 } 7805 } 7806 7807 onDetachedFromWindow(); 7808 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 7809 mAttachInfo.mScrollContainers.remove(this); 7810 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 7811 } 7812 mAttachInfo = null; 7813 } 7814 7815 /** 7816 * Store this view hierarchy's frozen state into the given container. 7817 * 7818 * @param container The SparseArray in which to save the view's state. 7819 * 7820 * @see #restoreHierarchyState 7821 * @see #dispatchSaveInstanceState 7822 * @see #onSaveInstanceState 7823 */ 7824 public void saveHierarchyState(SparseArray<Parcelable> container) { 7825 dispatchSaveInstanceState(container); 7826 } 7827 7828 /** 7829 * Called by {@link #saveHierarchyState} to store the state for this view and its children. 7830 * May be overridden to modify how freezing happens to a view's children; for example, some 7831 * views may want to not store state for their children. 7832 * 7833 * @param container The SparseArray in which to save the view's state. 7834 * 7835 * @see #dispatchRestoreInstanceState 7836 * @see #saveHierarchyState 7837 * @see #onSaveInstanceState 7838 */ 7839 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 7840 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 7841 mPrivateFlags &= ~SAVE_STATE_CALLED; 7842 Parcelable state = onSaveInstanceState(); 7843 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 7844 throw new IllegalStateException( 7845 "Derived class did not call super.onSaveInstanceState()"); 7846 } 7847 if (state != null) { 7848 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 7849 // + ": " + state); 7850 container.put(mID, state); 7851 } 7852 } 7853 } 7854 7855 /** 7856 * Hook allowing a view to generate a representation of its internal state 7857 * that can later be used to create a new instance with that same state. 7858 * This state should only contain information that is not persistent or can 7859 * not be reconstructed later. For example, you will never store your 7860 * current position on screen because that will be computed again when a 7861 * new instance of the view is placed in its view hierarchy. 7862 * <p> 7863 * Some examples of things you may store here: the current cursor position 7864 * in a text view (but usually not the text itself since that is stored in a 7865 * content provider or other persistent storage), the currently selected 7866 * item in a list view. 7867 * 7868 * @return Returns a Parcelable object containing the view's current dynamic 7869 * state, or null if there is nothing interesting to save. The 7870 * default implementation returns null. 7871 * @see #onRestoreInstanceState 7872 * @see #saveHierarchyState 7873 * @see #dispatchSaveInstanceState 7874 * @see #setSaveEnabled(boolean) 7875 */ 7876 protected Parcelable onSaveInstanceState() { 7877 mPrivateFlags |= SAVE_STATE_CALLED; 7878 return BaseSavedState.EMPTY_STATE; 7879 } 7880 7881 /** 7882 * Restore this view hierarchy's frozen state from the given container. 7883 * 7884 * @param container The SparseArray which holds previously frozen states. 7885 * 7886 * @see #saveHierarchyState 7887 * @see #dispatchRestoreInstanceState 7888 * @see #onRestoreInstanceState 7889 */ 7890 public void restoreHierarchyState(SparseArray<Parcelable> container) { 7891 dispatchRestoreInstanceState(container); 7892 } 7893 7894 /** 7895 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its 7896 * children. May be overridden to modify how restoreing happens to a view's children; for 7897 * example, some views may want to not store state for their children. 7898 * 7899 * @param container The SparseArray which holds previously saved state. 7900 * 7901 * @see #dispatchSaveInstanceState 7902 * @see #restoreHierarchyState 7903 * @see #onRestoreInstanceState 7904 */ 7905 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 7906 if (mID != NO_ID) { 7907 Parcelable state = container.get(mID); 7908 if (state != null) { 7909 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 7910 // + ": " + state); 7911 mPrivateFlags &= ~SAVE_STATE_CALLED; 7912 onRestoreInstanceState(state); 7913 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 7914 throw new IllegalStateException( 7915 "Derived class did not call super.onRestoreInstanceState()"); 7916 } 7917 } 7918 } 7919 } 7920 7921 /** 7922 * Hook allowing a view to re-apply a representation of its internal state that had previously 7923 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 7924 * null state. 7925 * 7926 * @param state The frozen state that had previously been returned by 7927 * {@link #onSaveInstanceState}. 7928 * 7929 * @see #onSaveInstanceState 7930 * @see #restoreHierarchyState 7931 * @see #dispatchRestoreInstanceState 7932 */ 7933 protected void onRestoreInstanceState(Parcelable state) { 7934 mPrivateFlags |= SAVE_STATE_CALLED; 7935 if (state != BaseSavedState.EMPTY_STATE && state != null) { 7936 throw new IllegalArgumentException("Wrong state class, expecting View State but " 7937 + "received " + state.getClass().toString() + " instead. This usually happens " 7938 + "when two views of different type have the same id in the same hierarchy. " 7939 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 7940 + "other views do not use the same id."); 7941 } 7942 } 7943 7944 /** 7945 * <p>Return the time at which the drawing of the view hierarchy started.</p> 7946 * 7947 * @return the drawing start time in milliseconds 7948 */ 7949 public long getDrawingTime() { 7950 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 7951 } 7952 7953 /** 7954 * <p>Enables or disables the duplication of the parent's state into this view. When 7955 * duplication is enabled, this view gets its drawable state from its parent rather 7956 * than from its own internal properties.</p> 7957 * 7958 * <p>Note: in the current implementation, setting this property to true after the 7959 * view was added to a ViewGroup might have no effect at all. This property should 7960 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 7961 * 7962 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 7963 * property is enabled, an exception will be thrown.</p> 7964 * 7965 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 7966 * parent, these states should not be affected by this method.</p> 7967 * 7968 * @param enabled True to enable duplication of the parent's drawable state, false 7969 * to disable it. 7970 * 7971 * @see #getDrawableState() 7972 * @see #isDuplicateParentStateEnabled() 7973 */ 7974 public void setDuplicateParentStateEnabled(boolean enabled) { 7975 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 7976 } 7977 7978 /** 7979 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 7980 * 7981 * @return True if this view's drawable state is duplicated from the parent, 7982 * false otherwise 7983 * 7984 * @see #getDrawableState() 7985 * @see #setDuplicateParentStateEnabled(boolean) 7986 */ 7987 public boolean isDuplicateParentStateEnabled() { 7988 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 7989 } 7990 7991 /** 7992 * <p>Specifies the type of layer backing this view. The layer can be 7993 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 7994 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 7995 * 7996 * <p>A layer is associated with an optional {@link android.graphics.Paint} 7997 * instance that controls how the layer is composed on screen. The following 7998 * properties of the paint are taken into account when composing the layer:</p> 7999 * <ul> 8000 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 8001 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 8002 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 8003 * </ul> 8004 * 8005 * <p>If this view has an alpha value set to < 1.0 by calling 8006 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 8007 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 8008 * equivalent to setting a hardware layer on this view and providing a paint with 8009 * the desired alpha value.<p> 8010 * 8011 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 8012 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 8013 * for more information on when and how to use layers.</p> 8014 * 8015 * @param layerType The ype of layer to use with this view, must be one of 8016 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 8017 * {@link #LAYER_TYPE_HARDWARE} 8018 * @param paint The paint used to compose the layer. This argument is optional 8019 * and can be null. It is ignored when the layer type is 8020 * {@link #LAYER_TYPE_NONE} 8021 * 8022 * @see #getLayerType() 8023 * @see #LAYER_TYPE_NONE 8024 * @see #LAYER_TYPE_SOFTWARE 8025 * @see #LAYER_TYPE_HARDWARE 8026 * @see #setAlpha(float) 8027 * 8028 * @attr ref android.R.styleable#View_layerType 8029 */ 8030 public void setLayerType(int layerType, Paint paint) { 8031 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 8032 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 8033 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 8034 } 8035 8036 if (layerType == mLayerType) { 8037 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 8038 mLayerPaint = paint == null ? new Paint() : paint; 8039 invalidateParentCaches(); 8040 invalidate(true); 8041 } 8042 return; 8043 } 8044 8045 // Destroy any previous software drawing cache if needed 8046 switch (mLayerType) { 8047 case LAYER_TYPE_SOFTWARE: 8048 if (mDrawingCache != null) { 8049 mDrawingCache.recycle(); 8050 mDrawingCache = null; 8051 } 8052 8053 if (mUnscaledDrawingCache != null) { 8054 mUnscaledDrawingCache.recycle(); 8055 mUnscaledDrawingCache = null; 8056 } 8057 break; 8058 case LAYER_TYPE_HARDWARE: 8059 if (mHardwareLayer != null) { 8060 mHardwareLayer.destroy(); 8061 mHardwareLayer = null; 8062 } 8063 break; 8064 default: 8065 break; 8066 } 8067 8068 mLayerType = layerType; 8069 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : (paint == null ? new Paint() : paint); 8070 8071 invalidateParentCaches(); 8072 invalidate(true); 8073 } 8074 8075 /** 8076 * Indicates what type of layer is currently associated with this view. By default 8077 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 8078 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 8079 * for more information on the different types of layers. 8080 * 8081 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 8082 * {@link #LAYER_TYPE_HARDWARE} 8083 * 8084 * @see #setLayerType(int, android.graphics.Paint) 8085 * @see #LAYER_TYPE_NONE 8086 * @see #LAYER_TYPE_SOFTWARE 8087 * @see #LAYER_TYPE_HARDWARE 8088 */ 8089 public int getLayerType() { 8090 return mLayerType; 8091 } 8092 8093 /** 8094 * <p>Returns a hardware layer that can be used to draw this view again 8095 * without executing its draw method.</p> 8096 * 8097 * @return A HardwareLayer ready to render, or null if an error occurred. 8098 */ 8099 HardwareLayer getHardwareLayer() { 8100 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) { 8101 return null; 8102 } 8103 8104 final int width = mRight - mLeft; 8105 final int height = mBottom - mTop; 8106 8107 if (width == 0 || height == 0) { 8108 return null; 8109 } 8110 8111 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 8112 if (mHardwareLayer == null) { 8113 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 8114 width, height, isOpaque()); 8115 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 8116 mHardwareLayer.resize(width, height); 8117 } 8118 8119 Canvas currentCanvas = mAttachInfo.mHardwareCanvas; 8120 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas); 8121 mAttachInfo.mHardwareCanvas = canvas; 8122 try { 8123 canvas.setViewport(width, height); 8124 // TODO: We should pass the dirty rect 8125 canvas.onPreDraw(null); 8126 8127 computeScroll(); 8128 canvas.translate(-mScrollX, -mScrollY); 8129 8130 final int restoreCount = canvas.save(); 8131 8132 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 8133 8134 // Fast path for layouts with no backgrounds 8135 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 8136 mPrivateFlags &= ~DIRTY_MASK; 8137 dispatchDraw(canvas); 8138 } else { 8139 draw(canvas); 8140 } 8141 8142 canvas.restoreToCount(restoreCount); 8143 } finally { 8144 canvas.onPostDraw(); 8145 mHardwareLayer.end(currentCanvas); 8146 mAttachInfo.mHardwareCanvas = currentCanvas; 8147 } 8148 } 8149 8150 return mHardwareLayer; 8151 } 8152 8153 /** 8154 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 8155 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 8156 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 8157 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 8158 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 8159 * null.</p> 8160 * 8161 * <p>Enabling the drawing cache is similar to 8162 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 8163 * acceleration is turned off. When hardware acceleration is turned on, enabling the 8164 * drawing cache has no effect on rendering because the system uses a different mechanism 8165 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 8166 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 8167 * for information on how to enable software and hardware layers.</p> 8168 * 8169 * <p>This API can be used to manually generate 8170 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 8171 * {@link #getDrawingCache()}.</p> 8172 * 8173 * @param enabled true to enable the drawing cache, false otherwise 8174 * 8175 * @see #isDrawingCacheEnabled() 8176 * @see #getDrawingCache() 8177 * @see #buildDrawingCache() 8178 * @see #setLayerType(int, android.graphics.Paint) 8179 */ 8180 public void setDrawingCacheEnabled(boolean enabled) { 8181 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 8182 } 8183 8184 /** 8185 * <p>Indicates whether the drawing cache is enabled for this view.</p> 8186 * 8187 * @return true if the drawing cache is enabled 8188 * 8189 * @see #setDrawingCacheEnabled(boolean) 8190 * @see #getDrawingCache() 8191 */ 8192 @ViewDebug.ExportedProperty(category = "drawing") 8193 public boolean isDrawingCacheEnabled() { 8194 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 8195 } 8196 8197 /** 8198 * Debugging utility which recursively outputs the dirty state of a view and its 8199 * descendants. 8200 * 8201 * @hide 8202 */ 8203 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 8204 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) + 8205 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" + 8206 (mPrivateFlags & View.DRAWING_CACHE_VALID) + 8207 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")"); 8208 if (clear) { 8209 mPrivateFlags &= clearMask; 8210 } 8211 if (this instanceof ViewGroup) { 8212 ViewGroup parent = (ViewGroup) this; 8213 final int count = parent.getChildCount(); 8214 for (int i = 0; i < count; i++) { 8215 final View child = parent.getChildAt(i); 8216 child.outputDirtyFlags(indent + " ", clear, clearMask); 8217 } 8218 } 8219 } 8220 8221 /** 8222 * This method is used by ViewGroup to cause its children to restore or recreate their 8223 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 8224 * to recreate its own display list, which would happen if it went through the normal 8225 * draw/dispatchDraw mechanisms. 8226 * 8227 * @hide 8228 */ 8229 protected void dispatchGetDisplayList() {} 8230 8231 /** 8232 * <p>Returns a display list that can be used to draw this view again 8233 * without executing its draw method.</p> 8234 * 8235 * @return A DisplayList ready to replay, or null if caching is not enabled. 8236 * 8237 * @hide 8238 */ 8239 public DisplayList getDisplayList() { 8240 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) { 8241 return null; 8242 } 8243 8244 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || 8245 mDisplayList == null || !mDisplayList.isValid() || 8246 mRecreateDisplayList)) { 8247 // Don't need to recreate the display list, just need to tell our 8248 // children to restore/recreate theirs 8249 if (mDisplayList != null && mDisplayList.isValid() && 8250 !mRecreateDisplayList) { 8251 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 8252 mPrivateFlags &= ~DIRTY_MASK; 8253 dispatchGetDisplayList(); 8254 8255 return mDisplayList; 8256 } 8257 8258 // If we got here, we're recreating it. Mark it as such to ensure that 8259 // we copy in child display lists into ours in drawChild() 8260 mRecreateDisplayList = true; 8261 if (mDisplayList == null) { 8262 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(this); 8263 // If we're creating a new display list, make sure our parent gets invalidated 8264 // since they will need to recreate their display list to account for this 8265 // new child display list. 8266 invalidateParentCaches(); 8267 } 8268 8269 final HardwareCanvas canvas = mDisplayList.start(); 8270 try { 8271 int width = mRight - mLeft; 8272 int height = mBottom - mTop; 8273 8274 canvas.setViewport(width, height); 8275 // The dirty rect should always be null for a display list 8276 canvas.onPreDraw(null); 8277 8278 final int restoreCount = canvas.save(); 8279 8280 computeScroll(); 8281 canvas.translate(-mScrollX, -mScrollY); 8282 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 8283 8284 // Fast path for layouts with no backgrounds 8285 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 8286 mPrivateFlags &= ~DIRTY_MASK; 8287 dispatchDraw(canvas); 8288 } else { 8289 draw(canvas); 8290 } 8291 8292 canvas.restoreToCount(restoreCount); 8293 } finally { 8294 canvas.onPostDraw(); 8295 8296 mDisplayList.end(); 8297 } 8298 } else { 8299 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 8300 mPrivateFlags &= ~DIRTY_MASK; 8301 } 8302 8303 return mDisplayList; 8304 } 8305 8306 /** 8307 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 8308 * 8309 * @return A non-scaled bitmap representing this view or null if cache is disabled. 8310 * 8311 * @see #getDrawingCache(boolean) 8312 */ 8313 public Bitmap getDrawingCache() { 8314 return getDrawingCache(false); 8315 } 8316 8317 /** 8318 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 8319 * is null when caching is disabled. If caching is enabled and the cache is not ready, 8320 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 8321 * draw from the cache when the cache is enabled. To benefit from the cache, you must 8322 * request the drawing cache by calling this method and draw it on screen if the 8323 * returned bitmap is not null.</p> 8324 * 8325 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 8326 * this method will create a bitmap of the same size as this view. Because this bitmap 8327 * will be drawn scaled by the parent ViewGroup, the result on screen might show 8328 * scaling artifacts. To avoid such artifacts, you should call this method by setting 8329 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 8330 * size than the view. This implies that your application must be able to handle this 8331 * size.</p> 8332 * 8333 * @param autoScale Indicates whether the generated bitmap should be scaled based on 8334 * the current density of the screen when the application is in compatibility 8335 * mode. 8336 * 8337 * @return A bitmap representing this view or null if cache is disabled. 8338 * 8339 * @see #setDrawingCacheEnabled(boolean) 8340 * @see #isDrawingCacheEnabled() 8341 * @see #buildDrawingCache(boolean) 8342 * @see #destroyDrawingCache() 8343 */ 8344 public Bitmap getDrawingCache(boolean autoScale) { 8345 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 8346 return null; 8347 } 8348 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 8349 buildDrawingCache(autoScale); 8350 } 8351 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 8352 } 8353 8354 /** 8355 * <p>Frees the resources used by the drawing cache. If you call 8356 * {@link #buildDrawingCache()} manually without calling 8357 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 8358 * should cleanup the cache with this method afterwards.</p> 8359 * 8360 * @see #setDrawingCacheEnabled(boolean) 8361 * @see #buildDrawingCache() 8362 * @see #getDrawingCache() 8363 */ 8364 public void destroyDrawingCache() { 8365 if (mDrawingCache != null) { 8366 mDrawingCache.recycle(); 8367 mDrawingCache = null; 8368 } 8369 if (mUnscaledDrawingCache != null) { 8370 mUnscaledDrawingCache.recycle(); 8371 mUnscaledDrawingCache = null; 8372 } 8373 } 8374 8375 /** 8376 * Setting a solid background color for the drawing cache's bitmaps will improve 8377 * perfromance and memory usage. Note, though that this should only be used if this 8378 * view will always be drawn on top of a solid color. 8379 * 8380 * @param color The background color to use for the drawing cache's bitmap 8381 * 8382 * @see #setDrawingCacheEnabled(boolean) 8383 * @see #buildDrawingCache() 8384 * @see #getDrawingCache() 8385 */ 8386 public void setDrawingCacheBackgroundColor(int color) { 8387 if (color != mDrawingCacheBackgroundColor) { 8388 mDrawingCacheBackgroundColor = color; 8389 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8390 } 8391 } 8392 8393 /** 8394 * @see #setDrawingCacheBackgroundColor(int) 8395 * 8396 * @return The background color to used for the drawing cache's bitmap 8397 */ 8398 public int getDrawingCacheBackgroundColor() { 8399 return mDrawingCacheBackgroundColor; 8400 } 8401 8402 /** 8403 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 8404 * 8405 * @see #buildDrawingCache(boolean) 8406 */ 8407 public void buildDrawingCache() { 8408 buildDrawingCache(false); 8409 } 8410 8411 /** 8412 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 8413 * 8414 * <p>If you call {@link #buildDrawingCache()} manually without calling 8415 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 8416 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 8417 * 8418 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 8419 * this method will create a bitmap of the same size as this view. Because this bitmap 8420 * will be drawn scaled by the parent ViewGroup, the result on screen might show 8421 * scaling artifacts. To avoid such artifacts, you should call this method by setting 8422 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 8423 * size than the view. This implies that your application must be able to handle this 8424 * size.</p> 8425 * 8426 * <p>You should avoid calling this method when hardware acceleration is enabled. If 8427 * you do not need the drawing cache bitmap, calling this method will increase memory 8428 * usage and cause the view to be rendered in software once, thus negatively impacting 8429 * performance.</p> 8430 * 8431 * @see #getDrawingCache() 8432 * @see #destroyDrawingCache() 8433 */ 8434 public void buildDrawingCache(boolean autoScale) { 8435 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 8436 mDrawingCache == null : mUnscaledDrawingCache == null)) { 8437 8438 if (ViewDebug.TRACE_HIERARCHY) { 8439 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 8440 } 8441 8442 int width = mRight - mLeft; 8443 int height = mBottom - mTop; 8444 8445 final AttachInfo attachInfo = mAttachInfo; 8446 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 8447 8448 if (autoScale && scalingRequired) { 8449 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 8450 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 8451 } 8452 8453 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 8454 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 8455 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 8456 8457 if (width <= 0 || height <= 0 || 8458 // Projected bitmap size in bytes 8459 (width * height * (opaque && !use32BitCache ? 2 : 4) > 8460 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 8461 destroyDrawingCache(); 8462 return; 8463 } 8464 8465 boolean clear = true; 8466 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 8467 8468 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 8469 Bitmap.Config quality; 8470 if (!opaque) { 8471 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 8472 case DRAWING_CACHE_QUALITY_AUTO: 8473 quality = Bitmap.Config.ARGB_8888; 8474 break; 8475 case DRAWING_CACHE_QUALITY_LOW: 8476 quality = Bitmap.Config.ARGB_4444; 8477 break; 8478 case DRAWING_CACHE_QUALITY_HIGH: 8479 quality = Bitmap.Config.ARGB_8888; 8480 break; 8481 default: 8482 quality = Bitmap.Config.ARGB_8888; 8483 break; 8484 } 8485 } else { 8486 // Optimization for translucent windows 8487 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 8488 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 8489 } 8490 8491 // Try to cleanup memory 8492 if (bitmap != null) bitmap.recycle(); 8493 8494 try { 8495 bitmap = Bitmap.createBitmap(width, height, quality); 8496 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 8497 if (autoScale) { 8498 mDrawingCache = bitmap; 8499 } else { 8500 mUnscaledDrawingCache = bitmap; 8501 } 8502 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 8503 } catch (OutOfMemoryError e) { 8504 // If there is not enough memory to create the bitmap cache, just 8505 // ignore the issue as bitmap caches are not required to draw the 8506 // view hierarchy 8507 if (autoScale) { 8508 mDrawingCache = null; 8509 } else { 8510 mUnscaledDrawingCache = null; 8511 } 8512 return; 8513 } 8514 8515 clear = drawingCacheBackgroundColor != 0; 8516 } 8517 8518 Canvas canvas; 8519 if (attachInfo != null) { 8520 canvas = attachInfo.mCanvas; 8521 if (canvas == null) { 8522 canvas = new Canvas(); 8523 } 8524 canvas.setBitmap(bitmap); 8525 // Temporarily clobber the cached Canvas in case one of our children 8526 // is also using a drawing cache. Without this, the children would 8527 // steal the canvas by attaching their own bitmap to it and bad, bad 8528 // thing would happen (invisible views, corrupted drawings, etc.) 8529 attachInfo.mCanvas = null; 8530 } else { 8531 // This case should hopefully never or seldom happen 8532 canvas = new Canvas(bitmap); 8533 } 8534 8535 if (clear) { 8536 bitmap.eraseColor(drawingCacheBackgroundColor); 8537 } 8538 8539 computeScroll(); 8540 final int restoreCount = canvas.save(); 8541 8542 if (autoScale && scalingRequired) { 8543 final float scale = attachInfo.mApplicationScale; 8544 canvas.scale(scale, scale); 8545 } 8546 8547 canvas.translate(-mScrollX, -mScrollY); 8548 8549 mPrivateFlags |= DRAWN; 8550 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 8551 mLayerType != LAYER_TYPE_NONE) { 8552 mPrivateFlags |= DRAWING_CACHE_VALID; 8553 } 8554 8555 // Fast path for layouts with no backgrounds 8556 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 8557 if (ViewDebug.TRACE_HIERARCHY) { 8558 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 8559 } 8560 mPrivateFlags &= ~DIRTY_MASK; 8561 dispatchDraw(canvas); 8562 } else { 8563 draw(canvas); 8564 } 8565 8566 canvas.restoreToCount(restoreCount); 8567 8568 if (attachInfo != null) { 8569 // Restore the cached Canvas for our siblings 8570 attachInfo.mCanvas = canvas; 8571 } 8572 } 8573 } 8574 8575 /** 8576 * Create a snapshot of the view into a bitmap. We should probably make 8577 * some form of this public, but should think about the API. 8578 */ 8579 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 8580 int width = mRight - mLeft; 8581 int height = mBottom - mTop; 8582 8583 final AttachInfo attachInfo = mAttachInfo; 8584 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 8585 width = (int) ((width * scale) + 0.5f); 8586 height = (int) ((height * scale) + 0.5f); 8587 8588 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 8589 if (bitmap == null) { 8590 throw new OutOfMemoryError(); 8591 } 8592 8593 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 8594 8595 Canvas canvas; 8596 if (attachInfo != null) { 8597 canvas = attachInfo.mCanvas; 8598 if (canvas == null) { 8599 canvas = new Canvas(); 8600 } 8601 canvas.setBitmap(bitmap); 8602 // Temporarily clobber the cached Canvas in case one of our children 8603 // is also using a drawing cache. Without this, the children would 8604 // steal the canvas by attaching their own bitmap to it and bad, bad 8605 // things would happen (invisible views, corrupted drawings, etc.) 8606 attachInfo.mCanvas = null; 8607 } else { 8608 // This case should hopefully never or seldom happen 8609 canvas = new Canvas(bitmap); 8610 } 8611 8612 if ((backgroundColor & 0xff000000) != 0) { 8613 bitmap.eraseColor(backgroundColor); 8614 } 8615 8616 computeScroll(); 8617 final int restoreCount = canvas.save(); 8618 canvas.scale(scale, scale); 8619 canvas.translate(-mScrollX, -mScrollY); 8620 8621 // Temporarily remove the dirty mask 8622 int flags = mPrivateFlags; 8623 mPrivateFlags &= ~DIRTY_MASK; 8624 8625 // Fast path for layouts with no backgrounds 8626 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 8627 dispatchDraw(canvas); 8628 } else { 8629 draw(canvas); 8630 } 8631 8632 mPrivateFlags = flags; 8633 8634 canvas.restoreToCount(restoreCount); 8635 8636 if (attachInfo != null) { 8637 // Restore the cached Canvas for our siblings 8638 attachInfo.mCanvas = canvas; 8639 } 8640 8641 return bitmap; 8642 } 8643 8644 /** 8645 * Indicates whether this View is currently in edit mode. A View is usually 8646 * in edit mode when displayed within a developer tool. For instance, if 8647 * this View is being drawn by a visual user interface builder, this method 8648 * should return true. 8649 * 8650 * Subclasses should check the return value of this method to provide 8651 * different behaviors if their normal behavior might interfere with the 8652 * host environment. For instance: the class spawns a thread in its 8653 * constructor, the drawing code relies on device-specific features, etc. 8654 * 8655 * This method is usually checked in the drawing code of custom widgets. 8656 * 8657 * @return True if this View is in edit mode, false otherwise. 8658 */ 8659 public boolean isInEditMode() { 8660 return false; 8661 } 8662 8663 /** 8664 * If the View draws content inside its padding and enables fading edges, 8665 * it needs to support padding offsets. Padding offsets are added to the 8666 * fading edges to extend the length of the fade so that it covers pixels 8667 * drawn inside the padding. 8668 * 8669 * Subclasses of this class should override this method if they need 8670 * to draw content inside the padding. 8671 * 8672 * @return True if padding offset must be applied, false otherwise. 8673 * 8674 * @see #getLeftPaddingOffset() 8675 * @see #getRightPaddingOffset() 8676 * @see #getTopPaddingOffset() 8677 * @see #getBottomPaddingOffset() 8678 * 8679 * @since CURRENT 8680 */ 8681 protected boolean isPaddingOffsetRequired() { 8682 return false; 8683 } 8684 8685 /** 8686 * Amount by which to extend the left fading region. Called only when 8687 * {@link #isPaddingOffsetRequired()} returns true. 8688 * 8689 * @return The left padding offset in pixels. 8690 * 8691 * @see #isPaddingOffsetRequired() 8692 * 8693 * @since CURRENT 8694 */ 8695 protected int getLeftPaddingOffset() { 8696 return 0; 8697 } 8698 8699 /** 8700 * Amount by which to extend the right fading region. Called only when 8701 * {@link #isPaddingOffsetRequired()} returns true. 8702 * 8703 * @return The right padding offset in pixels. 8704 * 8705 * @see #isPaddingOffsetRequired() 8706 * 8707 * @since CURRENT 8708 */ 8709 protected int getRightPaddingOffset() { 8710 return 0; 8711 } 8712 8713 /** 8714 * Amount by which to extend the top fading region. Called only when 8715 * {@link #isPaddingOffsetRequired()} returns true. 8716 * 8717 * @return The top padding offset in pixels. 8718 * 8719 * @see #isPaddingOffsetRequired() 8720 * 8721 * @since CURRENT 8722 */ 8723 protected int getTopPaddingOffset() { 8724 return 0; 8725 } 8726 8727 /** 8728 * Amount by which to extend the bottom fading region. Called only when 8729 * {@link #isPaddingOffsetRequired()} returns true. 8730 * 8731 * @return The bottom padding offset in pixels. 8732 * 8733 * @see #isPaddingOffsetRequired() 8734 * 8735 * @since CURRENT 8736 */ 8737 protected int getBottomPaddingOffset() { 8738 return 0; 8739 } 8740 8741 /** 8742 * <p>Indicates whether this view is attached to an hardware accelerated 8743 * window or not.</p> 8744 * 8745 * <p>Even if this method returns true, it does not mean that every call 8746 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 8747 * accelerated {@link android.graphics.Canvas}. For instance, if this view 8748 * is drawn onto an offscren {@link android.graphics.Bitmap} and its 8749 * window is hardware accelerated, 8750 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 8751 * return false, and this method will return true.</p> 8752 * 8753 * @return True if the view is attached to a window and the window is 8754 * hardware accelerated; false in any other case. 8755 */ 8756 public boolean isHardwareAccelerated() { 8757 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 8758 } 8759 8760 /** 8761 * Manually render this view (and all of its children) to the given Canvas. 8762 * The view must have already done a full layout before this function is 8763 * called. When implementing a view, implement {@link #onDraw} instead of 8764 * overriding this method. If you do need to override this method, call 8765 * the superclass version. 8766 * 8767 * @param canvas The Canvas to which the View is rendered. 8768 */ 8769 public void draw(Canvas canvas) { 8770 if (ViewDebug.TRACE_HIERARCHY) { 8771 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 8772 } 8773 8774 final int privateFlags = mPrivateFlags; 8775 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 8776 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 8777 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 8778 8779 /* 8780 * Draw traversal performs several drawing steps which must be executed 8781 * in the appropriate order: 8782 * 8783 * 1. Draw the background 8784 * 2. If necessary, save the canvas' layers to prepare for fading 8785 * 3. Draw view's content 8786 * 4. Draw children 8787 * 5. If necessary, draw the fading edges and restore layers 8788 * 6. Draw decorations (scrollbars for instance) 8789 */ 8790 8791 // Step 1, draw the background, if needed 8792 int saveCount; 8793 8794 if (!dirtyOpaque) { 8795 final Drawable background = mBGDrawable; 8796 if (background != null) { 8797 final int scrollX = mScrollX; 8798 final int scrollY = mScrollY; 8799 8800 if (mBackgroundSizeChanged) { 8801 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 8802 mBackgroundSizeChanged = false; 8803 } 8804 8805 if ((scrollX | scrollY) == 0) { 8806 background.draw(canvas); 8807 } else { 8808 canvas.translate(scrollX, scrollY); 8809 background.draw(canvas); 8810 canvas.translate(-scrollX, -scrollY); 8811 } 8812 } 8813 } 8814 8815 // skip step 2 & 5 if possible (common case) 8816 final int viewFlags = mViewFlags; 8817 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 8818 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 8819 if (!verticalEdges && !horizontalEdges) { 8820 // Step 3, draw the content 8821 if (!dirtyOpaque) onDraw(canvas); 8822 8823 // Step 4, draw the children 8824 dispatchDraw(canvas); 8825 8826 // Step 6, draw decorations (scrollbars) 8827 onDrawScrollBars(canvas); 8828 8829 // we're done... 8830 return; 8831 } 8832 8833 /* 8834 * Here we do the full fledged routine... 8835 * (this is an uncommon case where speed matters less, 8836 * this is why we repeat some of the tests that have been 8837 * done above) 8838 */ 8839 8840 boolean drawTop = false; 8841 boolean drawBottom = false; 8842 boolean drawLeft = false; 8843 boolean drawRight = false; 8844 8845 float topFadeStrength = 0.0f; 8846 float bottomFadeStrength = 0.0f; 8847 float leftFadeStrength = 0.0f; 8848 float rightFadeStrength = 0.0f; 8849 8850 // Step 2, save the canvas' layers 8851 int paddingLeft = mPaddingLeft; 8852 int paddingTop = mPaddingTop; 8853 8854 final boolean offsetRequired = isPaddingOffsetRequired(); 8855 if (offsetRequired) { 8856 paddingLeft += getLeftPaddingOffset(); 8857 paddingTop += getTopPaddingOffset(); 8858 } 8859 8860 int left = mScrollX + paddingLeft; 8861 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 8862 int top = mScrollY + paddingTop; 8863 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop; 8864 8865 if (offsetRequired) { 8866 right += getRightPaddingOffset(); 8867 bottom += getBottomPaddingOffset(); 8868 } 8869 8870 final ScrollabilityCache scrollabilityCache = mScrollCache; 8871 int length = scrollabilityCache.fadingEdgeLength; 8872 8873 // clip the fade length if top and bottom fades overlap 8874 // overlapping fades produce odd-looking artifacts 8875 if (verticalEdges && (top + length > bottom - length)) { 8876 length = (bottom - top) / 2; 8877 } 8878 8879 // also clip horizontal fades if necessary 8880 if (horizontalEdges && (left + length > right - length)) { 8881 length = (right - left) / 2; 8882 } 8883 8884 if (verticalEdges) { 8885 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 8886 drawTop = topFadeStrength > 0.0f; 8887 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 8888 drawBottom = bottomFadeStrength > 0.0f; 8889 } 8890 8891 if (horizontalEdges) { 8892 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 8893 drawLeft = leftFadeStrength > 0.0f; 8894 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 8895 drawRight = rightFadeStrength > 0.0f; 8896 } 8897 8898 saveCount = canvas.getSaveCount(); 8899 8900 int solidColor = getSolidColor(); 8901 if (solidColor == 0) { 8902 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 8903 8904 if (drawTop) { 8905 canvas.saveLayer(left, top, right, top + length, null, flags); 8906 } 8907 8908 if (drawBottom) { 8909 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 8910 } 8911 8912 if (drawLeft) { 8913 canvas.saveLayer(left, top, left + length, bottom, null, flags); 8914 } 8915 8916 if (drawRight) { 8917 canvas.saveLayer(right - length, top, right, bottom, null, flags); 8918 } 8919 } else { 8920 scrollabilityCache.setFadeColor(solidColor); 8921 } 8922 8923 // Step 3, draw the content 8924 if (!dirtyOpaque) onDraw(canvas); 8925 8926 // Step 4, draw the children 8927 dispatchDraw(canvas); 8928 8929 // Step 5, draw the fade effect and restore layers 8930 final Paint p = scrollabilityCache.paint; 8931 final Matrix matrix = scrollabilityCache.matrix; 8932 final Shader fade = scrollabilityCache.shader; 8933 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 8934 8935 if (drawTop) { 8936 matrix.setScale(1, fadeHeight * topFadeStrength); 8937 matrix.postTranslate(left, top); 8938 fade.setLocalMatrix(matrix); 8939 canvas.drawRect(left, top, right, top + length, p); 8940 } 8941 8942 if (drawBottom) { 8943 matrix.setScale(1, fadeHeight * bottomFadeStrength); 8944 matrix.postRotate(180); 8945 matrix.postTranslate(left, bottom); 8946 fade.setLocalMatrix(matrix); 8947 canvas.drawRect(left, bottom - length, right, bottom, p); 8948 } 8949 8950 if (drawLeft) { 8951 matrix.setScale(1, fadeHeight * leftFadeStrength); 8952 matrix.postRotate(-90); 8953 matrix.postTranslate(left, top); 8954 fade.setLocalMatrix(matrix); 8955 canvas.drawRect(left, top, left + length, bottom, p); 8956 } 8957 8958 if (drawRight) { 8959 matrix.setScale(1, fadeHeight * rightFadeStrength); 8960 matrix.postRotate(90); 8961 matrix.postTranslate(right, top); 8962 fade.setLocalMatrix(matrix); 8963 canvas.drawRect(right - length, top, right, bottom, p); 8964 } 8965 8966 canvas.restoreToCount(saveCount); 8967 8968 // Step 6, draw decorations (scrollbars) 8969 onDrawScrollBars(canvas); 8970 } 8971 8972 /** 8973 * Override this if your view is known to always be drawn on top of a solid color background, 8974 * and needs to draw fading edges. Returning a non-zero color enables the view system to 8975 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 8976 * should be set to 0xFF. 8977 * 8978 * @see #setVerticalFadingEdgeEnabled 8979 * @see #setHorizontalFadingEdgeEnabled 8980 * 8981 * @return The known solid color background for this view, or 0 if the color may vary 8982 */ 8983 public int getSolidColor() { 8984 return 0; 8985 } 8986 8987 /** 8988 * Build a human readable string representation of the specified view flags. 8989 * 8990 * @param flags the view flags to convert to a string 8991 * @return a String representing the supplied flags 8992 */ 8993 private static String printFlags(int flags) { 8994 String output = ""; 8995 int numFlags = 0; 8996 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 8997 output += "TAKES_FOCUS"; 8998 numFlags++; 8999 } 9000 9001 switch (flags & VISIBILITY_MASK) { 9002 case INVISIBLE: 9003 if (numFlags > 0) { 9004 output += " "; 9005 } 9006 output += "INVISIBLE"; 9007 // USELESS HERE numFlags++; 9008 break; 9009 case GONE: 9010 if (numFlags > 0) { 9011 output += " "; 9012 } 9013 output += "GONE"; 9014 // USELESS HERE numFlags++; 9015 break; 9016 default: 9017 break; 9018 } 9019 return output; 9020 } 9021 9022 /** 9023 * Build a human readable string representation of the specified private 9024 * view flags. 9025 * 9026 * @param privateFlags the private view flags to convert to a string 9027 * @return a String representing the supplied flags 9028 */ 9029 private static String printPrivateFlags(int privateFlags) { 9030 String output = ""; 9031 int numFlags = 0; 9032 9033 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 9034 output += "WANTS_FOCUS"; 9035 numFlags++; 9036 } 9037 9038 if ((privateFlags & FOCUSED) == FOCUSED) { 9039 if (numFlags > 0) { 9040 output += " "; 9041 } 9042 output += "FOCUSED"; 9043 numFlags++; 9044 } 9045 9046 if ((privateFlags & SELECTED) == SELECTED) { 9047 if (numFlags > 0) { 9048 output += " "; 9049 } 9050 output += "SELECTED"; 9051 numFlags++; 9052 } 9053 9054 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 9055 if (numFlags > 0) { 9056 output += " "; 9057 } 9058 output += "IS_ROOT_NAMESPACE"; 9059 numFlags++; 9060 } 9061 9062 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 9063 if (numFlags > 0) { 9064 output += " "; 9065 } 9066 output += "HAS_BOUNDS"; 9067 numFlags++; 9068 } 9069 9070 if ((privateFlags & DRAWN) == DRAWN) { 9071 if (numFlags > 0) { 9072 output += " "; 9073 } 9074 output += "DRAWN"; 9075 // USELESS HERE numFlags++; 9076 } 9077 return output; 9078 } 9079 9080 /** 9081 * <p>Indicates whether or not this view's layout will be requested during 9082 * the next hierarchy layout pass.</p> 9083 * 9084 * @return true if the layout will be forced during next layout pass 9085 */ 9086 public boolean isLayoutRequested() { 9087 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 9088 } 9089 9090 /** 9091 * Assign a size and position to a view and all of its 9092 * descendants 9093 * 9094 * <p>This is the second phase of the layout mechanism. 9095 * (The first is measuring). In this phase, each parent calls 9096 * layout on all of its children to position them. 9097 * This is typically done using the child measurements 9098 * that were stored in the measure pass().</p> 9099 * 9100 * <p>Derived classes should not override this method. 9101 * Derived classes with children should override 9102 * onLayout. In that method, they should 9103 * call layout on each of their children.</p> 9104 * 9105 * @param l Left position, relative to parent 9106 * @param t Top position, relative to parent 9107 * @param r Right position, relative to parent 9108 * @param b Bottom position, relative to parent 9109 */ 9110 @SuppressWarnings({"unchecked"}) 9111 public void layout(int l, int t, int r, int b) { 9112 int oldL = mLeft; 9113 int oldT = mTop; 9114 int oldB = mBottom; 9115 int oldR = mRight; 9116 boolean changed = setFrame(l, t, r, b); 9117 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 9118 if (ViewDebug.TRACE_HIERARCHY) { 9119 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 9120 } 9121 9122 onLayout(changed, l, t, r, b); 9123 mPrivateFlags &= ~LAYOUT_REQUIRED; 9124 9125 if (mOnLayoutChangeListeners != null) { 9126 ArrayList<OnLayoutChangeListener> listenersCopy = 9127 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone(); 9128 int numListeners = listenersCopy.size(); 9129 for (int i = 0; i < numListeners; ++i) { 9130 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 9131 } 9132 } 9133 } 9134 mPrivateFlags &= ~FORCE_LAYOUT; 9135 } 9136 9137 /** 9138 * Called from layout when this view should 9139 * assign a size and position to each of its children. 9140 * 9141 * Derived classes with children should override 9142 * this method and call layout on each of 9143 * their children. 9144 * @param changed This is a new size or position for this view 9145 * @param left Left position, relative to parent 9146 * @param top Top position, relative to parent 9147 * @param right Right position, relative to parent 9148 * @param bottom Bottom position, relative to parent 9149 */ 9150 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 9151 } 9152 9153 /** 9154 * Assign a size and position to this view. 9155 * 9156 * This is called from layout. 9157 * 9158 * @param left Left position, relative to parent 9159 * @param top Top position, relative to parent 9160 * @param right Right position, relative to parent 9161 * @param bottom Bottom position, relative to parent 9162 * @return true if the new size and position are different than the 9163 * previous ones 9164 * {@hide} 9165 */ 9166 protected boolean setFrame(int left, int top, int right, int bottom) { 9167 boolean changed = false; 9168 9169 if (DBG) { 9170 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 9171 + right + "," + bottom + ")"); 9172 } 9173 9174 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 9175 changed = true; 9176 9177 // Remember our drawn bit 9178 int drawn = mPrivateFlags & DRAWN; 9179 9180 // Invalidate our old position 9181 invalidate(true); 9182 9183 9184 int oldWidth = mRight - mLeft; 9185 int oldHeight = mBottom - mTop; 9186 9187 mLeft = left; 9188 mTop = top; 9189 mRight = right; 9190 mBottom = bottom; 9191 9192 mPrivateFlags |= HAS_BOUNDS; 9193 9194 int newWidth = right - left; 9195 int newHeight = bottom - top; 9196 9197 if (newWidth != oldWidth || newHeight != oldHeight) { 9198 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 9199 // A change in dimension means an auto-centered pivot point changes, too 9200 mMatrixDirty = true; 9201 } 9202 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 9203 } 9204 9205 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 9206 // If we are visible, force the DRAWN bit to on so that 9207 // this invalidate will go through (at least to our parent). 9208 // This is because someone may have invalidated this view 9209 // before this call to setFrame came in, thereby clearing 9210 // the DRAWN bit. 9211 mPrivateFlags |= DRAWN; 9212 invalidate(true); 9213 } 9214 9215 // Reset drawn bit to original value (invalidate turns it off) 9216 mPrivateFlags |= drawn; 9217 9218 mBackgroundSizeChanged = true; 9219 } 9220 return changed; 9221 } 9222 9223 /** 9224 * Finalize inflating a view from XML. This is called as the last phase 9225 * of inflation, after all child views have been added. 9226 * 9227 * <p>Even if the subclass overrides onFinishInflate, they should always be 9228 * sure to call the super method, so that we get called. 9229 */ 9230 protected void onFinishInflate() { 9231 } 9232 9233 /** 9234 * Returns the resources associated with this view. 9235 * 9236 * @return Resources object. 9237 */ 9238 public Resources getResources() { 9239 return mResources; 9240 } 9241 9242 /** 9243 * Invalidates the specified Drawable. 9244 * 9245 * @param drawable the drawable to invalidate 9246 */ 9247 public void invalidateDrawable(Drawable drawable) { 9248 if (verifyDrawable(drawable)) { 9249 final Rect dirty = drawable.getBounds(); 9250 final int scrollX = mScrollX; 9251 final int scrollY = mScrollY; 9252 9253 invalidate(dirty.left + scrollX, dirty.top + scrollY, 9254 dirty.right + scrollX, dirty.bottom + scrollY); 9255 } 9256 } 9257 9258 /** 9259 * Schedules an action on a drawable to occur at a specified time. 9260 * 9261 * @param who the recipient of the action 9262 * @param what the action to run on the drawable 9263 * @param when the time at which the action must occur. Uses the 9264 * {@link SystemClock#uptimeMillis} timebase. 9265 */ 9266 public void scheduleDrawable(Drawable who, Runnable what, long when) { 9267 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 9268 mAttachInfo.mHandler.postAtTime(what, who, when); 9269 } 9270 } 9271 9272 /** 9273 * Cancels a scheduled action on a drawable. 9274 * 9275 * @param who the recipient of the action 9276 * @param what the action to cancel 9277 */ 9278 public void unscheduleDrawable(Drawable who, Runnable what) { 9279 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 9280 mAttachInfo.mHandler.removeCallbacks(what, who); 9281 } 9282 } 9283 9284 /** 9285 * Unschedule any events associated with the given Drawable. This can be 9286 * used when selecting a new Drawable into a view, so that the previous 9287 * one is completely unscheduled. 9288 * 9289 * @param who The Drawable to unschedule. 9290 * 9291 * @see #drawableStateChanged 9292 */ 9293 public void unscheduleDrawable(Drawable who) { 9294 if (mAttachInfo != null) { 9295 mAttachInfo.mHandler.removeCallbacksAndMessages(who); 9296 } 9297 } 9298 9299 /** 9300 * If your view subclass is displaying its own Drawable objects, it should 9301 * override this function and return true for any Drawable it is 9302 * displaying. This allows animations for those drawables to be 9303 * scheduled. 9304 * 9305 * <p>Be sure to call through to the super class when overriding this 9306 * function. 9307 * 9308 * @param who The Drawable to verify. Return true if it is one you are 9309 * displaying, else return the result of calling through to the 9310 * super class. 9311 * 9312 * @return boolean If true than the Drawable is being displayed in the 9313 * view; else false and it is not allowed to animate. 9314 * 9315 * @see #unscheduleDrawable 9316 * @see #drawableStateChanged 9317 */ 9318 protected boolean verifyDrawable(Drawable who) { 9319 return who == mBGDrawable; 9320 } 9321 9322 /** 9323 * This function is called whenever the state of the view changes in such 9324 * a way that it impacts the state of drawables being shown. 9325 * 9326 * <p>Be sure to call through to the superclass when overriding this 9327 * function. 9328 * 9329 * @see Drawable#setState 9330 */ 9331 protected void drawableStateChanged() { 9332 Drawable d = mBGDrawable; 9333 if (d != null && d.isStateful()) { 9334 d.setState(getDrawableState()); 9335 } 9336 } 9337 9338 /** 9339 * Call this to force a view to update its drawable state. This will cause 9340 * drawableStateChanged to be called on this view. Views that are interested 9341 * in the new state should call getDrawableState. 9342 * 9343 * @see #drawableStateChanged 9344 * @see #getDrawableState 9345 */ 9346 public void refreshDrawableState() { 9347 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 9348 drawableStateChanged(); 9349 9350 ViewParent parent = mParent; 9351 if (parent != null) { 9352 parent.childDrawableStateChanged(this); 9353 } 9354 } 9355 9356 /** 9357 * Return an array of resource IDs of the drawable states representing the 9358 * current state of the view. 9359 * 9360 * @return The current drawable state 9361 * 9362 * @see Drawable#setState 9363 * @see #drawableStateChanged 9364 * @see #onCreateDrawableState 9365 */ 9366 public final int[] getDrawableState() { 9367 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 9368 return mDrawableState; 9369 } else { 9370 mDrawableState = onCreateDrawableState(0); 9371 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 9372 return mDrawableState; 9373 } 9374 } 9375 9376 /** 9377 * Generate the new {@link android.graphics.drawable.Drawable} state for 9378 * this view. This is called by the view 9379 * system when the cached Drawable state is determined to be invalid. To 9380 * retrieve the current state, you should use {@link #getDrawableState}. 9381 * 9382 * @param extraSpace if non-zero, this is the number of extra entries you 9383 * would like in the returned array in which you can place your own 9384 * states. 9385 * 9386 * @return Returns an array holding the current {@link Drawable} state of 9387 * the view. 9388 * 9389 * @see #mergeDrawableStates 9390 */ 9391 protected int[] onCreateDrawableState(int extraSpace) { 9392 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 9393 mParent instanceof View) { 9394 return ((View) mParent).onCreateDrawableState(extraSpace); 9395 } 9396 9397 int[] drawableState; 9398 9399 int privateFlags = mPrivateFlags; 9400 9401 int viewStateIndex = 0; 9402 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 9403 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 9404 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 9405 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 9406 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 9407 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 9408 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) { 9409 // This is set if HW acceleration is requested, even if the current 9410 // process doesn't allow it. This is just to allow app preview 9411 // windows to better match their app. 9412 viewStateIndex |= VIEW_STATE_ACCELERATED; 9413 } 9414 9415 drawableState = VIEW_STATE_SETS[viewStateIndex]; 9416 9417 //noinspection ConstantIfStatement 9418 if (false) { 9419 Log.i("View", "drawableStateIndex=" + viewStateIndex); 9420 Log.i("View", toString() 9421 + " pressed=" + ((privateFlags & PRESSED) != 0) 9422 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 9423 + " fo=" + hasFocus() 9424 + " sl=" + ((privateFlags & SELECTED) != 0) 9425 + " wf=" + hasWindowFocus() 9426 + ": " + Arrays.toString(drawableState)); 9427 } 9428 9429 if (extraSpace == 0) { 9430 return drawableState; 9431 } 9432 9433 final int[] fullState; 9434 if (drawableState != null) { 9435 fullState = new int[drawableState.length + extraSpace]; 9436 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 9437 } else { 9438 fullState = new int[extraSpace]; 9439 } 9440 9441 return fullState; 9442 } 9443 9444 /** 9445 * Merge your own state values in <var>additionalState</var> into the base 9446 * state values <var>baseState</var> that were returned by 9447 * {@link #onCreateDrawableState}. 9448 * 9449 * @param baseState The base state values returned by 9450 * {@link #onCreateDrawableState}, which will be modified to also hold your 9451 * own additional state values. 9452 * 9453 * @param additionalState The additional state values you would like 9454 * added to <var>baseState</var>; this array is not modified. 9455 * 9456 * @return As a convenience, the <var>baseState</var> array you originally 9457 * passed into the function is returned. 9458 * 9459 * @see #onCreateDrawableState 9460 */ 9461 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 9462 final int N = baseState.length; 9463 int i = N - 1; 9464 while (i >= 0 && baseState[i] == 0) { 9465 i--; 9466 } 9467 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 9468 return baseState; 9469 } 9470 9471 /** 9472 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 9473 * on all Drawable objects associated with this view. 9474 */ 9475 public void jumpDrawablesToCurrentState() { 9476 if (mBGDrawable != null) { 9477 mBGDrawable.jumpToCurrentState(); 9478 } 9479 } 9480 9481 /** 9482 * Sets the background color for this view. 9483 * @param color the color of the background 9484 */ 9485 @RemotableViewMethod 9486 public void setBackgroundColor(int color) { 9487 if (mBGDrawable instanceof ColorDrawable) { 9488 ((ColorDrawable) mBGDrawable).setColor(color); 9489 } else { 9490 setBackgroundDrawable(new ColorDrawable(color)); 9491 } 9492 } 9493 9494 /** 9495 * Set the background to a given resource. The resource should refer to 9496 * a Drawable object or 0 to remove the background. 9497 * @param resid The identifier of the resource. 9498 * @attr ref android.R.styleable#View_background 9499 */ 9500 @RemotableViewMethod 9501 public void setBackgroundResource(int resid) { 9502 if (resid != 0 && resid == mBackgroundResource) { 9503 return; 9504 } 9505 9506 Drawable d= null; 9507 if (resid != 0) { 9508 d = mResources.getDrawable(resid); 9509 } 9510 setBackgroundDrawable(d); 9511 9512 mBackgroundResource = resid; 9513 } 9514 9515 /** 9516 * Set the background to a given Drawable, or remove the background. If the 9517 * background has padding, this View's padding is set to the background's 9518 * padding. However, when a background is removed, this View's padding isn't 9519 * touched. If setting the padding is desired, please use 9520 * {@link #setPadding(int, int, int, int)}. 9521 * 9522 * @param d The Drawable to use as the background, or null to remove the 9523 * background 9524 */ 9525 public void setBackgroundDrawable(Drawable d) { 9526 boolean requestLayout = false; 9527 9528 mBackgroundResource = 0; 9529 9530 /* 9531 * Regardless of whether we're setting a new background or not, we want 9532 * to clear the previous drawable. 9533 */ 9534 if (mBGDrawable != null) { 9535 mBGDrawable.setCallback(null); 9536 unscheduleDrawable(mBGDrawable); 9537 } 9538 9539 if (d != null) { 9540 Rect padding = sThreadLocal.get(); 9541 if (padding == null) { 9542 padding = new Rect(); 9543 sThreadLocal.set(padding); 9544 } 9545 if (d.getPadding(padding)) { 9546 setPadding(padding.left, padding.top, padding.right, padding.bottom); 9547 } 9548 9549 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 9550 // if it has a different minimum size, we should layout again 9551 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 9552 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 9553 requestLayout = true; 9554 } 9555 9556 d.setCallback(this); 9557 if (d.isStateful()) { 9558 d.setState(getDrawableState()); 9559 } 9560 d.setVisible(getVisibility() == VISIBLE, false); 9561 mBGDrawable = d; 9562 9563 if ((mPrivateFlags & SKIP_DRAW) != 0) { 9564 mPrivateFlags &= ~SKIP_DRAW; 9565 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 9566 requestLayout = true; 9567 } 9568 } else { 9569 /* Remove the background */ 9570 mBGDrawable = null; 9571 9572 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 9573 /* 9574 * This view ONLY drew the background before and we're removing 9575 * the background, so now it won't draw anything 9576 * (hence we SKIP_DRAW) 9577 */ 9578 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 9579 mPrivateFlags |= SKIP_DRAW; 9580 } 9581 9582 /* 9583 * When the background is set, we try to apply its padding to this 9584 * View. When the background is removed, we don't touch this View's 9585 * padding. This is noted in the Javadocs. Hence, we don't need to 9586 * requestLayout(), the invalidate() below is sufficient. 9587 */ 9588 9589 // The old background's minimum size could have affected this 9590 // View's layout, so let's requestLayout 9591 requestLayout = true; 9592 } 9593 9594 computeOpaqueFlags(); 9595 9596 if (requestLayout) { 9597 requestLayout(); 9598 } 9599 9600 mBackgroundSizeChanged = true; 9601 invalidate(true); 9602 } 9603 9604 /** 9605 * Gets the background drawable 9606 * @return The drawable used as the background for this view, if any. 9607 */ 9608 public Drawable getBackground() { 9609 return mBGDrawable; 9610 } 9611 9612 /** 9613 * Sets the padding. The view may add on the space required to display 9614 * the scrollbars, depending on the style and visibility of the scrollbars. 9615 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 9616 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 9617 * from the values set in this call. 9618 * 9619 * @attr ref android.R.styleable#View_padding 9620 * @attr ref android.R.styleable#View_paddingBottom 9621 * @attr ref android.R.styleable#View_paddingLeft 9622 * @attr ref android.R.styleable#View_paddingRight 9623 * @attr ref android.R.styleable#View_paddingTop 9624 * @param left the left padding in pixels 9625 * @param top the top padding in pixels 9626 * @param right the right padding in pixels 9627 * @param bottom the bottom padding in pixels 9628 */ 9629 public void setPadding(int left, int top, int right, int bottom) { 9630 boolean changed = false; 9631 9632 mUserPaddingLeft = left; 9633 mUserPaddingRight = right; 9634 mUserPaddingBottom = bottom; 9635 9636 final int viewFlags = mViewFlags; 9637 9638 // Common case is there are no scroll bars. 9639 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 9640 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 9641 // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings. 9642 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 9643 ? 0 : getVerticalScrollbarWidth(); 9644 switch (mVerticalScrollbarPosition) { 9645 case SCROLLBAR_POSITION_DEFAULT: 9646 case SCROLLBAR_POSITION_RIGHT: 9647 right += offset; 9648 break; 9649 case SCROLLBAR_POSITION_LEFT: 9650 left += offset; 9651 break; 9652 } 9653 } 9654 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 9655 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 9656 ? 0 : getHorizontalScrollbarHeight(); 9657 } 9658 } 9659 9660 if (mPaddingLeft != left) { 9661 changed = true; 9662 mPaddingLeft = left; 9663 } 9664 if (mPaddingTop != top) { 9665 changed = true; 9666 mPaddingTop = top; 9667 } 9668 if (mPaddingRight != right) { 9669 changed = true; 9670 mPaddingRight = right; 9671 } 9672 if (mPaddingBottom != bottom) { 9673 changed = true; 9674 mPaddingBottom = bottom; 9675 } 9676 9677 if (changed) { 9678 requestLayout(); 9679 } 9680 } 9681 9682 /** 9683 * Returns the top padding of this view. 9684 * 9685 * @return the top padding in pixels 9686 */ 9687 public int getPaddingTop() { 9688 return mPaddingTop; 9689 } 9690 9691 /** 9692 * Returns the bottom padding of this view. If there are inset and enabled 9693 * scrollbars, this value may include the space required to display the 9694 * scrollbars as well. 9695 * 9696 * @return the bottom padding in pixels 9697 */ 9698 public int getPaddingBottom() { 9699 return mPaddingBottom; 9700 } 9701 9702 /** 9703 * Returns the left padding of this view. If there are inset and enabled 9704 * scrollbars, this value may include the space required to display the 9705 * scrollbars as well. 9706 * 9707 * @return the left padding in pixels 9708 */ 9709 public int getPaddingLeft() { 9710 return mPaddingLeft; 9711 } 9712 9713 /** 9714 * Returns the right padding of this view. If there are inset and enabled 9715 * scrollbars, this value may include the space required to display the 9716 * scrollbars as well. 9717 * 9718 * @return the right padding in pixels 9719 */ 9720 public int getPaddingRight() { 9721 return mPaddingRight; 9722 } 9723 9724 /** 9725 * Changes the selection state of this view. A view can be selected or not. 9726 * Note that selection is not the same as focus. Views are typically 9727 * selected in the context of an AdapterView like ListView or GridView; 9728 * the selected view is the view that is highlighted. 9729 * 9730 * @param selected true if the view must be selected, false otherwise 9731 */ 9732 public void setSelected(boolean selected) { 9733 if (((mPrivateFlags & SELECTED) != 0) != selected) { 9734 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 9735 if (!selected) resetPressedState(); 9736 invalidate(true); 9737 refreshDrawableState(); 9738 dispatchSetSelected(selected); 9739 } 9740 } 9741 9742 /** 9743 * Dispatch setSelected to all of this View's children. 9744 * 9745 * @see #setSelected(boolean) 9746 * 9747 * @param selected The new selected state 9748 */ 9749 protected void dispatchSetSelected(boolean selected) { 9750 } 9751 9752 /** 9753 * Indicates the selection state of this view. 9754 * 9755 * @return true if the view is selected, false otherwise 9756 */ 9757 @ViewDebug.ExportedProperty 9758 public boolean isSelected() { 9759 return (mPrivateFlags & SELECTED) != 0; 9760 } 9761 9762 /** 9763 * Changes the activated state of this view. A view can be activated or not. 9764 * Note that activation is not the same as selection. Selection is 9765 * a transient property, representing the view (hierarchy) the user is 9766 * currently interacting with. Activation is a longer-term state that the 9767 * user can move views in and out of. For example, in a list view with 9768 * single or multiple selection enabled, the views in the current selection 9769 * set are activated. (Um, yeah, we are deeply sorry about the terminology 9770 * here.) The activated state is propagated down to children of the view it 9771 * is set on. 9772 * 9773 * @param activated true if the view must be activated, false otherwise 9774 */ 9775 public void setActivated(boolean activated) { 9776 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 9777 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 9778 invalidate(true); 9779 refreshDrawableState(); 9780 dispatchSetActivated(activated); 9781 } 9782 } 9783 9784 /** 9785 * Dispatch setActivated to all of this View's children. 9786 * 9787 * @see #setActivated(boolean) 9788 * 9789 * @param activated The new activated state 9790 */ 9791 protected void dispatchSetActivated(boolean activated) { 9792 } 9793 9794 /** 9795 * Indicates the activation state of this view. 9796 * 9797 * @return true if the view is activated, false otherwise 9798 */ 9799 @ViewDebug.ExportedProperty 9800 public boolean isActivated() { 9801 return (mPrivateFlags & ACTIVATED) != 0; 9802 } 9803 9804 /** 9805 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 9806 * observer can be used to get notifications when global events, like 9807 * layout, happen. 9808 * 9809 * The returned ViewTreeObserver observer is not guaranteed to remain 9810 * valid for the lifetime of this View. If the caller of this method keeps 9811 * a long-lived reference to ViewTreeObserver, it should always check for 9812 * the return value of {@link ViewTreeObserver#isAlive()}. 9813 * 9814 * @return The ViewTreeObserver for this view's hierarchy. 9815 */ 9816 public ViewTreeObserver getViewTreeObserver() { 9817 if (mAttachInfo != null) { 9818 return mAttachInfo.mTreeObserver; 9819 } 9820 if (mFloatingTreeObserver == null) { 9821 mFloatingTreeObserver = new ViewTreeObserver(); 9822 } 9823 return mFloatingTreeObserver; 9824 } 9825 9826 /** 9827 * <p>Finds the topmost view in the current view hierarchy.</p> 9828 * 9829 * @return the topmost view containing this view 9830 */ 9831 public View getRootView() { 9832 if (mAttachInfo != null) { 9833 final View v = mAttachInfo.mRootView; 9834 if (v != null) { 9835 return v; 9836 } 9837 } 9838 9839 View parent = this; 9840 9841 while (parent.mParent != null && parent.mParent instanceof View) { 9842 parent = (View) parent.mParent; 9843 } 9844 9845 return parent; 9846 } 9847 9848 /** 9849 * <p>Computes the coordinates of this view on the screen. The argument 9850 * must be an array of two integers. After the method returns, the array 9851 * contains the x and y location in that order.</p> 9852 * 9853 * @param location an array of two integers in which to hold the coordinates 9854 */ 9855 public void getLocationOnScreen(int[] location) { 9856 getLocationInWindow(location); 9857 9858 final AttachInfo info = mAttachInfo; 9859 if (info != null) { 9860 location[0] += info.mWindowLeft; 9861 location[1] += info.mWindowTop; 9862 } 9863 } 9864 9865 /** 9866 * <p>Computes the coordinates of this view in its window. The argument 9867 * must be an array of two integers. After the method returns, the array 9868 * contains the x and y location in that order.</p> 9869 * 9870 * @param location an array of two integers in which to hold the coordinates 9871 */ 9872 public void getLocationInWindow(int[] location) { 9873 if (location == null || location.length < 2) { 9874 throw new IllegalArgumentException("location must be an array of " 9875 + "two integers"); 9876 } 9877 9878 location[0] = mLeft + (int) (mTranslationX + 0.5f); 9879 location[1] = mTop + (int) (mTranslationY + 0.5f); 9880 9881 ViewParent viewParent = mParent; 9882 while (viewParent instanceof View) { 9883 final View view = (View)viewParent; 9884 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX; 9885 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY; 9886 viewParent = view.mParent; 9887 } 9888 9889 if (viewParent instanceof ViewRoot) { 9890 // *cough* 9891 final ViewRoot vr = (ViewRoot)viewParent; 9892 location[1] -= vr.mCurScrollY; 9893 } 9894 } 9895 9896 /** 9897 * {@hide} 9898 * @param id the id of the view to be found 9899 * @return the view of the specified id, null if cannot be found 9900 */ 9901 protected View findViewTraversal(int id) { 9902 if (id == mID) { 9903 return this; 9904 } 9905 return null; 9906 } 9907 9908 /** 9909 * {@hide} 9910 * @param tag the tag of the view to be found 9911 * @return the view of specified tag, null if cannot be found 9912 */ 9913 protected View findViewWithTagTraversal(Object tag) { 9914 if (tag != null && tag.equals(mTag)) { 9915 return this; 9916 } 9917 return null; 9918 } 9919 9920 /** 9921 * {@hide} 9922 * @param predicate The predicate to evaluate. 9923 * @return The first view that matches the predicate or null. 9924 */ 9925 protected View findViewByPredicateTraversal(Predicate<View> predicate) { 9926 if (predicate.apply(this)) { 9927 return this; 9928 } 9929 return null; 9930 } 9931 9932 /** 9933 * Look for a child view with the given id. If this view has the given 9934 * id, return this view. 9935 * 9936 * @param id The id to search for. 9937 * @return The view that has the given id in the hierarchy or null 9938 */ 9939 public final View findViewById(int id) { 9940 if (id < 0) { 9941 return null; 9942 } 9943 return findViewTraversal(id); 9944 } 9945 9946 /** 9947 * Look for a child view with the given tag. If this view has the given 9948 * tag, return this view. 9949 * 9950 * @param tag The tag to search for, using "tag.equals(getTag())". 9951 * @return The View that has the given tag in the hierarchy or null 9952 */ 9953 public final View findViewWithTag(Object tag) { 9954 if (tag == null) { 9955 return null; 9956 } 9957 return findViewWithTagTraversal(tag); 9958 } 9959 9960 /** 9961 * {@hide} 9962 * Look for a child view that matches the specified predicate. 9963 * If this view matches the predicate, return this view. 9964 * 9965 * @param predicate The predicate to evaluate. 9966 * @return The first view that matches the predicate or null. 9967 */ 9968 public final View findViewByPredicate(Predicate<View> predicate) { 9969 return findViewByPredicateTraversal(predicate); 9970 } 9971 9972 /** 9973 * Sets the identifier for this view. The identifier does not have to be 9974 * unique in this view's hierarchy. The identifier should be a positive 9975 * number. 9976 * 9977 * @see #NO_ID 9978 * @see #getId 9979 * @see #findViewById 9980 * 9981 * @param id a number used to identify the view 9982 * 9983 * @attr ref android.R.styleable#View_id 9984 */ 9985 public void setId(int id) { 9986 mID = id; 9987 } 9988 9989 /** 9990 * {@hide} 9991 * 9992 * @param isRoot true if the view belongs to the root namespace, false 9993 * otherwise 9994 */ 9995 public void setIsRootNamespace(boolean isRoot) { 9996 if (isRoot) { 9997 mPrivateFlags |= IS_ROOT_NAMESPACE; 9998 } else { 9999 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 10000 } 10001 } 10002 10003 /** 10004 * {@hide} 10005 * 10006 * @return true if the view belongs to the root namespace, false otherwise 10007 */ 10008 public boolean isRootNamespace() { 10009 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 10010 } 10011 10012 /** 10013 * Returns this view's identifier. 10014 * 10015 * @return a positive integer used to identify the view or {@link #NO_ID} 10016 * if the view has no ID 10017 * 10018 * @see #setId 10019 * @see #findViewById 10020 * @attr ref android.R.styleable#View_id 10021 */ 10022 @ViewDebug.CapturedViewProperty 10023 public int getId() { 10024 return mID; 10025 } 10026 10027 /** 10028 * Returns this view's tag. 10029 * 10030 * @return the Object stored in this view as a tag 10031 * 10032 * @see #setTag(Object) 10033 * @see #getTag(int) 10034 */ 10035 @ViewDebug.ExportedProperty 10036 public Object getTag() { 10037 return mTag; 10038 } 10039 10040 /** 10041 * Sets the tag associated with this view. A tag can be used to mark 10042 * a view in its hierarchy and does not have to be unique within the 10043 * hierarchy. Tags can also be used to store data within a view without 10044 * resorting to another data structure. 10045 * 10046 * @param tag an Object to tag the view with 10047 * 10048 * @see #getTag() 10049 * @see #setTag(int, Object) 10050 */ 10051 public void setTag(final Object tag) { 10052 mTag = tag; 10053 } 10054 10055 /** 10056 * Returns the tag associated with this view and the specified key. 10057 * 10058 * @param key The key identifying the tag 10059 * 10060 * @return the Object stored in this view as a tag 10061 * 10062 * @see #setTag(int, Object) 10063 * @see #getTag() 10064 */ 10065 public Object getTag(int key) { 10066 SparseArray<Object> tags = null; 10067 synchronized (sTagsLock) { 10068 if (sTags != null) { 10069 tags = sTags.get(this); 10070 } 10071 } 10072 10073 if (tags != null) return tags.get(key); 10074 return null; 10075 } 10076 10077 /** 10078 * Sets a tag associated with this view and a key. A tag can be used 10079 * to mark a view in its hierarchy and does not have to be unique within 10080 * the hierarchy. Tags can also be used to store data within a view 10081 * without resorting to another data structure. 10082 * 10083 * The specified key should be an id declared in the resources of the 10084 * application to ensure it is unique (see the <a 10085 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 10086 * Keys identified as belonging to 10087 * the Android framework or not associated with any package will cause 10088 * an {@link IllegalArgumentException} to be thrown. 10089 * 10090 * @param key The key identifying the tag 10091 * @param tag An Object to tag the view with 10092 * 10093 * @throws IllegalArgumentException If they specified key is not valid 10094 * 10095 * @see #setTag(Object) 10096 * @see #getTag(int) 10097 */ 10098 public void setTag(int key, final Object tag) { 10099 // If the package id is 0x00 or 0x01, it's either an undefined package 10100 // or a framework id 10101 if ((key >>> 24) < 2) { 10102 throw new IllegalArgumentException("The key must be an application-specific " 10103 + "resource id."); 10104 } 10105 10106 setTagInternal(this, key, tag); 10107 } 10108 10109 /** 10110 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 10111 * framework id. 10112 * 10113 * @hide 10114 */ 10115 public void setTagInternal(int key, Object tag) { 10116 if ((key >>> 24) != 0x1) { 10117 throw new IllegalArgumentException("The key must be a framework-specific " 10118 + "resource id."); 10119 } 10120 10121 setTagInternal(this, key, tag); 10122 } 10123 10124 private static void setTagInternal(View view, int key, Object tag) { 10125 SparseArray<Object> tags = null; 10126 synchronized (sTagsLock) { 10127 if (sTags == null) { 10128 sTags = new WeakHashMap<View, SparseArray<Object>>(); 10129 } else { 10130 tags = sTags.get(view); 10131 } 10132 } 10133 10134 if (tags == null) { 10135 tags = new SparseArray<Object>(2); 10136 synchronized (sTagsLock) { 10137 sTags.put(view, tags); 10138 } 10139 } 10140 10141 tags.put(key, tag); 10142 } 10143 10144 /** 10145 * @param consistency The type of consistency. See ViewDebug for more information. 10146 * 10147 * @hide 10148 */ 10149 protected boolean dispatchConsistencyCheck(int consistency) { 10150 return onConsistencyCheck(consistency); 10151 } 10152 10153 /** 10154 * Method that subclasses should implement to check their consistency. The type of 10155 * consistency check is indicated by the bit field passed as a parameter. 10156 * 10157 * @param consistency The type of consistency. See ViewDebug for more information. 10158 * 10159 * @throws IllegalStateException if the view is in an inconsistent state. 10160 * 10161 * @hide 10162 */ 10163 protected boolean onConsistencyCheck(int consistency) { 10164 boolean result = true; 10165 10166 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 10167 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 10168 10169 if (checkLayout) { 10170 if (getParent() == null) { 10171 result = false; 10172 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 10173 "View " + this + " does not have a parent."); 10174 } 10175 10176 if (mAttachInfo == null) { 10177 result = false; 10178 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 10179 "View " + this + " is not attached to a window."); 10180 } 10181 } 10182 10183 if (checkDrawing) { 10184 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 10185 // from their draw() method 10186 10187 if ((mPrivateFlags & DRAWN) != DRAWN && 10188 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 10189 result = false; 10190 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 10191 "View " + this + " was invalidated but its drawing cache is valid."); 10192 } 10193 } 10194 10195 return result; 10196 } 10197 10198 /** 10199 * Prints information about this view in the log output, with the tag 10200 * {@link #VIEW_LOG_TAG}. 10201 * 10202 * @hide 10203 */ 10204 public void debug() { 10205 debug(0); 10206 } 10207 10208 /** 10209 * Prints information about this view in the log output, with the tag 10210 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 10211 * indentation defined by the <code>depth</code>. 10212 * 10213 * @param depth the indentation level 10214 * 10215 * @hide 10216 */ 10217 protected void debug(int depth) { 10218 String output = debugIndent(depth - 1); 10219 10220 output += "+ " + this; 10221 int id = getId(); 10222 if (id != -1) { 10223 output += " (id=" + id + ")"; 10224 } 10225 Object tag = getTag(); 10226 if (tag != null) { 10227 output += " (tag=" + tag + ")"; 10228 } 10229 Log.d(VIEW_LOG_TAG, output); 10230 10231 if ((mPrivateFlags & FOCUSED) != 0) { 10232 output = debugIndent(depth) + " FOCUSED"; 10233 Log.d(VIEW_LOG_TAG, output); 10234 } 10235 10236 output = debugIndent(depth); 10237 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 10238 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 10239 + "} "; 10240 Log.d(VIEW_LOG_TAG, output); 10241 10242 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 10243 || mPaddingBottom != 0) { 10244 output = debugIndent(depth); 10245 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 10246 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 10247 Log.d(VIEW_LOG_TAG, output); 10248 } 10249 10250 output = debugIndent(depth); 10251 output += "mMeasureWidth=" + mMeasuredWidth + 10252 " mMeasureHeight=" + mMeasuredHeight; 10253 Log.d(VIEW_LOG_TAG, output); 10254 10255 output = debugIndent(depth); 10256 if (mLayoutParams == null) { 10257 output += "BAD! no layout params"; 10258 } else { 10259 output = mLayoutParams.debug(output); 10260 } 10261 Log.d(VIEW_LOG_TAG, output); 10262 10263 output = debugIndent(depth); 10264 output += "flags={"; 10265 output += View.printFlags(mViewFlags); 10266 output += "}"; 10267 Log.d(VIEW_LOG_TAG, output); 10268 10269 output = debugIndent(depth); 10270 output += "privateFlags={"; 10271 output += View.printPrivateFlags(mPrivateFlags); 10272 output += "}"; 10273 Log.d(VIEW_LOG_TAG, output); 10274 } 10275 10276 /** 10277 * Creates an string of whitespaces used for indentation. 10278 * 10279 * @param depth the indentation level 10280 * @return a String containing (depth * 2 + 3) * 2 white spaces 10281 * 10282 * @hide 10283 */ 10284 protected static String debugIndent(int depth) { 10285 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 10286 for (int i = 0; i < (depth * 2) + 3; i++) { 10287 spaces.append(' ').append(' '); 10288 } 10289 return spaces.toString(); 10290 } 10291 10292 /** 10293 * <p>Return the offset of the widget's text baseline from the widget's top 10294 * boundary. If this widget does not support baseline alignment, this 10295 * method returns -1. </p> 10296 * 10297 * @return the offset of the baseline within the widget's bounds or -1 10298 * if baseline alignment is not supported 10299 */ 10300 @ViewDebug.ExportedProperty(category = "layout") 10301 public int getBaseline() { 10302 return -1; 10303 } 10304 10305 /** 10306 * Call this when something has changed which has invalidated the 10307 * layout of this view. This will schedule a layout pass of the view 10308 * tree. 10309 */ 10310 public void requestLayout() { 10311 if (ViewDebug.TRACE_HIERARCHY) { 10312 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 10313 } 10314 10315 mPrivateFlags |= FORCE_LAYOUT; 10316 mPrivateFlags |= INVALIDATED; 10317 10318 if (mParent != null && !mParent.isLayoutRequested()) { 10319 mParent.requestLayout(); 10320 } 10321 } 10322 10323 /** 10324 * Forces this view to be laid out during the next layout pass. 10325 * This method does not call requestLayout() or forceLayout() 10326 * on the parent. 10327 */ 10328 public void forceLayout() { 10329 mPrivateFlags |= FORCE_LAYOUT; 10330 mPrivateFlags |= INVALIDATED; 10331 } 10332 10333 /** 10334 * <p> 10335 * This is called to find out how big a view should be. The parent 10336 * supplies constraint information in the width and height parameters. 10337 * </p> 10338 * 10339 * <p> 10340 * The actual mesurement work of a view is performed in 10341 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 10342 * {@link #onMeasure(int, int)} can and must be overriden by subclasses. 10343 * </p> 10344 * 10345 * 10346 * @param widthMeasureSpec Horizontal space requirements as imposed by the 10347 * parent 10348 * @param heightMeasureSpec Vertical space requirements as imposed by the 10349 * parent 10350 * 10351 * @see #onMeasure(int, int) 10352 */ 10353 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 10354 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 10355 widthMeasureSpec != mOldWidthMeasureSpec || 10356 heightMeasureSpec != mOldHeightMeasureSpec) { 10357 10358 // first clears the measured dimension flag 10359 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 10360 10361 if (ViewDebug.TRACE_HIERARCHY) { 10362 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 10363 } 10364 10365 // measure ourselves, this should set the measured dimension flag back 10366 onMeasure(widthMeasureSpec, heightMeasureSpec); 10367 10368 // flag not set, setMeasuredDimension() was not invoked, we raise 10369 // an exception to warn the developer 10370 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 10371 throw new IllegalStateException("onMeasure() did not set the" 10372 + " measured dimension by calling" 10373 + " setMeasuredDimension()"); 10374 } 10375 10376 mPrivateFlags |= LAYOUT_REQUIRED; 10377 } 10378 10379 mOldWidthMeasureSpec = widthMeasureSpec; 10380 mOldHeightMeasureSpec = heightMeasureSpec; 10381 } 10382 10383 /** 10384 * <p> 10385 * Measure the view and its content to determine the measured width and the 10386 * measured height. This method is invoked by {@link #measure(int, int)} and 10387 * should be overriden by subclasses to provide accurate and efficient 10388 * measurement of their contents. 10389 * </p> 10390 * 10391 * <p> 10392 * <strong>CONTRACT:</strong> When overriding this method, you 10393 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 10394 * measured width and height of this view. Failure to do so will trigger an 10395 * <code>IllegalStateException</code>, thrown by 10396 * {@link #measure(int, int)}. Calling the superclass' 10397 * {@link #onMeasure(int, int)} is a valid use. 10398 * </p> 10399 * 10400 * <p> 10401 * The base class implementation of measure defaults to the background size, 10402 * unless a larger size is allowed by the MeasureSpec. Subclasses should 10403 * override {@link #onMeasure(int, int)} to provide better measurements of 10404 * their content. 10405 * </p> 10406 * 10407 * <p> 10408 * If this method is overridden, it is the subclass's responsibility to make 10409 * sure the measured height and width are at least the view's minimum height 10410 * and width ({@link #getSuggestedMinimumHeight()} and 10411 * {@link #getSuggestedMinimumWidth()}). 10412 * </p> 10413 * 10414 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 10415 * The requirements are encoded with 10416 * {@link android.view.View.MeasureSpec}. 10417 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 10418 * The requirements are encoded with 10419 * {@link android.view.View.MeasureSpec}. 10420 * 10421 * @see #getMeasuredWidth() 10422 * @see #getMeasuredHeight() 10423 * @see #setMeasuredDimension(int, int) 10424 * @see #getSuggestedMinimumHeight() 10425 * @see #getSuggestedMinimumWidth() 10426 * @see android.view.View.MeasureSpec#getMode(int) 10427 * @see android.view.View.MeasureSpec#getSize(int) 10428 */ 10429 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 10430 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 10431 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 10432 } 10433 10434 /** 10435 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 10436 * measured width and measured height. Failing to do so will trigger an 10437 * exception at measurement time.</p> 10438 * 10439 * @param measuredWidth The measured width of this view. May be a complex 10440 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 10441 * {@link #MEASURED_STATE_TOO_SMALL}. 10442 * @param measuredHeight The measured height of this view. May be a complex 10443 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 10444 * {@link #MEASURED_STATE_TOO_SMALL}. 10445 */ 10446 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 10447 mMeasuredWidth = measuredWidth; 10448 mMeasuredHeight = measuredHeight; 10449 10450 mPrivateFlags |= MEASURED_DIMENSION_SET; 10451 } 10452 10453 /** 10454 * Merge two states as returned by {@link #getMeasuredState()}. 10455 * @param curState The current state as returned from a view or the result 10456 * of combining multiple views. 10457 * @param newState The new view state to combine. 10458 * @return Returns a new integer reflecting the combination of the two 10459 * states. 10460 */ 10461 public static int combineMeasuredStates(int curState, int newState) { 10462 return curState | newState; 10463 } 10464 10465 /** 10466 * Version of {@link #resolveSizeAndState(int, int, int)} 10467 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 10468 */ 10469 public static int resolveSize(int size, int measureSpec) { 10470 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 10471 } 10472 10473 /** 10474 * Utility to reconcile a desired size and state, with constraints imposed 10475 * by a MeasureSpec. Will take the desired size, unless a different size 10476 * is imposed by the constraints. The returned value is a compound integer, 10477 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 10478 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 10479 * size is smaller than the size the view wants to be. 10480 * 10481 * @param size How big the view wants to be 10482 * @param measureSpec Constraints imposed by the parent 10483 * @return Size information bit mask as defined by 10484 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 10485 */ 10486 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 10487 int result = size; 10488 int specMode = MeasureSpec.getMode(measureSpec); 10489 int specSize = MeasureSpec.getSize(measureSpec); 10490 switch (specMode) { 10491 case MeasureSpec.UNSPECIFIED: 10492 result = size; 10493 break; 10494 case MeasureSpec.AT_MOST: 10495 if (specSize < size) { 10496 result = specSize | MEASURED_STATE_TOO_SMALL; 10497 } else { 10498 result = size; 10499 } 10500 break; 10501 case MeasureSpec.EXACTLY: 10502 result = specSize; 10503 break; 10504 } 10505 return result | (childMeasuredState&MEASURED_STATE_MASK); 10506 } 10507 10508 /** 10509 * Utility to return a default size. Uses the supplied size if the 10510 * MeasureSpec imposed no contraints. Will get larger if allowed 10511 * by the MeasureSpec. 10512 * 10513 * @param size Default size for this view 10514 * @param measureSpec Constraints imposed by the parent 10515 * @return The size this view should be. 10516 */ 10517 public static int getDefaultSize(int size, int measureSpec) { 10518 int result = size; 10519 int specMode = MeasureSpec.getMode(measureSpec); 10520 int specSize = MeasureSpec.getSize(measureSpec); 10521 10522 switch (specMode) { 10523 case MeasureSpec.UNSPECIFIED: 10524 result = size; 10525 break; 10526 case MeasureSpec.AT_MOST: 10527 case MeasureSpec.EXACTLY: 10528 result = specSize; 10529 break; 10530 } 10531 return result; 10532 } 10533 10534 /** 10535 * Returns the suggested minimum height that the view should use. This 10536 * returns the maximum of the view's minimum height 10537 * and the background's minimum height 10538 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 10539 * <p> 10540 * When being used in {@link #onMeasure(int, int)}, the caller should still 10541 * ensure the returned height is within the requirements of the parent. 10542 * 10543 * @return The suggested minimum height of the view. 10544 */ 10545 protected int getSuggestedMinimumHeight() { 10546 int suggestedMinHeight = mMinHeight; 10547 10548 if (mBGDrawable != null) { 10549 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 10550 if (suggestedMinHeight < bgMinHeight) { 10551 suggestedMinHeight = bgMinHeight; 10552 } 10553 } 10554 10555 return suggestedMinHeight; 10556 } 10557 10558 /** 10559 * Returns the suggested minimum width that the view should use. This 10560 * returns the maximum of the view's minimum width) 10561 * and the background's minimum width 10562 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 10563 * <p> 10564 * When being used in {@link #onMeasure(int, int)}, the caller should still 10565 * ensure the returned width is within the requirements of the parent. 10566 * 10567 * @return The suggested minimum width of the view. 10568 */ 10569 protected int getSuggestedMinimumWidth() { 10570 int suggestedMinWidth = mMinWidth; 10571 10572 if (mBGDrawable != null) { 10573 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 10574 if (suggestedMinWidth < bgMinWidth) { 10575 suggestedMinWidth = bgMinWidth; 10576 } 10577 } 10578 10579 return suggestedMinWidth; 10580 } 10581 10582 /** 10583 * Sets the minimum height of the view. It is not guaranteed the view will 10584 * be able to achieve this minimum height (for example, if its parent layout 10585 * constrains it with less available height). 10586 * 10587 * @param minHeight The minimum height the view will try to be. 10588 */ 10589 public void setMinimumHeight(int minHeight) { 10590 mMinHeight = minHeight; 10591 } 10592 10593 /** 10594 * Sets the minimum width of the view. It is not guaranteed the view will 10595 * be able to achieve this minimum width (for example, if its parent layout 10596 * constrains it with less available width). 10597 * 10598 * @param minWidth The minimum width the view will try to be. 10599 */ 10600 public void setMinimumWidth(int minWidth) { 10601 mMinWidth = minWidth; 10602 } 10603 10604 /** 10605 * Get the animation currently associated with this view. 10606 * 10607 * @return The animation that is currently playing or 10608 * scheduled to play for this view. 10609 */ 10610 public Animation getAnimation() { 10611 return mCurrentAnimation; 10612 } 10613 10614 /** 10615 * Start the specified animation now. 10616 * 10617 * @param animation the animation to start now 10618 */ 10619 public void startAnimation(Animation animation) { 10620 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 10621 setAnimation(animation); 10622 invalidateParentCaches(); 10623 invalidate(true); 10624 } 10625 10626 /** 10627 * Cancels any animations for this view. 10628 */ 10629 public void clearAnimation() { 10630 if (mCurrentAnimation != null) { 10631 mCurrentAnimation.detach(); 10632 } 10633 mCurrentAnimation = null; 10634 invalidateParentIfNeeded(); 10635 } 10636 10637 /** 10638 * Sets the next animation to play for this view. 10639 * If you want the animation to play immediately, use 10640 * startAnimation. This method provides allows fine-grained 10641 * control over the start time and invalidation, but you 10642 * must make sure that 1) the animation has a start time set, and 10643 * 2) the view will be invalidated when the animation is supposed to 10644 * start. 10645 * 10646 * @param animation The next animation, or null. 10647 */ 10648 public void setAnimation(Animation animation) { 10649 mCurrentAnimation = animation; 10650 if (animation != null) { 10651 animation.reset(); 10652 } 10653 } 10654 10655 /** 10656 * Invoked by a parent ViewGroup to notify the start of the animation 10657 * currently associated with this view. If you override this method, 10658 * always call super.onAnimationStart(); 10659 * 10660 * @see #setAnimation(android.view.animation.Animation) 10661 * @see #getAnimation() 10662 */ 10663 protected void onAnimationStart() { 10664 mPrivateFlags |= ANIMATION_STARTED; 10665 } 10666 10667 /** 10668 * Invoked by a parent ViewGroup to notify the end of the animation 10669 * currently associated with this view. If you override this method, 10670 * always call super.onAnimationEnd(); 10671 * 10672 * @see #setAnimation(android.view.animation.Animation) 10673 * @see #getAnimation() 10674 */ 10675 protected void onAnimationEnd() { 10676 mPrivateFlags &= ~ANIMATION_STARTED; 10677 } 10678 10679 /** 10680 * Invoked if there is a Transform that involves alpha. Subclass that can 10681 * draw themselves with the specified alpha should return true, and then 10682 * respect that alpha when their onDraw() is called. If this returns false 10683 * then the view may be redirected to draw into an offscreen buffer to 10684 * fulfill the request, which will look fine, but may be slower than if the 10685 * subclass handles it internally. The default implementation returns false. 10686 * 10687 * @param alpha The alpha (0..255) to apply to the view's drawing 10688 * @return true if the view can draw with the specified alpha. 10689 */ 10690 protected boolean onSetAlpha(int alpha) { 10691 return false; 10692 } 10693 10694 /** 10695 * This is used by the RootView to perform an optimization when 10696 * the view hierarchy contains one or several SurfaceView. 10697 * SurfaceView is always considered transparent, but its children are not, 10698 * therefore all View objects remove themselves from the global transparent 10699 * region (passed as a parameter to this function). 10700 * 10701 * @param region The transparent region for this ViewRoot (window). 10702 * 10703 * @return Returns true if the effective visibility of the view at this 10704 * point is opaque, regardless of the transparent region; returns false 10705 * if it is possible for underlying windows to be seen behind the view. 10706 * 10707 * {@hide} 10708 */ 10709 public boolean gatherTransparentRegion(Region region) { 10710 final AttachInfo attachInfo = mAttachInfo; 10711 if (region != null && attachInfo != null) { 10712 final int pflags = mPrivateFlags; 10713 if ((pflags & SKIP_DRAW) == 0) { 10714 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 10715 // remove it from the transparent region. 10716 final int[] location = attachInfo.mTransparentLocation; 10717 getLocationInWindow(location); 10718 region.op(location[0], location[1], location[0] + mRight - mLeft, 10719 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 10720 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 10721 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 10722 // exists, so we remove the background drawable's non-transparent 10723 // parts from this transparent region. 10724 applyDrawableToTransparentRegion(mBGDrawable, region); 10725 } 10726 } 10727 return true; 10728 } 10729 10730 /** 10731 * Play a sound effect for this view. 10732 * 10733 * <p>The framework will play sound effects for some built in actions, such as 10734 * clicking, but you may wish to play these effects in your widget, 10735 * for instance, for internal navigation. 10736 * 10737 * <p>The sound effect will only be played if sound effects are enabled by the user, and 10738 * {@link #isSoundEffectsEnabled()} is true. 10739 * 10740 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 10741 */ 10742 public void playSoundEffect(int soundConstant) { 10743 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 10744 return; 10745 } 10746 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 10747 } 10748 10749 /** 10750 * BZZZTT!!1! 10751 * 10752 * <p>Provide haptic feedback to the user for this view. 10753 * 10754 * <p>The framework will provide haptic feedback for some built in actions, 10755 * such as long presses, but you may wish to provide feedback for your 10756 * own widget. 10757 * 10758 * <p>The feedback will only be performed if 10759 * {@link #isHapticFeedbackEnabled()} is true. 10760 * 10761 * @param feedbackConstant One of the constants defined in 10762 * {@link HapticFeedbackConstants} 10763 */ 10764 public boolean performHapticFeedback(int feedbackConstant) { 10765 return performHapticFeedback(feedbackConstant, 0); 10766 } 10767 10768 /** 10769 * BZZZTT!!1! 10770 * 10771 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 10772 * 10773 * @param feedbackConstant One of the constants defined in 10774 * {@link HapticFeedbackConstants} 10775 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 10776 */ 10777 public boolean performHapticFeedback(int feedbackConstant, int flags) { 10778 if (mAttachInfo == null) { 10779 return false; 10780 } 10781 //noinspection SimplifiableIfStatement 10782 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 10783 && !isHapticFeedbackEnabled()) { 10784 return false; 10785 } 10786 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 10787 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 10788 } 10789 10790 /** 10791 * Request that the visibility of the status bar be changed. 10792 */ 10793 public void setSystemUiVisibility(int visibility) { 10794 if (visibility != mSystemUiVisibility) { 10795 mSystemUiVisibility = visibility; 10796 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 10797 mParent.recomputeViewAttributes(this); 10798 } 10799 } 10800 } 10801 10802 /** 10803 * Returns the status bar visibility that this view has requested. 10804 */ 10805 public int getSystemUiVisibility() { 10806 return mSystemUiVisibility; 10807 } 10808 10809 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 10810 mOnSystemUiVisibilityChangeListener = l; 10811 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 10812 mParent.recomputeViewAttributes(this); 10813 } 10814 } 10815 10816 /** 10817 */ 10818 public void dispatchSystemUiVisibilityChanged(int visibility) { 10819 mSystemUiVisibility = visibility; 10820 if (mOnSystemUiVisibilityChangeListener != null) { 10821 mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(visibility); 10822 } 10823 } 10824 10825 /** 10826 * !!! TODO: real docs 10827 * 10828 * The base class implementation makes the shadow the same size and appearance 10829 * as the view itself, and positions it with its center at the touch point. 10830 */ 10831 public static class DragShadowBuilder { 10832 private final WeakReference<View> mView; 10833 10834 /** 10835 * Construct a shadow builder object for use with the given View object. The 10836 * default implementation will construct a drag shadow the same size and 10837 * appearance as the supplied View. 10838 * 10839 * @param view A view within the application's layout whose appearance 10840 * should be replicated as the drag shadow. 10841 */ 10842 public DragShadowBuilder(View view) { 10843 mView = new WeakReference<View>(view); 10844 } 10845 10846 /** 10847 * Construct a shadow builder object with no associated View. This 10848 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 10849 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 10850 * to supply the drag shadow's dimensions and appearance without 10851 * reference to any View object. 10852 */ 10853 public DragShadowBuilder() { 10854 mView = new WeakReference<View>(null); 10855 } 10856 10857 /** 10858 * Returns the View object that had been passed to the 10859 * {@link #View.DragShadowBuilder(View)} 10860 * constructor. If that View parameter was {@code null} or if the 10861 * {@link #View.DragShadowBuilder()} 10862 * constructor was used to instantiate the builder object, this method will return 10863 * null. 10864 * 10865 * @return The View object associate with this builder object. 10866 */ 10867 final public View getView() { 10868 return mView.get(); 10869 } 10870 10871 /** 10872 * Provide the draggable-shadow metrics for the operation: the dimensions of 10873 * the shadow image itself, and the point within that shadow that should 10874 * be centered under the touch location while dragging. 10875 * <p> 10876 * The default implementation sets the dimensions of the shadow to be the 10877 * same as the dimensions of the View object that had been supplied to the 10878 * {@link #View.DragShadowBuilder(View)} constructor 10879 * when the builder object was instantiated, and centers the shadow under the touch 10880 * point. 10881 * 10882 * @param shadowSize The application should set the {@code x} member of this 10883 * parameter to the desired shadow width, and the {@code y} member to 10884 * the desired height. 10885 * @param shadowTouchPoint The application should set this point to be the 10886 * location within the shadow that should track directly underneath 10887 * the touch point on the screen during a drag. 10888 */ 10889 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 10890 final View view = mView.get(); 10891 if (view != null) { 10892 shadowSize.set(view.getWidth(), view.getHeight()); 10893 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 10894 } else { 10895 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 10896 } 10897 } 10898 10899 /** 10900 * Draw the shadow image for the upcoming drag. The shadow canvas was 10901 * created with the dimensions supplied by the 10902 * {@link #onProvideShadowMetrics(Point, Point)} callback. 10903 * <p> 10904 * The default implementation replicates the appearance of the View object 10905 * that had been supplied to the 10906 * {@link #View.DragShadowBuilder(View)} 10907 * constructor when the builder object was instantiated. 10908 * 10909 * @param canvas 10910 */ 10911 public void onDrawShadow(Canvas canvas) { 10912 final View view = mView.get(); 10913 if (view != null) { 10914 view.draw(canvas); 10915 } else { 10916 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 10917 } 10918 } 10919 } 10920 10921 /** 10922 * Drag and drop. App calls startDrag(), then callbacks to the shadow builder's 10923 * {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} and 10924 * {@link DragShadowBuilder#onDrawShadow(Canvas)} methods happen, then the drag 10925 * operation is handed over to the OS. 10926 * !!! TODO: real docs 10927 * 10928 * @param data !!! TODO 10929 * @param shadowBuilder !!! TODO 10930 * @param myLocalState An arbitrary object that will be passed as part of every DragEvent 10931 * delivered to the calling application during the course of the current drag operation. 10932 * This object is private to the application that called startDrag(), and is not 10933 * visible to other applications. It provides a lightweight way for the application to 10934 * propagate information from the initiator to the recipient of a drag within its own 10935 * application; for example, to help disambiguate between 'copy' and 'move' semantics. 10936 * @param flags Flags affecting the drag operation. At present no flags are defined; 10937 * pass 0 for this parameter. 10938 * @return {@code true} if the drag operation was initiated successfully; {@code false} if 10939 * an error prevented the drag from taking place. 10940 */ 10941 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 10942 Object myLocalState, int flags) { 10943 if (ViewDebug.DEBUG_DRAG) { 10944 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 10945 } 10946 boolean okay = false; 10947 10948 Point shadowSize = new Point(); 10949 Point shadowTouchPoint = new Point(); 10950 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 10951 10952 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 10953 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 10954 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 10955 } 10956 10957 if (ViewDebug.DEBUG_DRAG) { 10958 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 10959 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 10960 } 10961 Surface surface = new Surface(); 10962 try { 10963 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 10964 flags, shadowSize.x, shadowSize.y, surface); 10965 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 10966 + " surface=" + surface); 10967 if (token != null) { 10968 Canvas canvas = surface.lockCanvas(null); 10969 try { 10970 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 10971 shadowBuilder.onDrawShadow(canvas); 10972 } finally { 10973 surface.unlockCanvasAndPost(canvas); 10974 } 10975 10976 final ViewRoot root = getViewRoot(); 10977 10978 // Cache the local state object for delivery with DragEvents 10979 root.setLocalDragState(myLocalState); 10980 10981 // repurpose 'shadowSize' for the last touch point 10982 root.getLastTouchPoint(shadowSize); 10983 10984 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 10985 shadowSize.x, shadowSize.y, 10986 shadowTouchPoint.x, shadowTouchPoint.y, data); 10987 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 10988 } 10989 } catch (Exception e) { 10990 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 10991 surface.destroy(); 10992 } 10993 10994 return okay; 10995 } 10996 10997 /** 10998 * Drag-and-drop event dispatch. The event.getAction() verb is one of the DragEvent 10999 * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT. 11000 * 11001 * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content 11002 * being dragged. onDragEvent() should return 'true' if the view can handle 11003 * a drop of that content. A view that returns 'false' here will receive no 11004 * further calls to onDragEvent() about the drag/drop operation. 11005 * 11006 * For DRAG_ENTERED, event.getClipDescription() describes the content being 11007 * dragged. This will be the same content description passed in the 11008 * DRAG_STARTED_EVENT invocation. 11009 * 11010 * For DRAG_EXITED, event.getClipDescription() describes the content being 11011 * dragged. This will be the same content description passed in the 11012 * DRAG_STARTED_EVENT invocation. The view should return to its approriate 11013 * drag-acceptance visual state. 11014 * 11015 * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View 11016 * coordinates of the current drag point. The view must return 'true' if it 11017 * can accept a drop of the current drag content, false otherwise. 11018 * 11019 * For DROP_EVENT, event.getX() and event.getY() give the location of the drop 11020 * within the view; also, event.getClipData() returns the full data payload 11021 * being dropped. The view should return 'true' if it consumed the dropped 11022 * content, 'false' if it did not. 11023 * 11024 * For DRAG_ENDED_EVENT, the 'event' argument may be null. The view should return 11025 * to its normal visual state. 11026 */ 11027 public boolean onDragEvent(DragEvent event) { 11028 return false; 11029 } 11030 11031 /** 11032 * Views typically don't need to override dispatchDragEvent(); it just calls 11033 * onDragEvent(event) and passes the result up appropriately. 11034 */ 11035 public boolean dispatchDragEvent(DragEvent event) { 11036 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 11037 && mOnDragListener.onDrag(this, event)) { 11038 return true; 11039 } 11040 return onDragEvent(event); 11041 } 11042 11043 /** 11044 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 11045 * it is ever exposed at all. 11046 * @hide 11047 */ 11048 public void onCloseSystemDialogs(String reason) { 11049 } 11050 11051 /** 11052 * Given a Drawable whose bounds have been set to draw into this view, 11053 * update a Region being computed for {@link #gatherTransparentRegion} so 11054 * that any non-transparent parts of the Drawable are removed from the 11055 * given transparent region. 11056 * 11057 * @param dr The Drawable whose transparency is to be applied to the region. 11058 * @param region A Region holding the current transparency information, 11059 * where any parts of the region that are set are considered to be 11060 * transparent. On return, this region will be modified to have the 11061 * transparency information reduced by the corresponding parts of the 11062 * Drawable that are not transparent. 11063 * {@hide} 11064 */ 11065 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 11066 if (DBG) { 11067 Log.i("View", "Getting transparent region for: " + this); 11068 } 11069 final Region r = dr.getTransparentRegion(); 11070 final Rect db = dr.getBounds(); 11071 final AttachInfo attachInfo = mAttachInfo; 11072 if (r != null && attachInfo != null) { 11073 final int w = getRight()-getLeft(); 11074 final int h = getBottom()-getTop(); 11075 if (db.left > 0) { 11076 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 11077 r.op(0, 0, db.left, h, Region.Op.UNION); 11078 } 11079 if (db.right < w) { 11080 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 11081 r.op(db.right, 0, w, h, Region.Op.UNION); 11082 } 11083 if (db.top > 0) { 11084 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 11085 r.op(0, 0, w, db.top, Region.Op.UNION); 11086 } 11087 if (db.bottom < h) { 11088 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 11089 r.op(0, db.bottom, w, h, Region.Op.UNION); 11090 } 11091 final int[] location = attachInfo.mTransparentLocation; 11092 getLocationInWindow(location); 11093 r.translate(location[0], location[1]); 11094 region.op(r, Region.Op.INTERSECT); 11095 } else { 11096 region.op(db, Region.Op.DIFFERENCE); 11097 } 11098 } 11099 11100 private void postCheckForLongClick(int delayOffset) { 11101 mHasPerformedLongPress = false; 11102 11103 if (mPendingCheckForLongPress == null) { 11104 mPendingCheckForLongPress = new CheckForLongPress(); 11105 } 11106 mPendingCheckForLongPress.rememberWindowAttachCount(); 11107 postDelayed(mPendingCheckForLongPress, 11108 ViewConfiguration.getLongPressTimeout() - delayOffset); 11109 } 11110 11111 /** 11112 * Inflate a view from an XML resource. This convenience method wraps the {@link 11113 * LayoutInflater} class, which provides a full range of options for view inflation. 11114 * 11115 * @param context The Context object for your activity or application. 11116 * @param resource The resource ID to inflate 11117 * @param root A view group that will be the parent. Used to properly inflate the 11118 * layout_* parameters. 11119 * @see LayoutInflater 11120 */ 11121 public static View inflate(Context context, int resource, ViewGroup root) { 11122 LayoutInflater factory = LayoutInflater.from(context); 11123 return factory.inflate(resource, root); 11124 } 11125 11126 /** 11127 * Scroll the view with standard behavior for scrolling beyond the normal 11128 * content boundaries. Views that call this method should override 11129 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 11130 * results of an over-scroll operation. 11131 * 11132 * Views can use this method to handle any touch or fling-based scrolling. 11133 * 11134 * @param deltaX Change in X in pixels 11135 * @param deltaY Change in Y in pixels 11136 * @param scrollX Current X scroll value in pixels before applying deltaX 11137 * @param scrollY Current Y scroll value in pixels before applying deltaY 11138 * @param scrollRangeX Maximum content scroll range along the X axis 11139 * @param scrollRangeY Maximum content scroll range along the Y axis 11140 * @param maxOverScrollX Number of pixels to overscroll by in either direction 11141 * along the X axis. 11142 * @param maxOverScrollY Number of pixels to overscroll by in either direction 11143 * along the Y axis. 11144 * @param isTouchEvent true if this scroll operation is the result of a touch event. 11145 * @return true if scrolling was clamped to an over-scroll boundary along either 11146 * axis, false otherwise. 11147 */ 11148 protected boolean overScrollBy(int deltaX, int deltaY, 11149 int scrollX, int scrollY, 11150 int scrollRangeX, int scrollRangeY, 11151 int maxOverScrollX, int maxOverScrollY, 11152 boolean isTouchEvent) { 11153 final int overScrollMode = mOverScrollMode; 11154 final boolean canScrollHorizontal = 11155 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 11156 final boolean canScrollVertical = 11157 computeVerticalScrollRange() > computeVerticalScrollExtent(); 11158 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 11159 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 11160 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 11161 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 11162 11163 int newScrollX = scrollX + deltaX; 11164 if (!overScrollHorizontal) { 11165 maxOverScrollX = 0; 11166 } 11167 11168 int newScrollY = scrollY + deltaY; 11169 if (!overScrollVertical) { 11170 maxOverScrollY = 0; 11171 } 11172 11173 // Clamp values if at the limits and record 11174 final int left = -maxOverScrollX; 11175 final int right = maxOverScrollX + scrollRangeX; 11176 final int top = -maxOverScrollY; 11177 final int bottom = maxOverScrollY + scrollRangeY; 11178 11179 boolean clampedX = false; 11180 if (newScrollX > right) { 11181 newScrollX = right; 11182 clampedX = true; 11183 } else if (newScrollX < left) { 11184 newScrollX = left; 11185 clampedX = true; 11186 } 11187 11188 boolean clampedY = false; 11189 if (newScrollY > bottom) { 11190 newScrollY = bottom; 11191 clampedY = true; 11192 } else if (newScrollY < top) { 11193 newScrollY = top; 11194 clampedY = true; 11195 } 11196 11197 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 11198 11199 return clampedX || clampedY; 11200 } 11201 11202 /** 11203 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 11204 * respond to the results of an over-scroll operation. 11205 * 11206 * @param scrollX New X scroll value in pixels 11207 * @param scrollY New Y scroll value in pixels 11208 * @param clampedX True if scrollX was clamped to an over-scroll boundary 11209 * @param clampedY True if scrollY was clamped to an over-scroll boundary 11210 */ 11211 protected void onOverScrolled(int scrollX, int scrollY, 11212 boolean clampedX, boolean clampedY) { 11213 // Intentionally empty. 11214 } 11215 11216 /** 11217 * Returns the over-scroll mode for this view. The result will be 11218 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 11219 * (allow over-scrolling only if the view content is larger than the container), 11220 * or {@link #OVER_SCROLL_NEVER}. 11221 * 11222 * @return This view's over-scroll mode. 11223 */ 11224 public int getOverScrollMode() { 11225 return mOverScrollMode; 11226 } 11227 11228 /** 11229 * Set the over-scroll mode for this view. Valid over-scroll modes are 11230 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 11231 * (allow over-scrolling only if the view content is larger than the container), 11232 * or {@link #OVER_SCROLL_NEVER}. 11233 * 11234 * Setting the over-scroll mode of a view will have an effect only if the 11235 * view is capable of scrolling. 11236 * 11237 * @param overScrollMode The new over-scroll mode for this view. 11238 */ 11239 public void setOverScrollMode(int overScrollMode) { 11240 if (overScrollMode != OVER_SCROLL_ALWAYS && 11241 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 11242 overScrollMode != OVER_SCROLL_NEVER) { 11243 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 11244 } 11245 mOverScrollMode = overScrollMode; 11246 } 11247 11248 /** 11249 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 11250 * Each MeasureSpec represents a requirement for either the width or the height. 11251 * A MeasureSpec is comprised of a size and a mode. There are three possible 11252 * modes: 11253 * <dl> 11254 * <dt>UNSPECIFIED</dt> 11255 * <dd> 11256 * The parent has not imposed any constraint on the child. It can be whatever size 11257 * it wants. 11258 * </dd> 11259 * 11260 * <dt>EXACTLY</dt> 11261 * <dd> 11262 * The parent has determined an exact size for the child. The child is going to be 11263 * given those bounds regardless of how big it wants to be. 11264 * </dd> 11265 * 11266 * <dt>AT_MOST</dt> 11267 * <dd> 11268 * The child can be as large as it wants up to the specified size. 11269 * </dd> 11270 * </dl> 11271 * 11272 * MeasureSpecs are implemented as ints to reduce object allocation. This class 11273 * is provided to pack and unpack the <size, mode> tuple into the int. 11274 */ 11275 public static class MeasureSpec { 11276 private static final int MODE_SHIFT = 30; 11277 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 11278 11279 /** 11280 * Measure specification mode: The parent has not imposed any constraint 11281 * on the child. It can be whatever size it wants. 11282 */ 11283 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 11284 11285 /** 11286 * Measure specification mode: The parent has determined an exact size 11287 * for the child. The child is going to be given those bounds regardless 11288 * of how big it wants to be. 11289 */ 11290 public static final int EXACTLY = 1 << MODE_SHIFT; 11291 11292 /** 11293 * Measure specification mode: The child can be as large as it wants up 11294 * to the specified size. 11295 */ 11296 public static final int AT_MOST = 2 << MODE_SHIFT; 11297 11298 /** 11299 * Creates a measure specification based on the supplied size and mode. 11300 * 11301 * The mode must always be one of the following: 11302 * <ul> 11303 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 11304 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 11305 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 11306 * </ul> 11307 * 11308 * @param size the size of the measure specification 11309 * @param mode the mode of the measure specification 11310 * @return the measure specification based on size and mode 11311 */ 11312 public static int makeMeasureSpec(int size, int mode) { 11313 return size + mode; 11314 } 11315 11316 /** 11317 * Extracts the mode from the supplied measure specification. 11318 * 11319 * @param measureSpec the measure specification to extract the mode from 11320 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 11321 * {@link android.view.View.MeasureSpec#AT_MOST} or 11322 * {@link android.view.View.MeasureSpec#EXACTLY} 11323 */ 11324 public static int getMode(int measureSpec) { 11325 return (measureSpec & MODE_MASK); 11326 } 11327 11328 /** 11329 * Extracts the size from the supplied measure specification. 11330 * 11331 * @param measureSpec the measure specification to extract the size from 11332 * @return the size in pixels defined in the supplied measure specification 11333 */ 11334 public static int getSize(int measureSpec) { 11335 return (measureSpec & ~MODE_MASK); 11336 } 11337 11338 /** 11339 * Returns a String representation of the specified measure 11340 * specification. 11341 * 11342 * @param measureSpec the measure specification to convert to a String 11343 * @return a String with the following format: "MeasureSpec: MODE SIZE" 11344 */ 11345 public static String toString(int measureSpec) { 11346 int mode = getMode(measureSpec); 11347 int size = getSize(measureSpec); 11348 11349 StringBuilder sb = new StringBuilder("MeasureSpec: "); 11350 11351 if (mode == UNSPECIFIED) 11352 sb.append("UNSPECIFIED "); 11353 else if (mode == EXACTLY) 11354 sb.append("EXACTLY "); 11355 else if (mode == AT_MOST) 11356 sb.append("AT_MOST "); 11357 else 11358 sb.append(mode).append(" "); 11359 11360 sb.append(size); 11361 return sb.toString(); 11362 } 11363 } 11364 11365 class CheckForLongPress implements Runnable { 11366 11367 private int mOriginalWindowAttachCount; 11368 11369 public void run() { 11370 if (isPressed() && (mParent != null) 11371 && mOriginalWindowAttachCount == mWindowAttachCount) { 11372 if (performLongClick()) { 11373 mHasPerformedLongPress = true; 11374 } 11375 } 11376 } 11377 11378 public void rememberWindowAttachCount() { 11379 mOriginalWindowAttachCount = mWindowAttachCount; 11380 } 11381 } 11382 11383 private final class CheckForTap implements Runnable { 11384 public void run() { 11385 mPrivateFlags &= ~PREPRESSED; 11386 mPrivateFlags |= PRESSED; 11387 refreshDrawableState(); 11388 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 11389 postCheckForLongClick(ViewConfiguration.getTapTimeout()); 11390 } 11391 } 11392 } 11393 11394 private final class PerformClick implements Runnable { 11395 public void run() { 11396 performClick(); 11397 } 11398 } 11399 11400 /** @hide */ 11401 public void hackTurnOffWindowResizeAnim(boolean off) { 11402 mAttachInfo.mTurnOffWindowResizeAnim = off; 11403 } 11404 11405 /** 11406 * Interface definition for a callback to be invoked when a key event is 11407 * dispatched to this view. The callback will be invoked before the key 11408 * event is given to the view. 11409 */ 11410 public interface OnKeyListener { 11411 /** 11412 * Called when a key is dispatched to a view. This allows listeners to 11413 * get a chance to respond before the target view. 11414 * 11415 * @param v The view the key has been dispatched to. 11416 * @param keyCode The code for the physical key that was pressed 11417 * @param event The KeyEvent object containing full information about 11418 * the event. 11419 * @return True if the listener has consumed the event, false otherwise. 11420 */ 11421 boolean onKey(View v, int keyCode, KeyEvent event); 11422 } 11423 11424 /** 11425 * Interface definition for a callback to be invoked when a touch event is 11426 * dispatched to this view. The callback will be invoked before the touch 11427 * event is given to the view. 11428 */ 11429 public interface OnTouchListener { 11430 /** 11431 * Called when a touch event is dispatched to a view. This allows listeners to 11432 * get a chance to respond before the target view. 11433 * 11434 * @param v The view the touch event has been dispatched to. 11435 * @param event The MotionEvent object containing full information about 11436 * the event. 11437 * @return True if the listener has consumed the event, false otherwise. 11438 */ 11439 boolean onTouch(View v, MotionEvent event); 11440 } 11441 11442 /** 11443 * Interface definition for a callback to be invoked when a view has been clicked and held. 11444 */ 11445 public interface OnLongClickListener { 11446 /** 11447 * Called when a view has been clicked and held. 11448 * 11449 * @param v The view that was clicked and held. 11450 * 11451 * @return true if the callback consumed the long click, false otherwise. 11452 */ 11453 boolean onLongClick(View v); 11454 } 11455 11456 /** 11457 * Interface definition for a callback to be invoked when a drag is being dispatched 11458 * to this view. The callback will be invoked before the hosting view's own 11459 * onDrag(event) method. If the listener wants to fall back to the hosting view's 11460 * onDrag(event) behavior, it should return 'false' from this callback. 11461 */ 11462 public interface OnDragListener { 11463 /** 11464 * Called when a drag event is dispatched to a view. This allows listeners 11465 * to get a chance to override base View behavior. 11466 * 11467 * @param v The view the drag has been dispatched to. 11468 * @param event The DragEvent object containing full information 11469 * about the event. 11470 * @return true if the listener consumed the DragEvent, false in order to fall 11471 * back to the view's default handling. 11472 */ 11473 boolean onDrag(View v, DragEvent event); 11474 } 11475 11476 /** 11477 * Interface definition for a callback to be invoked when the focus state of 11478 * a view changed. 11479 */ 11480 public interface OnFocusChangeListener { 11481 /** 11482 * Called when the focus state of a view has changed. 11483 * 11484 * @param v The view whose state has changed. 11485 * @param hasFocus The new focus state of v. 11486 */ 11487 void onFocusChange(View v, boolean hasFocus); 11488 } 11489 11490 /** 11491 * Interface definition for a callback to be invoked when a view is clicked. 11492 */ 11493 public interface OnClickListener { 11494 /** 11495 * Called when a view has been clicked. 11496 * 11497 * @param v The view that was clicked. 11498 */ 11499 void onClick(View v); 11500 } 11501 11502 /** 11503 * Interface definition for a callback to be invoked when the context menu 11504 * for this view is being built. 11505 */ 11506 public interface OnCreateContextMenuListener { 11507 /** 11508 * Called when the context menu for this view is being built. It is not 11509 * safe to hold onto the menu after this method returns. 11510 * 11511 * @param menu The context menu that is being built 11512 * @param v The view for which the context menu is being built 11513 * @param menuInfo Extra information about the item for which the 11514 * context menu should be shown. This information will vary 11515 * depending on the class of v. 11516 */ 11517 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 11518 } 11519 11520 /** 11521 * Interface definition for a callback to be invoked when the status bar changes 11522 * visibility. 11523 * 11524 * @see #setOnSystemUiVisibilityChangeListener 11525 */ 11526 public interface OnSystemUiVisibilityChangeListener { 11527 /** 11528 * Called when the status bar changes visibility because of a call to 11529 * {@link #setSystemUiVisibility}. 11530 * 11531 * @param visibility {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}. 11532 */ 11533 public void onSystemUiVisibilityChange(int visibility); 11534 } 11535 11536 private final class UnsetPressedState implements Runnable { 11537 public void run() { 11538 setPressed(false); 11539 } 11540 } 11541 11542 /** 11543 * Base class for derived classes that want to save and restore their own 11544 * state in {@link android.view.View#onSaveInstanceState()}. 11545 */ 11546 public static class BaseSavedState extends AbsSavedState { 11547 /** 11548 * Constructor used when reading from a parcel. Reads the state of the superclass. 11549 * 11550 * @param source 11551 */ 11552 public BaseSavedState(Parcel source) { 11553 super(source); 11554 } 11555 11556 /** 11557 * Constructor called by derived classes when creating their SavedState objects 11558 * 11559 * @param superState The state of the superclass of this view 11560 */ 11561 public BaseSavedState(Parcelable superState) { 11562 super(superState); 11563 } 11564 11565 public static final Parcelable.Creator<BaseSavedState> CREATOR = 11566 new Parcelable.Creator<BaseSavedState>() { 11567 public BaseSavedState createFromParcel(Parcel in) { 11568 return new BaseSavedState(in); 11569 } 11570 11571 public BaseSavedState[] newArray(int size) { 11572 return new BaseSavedState[size]; 11573 } 11574 }; 11575 } 11576 11577 /** 11578 * A set of information given to a view when it is attached to its parent 11579 * window. 11580 */ 11581 static class AttachInfo { 11582 interface Callbacks { 11583 void playSoundEffect(int effectId); 11584 boolean performHapticFeedback(int effectId, boolean always); 11585 } 11586 11587 /** 11588 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 11589 * to a Handler. This class contains the target (View) to invalidate and 11590 * the coordinates of the dirty rectangle. 11591 * 11592 * For performance purposes, this class also implements a pool of up to 11593 * POOL_LIMIT objects that get reused. This reduces memory allocations 11594 * whenever possible. 11595 */ 11596 static class InvalidateInfo implements Poolable<InvalidateInfo> { 11597 private static final int POOL_LIMIT = 10; 11598 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 11599 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 11600 public InvalidateInfo newInstance() { 11601 return new InvalidateInfo(); 11602 } 11603 11604 public void onAcquired(InvalidateInfo element) { 11605 } 11606 11607 public void onReleased(InvalidateInfo element) { 11608 } 11609 }, POOL_LIMIT) 11610 ); 11611 11612 private InvalidateInfo mNext; 11613 11614 View target; 11615 11616 int left; 11617 int top; 11618 int right; 11619 int bottom; 11620 11621 public void setNextPoolable(InvalidateInfo element) { 11622 mNext = element; 11623 } 11624 11625 public InvalidateInfo getNextPoolable() { 11626 return mNext; 11627 } 11628 11629 static InvalidateInfo acquire() { 11630 return sPool.acquire(); 11631 } 11632 11633 void release() { 11634 sPool.release(this); 11635 } 11636 } 11637 11638 final IWindowSession mSession; 11639 11640 final IWindow mWindow; 11641 11642 final IBinder mWindowToken; 11643 11644 final Callbacks mRootCallbacks; 11645 11646 Canvas mHardwareCanvas; 11647 11648 /** 11649 * The top view of the hierarchy. 11650 */ 11651 View mRootView; 11652 11653 IBinder mPanelParentWindowToken; 11654 Surface mSurface; 11655 11656 boolean mHardwareAccelerated; 11657 boolean mHardwareAccelerationRequested; 11658 HardwareRenderer mHardwareRenderer; 11659 11660 /** 11661 * Scale factor used by the compatibility mode 11662 */ 11663 float mApplicationScale; 11664 11665 /** 11666 * Indicates whether the application is in compatibility mode 11667 */ 11668 boolean mScalingRequired; 11669 11670 /** 11671 * If set, ViewRoot doesn't use its lame animation for when the window resizes. 11672 */ 11673 boolean mTurnOffWindowResizeAnim; 11674 11675 /** 11676 * Left position of this view's window 11677 */ 11678 int mWindowLeft; 11679 11680 /** 11681 * Top position of this view's window 11682 */ 11683 int mWindowTop; 11684 11685 /** 11686 * Indicates whether views need to use 32-bit drawing caches 11687 */ 11688 boolean mUse32BitDrawingCache; 11689 11690 /** 11691 * For windows that are full-screen but using insets to layout inside 11692 * of the screen decorations, these are the current insets for the 11693 * content of the window. 11694 */ 11695 final Rect mContentInsets = new Rect(); 11696 11697 /** 11698 * For windows that are full-screen but using insets to layout inside 11699 * of the screen decorations, these are the current insets for the 11700 * actual visible parts of the window. 11701 */ 11702 final Rect mVisibleInsets = new Rect(); 11703 11704 /** 11705 * The internal insets given by this window. This value is 11706 * supplied by the client (through 11707 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 11708 * be given to the window manager when changed to be used in laying 11709 * out windows behind it. 11710 */ 11711 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 11712 = new ViewTreeObserver.InternalInsetsInfo(); 11713 11714 /** 11715 * All views in the window's hierarchy that serve as scroll containers, 11716 * used to determine if the window can be resized or must be panned 11717 * to adjust for a soft input area. 11718 */ 11719 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 11720 11721 final KeyEvent.DispatcherState mKeyDispatchState 11722 = new KeyEvent.DispatcherState(); 11723 11724 /** 11725 * Indicates whether the view's window currently has the focus. 11726 */ 11727 boolean mHasWindowFocus; 11728 11729 /** 11730 * The current visibility of the window. 11731 */ 11732 int mWindowVisibility; 11733 11734 /** 11735 * Indicates the time at which drawing started to occur. 11736 */ 11737 long mDrawingTime; 11738 11739 /** 11740 * Indicates whether or not ignoring the DIRTY_MASK flags. 11741 */ 11742 boolean mIgnoreDirtyState; 11743 11744 /** 11745 * Indicates whether the view's window is currently in touch mode. 11746 */ 11747 boolean mInTouchMode; 11748 11749 /** 11750 * Indicates that ViewRoot should trigger a global layout change 11751 * the next time it performs a traversal 11752 */ 11753 boolean mRecomputeGlobalAttributes; 11754 11755 /** 11756 * Set during a traveral if any views want to keep the screen on. 11757 */ 11758 boolean mKeepScreenOn; 11759 11760 /** 11761 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 11762 */ 11763 int mSystemUiVisibility; 11764 11765 /** 11766 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 11767 * attached. 11768 */ 11769 boolean mHasSystemUiListeners; 11770 11771 /** 11772 * Set if the visibility of any views has changed. 11773 */ 11774 boolean mViewVisibilityChanged; 11775 11776 /** 11777 * Set to true if a view has been scrolled. 11778 */ 11779 boolean mViewScrollChanged; 11780 11781 /** 11782 * Global to the view hierarchy used as a temporary for dealing with 11783 * x/y points in the transparent region computations. 11784 */ 11785 final int[] mTransparentLocation = new int[2]; 11786 11787 /** 11788 * Global to the view hierarchy used as a temporary for dealing with 11789 * x/y points in the ViewGroup.invalidateChild implementation. 11790 */ 11791 final int[] mInvalidateChildLocation = new int[2]; 11792 11793 11794 /** 11795 * Global to the view hierarchy used as a temporary for dealing with 11796 * x/y location when view is transformed. 11797 */ 11798 final float[] mTmpTransformLocation = new float[2]; 11799 11800 /** 11801 * The view tree observer used to dispatch global events like 11802 * layout, pre-draw, touch mode change, etc. 11803 */ 11804 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 11805 11806 /** 11807 * A Canvas used by the view hierarchy to perform bitmap caching. 11808 */ 11809 Canvas mCanvas; 11810 11811 /** 11812 * A Handler supplied by a view's {@link android.view.ViewRoot}. This 11813 * handler can be used to pump events in the UI events queue. 11814 */ 11815 final Handler mHandler; 11816 11817 /** 11818 * Identifier for messages requesting the view to be invalidated. 11819 * Such messages should be sent to {@link #mHandler}. 11820 */ 11821 static final int INVALIDATE_MSG = 0x1; 11822 11823 /** 11824 * Identifier for messages requesting the view to invalidate a region. 11825 * Such messages should be sent to {@link #mHandler}. 11826 */ 11827 static final int INVALIDATE_RECT_MSG = 0x2; 11828 11829 /** 11830 * Temporary for use in computing invalidate rectangles while 11831 * calling up the hierarchy. 11832 */ 11833 final Rect mTmpInvalRect = new Rect(); 11834 11835 /** 11836 * Temporary for use in computing hit areas with transformed views 11837 */ 11838 final RectF mTmpTransformRect = new RectF(); 11839 11840 /** 11841 * Temporary list for use in collecting focusable descendents of a view. 11842 */ 11843 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 11844 11845 /** 11846 * Creates a new set of attachment information with the specified 11847 * events handler and thread. 11848 * 11849 * @param handler the events handler the view must use 11850 */ 11851 AttachInfo(IWindowSession session, IWindow window, 11852 Handler handler, Callbacks effectPlayer) { 11853 mSession = session; 11854 mWindow = window; 11855 mWindowToken = window.asBinder(); 11856 mHandler = handler; 11857 mRootCallbacks = effectPlayer; 11858 } 11859 } 11860 11861 /** 11862 * <p>ScrollabilityCache holds various fields used by a View when scrolling 11863 * is supported. This avoids keeping too many unused fields in most 11864 * instances of View.</p> 11865 */ 11866 private static class ScrollabilityCache implements Runnable { 11867 11868 /** 11869 * Scrollbars are not visible 11870 */ 11871 public static final int OFF = 0; 11872 11873 /** 11874 * Scrollbars are visible 11875 */ 11876 public static final int ON = 1; 11877 11878 /** 11879 * Scrollbars are fading away 11880 */ 11881 public static final int FADING = 2; 11882 11883 public boolean fadeScrollBars; 11884 11885 public int fadingEdgeLength; 11886 public int scrollBarDefaultDelayBeforeFade; 11887 public int scrollBarFadeDuration; 11888 11889 public int scrollBarSize; 11890 public ScrollBarDrawable scrollBar; 11891 public float[] interpolatorValues; 11892 public View host; 11893 11894 public final Paint paint; 11895 public final Matrix matrix; 11896 public Shader shader; 11897 11898 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 11899 11900 private static final float[] OPAQUE = { 255 }; 11901 private static final float[] TRANSPARENT = { 0.0f }; 11902 11903 /** 11904 * When fading should start. This time moves into the future every time 11905 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 11906 */ 11907 public long fadeStartTime; 11908 11909 11910 /** 11911 * The current state of the scrollbars: ON, OFF, or FADING 11912 */ 11913 public int state = OFF; 11914 11915 private int mLastColor; 11916 11917 public ScrollabilityCache(ViewConfiguration configuration, View host) { 11918 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 11919 scrollBarSize = configuration.getScaledScrollBarSize(); 11920 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 11921 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 11922 11923 paint = new Paint(); 11924 matrix = new Matrix(); 11925 // use use a height of 1, and then wack the matrix each time we 11926 // actually use it. 11927 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 11928 11929 paint.setShader(shader); 11930 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 11931 this.host = host; 11932 } 11933 11934 public void setFadeColor(int color) { 11935 if (color != 0 && color != mLastColor) { 11936 mLastColor = color; 11937 color |= 0xFF000000; 11938 11939 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 11940 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 11941 11942 paint.setShader(shader); 11943 // Restore the default transfer mode (src_over) 11944 paint.setXfermode(null); 11945 } 11946 } 11947 11948 public void run() { 11949 long now = AnimationUtils.currentAnimationTimeMillis(); 11950 if (now >= fadeStartTime) { 11951 11952 // the animation fades the scrollbars out by changing 11953 // the opacity (alpha) from fully opaque to fully 11954 // transparent 11955 int nextFrame = (int) now; 11956 int framesCount = 0; 11957 11958 Interpolator interpolator = scrollBarInterpolator; 11959 11960 // Start opaque 11961 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 11962 11963 // End transparent 11964 nextFrame += scrollBarFadeDuration; 11965 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 11966 11967 state = FADING; 11968 11969 // Kick off the fade animation 11970 host.invalidate(true); 11971 } 11972 } 11973 11974 } 11975} 11976