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