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