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