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