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