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