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