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