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