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