View.java revision 55dbb6516d8b3d04ed23cfd613aee24bd525b965
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 mBackgroundSizeChanged = true; 5834 } 5835 } 5836 5837 /** 5838 * Bottom position of this view relative to its parent. 5839 * 5840 * @return The bottom of this view, in pixels. 5841 */ 5842 @ViewDebug.CapturedViewProperty 5843 public final int getBottom() { 5844 return mBottom; 5845 } 5846 5847 /** 5848 * Sets the bottom position of this view relative to its parent. This method is meant to be 5849 * called by the layout system and should not generally be called otherwise, because the 5850 * property may be changed at any time by the layout. 5851 * 5852 * @param bottom The bottom of this view, in pixels. 5853 */ 5854 public final void setBottom(int bottom) { 5855 if (bottom != mBottom) { 5856 updateMatrix(); 5857 if (mMatrixIsIdentity) { 5858 final ViewParent p = mParent; 5859 if (p != null && mAttachInfo != null) { 5860 final Rect r = mAttachInfo.mTmpInvalRect; 5861 int maxBottom; 5862 if (bottom < mBottom) { 5863 maxBottom = mBottom; 5864 } else { 5865 maxBottom = bottom; 5866 } 5867 r.set(0, 0, mRight - mLeft, maxBottom - mTop); 5868 p.invalidateChild(this, r); 5869 } 5870 } else { 5871 // Double-invalidation is necessary to capture view's old and new areas 5872 invalidate(); 5873 } 5874 5875 int width = mRight - mLeft; 5876 int oldHeight = mBottom - mTop; 5877 5878 mBottom = bottom; 5879 5880 onSizeChanged(width, mBottom - mTop, width, oldHeight); 5881 5882 if (!mMatrixIsIdentity) { 5883 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 5884 invalidate(); 5885 } 5886 mBackgroundSizeChanged = true; 5887 } 5888 } 5889 5890 /** 5891 * Left position of this view relative to its parent. 5892 * 5893 * @return The left edge of this view, in pixels. 5894 */ 5895 @ViewDebug.CapturedViewProperty 5896 public final int getLeft() { 5897 return mLeft; 5898 } 5899 5900 /** 5901 * Sets the left position of this view relative to its parent. This method is meant to be called 5902 * by the layout system and should not generally be called otherwise, because the property 5903 * may be changed at any time by the layout. 5904 * 5905 * @param left The bottom of this view, in pixels. 5906 */ 5907 public final void setLeft(int left) { 5908 if (left != mLeft) { 5909 updateMatrix(); 5910 if (mMatrixIsIdentity) { 5911 final ViewParent p = mParent; 5912 if (p != null && mAttachInfo != null) { 5913 final Rect r = mAttachInfo.mTmpInvalRect; 5914 int minLeft; 5915 int xLoc; 5916 if (left < mLeft) { 5917 minLeft = left; 5918 xLoc = left - mLeft; 5919 } else { 5920 minLeft = mLeft; 5921 xLoc = 0; 5922 } 5923 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop); 5924 p.invalidateChild(this, r); 5925 } 5926 } else { 5927 // Double-invalidation is necessary to capture view's old and new areas 5928 invalidate(); 5929 } 5930 5931 int oldWidth = mRight - mLeft; 5932 int height = mBottom - mTop; 5933 5934 mLeft = left; 5935 5936 onSizeChanged(mRight - mLeft, height, oldWidth, height); 5937 5938 if (!mMatrixIsIdentity) { 5939 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 5940 invalidate(); 5941 } 5942 mBackgroundSizeChanged = true; 5943 } 5944 } 5945 5946 /** 5947 * Right position of this view relative to its parent. 5948 * 5949 * @return The right edge of this view, in pixels. 5950 */ 5951 @ViewDebug.CapturedViewProperty 5952 public final int getRight() { 5953 return mRight; 5954 } 5955 5956 /** 5957 * Sets the right position of this view relative to its parent. This method is meant to be called 5958 * by the layout system and should not generally be called otherwise, because the property 5959 * may be changed at any time by the layout. 5960 * 5961 * @param right The bottom of this view, in pixels. 5962 */ 5963 public final void setRight(int right) { 5964 if (right != mRight) { 5965 updateMatrix(); 5966 if (mMatrixIsIdentity) { 5967 final ViewParent p = mParent; 5968 if (p != null && mAttachInfo != null) { 5969 final Rect r = mAttachInfo.mTmpInvalRect; 5970 int maxRight; 5971 if (right < mRight) { 5972 maxRight = mRight; 5973 } else { 5974 maxRight = right; 5975 } 5976 r.set(0, 0, maxRight - mLeft, mBottom - mTop); 5977 p.invalidateChild(this, r); 5978 } 5979 } else { 5980 // Double-invalidation is necessary to capture view's old and new areas 5981 invalidate(); 5982 } 5983 5984 int oldWidth = mRight - mLeft; 5985 int height = mBottom - mTop; 5986 5987 mRight = right; 5988 5989 onSizeChanged(mRight - mLeft, height, oldWidth, height); 5990 5991 if (!mMatrixIsIdentity) { 5992 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 5993 invalidate(); 5994 } 5995 mBackgroundSizeChanged = true; 5996 } 5997 } 5998 5999 /** 6000 * The visual x position of this view, in pixels. This is equivalent to the 6001 * {@link #setTranslationX(float) translationX} property plus the current 6002 * {@link #getLeft() left} property. 6003 * 6004 * @return The visual x position of this view, in pixels. 6005 */ 6006 public float getX() { 6007 return mLeft + mTranslationX; 6008 } 6009 6010 /** 6011 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 6012 * {@link #setTranslationX(float) translationX} property to be the difference between 6013 * the x value passed in and the current {@link #getLeft() left} property. 6014 * 6015 * @param x The visual x position of this view, in pixels. 6016 */ 6017 public void setX(float x) { 6018 setTranslationX(x - mLeft); 6019 } 6020 6021 /** 6022 * The visual y position of this view, in pixels. This is equivalent to the 6023 * {@link #setTranslationY(float) translationY} property plus the current 6024 * {@link #getTop() top} property. 6025 * 6026 * @return The visual y position of this view, in pixels. 6027 */ 6028 public float getY() { 6029 return mTop + mTranslationY; 6030 } 6031 6032 /** 6033 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 6034 * {@link #setTranslationY(float) translationY} property to be the difference between 6035 * the y value passed in and the current {@link #getTop() top} property. 6036 * 6037 * @param y The visual y position of this view, in pixels. 6038 */ 6039 public void setY(float y) { 6040 setTranslationY(y - mTop); 6041 } 6042 6043 6044 /** 6045 * The horizontal location of this view relative to its {@link #getLeft() left} position. 6046 * This position is post-layout, in addition to wherever the object's 6047 * layout placed it. 6048 * 6049 * @return The horizontal position of this view relative to its left position, in pixels. 6050 */ 6051 public float getTranslationX() { 6052 return mTranslationX; 6053 } 6054 6055 /** 6056 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 6057 * This effectively positions the object post-layout, in addition to wherever the object's 6058 * layout placed it. 6059 * 6060 * @param translationX The horizontal position of this view relative to its left position, 6061 * in pixels. 6062 * 6063 * @attr ref android.R.styleable#View_translationX 6064 */ 6065 public void setTranslationX(float translationX) { 6066 if (mTranslationX != translationX) { 6067 // Double-invalidation is necessary to capture view's old and new areas 6068 invalidate(false); 6069 mTranslationX = translationX; 6070 mMatrixDirty = true; 6071 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6072 invalidate(false); 6073 } 6074 } 6075 6076 /** 6077 * The horizontal location of this view relative to its {@link #getTop() top} position. 6078 * This position is post-layout, in addition to wherever the object's 6079 * layout placed it. 6080 * 6081 * @return The vertical position of this view relative to its top position, 6082 * in pixels. 6083 */ 6084 public float getTranslationY() { 6085 return mTranslationY; 6086 } 6087 6088 /** 6089 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 6090 * This effectively positions the object post-layout, in addition to wherever the object's 6091 * layout placed it. 6092 * 6093 * @param translationY The vertical position of this view relative to its top position, 6094 * in pixels. 6095 * 6096 * @attr ref android.R.styleable#View_translationY 6097 */ 6098 public void setTranslationY(float translationY) { 6099 if (mTranslationY != translationY) { 6100 // Double-invalidation is necessary to capture view's old and new areas 6101 invalidate(false); 6102 mTranslationY = translationY; 6103 mMatrixDirty = true; 6104 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6105 invalidate(false); 6106 } 6107 } 6108 6109 /** 6110 * Hit rectangle in parent's coordinates 6111 * 6112 * @param outRect The hit rectangle of the view. 6113 */ 6114 public void getHitRect(Rect outRect) { 6115 updateMatrix(); 6116 if (mMatrixIsIdentity || mAttachInfo == null) { 6117 outRect.set(mLeft, mTop, mRight, mBottom); 6118 } else { 6119 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 6120 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY); 6121 mMatrix.mapRect(tmpRect); 6122 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 6123 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 6124 } 6125 } 6126 6127 /** 6128 * Determines whether the given point, in local coordinates is inside the view. 6129 */ 6130 /*package*/ final boolean pointInView(float localX, float localY) { 6131 return localX >= 0 && localX < (mRight - mLeft) 6132 && localY >= 0 && localY < (mBottom - mTop); 6133 } 6134 6135 /** 6136 * Utility method to determine whether the given point, in local coordinates, 6137 * is inside the view, where the area of the view is expanded by the slop factor. 6138 * This method is called while processing touch-move events to determine if the event 6139 * is still within the view. 6140 */ 6141 private boolean pointInView(float localX, float localY, float slop) { 6142 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 6143 localY < ((mBottom - mTop) + slop); 6144 } 6145 6146 /** 6147 * When a view has focus and the user navigates away from it, the next view is searched for 6148 * starting from the rectangle filled in by this method. 6149 * 6150 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your 6151 * view maintains some idea of internal selection, such as a cursor, or a selected row 6152 * or column, you should override this method and fill in a more specific rectangle. 6153 * 6154 * @param r The rectangle to fill in, in this view's coordinates. 6155 */ 6156 public void getFocusedRect(Rect r) { 6157 getDrawingRect(r); 6158 } 6159 6160 /** 6161 * If some part of this view is not clipped by any of its parents, then 6162 * return that area in r in global (root) coordinates. To convert r to local 6163 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x, 6164 * -globalOffset.y)) If the view is completely clipped or translated out, 6165 * return false. 6166 * 6167 * @param r If true is returned, r holds the global coordinates of the 6168 * visible portion of this view. 6169 * @param globalOffset If true is returned, globalOffset holds the dx,dy 6170 * between this view and its root. globalOffet may be null. 6171 * @return true if r is non-empty (i.e. part of the view is visible at the 6172 * root level. 6173 */ 6174 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 6175 int width = mRight - mLeft; 6176 int height = mBottom - mTop; 6177 if (width > 0 && height > 0) { 6178 r.set(0, 0, width, height); 6179 if (globalOffset != null) { 6180 globalOffset.set(-mScrollX, -mScrollY); 6181 } 6182 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 6183 } 6184 return false; 6185 } 6186 6187 public final boolean getGlobalVisibleRect(Rect r) { 6188 return getGlobalVisibleRect(r, null); 6189 } 6190 6191 public final boolean getLocalVisibleRect(Rect r) { 6192 Point offset = new Point(); 6193 if (getGlobalVisibleRect(r, offset)) { 6194 r.offset(-offset.x, -offset.y); // make r local 6195 return true; 6196 } 6197 return false; 6198 } 6199 6200 /** 6201 * Offset this view's vertical location by the specified number of pixels. 6202 * 6203 * @param offset the number of pixels to offset the view by 6204 */ 6205 public void offsetTopAndBottom(int offset) { 6206 if (offset != 0) { 6207 updateMatrix(); 6208 if (mMatrixIsIdentity) { 6209 final ViewParent p = mParent; 6210 if (p != null && mAttachInfo != null) { 6211 final Rect r = mAttachInfo.mTmpInvalRect; 6212 int minTop; 6213 int maxBottom; 6214 int yLoc; 6215 if (offset < 0) { 6216 minTop = mTop + offset; 6217 maxBottom = mBottom; 6218 yLoc = offset; 6219 } else { 6220 minTop = mTop; 6221 maxBottom = mBottom + offset; 6222 yLoc = 0; 6223 } 6224 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 6225 p.invalidateChild(this, r); 6226 } 6227 } else { 6228 invalidate(false); 6229 } 6230 6231 mTop += offset; 6232 mBottom += offset; 6233 6234 if (!mMatrixIsIdentity) { 6235 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6236 invalidate(false); 6237 } 6238 } 6239 } 6240 6241 /** 6242 * Offset this view's horizontal location by the specified amount of pixels. 6243 * 6244 * @param offset the numer of pixels to offset the view by 6245 */ 6246 public void offsetLeftAndRight(int offset) { 6247 if (offset != 0) { 6248 updateMatrix(); 6249 if (mMatrixIsIdentity) { 6250 final ViewParent p = mParent; 6251 if (p != null && mAttachInfo != null) { 6252 final Rect r = mAttachInfo.mTmpInvalRect; 6253 int minLeft; 6254 int maxRight; 6255 if (offset < 0) { 6256 minLeft = mLeft + offset; 6257 maxRight = mRight; 6258 } else { 6259 minLeft = mLeft; 6260 maxRight = mRight + offset; 6261 } 6262 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 6263 p.invalidateChild(this, r); 6264 } 6265 } else { 6266 invalidate(false); 6267 } 6268 6269 mLeft += offset; 6270 mRight += offset; 6271 6272 if (!mMatrixIsIdentity) { 6273 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6274 invalidate(false); 6275 } 6276 } 6277 } 6278 6279 /** 6280 * Get the LayoutParams associated with this view. All views should have 6281 * layout parameters. These supply parameters to the <i>parent</i> of this 6282 * view specifying how it should be arranged. There are many subclasses of 6283 * ViewGroup.LayoutParams, and these correspond to the different subclasses 6284 * of ViewGroup that are responsible for arranging their children. 6285 * @return The LayoutParams associated with this view 6286 */ 6287 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 6288 public ViewGroup.LayoutParams getLayoutParams() { 6289 return mLayoutParams; 6290 } 6291 6292 /** 6293 * Set the layout parameters associated with this view. These supply 6294 * parameters to the <i>parent</i> of this view specifying how it should be 6295 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 6296 * correspond to the different subclasses of ViewGroup that are responsible 6297 * for arranging their children. 6298 * 6299 * @param params the layout parameters for this view 6300 */ 6301 public void setLayoutParams(ViewGroup.LayoutParams params) { 6302 if (params == null) { 6303 throw new NullPointerException("params == null"); 6304 } 6305 mLayoutParams = params; 6306 requestLayout(); 6307 } 6308 6309 /** 6310 * Set the scrolled position of your view. This will cause a call to 6311 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6312 * invalidated. 6313 * @param x the x position to scroll to 6314 * @param y the y position to scroll to 6315 */ 6316 public void scrollTo(int x, int y) { 6317 if (mScrollX != x || mScrollY != y) { 6318 int oldX = mScrollX; 6319 int oldY = mScrollY; 6320 mScrollX = x; 6321 mScrollY = y; 6322 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 6323 if (!awakenScrollBars()) { 6324 invalidate(); 6325 } 6326 } 6327 } 6328 6329 /** 6330 * Move the scrolled position of your view. This will cause a call to 6331 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6332 * invalidated. 6333 * @param x the amount of pixels to scroll by horizontally 6334 * @param y the amount of pixels to scroll by vertically 6335 */ 6336 public void scrollBy(int x, int y) { 6337 scrollTo(mScrollX + x, mScrollY + y); 6338 } 6339 6340 /** 6341 * <p>Trigger the scrollbars to draw. When invoked this method starts an 6342 * animation to fade the scrollbars out after a default delay. If a subclass 6343 * provides animated scrolling, the start delay should equal the duration 6344 * of the scrolling animation.</p> 6345 * 6346 * <p>The animation starts only if at least one of the scrollbars is 6347 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 6348 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 6349 * this method returns true, and false otherwise. If the animation is 6350 * started, this method calls {@link #invalidate()}; in that case the 6351 * caller should not call {@link #invalidate()}.</p> 6352 * 6353 * <p>This method should be invoked every time a subclass directly updates 6354 * the scroll parameters.</p> 6355 * 6356 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 6357 * and {@link #scrollTo(int, int)}.</p> 6358 * 6359 * @return true if the animation is played, false otherwise 6360 * 6361 * @see #awakenScrollBars(int) 6362 * @see #scrollBy(int, int) 6363 * @see #scrollTo(int, int) 6364 * @see #isHorizontalScrollBarEnabled() 6365 * @see #isVerticalScrollBarEnabled() 6366 * @see #setHorizontalScrollBarEnabled(boolean) 6367 * @see #setVerticalScrollBarEnabled(boolean) 6368 */ 6369 protected boolean awakenScrollBars() { 6370 return mScrollCache != null && 6371 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 6372 } 6373 6374 /** 6375 * Trigger the scrollbars to draw. 6376 * This method differs from awakenScrollBars() only in its default duration. 6377 * initialAwakenScrollBars() will show the scroll bars for longer than 6378 * usual to give the user more of a chance to notice them. 6379 * 6380 * @return true if the animation is played, false otherwise. 6381 */ 6382 private boolean initialAwakenScrollBars() { 6383 return mScrollCache != null && 6384 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 6385 } 6386 6387 /** 6388 * <p> 6389 * Trigger the scrollbars to draw. When invoked this method starts an 6390 * animation to fade the scrollbars out after a fixed delay. If a subclass 6391 * provides animated scrolling, the start delay should equal the duration of 6392 * the scrolling animation. 6393 * </p> 6394 * 6395 * <p> 6396 * The animation starts only if at least one of the scrollbars is enabled, 6397 * as specified by {@link #isHorizontalScrollBarEnabled()} and 6398 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 6399 * this method returns true, and false otherwise. If the animation is 6400 * started, this method calls {@link #invalidate()}; in that case the caller 6401 * should not call {@link #invalidate()}. 6402 * </p> 6403 * 6404 * <p> 6405 * This method should be invoked everytime a subclass directly updates the 6406 * scroll parameters. 6407 * </p> 6408 * 6409 * @param startDelay the delay, in milliseconds, after which the animation 6410 * should start; when the delay is 0, the animation starts 6411 * immediately 6412 * @return true if the animation is played, false otherwise 6413 * 6414 * @see #scrollBy(int, int) 6415 * @see #scrollTo(int, int) 6416 * @see #isHorizontalScrollBarEnabled() 6417 * @see #isVerticalScrollBarEnabled() 6418 * @see #setHorizontalScrollBarEnabled(boolean) 6419 * @see #setVerticalScrollBarEnabled(boolean) 6420 */ 6421 protected boolean awakenScrollBars(int startDelay) { 6422 return awakenScrollBars(startDelay, true); 6423 } 6424 6425 /** 6426 * <p> 6427 * Trigger the scrollbars to draw. When invoked this method starts an 6428 * animation to fade the scrollbars out after a fixed delay. If a subclass 6429 * provides animated scrolling, the start delay should equal the duration of 6430 * the scrolling animation. 6431 * </p> 6432 * 6433 * <p> 6434 * The animation starts only if at least one of the scrollbars is enabled, 6435 * as specified by {@link #isHorizontalScrollBarEnabled()} and 6436 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 6437 * this method returns true, and false otherwise. If the animation is 6438 * started, this method calls {@link #invalidate()} if the invalidate parameter 6439 * is set to true; in that case the caller 6440 * should not call {@link #invalidate()}. 6441 * </p> 6442 * 6443 * <p> 6444 * This method should be invoked everytime a subclass directly updates the 6445 * scroll parameters. 6446 * </p> 6447 * 6448 * @param startDelay the delay, in milliseconds, after which the animation 6449 * should start; when the delay is 0, the animation starts 6450 * immediately 6451 * 6452 * @param invalidate Wheter this method should call invalidate 6453 * 6454 * @return true if the animation is played, false otherwise 6455 * 6456 * @see #scrollBy(int, int) 6457 * @see #scrollTo(int, int) 6458 * @see #isHorizontalScrollBarEnabled() 6459 * @see #isVerticalScrollBarEnabled() 6460 * @see #setHorizontalScrollBarEnabled(boolean) 6461 * @see #setVerticalScrollBarEnabled(boolean) 6462 */ 6463 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 6464 final ScrollabilityCache scrollCache = mScrollCache; 6465 6466 if (scrollCache == null || !scrollCache.fadeScrollBars) { 6467 return false; 6468 } 6469 6470 if (scrollCache.scrollBar == null) { 6471 scrollCache.scrollBar = new ScrollBarDrawable(); 6472 } 6473 6474 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 6475 6476 if (invalidate) { 6477 // Invalidate to show the scrollbars 6478 invalidate(); 6479 } 6480 6481 if (scrollCache.state == ScrollabilityCache.OFF) { 6482 // FIXME: this is copied from WindowManagerService. 6483 // We should get this value from the system when it 6484 // is possible to do so. 6485 final int KEY_REPEAT_FIRST_DELAY = 750; 6486 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 6487 } 6488 6489 // Tell mScrollCache when we should start fading. This may 6490 // extend the fade start time if one was already scheduled 6491 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 6492 scrollCache.fadeStartTime = fadeStartTime; 6493 scrollCache.state = ScrollabilityCache.ON; 6494 6495 // Schedule our fader to run, unscheduling any old ones first 6496 if (mAttachInfo != null) { 6497 mAttachInfo.mHandler.removeCallbacks(scrollCache); 6498 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 6499 } 6500 6501 return true; 6502 } 6503 6504 return false; 6505 } 6506 6507 /** 6508 * Mark the the area defined by dirty as needing to be drawn. If the view is 6509 * visible, {@link #onDraw} will be called at some point in the future. 6510 * This must be called from a UI thread. To call from a non-UI thread, call 6511 * {@link #postInvalidate()}. 6512 * 6513 * WARNING: This method is destructive to dirty. 6514 * @param dirty the rectangle representing the bounds of the dirty region 6515 */ 6516 public void invalidate(Rect dirty) { 6517 if (ViewDebug.TRACE_HIERARCHY) { 6518 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 6519 } 6520 6521 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 6522 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 6523 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6524 final ViewParent p = mParent; 6525 final AttachInfo ai = mAttachInfo; 6526 if (p != null && ai != null && ai.mHardwareAccelerated) { 6527 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 6528 // with a null dirty rect, which tells the ViewRoot to redraw everything 6529 p.invalidateChild(this, null); 6530 return; 6531 } 6532 if (p != null && ai != null) { 6533 final int scrollX = mScrollX; 6534 final int scrollY = mScrollY; 6535 final Rect r = ai.mTmpInvalRect; 6536 r.set(dirty.left - scrollX, dirty.top - scrollY, 6537 dirty.right - scrollX, dirty.bottom - scrollY); 6538 mParent.invalidateChild(this, r); 6539 } 6540 } 6541 } 6542 6543 /** 6544 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn. 6545 * The coordinates of the dirty rect are relative to the view. 6546 * If the view is visible, {@link #onDraw} will be called at some point 6547 * in the future. This must be called from a UI thread. To call 6548 * from a non-UI thread, call {@link #postInvalidate()}. 6549 * @param l the left position of the dirty region 6550 * @param t the top position of the dirty region 6551 * @param r the right position of the dirty region 6552 * @param b the bottom position of the dirty region 6553 */ 6554 public void invalidate(int l, int t, int r, int b) { 6555 if (ViewDebug.TRACE_HIERARCHY) { 6556 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 6557 } 6558 6559 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 6560 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 6561 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6562 final ViewParent p = mParent; 6563 final AttachInfo ai = mAttachInfo; 6564 if (p != null && ai != null && ai.mHardwareAccelerated) { 6565 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 6566 // with a null dirty rect, which tells the ViewRoot to redraw everything 6567 p.invalidateChild(this, null); 6568 return; 6569 } 6570 if (p != null && ai != null && l < r && t < b) { 6571 final int scrollX = mScrollX; 6572 final int scrollY = mScrollY; 6573 final Rect tmpr = ai.mTmpInvalRect; 6574 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 6575 p.invalidateChild(this, tmpr); 6576 } 6577 } 6578 } 6579 6580 /** 6581 * Invalidate the whole view. If the view is visible, {@link #onDraw} will 6582 * be called at some point in the future. This must be called from a 6583 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 6584 */ 6585 public void invalidate() { 6586 invalidate(true); 6587 } 6588 6589 /** 6590 * This is where the invalidate() work actually happens. A full invalidate() 6591 * causes the drawing cache to be invalidated, but this function can be called with 6592 * invalidateCache set to false to skip that invalidation step for cases that do not 6593 * need it (for example, a component that remains at the same dimensions with the same 6594 * content). 6595 * 6596 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 6597 * well. This is usually true for a full invalidate, but may be set to false if the 6598 * View's contents or dimensions have not changed. 6599 */ 6600 private void invalidate(boolean invalidateCache) { 6601 if (ViewDebug.TRACE_HIERARCHY) { 6602 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 6603 } 6604 6605 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 6606 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID)) { 6607 mPrivateFlags &= ~DRAWN; 6608 if (invalidateCache) { 6609 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6610 } 6611 final AttachInfo ai = mAttachInfo; 6612 final ViewParent p = mParent; 6613 if (p != null && ai != null && ai.mHardwareAccelerated) { 6614 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 6615 // with a null dirty rect, which tells the ViewRoot to redraw everything 6616 p.invalidateChild(this, null); 6617 return; 6618 } 6619 6620 if (p != null && ai != null) { 6621 final Rect r = ai.mTmpInvalRect; 6622 r.set(0, 0, mRight - mLeft, mBottom - mTop); 6623 // Don't call invalidate -- we don't want to internally scroll 6624 // our own bounds 6625 p.invalidateChild(this, r); 6626 } 6627 } 6628 } 6629 6630 /** 6631 * Indicates whether this View is opaque. An opaque View guarantees that it will 6632 * draw all the pixels overlapping its bounds using a fully opaque color. 6633 * 6634 * Subclasses of View should override this method whenever possible to indicate 6635 * whether an instance is opaque. Opaque Views are treated in a special way by 6636 * the View hierarchy, possibly allowing it to perform optimizations during 6637 * invalidate/draw passes. 6638 * 6639 * @return True if this View is guaranteed to be fully opaque, false otherwise. 6640 */ 6641 @ViewDebug.ExportedProperty(category = "drawing") 6642 public boolean isOpaque() { 6643 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK && 6644 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD); 6645 } 6646 6647 /** 6648 * @hide 6649 */ 6650 protected void computeOpaqueFlags() { 6651 // Opaque if: 6652 // - Has a background 6653 // - Background is opaque 6654 // - Doesn't have scrollbars or scrollbars are inside overlay 6655 6656 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) { 6657 mPrivateFlags |= OPAQUE_BACKGROUND; 6658 } else { 6659 mPrivateFlags &= ~OPAQUE_BACKGROUND; 6660 } 6661 6662 final int flags = mViewFlags; 6663 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 6664 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 6665 mPrivateFlags |= OPAQUE_SCROLLBARS; 6666 } else { 6667 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 6668 } 6669 } 6670 6671 /** 6672 * @hide 6673 */ 6674 protected boolean hasOpaqueScrollbars() { 6675 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 6676 } 6677 6678 /** 6679 * @return A handler associated with the thread running the View. This 6680 * handler can be used to pump events in the UI events queue. 6681 */ 6682 public Handler getHandler() { 6683 if (mAttachInfo != null) { 6684 return mAttachInfo.mHandler; 6685 } 6686 return null; 6687 } 6688 6689 /** 6690 * Causes the Runnable to be added to the message queue. 6691 * The runnable will be run on the user interface thread. 6692 * 6693 * @param action The Runnable that will be executed. 6694 * 6695 * @return Returns true if the Runnable was successfully placed in to the 6696 * message queue. Returns false on failure, usually because the 6697 * looper processing the message queue is exiting. 6698 */ 6699 public boolean post(Runnable action) { 6700 Handler handler; 6701 if (mAttachInfo != null) { 6702 handler = mAttachInfo.mHandler; 6703 } else { 6704 // Assume that post will succeed later 6705 ViewRoot.getRunQueue().post(action); 6706 return true; 6707 } 6708 6709 return handler.post(action); 6710 } 6711 6712 /** 6713 * Causes the Runnable to be added to the message queue, to be run 6714 * after the specified amount of time elapses. 6715 * The runnable will be run on the user interface thread. 6716 * 6717 * @param action The Runnable that will be executed. 6718 * @param delayMillis The delay (in milliseconds) until the Runnable 6719 * will be executed. 6720 * 6721 * @return true if the Runnable was successfully placed in to the 6722 * message queue. Returns false on failure, usually because the 6723 * looper processing the message queue is exiting. Note that a 6724 * result of true does not mean the Runnable will be processed -- 6725 * if the looper is quit before the delivery time of the message 6726 * occurs then the message will be dropped. 6727 */ 6728 public boolean postDelayed(Runnable action, long delayMillis) { 6729 Handler handler; 6730 if (mAttachInfo != null) { 6731 handler = mAttachInfo.mHandler; 6732 } else { 6733 // Assume that post will succeed later 6734 ViewRoot.getRunQueue().postDelayed(action, delayMillis); 6735 return true; 6736 } 6737 6738 return handler.postDelayed(action, delayMillis); 6739 } 6740 6741 /** 6742 * Removes the specified Runnable from the message queue. 6743 * 6744 * @param action The Runnable to remove from the message handling queue 6745 * 6746 * @return true if this view could ask the Handler to remove the Runnable, 6747 * false otherwise. When the returned value is true, the Runnable 6748 * may or may not have been actually removed from the message queue 6749 * (for instance, if the Runnable was not in the queue already.) 6750 */ 6751 public boolean removeCallbacks(Runnable action) { 6752 Handler handler; 6753 if (mAttachInfo != null) { 6754 handler = mAttachInfo.mHandler; 6755 } else { 6756 // Assume that post will succeed later 6757 ViewRoot.getRunQueue().removeCallbacks(action); 6758 return true; 6759 } 6760 6761 handler.removeCallbacks(action); 6762 return true; 6763 } 6764 6765 /** 6766 * Cause an invalidate to happen on a subsequent cycle through the event loop. 6767 * Use this to invalidate the View from a non-UI thread. 6768 * 6769 * @see #invalidate() 6770 */ 6771 public void postInvalidate() { 6772 postInvalidateDelayed(0); 6773 } 6774 6775 /** 6776 * Cause an invalidate of the specified area to happen on a subsequent cycle 6777 * through the event loop. Use this to invalidate the View from a non-UI thread. 6778 * 6779 * @param left The left coordinate of the rectangle to invalidate. 6780 * @param top The top coordinate of the rectangle to invalidate. 6781 * @param right The right coordinate of the rectangle to invalidate. 6782 * @param bottom The bottom coordinate of the rectangle to invalidate. 6783 * 6784 * @see #invalidate(int, int, int, int) 6785 * @see #invalidate(Rect) 6786 */ 6787 public void postInvalidate(int left, int top, int right, int bottom) { 6788 postInvalidateDelayed(0, left, top, right, bottom); 6789 } 6790 6791 /** 6792 * Cause an invalidate to happen on a subsequent cycle through the event 6793 * loop. Waits for the specified amount of time. 6794 * 6795 * @param delayMilliseconds the duration in milliseconds to delay the 6796 * invalidation by 6797 */ 6798 public void postInvalidateDelayed(long delayMilliseconds) { 6799 // We try only with the AttachInfo because there's no point in invalidating 6800 // if we are not attached to our window 6801 if (mAttachInfo != null) { 6802 Message msg = Message.obtain(); 6803 msg.what = AttachInfo.INVALIDATE_MSG; 6804 msg.obj = this; 6805 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 6806 } 6807 } 6808 6809 /** 6810 * Cause an invalidate of the specified area to happen on a subsequent cycle 6811 * through the event loop. Waits for the specified amount of time. 6812 * 6813 * @param delayMilliseconds the duration in milliseconds to delay the 6814 * invalidation by 6815 * @param left The left coordinate of the rectangle to invalidate. 6816 * @param top The top coordinate of the rectangle to invalidate. 6817 * @param right The right coordinate of the rectangle to invalidate. 6818 * @param bottom The bottom coordinate of the rectangle to invalidate. 6819 */ 6820 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 6821 int right, int bottom) { 6822 6823 // We try only with the AttachInfo because there's no point in invalidating 6824 // if we are not attached to our window 6825 if (mAttachInfo != null) { 6826 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 6827 info.target = this; 6828 info.left = left; 6829 info.top = top; 6830 info.right = right; 6831 info.bottom = bottom; 6832 6833 final Message msg = Message.obtain(); 6834 msg.what = AttachInfo.INVALIDATE_RECT_MSG; 6835 msg.obj = info; 6836 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 6837 } 6838 } 6839 6840 /** 6841 * Called by a parent to request that a child update its values for mScrollX 6842 * and mScrollY if necessary. This will typically be done if the child is 6843 * animating a scroll using a {@link android.widget.Scroller Scroller} 6844 * object. 6845 */ 6846 public void computeScroll() { 6847 } 6848 6849 /** 6850 * <p>Indicate whether the horizontal edges are faded when the view is 6851 * scrolled horizontally.</p> 6852 * 6853 * @return true if the horizontal edges should are faded on scroll, false 6854 * otherwise 6855 * 6856 * @see #setHorizontalFadingEdgeEnabled(boolean) 6857 * @attr ref android.R.styleable#View_fadingEdge 6858 */ 6859 public boolean isHorizontalFadingEdgeEnabled() { 6860 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 6861 } 6862 6863 /** 6864 * <p>Define whether the horizontal edges should be faded when this view 6865 * is scrolled horizontally.</p> 6866 * 6867 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 6868 * be faded when the view is scrolled 6869 * horizontally 6870 * 6871 * @see #isHorizontalFadingEdgeEnabled() 6872 * @attr ref android.R.styleable#View_fadingEdge 6873 */ 6874 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 6875 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 6876 if (horizontalFadingEdgeEnabled) { 6877 initScrollCache(); 6878 } 6879 6880 mViewFlags ^= FADING_EDGE_HORIZONTAL; 6881 } 6882 } 6883 6884 /** 6885 * <p>Indicate whether the vertical edges are faded when the view is 6886 * scrolled horizontally.</p> 6887 * 6888 * @return true if the vertical edges should are faded on scroll, false 6889 * otherwise 6890 * 6891 * @see #setVerticalFadingEdgeEnabled(boolean) 6892 * @attr ref android.R.styleable#View_fadingEdge 6893 */ 6894 public boolean isVerticalFadingEdgeEnabled() { 6895 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 6896 } 6897 6898 /** 6899 * <p>Define whether the vertical edges should be faded when this view 6900 * is scrolled vertically.</p> 6901 * 6902 * @param verticalFadingEdgeEnabled true if the vertical edges should 6903 * be faded when the view is scrolled 6904 * vertically 6905 * 6906 * @see #isVerticalFadingEdgeEnabled() 6907 * @attr ref android.R.styleable#View_fadingEdge 6908 */ 6909 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 6910 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 6911 if (verticalFadingEdgeEnabled) { 6912 initScrollCache(); 6913 } 6914 6915 mViewFlags ^= FADING_EDGE_VERTICAL; 6916 } 6917 } 6918 6919 /** 6920 * Returns the strength, or intensity, of the top faded edge. The strength is 6921 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 6922 * returns 0.0 or 1.0 but no value in between. 6923 * 6924 * Subclasses should override this method to provide a smoother fade transition 6925 * when scrolling occurs. 6926 * 6927 * @return the intensity of the top fade as a float between 0.0f and 1.0f 6928 */ 6929 protected float getTopFadingEdgeStrength() { 6930 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 6931 } 6932 6933 /** 6934 * Returns the strength, or intensity, of the bottom faded edge. The strength is 6935 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 6936 * returns 0.0 or 1.0 but no value in between. 6937 * 6938 * Subclasses should override this method to provide a smoother fade transition 6939 * when scrolling occurs. 6940 * 6941 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 6942 */ 6943 protected float getBottomFadingEdgeStrength() { 6944 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 6945 computeVerticalScrollRange() ? 1.0f : 0.0f; 6946 } 6947 6948 /** 6949 * Returns the strength, or intensity, of the left faded edge. The strength is 6950 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 6951 * returns 0.0 or 1.0 but no value in between. 6952 * 6953 * Subclasses should override this method to provide a smoother fade transition 6954 * when scrolling occurs. 6955 * 6956 * @return the intensity of the left fade as a float between 0.0f and 1.0f 6957 */ 6958 protected float getLeftFadingEdgeStrength() { 6959 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 6960 } 6961 6962 /** 6963 * Returns the strength, or intensity, of the right faded edge. The strength is 6964 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 6965 * returns 0.0 or 1.0 but no value in between. 6966 * 6967 * Subclasses should override this method to provide a smoother fade transition 6968 * when scrolling occurs. 6969 * 6970 * @return the intensity of the right fade as a float between 0.0f and 1.0f 6971 */ 6972 protected float getRightFadingEdgeStrength() { 6973 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 6974 computeHorizontalScrollRange() ? 1.0f : 0.0f; 6975 } 6976 6977 /** 6978 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 6979 * scrollbar is not drawn by default.</p> 6980 * 6981 * @return true if the horizontal scrollbar should be painted, false 6982 * otherwise 6983 * 6984 * @see #setHorizontalScrollBarEnabled(boolean) 6985 */ 6986 public boolean isHorizontalScrollBarEnabled() { 6987 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 6988 } 6989 6990 /** 6991 * <p>Define whether the horizontal scrollbar should be drawn or not. The 6992 * scrollbar is not drawn by default.</p> 6993 * 6994 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 6995 * be painted 6996 * 6997 * @see #isHorizontalScrollBarEnabled() 6998 */ 6999 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 7000 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 7001 mViewFlags ^= SCROLLBARS_HORIZONTAL; 7002 computeOpaqueFlags(); 7003 recomputePadding(); 7004 } 7005 } 7006 7007 /** 7008 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 7009 * scrollbar is not drawn by default.</p> 7010 * 7011 * @return true if the vertical scrollbar should be painted, false 7012 * otherwise 7013 * 7014 * @see #setVerticalScrollBarEnabled(boolean) 7015 */ 7016 public boolean isVerticalScrollBarEnabled() { 7017 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 7018 } 7019 7020 /** 7021 * <p>Define whether the vertical scrollbar should be drawn or not. The 7022 * scrollbar is not drawn by default.</p> 7023 * 7024 * @param verticalScrollBarEnabled true if the vertical scrollbar should 7025 * be painted 7026 * 7027 * @see #isVerticalScrollBarEnabled() 7028 */ 7029 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 7030 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 7031 mViewFlags ^= SCROLLBARS_VERTICAL; 7032 computeOpaqueFlags(); 7033 recomputePadding(); 7034 } 7035 } 7036 7037 /** 7038 * @hide 7039 */ 7040 protected void recomputePadding() { 7041 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 7042 } 7043 7044 /** 7045 * Define whether scrollbars will fade when the view is not scrolling. 7046 * 7047 * @param fadeScrollbars wheter to enable fading 7048 * 7049 */ 7050 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 7051 initScrollCache(); 7052 final ScrollabilityCache scrollabilityCache = mScrollCache; 7053 scrollabilityCache.fadeScrollBars = fadeScrollbars; 7054 if (fadeScrollbars) { 7055 scrollabilityCache.state = ScrollabilityCache.OFF; 7056 } else { 7057 scrollabilityCache.state = ScrollabilityCache.ON; 7058 } 7059 } 7060 7061 /** 7062 * 7063 * Returns true if scrollbars will fade when this view is not scrolling 7064 * 7065 * @return true if scrollbar fading is enabled 7066 */ 7067 public boolean isScrollbarFadingEnabled() { 7068 return mScrollCache != null && mScrollCache.fadeScrollBars; 7069 } 7070 7071 /** 7072 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 7073 * inset. When inset, they add to the padding of the view. And the scrollbars 7074 * can be drawn inside the padding area or on the edge of the view. For example, 7075 * if a view has a background drawable and you want to draw the scrollbars 7076 * inside the padding specified by the drawable, you can use 7077 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 7078 * appear at the edge of the view, ignoring the padding, then you can use 7079 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 7080 * @param style the style of the scrollbars. Should be one of 7081 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 7082 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 7083 * @see #SCROLLBARS_INSIDE_OVERLAY 7084 * @see #SCROLLBARS_INSIDE_INSET 7085 * @see #SCROLLBARS_OUTSIDE_OVERLAY 7086 * @see #SCROLLBARS_OUTSIDE_INSET 7087 */ 7088 public void setScrollBarStyle(int style) { 7089 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 7090 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 7091 computeOpaqueFlags(); 7092 recomputePadding(); 7093 } 7094 } 7095 7096 /** 7097 * <p>Returns the current scrollbar style.</p> 7098 * @return the current scrollbar style 7099 * @see #SCROLLBARS_INSIDE_OVERLAY 7100 * @see #SCROLLBARS_INSIDE_INSET 7101 * @see #SCROLLBARS_OUTSIDE_OVERLAY 7102 * @see #SCROLLBARS_OUTSIDE_INSET 7103 */ 7104 public int getScrollBarStyle() { 7105 return mViewFlags & SCROLLBARS_STYLE_MASK; 7106 } 7107 7108 /** 7109 * <p>Compute the horizontal range that the horizontal scrollbar 7110 * represents.</p> 7111 * 7112 * <p>The range is expressed in arbitrary units that must be the same as the 7113 * units used by {@link #computeHorizontalScrollExtent()} and 7114 * {@link #computeHorizontalScrollOffset()}.</p> 7115 * 7116 * <p>The default range is the drawing width of this view.</p> 7117 * 7118 * @return the total horizontal range represented by the horizontal 7119 * scrollbar 7120 * 7121 * @see #computeHorizontalScrollExtent() 7122 * @see #computeHorizontalScrollOffset() 7123 * @see android.widget.ScrollBarDrawable 7124 */ 7125 protected int computeHorizontalScrollRange() { 7126 return getWidth(); 7127 } 7128 7129 /** 7130 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 7131 * within the horizontal range. This value is used to compute the position 7132 * of the thumb within the scrollbar's track.</p> 7133 * 7134 * <p>The range is expressed in arbitrary units that must be the same as the 7135 * units used by {@link #computeHorizontalScrollRange()} and 7136 * {@link #computeHorizontalScrollExtent()}.</p> 7137 * 7138 * <p>The default offset is the scroll offset of this view.</p> 7139 * 7140 * @return the horizontal offset of the scrollbar's thumb 7141 * 7142 * @see #computeHorizontalScrollRange() 7143 * @see #computeHorizontalScrollExtent() 7144 * @see android.widget.ScrollBarDrawable 7145 */ 7146 protected int computeHorizontalScrollOffset() { 7147 return mScrollX; 7148 } 7149 7150 /** 7151 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 7152 * within the horizontal range. This value is used to compute the length 7153 * of the thumb within the scrollbar's track.</p> 7154 * 7155 * <p>The range is expressed in arbitrary units that must be the same as the 7156 * units used by {@link #computeHorizontalScrollRange()} and 7157 * {@link #computeHorizontalScrollOffset()}.</p> 7158 * 7159 * <p>The default extent is the drawing width of this view.</p> 7160 * 7161 * @return the horizontal extent of the scrollbar's thumb 7162 * 7163 * @see #computeHorizontalScrollRange() 7164 * @see #computeHorizontalScrollOffset() 7165 * @see android.widget.ScrollBarDrawable 7166 */ 7167 protected int computeHorizontalScrollExtent() { 7168 return getWidth(); 7169 } 7170 7171 /** 7172 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 7173 * 7174 * <p>The range is expressed in arbitrary units that must be the same as the 7175 * units used by {@link #computeVerticalScrollExtent()} and 7176 * {@link #computeVerticalScrollOffset()}.</p> 7177 * 7178 * @return the total vertical range represented by the vertical scrollbar 7179 * 7180 * <p>The default range is the drawing height of this view.</p> 7181 * 7182 * @see #computeVerticalScrollExtent() 7183 * @see #computeVerticalScrollOffset() 7184 * @see android.widget.ScrollBarDrawable 7185 */ 7186 protected int computeVerticalScrollRange() { 7187 return getHeight(); 7188 } 7189 7190 /** 7191 * <p>Compute the vertical offset of the vertical scrollbar's thumb 7192 * within the horizontal range. This value is used to compute the position 7193 * of the thumb within the scrollbar's track.</p> 7194 * 7195 * <p>The range is expressed in arbitrary units that must be the same as the 7196 * units used by {@link #computeVerticalScrollRange()} and 7197 * {@link #computeVerticalScrollExtent()}.</p> 7198 * 7199 * <p>The default offset is the scroll offset of this view.</p> 7200 * 7201 * @return the vertical offset of the scrollbar's thumb 7202 * 7203 * @see #computeVerticalScrollRange() 7204 * @see #computeVerticalScrollExtent() 7205 * @see android.widget.ScrollBarDrawable 7206 */ 7207 protected int computeVerticalScrollOffset() { 7208 return mScrollY; 7209 } 7210 7211 /** 7212 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 7213 * within the vertical range. This value is used to compute the length 7214 * of the thumb within the scrollbar's track.</p> 7215 * 7216 * <p>The range is expressed in arbitrary units that must be the same as the 7217 * units used by {@link #computeVerticalScrollRange()} and 7218 * {@link #computeVerticalScrollOffset()}.</p> 7219 * 7220 * <p>The default extent is the drawing height of this view.</p> 7221 * 7222 * @return the vertical extent of the scrollbar's thumb 7223 * 7224 * @see #computeVerticalScrollRange() 7225 * @see #computeVerticalScrollOffset() 7226 * @see android.widget.ScrollBarDrawable 7227 */ 7228 protected int computeVerticalScrollExtent() { 7229 return getHeight(); 7230 } 7231 7232 /** 7233 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 7234 * scrollbars are painted only if they have been awakened first.</p> 7235 * 7236 * @param canvas the canvas on which to draw the scrollbars 7237 * 7238 * @see #awakenScrollBars(int) 7239 */ 7240 protected final void onDrawScrollBars(Canvas canvas) { 7241 // scrollbars are drawn only when the animation is running 7242 final ScrollabilityCache cache = mScrollCache; 7243 if (cache != null) { 7244 7245 int state = cache.state; 7246 7247 if (state == ScrollabilityCache.OFF) { 7248 return; 7249 } 7250 7251 boolean invalidate = false; 7252 7253 if (state == ScrollabilityCache.FADING) { 7254 // We're fading -- get our fade interpolation 7255 if (cache.interpolatorValues == null) { 7256 cache.interpolatorValues = new float[1]; 7257 } 7258 7259 float[] values = cache.interpolatorValues; 7260 7261 // Stops the animation if we're done 7262 if (cache.scrollBarInterpolator.timeToValues(values) == 7263 Interpolator.Result.FREEZE_END) { 7264 cache.state = ScrollabilityCache.OFF; 7265 } else { 7266 cache.scrollBar.setAlpha(Math.round(values[0])); 7267 } 7268 7269 // This will make the scroll bars inval themselves after 7270 // drawing. We only want this when we're fading so that 7271 // we prevent excessive redraws 7272 invalidate = true; 7273 } else { 7274 // We're just on -- but we may have been fading before so 7275 // reset alpha 7276 cache.scrollBar.setAlpha(255); 7277 } 7278 7279 7280 final int viewFlags = mViewFlags; 7281 7282 final boolean drawHorizontalScrollBar = 7283 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 7284 final boolean drawVerticalScrollBar = 7285 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 7286 && !isVerticalScrollBarHidden(); 7287 7288 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 7289 final int width = mRight - mLeft; 7290 final int height = mBottom - mTop; 7291 7292 final ScrollBarDrawable scrollBar = cache.scrollBar; 7293 int size = scrollBar.getSize(false); 7294 if (size <= 0) { 7295 size = cache.scrollBarSize; 7296 } 7297 7298 final int scrollX = mScrollX; 7299 final int scrollY = mScrollY; 7300 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 7301 7302 int left, top, right, bottom; 7303 7304 if (drawHorizontalScrollBar) { 7305 scrollBar.setParameters(computeHorizontalScrollRange(), 7306 computeHorizontalScrollOffset(), 7307 computeHorizontalScrollExtent(), false); 7308 final int verticalScrollBarGap = drawVerticalScrollBar ? 7309 getVerticalScrollbarWidth() : 0; 7310 top = scrollY + height - size - (mUserPaddingBottom & inside); 7311 left = scrollX + (mPaddingLeft & inside); 7312 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 7313 bottom = top + size; 7314 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 7315 if (invalidate) { 7316 invalidate(left, top, right, bottom); 7317 } 7318 } 7319 7320 if (drawVerticalScrollBar) { 7321 scrollBar.setParameters(computeVerticalScrollRange(), 7322 computeVerticalScrollOffset(), 7323 computeVerticalScrollExtent(), true); 7324 switch (mVerticalScrollbarPosition) { 7325 default: 7326 case SCROLLBAR_POSITION_DEFAULT: 7327 case SCROLLBAR_POSITION_RIGHT: 7328 left = scrollX + width - size - (mUserPaddingRight & inside); 7329 break; 7330 case SCROLLBAR_POSITION_LEFT: 7331 left = scrollX + (mUserPaddingLeft & inside); 7332 break; 7333 } 7334 top = scrollY + (mPaddingTop & inside); 7335 right = left + size; 7336 bottom = scrollY + height - (mUserPaddingBottom & inside); 7337 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 7338 if (invalidate) { 7339 invalidate(left, top, right, bottom); 7340 } 7341 } 7342 } 7343 } 7344 } 7345 7346 /** 7347 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 7348 * FastScroller is visible. 7349 * @return whether to temporarily hide the vertical scrollbar 7350 * @hide 7351 */ 7352 protected boolean isVerticalScrollBarHidden() { 7353 return false; 7354 } 7355 7356 /** 7357 * <p>Draw the horizontal scrollbar if 7358 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 7359 * 7360 * @param canvas the canvas on which to draw the scrollbar 7361 * @param scrollBar the scrollbar's drawable 7362 * 7363 * @see #isHorizontalScrollBarEnabled() 7364 * @see #computeHorizontalScrollRange() 7365 * @see #computeHorizontalScrollExtent() 7366 * @see #computeHorizontalScrollOffset() 7367 * @see android.widget.ScrollBarDrawable 7368 * @hide 7369 */ 7370 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 7371 int l, int t, int r, int b) { 7372 scrollBar.setBounds(l, t, r, b); 7373 scrollBar.draw(canvas); 7374 } 7375 7376 /** 7377 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 7378 * returns true.</p> 7379 * 7380 * @param canvas the canvas on which to draw the scrollbar 7381 * @param scrollBar the scrollbar's drawable 7382 * 7383 * @see #isVerticalScrollBarEnabled() 7384 * @see #computeVerticalScrollRange() 7385 * @see #computeVerticalScrollExtent() 7386 * @see #computeVerticalScrollOffset() 7387 * @see android.widget.ScrollBarDrawable 7388 * @hide 7389 */ 7390 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 7391 int l, int t, int r, int b) { 7392 scrollBar.setBounds(l, t, r, b); 7393 scrollBar.draw(canvas); 7394 } 7395 7396 /** 7397 * Implement this to do your drawing. 7398 * 7399 * @param canvas the canvas on which the background will be drawn 7400 */ 7401 protected void onDraw(Canvas canvas) { 7402 } 7403 7404 /* 7405 * Caller is responsible for calling requestLayout if necessary. 7406 * (This allows addViewInLayout to not request a new layout.) 7407 */ 7408 void assignParent(ViewParent parent) { 7409 if (mParent == null) { 7410 mParent = parent; 7411 } else if (parent == null) { 7412 mParent = null; 7413 } else { 7414 throw new RuntimeException("view " + this + " being added, but" 7415 + " it already has a parent"); 7416 } 7417 } 7418 7419 /** 7420 * This is called when the view is attached to a window. At this point it 7421 * has a Surface and will start drawing. Note that this function is 7422 * guaranteed to be called before {@link #onDraw}, however it may be called 7423 * any time before the first onDraw -- including before or after 7424 * {@link #onMeasure}. 7425 * 7426 * @see #onDetachedFromWindow() 7427 */ 7428 protected void onAttachedToWindow() { 7429 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 7430 mParent.requestTransparentRegion(this); 7431 } 7432 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 7433 initialAwakenScrollBars(); 7434 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH; 7435 } 7436 jumpDrawablesToCurrentState(); 7437 } 7438 7439 /** 7440 * This is called when the view is detached from a window. At this point it 7441 * no longer has a surface for drawing. 7442 * 7443 * @see #onAttachedToWindow() 7444 */ 7445 protected void onDetachedFromWindow() { 7446 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 7447 removeUnsetPressCallback(); 7448 removeLongPressCallback(); 7449 destroyDrawingCache(); 7450 } 7451 7452 /** 7453 * @return The number of times this view has been attached to a window 7454 */ 7455 protected int getWindowAttachCount() { 7456 return mWindowAttachCount; 7457 } 7458 7459 /** 7460 * Retrieve a unique token identifying the window this view is attached to. 7461 * @return Return the window's token for use in 7462 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 7463 */ 7464 public IBinder getWindowToken() { 7465 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 7466 } 7467 7468 /** 7469 * Retrieve a unique token identifying the top-level "real" window of 7470 * the window that this view is attached to. That is, this is like 7471 * {@link #getWindowToken}, except if the window this view in is a panel 7472 * window (attached to another containing window), then the token of 7473 * the containing window is returned instead. 7474 * 7475 * @return Returns the associated window token, either 7476 * {@link #getWindowToken()} or the containing window's token. 7477 */ 7478 public IBinder getApplicationWindowToken() { 7479 AttachInfo ai = mAttachInfo; 7480 if (ai != null) { 7481 IBinder appWindowToken = ai.mPanelParentWindowToken; 7482 if (appWindowToken == null) { 7483 appWindowToken = ai.mWindowToken; 7484 } 7485 return appWindowToken; 7486 } 7487 return null; 7488 } 7489 7490 /** 7491 * Retrieve private session object this view hierarchy is using to 7492 * communicate with the window manager. 7493 * @return the session object to communicate with the window manager 7494 */ 7495 /*package*/ IWindowSession getWindowSession() { 7496 return mAttachInfo != null ? mAttachInfo.mSession : null; 7497 } 7498 7499 /** 7500 * @param info the {@link android.view.View.AttachInfo} to associated with 7501 * this view 7502 */ 7503 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 7504 //System.out.println("Attached! " + this); 7505 mAttachInfo = info; 7506 mWindowAttachCount++; 7507 // We will need to evaluate the drawable state at least once. 7508 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 7509 if (mFloatingTreeObserver != null) { 7510 info.mTreeObserver.merge(mFloatingTreeObserver); 7511 mFloatingTreeObserver = null; 7512 } 7513 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 7514 mAttachInfo.mScrollContainers.add(this); 7515 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 7516 } 7517 performCollectViewAttributes(visibility); 7518 onAttachedToWindow(); 7519 int vis = info.mWindowVisibility; 7520 if (vis != GONE) { 7521 onWindowVisibilityChanged(vis); 7522 } 7523 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 7524 // If nobody has evaluated the drawable state yet, then do it now. 7525 refreshDrawableState(); 7526 } 7527 } 7528 7529 void dispatchDetachedFromWindow() { 7530 //System.out.println("Detached! " + this); 7531 AttachInfo info = mAttachInfo; 7532 if (info != null) { 7533 int vis = info.mWindowVisibility; 7534 if (vis != GONE) { 7535 onWindowVisibilityChanged(GONE); 7536 } 7537 } 7538 7539 onDetachedFromWindow(); 7540 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 7541 mAttachInfo.mScrollContainers.remove(this); 7542 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 7543 } 7544 mAttachInfo = null; 7545 } 7546 7547 /** 7548 * Store this view hierarchy's frozen state into the given container. 7549 * 7550 * @param container The SparseArray in which to save the view's state. 7551 * 7552 * @see #restoreHierarchyState 7553 * @see #dispatchSaveInstanceState 7554 * @see #onSaveInstanceState 7555 */ 7556 public void saveHierarchyState(SparseArray<Parcelable> container) { 7557 dispatchSaveInstanceState(container); 7558 } 7559 7560 /** 7561 * Called by {@link #saveHierarchyState} to store the state for this view and its children. 7562 * May be overridden to modify how freezing happens to a view's children; for example, some 7563 * views may want to not store state for their children. 7564 * 7565 * @param container The SparseArray in which to save the view's state. 7566 * 7567 * @see #dispatchRestoreInstanceState 7568 * @see #saveHierarchyState 7569 * @see #onSaveInstanceState 7570 */ 7571 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 7572 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 7573 mPrivateFlags &= ~SAVE_STATE_CALLED; 7574 Parcelable state = onSaveInstanceState(); 7575 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 7576 throw new IllegalStateException( 7577 "Derived class did not call super.onSaveInstanceState()"); 7578 } 7579 if (state != null) { 7580 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 7581 // + ": " + state); 7582 container.put(mID, state); 7583 } 7584 } 7585 } 7586 7587 /** 7588 * Hook allowing a view to generate a representation of its internal state 7589 * that can later be used to create a new instance with that same state. 7590 * This state should only contain information that is not persistent or can 7591 * not be reconstructed later. For example, you will never store your 7592 * current position on screen because that will be computed again when a 7593 * new instance of the view is placed in its view hierarchy. 7594 * <p> 7595 * Some examples of things you may store here: the current cursor position 7596 * in a text view (but usually not the text itself since that is stored in a 7597 * content provider or other persistent storage), the currently selected 7598 * item in a list view. 7599 * 7600 * @return Returns a Parcelable object containing the view's current dynamic 7601 * state, or null if there is nothing interesting to save. The 7602 * default implementation returns null. 7603 * @see #onRestoreInstanceState 7604 * @see #saveHierarchyState 7605 * @see #dispatchSaveInstanceState 7606 * @see #setSaveEnabled(boolean) 7607 */ 7608 protected Parcelable onSaveInstanceState() { 7609 mPrivateFlags |= SAVE_STATE_CALLED; 7610 return BaseSavedState.EMPTY_STATE; 7611 } 7612 7613 /** 7614 * Restore this view hierarchy's frozen state from the given container. 7615 * 7616 * @param container The SparseArray which holds previously frozen states. 7617 * 7618 * @see #saveHierarchyState 7619 * @see #dispatchRestoreInstanceState 7620 * @see #onRestoreInstanceState 7621 */ 7622 public void restoreHierarchyState(SparseArray<Parcelable> container) { 7623 dispatchRestoreInstanceState(container); 7624 } 7625 7626 /** 7627 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its 7628 * children. May be overridden to modify how restoreing happens to a view's children; for 7629 * example, some views may want to not store state for their children. 7630 * 7631 * @param container The SparseArray which holds previously saved state. 7632 * 7633 * @see #dispatchSaveInstanceState 7634 * @see #restoreHierarchyState 7635 * @see #onRestoreInstanceState 7636 */ 7637 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 7638 if (mID != NO_ID) { 7639 Parcelable state = container.get(mID); 7640 if (state != null) { 7641 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 7642 // + ": " + state); 7643 mPrivateFlags &= ~SAVE_STATE_CALLED; 7644 onRestoreInstanceState(state); 7645 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 7646 throw new IllegalStateException( 7647 "Derived class did not call super.onRestoreInstanceState()"); 7648 } 7649 } 7650 } 7651 } 7652 7653 /** 7654 * Hook allowing a view to re-apply a representation of its internal state that had previously 7655 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 7656 * null state. 7657 * 7658 * @param state The frozen state that had previously been returned by 7659 * {@link #onSaveInstanceState}. 7660 * 7661 * @see #onSaveInstanceState 7662 * @see #restoreHierarchyState 7663 * @see #dispatchRestoreInstanceState 7664 */ 7665 protected void onRestoreInstanceState(Parcelable state) { 7666 mPrivateFlags |= SAVE_STATE_CALLED; 7667 if (state != BaseSavedState.EMPTY_STATE && state != null) { 7668 throw new IllegalArgumentException("Wrong state class, expecting View State but " 7669 + "received " + state.getClass().toString() + " instead. This usually happens " 7670 + "when two views of different type have the same id in the same hierarchy. " 7671 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 7672 + "other views do not use the same id."); 7673 } 7674 } 7675 7676 /** 7677 * <p>Return the time at which the drawing of the view hierarchy started.</p> 7678 * 7679 * @return the drawing start time in milliseconds 7680 */ 7681 public long getDrawingTime() { 7682 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 7683 } 7684 7685 /** 7686 * <p>Enables or disables the duplication of the parent's state into this view. When 7687 * duplication is enabled, this view gets its drawable state from its parent rather 7688 * than from its own internal properties.</p> 7689 * 7690 * <p>Note: in the current implementation, setting this property to true after the 7691 * view was added to a ViewGroup might have no effect at all. This property should 7692 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 7693 * 7694 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 7695 * property is enabled, an exception will be thrown.</p> 7696 * 7697 * @param enabled True to enable duplication of the parent's drawable state, false 7698 * to disable it. 7699 * 7700 * @see #getDrawableState() 7701 * @see #isDuplicateParentStateEnabled() 7702 */ 7703 public void setDuplicateParentStateEnabled(boolean enabled) { 7704 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 7705 } 7706 7707 /** 7708 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 7709 * 7710 * @return True if this view's drawable state is duplicated from the parent, 7711 * false otherwise 7712 * 7713 * @see #getDrawableState() 7714 * @see #setDuplicateParentStateEnabled(boolean) 7715 */ 7716 public boolean isDuplicateParentStateEnabled() { 7717 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 7718 } 7719 7720 /** 7721 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 7722 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 7723 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 7724 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 7725 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 7726 * null.</p> 7727 * 7728 * @param enabled true to enable the drawing cache, false otherwise 7729 * 7730 * @see #isDrawingCacheEnabled() 7731 * @see #getDrawingCache() 7732 * @see #buildDrawingCache() 7733 */ 7734 public void setDrawingCacheEnabled(boolean enabled) { 7735 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 7736 } 7737 7738 /** 7739 * <p>Indicates whether the drawing cache is enabled for this view.</p> 7740 * 7741 * @return true if the drawing cache is enabled 7742 * 7743 * @see #setDrawingCacheEnabled(boolean) 7744 * @see #getDrawingCache() 7745 */ 7746 @ViewDebug.ExportedProperty(category = "drawing") 7747 public boolean isDrawingCacheEnabled() { 7748 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 7749 } 7750 7751 /** 7752 * <p>Returns a display list that can be used to draw this view again 7753 * without executing its draw method.</p> 7754 * 7755 * @return A DisplayList ready to replay, or null if caching is not enabled. 7756 */ 7757 DisplayList getDisplayList() { 7758 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 7759 return null; 7760 } 7761 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) { 7762 return null; 7763 } 7764 7765 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED && 7766 ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mDisplayList == null)) { 7767 7768 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(); 7769 7770 final HardwareCanvas canvas = mDisplayList.start(); 7771 try { 7772 int width = mRight - mLeft; 7773 int height = mBottom - mTop; 7774 7775 canvas.setViewport(width, height); 7776 canvas.onPreDraw(); 7777 7778 final int restoreCount = canvas.save(); 7779 7780 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 7781 7782 // Fast path for layouts with no backgrounds 7783 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 7784 mPrivateFlags &= ~DIRTY_MASK; 7785 dispatchDraw(canvas); 7786 } else { 7787 draw(canvas); 7788 } 7789 7790 canvas.restoreToCount(restoreCount); 7791 } finally { 7792 canvas.onPostDraw(); 7793 7794 mDisplayList.end(); 7795 } 7796 } 7797 7798 return mDisplayList; 7799 } 7800 7801 /** 7802 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 7803 * 7804 * @return A non-scaled bitmap representing this view or null if cache is disabled. 7805 * 7806 * @see #getDrawingCache(boolean) 7807 */ 7808 public Bitmap getDrawingCache() { 7809 return getDrawingCache(false); 7810 } 7811 7812 /** 7813 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 7814 * is null when caching is disabled. If caching is enabled and the cache is not ready, 7815 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 7816 * draw from the cache when the cache is enabled. To benefit from the cache, you must 7817 * request the drawing cache by calling this method and draw it on screen if the 7818 * returned bitmap is not null.</p> 7819 * 7820 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 7821 * this method will create a bitmap of the same size as this view. Because this bitmap 7822 * will be drawn scaled by the parent ViewGroup, the result on screen might show 7823 * scaling artifacts. To avoid such artifacts, you should call this method by setting 7824 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 7825 * size than the view. This implies that your application must be able to handle this 7826 * size.</p> 7827 * 7828 * @param autoScale Indicates whether the generated bitmap should be scaled based on 7829 * the current density of the screen when the application is in compatibility 7830 * mode. 7831 * 7832 * @return A bitmap representing this view or null if cache is disabled. 7833 * 7834 * @see #setDrawingCacheEnabled(boolean) 7835 * @see #isDrawingCacheEnabled() 7836 * @see #buildDrawingCache(boolean) 7837 * @see #destroyDrawingCache() 7838 */ 7839 public Bitmap getDrawingCache(boolean autoScale) { 7840 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 7841 return null; 7842 } 7843 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 7844 buildDrawingCache(autoScale); 7845 } 7846 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 7847 } 7848 7849 /** 7850 * <p>Frees the resources used by the drawing cache. If you call 7851 * {@link #buildDrawingCache()} manually without calling 7852 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 7853 * should cleanup the cache with this method afterwards.</p> 7854 * 7855 * @see #setDrawingCacheEnabled(boolean) 7856 * @see #buildDrawingCache() 7857 * @see #getDrawingCache() 7858 */ 7859 public void destroyDrawingCache() { 7860 if (mDrawingCache != null) { 7861 mDrawingCache.recycle(); 7862 mDrawingCache = null; 7863 } 7864 if (mUnscaledDrawingCache != null) { 7865 mUnscaledDrawingCache.recycle(); 7866 mUnscaledDrawingCache = null; 7867 } 7868 if (mDisplayList != null) { 7869 mDisplayList = null; 7870 } 7871 } 7872 7873 /** 7874 * Setting a solid background color for the drawing cache's bitmaps will improve 7875 * perfromance and memory usage. Note, though that this should only be used if this 7876 * view will always be drawn on top of a solid color. 7877 * 7878 * @param color The background color to use for the drawing cache's bitmap 7879 * 7880 * @see #setDrawingCacheEnabled(boolean) 7881 * @see #buildDrawingCache() 7882 * @see #getDrawingCache() 7883 */ 7884 public void setDrawingCacheBackgroundColor(int color) { 7885 if (color != mDrawingCacheBackgroundColor) { 7886 mDrawingCacheBackgroundColor = color; 7887 mPrivateFlags &= ~DRAWING_CACHE_VALID; 7888 } 7889 } 7890 7891 /** 7892 * @see #setDrawingCacheBackgroundColor(int) 7893 * 7894 * @return The background color to used for the drawing cache's bitmap 7895 */ 7896 public int getDrawingCacheBackgroundColor() { 7897 return mDrawingCacheBackgroundColor; 7898 } 7899 7900 /** 7901 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 7902 * 7903 * @see #buildDrawingCache(boolean) 7904 */ 7905 public void buildDrawingCache() { 7906 buildDrawingCache(false); 7907 } 7908 7909 /** 7910 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 7911 * 7912 * <p>If you call {@link #buildDrawingCache()} manually without calling 7913 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 7914 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 7915 * 7916 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 7917 * this method will create a bitmap of the same size as this view. Because this bitmap 7918 * will be drawn scaled by the parent ViewGroup, the result on screen might show 7919 * scaling artifacts. To avoid such artifacts, you should call this method by setting 7920 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 7921 * size than the view. This implies that your application must be able to handle this 7922 * size.</p> 7923 * 7924 * <p>You should avoid calling this method when hardware acceleration is enabled. If 7925 * you do not need the drawing cache bitmap, calling this method will increase memory 7926 * usage and cause the view to be rendered in software once, thus negatively impacting 7927 * performance.</p> 7928 * 7929 * @see #getDrawingCache() 7930 * @see #destroyDrawingCache() 7931 */ 7932 public void buildDrawingCache(boolean autoScale) { 7933 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 7934 mDrawingCache == null : mUnscaledDrawingCache == null)) { 7935 7936 if (ViewDebug.TRACE_HIERARCHY) { 7937 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 7938 } 7939 7940 int width = mRight - mLeft; 7941 int height = mBottom - mTop; 7942 7943 final AttachInfo attachInfo = mAttachInfo; 7944 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 7945 7946 if (autoScale && scalingRequired) { 7947 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 7948 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 7949 } 7950 7951 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 7952 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 7953 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 7954 7955 if (width <= 0 || height <= 0 || 7956 // Projected bitmap size in bytes 7957 (width * height * (opaque && !use32BitCache ? 2 : 4) > 7958 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 7959 destroyDrawingCache(); 7960 return; 7961 } 7962 7963 boolean clear = true; 7964 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 7965 7966 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 7967 Bitmap.Config quality; 7968 if (!opaque) { 7969 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 7970 case DRAWING_CACHE_QUALITY_AUTO: 7971 quality = Bitmap.Config.ARGB_8888; 7972 break; 7973 case DRAWING_CACHE_QUALITY_LOW: 7974 quality = Bitmap.Config.ARGB_4444; 7975 break; 7976 case DRAWING_CACHE_QUALITY_HIGH: 7977 quality = Bitmap.Config.ARGB_8888; 7978 break; 7979 default: 7980 quality = Bitmap.Config.ARGB_8888; 7981 break; 7982 } 7983 } else { 7984 // Optimization for translucent windows 7985 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 7986 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 7987 } 7988 7989 // Try to cleanup memory 7990 if (bitmap != null) bitmap.recycle(); 7991 7992 try { 7993 bitmap = Bitmap.createBitmap(width, height, quality); 7994 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 7995 if (autoScale) { 7996 mDrawingCache = bitmap; 7997 } else { 7998 mUnscaledDrawingCache = bitmap; 7999 } 8000 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 8001 } catch (OutOfMemoryError e) { 8002 // If there is not enough memory to create the bitmap cache, just 8003 // ignore the issue as bitmap caches are not required to draw the 8004 // view hierarchy 8005 if (autoScale) { 8006 mDrawingCache = null; 8007 } else { 8008 mUnscaledDrawingCache = null; 8009 } 8010 return; 8011 } 8012 8013 clear = drawingCacheBackgroundColor != 0; 8014 } 8015 8016 Canvas canvas; 8017 if (attachInfo != null) { 8018 canvas = attachInfo.mCanvas; 8019 if (canvas == null) { 8020 canvas = new Canvas(); 8021 } 8022 canvas.setBitmap(bitmap); 8023 // Temporarily clobber the cached Canvas in case one of our children 8024 // is also using a drawing cache. Without this, the children would 8025 // steal the canvas by attaching their own bitmap to it and bad, bad 8026 // thing would happen (invisible views, corrupted drawings, etc.) 8027 attachInfo.mCanvas = null; 8028 } else { 8029 // This case should hopefully never or seldom happen 8030 canvas = new Canvas(bitmap); 8031 } 8032 8033 if (clear) { 8034 bitmap.eraseColor(drawingCacheBackgroundColor); 8035 } 8036 8037 computeScroll(); 8038 final int restoreCount = canvas.save(); 8039 8040 if (autoScale && scalingRequired) { 8041 final float scale = attachInfo.mApplicationScale; 8042 canvas.scale(scale, scale); 8043 } 8044 8045 canvas.translate(-mScrollX, -mScrollY); 8046 8047 mPrivateFlags |= DRAWN; 8048 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated) { 8049 mPrivateFlags |= DRAWING_CACHE_VALID; 8050 } 8051 8052 // Fast path for layouts with no backgrounds 8053 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 8054 if (ViewDebug.TRACE_HIERARCHY) { 8055 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 8056 } 8057 mPrivateFlags &= ~DIRTY_MASK; 8058 dispatchDraw(canvas); 8059 } else { 8060 draw(canvas); 8061 } 8062 8063 canvas.restoreToCount(restoreCount); 8064 8065 if (attachInfo != null) { 8066 // Restore the cached Canvas for our siblings 8067 attachInfo.mCanvas = canvas; 8068 } 8069 } 8070 } 8071 8072 /** 8073 * Create a snapshot of the view into a bitmap. We should probably make 8074 * some form of this public, but should think about the API. 8075 */ 8076 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 8077 int width = mRight - mLeft; 8078 int height = mBottom - mTop; 8079 8080 final AttachInfo attachInfo = mAttachInfo; 8081 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 8082 width = (int) ((width * scale) + 0.5f); 8083 height = (int) ((height * scale) + 0.5f); 8084 8085 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 8086 if (bitmap == null) { 8087 throw new OutOfMemoryError(); 8088 } 8089 8090 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 8091 8092 Canvas canvas; 8093 if (attachInfo != null) { 8094 canvas = attachInfo.mCanvas; 8095 if (canvas == null) { 8096 canvas = new Canvas(); 8097 } 8098 canvas.setBitmap(bitmap); 8099 // Temporarily clobber the cached Canvas in case one of our children 8100 // is also using a drawing cache. Without this, the children would 8101 // steal the canvas by attaching their own bitmap to it and bad, bad 8102 // things would happen (invisible views, corrupted drawings, etc.) 8103 attachInfo.mCanvas = null; 8104 } else { 8105 // This case should hopefully never or seldom happen 8106 canvas = new Canvas(bitmap); 8107 } 8108 8109 if ((backgroundColor & 0xff000000) != 0) { 8110 bitmap.eraseColor(backgroundColor); 8111 } 8112 8113 computeScroll(); 8114 final int restoreCount = canvas.save(); 8115 canvas.scale(scale, scale); 8116 canvas.translate(-mScrollX, -mScrollY); 8117 8118 // Temporarily remove the dirty mask 8119 int flags = mPrivateFlags; 8120 mPrivateFlags &= ~DIRTY_MASK; 8121 8122 // Fast path for layouts with no backgrounds 8123 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 8124 dispatchDraw(canvas); 8125 } else { 8126 draw(canvas); 8127 } 8128 8129 mPrivateFlags = flags; 8130 8131 canvas.restoreToCount(restoreCount); 8132 8133 if (attachInfo != null) { 8134 // Restore the cached Canvas for our siblings 8135 attachInfo.mCanvas = canvas; 8136 } 8137 8138 return bitmap; 8139 } 8140 8141 /** 8142 * Indicates whether this View is currently in edit mode. A View is usually 8143 * in edit mode when displayed within a developer tool. For instance, if 8144 * this View is being drawn by a visual user interface builder, this method 8145 * should return true. 8146 * 8147 * Subclasses should check the return value of this method to provide 8148 * different behaviors if their normal behavior might interfere with the 8149 * host environment. For instance: the class spawns a thread in its 8150 * constructor, the drawing code relies on device-specific features, etc. 8151 * 8152 * This method is usually checked in the drawing code of custom widgets. 8153 * 8154 * @return True if this View is in edit mode, false otherwise. 8155 */ 8156 public boolean isInEditMode() { 8157 return false; 8158 } 8159 8160 /** 8161 * If the View draws content inside its padding and enables fading edges, 8162 * it needs to support padding offsets. Padding offsets are added to the 8163 * fading edges to extend the length of the fade so that it covers pixels 8164 * drawn inside the padding. 8165 * 8166 * Subclasses of this class should override this method if they need 8167 * to draw content inside the padding. 8168 * 8169 * @return True if padding offset must be applied, false otherwise. 8170 * 8171 * @see #getLeftPaddingOffset() 8172 * @see #getRightPaddingOffset() 8173 * @see #getTopPaddingOffset() 8174 * @see #getBottomPaddingOffset() 8175 * 8176 * @since CURRENT 8177 */ 8178 protected boolean isPaddingOffsetRequired() { 8179 return false; 8180 } 8181 8182 /** 8183 * Amount by which to extend the left fading region. Called only when 8184 * {@link #isPaddingOffsetRequired()} returns true. 8185 * 8186 * @return The left padding offset in pixels. 8187 * 8188 * @see #isPaddingOffsetRequired() 8189 * 8190 * @since CURRENT 8191 */ 8192 protected int getLeftPaddingOffset() { 8193 return 0; 8194 } 8195 8196 /** 8197 * Amount by which to extend the right fading region. Called only when 8198 * {@link #isPaddingOffsetRequired()} returns true. 8199 * 8200 * @return The right padding offset in pixels. 8201 * 8202 * @see #isPaddingOffsetRequired() 8203 * 8204 * @since CURRENT 8205 */ 8206 protected int getRightPaddingOffset() { 8207 return 0; 8208 } 8209 8210 /** 8211 * Amount by which to extend the top fading region. Called only when 8212 * {@link #isPaddingOffsetRequired()} returns true. 8213 * 8214 * @return The top padding offset in pixels. 8215 * 8216 * @see #isPaddingOffsetRequired() 8217 * 8218 * @since CURRENT 8219 */ 8220 protected int getTopPaddingOffset() { 8221 return 0; 8222 } 8223 8224 /** 8225 * Amount by which to extend the bottom fading region. Called only when 8226 * {@link #isPaddingOffsetRequired()} returns true. 8227 * 8228 * @return The bottom padding offset in pixels. 8229 * 8230 * @see #isPaddingOffsetRequired() 8231 * 8232 * @since CURRENT 8233 */ 8234 protected int getBottomPaddingOffset() { 8235 return 0; 8236 } 8237 8238 /** 8239 * <p>Indicates whether this view is attached to an hardware accelerated 8240 * window or not.</p> 8241 * 8242 * <p>Even if this method returns true, it does not mean that every call 8243 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 8244 * accelerated {@link android.graphics.Canvas}. For instance, if this view 8245 * is drawn onto an offscren {@link android.graphics.Bitmap} and its 8246 * window is hardware accelerated, 8247 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 8248 * return false, and this method will return true.</p> 8249 * 8250 * @return True if the view is attached to a window and the window is 8251 * hardware accelerated; false in any other case. 8252 */ 8253 public boolean isHardwareAccelerated() { 8254 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 8255 } 8256 8257 /** 8258 * Manually render this view (and all of its children) to the given Canvas. 8259 * The view must have already done a full layout before this function is 8260 * called. When implementing a view, implement {@link #onDraw} instead of 8261 * overriding this method. If you do need to override this method, call 8262 * the superclass version. 8263 * 8264 * @param canvas The Canvas to which the View is rendered. 8265 */ 8266 public void draw(Canvas canvas) { 8267 if (ViewDebug.TRACE_HIERARCHY) { 8268 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 8269 } 8270 8271 final int privateFlags = mPrivateFlags; 8272 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 8273 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 8274 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 8275 8276 /* 8277 * Draw traversal performs several drawing steps which must be executed 8278 * in the appropriate order: 8279 * 8280 * 1. Draw the background 8281 * 2. If necessary, save the canvas' layers to prepare for fading 8282 * 3. Draw view's content 8283 * 4. Draw children 8284 * 5. If necessary, draw the fading edges and restore layers 8285 * 6. Draw decorations (scrollbars for instance) 8286 */ 8287 8288 // Step 1, draw the background, if needed 8289 int saveCount; 8290 8291 if (!dirtyOpaque) { 8292 final Drawable background = mBGDrawable; 8293 if (background != null) { 8294 final int scrollX = mScrollX; 8295 final int scrollY = mScrollY; 8296 8297 if (mBackgroundSizeChanged) { 8298 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 8299 mBackgroundSizeChanged = false; 8300 } 8301 8302 if ((scrollX | scrollY) == 0) { 8303 background.draw(canvas); 8304 } else { 8305 canvas.translate(scrollX, scrollY); 8306 background.draw(canvas); 8307 canvas.translate(-scrollX, -scrollY); 8308 } 8309 } 8310 } 8311 8312 // skip step 2 & 5 if possible (common case) 8313 final int viewFlags = mViewFlags; 8314 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 8315 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 8316 if (!verticalEdges && !horizontalEdges) { 8317 // Step 3, draw the content 8318 if (!dirtyOpaque) onDraw(canvas); 8319 8320 // Step 4, draw the children 8321 dispatchDraw(canvas); 8322 8323 // Step 6, draw decorations (scrollbars) 8324 onDrawScrollBars(canvas); 8325 8326 // we're done... 8327 return; 8328 } 8329 8330 /* 8331 * Here we do the full fledged routine... 8332 * (this is an uncommon case where speed matters less, 8333 * this is why we repeat some of the tests that have been 8334 * done above) 8335 */ 8336 8337 boolean drawTop = false; 8338 boolean drawBottom = false; 8339 boolean drawLeft = false; 8340 boolean drawRight = false; 8341 8342 float topFadeStrength = 0.0f; 8343 float bottomFadeStrength = 0.0f; 8344 float leftFadeStrength = 0.0f; 8345 float rightFadeStrength = 0.0f; 8346 8347 // Step 2, save the canvas' layers 8348 int paddingLeft = mPaddingLeft; 8349 int paddingTop = mPaddingTop; 8350 8351 final boolean offsetRequired = isPaddingOffsetRequired(); 8352 if (offsetRequired) { 8353 paddingLeft += getLeftPaddingOffset(); 8354 paddingTop += getTopPaddingOffset(); 8355 } 8356 8357 int left = mScrollX + paddingLeft; 8358 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 8359 int top = mScrollY + paddingTop; 8360 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop; 8361 8362 if (offsetRequired) { 8363 right += getRightPaddingOffset(); 8364 bottom += getBottomPaddingOffset(); 8365 } 8366 8367 final ScrollabilityCache scrollabilityCache = mScrollCache; 8368 int length = scrollabilityCache.fadingEdgeLength; 8369 8370 // clip the fade length if top and bottom fades overlap 8371 // overlapping fades produce odd-looking artifacts 8372 if (verticalEdges && (top + length > bottom - length)) { 8373 length = (bottom - top) / 2; 8374 } 8375 8376 // also clip horizontal fades if necessary 8377 if (horizontalEdges && (left + length > right - length)) { 8378 length = (right - left) / 2; 8379 } 8380 8381 if (verticalEdges) { 8382 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 8383 drawTop = topFadeStrength > 0.0f; 8384 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 8385 drawBottom = bottomFadeStrength > 0.0f; 8386 } 8387 8388 if (horizontalEdges) { 8389 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 8390 drawLeft = leftFadeStrength > 0.0f; 8391 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 8392 drawRight = rightFadeStrength > 0.0f; 8393 } 8394 8395 saveCount = canvas.getSaveCount(); 8396 8397 int solidColor = getSolidColor(); 8398 if (solidColor == 0) { 8399 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 8400 8401 if (drawTop) { 8402 canvas.saveLayer(left, top, right, top + length, null, flags); 8403 } 8404 8405 if (drawBottom) { 8406 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 8407 } 8408 8409 if (drawLeft) { 8410 canvas.saveLayer(left, top, left + length, bottom, null, flags); 8411 } 8412 8413 if (drawRight) { 8414 canvas.saveLayer(right - length, top, right, bottom, null, flags); 8415 } 8416 } else { 8417 scrollabilityCache.setFadeColor(solidColor); 8418 } 8419 8420 // Step 3, draw the content 8421 if (!dirtyOpaque) onDraw(canvas); 8422 8423 // Step 4, draw the children 8424 dispatchDraw(canvas); 8425 8426 // Step 5, draw the fade effect and restore layers 8427 final Paint p = scrollabilityCache.paint; 8428 final Matrix matrix = scrollabilityCache.matrix; 8429 final Shader fade = scrollabilityCache.shader; 8430 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 8431 8432 if (drawTop) { 8433 matrix.setScale(1, fadeHeight * topFadeStrength); 8434 matrix.postTranslate(left, top); 8435 fade.setLocalMatrix(matrix); 8436 canvas.drawRect(left, top, right, top + length, p); 8437 } 8438 8439 if (drawBottom) { 8440 matrix.setScale(1, fadeHeight * bottomFadeStrength); 8441 matrix.postRotate(180); 8442 matrix.postTranslate(left, bottom); 8443 fade.setLocalMatrix(matrix); 8444 canvas.drawRect(left, bottom - length, right, bottom, p); 8445 } 8446 8447 if (drawLeft) { 8448 matrix.setScale(1, fadeHeight * leftFadeStrength); 8449 matrix.postRotate(-90); 8450 matrix.postTranslate(left, top); 8451 fade.setLocalMatrix(matrix); 8452 canvas.drawRect(left, top, left + length, bottom, p); 8453 } 8454 8455 if (drawRight) { 8456 matrix.setScale(1, fadeHeight * rightFadeStrength); 8457 matrix.postRotate(90); 8458 matrix.postTranslate(right, top); 8459 fade.setLocalMatrix(matrix); 8460 canvas.drawRect(right - length, top, right, bottom, p); 8461 } 8462 8463 canvas.restoreToCount(saveCount); 8464 8465 // Step 6, draw decorations (scrollbars) 8466 onDrawScrollBars(canvas); 8467 } 8468 8469 /** 8470 * Override this if your view is known to always be drawn on top of a solid color background, 8471 * and needs to draw fading edges. Returning a non-zero color enables the view system to 8472 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 8473 * should be set to 0xFF. 8474 * 8475 * @see #setVerticalFadingEdgeEnabled 8476 * @see #setHorizontalFadingEdgeEnabled 8477 * 8478 * @return The known solid color background for this view, or 0 if the color may vary 8479 */ 8480 public int getSolidColor() { 8481 return 0; 8482 } 8483 8484 /** 8485 * Build a human readable string representation of the specified view flags. 8486 * 8487 * @param flags the view flags to convert to a string 8488 * @return a String representing the supplied flags 8489 */ 8490 private static String printFlags(int flags) { 8491 String output = ""; 8492 int numFlags = 0; 8493 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 8494 output += "TAKES_FOCUS"; 8495 numFlags++; 8496 } 8497 8498 switch (flags & VISIBILITY_MASK) { 8499 case INVISIBLE: 8500 if (numFlags > 0) { 8501 output += " "; 8502 } 8503 output += "INVISIBLE"; 8504 // USELESS HERE numFlags++; 8505 break; 8506 case GONE: 8507 if (numFlags > 0) { 8508 output += " "; 8509 } 8510 output += "GONE"; 8511 // USELESS HERE numFlags++; 8512 break; 8513 default: 8514 break; 8515 } 8516 return output; 8517 } 8518 8519 /** 8520 * Build a human readable string representation of the specified private 8521 * view flags. 8522 * 8523 * @param privateFlags the private view flags to convert to a string 8524 * @return a String representing the supplied flags 8525 */ 8526 private static String printPrivateFlags(int privateFlags) { 8527 String output = ""; 8528 int numFlags = 0; 8529 8530 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 8531 output += "WANTS_FOCUS"; 8532 numFlags++; 8533 } 8534 8535 if ((privateFlags & FOCUSED) == FOCUSED) { 8536 if (numFlags > 0) { 8537 output += " "; 8538 } 8539 output += "FOCUSED"; 8540 numFlags++; 8541 } 8542 8543 if ((privateFlags & SELECTED) == SELECTED) { 8544 if (numFlags > 0) { 8545 output += " "; 8546 } 8547 output += "SELECTED"; 8548 numFlags++; 8549 } 8550 8551 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 8552 if (numFlags > 0) { 8553 output += " "; 8554 } 8555 output += "IS_ROOT_NAMESPACE"; 8556 numFlags++; 8557 } 8558 8559 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 8560 if (numFlags > 0) { 8561 output += " "; 8562 } 8563 output += "HAS_BOUNDS"; 8564 numFlags++; 8565 } 8566 8567 if ((privateFlags & DRAWN) == DRAWN) { 8568 if (numFlags > 0) { 8569 output += " "; 8570 } 8571 output += "DRAWN"; 8572 // USELESS HERE numFlags++; 8573 } 8574 return output; 8575 } 8576 8577 /** 8578 * <p>Indicates whether or not this view's layout will be requested during 8579 * the next hierarchy layout pass.</p> 8580 * 8581 * @return true if the layout will be forced during next layout pass 8582 */ 8583 public boolean isLayoutRequested() { 8584 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 8585 } 8586 8587 /** 8588 * Assign a size and position to a view and all of its 8589 * descendants 8590 * 8591 * <p>This is the second phase of the layout mechanism. 8592 * (The first is measuring). In this phase, each parent calls 8593 * layout on all of its children to position them. 8594 * This is typically done using the child measurements 8595 * that were stored in the measure pass(). 8596 * 8597 * Derived classes with children should override 8598 * onLayout. In that method, they should 8599 * call layout on each of their children. 8600 * 8601 * @param l Left position, relative to parent 8602 * @param t Top position, relative to parent 8603 * @param r Right position, relative to parent 8604 * @param b Bottom position, relative to parent 8605 */ 8606 @SuppressWarnings({"unchecked"}) 8607 public final void layout(int l, int t, int r, int b) { 8608 int oldL = mLeft; 8609 int oldT = mTop; 8610 int oldB = mBottom; 8611 int oldR = mRight; 8612 boolean changed = setFrame(l, t, r, b); 8613 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 8614 if (ViewDebug.TRACE_HIERARCHY) { 8615 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 8616 } 8617 8618 onLayout(changed, l, t, r, b); 8619 mPrivateFlags &= ~LAYOUT_REQUIRED; 8620 8621 if (mOnLayoutChangeListeners != null) { 8622 ArrayList<OnLayoutChangeListener> listenersCopy = 8623 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone(); 8624 int numListeners = listenersCopy.size(); 8625 for (int i = 0; i < numListeners; ++i) { 8626 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 8627 } 8628 } 8629 } 8630 mPrivateFlags &= ~FORCE_LAYOUT; 8631 } 8632 8633 /** 8634 * Called from layout when this view should 8635 * assign a size and position to each of its children. 8636 * 8637 * Derived classes with children should override 8638 * this method and call layout on each of 8639 * their children. 8640 * @param changed This is a new size or position for this view 8641 * @param left Left position, relative to parent 8642 * @param top Top position, relative to parent 8643 * @param right Right position, relative to parent 8644 * @param bottom Bottom position, relative to parent 8645 */ 8646 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 8647 } 8648 8649 /** 8650 * Assign a size and position to this view. 8651 * 8652 * This is called from layout. 8653 * 8654 * @param left Left position, relative to parent 8655 * @param top Top position, relative to parent 8656 * @param right Right position, relative to parent 8657 * @param bottom Bottom position, relative to parent 8658 * @return true if the new size and position are different than the 8659 * previous ones 8660 * {@hide} 8661 */ 8662 protected boolean setFrame(int left, int top, int right, int bottom) { 8663 boolean changed = false; 8664 8665 if (DBG) { 8666 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 8667 + right + "," + bottom + ")"); 8668 } 8669 8670 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 8671 changed = true; 8672 8673 // Remember our drawn bit 8674 int drawn = mPrivateFlags & DRAWN; 8675 8676 // Invalidate our old position 8677 invalidate(); 8678 8679 8680 int oldWidth = mRight - mLeft; 8681 int oldHeight = mBottom - mTop; 8682 8683 mLeft = left; 8684 mTop = top; 8685 mRight = right; 8686 mBottom = bottom; 8687 8688 mPrivateFlags |= HAS_BOUNDS; 8689 8690 int newWidth = right - left; 8691 int newHeight = bottom - top; 8692 8693 if (newWidth != oldWidth || newHeight != oldHeight) { 8694 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 8695 } 8696 8697 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 8698 // If we are visible, force the DRAWN bit to on so that 8699 // this invalidate will go through (at least to our parent). 8700 // This is because someone may have invalidated this view 8701 // before this call to setFrame came in, therby clearing 8702 // the DRAWN bit. 8703 mPrivateFlags |= DRAWN; 8704 invalidate(); 8705 } 8706 8707 // Reset drawn bit to original value (invalidate turns it off) 8708 mPrivateFlags |= drawn; 8709 8710 mBackgroundSizeChanged = true; 8711 } 8712 return changed; 8713 } 8714 8715 /** 8716 * Finalize inflating a view from XML. This is called as the last phase 8717 * of inflation, after all child views have been added. 8718 * 8719 * <p>Even if the subclass overrides onFinishInflate, they should always be 8720 * sure to call the super method, so that we get called. 8721 */ 8722 protected void onFinishInflate() { 8723 } 8724 8725 /** 8726 * Returns the resources associated with this view. 8727 * 8728 * @return Resources object. 8729 */ 8730 public Resources getResources() { 8731 return mResources; 8732 } 8733 8734 /** 8735 * Invalidates the specified Drawable. 8736 * 8737 * @param drawable the drawable to invalidate 8738 */ 8739 public void invalidateDrawable(Drawable drawable) { 8740 if (verifyDrawable(drawable)) { 8741 final Rect dirty = drawable.getBounds(); 8742 final int scrollX = mScrollX; 8743 final int scrollY = mScrollY; 8744 8745 invalidate(dirty.left + scrollX, dirty.top + scrollY, 8746 dirty.right + scrollX, dirty.bottom + scrollY); 8747 } 8748 } 8749 8750 /** 8751 * Schedules an action on a drawable to occur at a specified time. 8752 * 8753 * @param who the recipient of the action 8754 * @param what the action to run on the drawable 8755 * @param when the time at which the action must occur. Uses the 8756 * {@link SystemClock#uptimeMillis} timebase. 8757 */ 8758 public void scheduleDrawable(Drawable who, Runnable what, long when) { 8759 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 8760 mAttachInfo.mHandler.postAtTime(what, who, when); 8761 } 8762 } 8763 8764 /** 8765 * Cancels a scheduled action on a drawable. 8766 * 8767 * @param who the recipient of the action 8768 * @param what the action to cancel 8769 */ 8770 public void unscheduleDrawable(Drawable who, Runnable what) { 8771 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 8772 mAttachInfo.mHandler.removeCallbacks(what, who); 8773 } 8774 } 8775 8776 /** 8777 * Unschedule any events associated with the given Drawable. This can be 8778 * used when selecting a new Drawable into a view, so that the previous 8779 * one is completely unscheduled. 8780 * 8781 * @param who The Drawable to unschedule. 8782 * 8783 * @see #drawableStateChanged 8784 */ 8785 public void unscheduleDrawable(Drawable who) { 8786 if (mAttachInfo != null) { 8787 mAttachInfo.mHandler.removeCallbacksAndMessages(who); 8788 } 8789 } 8790 8791 /** 8792 * If your view subclass is displaying its own Drawable objects, it should 8793 * override this function and return true for any Drawable it is 8794 * displaying. This allows animations for those drawables to be 8795 * scheduled. 8796 * 8797 * <p>Be sure to call through to the super class when overriding this 8798 * function. 8799 * 8800 * @param who The Drawable to verify. Return true if it is one you are 8801 * displaying, else return the result of calling through to the 8802 * super class. 8803 * 8804 * @return boolean If true than the Drawable is being displayed in the 8805 * view; else false and it is not allowed to animate. 8806 * 8807 * @see #unscheduleDrawable 8808 * @see #drawableStateChanged 8809 */ 8810 protected boolean verifyDrawable(Drawable who) { 8811 return who == mBGDrawable; 8812 } 8813 8814 /** 8815 * This function is called whenever the state of the view changes in such 8816 * a way that it impacts the state of drawables being shown. 8817 * 8818 * <p>Be sure to call through to the superclass when overriding this 8819 * function. 8820 * 8821 * @see Drawable#setState 8822 */ 8823 protected void drawableStateChanged() { 8824 Drawable d = mBGDrawable; 8825 if (d != null && d.isStateful()) { 8826 d.setState(getDrawableState()); 8827 } 8828 } 8829 8830 /** 8831 * Call this to force a view to update its drawable state. This will cause 8832 * drawableStateChanged to be called on this view. Views that are interested 8833 * in the new state should call getDrawableState. 8834 * 8835 * @see #drawableStateChanged 8836 * @see #getDrawableState 8837 */ 8838 public void refreshDrawableState() { 8839 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 8840 drawableStateChanged(); 8841 8842 ViewParent parent = mParent; 8843 if (parent != null) { 8844 parent.childDrawableStateChanged(this); 8845 } 8846 } 8847 8848 /** 8849 * Return an array of resource IDs of the drawable states representing the 8850 * current state of the view. 8851 * 8852 * @return The current drawable state 8853 * 8854 * @see Drawable#setState 8855 * @see #drawableStateChanged 8856 * @see #onCreateDrawableState 8857 */ 8858 public final int[] getDrawableState() { 8859 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 8860 return mDrawableState; 8861 } else { 8862 mDrawableState = onCreateDrawableState(0); 8863 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 8864 return mDrawableState; 8865 } 8866 } 8867 8868 /** 8869 * Generate the new {@link android.graphics.drawable.Drawable} state for 8870 * this view. This is called by the view 8871 * system when the cached Drawable state is determined to be invalid. To 8872 * retrieve the current state, you should use {@link #getDrawableState}. 8873 * 8874 * @param extraSpace if non-zero, this is the number of extra entries you 8875 * would like in the returned array in which you can place your own 8876 * states. 8877 * 8878 * @return Returns an array holding the current {@link Drawable} state of 8879 * the view. 8880 * 8881 * @see #mergeDrawableStates 8882 */ 8883 protected int[] onCreateDrawableState(int extraSpace) { 8884 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 8885 mParent instanceof View) { 8886 return ((View) mParent).onCreateDrawableState(extraSpace); 8887 } 8888 8889 int[] drawableState; 8890 8891 int privateFlags = mPrivateFlags; 8892 8893 int viewStateIndex = 0; 8894 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 8895 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 8896 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 8897 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 8898 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 8899 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 8900 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) { 8901 // This is set if HW acceleration is requested, even if the current 8902 // process doesn't allow it. This is just to allow app preview 8903 // windows to better match their app. 8904 viewStateIndex |= VIEW_STATE_ACCELERATED; 8905 } 8906 8907 drawableState = VIEW_STATE_SETS[viewStateIndex]; 8908 8909 //noinspection ConstantIfStatement 8910 if (false) { 8911 Log.i("View", "drawableStateIndex=" + viewStateIndex); 8912 Log.i("View", toString() 8913 + " pressed=" + ((privateFlags & PRESSED) != 0) 8914 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 8915 + " fo=" + hasFocus() 8916 + " sl=" + ((privateFlags & SELECTED) != 0) 8917 + " wf=" + hasWindowFocus() 8918 + ": " + Arrays.toString(drawableState)); 8919 } 8920 8921 if (extraSpace == 0) { 8922 return drawableState; 8923 } 8924 8925 final int[] fullState; 8926 if (drawableState != null) { 8927 fullState = new int[drawableState.length + extraSpace]; 8928 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 8929 } else { 8930 fullState = new int[extraSpace]; 8931 } 8932 8933 return fullState; 8934 } 8935 8936 /** 8937 * Merge your own state values in <var>additionalState</var> into the base 8938 * state values <var>baseState</var> that were returned by 8939 * {@link #onCreateDrawableState}. 8940 * 8941 * @param baseState The base state values returned by 8942 * {@link #onCreateDrawableState}, which will be modified to also hold your 8943 * own additional state values. 8944 * 8945 * @param additionalState The additional state values you would like 8946 * added to <var>baseState</var>; this array is not modified. 8947 * 8948 * @return As a convenience, the <var>baseState</var> array you originally 8949 * passed into the function is returned. 8950 * 8951 * @see #onCreateDrawableState 8952 */ 8953 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 8954 final int N = baseState.length; 8955 int i = N - 1; 8956 while (i >= 0 && baseState[i] == 0) { 8957 i--; 8958 } 8959 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 8960 return baseState; 8961 } 8962 8963 /** 8964 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 8965 * on all Drawable objects associated with this view. 8966 */ 8967 public void jumpDrawablesToCurrentState() { 8968 if (mBGDrawable != null) { 8969 mBGDrawable.jumpToCurrentState(); 8970 } 8971 } 8972 8973 /** 8974 * Sets the background color for this view. 8975 * @param color the color of the background 8976 */ 8977 @RemotableViewMethod 8978 public void setBackgroundColor(int color) { 8979 if (mBGDrawable instanceof ColorDrawable) { 8980 ((ColorDrawable) mBGDrawable).setColor(color); 8981 } else { 8982 setBackgroundDrawable(new ColorDrawable(color)); 8983 } 8984 } 8985 8986 /** 8987 * Set the background to a given resource. The resource should refer to 8988 * a Drawable object or 0 to remove the background. 8989 * @param resid The identifier of the resource. 8990 * @attr ref android.R.styleable#View_background 8991 */ 8992 @RemotableViewMethod 8993 public void setBackgroundResource(int resid) { 8994 if (resid != 0 && resid == mBackgroundResource) { 8995 return; 8996 } 8997 8998 Drawable d= null; 8999 if (resid != 0) { 9000 d = mResources.getDrawable(resid); 9001 } 9002 setBackgroundDrawable(d); 9003 9004 mBackgroundResource = resid; 9005 } 9006 9007 /** 9008 * Set the background to a given Drawable, or remove the background. If the 9009 * background has padding, this View's padding is set to the background's 9010 * padding. However, when a background is removed, this View's padding isn't 9011 * touched. If setting the padding is desired, please use 9012 * {@link #setPadding(int, int, int, int)}. 9013 * 9014 * @param d The Drawable to use as the background, or null to remove the 9015 * background 9016 */ 9017 public void setBackgroundDrawable(Drawable d) { 9018 boolean requestLayout = false; 9019 9020 mBackgroundResource = 0; 9021 9022 /* 9023 * Regardless of whether we're setting a new background or not, we want 9024 * to clear the previous drawable. 9025 */ 9026 if (mBGDrawable != null) { 9027 mBGDrawable.setCallback(null); 9028 unscheduleDrawable(mBGDrawable); 9029 } 9030 9031 if (d != null) { 9032 Rect padding = sThreadLocal.get(); 9033 if (padding == null) { 9034 padding = new Rect(); 9035 sThreadLocal.set(padding); 9036 } 9037 if (d.getPadding(padding)) { 9038 setPadding(padding.left, padding.top, padding.right, padding.bottom); 9039 } 9040 9041 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 9042 // if it has a different minimum size, we should layout again 9043 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 9044 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 9045 requestLayout = true; 9046 } 9047 9048 d.setCallback(this); 9049 if (d.isStateful()) { 9050 d.setState(getDrawableState()); 9051 } 9052 d.setVisible(getVisibility() == VISIBLE, false); 9053 mBGDrawable = d; 9054 9055 if ((mPrivateFlags & SKIP_DRAW) != 0) { 9056 mPrivateFlags &= ~SKIP_DRAW; 9057 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 9058 requestLayout = true; 9059 } 9060 } else { 9061 /* Remove the background */ 9062 mBGDrawable = null; 9063 9064 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 9065 /* 9066 * This view ONLY drew the background before and we're removing 9067 * the background, so now it won't draw anything 9068 * (hence we SKIP_DRAW) 9069 */ 9070 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 9071 mPrivateFlags |= SKIP_DRAW; 9072 } 9073 9074 /* 9075 * When the background is set, we try to apply its padding to this 9076 * View. When the background is removed, we don't touch this View's 9077 * padding. This is noted in the Javadocs. Hence, we don't need to 9078 * requestLayout(), the invalidate() below is sufficient. 9079 */ 9080 9081 // The old background's minimum size could have affected this 9082 // View's layout, so let's requestLayout 9083 requestLayout = true; 9084 } 9085 9086 computeOpaqueFlags(); 9087 9088 if (requestLayout) { 9089 requestLayout(); 9090 } 9091 9092 mBackgroundSizeChanged = true; 9093 invalidate(); 9094 } 9095 9096 /** 9097 * Gets the background drawable 9098 * @return The drawable used as the background for this view, if any. 9099 */ 9100 public Drawable getBackground() { 9101 return mBGDrawable; 9102 } 9103 9104 /** 9105 * Sets the padding. The view may add on the space required to display 9106 * the scrollbars, depending on the style and visibility of the scrollbars. 9107 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 9108 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 9109 * from the values set in this call. 9110 * 9111 * @attr ref android.R.styleable#View_padding 9112 * @attr ref android.R.styleable#View_paddingBottom 9113 * @attr ref android.R.styleable#View_paddingLeft 9114 * @attr ref android.R.styleable#View_paddingRight 9115 * @attr ref android.R.styleable#View_paddingTop 9116 * @param left the left padding in pixels 9117 * @param top the top padding in pixels 9118 * @param right the right padding in pixels 9119 * @param bottom the bottom padding in pixels 9120 */ 9121 public void setPadding(int left, int top, int right, int bottom) { 9122 boolean changed = false; 9123 9124 mUserPaddingLeft = left; 9125 mUserPaddingRight = right; 9126 mUserPaddingBottom = bottom; 9127 9128 final int viewFlags = mViewFlags; 9129 9130 // Common case is there are no scroll bars. 9131 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 9132 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 9133 // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings. 9134 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 9135 ? 0 : getVerticalScrollbarWidth(); 9136 switch (mVerticalScrollbarPosition) { 9137 case SCROLLBAR_POSITION_DEFAULT: 9138 case SCROLLBAR_POSITION_RIGHT: 9139 right += offset; 9140 break; 9141 case SCROLLBAR_POSITION_LEFT: 9142 left += offset; 9143 break; 9144 } 9145 } 9146 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 9147 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 9148 ? 0 : getHorizontalScrollbarHeight(); 9149 } 9150 } 9151 9152 if (mPaddingLeft != left) { 9153 changed = true; 9154 mPaddingLeft = left; 9155 } 9156 if (mPaddingTop != top) { 9157 changed = true; 9158 mPaddingTop = top; 9159 } 9160 if (mPaddingRight != right) { 9161 changed = true; 9162 mPaddingRight = right; 9163 } 9164 if (mPaddingBottom != bottom) { 9165 changed = true; 9166 mPaddingBottom = bottom; 9167 } 9168 9169 if (changed) { 9170 requestLayout(); 9171 } 9172 } 9173 9174 /** 9175 * Returns the top padding of this view. 9176 * 9177 * @return the top padding in pixels 9178 */ 9179 public int getPaddingTop() { 9180 return mPaddingTop; 9181 } 9182 9183 /** 9184 * Returns the bottom padding of this view. If there are inset and enabled 9185 * scrollbars, this value may include the space required to display the 9186 * scrollbars as well. 9187 * 9188 * @return the bottom padding in pixels 9189 */ 9190 public int getPaddingBottom() { 9191 return mPaddingBottom; 9192 } 9193 9194 /** 9195 * Returns the left padding of this view. If there are inset and enabled 9196 * scrollbars, this value may include the space required to display the 9197 * scrollbars as well. 9198 * 9199 * @return the left padding in pixels 9200 */ 9201 public int getPaddingLeft() { 9202 return mPaddingLeft; 9203 } 9204 9205 /** 9206 * Returns the right padding of this view. If there are inset and enabled 9207 * scrollbars, this value may include the space required to display the 9208 * scrollbars as well. 9209 * 9210 * @return the right padding in pixels 9211 */ 9212 public int getPaddingRight() { 9213 return mPaddingRight; 9214 } 9215 9216 /** 9217 * Changes the selection state of this view. A view can be selected or not. 9218 * Note that selection is not the same as focus. Views are typically 9219 * selected in the context of an AdapterView like ListView or GridView; 9220 * the selected view is the view that is highlighted. 9221 * 9222 * @param selected true if the view must be selected, false otherwise 9223 */ 9224 public void setSelected(boolean selected) { 9225 if (((mPrivateFlags & SELECTED) != 0) != selected) { 9226 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 9227 if (!selected) resetPressedState(); 9228 invalidate(); 9229 refreshDrawableState(); 9230 dispatchSetSelected(selected); 9231 } 9232 } 9233 9234 /** 9235 * Dispatch setSelected to all of this View's children. 9236 * 9237 * @see #setSelected(boolean) 9238 * 9239 * @param selected The new selected state 9240 */ 9241 protected void dispatchSetSelected(boolean selected) { 9242 } 9243 9244 /** 9245 * Indicates the selection state of this view. 9246 * 9247 * @return true if the view is selected, false otherwise 9248 */ 9249 @ViewDebug.ExportedProperty 9250 public boolean isSelected() { 9251 return (mPrivateFlags & SELECTED) != 0; 9252 } 9253 9254 /** 9255 * Changes the activated state of this view. A view can be activated or not. 9256 * Note that activation is not the same as selection. Selection is 9257 * a transient property, representing the view (hierarchy) the user is 9258 * currently interacting with. Activation is a longer-term state that the 9259 * user can move views in and out of. For example, in a list view with 9260 * single or multiple selection enabled, the views in the current selection 9261 * set are activated. (Um, yeah, we are deeply sorry about the terminology 9262 * here.) The activated state is propagated down to children of the view it 9263 * is set on. 9264 * 9265 * @param activated true if the view must be activated, false otherwise 9266 */ 9267 public void setActivated(boolean activated) { 9268 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 9269 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 9270 invalidate(); 9271 refreshDrawableState(); 9272 dispatchSetActivated(activated); 9273 } 9274 } 9275 9276 /** 9277 * Dispatch setActivated to all of this View's children. 9278 * 9279 * @see #setActivated(boolean) 9280 * 9281 * @param activated The new activated state 9282 */ 9283 protected void dispatchSetActivated(boolean activated) { 9284 } 9285 9286 /** 9287 * Indicates the activation state of this view. 9288 * 9289 * @return true if the view is activated, false otherwise 9290 */ 9291 @ViewDebug.ExportedProperty 9292 public boolean isActivated() { 9293 return (mPrivateFlags & ACTIVATED) != 0; 9294 } 9295 9296 /** 9297 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 9298 * observer can be used to get notifications when global events, like 9299 * layout, happen. 9300 * 9301 * The returned ViewTreeObserver observer is not guaranteed to remain 9302 * valid for the lifetime of this View. If the caller of this method keeps 9303 * a long-lived reference to ViewTreeObserver, it should always check for 9304 * the return value of {@link ViewTreeObserver#isAlive()}. 9305 * 9306 * @return The ViewTreeObserver for this view's hierarchy. 9307 */ 9308 public ViewTreeObserver getViewTreeObserver() { 9309 if (mAttachInfo != null) { 9310 return mAttachInfo.mTreeObserver; 9311 } 9312 if (mFloatingTreeObserver == null) { 9313 mFloatingTreeObserver = new ViewTreeObserver(); 9314 } 9315 return mFloatingTreeObserver; 9316 } 9317 9318 /** 9319 * <p>Finds the topmost view in the current view hierarchy.</p> 9320 * 9321 * @return the topmost view containing this view 9322 */ 9323 public View getRootView() { 9324 if (mAttachInfo != null) { 9325 final View v = mAttachInfo.mRootView; 9326 if (v != null) { 9327 return v; 9328 } 9329 } 9330 9331 View parent = this; 9332 9333 while (parent.mParent != null && parent.mParent instanceof View) { 9334 parent = (View) parent.mParent; 9335 } 9336 9337 return parent; 9338 } 9339 9340 /** 9341 * <p>Computes the coordinates of this view on the screen. The argument 9342 * must be an array of two integers. After the method returns, the array 9343 * contains the x and y location in that order.</p> 9344 * 9345 * @param location an array of two integers in which to hold the coordinates 9346 */ 9347 public void getLocationOnScreen(int[] location) { 9348 getLocationInWindow(location); 9349 9350 final AttachInfo info = mAttachInfo; 9351 if (info != null) { 9352 location[0] += info.mWindowLeft; 9353 location[1] += info.mWindowTop; 9354 } 9355 } 9356 9357 /** 9358 * <p>Computes the coordinates of this view in its window. The argument 9359 * must be an array of two integers. After the method returns, the array 9360 * contains the x and y location in that order.</p> 9361 * 9362 * @param location an array of two integers in which to hold the coordinates 9363 */ 9364 public void getLocationInWindow(int[] location) { 9365 if (location == null || location.length < 2) { 9366 throw new IllegalArgumentException("location must be an array of " 9367 + "two integers"); 9368 } 9369 9370 location[0] = mLeft + (int) (mTranslationX + 0.5f); 9371 location[1] = mTop + (int) (mTranslationY + 0.5f); 9372 9373 ViewParent viewParent = mParent; 9374 while (viewParent instanceof View) { 9375 final View view = (View)viewParent; 9376 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX; 9377 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY; 9378 viewParent = view.mParent; 9379 } 9380 9381 if (viewParent instanceof ViewRoot) { 9382 // *cough* 9383 final ViewRoot vr = (ViewRoot)viewParent; 9384 location[1] -= vr.mCurScrollY; 9385 } 9386 } 9387 9388 /** 9389 * {@hide} 9390 * @param id the id of the view to be found 9391 * @return the view of the specified id, null if cannot be found 9392 */ 9393 protected View findViewTraversal(int id) { 9394 if (id == mID) { 9395 return this; 9396 } 9397 return null; 9398 } 9399 9400 /** 9401 * {@hide} 9402 * @param tag the tag of the view to be found 9403 * @return the view of specified tag, null if cannot be found 9404 */ 9405 protected View findViewWithTagTraversal(Object tag) { 9406 if (tag != null && tag.equals(mTag)) { 9407 return this; 9408 } 9409 return null; 9410 } 9411 9412 /** 9413 * {@hide} 9414 * @param predicate The predicate to evaluate. 9415 * @return The first view that matches the predicate or null. 9416 */ 9417 protected View findViewByPredicateTraversal(Predicate<View> predicate) { 9418 if (predicate.apply(this)) { 9419 return this; 9420 } 9421 return null; 9422 } 9423 9424 /** 9425 * Look for a child view with the given id. If this view has the given 9426 * id, return this view. 9427 * 9428 * @param id The id to search for. 9429 * @return The view that has the given id in the hierarchy or null 9430 */ 9431 public final View findViewById(int id) { 9432 if (id < 0) { 9433 return null; 9434 } 9435 return findViewTraversal(id); 9436 } 9437 9438 /** 9439 * Look for a child view with the given tag. If this view has the given 9440 * tag, return this view. 9441 * 9442 * @param tag The tag to search for, using "tag.equals(getTag())". 9443 * @return The View that has the given tag in the hierarchy or null 9444 */ 9445 public final View findViewWithTag(Object tag) { 9446 if (tag == null) { 9447 return null; 9448 } 9449 return findViewWithTagTraversal(tag); 9450 } 9451 9452 /** 9453 * {@hide} 9454 * Look for a child view that matches the specified predicate. 9455 * If this view matches the predicate, return this view. 9456 * 9457 * @param predicate The predicate to evaluate. 9458 * @return The first view that matches the predicate or null. 9459 */ 9460 public final View findViewByPredicate(Predicate<View> predicate) { 9461 return findViewByPredicateTraversal(predicate); 9462 } 9463 9464 /** 9465 * Sets the identifier for this view. The identifier does not have to be 9466 * unique in this view's hierarchy. The identifier should be a positive 9467 * number. 9468 * 9469 * @see #NO_ID 9470 * @see #getId 9471 * @see #findViewById 9472 * 9473 * @param id a number used to identify the view 9474 * 9475 * @attr ref android.R.styleable#View_id 9476 */ 9477 public void setId(int id) { 9478 mID = id; 9479 } 9480 9481 /** 9482 * {@hide} 9483 * 9484 * @param isRoot true if the view belongs to the root namespace, false 9485 * otherwise 9486 */ 9487 public void setIsRootNamespace(boolean isRoot) { 9488 if (isRoot) { 9489 mPrivateFlags |= IS_ROOT_NAMESPACE; 9490 } else { 9491 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 9492 } 9493 } 9494 9495 /** 9496 * {@hide} 9497 * 9498 * @return true if the view belongs to the root namespace, false otherwise 9499 */ 9500 public boolean isRootNamespace() { 9501 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 9502 } 9503 9504 /** 9505 * Returns this view's identifier. 9506 * 9507 * @return a positive integer used to identify the view or {@link #NO_ID} 9508 * if the view has no ID 9509 * 9510 * @see #setId 9511 * @see #findViewById 9512 * @attr ref android.R.styleable#View_id 9513 */ 9514 @ViewDebug.CapturedViewProperty 9515 public int getId() { 9516 return mID; 9517 } 9518 9519 /** 9520 * Returns this view's tag. 9521 * 9522 * @return the Object stored in this view as a tag 9523 * 9524 * @see #setTag(Object) 9525 * @see #getTag(int) 9526 */ 9527 @ViewDebug.ExportedProperty 9528 public Object getTag() { 9529 return mTag; 9530 } 9531 9532 /** 9533 * Sets the tag associated with this view. A tag can be used to mark 9534 * a view in its hierarchy and does not have to be unique within the 9535 * hierarchy. Tags can also be used to store data within a view without 9536 * resorting to another data structure. 9537 * 9538 * @param tag an Object to tag the view with 9539 * 9540 * @see #getTag() 9541 * @see #setTag(int, Object) 9542 */ 9543 public void setTag(final Object tag) { 9544 mTag = tag; 9545 } 9546 9547 /** 9548 * Returns the tag associated with this view and the specified key. 9549 * 9550 * @param key The key identifying the tag 9551 * 9552 * @return the Object stored in this view as a tag 9553 * 9554 * @see #setTag(int, Object) 9555 * @see #getTag() 9556 */ 9557 public Object getTag(int key) { 9558 SparseArray<Object> tags = null; 9559 synchronized (sTagsLock) { 9560 if (sTags != null) { 9561 tags = sTags.get(this); 9562 } 9563 } 9564 9565 if (tags != null) return tags.get(key); 9566 return null; 9567 } 9568 9569 /** 9570 * Sets a tag associated with this view and a key. A tag can be used 9571 * to mark a view in its hierarchy and does not have to be unique within 9572 * the hierarchy. Tags can also be used to store data within a view 9573 * without resorting to another data structure. 9574 * 9575 * The specified key should be an id declared in the resources of the 9576 * application to ensure it is unique (see the <a 9577 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 9578 * Keys identified as belonging to 9579 * the Android framework or not associated with any package will cause 9580 * an {@link IllegalArgumentException} to be thrown. 9581 * 9582 * @param key The key identifying the tag 9583 * @param tag An Object to tag the view with 9584 * 9585 * @throws IllegalArgumentException If they specified key is not valid 9586 * 9587 * @see #setTag(Object) 9588 * @see #getTag(int) 9589 */ 9590 public void setTag(int key, final Object tag) { 9591 // If the package id is 0x00 or 0x01, it's either an undefined package 9592 // or a framework id 9593 if ((key >>> 24) < 2) { 9594 throw new IllegalArgumentException("The key must be an application-specific " 9595 + "resource id."); 9596 } 9597 9598 setTagInternal(this, key, tag); 9599 } 9600 9601 /** 9602 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 9603 * framework id. 9604 * 9605 * @hide 9606 */ 9607 public void setTagInternal(int key, Object tag) { 9608 if ((key >>> 24) != 0x1) { 9609 throw new IllegalArgumentException("The key must be a framework-specific " 9610 + "resource id."); 9611 } 9612 9613 setTagInternal(this, key, tag); 9614 } 9615 9616 private static void setTagInternal(View view, int key, Object tag) { 9617 SparseArray<Object> tags = null; 9618 synchronized (sTagsLock) { 9619 if (sTags == null) { 9620 sTags = new WeakHashMap<View, SparseArray<Object>>(); 9621 } else { 9622 tags = sTags.get(view); 9623 } 9624 } 9625 9626 if (tags == null) { 9627 tags = new SparseArray<Object>(2); 9628 synchronized (sTagsLock) { 9629 sTags.put(view, tags); 9630 } 9631 } 9632 9633 tags.put(key, tag); 9634 } 9635 9636 /** 9637 * @param consistency The type of consistency. See ViewDebug for more information. 9638 * 9639 * @hide 9640 */ 9641 protected boolean dispatchConsistencyCheck(int consistency) { 9642 return onConsistencyCheck(consistency); 9643 } 9644 9645 /** 9646 * Method that subclasses should implement to check their consistency. The type of 9647 * consistency check is indicated by the bit field passed as a parameter. 9648 * 9649 * @param consistency The type of consistency. See ViewDebug for more information. 9650 * 9651 * @throws IllegalStateException if the view is in an inconsistent state. 9652 * 9653 * @hide 9654 */ 9655 protected boolean onConsistencyCheck(int consistency) { 9656 boolean result = true; 9657 9658 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 9659 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 9660 9661 if (checkLayout) { 9662 if (getParent() == null) { 9663 result = false; 9664 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 9665 "View " + this + " does not have a parent."); 9666 } 9667 9668 if (mAttachInfo == null) { 9669 result = false; 9670 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 9671 "View " + this + " is not attached to a window."); 9672 } 9673 } 9674 9675 if (checkDrawing) { 9676 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 9677 // from their draw() method 9678 9679 if ((mPrivateFlags & DRAWN) != DRAWN && 9680 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 9681 result = false; 9682 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 9683 "View " + this + " was invalidated but its drawing cache is valid."); 9684 } 9685 } 9686 9687 return result; 9688 } 9689 9690 /** 9691 * Prints information about this view in the log output, with the tag 9692 * {@link #VIEW_LOG_TAG}. 9693 * 9694 * @hide 9695 */ 9696 public void debug() { 9697 debug(0); 9698 } 9699 9700 /** 9701 * Prints information about this view in the log output, with the tag 9702 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 9703 * indentation defined by the <code>depth</code>. 9704 * 9705 * @param depth the indentation level 9706 * 9707 * @hide 9708 */ 9709 protected void debug(int depth) { 9710 String output = debugIndent(depth - 1); 9711 9712 output += "+ " + this; 9713 int id = getId(); 9714 if (id != -1) { 9715 output += " (id=" + id + ")"; 9716 } 9717 Object tag = getTag(); 9718 if (tag != null) { 9719 output += " (tag=" + tag + ")"; 9720 } 9721 Log.d(VIEW_LOG_TAG, output); 9722 9723 if ((mPrivateFlags & FOCUSED) != 0) { 9724 output = debugIndent(depth) + " FOCUSED"; 9725 Log.d(VIEW_LOG_TAG, output); 9726 } 9727 9728 output = debugIndent(depth); 9729 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 9730 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 9731 + "} "; 9732 Log.d(VIEW_LOG_TAG, output); 9733 9734 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 9735 || mPaddingBottom != 0) { 9736 output = debugIndent(depth); 9737 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 9738 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 9739 Log.d(VIEW_LOG_TAG, output); 9740 } 9741 9742 output = debugIndent(depth); 9743 output += "mMeasureWidth=" + mMeasuredWidth + 9744 " mMeasureHeight=" + mMeasuredHeight; 9745 Log.d(VIEW_LOG_TAG, output); 9746 9747 output = debugIndent(depth); 9748 if (mLayoutParams == null) { 9749 output += "BAD! no layout params"; 9750 } else { 9751 output = mLayoutParams.debug(output); 9752 } 9753 Log.d(VIEW_LOG_TAG, output); 9754 9755 output = debugIndent(depth); 9756 output += "flags={"; 9757 output += View.printFlags(mViewFlags); 9758 output += "}"; 9759 Log.d(VIEW_LOG_TAG, output); 9760 9761 output = debugIndent(depth); 9762 output += "privateFlags={"; 9763 output += View.printPrivateFlags(mPrivateFlags); 9764 output += "}"; 9765 Log.d(VIEW_LOG_TAG, output); 9766 } 9767 9768 /** 9769 * Creates an string of whitespaces used for indentation. 9770 * 9771 * @param depth the indentation level 9772 * @return a String containing (depth * 2 + 3) * 2 white spaces 9773 * 9774 * @hide 9775 */ 9776 protected static String debugIndent(int depth) { 9777 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 9778 for (int i = 0; i < (depth * 2) + 3; i++) { 9779 spaces.append(' ').append(' '); 9780 } 9781 return spaces.toString(); 9782 } 9783 9784 /** 9785 * <p>Return the offset of the widget's text baseline from the widget's top 9786 * boundary. If this widget does not support baseline alignment, this 9787 * method returns -1. </p> 9788 * 9789 * @return the offset of the baseline within the widget's bounds or -1 9790 * if baseline alignment is not supported 9791 */ 9792 @ViewDebug.ExportedProperty(category = "layout") 9793 public int getBaseline() { 9794 return -1; 9795 } 9796 9797 /** 9798 * Call this when something has changed which has invalidated the 9799 * layout of this view. This will schedule a layout pass of the view 9800 * tree. 9801 */ 9802 public void requestLayout() { 9803 if (ViewDebug.TRACE_HIERARCHY) { 9804 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 9805 } 9806 9807 mPrivateFlags |= FORCE_LAYOUT; 9808 9809 if (mParent != null && !mParent.isLayoutRequested()) { 9810 mParent.requestLayout(); 9811 } 9812 } 9813 9814 /** 9815 * Forces this view to be laid out during the next layout pass. 9816 * This method does not call requestLayout() or forceLayout() 9817 * on the parent. 9818 */ 9819 public void forceLayout() { 9820 mPrivateFlags |= FORCE_LAYOUT; 9821 } 9822 9823 /** 9824 * <p> 9825 * This is called to find out how big a view should be. The parent 9826 * supplies constraint information in the width and height parameters. 9827 * </p> 9828 * 9829 * <p> 9830 * The actual mesurement work of a view is performed in 9831 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 9832 * {@link #onMeasure(int, int)} can and must be overriden by subclasses. 9833 * </p> 9834 * 9835 * 9836 * @param widthMeasureSpec Horizontal space requirements as imposed by the 9837 * parent 9838 * @param heightMeasureSpec Vertical space requirements as imposed by the 9839 * parent 9840 * 9841 * @see #onMeasure(int, int) 9842 */ 9843 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 9844 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 9845 widthMeasureSpec != mOldWidthMeasureSpec || 9846 heightMeasureSpec != mOldHeightMeasureSpec) { 9847 9848 // first clears the measured dimension flag 9849 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 9850 9851 if (ViewDebug.TRACE_HIERARCHY) { 9852 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 9853 } 9854 9855 // measure ourselves, this should set the measured dimension flag back 9856 onMeasure(widthMeasureSpec, heightMeasureSpec); 9857 9858 // flag not set, setMeasuredDimension() was not invoked, we raise 9859 // an exception to warn the developer 9860 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 9861 throw new IllegalStateException("onMeasure() did not set the" 9862 + " measured dimension by calling" 9863 + " setMeasuredDimension()"); 9864 } 9865 9866 mPrivateFlags |= LAYOUT_REQUIRED; 9867 } 9868 9869 mOldWidthMeasureSpec = widthMeasureSpec; 9870 mOldHeightMeasureSpec = heightMeasureSpec; 9871 } 9872 9873 /** 9874 * <p> 9875 * Measure the view and its content to determine the measured width and the 9876 * measured height. This method is invoked by {@link #measure(int, int)} and 9877 * should be overriden by subclasses to provide accurate and efficient 9878 * measurement of their contents. 9879 * </p> 9880 * 9881 * <p> 9882 * <strong>CONTRACT:</strong> When overriding this method, you 9883 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 9884 * measured width and height of this view. Failure to do so will trigger an 9885 * <code>IllegalStateException</code>, thrown by 9886 * {@link #measure(int, int)}. Calling the superclass' 9887 * {@link #onMeasure(int, int)} is a valid use. 9888 * </p> 9889 * 9890 * <p> 9891 * The base class implementation of measure defaults to the background size, 9892 * unless a larger size is allowed by the MeasureSpec. Subclasses should 9893 * override {@link #onMeasure(int, int)} to provide better measurements of 9894 * their content. 9895 * </p> 9896 * 9897 * <p> 9898 * If this method is overridden, it is the subclass's responsibility to make 9899 * sure the measured height and width are at least the view's minimum height 9900 * and width ({@link #getSuggestedMinimumHeight()} and 9901 * {@link #getSuggestedMinimumWidth()}). 9902 * </p> 9903 * 9904 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 9905 * The requirements are encoded with 9906 * {@link android.view.View.MeasureSpec}. 9907 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 9908 * The requirements are encoded with 9909 * {@link android.view.View.MeasureSpec}. 9910 * 9911 * @see #getMeasuredWidth() 9912 * @see #getMeasuredHeight() 9913 * @see #setMeasuredDimension(int, int) 9914 * @see #getSuggestedMinimumHeight() 9915 * @see #getSuggestedMinimumWidth() 9916 * @see android.view.View.MeasureSpec#getMode(int) 9917 * @see android.view.View.MeasureSpec#getSize(int) 9918 */ 9919 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 9920 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 9921 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 9922 } 9923 9924 /** 9925 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 9926 * measured width and measured height. Failing to do so will trigger an 9927 * exception at measurement time.</p> 9928 * 9929 * @param measuredWidth The measured width 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 * @param measuredHeight The measured height of this view. May be a complex 9933 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 9934 * {@link #MEASURED_STATE_TOO_SMALL}. 9935 */ 9936 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 9937 mMeasuredWidth = measuredWidth; 9938 mMeasuredHeight = measuredHeight; 9939 9940 mPrivateFlags |= MEASURED_DIMENSION_SET; 9941 } 9942 9943 /** 9944 * Merge two states as returned by {@link #getMeasuredState()}. 9945 * @param curState The current state as returned from a view or the result 9946 * of combining multiple views. 9947 * @param newState The new view state to combine. 9948 * @return Returns a new integer reflecting the combination of the two 9949 * states. 9950 */ 9951 public static int combineMeasuredStates(int curState, int newState) { 9952 return curState | newState; 9953 } 9954 9955 /** 9956 * Version of {@link #resolveSizeAndState(int, int, int)} 9957 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 9958 */ 9959 public static int resolveSize(int size, int measureSpec) { 9960 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 9961 } 9962 9963 /** 9964 * Utility to reconcile a desired size and state, with constraints imposed 9965 * by a MeasureSpec. Will take the desired size, unless a different size 9966 * is imposed by the constraints. The returned value is a compound integer, 9967 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 9968 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 9969 * size is smaller than the size the view wants to be. 9970 * 9971 * @param size How big the view wants to be 9972 * @param measureSpec Constraints imposed by the parent 9973 * @return Size information bit mask as defined by 9974 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9975 */ 9976 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 9977 int result = size; 9978 int specMode = MeasureSpec.getMode(measureSpec); 9979 int specSize = MeasureSpec.getSize(measureSpec); 9980 switch (specMode) { 9981 case MeasureSpec.UNSPECIFIED: 9982 result = size; 9983 break; 9984 case MeasureSpec.AT_MOST: 9985 if (specSize < size) { 9986 result = specSize | MEASURED_STATE_TOO_SMALL; 9987 } else { 9988 result = size; 9989 } 9990 break; 9991 case MeasureSpec.EXACTLY: 9992 result = specSize; 9993 break; 9994 } 9995 return result | (childMeasuredState&MEASURED_STATE_MASK); 9996 } 9997 9998 /** 9999 * Utility to return a default size. Uses the supplied size if the 10000 * MeasureSpec imposed no contraints. Will get larger if allowed 10001 * by the MeasureSpec. 10002 * 10003 * @param size Default size for this view 10004 * @param measureSpec Constraints imposed by the parent 10005 * @return The size this view should be. 10006 */ 10007 public static int getDefaultSize(int size, int measureSpec) { 10008 int result = size; 10009 int specMode = MeasureSpec.getMode(measureSpec); 10010 int specSize = MeasureSpec.getSize(measureSpec); 10011 10012 switch (specMode) { 10013 case MeasureSpec.UNSPECIFIED: 10014 result = size; 10015 break; 10016 case MeasureSpec.AT_MOST: 10017 case MeasureSpec.EXACTLY: 10018 result = specSize; 10019 break; 10020 } 10021 return result; 10022 } 10023 10024 /** 10025 * Returns the suggested minimum height that the view should use. This 10026 * returns the maximum of the view's minimum height 10027 * and the background's minimum height 10028 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 10029 * <p> 10030 * When being used in {@link #onMeasure(int, int)}, the caller should still 10031 * ensure the returned height is within the requirements of the parent. 10032 * 10033 * @return The suggested minimum height of the view. 10034 */ 10035 protected int getSuggestedMinimumHeight() { 10036 int suggestedMinHeight = mMinHeight; 10037 10038 if (mBGDrawable != null) { 10039 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 10040 if (suggestedMinHeight < bgMinHeight) { 10041 suggestedMinHeight = bgMinHeight; 10042 } 10043 } 10044 10045 return suggestedMinHeight; 10046 } 10047 10048 /** 10049 * Returns the suggested minimum width that the view should use. This 10050 * returns the maximum of the view's minimum width) 10051 * and the background's minimum width 10052 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 10053 * <p> 10054 * When being used in {@link #onMeasure(int, int)}, the caller should still 10055 * ensure the returned width is within the requirements of the parent. 10056 * 10057 * @return The suggested minimum width of the view. 10058 */ 10059 protected int getSuggestedMinimumWidth() { 10060 int suggestedMinWidth = mMinWidth; 10061 10062 if (mBGDrawable != null) { 10063 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 10064 if (suggestedMinWidth < bgMinWidth) { 10065 suggestedMinWidth = bgMinWidth; 10066 } 10067 } 10068 10069 return suggestedMinWidth; 10070 } 10071 10072 /** 10073 * Sets the minimum height of the view. It is not guaranteed the view will 10074 * be able to achieve this minimum height (for example, if its parent layout 10075 * constrains it with less available height). 10076 * 10077 * @param minHeight The minimum height the view will try to be. 10078 */ 10079 public void setMinimumHeight(int minHeight) { 10080 mMinHeight = minHeight; 10081 } 10082 10083 /** 10084 * Sets the minimum width of the view. It is not guaranteed the view will 10085 * be able to achieve this minimum width (for example, if its parent layout 10086 * constrains it with less available width). 10087 * 10088 * @param minWidth The minimum width the view will try to be. 10089 */ 10090 public void setMinimumWidth(int minWidth) { 10091 mMinWidth = minWidth; 10092 } 10093 10094 /** 10095 * Get the animation currently associated with this view. 10096 * 10097 * @return The animation that is currently playing or 10098 * scheduled to play for this view. 10099 */ 10100 public Animation getAnimation() { 10101 return mCurrentAnimation; 10102 } 10103 10104 /** 10105 * Start the specified animation now. 10106 * 10107 * @param animation the animation to start now 10108 */ 10109 public void startAnimation(Animation animation) { 10110 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 10111 setAnimation(animation); 10112 invalidate(); 10113 } 10114 10115 /** 10116 * Cancels any animations for this view. 10117 */ 10118 public void clearAnimation() { 10119 if (mCurrentAnimation != null) { 10120 mCurrentAnimation.detach(); 10121 } 10122 mCurrentAnimation = null; 10123 } 10124 10125 /** 10126 * Sets the next animation to play for this view. 10127 * If you want the animation to play immediately, use 10128 * startAnimation. This method provides allows fine-grained 10129 * control over the start time and invalidation, but you 10130 * must make sure that 1) the animation has a start time set, and 10131 * 2) the view will be invalidated when the animation is supposed to 10132 * start. 10133 * 10134 * @param animation The next animation, or null. 10135 */ 10136 public void setAnimation(Animation animation) { 10137 mCurrentAnimation = animation; 10138 if (animation != null) { 10139 animation.reset(); 10140 } 10141 } 10142 10143 /** 10144 * Invoked by a parent ViewGroup to notify the start of the animation 10145 * currently associated with this view. If you override this method, 10146 * always call super.onAnimationStart(); 10147 * 10148 * @see #setAnimation(android.view.animation.Animation) 10149 * @see #getAnimation() 10150 */ 10151 protected void onAnimationStart() { 10152 mPrivateFlags |= ANIMATION_STARTED; 10153 } 10154 10155 /** 10156 * Invoked by a parent ViewGroup to notify the end of the animation 10157 * currently associated with this view. If you override this method, 10158 * always call super.onAnimationEnd(); 10159 * 10160 * @see #setAnimation(android.view.animation.Animation) 10161 * @see #getAnimation() 10162 */ 10163 protected void onAnimationEnd() { 10164 mPrivateFlags &= ~ANIMATION_STARTED; 10165 } 10166 10167 /** 10168 * Invoked if there is a Transform that involves alpha. Subclass that can 10169 * draw themselves with the specified alpha should return true, and then 10170 * respect that alpha when their onDraw() is called. If this returns false 10171 * then the view may be redirected to draw into an offscreen buffer to 10172 * fulfill the request, which will look fine, but may be slower than if the 10173 * subclass handles it internally. The default implementation returns false. 10174 * 10175 * @param alpha The alpha (0..255) to apply to the view's drawing 10176 * @return true if the view can draw with the specified alpha. 10177 */ 10178 protected boolean onSetAlpha(int alpha) { 10179 return false; 10180 } 10181 10182 /** 10183 * This is used by the RootView to perform an optimization when 10184 * the view hierarchy contains one or several SurfaceView. 10185 * SurfaceView is always considered transparent, but its children are not, 10186 * therefore all View objects remove themselves from the global transparent 10187 * region (passed as a parameter to this function). 10188 * 10189 * @param region The transparent region for this ViewRoot (window). 10190 * 10191 * @return Returns true if the effective visibility of the view at this 10192 * point is opaque, regardless of the transparent region; returns false 10193 * if it is possible for underlying windows to be seen behind the view. 10194 * 10195 * {@hide} 10196 */ 10197 public boolean gatherTransparentRegion(Region region) { 10198 final AttachInfo attachInfo = mAttachInfo; 10199 if (region != null && attachInfo != null) { 10200 final int pflags = mPrivateFlags; 10201 if ((pflags & SKIP_DRAW) == 0) { 10202 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 10203 // remove it from the transparent region. 10204 final int[] location = attachInfo.mTransparentLocation; 10205 getLocationInWindow(location); 10206 region.op(location[0], location[1], location[0] + mRight - mLeft, 10207 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 10208 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 10209 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 10210 // exists, so we remove the background drawable's non-transparent 10211 // parts from this transparent region. 10212 applyDrawableToTransparentRegion(mBGDrawable, region); 10213 } 10214 } 10215 return true; 10216 } 10217 10218 /** 10219 * Play a sound effect for this view. 10220 * 10221 * <p>The framework will play sound effects for some built in actions, such as 10222 * clicking, but you may wish to play these effects in your widget, 10223 * for instance, for internal navigation. 10224 * 10225 * <p>The sound effect will only be played if sound effects are enabled by the user, and 10226 * {@link #isSoundEffectsEnabled()} is true. 10227 * 10228 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 10229 */ 10230 public void playSoundEffect(int soundConstant) { 10231 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 10232 return; 10233 } 10234 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 10235 } 10236 10237 /** 10238 * BZZZTT!!1! 10239 * 10240 * <p>Provide haptic feedback to the user for this view. 10241 * 10242 * <p>The framework will provide haptic feedback for some built in actions, 10243 * such as long presses, but you may wish to provide feedback for your 10244 * own widget. 10245 * 10246 * <p>The feedback will only be performed if 10247 * {@link #isHapticFeedbackEnabled()} is true. 10248 * 10249 * @param feedbackConstant One of the constants defined in 10250 * {@link HapticFeedbackConstants} 10251 */ 10252 public boolean performHapticFeedback(int feedbackConstant) { 10253 return performHapticFeedback(feedbackConstant, 0); 10254 } 10255 10256 /** 10257 * BZZZTT!!1! 10258 * 10259 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 10260 * 10261 * @param feedbackConstant One of the constants defined in 10262 * {@link HapticFeedbackConstants} 10263 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 10264 */ 10265 public boolean performHapticFeedback(int feedbackConstant, int flags) { 10266 if (mAttachInfo == null) { 10267 return false; 10268 } 10269 //noinspection SimplifiableIfStatement 10270 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 10271 && !isHapticFeedbackEnabled()) { 10272 return false; 10273 } 10274 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 10275 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 10276 } 10277 10278 /** 10279 * !!! TODO: real docs 10280 * 10281 * The base class implementation makes the thumbnail the same size and appearance 10282 * as the view itself, and positions it with its center at the touch point. 10283 */ 10284 public static class DragThumbnailBuilder { 10285 private final WeakReference<View> mView; 10286 10287 /** 10288 * Construct a thumbnail builder object for use with the given view. 10289 * @param view 10290 */ 10291 public DragThumbnailBuilder(View view) { 10292 mView = new WeakReference<View>(view); 10293 } 10294 10295 final public View getView() { 10296 return mView.get(); 10297 } 10298 10299 /** 10300 * Provide the draggable-thumbnail metrics for the operation: the dimensions of 10301 * the thumbnail image itself, and the point within that thumbnail that should 10302 * be centered under the touch location while dragging. 10303 * <p> 10304 * The default implementation sets the dimensions of the thumbnail to be the 10305 * same as the dimensions of the View itself and centers the thumbnail under 10306 * the touch point. 10307 * 10308 * @param thumbnailSize The application should set the {@code x} member of this 10309 * parameter to the desired thumbnail width, and the {@code y} member to 10310 * the desired height. 10311 * @param thumbnailTouchPoint The application should set this point to be the 10312 * location within the thumbnail that should track directly underneath 10313 * the touch point on the screen during a drag. 10314 */ 10315 public void onProvideThumbnailMetrics(Point thumbnailSize, Point thumbnailTouchPoint) { 10316 final View view = mView.get(); 10317 if (view != null) { 10318 thumbnailSize.set(view.getWidth(), view.getHeight()); 10319 thumbnailTouchPoint.set(thumbnailSize.x / 2, thumbnailSize.y / 2); 10320 } else { 10321 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 10322 } 10323 } 10324 10325 /** 10326 * Draw the thumbnail image for the upcoming drag. The thumbnail canvas was 10327 * created with the dimensions supplied by the onProvideThumbnailMetrics() 10328 * callback. 10329 * 10330 * @param canvas 10331 */ 10332 public void onDrawThumbnail(Canvas canvas) { 10333 final View view = mView.get(); 10334 if (view != null) { 10335 view.draw(canvas); 10336 } else { 10337 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag thumb but no view"); 10338 } 10339 } 10340 } 10341 10342 /** 10343 * Drag and drop. App calls startDrag(), then callbacks to the thumbnail builder's 10344 * onProvideThumbnailMetrics() and onDrawThumbnail() methods happen, then the drag 10345 * operation is handed over to the OS. 10346 * !!! TODO: real docs 10347 * 10348 * @param data !!! TODO 10349 * @param thumbBuilder !!! TODO 10350 * @param myWindowOnly When {@code true}, indicates that the drag operation should be 10351 * restricted to the calling application. In this case only the calling application 10352 * will see any DragEvents related to this drag operation. 10353 * @param myLocalState An arbitrary object that will be passed as part of every DragEvent 10354 * delivered to the calling application during the course of the current drag operation. 10355 * This object is private to the application that called startDrag(), and is not 10356 * visible to other applications. It provides a lightweight way for the application to 10357 * propagate information from the initiator to the recipient of a drag within its own 10358 * application; for example, to help disambiguate between 'copy' and 'move' semantics. 10359 * @return {@code true} if the drag operation was initiated successfully; {@code false} if 10360 * an error prevented the drag from taking place. 10361 */ 10362 public final boolean startDrag(ClipData data, DragThumbnailBuilder thumbBuilder, 10363 boolean myWindowOnly, Object myLocalState) { 10364 if (ViewDebug.DEBUG_DRAG) { 10365 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " local=" + myWindowOnly); 10366 } 10367 boolean okay = false; 10368 10369 Point thumbSize = new Point(); 10370 Point thumbTouchPoint = new Point(); 10371 thumbBuilder.onProvideThumbnailMetrics(thumbSize, thumbTouchPoint); 10372 10373 if ((thumbSize.x < 0) || (thumbSize.y < 0) || 10374 (thumbTouchPoint.x < 0) || (thumbTouchPoint.y < 0)) { 10375 throw new IllegalStateException("Drag thumb dimensions must not be negative"); 10376 } 10377 10378 if (ViewDebug.DEBUG_DRAG) { 10379 Log.d(VIEW_LOG_TAG, "drag thumb: width=" + thumbSize.x + " height=" + thumbSize.y 10380 + " thumbX=" + thumbTouchPoint.x + " thumbY=" + thumbTouchPoint.y); 10381 } 10382 Surface surface = new Surface(); 10383 try { 10384 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 10385 myWindowOnly, thumbSize.x, thumbSize.y, surface); 10386 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 10387 + " surface=" + surface); 10388 if (token != null) { 10389 Canvas canvas = surface.lockCanvas(null); 10390 try { 10391 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 10392 thumbBuilder.onDrawThumbnail(canvas); 10393 } finally { 10394 surface.unlockCanvasAndPost(canvas); 10395 } 10396 10397 final ViewRoot root = getViewRoot(); 10398 10399 // Cache the local state object for delivery with DragEvents 10400 root.setLocalDragState(myLocalState); 10401 10402 // repurpose 'thumbSize' for the last touch point 10403 root.getLastTouchPoint(thumbSize); 10404 10405 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 10406 (float) thumbSize.x, (float) thumbSize.y, 10407 (float) thumbTouchPoint.x, (float) thumbTouchPoint.y, data); 10408 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 10409 } 10410 } catch (Exception e) { 10411 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 10412 surface.destroy(); 10413 } 10414 10415 return okay; 10416 } 10417 10418 /** 10419 * Drag-and-drop event dispatch. The event.getAction() verb is one of the DragEvent 10420 * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT. 10421 * 10422 * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content 10423 * being dragged. onDragEvent() should return 'true' if the view can handle 10424 * a drop of that content. A view that returns 'false' here will receive no 10425 * further calls to onDragEvent() about the drag/drop operation. 10426 * 10427 * For DRAG_ENTERED, event.getClipDescription() describes the content being 10428 * dragged. This will be the same content description passed in the 10429 * DRAG_STARTED_EVENT invocation. 10430 * 10431 * For DRAG_EXITED, event.getClipDescription() describes the content being 10432 * dragged. This will be the same content description passed in the 10433 * DRAG_STARTED_EVENT invocation. The view should return to its approriate 10434 * drag-acceptance visual state. 10435 * 10436 * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View 10437 * coordinates of the current drag point. The view must return 'true' if it 10438 * can accept a drop of the current drag content, false otherwise. 10439 * 10440 * For DROP_EVENT, event.getX() and event.getY() give the location of the drop 10441 * within the view; also, event.getClipData() returns the full data payload 10442 * being dropped. The view should return 'true' if it consumed the dropped 10443 * content, 'false' if it did not. 10444 * 10445 * For DRAG_ENDED_EVENT, the 'event' argument may be null. The view should return 10446 * to its normal visual state. 10447 */ 10448 public boolean onDragEvent(DragEvent event) { 10449 return false; 10450 } 10451 10452 /** 10453 * Views typically don't need to override dispatchDragEvent(); it just calls 10454 * onDragEvent(event) and passes the result up appropriately. 10455 */ 10456 public boolean dispatchDragEvent(DragEvent event) { 10457 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 10458 && mOnDragListener.onDrag(this, event)) { 10459 return true; 10460 } 10461 return onDragEvent(event); 10462 } 10463 10464 /** 10465 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 10466 * it is ever exposed at all. 10467 * @hide 10468 */ 10469 public void onCloseSystemDialogs(String reason) { 10470 } 10471 10472 /** 10473 * Given a Drawable whose bounds have been set to draw into this view, 10474 * update a Region being computed for {@link #gatherTransparentRegion} so 10475 * that any non-transparent parts of the Drawable are removed from the 10476 * given transparent region. 10477 * 10478 * @param dr The Drawable whose transparency is to be applied to the region. 10479 * @param region A Region holding the current transparency information, 10480 * where any parts of the region that are set are considered to be 10481 * transparent. On return, this region will be modified to have the 10482 * transparency information reduced by the corresponding parts of the 10483 * Drawable that are not transparent. 10484 * {@hide} 10485 */ 10486 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 10487 if (DBG) { 10488 Log.i("View", "Getting transparent region for: " + this); 10489 } 10490 final Region r = dr.getTransparentRegion(); 10491 final Rect db = dr.getBounds(); 10492 final AttachInfo attachInfo = mAttachInfo; 10493 if (r != null && attachInfo != null) { 10494 final int w = getRight()-getLeft(); 10495 final int h = getBottom()-getTop(); 10496 if (db.left > 0) { 10497 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 10498 r.op(0, 0, db.left, h, Region.Op.UNION); 10499 } 10500 if (db.right < w) { 10501 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 10502 r.op(db.right, 0, w, h, Region.Op.UNION); 10503 } 10504 if (db.top > 0) { 10505 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 10506 r.op(0, 0, w, db.top, Region.Op.UNION); 10507 } 10508 if (db.bottom < h) { 10509 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 10510 r.op(0, db.bottom, w, h, Region.Op.UNION); 10511 } 10512 final int[] location = attachInfo.mTransparentLocation; 10513 getLocationInWindow(location); 10514 r.translate(location[0], location[1]); 10515 region.op(r, Region.Op.INTERSECT); 10516 } else { 10517 region.op(db, Region.Op.DIFFERENCE); 10518 } 10519 } 10520 10521 private void postCheckForLongClick(int delayOffset) { 10522 mHasPerformedLongPress = false; 10523 10524 if (mPendingCheckForLongPress == null) { 10525 mPendingCheckForLongPress = new CheckForLongPress(); 10526 } 10527 mPendingCheckForLongPress.rememberWindowAttachCount(); 10528 postDelayed(mPendingCheckForLongPress, 10529 ViewConfiguration.getLongPressTimeout() - delayOffset); 10530 } 10531 10532 /** 10533 * Inflate a view from an XML resource. This convenience method wraps the {@link 10534 * LayoutInflater} class, which provides a full range of options for view inflation. 10535 * 10536 * @param context The Context object for your activity or application. 10537 * @param resource The resource ID to inflate 10538 * @param root A view group that will be the parent. Used to properly inflate the 10539 * layout_* parameters. 10540 * @see LayoutInflater 10541 */ 10542 public static View inflate(Context context, int resource, ViewGroup root) { 10543 LayoutInflater factory = LayoutInflater.from(context); 10544 return factory.inflate(resource, root); 10545 } 10546 10547 /** 10548 * Scroll the view with standard behavior for scrolling beyond the normal 10549 * content boundaries. Views that call this method should override 10550 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 10551 * results of an over-scroll operation. 10552 * 10553 * Views can use this method to handle any touch or fling-based scrolling. 10554 * 10555 * @param deltaX Change in X in pixels 10556 * @param deltaY Change in Y in pixels 10557 * @param scrollX Current X scroll value in pixels before applying deltaX 10558 * @param scrollY Current Y scroll value in pixels before applying deltaY 10559 * @param scrollRangeX Maximum content scroll range along the X axis 10560 * @param scrollRangeY Maximum content scroll range along the Y axis 10561 * @param maxOverScrollX Number of pixels to overscroll by in either direction 10562 * along the X axis. 10563 * @param maxOverScrollY Number of pixels to overscroll by in either direction 10564 * along the Y axis. 10565 * @param isTouchEvent true if this scroll operation is the result of a touch event. 10566 * @return true if scrolling was clamped to an over-scroll boundary along either 10567 * axis, false otherwise. 10568 */ 10569 protected boolean overScrollBy(int deltaX, int deltaY, 10570 int scrollX, int scrollY, 10571 int scrollRangeX, int scrollRangeY, 10572 int maxOverScrollX, int maxOverScrollY, 10573 boolean isTouchEvent) { 10574 final int overScrollMode = mOverScrollMode; 10575 final boolean canScrollHorizontal = 10576 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 10577 final boolean canScrollVertical = 10578 computeVerticalScrollRange() > computeVerticalScrollExtent(); 10579 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 10580 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 10581 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 10582 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 10583 10584 int newScrollX = scrollX + deltaX; 10585 if (!overScrollHorizontal) { 10586 maxOverScrollX = 0; 10587 } 10588 10589 int newScrollY = scrollY + deltaY; 10590 if (!overScrollVertical) { 10591 maxOverScrollY = 0; 10592 } 10593 10594 // Clamp values if at the limits and record 10595 final int left = -maxOverScrollX; 10596 final int right = maxOverScrollX + scrollRangeX; 10597 final int top = -maxOverScrollY; 10598 final int bottom = maxOverScrollY + scrollRangeY; 10599 10600 boolean clampedX = false; 10601 if (newScrollX > right) { 10602 newScrollX = right; 10603 clampedX = true; 10604 } else if (newScrollX < left) { 10605 newScrollX = left; 10606 clampedX = true; 10607 } 10608 10609 boolean clampedY = false; 10610 if (newScrollY > bottom) { 10611 newScrollY = bottom; 10612 clampedY = true; 10613 } else if (newScrollY < top) { 10614 newScrollY = top; 10615 clampedY = true; 10616 } 10617 10618 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 10619 10620 return clampedX || clampedY; 10621 } 10622 10623 /** 10624 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 10625 * respond to the results of an over-scroll operation. 10626 * 10627 * @param scrollX New X scroll value in pixels 10628 * @param scrollY New Y scroll value in pixels 10629 * @param clampedX True if scrollX was clamped to an over-scroll boundary 10630 * @param clampedY True if scrollY was clamped to an over-scroll boundary 10631 */ 10632 protected void onOverScrolled(int scrollX, int scrollY, 10633 boolean clampedX, boolean clampedY) { 10634 // Intentionally empty. 10635 } 10636 10637 /** 10638 * Returns the over-scroll mode for this view. The result will be 10639 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 10640 * (allow over-scrolling only if the view content is larger than the container), 10641 * or {@link #OVER_SCROLL_NEVER}. 10642 * 10643 * @return This view's over-scroll mode. 10644 */ 10645 public int getOverScrollMode() { 10646 return mOverScrollMode; 10647 } 10648 10649 /** 10650 * Set the over-scroll mode for this view. Valid over-scroll modes are 10651 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 10652 * (allow over-scrolling only if the view content is larger than the container), 10653 * or {@link #OVER_SCROLL_NEVER}. 10654 * 10655 * Setting the over-scroll mode of a view will have an effect only if the 10656 * view is capable of scrolling. 10657 * 10658 * @param overScrollMode The new over-scroll mode for this view. 10659 */ 10660 public void setOverScrollMode(int overScrollMode) { 10661 if (overScrollMode != OVER_SCROLL_ALWAYS && 10662 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 10663 overScrollMode != OVER_SCROLL_NEVER) { 10664 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 10665 } 10666 mOverScrollMode = overScrollMode; 10667 } 10668 10669 /** 10670 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 10671 * Each MeasureSpec represents a requirement for either the width or the height. 10672 * A MeasureSpec is comprised of a size and a mode. There are three possible 10673 * modes: 10674 * <dl> 10675 * <dt>UNSPECIFIED</dt> 10676 * <dd> 10677 * The parent has not imposed any constraint on the child. It can be whatever size 10678 * it wants. 10679 * </dd> 10680 * 10681 * <dt>EXACTLY</dt> 10682 * <dd> 10683 * The parent has determined an exact size for the child. The child is going to be 10684 * given those bounds regardless of how big it wants to be. 10685 * </dd> 10686 * 10687 * <dt>AT_MOST</dt> 10688 * <dd> 10689 * The child can be as large as it wants up to the specified size. 10690 * </dd> 10691 * </dl> 10692 * 10693 * MeasureSpecs are implemented as ints to reduce object allocation. This class 10694 * is provided to pack and unpack the <size, mode> tuple into the int. 10695 */ 10696 public static class MeasureSpec { 10697 private static final int MODE_SHIFT = 30; 10698 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 10699 10700 /** 10701 * Measure specification mode: The parent has not imposed any constraint 10702 * on the child. It can be whatever size it wants. 10703 */ 10704 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 10705 10706 /** 10707 * Measure specification mode: The parent has determined an exact size 10708 * for the child. The child is going to be given those bounds regardless 10709 * of how big it wants to be. 10710 */ 10711 public static final int EXACTLY = 1 << MODE_SHIFT; 10712 10713 /** 10714 * Measure specification mode: The child can be as large as it wants up 10715 * to the specified size. 10716 */ 10717 public static final int AT_MOST = 2 << MODE_SHIFT; 10718 10719 /** 10720 * Creates a measure specification based on the supplied size and mode. 10721 * 10722 * The mode must always be one of the following: 10723 * <ul> 10724 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 10725 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 10726 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 10727 * </ul> 10728 * 10729 * @param size the size of the measure specification 10730 * @param mode the mode of the measure specification 10731 * @return the measure specification based on size and mode 10732 */ 10733 public static int makeMeasureSpec(int size, int mode) { 10734 return size + mode; 10735 } 10736 10737 /** 10738 * Extracts the mode from the supplied measure specification. 10739 * 10740 * @param measureSpec the measure specification to extract the mode from 10741 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 10742 * {@link android.view.View.MeasureSpec#AT_MOST} or 10743 * {@link android.view.View.MeasureSpec#EXACTLY} 10744 */ 10745 public static int getMode(int measureSpec) { 10746 return (measureSpec & MODE_MASK); 10747 } 10748 10749 /** 10750 * Extracts the size from the supplied measure specification. 10751 * 10752 * @param measureSpec the measure specification to extract the size from 10753 * @return the size in pixels defined in the supplied measure specification 10754 */ 10755 public static int getSize(int measureSpec) { 10756 return (measureSpec & ~MODE_MASK); 10757 } 10758 10759 /** 10760 * Returns a String representation of the specified measure 10761 * specification. 10762 * 10763 * @param measureSpec the measure specification to convert to a String 10764 * @return a String with the following format: "MeasureSpec: MODE SIZE" 10765 */ 10766 public static String toString(int measureSpec) { 10767 int mode = getMode(measureSpec); 10768 int size = getSize(measureSpec); 10769 10770 StringBuilder sb = new StringBuilder("MeasureSpec: "); 10771 10772 if (mode == UNSPECIFIED) 10773 sb.append("UNSPECIFIED "); 10774 else if (mode == EXACTLY) 10775 sb.append("EXACTLY "); 10776 else if (mode == AT_MOST) 10777 sb.append("AT_MOST "); 10778 else 10779 sb.append(mode).append(" "); 10780 10781 sb.append(size); 10782 return sb.toString(); 10783 } 10784 } 10785 10786 class CheckForLongPress implements Runnable { 10787 10788 private int mOriginalWindowAttachCount; 10789 10790 public void run() { 10791 if (isPressed() && (mParent != null) 10792 && mOriginalWindowAttachCount == mWindowAttachCount) { 10793 if (performLongClick()) { 10794 mHasPerformedLongPress = true; 10795 } 10796 } 10797 } 10798 10799 public void rememberWindowAttachCount() { 10800 mOriginalWindowAttachCount = mWindowAttachCount; 10801 } 10802 } 10803 10804 private final class CheckForTap implements Runnable { 10805 public void run() { 10806 mPrivateFlags &= ~PREPRESSED; 10807 mPrivateFlags |= PRESSED; 10808 refreshDrawableState(); 10809 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 10810 postCheckForLongClick(ViewConfiguration.getTapTimeout()); 10811 } 10812 } 10813 } 10814 10815 private final class PerformClick implements Runnable { 10816 public void run() { 10817 performClick(); 10818 } 10819 } 10820 10821 /** 10822 * Interface definition for a callback to be invoked when a key event is 10823 * dispatched to this view. The callback will be invoked before the key 10824 * event is given to the view. 10825 */ 10826 public interface OnKeyListener { 10827 /** 10828 * Called when a key is dispatched to a view. This allows listeners to 10829 * get a chance to respond before the target view. 10830 * 10831 * @param v The view the key has been dispatched to. 10832 * @param keyCode The code for the physical key that was pressed 10833 * @param event The KeyEvent object containing full information about 10834 * the event. 10835 * @return True if the listener has consumed the event, false otherwise. 10836 */ 10837 boolean onKey(View v, int keyCode, KeyEvent event); 10838 } 10839 10840 /** 10841 * Interface definition for a callback to be invoked when a touch event is 10842 * dispatched to this view. The callback will be invoked before the touch 10843 * event is given to the view. 10844 */ 10845 public interface OnTouchListener { 10846 /** 10847 * Called when a touch event is dispatched to a view. This allows listeners to 10848 * get a chance to respond before the target view. 10849 * 10850 * @param v The view the touch event has been dispatched to. 10851 * @param event The MotionEvent object containing full information about 10852 * the event. 10853 * @return True if the listener has consumed the event, false otherwise. 10854 */ 10855 boolean onTouch(View v, MotionEvent event); 10856 } 10857 10858 /** 10859 * Interface definition for a callback to be invoked when a view has been clicked and held. 10860 */ 10861 public interface OnLongClickListener { 10862 /** 10863 * Called when a view has been clicked and held. 10864 * 10865 * @param v The view that was clicked and held. 10866 * 10867 * return True if the callback consumed the long click, false otherwise 10868 */ 10869 boolean onLongClick(View v); 10870 } 10871 10872 /** 10873 * Interface definition for a callback to be invoked when a drag is being dispatched 10874 * to this view. The callback will be invoked before the hosting view's own 10875 * onDrag(event) method. If the listener wants to fall back to the hosting view's 10876 * onDrag(event) behavior, it should return 'false' from this callback. 10877 */ 10878 public interface OnDragListener { 10879 /** 10880 * Called when a drag event is dispatched to a view. This allows listeners 10881 * to get a chance to override base View behavior. 10882 * 10883 * @param v The view the drag has been dispatched to. 10884 * @param event The DragEvent object containing full information 10885 * about the event. 10886 * @return true if the listener consumed the DragEvent, false in order to fall 10887 * back to the view's default handling. 10888 */ 10889 boolean onDrag(View v, DragEvent event); 10890 } 10891 10892 /** 10893 * Interface definition for a callback to be invoked when the focus state of 10894 * a view changed. 10895 */ 10896 public interface OnFocusChangeListener { 10897 /** 10898 * Called when the focus state of a view has changed. 10899 * 10900 * @param v The view whose state has changed. 10901 * @param hasFocus The new focus state of v. 10902 */ 10903 void onFocusChange(View v, boolean hasFocus); 10904 } 10905 10906 /** 10907 * Interface definition for a callback to be invoked when a view is clicked. 10908 */ 10909 public interface OnClickListener { 10910 /** 10911 * Called when a view has been clicked. 10912 * 10913 * @param v The view that was clicked. 10914 */ 10915 void onClick(View v); 10916 } 10917 10918 /** 10919 * Interface definition for a callback to be invoked when the context menu 10920 * for this view is being built. 10921 */ 10922 public interface OnCreateContextMenuListener { 10923 /** 10924 * Called when the context menu for this view is being built. It is not 10925 * safe to hold onto the menu after this method returns. 10926 * 10927 * @param menu The context menu that is being built 10928 * @param v The view for which the context menu is being built 10929 * @param menuInfo Extra information about the item for which the 10930 * context menu should be shown. This information will vary 10931 * depending on the class of v. 10932 */ 10933 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 10934 } 10935 10936 private final class UnsetPressedState implements Runnable { 10937 public void run() { 10938 setPressed(false); 10939 } 10940 } 10941 10942 /** 10943 * Base class for derived classes that want to save and restore their own 10944 * state in {@link android.view.View#onSaveInstanceState()}. 10945 */ 10946 public static class BaseSavedState extends AbsSavedState { 10947 /** 10948 * Constructor used when reading from a parcel. Reads the state of the superclass. 10949 * 10950 * @param source 10951 */ 10952 public BaseSavedState(Parcel source) { 10953 super(source); 10954 } 10955 10956 /** 10957 * Constructor called by derived classes when creating their SavedState objects 10958 * 10959 * @param superState The state of the superclass of this view 10960 */ 10961 public BaseSavedState(Parcelable superState) { 10962 super(superState); 10963 } 10964 10965 public static final Parcelable.Creator<BaseSavedState> CREATOR = 10966 new Parcelable.Creator<BaseSavedState>() { 10967 public BaseSavedState createFromParcel(Parcel in) { 10968 return new BaseSavedState(in); 10969 } 10970 10971 public BaseSavedState[] newArray(int size) { 10972 return new BaseSavedState[size]; 10973 } 10974 }; 10975 } 10976 10977 /** 10978 * A set of information given to a view when it is attached to its parent 10979 * window. 10980 */ 10981 static class AttachInfo { 10982 interface Callbacks { 10983 void playSoundEffect(int effectId); 10984 boolean performHapticFeedback(int effectId, boolean always); 10985 } 10986 10987 /** 10988 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 10989 * to a Handler. This class contains the target (View) to invalidate and 10990 * the coordinates of the dirty rectangle. 10991 * 10992 * For performance purposes, this class also implements a pool of up to 10993 * POOL_LIMIT objects that get reused. This reduces memory allocations 10994 * whenever possible. 10995 */ 10996 static class InvalidateInfo implements Poolable<InvalidateInfo> { 10997 private static final int POOL_LIMIT = 10; 10998 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 10999 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 11000 public InvalidateInfo newInstance() { 11001 return new InvalidateInfo(); 11002 } 11003 11004 public void onAcquired(InvalidateInfo element) { 11005 } 11006 11007 public void onReleased(InvalidateInfo element) { 11008 } 11009 }, POOL_LIMIT) 11010 ); 11011 11012 private InvalidateInfo mNext; 11013 11014 View target; 11015 11016 int left; 11017 int top; 11018 int right; 11019 int bottom; 11020 11021 public void setNextPoolable(InvalidateInfo element) { 11022 mNext = element; 11023 } 11024 11025 public InvalidateInfo getNextPoolable() { 11026 return mNext; 11027 } 11028 11029 static InvalidateInfo acquire() { 11030 return sPool.acquire(); 11031 } 11032 11033 void release() { 11034 sPool.release(this); 11035 } 11036 } 11037 11038 final IWindowSession mSession; 11039 11040 final IWindow mWindow; 11041 11042 final IBinder mWindowToken; 11043 11044 final Callbacks mRootCallbacks; 11045 11046 /** 11047 * The top view of the hierarchy. 11048 */ 11049 View mRootView; 11050 11051 IBinder mPanelParentWindowToken; 11052 Surface mSurface; 11053 11054 boolean mHardwareAccelerated; 11055 boolean mHardwareAccelerationRequested; 11056 HardwareRenderer mHardwareRenderer; 11057 11058 /** 11059 * Scale factor used by the compatibility mode 11060 */ 11061 float mApplicationScale; 11062 11063 /** 11064 * Indicates whether the application is in compatibility mode 11065 */ 11066 boolean mScalingRequired; 11067 11068 /** 11069 * Left position of this view's window 11070 */ 11071 int mWindowLeft; 11072 11073 /** 11074 * Top position of this view's window 11075 */ 11076 int mWindowTop; 11077 11078 /** 11079 * Indicates whether views need to use 32-bit drawing caches 11080 */ 11081 boolean mUse32BitDrawingCache; 11082 11083 /** 11084 * For windows that are full-screen but using insets to layout inside 11085 * of the screen decorations, these are the current insets for the 11086 * content of the window. 11087 */ 11088 final Rect mContentInsets = new Rect(); 11089 11090 /** 11091 * For windows that are full-screen but using insets to layout inside 11092 * of the screen decorations, these are the current insets for the 11093 * actual visible parts of the window. 11094 */ 11095 final Rect mVisibleInsets = new Rect(); 11096 11097 /** 11098 * The internal insets given by this window. This value is 11099 * supplied by the client (through 11100 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 11101 * be given to the window manager when changed to be used in laying 11102 * out windows behind it. 11103 */ 11104 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 11105 = new ViewTreeObserver.InternalInsetsInfo(); 11106 11107 /** 11108 * All views in the window's hierarchy that serve as scroll containers, 11109 * used to determine if the window can be resized or must be panned 11110 * to adjust for a soft input area. 11111 */ 11112 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 11113 11114 final KeyEvent.DispatcherState mKeyDispatchState 11115 = new KeyEvent.DispatcherState(); 11116 11117 /** 11118 * Indicates whether the view's window currently has the focus. 11119 */ 11120 boolean mHasWindowFocus; 11121 11122 /** 11123 * The current visibility of the window. 11124 */ 11125 int mWindowVisibility; 11126 11127 /** 11128 * Indicates the time at which drawing started to occur. 11129 */ 11130 long mDrawingTime; 11131 11132 /** 11133 * Indicates whether or not ignoring the DIRTY_MASK flags. 11134 */ 11135 boolean mIgnoreDirtyState; 11136 11137 /** 11138 * Indicates whether the view's window is currently in touch mode. 11139 */ 11140 boolean mInTouchMode; 11141 11142 /** 11143 * Indicates that ViewRoot should trigger a global layout change 11144 * the next time it performs a traversal 11145 */ 11146 boolean mRecomputeGlobalAttributes; 11147 11148 /** 11149 * Set during a traveral if any views want to keep the screen on. 11150 */ 11151 boolean mKeepScreenOn; 11152 11153 /** 11154 * Set if the visibility of any views has changed. 11155 */ 11156 boolean mViewVisibilityChanged; 11157 11158 /** 11159 * Set to true if a view has been scrolled. 11160 */ 11161 boolean mViewScrollChanged; 11162 11163 /** 11164 * Global to the view hierarchy used as a temporary for dealing with 11165 * x/y points in the transparent region computations. 11166 */ 11167 final int[] mTransparentLocation = new int[2]; 11168 11169 /** 11170 * Global to the view hierarchy used as a temporary for dealing with 11171 * x/y points in the ViewGroup.invalidateChild implementation. 11172 */ 11173 final int[] mInvalidateChildLocation = new int[2]; 11174 11175 11176 /** 11177 * Global to the view hierarchy used as a temporary for dealing with 11178 * x/y location when view is transformed. 11179 */ 11180 final float[] mTmpTransformLocation = new float[2]; 11181 11182 /** 11183 * The view tree observer used to dispatch global events like 11184 * layout, pre-draw, touch mode change, etc. 11185 */ 11186 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 11187 11188 /** 11189 * A Canvas used by the view hierarchy to perform bitmap caching. 11190 */ 11191 Canvas mCanvas; 11192 11193 /** 11194 * A Handler supplied by a view's {@link android.view.ViewRoot}. This 11195 * handler can be used to pump events in the UI events queue. 11196 */ 11197 final Handler mHandler; 11198 11199 /** 11200 * Identifier for messages requesting the view to be invalidated. 11201 * Such messages should be sent to {@link #mHandler}. 11202 */ 11203 static final int INVALIDATE_MSG = 0x1; 11204 11205 /** 11206 * Identifier for messages requesting the view to invalidate a region. 11207 * Such messages should be sent to {@link #mHandler}. 11208 */ 11209 static final int INVALIDATE_RECT_MSG = 0x2; 11210 11211 /** 11212 * Temporary for use in computing invalidate rectangles while 11213 * calling up the hierarchy. 11214 */ 11215 final Rect mTmpInvalRect = new Rect(); 11216 11217 /** 11218 * Temporary for use in computing hit areas with transformed views 11219 */ 11220 final RectF mTmpTransformRect = new RectF(); 11221 11222 /** 11223 * Temporary list for use in collecting focusable descendents of a view. 11224 */ 11225 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 11226 11227 /** 11228 * Creates a new set of attachment information with the specified 11229 * events handler and thread. 11230 * 11231 * @param handler the events handler the view must use 11232 */ 11233 AttachInfo(IWindowSession session, IWindow window, 11234 Handler handler, Callbacks effectPlayer) { 11235 mSession = session; 11236 mWindow = window; 11237 mWindowToken = window.asBinder(); 11238 mHandler = handler; 11239 mRootCallbacks = effectPlayer; 11240 } 11241 } 11242 11243 /** 11244 * <p>ScrollabilityCache holds various fields used by a View when scrolling 11245 * is supported. This avoids keeping too many unused fields in most 11246 * instances of View.</p> 11247 */ 11248 private static class ScrollabilityCache implements Runnable { 11249 11250 /** 11251 * Scrollbars are not visible 11252 */ 11253 public static final int OFF = 0; 11254 11255 /** 11256 * Scrollbars are visible 11257 */ 11258 public static final int ON = 1; 11259 11260 /** 11261 * Scrollbars are fading away 11262 */ 11263 public static final int FADING = 2; 11264 11265 public boolean fadeScrollBars; 11266 11267 public int fadingEdgeLength; 11268 public int scrollBarDefaultDelayBeforeFade; 11269 public int scrollBarFadeDuration; 11270 11271 public int scrollBarSize; 11272 public ScrollBarDrawable scrollBar; 11273 public float[] interpolatorValues; 11274 public View host; 11275 11276 public final Paint paint; 11277 public final Matrix matrix; 11278 public Shader shader; 11279 11280 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 11281 11282 private final float[] mOpaque = { 255.0f }; 11283 private final float[] mTransparent = { 0.0f }; 11284 11285 /** 11286 * When fading should start. This time moves into the future every time 11287 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 11288 */ 11289 public long fadeStartTime; 11290 11291 11292 /** 11293 * The current state of the scrollbars: ON, OFF, or FADING 11294 */ 11295 public int state = OFF; 11296 11297 private int mLastColor; 11298 11299 public ScrollabilityCache(ViewConfiguration configuration, View host) { 11300 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 11301 scrollBarSize = configuration.getScaledScrollBarSize(); 11302 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 11303 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 11304 11305 paint = new Paint(); 11306 matrix = new Matrix(); 11307 // use use a height of 1, and then wack the matrix each time we 11308 // actually use it. 11309 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 11310 11311 paint.setShader(shader); 11312 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 11313 this.host = host; 11314 } 11315 11316 public void setFadeColor(int color) { 11317 if (color != 0 && color != mLastColor) { 11318 mLastColor = color; 11319 color |= 0xFF000000; 11320 11321 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 11322 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 11323 11324 paint.setShader(shader); 11325 // Restore the default transfer mode (src_over) 11326 paint.setXfermode(null); 11327 } 11328 } 11329 11330 public void run() { 11331 long now = AnimationUtils.currentAnimationTimeMillis(); 11332 if (now >= fadeStartTime) { 11333 11334 // the animation fades the scrollbars out by changing 11335 // the opacity (alpha) from fully opaque to fully 11336 // transparent 11337 int nextFrame = (int) now; 11338 int framesCount = 0; 11339 11340 Interpolator interpolator = scrollBarInterpolator; 11341 11342 // Start opaque 11343 interpolator.setKeyFrame(framesCount++, nextFrame, mOpaque); 11344 11345 // End transparent 11346 nextFrame += scrollBarFadeDuration; 11347 interpolator.setKeyFrame(framesCount, nextFrame, mTransparent); 11348 11349 state = FADING; 11350 11351 // Kick off the fade animation 11352 host.invalidate(); 11353 } 11354 } 11355 11356 } 11357} 11358