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