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