View.java revision aa126171ae5c4c6449345471500f9bb124558643
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import com.android.internal.R; 20import com.android.internal.util.Predicate; 21import com.android.internal.view.menu.MenuBuilder; 22 23import android.content.ClipData; 24import android.content.Context; 25import android.content.res.Configuration; 26import android.content.res.Resources; 27import android.content.res.TypedArray; 28import android.graphics.Bitmap; 29import android.graphics.Camera; 30import android.graphics.Canvas; 31import android.graphics.Interpolator; 32import android.graphics.LinearGradient; 33import android.graphics.Matrix; 34import android.graphics.Paint; 35import android.graphics.PixelFormat; 36import android.graphics.Point; 37import android.graphics.PorterDuff; 38import android.graphics.PorterDuffXfermode; 39import android.graphics.Rect; 40import android.graphics.RectF; 41import android.graphics.Region; 42import android.graphics.Shader; 43import android.graphics.drawable.ColorDrawable; 44import android.graphics.drawable.Drawable; 45import android.os.Handler; 46import android.os.IBinder; 47import android.os.Message; 48import android.os.Parcel; 49import android.os.Parcelable; 50import android.os.RemoteException; 51import android.os.SystemClock; 52import android.os.SystemProperties; 53import android.text.format.DateUtils; 54import android.util.AttributeSet; 55import android.util.Log; 56import android.util.Pool; 57import android.util.Poolable; 58import android.util.PoolableManager; 59import android.util.Pools; 60import android.util.SparseArray; 61import android.util.TypedValue; 62import android.view.ContextMenu.ContextMenuInfo; 63import android.view.accessibility.AccessibilityEvent; 64import android.view.accessibility.AccessibilityEventSource; 65import android.view.accessibility.AccessibilityManager; 66import android.view.animation.Animation; 67import android.view.animation.AnimationUtils; 68import android.view.inputmethod.EditorInfo; 69import android.view.inputmethod.InputConnection; 70import android.view.inputmethod.InputMethodManager; 71import android.widget.ScrollBarDrawable; 72 73import java.lang.ref.WeakReference; 74import java.lang.reflect.InvocationTargetException; 75import java.lang.reflect.Method; 76import java.util.ArrayList; 77import java.util.Arrays; 78import java.util.WeakHashMap; 79import java.util.concurrent.CopyOnWriteArrayList; 80 81/** 82 * <p> 83 * This class represents the basic building block for user interface components. A View 84 * occupies a rectangular area on the screen and is responsible for drawing and 85 * event handling. View is the base class for <em>widgets</em>, which are 86 * used to create interactive UI components (buttons, text fields, etc.). The 87 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 88 * are invisible containers that hold other Views (or other ViewGroups) and define 89 * their layout properties. 90 * </p> 91 * 92 * <div class="special"> 93 * <p>For an introduction to using this class to develop your 94 * application's user interface, read the Developer Guide documentation on 95 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics 96 * include: 97 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a> 98 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a> 99 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a> 100 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a> 101 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a> 102 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a> 103 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a> 104 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>. 105 * </p> 106 * </div> 107 * 108 * <a name="Using"></a> 109 * <h3>Using Views</h3> 110 * <p> 111 * All of the views in a window are arranged in a single tree. You can add views 112 * either from code or by specifying a tree of views in one or more XML layout 113 * files. There are many specialized subclasses of views that act as controls or 114 * are capable of displaying text, images, or other content. 115 * </p> 116 * <p> 117 * Once you have created a tree of views, there are typically a few types of 118 * common operations you may wish to perform: 119 * <ul> 120 * <li><strong>Set properties:</strong> for example setting the text of a 121 * {@link android.widget.TextView}. The available properties and the methods 122 * that set them will vary among the different subclasses of views. Note that 123 * properties that are known at build time can be set in the XML layout 124 * files.</li> 125 * <li><strong>Set focus:</strong> The framework will handled moving focus in 126 * response to user input. To force focus to a specific view, call 127 * {@link #requestFocus}.</li> 128 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 129 * that will be notified when something interesting happens to the view. For 130 * example, all views will let you set a listener to be notified when the view 131 * gains or loses focus. You can register such a listener using 132 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 133 * Other view subclasses offer more specialized listeners. For example, a Button 134 * exposes a listener to notify clients when the button is clicked.</li> 135 * <li><strong>Set visibility:</strong> You can hide or show views using 136 * {@link #setVisibility(int)}.</li> 137 * </ul> 138 * </p> 139 * <p><em> 140 * Note: The Android framework is responsible for measuring, laying out and 141 * drawing views. You should not call methods that perform these actions on 142 * views yourself unless you are actually implementing a 143 * {@link android.view.ViewGroup}. 144 * </em></p> 145 * 146 * <a name="Lifecycle"></a> 147 * <h3>Implementing a Custom View</h3> 148 * 149 * <p> 150 * To implement a custom view, you will usually begin by providing overrides for 151 * some of the standard methods that the framework calls on all views. You do 152 * not need to override all of these methods. In fact, you can start by just 153 * overriding {@link #onDraw(android.graphics.Canvas)}. 154 * <table border="2" width="85%" align="center" cellpadding="5"> 155 * <thead> 156 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 157 * </thead> 158 * 159 * <tbody> 160 * <tr> 161 * <td rowspan="2">Creation</td> 162 * <td>Constructors</td> 163 * <td>There is a form of the constructor that are called when the view 164 * is created from code and a form that is called when the view is 165 * inflated from a layout file. The second form should parse and apply 166 * any attributes defined in the layout file. 167 * </td> 168 * </tr> 169 * <tr> 170 * <td><code>{@link #onFinishInflate()}</code></td> 171 * <td>Called after a view and all of its children has been inflated 172 * from XML.</td> 173 * </tr> 174 * 175 * <tr> 176 * <td rowspan="3">Layout</td> 177 * <td><code>{@link #onMeasure(int, int)}</code></td> 178 * <td>Called to determine the size requirements for this view and all 179 * of its children. 180 * </td> 181 * </tr> 182 * <tr> 183 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 184 * <td>Called when this view should assign a size and position to all 185 * of its children. 186 * </td> 187 * </tr> 188 * <tr> 189 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 190 * <td>Called when the size of this view has changed. 191 * </td> 192 * </tr> 193 * 194 * <tr> 195 * <td>Drawing</td> 196 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 197 * <td>Called when the view should render its content. 198 * </td> 199 * </tr> 200 * 201 * <tr> 202 * <td rowspan="4">Event processing</td> 203 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 204 * <td>Called when a new key event occurs. 205 * </td> 206 * </tr> 207 * <tr> 208 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 209 * <td>Called when a key up event occurs. 210 * </td> 211 * </tr> 212 * <tr> 213 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 214 * <td>Called when a trackball motion event occurs. 215 * </td> 216 * </tr> 217 * <tr> 218 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 219 * <td>Called when a touch screen motion event occurs. 220 * </td> 221 * </tr> 222 * 223 * <tr> 224 * <td rowspan="2">Focus</td> 225 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 226 * <td>Called when the view gains or loses focus. 227 * </td> 228 * </tr> 229 * 230 * <tr> 231 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 232 * <td>Called when the window containing the view gains or loses focus. 233 * </td> 234 * </tr> 235 * 236 * <tr> 237 * <td rowspan="3">Attaching</td> 238 * <td><code>{@link #onAttachedToWindow()}</code></td> 239 * <td>Called when the view is attached to a window. 240 * </td> 241 * </tr> 242 * 243 * <tr> 244 * <td><code>{@link #onDetachedFromWindow}</code></td> 245 * <td>Called when the view is detached from its window. 246 * </td> 247 * </tr> 248 * 249 * <tr> 250 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 251 * <td>Called when the visibility of the window containing the view 252 * has changed. 253 * </td> 254 * </tr> 255 * </tbody> 256 * 257 * </table> 258 * </p> 259 * 260 * <a name="IDs"></a> 261 * <h3>IDs</h3> 262 * Views may have an integer id associated with them. These ids are typically 263 * assigned in the layout XML files, and are used to find specific views within 264 * the view tree. A common pattern is to: 265 * <ul> 266 * <li>Define a Button in the layout file and assign it a unique ID. 267 * <pre> 268 * <Button 269 * android:id="@+id/my_button" 270 * android:layout_width="wrap_content" 271 * android:layout_height="wrap_content" 272 * android:text="@string/my_button_text"/> 273 * </pre></li> 274 * <li>From the onCreate method of an Activity, find the Button 275 * <pre class="prettyprint"> 276 * Button myButton = (Button) findViewById(R.id.my_button); 277 * </pre></li> 278 * </ul> 279 * <p> 280 * View IDs need not be unique throughout the tree, but it is good practice to 281 * ensure that they are at least unique within the part of the tree you are 282 * searching. 283 * </p> 284 * 285 * <a name="Position"></a> 286 * <h3>Position</h3> 287 * <p> 288 * The geometry of a view is that of a rectangle. A view has a location, 289 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 290 * two dimensions, expressed as a width and a height. The unit for location 291 * and dimensions is the pixel. 292 * </p> 293 * 294 * <p> 295 * It is possible to retrieve the location of a view by invoking the methods 296 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 297 * coordinate of the rectangle representing the view. The latter returns the 298 * top, or Y, coordinate of the rectangle representing the view. These methods 299 * both return the location of the view relative to its parent. For instance, 300 * when getLeft() returns 20, that means the view is located 20 pixels to the 301 * right of the left edge of its direct parent. 302 * </p> 303 * 304 * <p> 305 * In addition, several convenience methods are offered to avoid unnecessary 306 * computations, namely {@link #getRight()} and {@link #getBottom()}. 307 * These methods return the coordinates of the right and bottom edges of the 308 * rectangle representing the view. For instance, calling {@link #getRight()} 309 * is similar to the following computation: <code>getLeft() + getWidth()</code> 310 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 311 * </p> 312 * 313 * <a name="SizePaddingMargins"></a> 314 * <h3>Size, padding and margins</h3> 315 * <p> 316 * The size of a view is expressed with a width and a height. A view actually 317 * possess two pairs of width and height values. 318 * </p> 319 * 320 * <p> 321 * The first pair is known as <em>measured width</em> and 322 * <em>measured height</em>. These dimensions define how big a view wants to be 323 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 324 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 325 * and {@link #getMeasuredHeight()}. 326 * </p> 327 * 328 * <p> 329 * The second pair is simply known as <em>width</em> and <em>height</em>, or 330 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 331 * dimensions define the actual size of the view on screen, at drawing time and 332 * after layout. These values may, but do not have to, be different from the 333 * measured width and height. The width and height can be obtained by calling 334 * {@link #getWidth()} and {@link #getHeight()}. 335 * </p> 336 * 337 * <p> 338 * To measure its dimensions, a view takes into account its padding. The padding 339 * is expressed in pixels for the left, top, right and bottom parts of the view. 340 * Padding can be used to offset the content of the view by a specific amount of 341 * pixels. For instance, a left padding of 2 will push the view's content by 342 * 2 pixels to the right of the left edge. Padding can be set using the 343 * {@link #setPadding(int, int, int, int)} method and queried by calling 344 * {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 345 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}. 346 * </p> 347 * 348 * <p> 349 * Even though a view can define a padding, it does not provide any support for 350 * margins. However, view groups provide such a support. Refer to 351 * {@link android.view.ViewGroup} and 352 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 353 * </p> 354 * 355 * <a name="Layout"></a> 356 * <h3>Layout</h3> 357 * <p> 358 * Layout is a two pass process: a measure pass and a layout pass. The measuring 359 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 360 * of the view tree. Each view pushes dimension specifications down the tree 361 * during the recursion. At the end of the measure pass, every view has stored 362 * its measurements. The second pass happens in 363 * {@link #layout(int,int,int,int)} and is also top-down. During 364 * this pass each parent is responsible for positioning all of its children 365 * using the sizes computed in the measure pass. 366 * </p> 367 * 368 * <p> 369 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 370 * {@link #getMeasuredHeight()} values must be set, along with those for all of 371 * that view's descendants. A view's measured width and measured height values 372 * must respect the constraints imposed by the view's parents. This guarantees 373 * that at the end of the measure pass, all parents accept all of their 374 * children's measurements. A parent view may call measure() more than once on 375 * its children. For example, the parent may measure each child once with 376 * unspecified dimensions to find out how big they want to be, then call 377 * measure() on them again with actual numbers if the sum of all the children's 378 * unconstrained sizes is too big or too small. 379 * </p> 380 * 381 * <p> 382 * The measure pass uses two classes to communicate dimensions. The 383 * {@link MeasureSpec} class is used by views to tell their parents how they 384 * want to be measured and positioned. The base LayoutParams class just 385 * describes how big the view wants to be for both width and height. For each 386 * dimension, it can specify one of: 387 * <ul> 388 * <li> an exact number 389 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 390 * (minus padding) 391 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 392 * enclose its content (plus padding). 393 * </ul> 394 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 395 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 396 * an X and Y value. 397 * </p> 398 * 399 * <p> 400 * MeasureSpecs are used to push requirements down the tree from parent to 401 * child. A MeasureSpec can be in one of three modes: 402 * <ul> 403 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 404 * of a child view. For example, a LinearLayout may call measure() on its child 405 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 406 * tall the child view wants to be given a width of 240 pixels. 407 * <li>EXACTLY: This is used by the parent to impose an exact size on the 408 * child. The child must use this size, and guarantee that all of its 409 * descendants will fit within this size. 410 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 411 * child. The child must gurantee that it and all of its descendants will fit 412 * within this size. 413 * </ul> 414 * </p> 415 * 416 * <p> 417 * To intiate a layout, call {@link #requestLayout}. This method is typically 418 * called by a view on itself when it believes that is can no longer fit within 419 * its current bounds. 420 * </p> 421 * 422 * <a name="Drawing"></a> 423 * <h3>Drawing</h3> 424 * <p> 425 * Drawing is handled by walking the tree and rendering each view that 426 * intersects the the invalid region. Because the tree is traversed in-order, 427 * this means that parents will draw before (i.e., behind) their children, with 428 * siblings drawn in the order they appear in the tree. 429 * If you set a background drawable for a View, then the View will draw it for you 430 * before calling back to its <code>onDraw()</code> method. 431 * </p> 432 * 433 * <p> 434 * Note that the framework will not draw views that are not in the invalid region. 435 * </p> 436 * 437 * <p> 438 * To force a view to draw, call {@link #invalidate()}. 439 * </p> 440 * 441 * <a name="EventHandlingThreading"></a> 442 * <h3>Event Handling and Threading</h3> 443 * <p> 444 * The basic cycle of a view is as follows: 445 * <ol> 446 * <li>An event comes in and is dispatched to the appropriate view. The view 447 * handles the event and notifies any listeners.</li> 448 * <li>If in the course of processing the event, the view's bounds may need 449 * to be changed, the view will call {@link #requestLayout()}.</li> 450 * <li>Similarly, if in the course of processing the event the view's appearance 451 * may need to be changed, the view will call {@link #invalidate()}.</li> 452 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 453 * the framework will take care of measuring, laying out, and drawing the tree 454 * as appropriate.</li> 455 * </ol> 456 * </p> 457 * 458 * <p><em>Note: The entire view tree is single threaded. You must always be on 459 * the UI thread when calling any method on any view.</em> 460 * If you are doing work on other threads and want to update the state of a view 461 * from that thread, you should use a {@link Handler}. 462 * </p> 463 * 464 * <a name="FocusHandling"></a> 465 * <h3>Focus Handling</h3> 466 * <p> 467 * The framework will handle routine focus movement in response to user input. 468 * This includes changing the focus as views are removed or hidden, or as new 469 * views become available. Views indicate their willingness to take focus 470 * through the {@link #isFocusable} method. To change whether a view can take 471 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 472 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 473 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 474 * </p> 475 * <p> 476 * Focus movement is based on an algorithm which finds the nearest neighbor in a 477 * given direction. In rare cases, the default algorithm may not match the 478 * intended behavior of the developer. In these situations, you can provide 479 * explicit overrides by using these XML attributes in the layout file: 480 * <pre> 481 * nextFocusDown 482 * nextFocusLeft 483 * nextFocusRight 484 * nextFocusUp 485 * </pre> 486 * </p> 487 * 488 * 489 * <p> 490 * To get a particular view to take focus, call {@link #requestFocus()}. 491 * </p> 492 * 493 * <a name="TouchMode"></a> 494 * <h3>Touch Mode</h3> 495 * <p> 496 * When a user is navigating a user interface via directional keys such as a D-pad, it is 497 * necessary to give focus to actionable items such as buttons so the user can see 498 * what will take input. If the device has touch capabilities, however, and the user 499 * begins interacting with the interface by touching it, it is no longer necessary to 500 * always highlight, or give focus to, a particular view. This motivates a mode 501 * for interaction named 'touch mode'. 502 * </p> 503 * <p> 504 * For a touch capable device, once the user touches the screen, the device 505 * will enter touch mode. From this point onward, only views for which 506 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 507 * Other views that are touchable, like buttons, will not take focus when touched; they will 508 * only fire the on click listeners. 509 * </p> 510 * <p> 511 * Any time a user hits a directional key, such as a D-pad direction, the view device will 512 * exit touch mode, and find a view to take focus, so that the user may resume interacting 513 * with the user interface without touching the screen again. 514 * </p> 515 * <p> 516 * The touch mode state is maintained across {@link android.app.Activity}s. Call 517 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 518 * </p> 519 * 520 * <a name="Scrolling"></a> 521 * <h3>Scrolling</h3> 522 * <p> 523 * The framework provides basic support for views that wish to internally 524 * scroll their content. This includes keeping track of the X and Y scroll 525 * offset as well as mechanisms for drawing scrollbars. See 526 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 527 * {@link #awakenScrollBars()} for more details. 528 * </p> 529 * 530 * <a name="Tags"></a> 531 * <h3>Tags</h3> 532 * <p> 533 * Unlike IDs, tags are not used to identify views. Tags are essentially an 534 * extra piece of information that can be associated with a view. They are most 535 * often used as a convenience to store data related to views in the views 536 * themselves rather than by putting them in a separate structure. 537 * </p> 538 * 539 * <a name="Animation"></a> 540 * <h3>Animation</h3> 541 * <p> 542 * You can attach an {@link Animation} object to a view using 543 * {@link #setAnimation(Animation)} or 544 * {@link #startAnimation(Animation)}. The animation can alter the scale, 545 * rotation, translation and alpha of a view over time. If the animation is 546 * attached to a view that has children, the animation will affect the entire 547 * subtree rooted by that node. When an animation is started, the framework will 548 * take care of redrawing the appropriate views until the animation completes. 549 * </p> 550 * <p> 551 * Starting with Android 3.0, the preferred way of animating views is to use the 552 * {@link android.animation} package APIs. 553 * </p> 554 * 555 * <a name="Security"></a> 556 * <h3>Security</h3> 557 * <p> 558 * Sometimes it is essential that an application be able to verify that an action 559 * is being performed with the full knowledge and consent of the user, such as 560 * granting a permission request, making a purchase or clicking on an advertisement. 561 * Unfortunately, a malicious application could try to spoof the user into 562 * performing these actions, unaware, by concealing the intended purpose of the view. 563 * As a remedy, the framework offers a touch filtering mechanism that can be used to 564 * improve the security of views that provide access to sensitive functionality. 565 * </p><p> 566 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 567 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 568 * will discard touches that are received whenever the view's window is obscured by 569 * another visible window. As a result, the view will not receive touches whenever a 570 * toast, dialog or other window appears above the view's window. 571 * </p><p> 572 * For more fine-grained control over security, consider overriding the 573 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 574 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 575 * </p> 576 * 577 * @attr ref android.R.styleable#View_alpha 578 * @attr ref android.R.styleable#View_background 579 * @attr ref android.R.styleable#View_clickable 580 * @attr ref android.R.styleable#View_contentDescription 581 * @attr ref android.R.styleable#View_drawingCacheQuality 582 * @attr ref android.R.styleable#View_duplicateParentState 583 * @attr ref android.R.styleable#View_id 584 * @attr ref android.R.styleable#View_fadingEdge 585 * @attr ref android.R.styleable#View_fadingEdgeLength 586 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 587 * @attr ref android.R.styleable#View_fitsSystemWindows 588 * @attr ref android.R.styleable#View_isScrollContainer 589 * @attr ref android.R.styleable#View_focusable 590 * @attr ref android.R.styleable#View_focusableInTouchMode 591 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 592 * @attr ref android.R.styleable#View_keepScreenOn 593 * @attr ref android.R.styleable#View_layerType 594 * @attr ref android.R.styleable#View_longClickable 595 * @attr ref android.R.styleable#View_minHeight 596 * @attr ref android.R.styleable#View_minWidth 597 * @attr ref android.R.styleable#View_nextFocusDown 598 * @attr ref android.R.styleable#View_nextFocusLeft 599 * @attr ref android.R.styleable#View_nextFocusRight 600 * @attr ref android.R.styleable#View_nextFocusUp 601 * @attr ref android.R.styleable#View_onClick 602 * @attr ref android.R.styleable#View_padding 603 * @attr ref android.R.styleable#View_paddingBottom 604 * @attr ref android.R.styleable#View_paddingLeft 605 * @attr ref android.R.styleable#View_paddingRight 606 * @attr ref android.R.styleable#View_paddingTop 607 * @attr ref android.R.styleable#View_saveEnabled 608 * @attr ref android.R.styleable#View_rotation 609 * @attr ref android.R.styleable#View_rotationX 610 * @attr ref android.R.styleable#View_rotationY 611 * @attr ref android.R.styleable#View_scaleX 612 * @attr ref android.R.styleable#View_scaleY 613 * @attr ref android.R.styleable#View_scrollX 614 * @attr ref android.R.styleable#View_scrollY 615 * @attr ref android.R.styleable#View_scrollbarSize 616 * @attr ref android.R.styleable#View_scrollbarStyle 617 * @attr ref android.R.styleable#View_scrollbars 618 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 619 * @attr ref android.R.styleable#View_scrollbarFadeDuration 620 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 621 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 622 * @attr ref android.R.styleable#View_scrollbarThumbVertical 623 * @attr ref android.R.styleable#View_scrollbarTrackVertical 624 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 625 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 626 * @attr ref android.R.styleable#View_soundEffectsEnabled 627 * @attr ref android.R.styleable#View_tag 628 * @attr ref android.R.styleable#View_transformPivotX 629 * @attr ref android.R.styleable#View_transformPivotY 630 * @attr ref android.R.styleable#View_translationX 631 * @attr ref android.R.styleable#View_translationY 632 * @attr ref android.R.styleable#View_visibility 633 * 634 * @see android.view.ViewGroup 635 */ 636public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource { 637 private static final boolean DBG = false; 638 639 /** 640 * The logging tag used by this class with android.util.Log. 641 */ 642 protected static final String VIEW_LOG_TAG = "View"; 643 644 /** 645 * Used to mark a View that has no ID. 646 */ 647 public static final int NO_ID = -1; 648 649 /** 650 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 651 * calling setFlags. 652 */ 653 private static final int NOT_FOCUSABLE = 0x00000000; 654 655 /** 656 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 657 * setFlags. 658 */ 659 private static final int FOCUSABLE = 0x00000001; 660 661 /** 662 * Mask for use with setFlags indicating bits used for focus. 663 */ 664 private static final int FOCUSABLE_MASK = 0x00000001; 665 666 /** 667 * This view will adjust its padding to fit sytem windows (e.g. status bar) 668 */ 669 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 670 671 /** 672 * This view is visible. Use with {@link #setVisibility(int)}. 673 */ 674 public static final int VISIBLE = 0x00000000; 675 676 /** 677 * This view is invisible, but it still takes up space for layout purposes. 678 * Use with {@link #setVisibility(int)}. 679 */ 680 public static final int INVISIBLE = 0x00000004; 681 682 /** 683 * This view is invisible, and it doesn't take any space for layout 684 * purposes. Use with {@link #setVisibility(int)}. 685 */ 686 public static final int GONE = 0x00000008; 687 688 /** 689 * Mask for use with setFlags indicating bits used for visibility. 690 * {@hide} 691 */ 692 static final int VISIBILITY_MASK = 0x0000000C; 693 694 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 695 696 /** 697 * This view is enabled. Intrepretation varies by subclass. 698 * Use with ENABLED_MASK when calling setFlags. 699 * {@hide} 700 */ 701 static final int ENABLED = 0x00000000; 702 703 /** 704 * This view is disabled. Intrepretation varies by subclass. 705 * Use with ENABLED_MASK when calling setFlags. 706 * {@hide} 707 */ 708 static final int DISABLED = 0x00000020; 709 710 /** 711 * Mask for use with setFlags indicating bits used for indicating whether 712 * this view is enabled 713 * {@hide} 714 */ 715 static final int ENABLED_MASK = 0x00000020; 716 717 /** 718 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 719 * called and further optimizations will be performed. It is okay to have 720 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 721 * {@hide} 722 */ 723 static final int WILL_NOT_DRAW = 0x00000080; 724 725 /** 726 * Mask for use with setFlags indicating bits used for indicating whether 727 * this view is will draw 728 * {@hide} 729 */ 730 static final int DRAW_MASK = 0x00000080; 731 732 /** 733 * <p>This view doesn't show scrollbars.</p> 734 * {@hide} 735 */ 736 static final int SCROLLBARS_NONE = 0x00000000; 737 738 /** 739 * <p>This view shows horizontal scrollbars.</p> 740 * {@hide} 741 */ 742 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 743 744 /** 745 * <p>This view shows vertical scrollbars.</p> 746 * {@hide} 747 */ 748 static final int SCROLLBARS_VERTICAL = 0x00000200; 749 750 /** 751 * <p>Mask for use with setFlags indicating bits used for indicating which 752 * scrollbars are enabled.</p> 753 * {@hide} 754 */ 755 static final int SCROLLBARS_MASK = 0x00000300; 756 757 /** 758 * Indicates that the view should filter touches when its window is obscured. 759 * Refer to the class comments for more information about this security feature. 760 * {@hide} 761 */ 762 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 763 764 // note flag value 0x00000800 is now available for next flags... 765 766 /** 767 * <p>This view doesn't show fading edges.</p> 768 * {@hide} 769 */ 770 static final int FADING_EDGE_NONE = 0x00000000; 771 772 /** 773 * <p>This view shows horizontal fading edges.</p> 774 * {@hide} 775 */ 776 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 777 778 /** 779 * <p>This view shows vertical fading edges.</p> 780 * {@hide} 781 */ 782 static final int FADING_EDGE_VERTICAL = 0x00002000; 783 784 /** 785 * <p>Mask for use with setFlags indicating bits used for indicating which 786 * fading edges are enabled.</p> 787 * {@hide} 788 */ 789 static final int FADING_EDGE_MASK = 0x00003000; 790 791 /** 792 * <p>Indicates this view can be clicked. When clickable, a View reacts 793 * to clicks by notifying the OnClickListener.<p> 794 * {@hide} 795 */ 796 static final int CLICKABLE = 0x00004000; 797 798 /** 799 * <p>Indicates this view is caching its drawing into a bitmap.</p> 800 * {@hide} 801 */ 802 static final int DRAWING_CACHE_ENABLED = 0x00008000; 803 804 /** 805 * <p>Indicates that no icicle should be saved for this view.<p> 806 * {@hide} 807 */ 808 static final int SAVE_DISABLED = 0x000010000; 809 810 /** 811 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 812 * property.</p> 813 * {@hide} 814 */ 815 static final int SAVE_DISABLED_MASK = 0x000010000; 816 817 /** 818 * <p>Indicates that no drawing cache should ever be created for this view.<p> 819 * {@hide} 820 */ 821 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 822 823 /** 824 * <p>Indicates this view can take / keep focus when int touch mode.</p> 825 * {@hide} 826 */ 827 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 828 829 /** 830 * <p>Enables low quality mode for the drawing cache.</p> 831 */ 832 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 833 834 /** 835 * <p>Enables high quality mode for the drawing cache.</p> 836 */ 837 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 838 839 /** 840 * <p>Enables automatic quality mode for the drawing cache.</p> 841 */ 842 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 843 844 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 845 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 846 }; 847 848 /** 849 * <p>Mask for use with setFlags indicating bits used for the cache 850 * quality property.</p> 851 * {@hide} 852 */ 853 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 854 855 /** 856 * <p> 857 * Indicates this view can be long clicked. When long clickable, a View 858 * reacts to long clicks by notifying the OnLongClickListener or showing a 859 * context menu. 860 * </p> 861 * {@hide} 862 */ 863 static final int LONG_CLICKABLE = 0x00200000; 864 865 /** 866 * <p>Indicates that this view gets its drawable states from its direct parent 867 * and ignores its original internal states.</p> 868 * 869 * @hide 870 */ 871 static final int DUPLICATE_PARENT_STATE = 0x00400000; 872 873 /** 874 * The scrollbar style to display the scrollbars inside the content area, 875 * without increasing the padding. The scrollbars will be overlaid with 876 * translucency on the view's content. 877 */ 878 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 879 880 /** 881 * The scrollbar style to display the scrollbars inside the padded area, 882 * increasing the padding of the view. The scrollbars will not overlap the 883 * content area of the view. 884 */ 885 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 886 887 /** 888 * The scrollbar style to display the scrollbars at the edge of the view, 889 * without increasing the padding. The scrollbars will be overlaid with 890 * translucency. 891 */ 892 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 893 894 /** 895 * The scrollbar style to display the scrollbars at the edge of the view, 896 * increasing the padding of the view. The scrollbars will only overlap the 897 * background, if any. 898 */ 899 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 900 901 /** 902 * Mask to check if the scrollbar style is overlay or inset. 903 * {@hide} 904 */ 905 static final int SCROLLBARS_INSET_MASK = 0x01000000; 906 907 /** 908 * Mask to check if the scrollbar style is inside or outside. 909 * {@hide} 910 */ 911 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 912 913 /** 914 * Mask for scrollbar style. 915 * {@hide} 916 */ 917 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 918 919 /** 920 * View flag indicating that the screen should remain on while the 921 * window containing this view is visible to the user. This effectively 922 * takes care of automatically setting the WindowManager's 923 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 924 */ 925 public static final int KEEP_SCREEN_ON = 0x04000000; 926 927 /** 928 * View flag indicating whether this view should have sound effects enabled 929 * for events such as clicking and touching. 930 */ 931 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 932 933 /** 934 * View flag indicating whether this view should have haptic feedback 935 * enabled for events such as long presses. 936 */ 937 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 938 939 /** 940 * <p>Indicates that the view hierarchy should stop saving state when 941 * it reaches this view. If state saving is initiated immediately at 942 * the view, it will be allowed. 943 * {@hide} 944 */ 945 static final int PARENT_SAVE_DISABLED = 0x20000000; 946 947 /** 948 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 949 * {@hide} 950 */ 951 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 952 953 /** 954 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 955 * should add all focusable Views regardless if they are focusable in touch mode. 956 */ 957 public static final int FOCUSABLES_ALL = 0x00000000; 958 959 /** 960 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 961 * should add only Views focusable in touch mode. 962 */ 963 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 964 965 /** 966 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 967 * item. 968 */ 969 public static final int FOCUS_BACKWARD = 0x00000001; 970 971 /** 972 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 973 * item. 974 */ 975 public static final int FOCUS_FORWARD = 0x00000002; 976 977 /** 978 * Use with {@link #focusSearch(int)}. Move focus to the left. 979 */ 980 public static final int FOCUS_LEFT = 0x00000011; 981 982 /** 983 * Use with {@link #focusSearch(int)}. Move focus up. 984 */ 985 public static final int FOCUS_UP = 0x00000021; 986 987 /** 988 * Use with {@link #focusSearch(int)}. Move focus to the right. 989 */ 990 public static final int FOCUS_RIGHT = 0x00000042; 991 992 /** 993 * Use with {@link #focusSearch(int)}. Move focus down. 994 */ 995 public static final int FOCUS_DOWN = 0x00000082; 996 997 /** 998 * Bits of {@link #getMeasuredWidthAndState()} and 999 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1000 */ 1001 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1002 1003 /** 1004 * Bits of {@link #getMeasuredWidthAndState()} and 1005 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1006 */ 1007 public static final int MEASURED_STATE_MASK = 0xff000000; 1008 1009 /** 1010 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1011 * for functions that combine both width and height into a single int, 1012 * such as {@link #getMeasuredState()} and the childState argument of 1013 * {@link #resolveSizeAndState(int, int, int)}. 1014 */ 1015 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1016 1017 /** 1018 * Bit of {@link #getMeasuredWidthAndState()} and 1019 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1020 * is smaller that the space the view would like to have. 1021 */ 1022 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1023 1024 /** 1025 * Base View state sets 1026 */ 1027 // Singles 1028 /** 1029 * Indicates the view has no states set. States are used with 1030 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1031 * view depending on its state. 1032 * 1033 * @see android.graphics.drawable.Drawable 1034 * @see #getDrawableState() 1035 */ 1036 protected static final int[] EMPTY_STATE_SET; 1037 /** 1038 * Indicates the view is enabled. States are used with 1039 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1040 * view depending on its state. 1041 * 1042 * @see android.graphics.drawable.Drawable 1043 * @see #getDrawableState() 1044 */ 1045 protected static final int[] ENABLED_STATE_SET; 1046 /** 1047 * Indicates the view is focused. States are used with 1048 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1049 * view depending on its state. 1050 * 1051 * @see android.graphics.drawable.Drawable 1052 * @see #getDrawableState() 1053 */ 1054 protected static final int[] FOCUSED_STATE_SET; 1055 /** 1056 * Indicates the view is selected. States are used with 1057 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1058 * view depending on its state. 1059 * 1060 * @see android.graphics.drawable.Drawable 1061 * @see #getDrawableState() 1062 */ 1063 protected static final int[] SELECTED_STATE_SET; 1064 /** 1065 * Indicates the view is pressed. States are used with 1066 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1067 * view depending on its state. 1068 * 1069 * @see android.graphics.drawable.Drawable 1070 * @see #getDrawableState() 1071 * @hide 1072 */ 1073 protected static final int[] PRESSED_STATE_SET; 1074 /** 1075 * Indicates the view's window has focus. States are used with 1076 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1077 * view depending on its state. 1078 * 1079 * @see android.graphics.drawable.Drawable 1080 * @see #getDrawableState() 1081 */ 1082 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1083 // Doubles 1084 /** 1085 * Indicates the view is enabled and has the focus. 1086 * 1087 * @see #ENABLED_STATE_SET 1088 * @see #FOCUSED_STATE_SET 1089 */ 1090 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1091 /** 1092 * Indicates the view is enabled and selected. 1093 * 1094 * @see #ENABLED_STATE_SET 1095 * @see #SELECTED_STATE_SET 1096 */ 1097 protected static final int[] ENABLED_SELECTED_STATE_SET; 1098 /** 1099 * Indicates the view is enabled and that its window has focus. 1100 * 1101 * @see #ENABLED_STATE_SET 1102 * @see #WINDOW_FOCUSED_STATE_SET 1103 */ 1104 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1105 /** 1106 * Indicates the view is focused and selected. 1107 * 1108 * @see #FOCUSED_STATE_SET 1109 * @see #SELECTED_STATE_SET 1110 */ 1111 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1112 /** 1113 * Indicates the view has the focus and that its window has the focus. 1114 * 1115 * @see #FOCUSED_STATE_SET 1116 * @see #WINDOW_FOCUSED_STATE_SET 1117 */ 1118 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1119 /** 1120 * Indicates the view is selected and that its window has the focus. 1121 * 1122 * @see #SELECTED_STATE_SET 1123 * @see #WINDOW_FOCUSED_STATE_SET 1124 */ 1125 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1126 // Triples 1127 /** 1128 * Indicates the view is enabled, focused and selected. 1129 * 1130 * @see #ENABLED_STATE_SET 1131 * @see #FOCUSED_STATE_SET 1132 * @see #SELECTED_STATE_SET 1133 */ 1134 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1135 /** 1136 * Indicates the view is enabled, focused and its window has the focus. 1137 * 1138 * @see #ENABLED_STATE_SET 1139 * @see #FOCUSED_STATE_SET 1140 * @see #WINDOW_FOCUSED_STATE_SET 1141 */ 1142 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1143 /** 1144 * Indicates the view is enabled, selected and its window has the focus. 1145 * 1146 * @see #ENABLED_STATE_SET 1147 * @see #SELECTED_STATE_SET 1148 * @see #WINDOW_FOCUSED_STATE_SET 1149 */ 1150 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1151 /** 1152 * Indicates the view is focused, selected and its window has the focus. 1153 * 1154 * @see #FOCUSED_STATE_SET 1155 * @see #SELECTED_STATE_SET 1156 * @see #WINDOW_FOCUSED_STATE_SET 1157 */ 1158 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1159 /** 1160 * Indicates the view is enabled, focused, selected and its window 1161 * has the focus. 1162 * 1163 * @see #ENABLED_STATE_SET 1164 * @see #FOCUSED_STATE_SET 1165 * @see #SELECTED_STATE_SET 1166 * @see #WINDOW_FOCUSED_STATE_SET 1167 */ 1168 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1169 /** 1170 * Indicates the view is pressed and its window has the focus. 1171 * 1172 * @see #PRESSED_STATE_SET 1173 * @see #WINDOW_FOCUSED_STATE_SET 1174 */ 1175 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1176 /** 1177 * Indicates the view is pressed and selected. 1178 * 1179 * @see #PRESSED_STATE_SET 1180 * @see #SELECTED_STATE_SET 1181 */ 1182 protected static final int[] PRESSED_SELECTED_STATE_SET; 1183 /** 1184 * Indicates the view is pressed, selected and its window has the focus. 1185 * 1186 * @see #PRESSED_STATE_SET 1187 * @see #SELECTED_STATE_SET 1188 * @see #WINDOW_FOCUSED_STATE_SET 1189 */ 1190 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1191 /** 1192 * Indicates the view is pressed and focused. 1193 * 1194 * @see #PRESSED_STATE_SET 1195 * @see #FOCUSED_STATE_SET 1196 */ 1197 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1198 /** 1199 * Indicates the view is pressed, focused and its window has the focus. 1200 * 1201 * @see #PRESSED_STATE_SET 1202 * @see #FOCUSED_STATE_SET 1203 * @see #WINDOW_FOCUSED_STATE_SET 1204 */ 1205 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1206 /** 1207 * Indicates the view is pressed, focused and selected. 1208 * 1209 * @see #PRESSED_STATE_SET 1210 * @see #SELECTED_STATE_SET 1211 * @see #FOCUSED_STATE_SET 1212 */ 1213 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1214 /** 1215 * Indicates the view is pressed, focused, selected and its window has the focus. 1216 * 1217 * @see #PRESSED_STATE_SET 1218 * @see #FOCUSED_STATE_SET 1219 * @see #SELECTED_STATE_SET 1220 * @see #WINDOW_FOCUSED_STATE_SET 1221 */ 1222 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1223 /** 1224 * Indicates the view is pressed and enabled. 1225 * 1226 * @see #PRESSED_STATE_SET 1227 * @see #ENABLED_STATE_SET 1228 */ 1229 protected static final int[] PRESSED_ENABLED_STATE_SET; 1230 /** 1231 * Indicates the view is pressed, enabled and its window has the focus. 1232 * 1233 * @see #PRESSED_STATE_SET 1234 * @see #ENABLED_STATE_SET 1235 * @see #WINDOW_FOCUSED_STATE_SET 1236 */ 1237 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1238 /** 1239 * Indicates the view is pressed, enabled and selected. 1240 * 1241 * @see #PRESSED_STATE_SET 1242 * @see #ENABLED_STATE_SET 1243 * @see #SELECTED_STATE_SET 1244 */ 1245 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1246 /** 1247 * Indicates the view is pressed, enabled, selected and its window has the 1248 * focus. 1249 * 1250 * @see #PRESSED_STATE_SET 1251 * @see #ENABLED_STATE_SET 1252 * @see #SELECTED_STATE_SET 1253 * @see #WINDOW_FOCUSED_STATE_SET 1254 */ 1255 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1256 /** 1257 * Indicates the view is pressed, enabled and focused. 1258 * 1259 * @see #PRESSED_STATE_SET 1260 * @see #ENABLED_STATE_SET 1261 * @see #FOCUSED_STATE_SET 1262 */ 1263 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1264 /** 1265 * Indicates the view is pressed, enabled, focused and its window has the 1266 * focus. 1267 * 1268 * @see #PRESSED_STATE_SET 1269 * @see #ENABLED_STATE_SET 1270 * @see #FOCUSED_STATE_SET 1271 * @see #WINDOW_FOCUSED_STATE_SET 1272 */ 1273 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1274 /** 1275 * Indicates the view is pressed, enabled, focused and selected. 1276 * 1277 * @see #PRESSED_STATE_SET 1278 * @see #ENABLED_STATE_SET 1279 * @see #SELECTED_STATE_SET 1280 * @see #FOCUSED_STATE_SET 1281 */ 1282 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1283 /** 1284 * Indicates the view is pressed, enabled, focused, selected and its window 1285 * has the focus. 1286 * 1287 * @see #PRESSED_STATE_SET 1288 * @see #ENABLED_STATE_SET 1289 * @see #SELECTED_STATE_SET 1290 * @see #FOCUSED_STATE_SET 1291 * @see #WINDOW_FOCUSED_STATE_SET 1292 */ 1293 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1294 1295 /** 1296 * The order here is very important to {@link #getDrawableState()} 1297 */ 1298 private static final int[][] VIEW_STATE_SETS; 1299 1300 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1301 static final int VIEW_STATE_SELECTED = 1 << 1; 1302 static final int VIEW_STATE_FOCUSED = 1 << 2; 1303 static final int VIEW_STATE_ENABLED = 1 << 3; 1304 static final int VIEW_STATE_PRESSED = 1 << 4; 1305 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1306 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1307 static final int VIEW_STATE_HOVERED = 1 << 7; 1308 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1309 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1310 1311 static final int[] VIEW_STATE_IDS = new int[] { 1312 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1313 R.attr.state_selected, VIEW_STATE_SELECTED, 1314 R.attr.state_focused, VIEW_STATE_FOCUSED, 1315 R.attr.state_enabled, VIEW_STATE_ENABLED, 1316 R.attr.state_pressed, VIEW_STATE_PRESSED, 1317 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1318 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1319 R.attr.state_hovered, VIEW_STATE_HOVERED, 1320 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1321 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED, 1322 }; 1323 1324 static { 1325 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1326 throw new IllegalStateException( 1327 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1328 } 1329 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1330 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1331 int viewState = R.styleable.ViewDrawableStates[i]; 1332 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1333 if (VIEW_STATE_IDS[j] == viewState) { 1334 orderedIds[i * 2] = viewState; 1335 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1336 } 1337 } 1338 } 1339 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1340 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1341 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1342 int numBits = Integer.bitCount(i); 1343 int[] set = new int[numBits]; 1344 int pos = 0; 1345 for (int j = 0; j < orderedIds.length; j += 2) { 1346 if ((i & orderedIds[j+1]) != 0) { 1347 set[pos++] = orderedIds[j]; 1348 } 1349 } 1350 VIEW_STATE_SETS[i] = set; 1351 } 1352 1353 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1354 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1355 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1356 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1357 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1358 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1359 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1360 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1361 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1362 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1363 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1364 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1365 | VIEW_STATE_FOCUSED]; 1366 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1367 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1368 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1369 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1370 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1371 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1372 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1373 | VIEW_STATE_ENABLED]; 1374 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1375 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1376 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1377 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1378 | VIEW_STATE_ENABLED]; 1379 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1380 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1381 | VIEW_STATE_ENABLED]; 1382 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1383 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1384 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1385 1386 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1387 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1388 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1389 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1390 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1391 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1392 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1393 | VIEW_STATE_PRESSED]; 1394 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1395 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1396 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1397 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1398 | VIEW_STATE_PRESSED]; 1399 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1400 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1401 | VIEW_STATE_PRESSED]; 1402 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1403 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1404 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1405 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1406 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1407 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1408 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1409 | VIEW_STATE_PRESSED]; 1410 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1411 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1412 | VIEW_STATE_PRESSED]; 1413 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1414 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1415 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1416 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1417 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1418 | VIEW_STATE_PRESSED]; 1419 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1420 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1421 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1422 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1423 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1424 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1425 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1426 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1427 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1428 | VIEW_STATE_PRESSED]; 1429 } 1430 1431 /** 1432 * Temporary Rect currently for use in setBackground(). This will probably 1433 * be extended in the future to hold our own class with more than just 1434 * a Rect. :) 1435 */ 1436 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1437 1438 /** 1439 * Map used to store views' tags. 1440 */ 1441 private static WeakHashMap<View, SparseArray<Object>> sTags; 1442 1443 /** 1444 * Lock used to access sTags. 1445 */ 1446 private static final Object sTagsLock = new Object(); 1447 1448 /** 1449 * The animation currently associated with this view. 1450 * @hide 1451 */ 1452 protected Animation mCurrentAnimation = null; 1453 1454 /** 1455 * Width as measured during measure pass. 1456 * {@hide} 1457 */ 1458 @ViewDebug.ExportedProperty(category = "measurement") 1459 int mMeasuredWidth; 1460 1461 /** 1462 * Height as measured during measure pass. 1463 * {@hide} 1464 */ 1465 @ViewDebug.ExportedProperty(category = "measurement") 1466 int mMeasuredHeight; 1467 1468 /** 1469 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1470 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1471 * its display list. This flag, used only when hw accelerated, allows us to clear the 1472 * flag while retaining this information until it's needed (at getDisplayList() time and 1473 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1474 * 1475 * {@hide} 1476 */ 1477 boolean mRecreateDisplayList = false; 1478 1479 /** 1480 * The view's identifier. 1481 * {@hide} 1482 * 1483 * @see #setId(int) 1484 * @see #getId() 1485 */ 1486 @ViewDebug.ExportedProperty(resolveId = true) 1487 int mID = NO_ID; 1488 1489 /** 1490 * The view's tag. 1491 * {@hide} 1492 * 1493 * @see #setTag(Object) 1494 * @see #getTag() 1495 */ 1496 protected Object mTag; 1497 1498 // for mPrivateFlags: 1499 /** {@hide} */ 1500 static final int WANTS_FOCUS = 0x00000001; 1501 /** {@hide} */ 1502 static final int FOCUSED = 0x00000002; 1503 /** {@hide} */ 1504 static final int SELECTED = 0x00000004; 1505 /** {@hide} */ 1506 static final int IS_ROOT_NAMESPACE = 0x00000008; 1507 /** {@hide} */ 1508 static final int HAS_BOUNDS = 0x00000010; 1509 /** {@hide} */ 1510 static final int DRAWN = 0x00000020; 1511 /** 1512 * When this flag is set, this view is running an animation on behalf of its 1513 * children and should therefore not cancel invalidate requests, even if they 1514 * lie outside of this view's bounds. 1515 * 1516 * {@hide} 1517 */ 1518 static final int DRAW_ANIMATION = 0x00000040; 1519 /** {@hide} */ 1520 static final int SKIP_DRAW = 0x00000080; 1521 /** {@hide} */ 1522 static final int ONLY_DRAWS_BACKGROUND = 0x00000100; 1523 /** {@hide} */ 1524 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1525 /** {@hide} */ 1526 static final int DRAWABLE_STATE_DIRTY = 0x00000400; 1527 /** {@hide} */ 1528 static final int MEASURED_DIMENSION_SET = 0x00000800; 1529 /** {@hide} */ 1530 static final int FORCE_LAYOUT = 0x00001000; 1531 /** {@hide} */ 1532 static final int LAYOUT_REQUIRED = 0x00002000; 1533 1534 private static final int PRESSED = 0x00004000; 1535 1536 /** {@hide} */ 1537 static final int DRAWING_CACHE_VALID = 0x00008000; 1538 /** 1539 * Flag used to indicate that this view should be drawn once more (and only once 1540 * more) after its animation has completed. 1541 * {@hide} 1542 */ 1543 static final int ANIMATION_STARTED = 0x00010000; 1544 1545 private static final int SAVE_STATE_CALLED = 0x00020000; 1546 1547 /** 1548 * Indicates that the View returned true when onSetAlpha() was called and that 1549 * the alpha must be restored. 1550 * {@hide} 1551 */ 1552 static final int ALPHA_SET = 0x00040000; 1553 1554 /** 1555 * Set by {@link #setScrollContainer(boolean)}. 1556 */ 1557 static final int SCROLL_CONTAINER = 0x00080000; 1558 1559 /** 1560 * Set by {@link #setScrollContainer(boolean)}. 1561 */ 1562 static final int SCROLL_CONTAINER_ADDED = 0x00100000; 1563 1564 /** 1565 * View flag indicating whether this view was invalidated (fully or partially.) 1566 * 1567 * @hide 1568 */ 1569 static final int DIRTY = 0x00200000; 1570 1571 /** 1572 * View flag indicating whether this view was invalidated by an opaque 1573 * invalidate request. 1574 * 1575 * @hide 1576 */ 1577 static final int DIRTY_OPAQUE = 0x00400000; 1578 1579 /** 1580 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}. 1581 * 1582 * @hide 1583 */ 1584 static final int DIRTY_MASK = 0x00600000; 1585 1586 /** 1587 * Indicates whether the background is opaque. 1588 * 1589 * @hide 1590 */ 1591 static final int OPAQUE_BACKGROUND = 0x00800000; 1592 1593 /** 1594 * Indicates whether the scrollbars are opaque. 1595 * 1596 * @hide 1597 */ 1598 static final int OPAQUE_SCROLLBARS = 0x01000000; 1599 1600 /** 1601 * Indicates whether the view is opaque. 1602 * 1603 * @hide 1604 */ 1605 static final int OPAQUE_MASK = 0x01800000; 1606 1607 /** 1608 * Indicates a prepressed state; 1609 * the short time between ACTION_DOWN and recognizing 1610 * a 'real' press. Prepressed is used to recognize quick taps 1611 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1612 * 1613 * @hide 1614 */ 1615 private static final int PREPRESSED = 0x02000000; 1616 1617 /** 1618 * Indicates whether the view is temporarily detached. 1619 * 1620 * @hide 1621 */ 1622 static final int CANCEL_NEXT_UP_EVENT = 0x04000000; 1623 1624 /** 1625 * Indicates that we should awaken scroll bars once attached 1626 * 1627 * @hide 1628 */ 1629 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1630 1631 /** 1632 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1633 * @hide 1634 */ 1635 private static final int HOVERED = 0x10000000; 1636 1637 /** 1638 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1639 * for transform operations 1640 * 1641 * @hide 1642 */ 1643 private static final int PIVOT_EXPLICITLY_SET = 0x20000000; 1644 1645 /** {@hide} */ 1646 static final int ACTIVATED = 0x40000000; 1647 1648 /** 1649 * Indicates that this view was specifically invalidated, not just dirtied because some 1650 * child view was invalidated. The flag is used to determine when we need to recreate 1651 * a view's display list (as opposed to just returning a reference to its existing 1652 * display list). 1653 * 1654 * @hide 1655 */ 1656 static final int INVALIDATED = 0x80000000; 1657 1658 /* Masks for mPrivateFlags2 */ 1659 1660 /** 1661 * Indicates that this view has reported that it can accept the current drag's content. 1662 * Cleared when the drag operation concludes. 1663 * @hide 1664 */ 1665 static final int DRAG_CAN_ACCEPT = 0x00000001; 1666 1667 /** 1668 * Indicates that this view is currently directly under the drag location in a 1669 * drag-and-drop operation involving content that it can accept. Cleared when 1670 * the drag exits the view, or when the drag operation concludes. 1671 * @hide 1672 */ 1673 static final int DRAG_HOVERED = 0x00000002; 1674 1675 /* End of masks for mPrivateFlags2 */ 1676 1677 static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED; 1678 1679 /** 1680 * Always allow a user to over-scroll this view, provided it is a 1681 * view that can scroll. 1682 * 1683 * @see #getOverScrollMode() 1684 * @see #setOverScrollMode(int) 1685 */ 1686 public static final int OVER_SCROLL_ALWAYS = 0; 1687 1688 /** 1689 * Allow a user to over-scroll this view only if the content is large 1690 * enough to meaningfully scroll, provided it is a view that can scroll. 1691 * 1692 * @see #getOverScrollMode() 1693 * @see #setOverScrollMode(int) 1694 */ 1695 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 1696 1697 /** 1698 * Never allow a user to over-scroll this view. 1699 * 1700 * @see #getOverScrollMode() 1701 * @see #setOverScrollMode(int) 1702 */ 1703 public static final int OVER_SCROLL_NEVER = 2; 1704 1705 /** 1706 * View has requested the status bar to be visible (the default). 1707 * 1708 * @see #setSystemUiVisibility(int) 1709 */ 1710 public static final int STATUS_BAR_VISIBLE = 0; 1711 1712 /** 1713 * View has requested the status bar to be hidden. 1714 * 1715 * @see #setSystemUiVisibility(int) 1716 */ 1717 public static final int STATUS_BAR_HIDDEN = 0x00000001; 1718 1719 /** 1720 * @hide 1721 * 1722 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1723 * out of the public fields to keep the undefined bits out of the developer's way. 1724 * 1725 * Flag to make the status bar not expandable. Unless you also 1726 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 1727 */ 1728 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 1729 1730 /** 1731 * @hide 1732 * 1733 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1734 * out of the public fields to keep the undefined bits out of the developer's way. 1735 * 1736 * Flag to hide notification icons and scrolling ticker text. 1737 */ 1738 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 1739 1740 /** 1741 * @hide 1742 * 1743 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1744 * out of the public fields to keep the undefined bits out of the developer's way. 1745 * 1746 * Flag to disable incoming notification alerts. This will not block 1747 * icons, but it will block sound, vibrating and other visual or aural notifications. 1748 */ 1749 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 1750 1751 /** 1752 * @hide 1753 * 1754 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1755 * out of the public fields to keep the undefined bits out of the developer's way. 1756 * 1757 * Flag to hide only the scrolling ticker. Note that 1758 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 1759 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 1760 */ 1761 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 1762 1763 /** 1764 * @hide 1765 * 1766 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1767 * out of the public fields to keep the undefined bits out of the developer's way. 1768 * 1769 * Flag to hide the center system info area. 1770 */ 1771 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 1772 1773 /** 1774 * @hide 1775 * 1776 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1777 * out of the public fields to keep the undefined bits out of the developer's way. 1778 * 1779 * Flag to hide only the navigation buttons. Don't use this 1780 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1781 * 1782 * THIS DOES NOT DISABLE THE BACK BUTTON 1783 */ 1784 public static final int STATUS_BAR_DISABLE_NAVIGATION = 0x00200000; 1785 1786 /** 1787 * @hide 1788 * 1789 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1790 * out of the public fields to keep the undefined bits out of the developer's way. 1791 * 1792 * Flag to hide only the back button. Don't use this 1793 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1794 */ 1795 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 1796 1797 /** 1798 * @hide 1799 * 1800 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1801 * out of the public fields to keep the undefined bits out of the developer's way. 1802 * 1803 * Flag to hide only the clock. You might use this if your activity has 1804 * its own clock making the status bar's clock redundant. 1805 */ 1806 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 1807 1808 /** 1809 * @hide 1810 */ 1811 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = STATUS_BAR_HIDDEN; 1812 1813 /** 1814 * Controls the over-scroll mode for this view. 1815 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 1816 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 1817 * and {@link #OVER_SCROLL_NEVER}. 1818 */ 1819 private int mOverScrollMode; 1820 1821 /** 1822 * The parent this view is attached to. 1823 * {@hide} 1824 * 1825 * @see #getParent() 1826 */ 1827 protected ViewParent mParent; 1828 1829 /** 1830 * {@hide} 1831 */ 1832 AttachInfo mAttachInfo; 1833 1834 /** 1835 * {@hide} 1836 */ 1837 @ViewDebug.ExportedProperty(flagMapping = { 1838 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT, 1839 name = "FORCE_LAYOUT"), 1840 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED, 1841 name = "LAYOUT_REQUIRED"), 1842 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID, 1843 name = "DRAWING_CACHE_INVALID", outputIf = false), 1844 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true), 1845 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false), 1846 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 1847 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY") 1848 }) 1849 int mPrivateFlags; 1850 int mPrivateFlags2; 1851 1852 /** 1853 * This view's request for the visibility of the status bar. 1854 * @hide 1855 */ 1856 @ViewDebug.ExportedProperty() 1857 int mSystemUiVisibility; 1858 1859 /** 1860 * Count of how many windows this view has been attached to. 1861 */ 1862 int mWindowAttachCount; 1863 1864 /** 1865 * The layout parameters associated with this view and used by the parent 1866 * {@link android.view.ViewGroup} to determine how this view should be 1867 * laid out. 1868 * {@hide} 1869 */ 1870 protected ViewGroup.LayoutParams mLayoutParams; 1871 1872 /** 1873 * The view flags hold various views states. 1874 * {@hide} 1875 */ 1876 @ViewDebug.ExportedProperty 1877 int mViewFlags; 1878 1879 /** 1880 * The transform matrix for the View. This transform is calculated internally 1881 * based on the rotation, scaleX, and scaleY properties. The identity matrix 1882 * is used by default. Do *not* use this variable directly; instead call 1883 * getMatrix(), which will automatically recalculate the matrix if necessary 1884 * to get the correct matrix based on the latest rotation and scale properties. 1885 */ 1886 private final Matrix mMatrix = new Matrix(); 1887 1888 /** 1889 * The transform matrix for the View. This transform is calculated internally 1890 * based on the rotation, scaleX, and scaleY properties. The identity matrix 1891 * is used by default. Do *not* use this variable directly; instead call 1892 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 1893 * to get the correct matrix based on the latest rotation and scale properties. 1894 */ 1895 private Matrix mInverseMatrix; 1896 1897 /** 1898 * An internal variable that tracks whether we need to recalculate the 1899 * transform matrix, based on whether the rotation or scaleX/Y properties 1900 * have changed since the matrix was last calculated. 1901 */ 1902 boolean mMatrixDirty = false; 1903 1904 /** 1905 * An internal variable that tracks whether we need to recalculate the 1906 * transform matrix, based on whether the rotation or scaleX/Y properties 1907 * have changed since the matrix was last calculated. 1908 */ 1909 private boolean mInverseMatrixDirty = true; 1910 1911 /** 1912 * A variable that tracks whether we need to recalculate the 1913 * transform matrix, based on whether the rotation or scaleX/Y properties 1914 * have changed since the matrix was last calculated. This variable 1915 * is only valid after a call to updateMatrix() or to a function that 1916 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 1917 */ 1918 private boolean mMatrixIsIdentity = true; 1919 1920 /** 1921 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 1922 */ 1923 private Camera mCamera = null; 1924 1925 /** 1926 * This matrix is used when computing the matrix for 3D rotations. 1927 */ 1928 private Matrix matrix3D = null; 1929 1930 /** 1931 * These prev values are used to recalculate a centered pivot point when necessary. The 1932 * pivot point is only used in matrix operations (when rotation, scale, or translation are 1933 * set), so thes values are only used then as well. 1934 */ 1935 private int mPrevWidth = -1; 1936 private int mPrevHeight = -1; 1937 1938 private boolean mLastIsOpaque; 1939 1940 /** 1941 * Convenience value to check for float values that are close enough to zero to be considered 1942 * zero. 1943 */ 1944 private static final float NONZERO_EPSILON = .001f; 1945 1946 /** 1947 * The degrees rotation around the vertical axis through the pivot point. 1948 */ 1949 @ViewDebug.ExportedProperty 1950 float mRotationY = 0f; 1951 1952 /** 1953 * The degrees rotation around the horizontal axis through the pivot point. 1954 */ 1955 @ViewDebug.ExportedProperty 1956 float mRotationX = 0f; 1957 1958 /** 1959 * The degrees rotation around the pivot point. 1960 */ 1961 @ViewDebug.ExportedProperty 1962 float mRotation = 0f; 1963 1964 /** 1965 * The amount of translation of the object away from its left property (post-layout). 1966 */ 1967 @ViewDebug.ExportedProperty 1968 float mTranslationX = 0f; 1969 1970 /** 1971 * The amount of translation of the object away from its top property (post-layout). 1972 */ 1973 @ViewDebug.ExportedProperty 1974 float mTranslationY = 0f; 1975 1976 /** 1977 * The amount of scale in the x direction around the pivot point. A 1978 * value of 1 means no scaling is applied. 1979 */ 1980 @ViewDebug.ExportedProperty 1981 float mScaleX = 1f; 1982 1983 /** 1984 * The amount of scale in the y direction around the pivot point. A 1985 * value of 1 means no scaling is applied. 1986 */ 1987 @ViewDebug.ExportedProperty 1988 float mScaleY = 1f; 1989 1990 /** 1991 * The amount of scale in the x direction around the pivot point. A 1992 * value of 1 means no scaling is applied. 1993 */ 1994 @ViewDebug.ExportedProperty 1995 float mPivotX = 0f; 1996 1997 /** 1998 * The amount of scale in the y direction around the pivot point. A 1999 * value of 1 means no scaling is applied. 2000 */ 2001 @ViewDebug.ExportedProperty 2002 float mPivotY = 0f; 2003 2004 /** 2005 * The opacity of the View. This is a value from 0 to 1, where 0 means 2006 * completely transparent and 1 means completely opaque. 2007 */ 2008 @ViewDebug.ExportedProperty 2009 float mAlpha = 1f; 2010 2011 /** 2012 * The distance in pixels from the left edge of this view's parent 2013 * to the left edge of this view. 2014 * {@hide} 2015 */ 2016 @ViewDebug.ExportedProperty(category = "layout") 2017 protected int mLeft; 2018 /** 2019 * The distance in pixels from the left edge of this view's parent 2020 * to the right edge of this view. 2021 * {@hide} 2022 */ 2023 @ViewDebug.ExportedProperty(category = "layout") 2024 protected int mRight; 2025 /** 2026 * The distance in pixels from the top edge of this view's parent 2027 * to the top edge of this view. 2028 * {@hide} 2029 */ 2030 @ViewDebug.ExportedProperty(category = "layout") 2031 protected int mTop; 2032 /** 2033 * The distance in pixels from the top edge of this view's parent 2034 * to the bottom edge of this view. 2035 * {@hide} 2036 */ 2037 @ViewDebug.ExportedProperty(category = "layout") 2038 protected int mBottom; 2039 2040 /** 2041 * The offset, in pixels, by which the content of this view is scrolled 2042 * horizontally. 2043 * {@hide} 2044 */ 2045 @ViewDebug.ExportedProperty(category = "scrolling") 2046 protected int mScrollX; 2047 /** 2048 * The offset, in pixels, by which the content of this view is scrolled 2049 * vertically. 2050 * {@hide} 2051 */ 2052 @ViewDebug.ExportedProperty(category = "scrolling") 2053 protected int mScrollY; 2054 2055 /** 2056 * The left padding in pixels, that is the distance in pixels between the 2057 * left edge of this view and the left edge of its content. 2058 * {@hide} 2059 */ 2060 @ViewDebug.ExportedProperty(category = "padding") 2061 protected int mPaddingLeft; 2062 /** 2063 * The right padding in pixels, that is the distance in pixels between the 2064 * right edge of this view and the right edge of its content. 2065 * {@hide} 2066 */ 2067 @ViewDebug.ExportedProperty(category = "padding") 2068 protected int mPaddingRight; 2069 /** 2070 * The top padding in pixels, that is the distance in pixels between the 2071 * top edge of this view and the top edge of its content. 2072 * {@hide} 2073 */ 2074 @ViewDebug.ExportedProperty(category = "padding") 2075 protected int mPaddingTop; 2076 /** 2077 * The bottom padding in pixels, that is the distance in pixels between the 2078 * bottom edge of this view and the bottom edge of its content. 2079 * {@hide} 2080 */ 2081 @ViewDebug.ExportedProperty(category = "padding") 2082 protected int mPaddingBottom; 2083 2084 /** 2085 * Briefly describes the view and is primarily used for accessibility support. 2086 */ 2087 private CharSequence mContentDescription; 2088 2089 /** 2090 * Cache the paddingRight set by the user to append to the scrollbar's size. 2091 */ 2092 @ViewDebug.ExportedProperty(category = "padding") 2093 int mUserPaddingRight; 2094 2095 /** 2096 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2097 */ 2098 @ViewDebug.ExportedProperty(category = "padding") 2099 int mUserPaddingBottom; 2100 2101 /** 2102 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2103 */ 2104 @ViewDebug.ExportedProperty(category = "padding") 2105 int mUserPaddingLeft; 2106 2107 /** 2108 * @hide 2109 */ 2110 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2111 /** 2112 * @hide 2113 */ 2114 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2115 2116 private Resources mResources = null; 2117 2118 private Drawable mBGDrawable; 2119 2120 private int mBackgroundResource; 2121 private boolean mBackgroundSizeChanged; 2122 2123 /** 2124 * Listener used to dispatch focus change events. 2125 * This field should be made private, so it is hidden from the SDK. 2126 * {@hide} 2127 */ 2128 protected OnFocusChangeListener mOnFocusChangeListener; 2129 2130 /** 2131 * Listeners for layout change events. 2132 */ 2133 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2134 2135 /** 2136 * Listeners for attach events. 2137 */ 2138 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2139 2140 /** 2141 * Listener used to dispatch click events. 2142 * This field should be made private, so it is hidden from the SDK. 2143 * {@hide} 2144 */ 2145 protected OnClickListener mOnClickListener; 2146 2147 /** 2148 * Listener used to dispatch long click events. 2149 * This field should be made private, so it is hidden from the SDK. 2150 * {@hide} 2151 */ 2152 protected OnLongClickListener mOnLongClickListener; 2153 2154 /** 2155 * Listener used to build the context menu. 2156 * This field should be made private, so it is hidden from the SDK. 2157 * {@hide} 2158 */ 2159 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2160 2161 private OnKeyListener mOnKeyListener; 2162 2163 private OnTouchListener mOnTouchListener; 2164 2165 private OnGenericMotionListener mOnGenericMotionListener; 2166 2167 private OnDragListener mOnDragListener; 2168 2169 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2170 2171 /** 2172 * The application environment this view lives in. 2173 * This field should be made private, so it is hidden from the SDK. 2174 * {@hide} 2175 */ 2176 protected Context mContext; 2177 2178 private ScrollabilityCache mScrollCache; 2179 2180 private int[] mDrawableState = null; 2181 2182 /** 2183 * Set to true when drawing cache is enabled and cannot be created. 2184 * 2185 * @hide 2186 */ 2187 public boolean mCachingFailed; 2188 2189 private Bitmap mDrawingCache; 2190 private Bitmap mUnscaledDrawingCache; 2191 private DisplayList mDisplayList; 2192 private HardwareLayer mHardwareLayer; 2193 2194 /** 2195 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2196 * the user may specify which view to go to next. 2197 */ 2198 private int mNextFocusLeftId = View.NO_ID; 2199 2200 /** 2201 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2202 * the user may specify which view to go to next. 2203 */ 2204 private int mNextFocusRightId = View.NO_ID; 2205 2206 /** 2207 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2208 * the user may specify which view to go to next. 2209 */ 2210 private int mNextFocusUpId = View.NO_ID; 2211 2212 /** 2213 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2214 * the user may specify which view to go to next. 2215 */ 2216 private int mNextFocusDownId = View.NO_ID; 2217 2218 /** 2219 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 2220 * the user may specify which view to go to next. 2221 */ 2222 int mNextFocusForwardId = View.NO_ID; 2223 2224 private CheckForLongPress mPendingCheckForLongPress; 2225 private CheckForTap mPendingCheckForTap = null; 2226 private PerformClick mPerformClick; 2227 2228 private UnsetPressedState mUnsetPressedState; 2229 2230 /** 2231 * Whether the long press's action has been invoked. The tap's action is invoked on the 2232 * up event while a long press is invoked as soon as the long press duration is reached, so 2233 * a long press could be performed before the tap is checked, in which case the tap's action 2234 * should not be invoked. 2235 */ 2236 private boolean mHasPerformedLongPress; 2237 2238 /** 2239 * The minimum height of the view. We'll try our best to have the height 2240 * of this view to at least this amount. 2241 */ 2242 @ViewDebug.ExportedProperty(category = "measurement") 2243 private int mMinHeight; 2244 2245 /** 2246 * The minimum width of the view. We'll try our best to have the width 2247 * of this view to at least this amount. 2248 */ 2249 @ViewDebug.ExportedProperty(category = "measurement") 2250 private int mMinWidth; 2251 2252 /** 2253 * The delegate to handle touch events that are physically in this view 2254 * but should be handled by another view. 2255 */ 2256 private TouchDelegate mTouchDelegate = null; 2257 2258 /** 2259 * Solid color to use as a background when creating the drawing cache. Enables 2260 * the cache to use 16 bit bitmaps instead of 32 bit. 2261 */ 2262 private int mDrawingCacheBackgroundColor = 0; 2263 2264 /** 2265 * Special tree observer used when mAttachInfo is null. 2266 */ 2267 private ViewTreeObserver mFloatingTreeObserver; 2268 2269 /** 2270 * Cache the touch slop from the context that created the view. 2271 */ 2272 private int mTouchSlop; 2273 2274 /** 2275 * Object that handles automatic animation of view properties. 2276 */ 2277 private ViewPropertyAnimator mAnimator = null; 2278 2279 /** 2280 * Flag indicating that a drag can cross window boundaries. When 2281 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 2282 * with this flag set, all visible applications will be able to participate 2283 * in the drag operation and receive the dragged content. 2284 * 2285 * @hide 2286 */ 2287 public static final int DRAG_FLAG_GLOBAL = 1; 2288 2289 /** 2290 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 2291 */ 2292 private float mVerticalScrollFactor; 2293 2294 /** 2295 * Position of the vertical scroll bar. 2296 */ 2297 private int mVerticalScrollbarPosition; 2298 2299 /** 2300 * Position the scroll bar at the default position as determined by the system. 2301 */ 2302 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 2303 2304 /** 2305 * Position the scroll bar along the left edge. 2306 */ 2307 public static final int SCROLLBAR_POSITION_LEFT = 1; 2308 2309 /** 2310 * Position the scroll bar along the right edge. 2311 */ 2312 public static final int SCROLLBAR_POSITION_RIGHT = 2; 2313 2314 /** 2315 * Indicates that the view does not have a layer. 2316 * 2317 * @see #getLayerType() 2318 * @see #setLayerType(int, android.graphics.Paint) 2319 * @see #LAYER_TYPE_SOFTWARE 2320 * @see #LAYER_TYPE_HARDWARE 2321 */ 2322 public static final int LAYER_TYPE_NONE = 0; 2323 2324 /** 2325 * <p>Indicates that the view has a software layer. A software layer is backed 2326 * by a bitmap and causes the view to be rendered using Android's software 2327 * rendering pipeline, even if hardware acceleration is enabled.</p> 2328 * 2329 * <p>Software layers have various usages:</p> 2330 * <p>When the application is not using hardware acceleration, a software layer 2331 * is useful to apply a specific color filter and/or blending mode and/or 2332 * translucency to a view and all its children.</p> 2333 * <p>When the application is using hardware acceleration, a software layer 2334 * is useful to render drawing primitives not supported by the hardware 2335 * accelerated pipeline. It can also be used to cache a complex view tree 2336 * into a texture and reduce the complexity of drawing operations. For instance, 2337 * when animating a complex view tree with a translation, a software layer can 2338 * be used to render the view tree only once.</p> 2339 * <p>Software layers should be avoided when the affected view tree updates 2340 * often. Every update will require to re-render the software layer, which can 2341 * potentially be slow (particularly when hardware acceleration is turned on 2342 * since the layer will have to be uploaded into a hardware texture after every 2343 * update.)</p> 2344 * 2345 * @see #getLayerType() 2346 * @see #setLayerType(int, android.graphics.Paint) 2347 * @see #LAYER_TYPE_NONE 2348 * @see #LAYER_TYPE_HARDWARE 2349 */ 2350 public static final int LAYER_TYPE_SOFTWARE = 1; 2351 2352 /** 2353 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 2354 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 2355 * OpenGL hardware) and causes the view to be rendered using Android's hardware 2356 * rendering pipeline, but only if hardware acceleration is turned on for the 2357 * view hierarchy. When hardware acceleration is turned off, hardware layers 2358 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 2359 * 2360 * <p>A hardware layer is useful to apply a specific color filter and/or 2361 * blending mode and/or translucency to a view and all its children.</p> 2362 * <p>A hardware layer can be used to cache a complex view tree into a 2363 * texture and reduce the complexity of drawing operations. For instance, 2364 * when animating a complex view tree with a translation, a hardware layer can 2365 * be used to render the view tree only once.</p> 2366 * <p>A hardware layer can also be used to increase the rendering quality when 2367 * rotation transformations are applied on a view. It can also be used to 2368 * prevent potential clipping issues when applying 3D transforms on a view.</p> 2369 * 2370 * @see #getLayerType() 2371 * @see #setLayerType(int, android.graphics.Paint) 2372 * @see #LAYER_TYPE_NONE 2373 * @see #LAYER_TYPE_SOFTWARE 2374 */ 2375 public static final int LAYER_TYPE_HARDWARE = 2; 2376 2377 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 2378 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 2379 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 2380 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 2381 }) 2382 int mLayerType = LAYER_TYPE_NONE; 2383 Paint mLayerPaint; 2384 Rect mLocalDirtyRect; 2385 2386 /** 2387 * Consistency verifier for debugging purposes. 2388 * @hide 2389 */ 2390 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 2391 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 2392 new InputEventConsistencyVerifier(this, 0) : null; 2393 2394 /** 2395 * Simple constructor to use when creating a view from code. 2396 * 2397 * @param context The Context the view is running in, through which it can 2398 * access the current theme, resources, etc. 2399 */ 2400 public View(Context context) { 2401 mContext = context; 2402 mResources = context != null ? context.getResources() : null; 2403 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 2404 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 2405 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 2406 } 2407 2408 /** 2409 * Constructor that is called when inflating a view from XML. This is called 2410 * when a view is being constructed from an XML file, supplying attributes 2411 * that were specified in the XML file. This version uses a default style of 2412 * 0, so the only attribute values applied are those in the Context's Theme 2413 * and the given AttributeSet. 2414 * 2415 * <p> 2416 * The method onFinishInflate() will be called after all children have been 2417 * added. 2418 * 2419 * @param context The Context the view is running in, through which it can 2420 * access the current theme, resources, etc. 2421 * @param attrs The attributes of the XML tag that is inflating the view. 2422 * @see #View(Context, AttributeSet, int) 2423 */ 2424 public View(Context context, AttributeSet attrs) { 2425 this(context, attrs, 0); 2426 } 2427 2428 /** 2429 * Perform inflation from XML and apply a class-specific base style. This 2430 * constructor of View allows subclasses to use their own base style when 2431 * they are inflating. For example, a Button class's constructor would call 2432 * this version of the super class constructor and supply 2433 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 2434 * the theme's button style to modify all of the base view attributes (in 2435 * particular its background) as well as the Button class's attributes. 2436 * 2437 * @param context The Context the view is running in, through which it can 2438 * access the current theme, resources, etc. 2439 * @param attrs The attributes of the XML tag that is inflating the view. 2440 * @param defStyle The default style to apply to this view. If 0, no style 2441 * will be applied (beyond what is included in the theme). This may 2442 * either be an attribute resource, whose value will be retrieved 2443 * from the current theme, or an explicit style resource. 2444 * @see #View(Context, AttributeSet) 2445 */ 2446 public View(Context context, AttributeSet attrs, int defStyle) { 2447 this(context); 2448 2449 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 2450 defStyle, 0); 2451 2452 Drawable background = null; 2453 2454 int leftPadding = -1; 2455 int topPadding = -1; 2456 int rightPadding = -1; 2457 int bottomPadding = -1; 2458 2459 int padding = -1; 2460 2461 int viewFlagValues = 0; 2462 int viewFlagMasks = 0; 2463 2464 boolean setScrollContainer = false; 2465 2466 int x = 0; 2467 int y = 0; 2468 2469 float tx = 0; 2470 float ty = 0; 2471 float rotation = 0; 2472 float rotationX = 0; 2473 float rotationY = 0; 2474 float sx = 1f; 2475 float sy = 1f; 2476 boolean transformSet = false; 2477 2478 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 2479 2480 int overScrollMode = mOverScrollMode; 2481 final int N = a.getIndexCount(); 2482 for (int i = 0; i < N; i++) { 2483 int attr = a.getIndex(i); 2484 switch (attr) { 2485 case com.android.internal.R.styleable.View_background: 2486 background = a.getDrawable(attr); 2487 break; 2488 case com.android.internal.R.styleable.View_padding: 2489 padding = a.getDimensionPixelSize(attr, -1); 2490 break; 2491 case com.android.internal.R.styleable.View_paddingLeft: 2492 leftPadding = a.getDimensionPixelSize(attr, -1); 2493 break; 2494 case com.android.internal.R.styleable.View_paddingTop: 2495 topPadding = a.getDimensionPixelSize(attr, -1); 2496 break; 2497 case com.android.internal.R.styleable.View_paddingRight: 2498 rightPadding = a.getDimensionPixelSize(attr, -1); 2499 break; 2500 case com.android.internal.R.styleable.View_paddingBottom: 2501 bottomPadding = a.getDimensionPixelSize(attr, -1); 2502 break; 2503 case com.android.internal.R.styleable.View_scrollX: 2504 x = a.getDimensionPixelOffset(attr, 0); 2505 break; 2506 case com.android.internal.R.styleable.View_scrollY: 2507 y = a.getDimensionPixelOffset(attr, 0); 2508 break; 2509 case com.android.internal.R.styleable.View_alpha: 2510 setAlpha(a.getFloat(attr, 1f)); 2511 break; 2512 case com.android.internal.R.styleable.View_transformPivotX: 2513 setPivotX(a.getDimensionPixelOffset(attr, 0)); 2514 break; 2515 case com.android.internal.R.styleable.View_transformPivotY: 2516 setPivotY(a.getDimensionPixelOffset(attr, 0)); 2517 break; 2518 case com.android.internal.R.styleable.View_translationX: 2519 tx = a.getDimensionPixelOffset(attr, 0); 2520 transformSet = true; 2521 break; 2522 case com.android.internal.R.styleable.View_translationY: 2523 ty = a.getDimensionPixelOffset(attr, 0); 2524 transformSet = true; 2525 break; 2526 case com.android.internal.R.styleable.View_rotation: 2527 rotation = a.getFloat(attr, 0); 2528 transformSet = true; 2529 break; 2530 case com.android.internal.R.styleable.View_rotationX: 2531 rotationX = a.getFloat(attr, 0); 2532 transformSet = true; 2533 break; 2534 case com.android.internal.R.styleable.View_rotationY: 2535 rotationY = a.getFloat(attr, 0); 2536 transformSet = true; 2537 break; 2538 case com.android.internal.R.styleable.View_scaleX: 2539 sx = a.getFloat(attr, 1f); 2540 transformSet = true; 2541 break; 2542 case com.android.internal.R.styleable.View_scaleY: 2543 sy = a.getFloat(attr, 1f); 2544 transformSet = true; 2545 break; 2546 case com.android.internal.R.styleable.View_id: 2547 mID = a.getResourceId(attr, NO_ID); 2548 break; 2549 case com.android.internal.R.styleable.View_tag: 2550 mTag = a.getText(attr); 2551 break; 2552 case com.android.internal.R.styleable.View_fitsSystemWindows: 2553 if (a.getBoolean(attr, false)) { 2554 viewFlagValues |= FITS_SYSTEM_WINDOWS; 2555 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 2556 } 2557 break; 2558 case com.android.internal.R.styleable.View_focusable: 2559 if (a.getBoolean(attr, false)) { 2560 viewFlagValues |= FOCUSABLE; 2561 viewFlagMasks |= FOCUSABLE_MASK; 2562 } 2563 break; 2564 case com.android.internal.R.styleable.View_focusableInTouchMode: 2565 if (a.getBoolean(attr, false)) { 2566 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 2567 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 2568 } 2569 break; 2570 case com.android.internal.R.styleable.View_clickable: 2571 if (a.getBoolean(attr, false)) { 2572 viewFlagValues |= CLICKABLE; 2573 viewFlagMasks |= CLICKABLE; 2574 } 2575 break; 2576 case com.android.internal.R.styleable.View_longClickable: 2577 if (a.getBoolean(attr, false)) { 2578 viewFlagValues |= LONG_CLICKABLE; 2579 viewFlagMasks |= LONG_CLICKABLE; 2580 } 2581 break; 2582 case com.android.internal.R.styleable.View_saveEnabled: 2583 if (!a.getBoolean(attr, true)) { 2584 viewFlagValues |= SAVE_DISABLED; 2585 viewFlagMasks |= SAVE_DISABLED_MASK; 2586 } 2587 break; 2588 case com.android.internal.R.styleable.View_duplicateParentState: 2589 if (a.getBoolean(attr, false)) { 2590 viewFlagValues |= DUPLICATE_PARENT_STATE; 2591 viewFlagMasks |= DUPLICATE_PARENT_STATE; 2592 } 2593 break; 2594 case com.android.internal.R.styleable.View_visibility: 2595 final int visibility = a.getInt(attr, 0); 2596 if (visibility != 0) { 2597 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 2598 viewFlagMasks |= VISIBILITY_MASK; 2599 } 2600 break; 2601 case com.android.internal.R.styleable.View_drawingCacheQuality: 2602 final int cacheQuality = a.getInt(attr, 0); 2603 if (cacheQuality != 0) { 2604 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 2605 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 2606 } 2607 break; 2608 case com.android.internal.R.styleable.View_contentDescription: 2609 mContentDescription = a.getString(attr); 2610 break; 2611 case com.android.internal.R.styleable.View_soundEffectsEnabled: 2612 if (!a.getBoolean(attr, true)) { 2613 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 2614 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 2615 } 2616 break; 2617 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 2618 if (!a.getBoolean(attr, true)) { 2619 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 2620 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 2621 } 2622 break; 2623 case R.styleable.View_scrollbars: 2624 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 2625 if (scrollbars != SCROLLBARS_NONE) { 2626 viewFlagValues |= scrollbars; 2627 viewFlagMasks |= SCROLLBARS_MASK; 2628 initializeScrollbars(a); 2629 } 2630 break; 2631 case R.styleable.View_fadingEdge: 2632 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 2633 if (fadingEdge != FADING_EDGE_NONE) { 2634 viewFlagValues |= fadingEdge; 2635 viewFlagMasks |= FADING_EDGE_MASK; 2636 initializeFadingEdge(a); 2637 } 2638 break; 2639 case R.styleable.View_scrollbarStyle: 2640 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 2641 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 2642 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 2643 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 2644 } 2645 break; 2646 case R.styleable.View_isScrollContainer: 2647 setScrollContainer = true; 2648 if (a.getBoolean(attr, false)) { 2649 setScrollContainer(true); 2650 } 2651 break; 2652 case com.android.internal.R.styleable.View_keepScreenOn: 2653 if (a.getBoolean(attr, false)) { 2654 viewFlagValues |= KEEP_SCREEN_ON; 2655 viewFlagMasks |= KEEP_SCREEN_ON; 2656 } 2657 break; 2658 case R.styleable.View_filterTouchesWhenObscured: 2659 if (a.getBoolean(attr, false)) { 2660 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 2661 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 2662 } 2663 break; 2664 case R.styleable.View_nextFocusLeft: 2665 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 2666 break; 2667 case R.styleable.View_nextFocusRight: 2668 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 2669 break; 2670 case R.styleable.View_nextFocusUp: 2671 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 2672 break; 2673 case R.styleable.View_nextFocusDown: 2674 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 2675 break; 2676 case R.styleable.View_nextFocusForward: 2677 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 2678 break; 2679 case R.styleable.View_minWidth: 2680 mMinWidth = a.getDimensionPixelSize(attr, 0); 2681 break; 2682 case R.styleable.View_minHeight: 2683 mMinHeight = a.getDimensionPixelSize(attr, 0); 2684 break; 2685 case R.styleable.View_onClick: 2686 if (context.isRestricted()) { 2687 throw new IllegalStateException("The android:onClick attribute cannot " 2688 + "be used within a restricted context"); 2689 } 2690 2691 final String handlerName = a.getString(attr); 2692 if (handlerName != null) { 2693 setOnClickListener(new OnClickListener() { 2694 private Method mHandler; 2695 2696 public void onClick(View v) { 2697 if (mHandler == null) { 2698 try { 2699 mHandler = getContext().getClass().getMethod(handlerName, 2700 View.class); 2701 } catch (NoSuchMethodException e) { 2702 int id = getId(); 2703 String idText = id == NO_ID ? "" : " with id '" 2704 + getContext().getResources().getResourceEntryName( 2705 id) + "'"; 2706 throw new IllegalStateException("Could not find a method " + 2707 handlerName + "(View) in the activity " 2708 + getContext().getClass() + " for onClick handler" 2709 + " on view " + View.this.getClass() + idText, e); 2710 } 2711 } 2712 2713 try { 2714 mHandler.invoke(getContext(), View.this); 2715 } catch (IllegalAccessException e) { 2716 throw new IllegalStateException("Could not execute non " 2717 + "public method of the activity", e); 2718 } catch (InvocationTargetException e) { 2719 throw new IllegalStateException("Could not execute " 2720 + "method of the activity", e); 2721 } 2722 } 2723 }); 2724 } 2725 break; 2726 case R.styleable.View_overScrollMode: 2727 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 2728 break; 2729 case R.styleable.View_verticalScrollbarPosition: 2730 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 2731 break; 2732 case R.styleable.View_layerType: 2733 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 2734 break; 2735 } 2736 } 2737 2738 setOverScrollMode(overScrollMode); 2739 2740 if (background != null) { 2741 setBackgroundDrawable(background); 2742 } 2743 2744 if (padding >= 0) { 2745 leftPadding = padding; 2746 topPadding = padding; 2747 rightPadding = padding; 2748 bottomPadding = padding; 2749 } 2750 2751 // If the user specified the padding (either with android:padding or 2752 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 2753 // use the default padding or the padding from the background drawable 2754 // (stored at this point in mPadding*) 2755 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft, 2756 topPadding >= 0 ? topPadding : mPaddingTop, 2757 rightPadding >= 0 ? rightPadding : mPaddingRight, 2758 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 2759 2760 if (viewFlagMasks != 0) { 2761 setFlags(viewFlagValues, viewFlagMasks); 2762 } 2763 2764 // Needs to be called after mViewFlags is set 2765 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 2766 recomputePadding(); 2767 } 2768 2769 if (x != 0 || y != 0) { 2770 scrollTo(x, y); 2771 } 2772 2773 if (transformSet) { 2774 setTranslationX(tx); 2775 setTranslationY(ty); 2776 setRotation(rotation); 2777 setRotationX(rotationX); 2778 setRotationY(rotationY); 2779 setScaleX(sx); 2780 setScaleY(sy); 2781 } 2782 2783 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 2784 setScrollContainer(true); 2785 } 2786 2787 computeOpaqueFlags(); 2788 2789 a.recycle(); 2790 } 2791 2792 /** 2793 * Non-public constructor for use in testing 2794 */ 2795 View() { 2796 } 2797 2798 /** 2799 * <p> 2800 * Initializes the fading edges from a given set of styled attributes. This 2801 * method should be called by subclasses that need fading edges and when an 2802 * instance of these subclasses is created programmatically rather than 2803 * being inflated from XML. This method is automatically called when the XML 2804 * is inflated. 2805 * </p> 2806 * 2807 * @param a the styled attributes set to initialize the fading edges from 2808 */ 2809 protected void initializeFadingEdge(TypedArray a) { 2810 initScrollCache(); 2811 2812 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 2813 R.styleable.View_fadingEdgeLength, 2814 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 2815 } 2816 2817 /** 2818 * Returns the size of the vertical faded edges used to indicate that more 2819 * content in this view is visible. 2820 * 2821 * @return The size in pixels of the vertical faded edge or 0 if vertical 2822 * faded edges are not enabled for this view. 2823 * @attr ref android.R.styleable#View_fadingEdgeLength 2824 */ 2825 public int getVerticalFadingEdgeLength() { 2826 if (isVerticalFadingEdgeEnabled()) { 2827 ScrollabilityCache cache = mScrollCache; 2828 if (cache != null) { 2829 return cache.fadingEdgeLength; 2830 } 2831 } 2832 return 0; 2833 } 2834 2835 /** 2836 * Set the size of the faded edge used to indicate that more content in this 2837 * view is available. Will not change whether the fading edge is enabled; use 2838 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 2839 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 2840 * for the vertical or horizontal fading edges. 2841 * 2842 * @param length The size in pixels of the faded edge used to indicate that more 2843 * content in this view is visible. 2844 */ 2845 public void setFadingEdgeLength(int length) { 2846 initScrollCache(); 2847 mScrollCache.fadingEdgeLength = length; 2848 } 2849 2850 /** 2851 * Returns the size of the horizontal faded edges used to indicate that more 2852 * content in this view is visible. 2853 * 2854 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 2855 * faded edges are not enabled for this view. 2856 * @attr ref android.R.styleable#View_fadingEdgeLength 2857 */ 2858 public int getHorizontalFadingEdgeLength() { 2859 if (isHorizontalFadingEdgeEnabled()) { 2860 ScrollabilityCache cache = mScrollCache; 2861 if (cache != null) { 2862 return cache.fadingEdgeLength; 2863 } 2864 } 2865 return 0; 2866 } 2867 2868 /** 2869 * Returns the width of the vertical scrollbar. 2870 * 2871 * @return The width in pixels of the vertical scrollbar or 0 if there 2872 * is no vertical scrollbar. 2873 */ 2874 public int getVerticalScrollbarWidth() { 2875 ScrollabilityCache cache = mScrollCache; 2876 if (cache != null) { 2877 ScrollBarDrawable scrollBar = cache.scrollBar; 2878 if (scrollBar != null) { 2879 int size = scrollBar.getSize(true); 2880 if (size <= 0) { 2881 size = cache.scrollBarSize; 2882 } 2883 return size; 2884 } 2885 return 0; 2886 } 2887 return 0; 2888 } 2889 2890 /** 2891 * Returns the height of the horizontal scrollbar. 2892 * 2893 * @return The height in pixels of the horizontal scrollbar or 0 if 2894 * there is no horizontal scrollbar. 2895 */ 2896 protected int getHorizontalScrollbarHeight() { 2897 ScrollabilityCache cache = mScrollCache; 2898 if (cache != null) { 2899 ScrollBarDrawable scrollBar = cache.scrollBar; 2900 if (scrollBar != null) { 2901 int size = scrollBar.getSize(false); 2902 if (size <= 0) { 2903 size = cache.scrollBarSize; 2904 } 2905 return size; 2906 } 2907 return 0; 2908 } 2909 return 0; 2910 } 2911 2912 /** 2913 * <p> 2914 * Initializes the scrollbars from a given set of styled attributes. This 2915 * method should be called by subclasses that need scrollbars and when an 2916 * instance of these subclasses is created programmatically rather than 2917 * being inflated from XML. This method is automatically called when the XML 2918 * is inflated. 2919 * </p> 2920 * 2921 * @param a the styled attributes set to initialize the scrollbars from 2922 */ 2923 protected void initializeScrollbars(TypedArray a) { 2924 initScrollCache(); 2925 2926 final ScrollabilityCache scrollabilityCache = mScrollCache; 2927 2928 if (scrollabilityCache.scrollBar == null) { 2929 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 2930 } 2931 2932 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 2933 2934 if (!fadeScrollbars) { 2935 scrollabilityCache.state = ScrollabilityCache.ON; 2936 } 2937 scrollabilityCache.fadeScrollBars = fadeScrollbars; 2938 2939 2940 scrollabilityCache.scrollBarFadeDuration = a.getInt( 2941 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 2942 .getScrollBarFadeDuration()); 2943 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 2944 R.styleable.View_scrollbarDefaultDelayBeforeFade, 2945 ViewConfiguration.getScrollDefaultDelay()); 2946 2947 2948 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 2949 com.android.internal.R.styleable.View_scrollbarSize, 2950 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 2951 2952 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 2953 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 2954 2955 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 2956 if (thumb != null) { 2957 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 2958 } 2959 2960 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 2961 false); 2962 if (alwaysDraw) { 2963 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 2964 } 2965 2966 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 2967 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 2968 2969 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 2970 if (thumb != null) { 2971 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 2972 } 2973 2974 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 2975 false); 2976 if (alwaysDraw) { 2977 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 2978 } 2979 2980 // Re-apply user/background padding so that scrollbar(s) get added 2981 recomputePadding(); 2982 } 2983 2984 /** 2985 * <p> 2986 * Initalizes the scrollability cache if necessary. 2987 * </p> 2988 */ 2989 private void initScrollCache() { 2990 if (mScrollCache == null) { 2991 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 2992 } 2993 } 2994 2995 /** 2996 * Set the position of the vertical scroll bar. Should be one of 2997 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 2998 * {@link #SCROLLBAR_POSITION_RIGHT}. 2999 * 3000 * @param position Where the vertical scroll bar should be positioned. 3001 */ 3002 public void setVerticalScrollbarPosition(int position) { 3003 if (mVerticalScrollbarPosition != position) { 3004 mVerticalScrollbarPosition = position; 3005 computeOpaqueFlags(); 3006 recomputePadding(); 3007 } 3008 } 3009 3010 /** 3011 * @return The position where the vertical scroll bar will show, if applicable. 3012 * @see #setVerticalScrollbarPosition(int) 3013 */ 3014 public int getVerticalScrollbarPosition() { 3015 return mVerticalScrollbarPosition; 3016 } 3017 3018 /** 3019 * Register a callback to be invoked when focus of this view changed. 3020 * 3021 * @param l The callback that will run. 3022 */ 3023 public void setOnFocusChangeListener(OnFocusChangeListener l) { 3024 mOnFocusChangeListener = l; 3025 } 3026 3027 /** 3028 * Add a listener that will be called when the bounds of the view change due to 3029 * layout processing. 3030 * 3031 * @param listener The listener that will be called when layout bounds change. 3032 */ 3033 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 3034 if (mOnLayoutChangeListeners == null) { 3035 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 3036 } 3037 mOnLayoutChangeListeners.add(listener); 3038 } 3039 3040 /** 3041 * Remove a listener for layout changes. 3042 * 3043 * @param listener The listener for layout bounds change. 3044 */ 3045 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 3046 if (mOnLayoutChangeListeners == null) { 3047 return; 3048 } 3049 mOnLayoutChangeListeners.remove(listener); 3050 } 3051 3052 /** 3053 * Add a listener for attach state changes. 3054 * 3055 * This listener will be called whenever this view is attached or detached 3056 * from a window. Remove the listener using 3057 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 3058 * 3059 * @param listener Listener to attach 3060 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 3061 */ 3062 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3063 if (mOnAttachStateChangeListeners == null) { 3064 mOnAttachStateChangeListeners = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 3065 } 3066 mOnAttachStateChangeListeners.add(listener); 3067 } 3068 3069 /** 3070 * Remove a listener for attach state changes. The listener will receive no further 3071 * notification of window attach/detach events. 3072 * 3073 * @param listener Listener to remove 3074 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 3075 */ 3076 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3077 if (mOnAttachStateChangeListeners == null) { 3078 return; 3079 } 3080 mOnAttachStateChangeListeners.remove(listener); 3081 } 3082 3083 /** 3084 * Returns the focus-change callback registered for this view. 3085 * 3086 * @return The callback, or null if one is not registered. 3087 */ 3088 public OnFocusChangeListener getOnFocusChangeListener() { 3089 return mOnFocusChangeListener; 3090 } 3091 3092 /** 3093 * Register a callback to be invoked when this view is clicked. If this view is not 3094 * clickable, it becomes clickable. 3095 * 3096 * @param l The callback that will run 3097 * 3098 * @see #setClickable(boolean) 3099 */ 3100 public void setOnClickListener(OnClickListener l) { 3101 if (!isClickable()) { 3102 setClickable(true); 3103 } 3104 mOnClickListener = l; 3105 } 3106 3107 /** 3108 * Register a callback to be invoked when this view is clicked and held. If this view is not 3109 * long clickable, it becomes long clickable. 3110 * 3111 * @param l The callback that will run 3112 * 3113 * @see #setLongClickable(boolean) 3114 */ 3115 public void setOnLongClickListener(OnLongClickListener l) { 3116 if (!isLongClickable()) { 3117 setLongClickable(true); 3118 } 3119 mOnLongClickListener = l; 3120 } 3121 3122 /** 3123 * Register a callback to be invoked when the context menu for this view is 3124 * being built. If this view is not long clickable, it becomes long clickable. 3125 * 3126 * @param l The callback that will run 3127 * 3128 */ 3129 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 3130 if (!isLongClickable()) { 3131 setLongClickable(true); 3132 } 3133 mOnCreateContextMenuListener = l; 3134 } 3135 3136 /** 3137 * Call this view's OnClickListener, if it is defined. 3138 * 3139 * @return True there was an assigned OnClickListener that was called, false 3140 * otherwise is returned. 3141 */ 3142 public boolean performClick() { 3143 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 3144 3145 if (mOnClickListener != null) { 3146 playSoundEffect(SoundEffectConstants.CLICK); 3147 mOnClickListener.onClick(this); 3148 return true; 3149 } 3150 3151 return false; 3152 } 3153 3154 /** 3155 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 3156 * OnLongClickListener did not consume the event. 3157 * 3158 * @return True if one of the above receivers consumed the event, false otherwise. 3159 */ 3160 public boolean performLongClick() { 3161 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 3162 3163 boolean handled = false; 3164 if (mOnLongClickListener != null) { 3165 handled = mOnLongClickListener.onLongClick(View.this); 3166 } 3167 if (!handled) { 3168 handled = showContextMenu(); 3169 } 3170 if (handled) { 3171 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 3172 } 3173 return handled; 3174 } 3175 3176 /** 3177 * Performs button-related actions during a touch down event. 3178 * 3179 * @param event The event. 3180 * @return True if the down was consumed. 3181 * 3182 * @hide 3183 */ 3184 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 3185 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 3186 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 3187 return true; 3188 } 3189 } 3190 return false; 3191 } 3192 3193 /** 3194 * Bring up the context menu for this view. 3195 * 3196 * @return Whether a context menu was displayed. 3197 */ 3198 public boolean showContextMenu() { 3199 return getParent().showContextMenuForChild(this); 3200 } 3201 3202 /** 3203 * Bring up the context menu for this view, referring to the item under the specified point. 3204 * 3205 * @param x The referenced x coordinate. 3206 * @param y The referenced y coordinate. 3207 * @param metaState The keyboard modifiers that were pressed. 3208 * @return Whether a context menu was displayed. 3209 * 3210 * @hide 3211 */ 3212 public boolean showContextMenu(float x, float y, int metaState) { 3213 return showContextMenu(); 3214 } 3215 3216 /** 3217 * Start an action mode. 3218 * 3219 * @param callback Callback that will control the lifecycle of the action mode 3220 * @return The new action mode if it is started, null otherwise 3221 * 3222 * @see ActionMode 3223 */ 3224 public ActionMode startActionMode(ActionMode.Callback callback) { 3225 return getParent().startActionModeForChild(this, callback); 3226 } 3227 3228 /** 3229 * Register a callback to be invoked when a key is pressed in this view. 3230 * @param l the key listener to attach to this view 3231 */ 3232 public void setOnKeyListener(OnKeyListener l) { 3233 mOnKeyListener = l; 3234 } 3235 3236 /** 3237 * Register a callback to be invoked when a touch event is sent to this view. 3238 * @param l the touch listener to attach to this view 3239 */ 3240 public void setOnTouchListener(OnTouchListener l) { 3241 mOnTouchListener = l; 3242 } 3243 3244 /** 3245 * Register a callback to be invoked when a generic motion event is sent to this view. 3246 * @param l the generic motion listener to attach to this view 3247 */ 3248 public void setOnGenericMotionListener(OnGenericMotionListener l) { 3249 mOnGenericMotionListener = l; 3250 } 3251 3252 /** 3253 * Register a drag event listener callback object for this View. The parameter is 3254 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 3255 * View, the system calls the 3256 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 3257 * @param l An implementation of {@link android.view.View.OnDragListener}. 3258 */ 3259 public void setOnDragListener(OnDragListener l) { 3260 mOnDragListener = l; 3261 } 3262 3263 /** 3264 * Give this view focus. This will cause 3265 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3266 * 3267 * Note: this does not check whether this {@link View} should get focus, it just 3268 * gives it focus no matter what. It should only be called internally by framework 3269 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 3270 * 3271 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 3272 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 3273 * focus moved when requestFocus() is called. It may not always 3274 * apply, in which case use the default View.FOCUS_DOWN. 3275 * @param previouslyFocusedRect The rectangle of the view that had focus 3276 * prior in this View's coordinate system. 3277 */ 3278 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 3279 if (DBG) { 3280 System.out.println(this + " requestFocus()"); 3281 } 3282 3283 if ((mPrivateFlags & FOCUSED) == 0) { 3284 mPrivateFlags |= FOCUSED; 3285 3286 if (mParent != null) { 3287 mParent.requestChildFocus(this, this); 3288 } 3289 3290 onFocusChanged(true, direction, previouslyFocusedRect); 3291 refreshDrawableState(); 3292 } 3293 } 3294 3295 /** 3296 * Request that a rectangle of this view be visible on the screen, 3297 * scrolling if necessary just enough. 3298 * 3299 * <p>A View should call this if it maintains some notion of which part 3300 * of its content is interesting. For example, a text editing view 3301 * should call this when its cursor moves. 3302 * 3303 * @param rectangle The rectangle. 3304 * @return Whether any parent scrolled. 3305 */ 3306 public boolean requestRectangleOnScreen(Rect rectangle) { 3307 return requestRectangleOnScreen(rectangle, false); 3308 } 3309 3310 /** 3311 * Request that a rectangle of this view be visible on the screen, 3312 * scrolling if necessary just enough. 3313 * 3314 * <p>A View should call this if it maintains some notion of which part 3315 * of its content is interesting. For example, a text editing view 3316 * should call this when its cursor moves. 3317 * 3318 * <p>When <code>immediate</code> is set to true, scrolling will not be 3319 * animated. 3320 * 3321 * @param rectangle The rectangle. 3322 * @param immediate True to forbid animated scrolling, false otherwise 3323 * @return Whether any parent scrolled. 3324 */ 3325 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 3326 View child = this; 3327 ViewParent parent = mParent; 3328 boolean scrolled = false; 3329 while (parent != null) { 3330 scrolled |= parent.requestChildRectangleOnScreen(child, 3331 rectangle, immediate); 3332 3333 // offset rect so next call has the rectangle in the 3334 // coordinate system of its direct child. 3335 rectangle.offset(child.getLeft(), child.getTop()); 3336 rectangle.offset(-child.getScrollX(), -child.getScrollY()); 3337 3338 if (!(parent instanceof View)) { 3339 break; 3340 } 3341 3342 child = (View) parent; 3343 parent = child.getParent(); 3344 } 3345 return scrolled; 3346 } 3347 3348 /** 3349 * Called when this view wants to give up focus. This will cause 3350 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3351 */ 3352 public void clearFocus() { 3353 if (DBG) { 3354 System.out.println(this + " clearFocus()"); 3355 } 3356 3357 if ((mPrivateFlags & FOCUSED) != 0) { 3358 mPrivateFlags &= ~FOCUSED; 3359 3360 if (mParent != null) { 3361 mParent.clearChildFocus(this); 3362 } 3363 3364 onFocusChanged(false, 0, null); 3365 refreshDrawableState(); 3366 } 3367 } 3368 3369 /** 3370 * Called to clear the focus of a view that is about to be removed. 3371 * Doesn't call clearChildFocus, which prevents this view from taking 3372 * focus again before it has been removed from the parent 3373 */ 3374 void clearFocusForRemoval() { 3375 if ((mPrivateFlags & FOCUSED) != 0) { 3376 mPrivateFlags &= ~FOCUSED; 3377 3378 onFocusChanged(false, 0, null); 3379 refreshDrawableState(); 3380 } 3381 } 3382 3383 /** 3384 * Called internally by the view system when a new view is getting focus. 3385 * This is what clears the old focus. 3386 */ 3387 void unFocus() { 3388 if (DBG) { 3389 System.out.println(this + " unFocus()"); 3390 } 3391 3392 if ((mPrivateFlags & FOCUSED) != 0) { 3393 mPrivateFlags &= ~FOCUSED; 3394 3395 onFocusChanged(false, 0, null); 3396 refreshDrawableState(); 3397 } 3398 } 3399 3400 /** 3401 * Returns true if this view has focus iteself, or is the ancestor of the 3402 * view that has focus. 3403 * 3404 * @return True if this view has or contains focus, false otherwise. 3405 */ 3406 @ViewDebug.ExportedProperty(category = "focus") 3407 public boolean hasFocus() { 3408 return (mPrivateFlags & FOCUSED) != 0; 3409 } 3410 3411 /** 3412 * Returns true if this view is focusable or if it contains a reachable View 3413 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 3414 * is a View whose parents do not block descendants focus. 3415 * 3416 * Only {@link #VISIBLE} views are considered focusable. 3417 * 3418 * @return True if the view is focusable or if the view contains a focusable 3419 * View, false otherwise. 3420 * 3421 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 3422 */ 3423 public boolean hasFocusable() { 3424 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 3425 } 3426 3427 /** 3428 * Called by the view system when the focus state of this view changes. 3429 * When the focus change event is caused by directional navigation, direction 3430 * and previouslyFocusedRect provide insight into where the focus is coming from. 3431 * When overriding, be sure to call up through to the super class so that 3432 * the standard focus handling will occur. 3433 * 3434 * @param gainFocus True if the View has focus; false otherwise. 3435 * @param direction The direction focus has moved when requestFocus() 3436 * is called to give this view focus. Values are 3437 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 3438 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 3439 * It may not always apply, in which case use the default. 3440 * @param previouslyFocusedRect The rectangle, in this view's coordinate 3441 * system, of the previously focused view. If applicable, this will be 3442 * passed in as finer grained information about where the focus is coming 3443 * from (in addition to direction). Will be <code>null</code> otherwise. 3444 */ 3445 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 3446 if (gainFocus) { 3447 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 3448 } 3449 3450 InputMethodManager imm = InputMethodManager.peekInstance(); 3451 if (!gainFocus) { 3452 if (isPressed()) { 3453 setPressed(false); 3454 } 3455 if (imm != null && mAttachInfo != null 3456 && mAttachInfo.mHasWindowFocus) { 3457 imm.focusOut(this); 3458 } 3459 onFocusLost(); 3460 } else if (imm != null && mAttachInfo != null 3461 && mAttachInfo.mHasWindowFocus) { 3462 imm.focusIn(this); 3463 } 3464 3465 invalidate(true); 3466 if (mOnFocusChangeListener != null) { 3467 mOnFocusChangeListener.onFocusChange(this, gainFocus); 3468 } 3469 3470 if (mAttachInfo != null) { 3471 mAttachInfo.mKeyDispatchState.reset(this); 3472 } 3473 } 3474 3475 /** 3476 * Sends an accessibility event of the given type. If accessiiblity is 3477 * not enabled this method has no effect. The default implementation calls 3478 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 3479 * to populate information about the event source (this View), then calls 3480 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 3481 * populate the text content of the event source including its descendants, 3482 * and last calls 3483 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 3484 * on its parent to resuest sending of the event to interested parties. 3485 * 3486 * @param eventType The type of the event to send. 3487 * 3488 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 3489 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3490 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 3491 */ 3492 public void sendAccessibilityEvent(int eventType) { 3493 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 3494 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 3495 } 3496 } 3497 3498 /** 3499 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 3500 * takes as an argument an empty {@link AccessibilityEvent} and does not 3501 * perfrom a check whether accessibility is enabled. 3502 * 3503 * @param event The event to send. 3504 * 3505 * @see #sendAccessibilityEvent(int) 3506 */ 3507 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 3508 if (!isShown()) { 3509 return; 3510 } 3511 onInitializeAccessibilityEvent(event); 3512 dispatchPopulateAccessibilityEvent(event); 3513 // In the beginning we called #isShown(), so we know that getParent() is not null. 3514 getParent().requestSendAccessibilityEvent(this, event); 3515 } 3516 3517 /** 3518 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 3519 * to its children for adding their text content to the event. Note that the 3520 * event text is populated in a separate dispatch path since we add to the 3521 * event not only the text of the source but also the text of all its descendants. 3522 * </p> 3523 * A typical implementation will call 3524 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 3525 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3526 * on each child. Override this method if custom population of the event text 3527 * content is required. 3528 * 3529 * @param event The event. 3530 * 3531 * @return True if the event population was completed. 3532 */ 3533 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 3534 onPopulateAccessibilityEvent(event); 3535 return false; 3536 } 3537 3538 /** 3539 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3540 * giving a chance to this View to populate the accessibility event with its 3541 * text content. While the implementation is free to modify other event 3542 * attributes this should be performed in 3543 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 3544 * <p> 3545 * Example: Adding formatted date string to an accessibility event in addition 3546 * to the text added by the super implementation. 3547 * </p><p><pre><code> 3548 * public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3549 * super.onPopulateAccessibilityEvent(event); 3550 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 3551 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 3552 * mCurrentDate.getTimeInMillis(), flags); 3553 * event.getText().add(selectedDateUtterance); 3554 * } 3555 * </code></pre></p> 3556 * 3557 * @param event The accessibility event which to populate. 3558 * 3559 * @see #sendAccessibilityEvent(int) 3560 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3561 */ 3562 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3563 3564 } 3565 3566 /** 3567 * Initializes an {@link AccessibilityEvent} with information about the 3568 * the type of the event and this View which is the event source. In other 3569 * words, the source of an accessibility event is the view whose state 3570 * change triggered firing the event. 3571 * <p> 3572 * Example: Setting the password property of an event in addition 3573 * to properties set by the super implementation. 3574 * </p><p><pre><code> 3575 * public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 3576 * super.onInitializeAccessibilityEvent(event); 3577 * event.setPassword(true); 3578 * } 3579 * </code></pre></p> 3580 * @param event The event to initialeze. 3581 * 3582 * @see #sendAccessibilityEvent(int) 3583 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3584 */ 3585 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 3586 event.setClassName(getClass().getName()); 3587 event.setPackageName(getContext().getPackageName()); 3588 event.setEnabled(isEnabled()); 3589 event.setContentDescription(mContentDescription); 3590 3591 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) { 3592 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList; 3593 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 3594 event.setItemCount(focusablesTempList.size()); 3595 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 3596 focusablesTempList.clear(); 3597 } 3598 } 3599 3600 /** 3601 * Gets the {@link View} description. It briefly describes the view and is 3602 * primarily used for accessibility support. Set this property to enable 3603 * better accessibility support for your application. This is especially 3604 * true for views that do not have textual representation (For example, 3605 * ImageButton). 3606 * 3607 * @return The content descriptiopn. 3608 * 3609 * @attr ref android.R.styleable#View_contentDescription 3610 */ 3611 public CharSequence getContentDescription() { 3612 return mContentDescription; 3613 } 3614 3615 /** 3616 * Sets the {@link View} description. It briefly describes the view and is 3617 * primarily used for accessibility support. Set this property to enable 3618 * better accessibility support for your application. This is especially 3619 * true for views that do not have textual representation (For example, 3620 * ImageButton). 3621 * 3622 * @param contentDescription The content description. 3623 * 3624 * @attr ref android.R.styleable#View_contentDescription 3625 */ 3626 public void setContentDescription(CharSequence contentDescription) { 3627 mContentDescription = contentDescription; 3628 } 3629 3630 /** 3631 * Invoked whenever this view loses focus, either by losing window focus or by losing 3632 * focus within its window. This method can be used to clear any state tied to the 3633 * focus. For instance, if a button is held pressed with the trackball and the window 3634 * loses focus, this method can be used to cancel the press. 3635 * 3636 * Subclasses of View overriding this method should always call super.onFocusLost(). 3637 * 3638 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 3639 * @see #onWindowFocusChanged(boolean) 3640 * 3641 * @hide pending API council approval 3642 */ 3643 protected void onFocusLost() { 3644 resetPressedState(); 3645 } 3646 3647 private void resetPressedState() { 3648 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 3649 return; 3650 } 3651 3652 if (isPressed()) { 3653 setPressed(false); 3654 3655 if (!mHasPerformedLongPress) { 3656 removeLongPressCallback(); 3657 } 3658 } 3659 } 3660 3661 /** 3662 * Returns true if this view has focus 3663 * 3664 * @return True if this view has focus, false otherwise. 3665 */ 3666 @ViewDebug.ExportedProperty(category = "focus") 3667 public boolean isFocused() { 3668 return (mPrivateFlags & FOCUSED) != 0; 3669 } 3670 3671 /** 3672 * Find the view in the hierarchy rooted at this view that currently has 3673 * focus. 3674 * 3675 * @return The view that currently has focus, or null if no focused view can 3676 * be found. 3677 */ 3678 public View findFocus() { 3679 return (mPrivateFlags & FOCUSED) != 0 ? this : null; 3680 } 3681 3682 /** 3683 * Change whether this view is one of the set of scrollable containers in 3684 * its window. This will be used to determine whether the window can 3685 * resize or must pan when a soft input area is open -- scrollable 3686 * containers allow the window to use resize mode since the container 3687 * will appropriately shrink. 3688 */ 3689 public void setScrollContainer(boolean isScrollContainer) { 3690 if (isScrollContainer) { 3691 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) { 3692 mAttachInfo.mScrollContainers.add(this); 3693 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 3694 } 3695 mPrivateFlags |= SCROLL_CONTAINER; 3696 } else { 3697 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 3698 mAttachInfo.mScrollContainers.remove(this); 3699 } 3700 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED); 3701 } 3702 } 3703 3704 /** 3705 * Returns the quality of the drawing cache. 3706 * 3707 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 3708 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 3709 * 3710 * @see #setDrawingCacheQuality(int) 3711 * @see #setDrawingCacheEnabled(boolean) 3712 * @see #isDrawingCacheEnabled() 3713 * 3714 * @attr ref android.R.styleable#View_drawingCacheQuality 3715 */ 3716 public int getDrawingCacheQuality() { 3717 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 3718 } 3719 3720 /** 3721 * Set the drawing cache quality of this view. This value is used only when the 3722 * drawing cache is enabled 3723 * 3724 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 3725 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 3726 * 3727 * @see #getDrawingCacheQuality() 3728 * @see #setDrawingCacheEnabled(boolean) 3729 * @see #isDrawingCacheEnabled() 3730 * 3731 * @attr ref android.R.styleable#View_drawingCacheQuality 3732 */ 3733 public void setDrawingCacheQuality(int quality) { 3734 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 3735 } 3736 3737 /** 3738 * Returns whether the screen should remain on, corresponding to the current 3739 * value of {@link #KEEP_SCREEN_ON}. 3740 * 3741 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 3742 * 3743 * @see #setKeepScreenOn(boolean) 3744 * 3745 * @attr ref android.R.styleable#View_keepScreenOn 3746 */ 3747 public boolean getKeepScreenOn() { 3748 return (mViewFlags & KEEP_SCREEN_ON) != 0; 3749 } 3750 3751 /** 3752 * Controls whether the screen should remain on, modifying the 3753 * value of {@link #KEEP_SCREEN_ON}. 3754 * 3755 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 3756 * 3757 * @see #getKeepScreenOn() 3758 * 3759 * @attr ref android.R.styleable#View_keepScreenOn 3760 */ 3761 public void setKeepScreenOn(boolean keepScreenOn) { 3762 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 3763 } 3764 3765 /** 3766 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 3767 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 3768 * 3769 * @attr ref android.R.styleable#View_nextFocusLeft 3770 */ 3771 public int getNextFocusLeftId() { 3772 return mNextFocusLeftId; 3773 } 3774 3775 /** 3776 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 3777 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 3778 * decide automatically. 3779 * 3780 * @attr ref android.R.styleable#View_nextFocusLeft 3781 */ 3782 public void setNextFocusLeftId(int nextFocusLeftId) { 3783 mNextFocusLeftId = nextFocusLeftId; 3784 } 3785 3786 /** 3787 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 3788 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 3789 * 3790 * @attr ref android.R.styleable#View_nextFocusRight 3791 */ 3792 public int getNextFocusRightId() { 3793 return mNextFocusRightId; 3794 } 3795 3796 /** 3797 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 3798 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 3799 * decide automatically. 3800 * 3801 * @attr ref android.R.styleable#View_nextFocusRight 3802 */ 3803 public void setNextFocusRightId(int nextFocusRightId) { 3804 mNextFocusRightId = nextFocusRightId; 3805 } 3806 3807 /** 3808 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 3809 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 3810 * 3811 * @attr ref android.R.styleable#View_nextFocusUp 3812 */ 3813 public int getNextFocusUpId() { 3814 return mNextFocusUpId; 3815 } 3816 3817 /** 3818 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 3819 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 3820 * decide automatically. 3821 * 3822 * @attr ref android.R.styleable#View_nextFocusUp 3823 */ 3824 public void setNextFocusUpId(int nextFocusUpId) { 3825 mNextFocusUpId = nextFocusUpId; 3826 } 3827 3828 /** 3829 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 3830 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 3831 * 3832 * @attr ref android.R.styleable#View_nextFocusDown 3833 */ 3834 public int getNextFocusDownId() { 3835 return mNextFocusDownId; 3836 } 3837 3838 /** 3839 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 3840 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 3841 * decide automatically. 3842 * 3843 * @attr ref android.R.styleable#View_nextFocusDown 3844 */ 3845 public void setNextFocusDownId(int nextFocusDownId) { 3846 mNextFocusDownId = nextFocusDownId; 3847 } 3848 3849 /** 3850 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 3851 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 3852 * 3853 * @attr ref android.R.styleable#View_nextFocusForward 3854 */ 3855 public int getNextFocusForwardId() { 3856 return mNextFocusForwardId; 3857 } 3858 3859 /** 3860 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 3861 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 3862 * decide automatically. 3863 * 3864 * @attr ref android.R.styleable#View_nextFocusForward 3865 */ 3866 public void setNextFocusForwardId(int nextFocusForwardId) { 3867 mNextFocusForwardId = nextFocusForwardId; 3868 } 3869 3870 /** 3871 * Returns the visibility of this view and all of its ancestors 3872 * 3873 * @return True if this view and all of its ancestors are {@link #VISIBLE} 3874 */ 3875 public boolean isShown() { 3876 View current = this; 3877 //noinspection ConstantConditions 3878 do { 3879 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 3880 return false; 3881 } 3882 ViewParent parent = current.mParent; 3883 if (parent == null) { 3884 return false; // We are not attached to the view root 3885 } 3886 if (!(parent instanceof View)) { 3887 return true; 3888 } 3889 current = (View) parent; 3890 } while (current != null); 3891 3892 return false; 3893 } 3894 3895 /** 3896 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag 3897 * is set 3898 * 3899 * @param insets Insets for system windows 3900 * 3901 * @return True if this view applied the insets, false otherwise 3902 */ 3903 protected boolean fitSystemWindows(Rect insets) { 3904 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 3905 mPaddingLeft = insets.left; 3906 mPaddingTop = insets.top; 3907 mPaddingRight = insets.right; 3908 mPaddingBottom = insets.bottom; 3909 requestLayout(); 3910 return true; 3911 } 3912 return false; 3913 } 3914 3915 /** 3916 * Returns the visibility status for this view. 3917 * 3918 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 3919 * @attr ref android.R.styleable#View_visibility 3920 */ 3921 @ViewDebug.ExportedProperty(mapping = { 3922 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 3923 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 3924 @ViewDebug.IntToString(from = GONE, to = "GONE") 3925 }) 3926 public int getVisibility() { 3927 return mViewFlags & VISIBILITY_MASK; 3928 } 3929 3930 /** 3931 * Set the enabled state of this view. 3932 * 3933 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 3934 * @attr ref android.R.styleable#View_visibility 3935 */ 3936 @RemotableViewMethod 3937 public void setVisibility(int visibility) { 3938 setFlags(visibility, VISIBILITY_MASK); 3939 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); 3940 } 3941 3942 /** 3943 * Returns the enabled status for this view. The interpretation of the 3944 * enabled state varies by subclass. 3945 * 3946 * @return True if this view is enabled, false otherwise. 3947 */ 3948 @ViewDebug.ExportedProperty 3949 public boolean isEnabled() { 3950 return (mViewFlags & ENABLED_MASK) == ENABLED; 3951 } 3952 3953 /** 3954 * Set the enabled state of this view. The interpretation of the enabled 3955 * state varies by subclass. 3956 * 3957 * @param enabled True if this view is enabled, false otherwise. 3958 */ 3959 @RemotableViewMethod 3960 public void setEnabled(boolean enabled) { 3961 if (enabled == isEnabled()) return; 3962 3963 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 3964 3965 /* 3966 * The View most likely has to change its appearance, so refresh 3967 * the drawable state. 3968 */ 3969 refreshDrawableState(); 3970 3971 // Invalidate too, since the default behavior for views is to be 3972 // be drawn at 50% alpha rather than to change the drawable. 3973 invalidate(true); 3974 } 3975 3976 /** 3977 * Set whether this view can receive the focus. 3978 * 3979 * Setting this to false will also ensure that this view is not focusable 3980 * in touch mode. 3981 * 3982 * @param focusable If true, this view can receive the focus. 3983 * 3984 * @see #setFocusableInTouchMode(boolean) 3985 * @attr ref android.R.styleable#View_focusable 3986 */ 3987 public void setFocusable(boolean focusable) { 3988 if (!focusable) { 3989 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 3990 } 3991 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 3992 } 3993 3994 /** 3995 * Set whether this view can receive focus while in touch mode. 3996 * 3997 * Setting this to true will also ensure that this view is focusable. 3998 * 3999 * @param focusableInTouchMode If true, this view can receive the focus while 4000 * in touch mode. 4001 * 4002 * @see #setFocusable(boolean) 4003 * @attr ref android.R.styleable#View_focusableInTouchMode 4004 */ 4005 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 4006 // Focusable in touch mode should always be set before the focusable flag 4007 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 4008 // which, in touch mode, will not successfully request focus on this view 4009 // because the focusable in touch mode flag is not set 4010 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 4011 if (focusableInTouchMode) { 4012 setFlags(FOCUSABLE, FOCUSABLE_MASK); 4013 } 4014 } 4015 4016 /** 4017 * Set whether this view should have sound effects enabled for events such as 4018 * clicking and touching. 4019 * 4020 * <p>You may wish to disable sound effects for a view if you already play sounds, 4021 * for instance, a dial key that plays dtmf tones. 4022 * 4023 * @param soundEffectsEnabled whether sound effects are enabled for this view. 4024 * @see #isSoundEffectsEnabled() 4025 * @see #playSoundEffect(int) 4026 * @attr ref android.R.styleable#View_soundEffectsEnabled 4027 */ 4028 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 4029 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 4030 } 4031 4032 /** 4033 * @return whether this view should have sound effects enabled for events such as 4034 * clicking and touching. 4035 * 4036 * @see #setSoundEffectsEnabled(boolean) 4037 * @see #playSoundEffect(int) 4038 * @attr ref android.R.styleable#View_soundEffectsEnabled 4039 */ 4040 @ViewDebug.ExportedProperty 4041 public boolean isSoundEffectsEnabled() { 4042 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 4043 } 4044 4045 /** 4046 * Set whether this view should have haptic feedback for events such as 4047 * long presses. 4048 * 4049 * <p>You may wish to disable haptic feedback if your view already controls 4050 * its own haptic feedback. 4051 * 4052 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 4053 * @see #isHapticFeedbackEnabled() 4054 * @see #performHapticFeedback(int) 4055 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4056 */ 4057 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 4058 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 4059 } 4060 4061 /** 4062 * @return whether this view should have haptic feedback enabled for events 4063 * long presses. 4064 * 4065 * @see #setHapticFeedbackEnabled(boolean) 4066 * @see #performHapticFeedback(int) 4067 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4068 */ 4069 @ViewDebug.ExportedProperty 4070 public boolean isHapticFeedbackEnabled() { 4071 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 4072 } 4073 4074 /** 4075 * If this view doesn't do any drawing on its own, set this flag to 4076 * allow further optimizations. By default, this flag is not set on 4077 * View, but could be set on some View subclasses such as ViewGroup. 4078 * 4079 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 4080 * you should clear this flag. 4081 * 4082 * @param willNotDraw whether or not this View draw on its own 4083 */ 4084 public void setWillNotDraw(boolean willNotDraw) { 4085 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 4086 } 4087 4088 /** 4089 * Returns whether or not this View draws on its own. 4090 * 4091 * @return true if this view has nothing to draw, false otherwise 4092 */ 4093 @ViewDebug.ExportedProperty(category = "drawing") 4094 public boolean willNotDraw() { 4095 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 4096 } 4097 4098 /** 4099 * When a View's drawing cache is enabled, drawing is redirected to an 4100 * offscreen bitmap. Some views, like an ImageView, must be able to 4101 * bypass this mechanism if they already draw a single bitmap, to avoid 4102 * unnecessary usage of the memory. 4103 * 4104 * @param willNotCacheDrawing true if this view does not cache its 4105 * drawing, false otherwise 4106 */ 4107 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 4108 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 4109 } 4110 4111 /** 4112 * Returns whether or not this View can cache its drawing or not. 4113 * 4114 * @return true if this view does not cache its drawing, false otherwise 4115 */ 4116 @ViewDebug.ExportedProperty(category = "drawing") 4117 public boolean willNotCacheDrawing() { 4118 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 4119 } 4120 4121 /** 4122 * Indicates whether this view reacts to click events or not. 4123 * 4124 * @return true if the view is clickable, false otherwise 4125 * 4126 * @see #setClickable(boolean) 4127 * @attr ref android.R.styleable#View_clickable 4128 */ 4129 @ViewDebug.ExportedProperty 4130 public boolean isClickable() { 4131 return (mViewFlags & CLICKABLE) == CLICKABLE; 4132 } 4133 4134 /** 4135 * Enables or disables click events for this view. When a view 4136 * is clickable it will change its state to "pressed" on every click. 4137 * Subclasses should set the view clickable to visually react to 4138 * user's clicks. 4139 * 4140 * @param clickable true to make the view clickable, false otherwise 4141 * 4142 * @see #isClickable() 4143 * @attr ref android.R.styleable#View_clickable 4144 */ 4145 public void setClickable(boolean clickable) { 4146 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 4147 } 4148 4149 /** 4150 * Indicates whether this view reacts to long click events or not. 4151 * 4152 * @return true if the view is long clickable, false otherwise 4153 * 4154 * @see #setLongClickable(boolean) 4155 * @attr ref android.R.styleable#View_longClickable 4156 */ 4157 public boolean isLongClickable() { 4158 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 4159 } 4160 4161 /** 4162 * Enables or disables long click events for this view. When a view is long 4163 * clickable it reacts to the user holding down the button for a longer 4164 * duration than a tap. This event can either launch the listener or a 4165 * context menu. 4166 * 4167 * @param longClickable true to make the view long clickable, false otherwise 4168 * @see #isLongClickable() 4169 * @attr ref android.R.styleable#View_longClickable 4170 */ 4171 public void setLongClickable(boolean longClickable) { 4172 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 4173 } 4174 4175 /** 4176 * Sets the pressed state for this view. 4177 * 4178 * @see #isClickable() 4179 * @see #setClickable(boolean) 4180 * 4181 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 4182 * the View's internal state from a previously set "pressed" state. 4183 */ 4184 public void setPressed(boolean pressed) { 4185 if (pressed) { 4186 mPrivateFlags |= PRESSED; 4187 } else { 4188 mPrivateFlags &= ~PRESSED; 4189 } 4190 refreshDrawableState(); 4191 dispatchSetPressed(pressed); 4192 } 4193 4194 /** 4195 * Dispatch setPressed to all of this View's children. 4196 * 4197 * @see #setPressed(boolean) 4198 * 4199 * @param pressed The new pressed state 4200 */ 4201 protected void dispatchSetPressed(boolean pressed) { 4202 } 4203 4204 /** 4205 * Indicates whether the view is currently in pressed state. Unless 4206 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 4207 * the pressed state. 4208 * 4209 * @see #setPressed(boolean) 4210 * @see #isClickable() 4211 * @see #setClickable(boolean) 4212 * 4213 * @return true if the view is currently pressed, false otherwise 4214 */ 4215 public boolean isPressed() { 4216 return (mPrivateFlags & PRESSED) == PRESSED; 4217 } 4218 4219 /** 4220 * Indicates whether this view will save its state (that is, 4221 * whether its {@link #onSaveInstanceState} method will be called). 4222 * 4223 * @return Returns true if the view state saving is enabled, else false. 4224 * 4225 * @see #setSaveEnabled(boolean) 4226 * @attr ref android.R.styleable#View_saveEnabled 4227 */ 4228 public boolean isSaveEnabled() { 4229 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 4230 } 4231 4232 /** 4233 * Controls whether the saving of this view's state is 4234 * enabled (that is, whether its {@link #onSaveInstanceState} method 4235 * will be called). Note that even if freezing is enabled, the 4236 * view still must have an id assigned to it (via {@link #setId(int)}) 4237 * for its state to be saved. This flag can only disable the 4238 * saving of this view; any child views may still have their state saved. 4239 * 4240 * @param enabled Set to false to <em>disable</em> state saving, or true 4241 * (the default) to allow it. 4242 * 4243 * @see #isSaveEnabled() 4244 * @see #setId(int) 4245 * @see #onSaveInstanceState() 4246 * @attr ref android.R.styleable#View_saveEnabled 4247 */ 4248 public void setSaveEnabled(boolean enabled) { 4249 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 4250 } 4251 4252 /** 4253 * Gets whether the framework should discard touches when the view's 4254 * window is obscured by another visible window. 4255 * Refer to the {@link View} security documentation for more details. 4256 * 4257 * @return True if touch filtering is enabled. 4258 * 4259 * @see #setFilterTouchesWhenObscured(boolean) 4260 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4261 */ 4262 @ViewDebug.ExportedProperty 4263 public boolean getFilterTouchesWhenObscured() { 4264 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 4265 } 4266 4267 /** 4268 * Sets whether the framework should discard touches when the view's 4269 * window is obscured by another visible window. 4270 * Refer to the {@link View} security documentation for more details. 4271 * 4272 * @param enabled True if touch filtering should be enabled. 4273 * 4274 * @see #getFilterTouchesWhenObscured 4275 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4276 */ 4277 public void setFilterTouchesWhenObscured(boolean enabled) { 4278 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 4279 FILTER_TOUCHES_WHEN_OBSCURED); 4280 } 4281 4282 /** 4283 * Indicates whether the entire hierarchy under this view will save its 4284 * state when a state saving traversal occurs from its parent. The default 4285 * is true; if false, these views will not be saved unless 4286 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4287 * 4288 * @return Returns true if the view state saving from parent is enabled, else false. 4289 * 4290 * @see #setSaveFromParentEnabled(boolean) 4291 */ 4292 public boolean isSaveFromParentEnabled() { 4293 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 4294 } 4295 4296 /** 4297 * Controls whether the entire hierarchy under this view will save its 4298 * state when a state saving traversal occurs from its parent. The default 4299 * is true; if false, these views will not be saved unless 4300 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4301 * 4302 * @param enabled Set to false to <em>disable</em> state saving, or true 4303 * (the default) to allow it. 4304 * 4305 * @see #isSaveFromParentEnabled() 4306 * @see #setId(int) 4307 * @see #onSaveInstanceState() 4308 */ 4309 public void setSaveFromParentEnabled(boolean enabled) { 4310 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 4311 } 4312 4313 4314 /** 4315 * Returns whether this View is able to take focus. 4316 * 4317 * @return True if this view can take focus, or false otherwise. 4318 * @attr ref android.R.styleable#View_focusable 4319 */ 4320 @ViewDebug.ExportedProperty(category = "focus") 4321 public final boolean isFocusable() { 4322 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 4323 } 4324 4325 /** 4326 * When a view is focusable, it may not want to take focus when in touch mode. 4327 * For example, a button would like focus when the user is navigating via a D-pad 4328 * so that the user can click on it, but once the user starts touching the screen, 4329 * the button shouldn't take focus 4330 * @return Whether the view is focusable in touch mode. 4331 * @attr ref android.R.styleable#View_focusableInTouchMode 4332 */ 4333 @ViewDebug.ExportedProperty 4334 public final boolean isFocusableInTouchMode() { 4335 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 4336 } 4337 4338 /** 4339 * Find the nearest view in the specified direction that can take focus. 4340 * This does not actually give focus to that view. 4341 * 4342 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4343 * 4344 * @return The nearest focusable in the specified direction, or null if none 4345 * can be found. 4346 */ 4347 public View focusSearch(int direction) { 4348 if (mParent != null) { 4349 return mParent.focusSearch(this, direction); 4350 } else { 4351 return null; 4352 } 4353 } 4354 4355 /** 4356 * This method is the last chance for the focused view and its ancestors to 4357 * respond to an arrow key. This is called when the focused view did not 4358 * consume the key internally, nor could the view system find a new view in 4359 * the requested direction to give focus to. 4360 * 4361 * @param focused The currently focused view. 4362 * @param direction The direction focus wants to move. One of FOCUS_UP, 4363 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 4364 * @return True if the this view consumed this unhandled move. 4365 */ 4366 public boolean dispatchUnhandledMove(View focused, int direction) { 4367 return false; 4368 } 4369 4370 /** 4371 * If a user manually specified the next view id for a particular direction, 4372 * use the root to look up the view. 4373 * @param root The root view of the hierarchy containing this view. 4374 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 4375 * or FOCUS_BACKWARD. 4376 * @return The user specified next view, or null if there is none. 4377 */ 4378 View findUserSetNextFocus(View root, int direction) { 4379 switch (direction) { 4380 case FOCUS_LEFT: 4381 if (mNextFocusLeftId == View.NO_ID) return null; 4382 return findViewShouldExist(root, mNextFocusLeftId); 4383 case FOCUS_RIGHT: 4384 if (mNextFocusRightId == View.NO_ID) return null; 4385 return findViewShouldExist(root, mNextFocusRightId); 4386 case FOCUS_UP: 4387 if (mNextFocusUpId == View.NO_ID) return null; 4388 return findViewShouldExist(root, mNextFocusUpId); 4389 case FOCUS_DOWN: 4390 if (mNextFocusDownId == View.NO_ID) return null; 4391 return findViewShouldExist(root, mNextFocusDownId); 4392 case FOCUS_FORWARD: 4393 if (mNextFocusForwardId == View.NO_ID) return null; 4394 return findViewShouldExist(root, mNextFocusForwardId); 4395 case FOCUS_BACKWARD: { 4396 final int id = mID; 4397 return root.findViewByPredicate(new Predicate<View>() { 4398 @Override 4399 public boolean apply(View t) { 4400 return t.mNextFocusForwardId == id; 4401 } 4402 }); 4403 } 4404 } 4405 return null; 4406 } 4407 4408 private static View findViewShouldExist(View root, int childViewId) { 4409 View result = root.findViewById(childViewId); 4410 if (result == null) { 4411 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified " 4412 + "by user for id " + childViewId); 4413 } 4414 return result; 4415 } 4416 4417 /** 4418 * Find and return all focusable views that are descendants of this view, 4419 * possibly including this view if it is focusable itself. 4420 * 4421 * @param direction The direction of the focus 4422 * @return A list of focusable views 4423 */ 4424 public ArrayList<View> getFocusables(int direction) { 4425 ArrayList<View> result = new ArrayList<View>(24); 4426 addFocusables(result, direction); 4427 return result; 4428 } 4429 4430 /** 4431 * Add any focusable views that are descendants of this view (possibly 4432 * including this view if it is focusable itself) to views. If we are in touch mode, 4433 * only add views that are also focusable in touch mode. 4434 * 4435 * @param views Focusable views found so far 4436 * @param direction The direction of the focus 4437 */ 4438 public void addFocusables(ArrayList<View> views, int direction) { 4439 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 4440 } 4441 4442 /** 4443 * Adds any focusable views that are descendants of this view (possibly 4444 * including this view if it is focusable itself) to views. This method 4445 * adds all focusable views regardless if we are in touch mode or 4446 * only views focusable in touch mode if we are in touch mode depending on 4447 * the focusable mode paramater. 4448 * 4449 * @param views Focusable views found so far or null if all we are interested is 4450 * the number of focusables. 4451 * @param direction The direction of the focus. 4452 * @param focusableMode The type of focusables to be added. 4453 * 4454 * @see #FOCUSABLES_ALL 4455 * @see #FOCUSABLES_TOUCH_MODE 4456 */ 4457 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 4458 if (!isFocusable()) { 4459 return; 4460 } 4461 4462 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 4463 isInTouchMode() && !isFocusableInTouchMode()) { 4464 return; 4465 } 4466 4467 if (views != null) { 4468 views.add(this); 4469 } 4470 } 4471 4472 /** 4473 * Find and return all touchable views that are descendants of this view, 4474 * possibly including this view if it is touchable itself. 4475 * 4476 * @return A list of touchable views 4477 */ 4478 public ArrayList<View> getTouchables() { 4479 ArrayList<View> result = new ArrayList<View>(); 4480 addTouchables(result); 4481 return result; 4482 } 4483 4484 /** 4485 * Add any touchable views that are descendants of this view (possibly 4486 * including this view if it is touchable itself) to views. 4487 * 4488 * @param views Touchable views found so far 4489 */ 4490 public void addTouchables(ArrayList<View> views) { 4491 final int viewFlags = mViewFlags; 4492 4493 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 4494 && (viewFlags & ENABLED_MASK) == ENABLED) { 4495 views.add(this); 4496 } 4497 } 4498 4499 /** 4500 * Call this to try to give focus to a specific view or to one of its 4501 * descendants. 4502 * 4503 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 4504 * false), or if it is focusable and it is not focusable in touch mode 4505 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 4506 * 4507 * See also {@link #focusSearch(int)}, which is what you call to say that you 4508 * have focus, and you want your parent to look for the next one. 4509 * 4510 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 4511 * {@link #FOCUS_DOWN} and <code>null</code>. 4512 * 4513 * @return Whether this view or one of its descendants actually took focus. 4514 */ 4515 public final boolean requestFocus() { 4516 return requestFocus(View.FOCUS_DOWN); 4517 } 4518 4519 4520 /** 4521 * Call this to try to give focus to a specific view or to one of its 4522 * descendants and give it a hint about what direction focus is heading. 4523 * 4524 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 4525 * false), or if it is focusable and it is not focusable in touch mode 4526 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 4527 * 4528 * See also {@link #focusSearch(int)}, which is what you call to say that you 4529 * have focus, and you want your parent to look for the next one. 4530 * 4531 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 4532 * <code>null</code> set for the previously focused rectangle. 4533 * 4534 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4535 * @return Whether this view or one of its descendants actually took focus. 4536 */ 4537 public final boolean requestFocus(int direction) { 4538 return requestFocus(direction, null); 4539 } 4540 4541 /** 4542 * Call this to try to give focus to a specific view or to one of its descendants 4543 * and give it hints about the direction and a specific rectangle that the focus 4544 * is coming from. The rectangle can help give larger views a finer grained hint 4545 * about where focus is coming from, and therefore, where to show selection, or 4546 * forward focus change internally. 4547 * 4548 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 4549 * false), or if it is focusable and it is not focusable in touch mode 4550 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 4551 * 4552 * A View will not take focus if it is not visible. 4553 * 4554 * A View will not take focus if one of its parents has 4555 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 4556 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 4557 * 4558 * See also {@link #focusSearch(int)}, which is what you call to say that you 4559 * have focus, and you want your parent to look for the next one. 4560 * 4561 * You may wish to override this method if your custom {@link View} has an internal 4562 * {@link View} that it wishes to forward the request to. 4563 * 4564 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4565 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 4566 * to give a finer grained hint about where focus is coming from. May be null 4567 * if there is no hint. 4568 * @return Whether this view or one of its descendants actually took focus. 4569 */ 4570 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 4571 // need to be focusable 4572 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 4573 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 4574 return false; 4575 } 4576 4577 // need to be focusable in touch mode if in touch mode 4578 if (isInTouchMode() && 4579 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 4580 return false; 4581 } 4582 4583 // need to not have any parents blocking us 4584 if (hasAncestorThatBlocksDescendantFocus()) { 4585 return false; 4586 } 4587 4588 handleFocusGainInternal(direction, previouslyFocusedRect); 4589 return true; 4590 } 4591 4592 /** Gets the ViewAncestor, or null if not attached. */ 4593 /*package*/ ViewAncestor getViewAncestor() { 4594 View root = getRootView(); 4595 return root != null ? (ViewAncestor)root.getParent() : null; 4596 } 4597 4598 /** 4599 * Call this to try to give focus to a specific view or to one of its descendants. This is a 4600 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 4601 * touch mode to request focus when they are touched. 4602 * 4603 * @return Whether this view or one of its descendants actually took focus. 4604 * 4605 * @see #isInTouchMode() 4606 * 4607 */ 4608 public final boolean requestFocusFromTouch() { 4609 // Leave touch mode if we need to 4610 if (isInTouchMode()) { 4611 ViewAncestor viewRoot = getViewAncestor(); 4612 if (viewRoot != null) { 4613 viewRoot.ensureTouchMode(false); 4614 } 4615 } 4616 return requestFocus(View.FOCUS_DOWN); 4617 } 4618 4619 /** 4620 * @return Whether any ancestor of this view blocks descendant focus. 4621 */ 4622 private boolean hasAncestorThatBlocksDescendantFocus() { 4623 ViewParent ancestor = mParent; 4624 while (ancestor instanceof ViewGroup) { 4625 final ViewGroup vgAncestor = (ViewGroup) ancestor; 4626 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 4627 return true; 4628 } else { 4629 ancestor = vgAncestor.getParent(); 4630 } 4631 } 4632 return false; 4633 } 4634 4635 /** 4636 * @hide 4637 */ 4638 public void dispatchStartTemporaryDetach() { 4639 onStartTemporaryDetach(); 4640 } 4641 4642 /** 4643 * This is called when a container is going to temporarily detach a child, with 4644 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 4645 * It will either be followed by {@link #onFinishTemporaryDetach()} or 4646 * {@link #onDetachedFromWindow()} when the container is done. 4647 */ 4648 public void onStartTemporaryDetach() { 4649 removeUnsetPressCallback(); 4650 mPrivateFlags |= CANCEL_NEXT_UP_EVENT; 4651 } 4652 4653 /** 4654 * @hide 4655 */ 4656 public void dispatchFinishTemporaryDetach() { 4657 onFinishTemporaryDetach(); 4658 } 4659 4660 /** 4661 * Called after {@link #onStartTemporaryDetach} when the container is done 4662 * changing the view. 4663 */ 4664 public void onFinishTemporaryDetach() { 4665 } 4666 4667 /** 4668 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 4669 * for this view's window. Returns null if the view is not currently attached 4670 * to the window. Normally you will not need to use this directly, but 4671 * just use the standard high-level event callbacks like 4672 * {@link #onKeyDown(int, KeyEvent)}. 4673 */ 4674 public KeyEvent.DispatcherState getKeyDispatcherState() { 4675 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 4676 } 4677 4678 /** 4679 * Dispatch a key event before it is processed by any input method 4680 * associated with the view hierarchy. This can be used to intercept 4681 * key events in special situations before the IME consumes them; a 4682 * typical example would be handling the BACK key to update the application's 4683 * UI instead of allowing the IME to see it and close itself. 4684 * 4685 * @param event The key event to be dispatched. 4686 * @return True if the event was handled, false otherwise. 4687 */ 4688 public boolean dispatchKeyEventPreIme(KeyEvent event) { 4689 return onKeyPreIme(event.getKeyCode(), event); 4690 } 4691 4692 /** 4693 * Dispatch a key event to the next view on the focus path. This path runs 4694 * from the top of the view tree down to the currently focused view. If this 4695 * view has focus, it will dispatch to itself. Otherwise it will dispatch 4696 * the next node down the focus path. This method also fires any key 4697 * listeners. 4698 * 4699 * @param event The key event to be dispatched. 4700 * @return True if the event was handled, false otherwise. 4701 */ 4702 public boolean dispatchKeyEvent(KeyEvent event) { 4703 if (mInputEventConsistencyVerifier != null) { 4704 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 4705 } 4706 4707 // Give any attached key listener a first crack at the event. 4708 //noinspection SimplifiableIfStatement 4709 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 4710 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 4711 return true; 4712 } 4713 4714 if (event.dispatch(this, mAttachInfo != null 4715 ? mAttachInfo.mKeyDispatchState : null, this)) { 4716 return true; 4717 } 4718 4719 if (mInputEventConsistencyVerifier != null) { 4720 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 4721 } 4722 return false; 4723 } 4724 4725 /** 4726 * Dispatches a key shortcut event. 4727 * 4728 * @param event The key event to be dispatched. 4729 * @return True if the event was handled by the view, false otherwise. 4730 */ 4731 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 4732 return onKeyShortcut(event.getKeyCode(), event); 4733 } 4734 4735 /** 4736 * Pass the touch screen motion event down to the target view, or this 4737 * view if it is the target. 4738 * 4739 * @param event The motion event to be dispatched. 4740 * @return True if the event was handled by the view, false otherwise. 4741 */ 4742 public boolean dispatchTouchEvent(MotionEvent event) { 4743 if (mInputEventConsistencyVerifier != null) { 4744 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 4745 } 4746 4747 if (onFilterTouchEventForSecurity(event)) { 4748 //noinspection SimplifiableIfStatement 4749 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && 4750 mOnTouchListener.onTouch(this, event)) { 4751 return true; 4752 } 4753 4754 if (onTouchEvent(event)) { 4755 return true; 4756 } 4757 } 4758 4759 if (mInputEventConsistencyVerifier != null) { 4760 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 4761 } 4762 return false; 4763 } 4764 4765 /** 4766 * Filter the touch event to apply security policies. 4767 * 4768 * @param event The motion event to be filtered. 4769 * @return True if the event should be dispatched, false if the event should be dropped. 4770 * 4771 * @see #getFilterTouchesWhenObscured 4772 */ 4773 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 4774 //noinspection RedundantIfStatement 4775 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 4776 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 4777 // Window is obscured, drop this touch. 4778 return false; 4779 } 4780 return true; 4781 } 4782 4783 /** 4784 * Pass a trackball motion event down to the focused view. 4785 * 4786 * @param event The motion event to be dispatched. 4787 * @return True if the event was handled by the view, false otherwise. 4788 */ 4789 public boolean dispatchTrackballEvent(MotionEvent event) { 4790 if (mInputEventConsistencyVerifier != null) { 4791 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 4792 } 4793 4794 //Log.i("view", "view=" + this + ", " + event.toString()); 4795 if (onTrackballEvent(event)) { 4796 return true; 4797 } 4798 4799 if (mInputEventConsistencyVerifier != null) { 4800 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 4801 } 4802 return false; 4803 } 4804 4805 /** 4806 * Dispatch a generic motion event. 4807 * <p> 4808 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 4809 * are delivered to the view under the pointer. All other generic motion events are 4810 * delivered to the focused view. Hover events are handled specially and are delivered 4811 * to {@link #onHoverEvent(MotionEvent)}. 4812 * </p> 4813 * 4814 * @param event The motion event to be dispatched. 4815 * @return True if the event was handled by the view, false otherwise. 4816 */ 4817 public boolean dispatchGenericMotionEvent(MotionEvent event) { 4818 if (mInputEventConsistencyVerifier != null) { 4819 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 4820 } 4821 4822 final int source = event.getSource(); 4823 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 4824 final int action = event.getAction(); 4825 if (action == MotionEvent.ACTION_HOVER_ENTER 4826 || action == MotionEvent.ACTION_HOVER_MOVE 4827 || action == MotionEvent.ACTION_HOVER_EXIT) { 4828 if (dispatchHoverEvent(event)) { 4829 return true; 4830 } 4831 } else if (dispatchGenericPointerEvent(event)) { 4832 return true; 4833 } 4834 } else if (dispatchGenericFocusedEvent(event)) { 4835 return true; 4836 } 4837 4838 //noinspection SimplifiableIfStatement 4839 if (mOnGenericMotionListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 4840 && mOnGenericMotionListener.onGenericMotion(this, event)) { 4841 return true; 4842 } 4843 4844 if (onGenericMotionEvent(event)) { 4845 return true; 4846 } 4847 4848 if (mInputEventConsistencyVerifier != null) { 4849 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 4850 } 4851 return false; 4852 } 4853 4854 /** 4855 * Dispatch a hover event. 4856 * <p> 4857 * Do not call this method directly. 4858 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 4859 * </p> 4860 * 4861 * @param event The motion event to be dispatched. 4862 * @return True if the event was handled by the view, false otherwise. 4863 * @hide 4864 */ 4865 protected boolean dispatchHoverEvent(MotionEvent event) { 4866 return onHoverEvent(event); 4867 } 4868 4869 /** 4870 * Dispatch a generic motion event to the view under the first pointer. 4871 * <p> 4872 * Do not call this method directly. 4873 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 4874 * </p> 4875 * 4876 * @param event The motion event to be dispatched. 4877 * @return True if the event was handled by the view, false otherwise. 4878 * @hide 4879 */ 4880 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 4881 return false; 4882 } 4883 4884 /** 4885 * Dispatch a generic motion event to the currently focused view. 4886 * <p> 4887 * Do not call this method directly. 4888 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 4889 * </p> 4890 * 4891 * @param event The motion event to be dispatched. 4892 * @return True if the event was handled by the view, false otherwise. 4893 * @hide 4894 */ 4895 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 4896 return false; 4897 } 4898 4899 /** 4900 * Dispatch a pointer event. 4901 * <p> 4902 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 4903 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 4904 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 4905 * and should not be expected to handle other pointing device features. 4906 * </p> 4907 * 4908 * @param event The motion event to be dispatched. 4909 * @return True if the event was handled by the view, false otherwise. 4910 * @hide 4911 */ 4912 public final boolean dispatchPointerEvent(MotionEvent event) { 4913 if (event.isTouchEvent()) { 4914 return dispatchTouchEvent(event); 4915 } else { 4916 return dispatchGenericMotionEvent(event); 4917 } 4918 } 4919 4920 /** 4921 * Called when the window containing this view gains or loses window focus. 4922 * ViewGroups should override to route to their children. 4923 * 4924 * @param hasFocus True if the window containing this view now has focus, 4925 * false otherwise. 4926 */ 4927 public void dispatchWindowFocusChanged(boolean hasFocus) { 4928 onWindowFocusChanged(hasFocus); 4929 } 4930 4931 /** 4932 * Called when the window containing this view gains or loses focus. Note 4933 * that this is separate from view focus: to receive key events, both 4934 * your view and its window must have focus. If a window is displayed 4935 * on top of yours that takes input focus, then your own window will lose 4936 * focus but the view focus will remain unchanged. 4937 * 4938 * @param hasWindowFocus True if the window containing this view now has 4939 * focus, false otherwise. 4940 */ 4941 public void onWindowFocusChanged(boolean hasWindowFocus) { 4942 InputMethodManager imm = InputMethodManager.peekInstance(); 4943 if (!hasWindowFocus) { 4944 if (isPressed()) { 4945 setPressed(false); 4946 } 4947 if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 4948 imm.focusOut(this); 4949 } 4950 removeLongPressCallback(); 4951 removeTapCallback(); 4952 onFocusLost(); 4953 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 4954 imm.focusIn(this); 4955 } 4956 refreshDrawableState(); 4957 } 4958 4959 /** 4960 * Returns true if this view is in a window that currently has window focus. 4961 * Note that this is not the same as the view itself having focus. 4962 * 4963 * @return True if this view is in a window that currently has window focus. 4964 */ 4965 public boolean hasWindowFocus() { 4966 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 4967 } 4968 4969 /** 4970 * Dispatch a view visibility change down the view hierarchy. 4971 * ViewGroups should override to route to their children. 4972 * @param changedView The view whose visibility changed. Could be 'this' or 4973 * an ancestor view. 4974 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 4975 * {@link #INVISIBLE} or {@link #GONE}. 4976 */ 4977 protected void dispatchVisibilityChanged(View changedView, int visibility) { 4978 onVisibilityChanged(changedView, visibility); 4979 } 4980 4981 /** 4982 * Called when the visibility of the view or an ancestor of the view is changed. 4983 * @param changedView The view whose visibility changed. Could be 'this' or 4984 * an ancestor view. 4985 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 4986 * {@link #INVISIBLE} or {@link #GONE}. 4987 */ 4988 protected void onVisibilityChanged(View changedView, int visibility) { 4989 if (visibility == VISIBLE) { 4990 if (mAttachInfo != null) { 4991 initialAwakenScrollBars(); 4992 } else { 4993 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH; 4994 } 4995 } 4996 } 4997 4998 /** 4999 * Dispatch a hint about whether this view is displayed. For instance, when 5000 * a View moves out of the screen, it might receives a display hint indicating 5001 * the view is not displayed. Applications should not <em>rely</em> on this hint 5002 * as there is no guarantee that they will receive one. 5003 * 5004 * @param hint A hint about whether or not this view is displayed: 5005 * {@link #VISIBLE} or {@link #INVISIBLE}. 5006 */ 5007 public void dispatchDisplayHint(int hint) { 5008 onDisplayHint(hint); 5009 } 5010 5011 /** 5012 * Gives this view a hint about whether is displayed or not. For instance, when 5013 * a View moves out of the screen, it might receives a display hint indicating 5014 * the view is not displayed. Applications should not <em>rely</em> on this hint 5015 * as there is no guarantee that they will receive one. 5016 * 5017 * @param hint A hint about whether or not this view is displayed: 5018 * {@link #VISIBLE} or {@link #INVISIBLE}. 5019 */ 5020 protected void onDisplayHint(int hint) { 5021 } 5022 5023 /** 5024 * Dispatch a window visibility change down the view hierarchy. 5025 * ViewGroups should override to route to their children. 5026 * 5027 * @param visibility The new visibility of the window. 5028 * 5029 * @see #onWindowVisibilityChanged(int) 5030 */ 5031 public void dispatchWindowVisibilityChanged(int visibility) { 5032 onWindowVisibilityChanged(visibility); 5033 } 5034 5035 /** 5036 * Called when the window containing has change its visibility 5037 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 5038 * that this tells you whether or not your window is being made visible 5039 * to the window manager; this does <em>not</em> tell you whether or not 5040 * your window is obscured by other windows on the screen, even if it 5041 * is itself visible. 5042 * 5043 * @param visibility The new visibility of the window. 5044 */ 5045 protected void onWindowVisibilityChanged(int visibility) { 5046 if (visibility == VISIBLE) { 5047 initialAwakenScrollBars(); 5048 } 5049 } 5050 5051 /** 5052 * Returns the current visibility of the window this view is attached to 5053 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 5054 * 5055 * @return Returns the current visibility of the view's window. 5056 */ 5057 public int getWindowVisibility() { 5058 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 5059 } 5060 5061 /** 5062 * Retrieve the overall visible display size in which the window this view is 5063 * attached to has been positioned in. This takes into account screen 5064 * decorations above the window, for both cases where the window itself 5065 * is being position inside of them or the window is being placed under 5066 * then and covered insets are used for the window to position its content 5067 * inside. In effect, this tells you the available area where content can 5068 * be placed and remain visible to users. 5069 * 5070 * <p>This function requires an IPC back to the window manager to retrieve 5071 * the requested information, so should not be used in performance critical 5072 * code like drawing. 5073 * 5074 * @param outRect Filled in with the visible display frame. If the view 5075 * is not attached to a window, this is simply the raw display size. 5076 */ 5077 public void getWindowVisibleDisplayFrame(Rect outRect) { 5078 if (mAttachInfo != null) { 5079 try { 5080 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 5081 } catch (RemoteException e) { 5082 return; 5083 } 5084 // XXX This is really broken, and probably all needs to be done 5085 // in the window manager, and we need to know more about whether 5086 // we want the area behind or in front of the IME. 5087 final Rect insets = mAttachInfo.mVisibleInsets; 5088 outRect.left += insets.left; 5089 outRect.top += insets.top; 5090 outRect.right -= insets.right; 5091 outRect.bottom -= insets.bottom; 5092 return; 5093 } 5094 Display d = WindowManagerImpl.getDefault().getDefaultDisplay(); 5095 d.getRectSize(outRect); 5096 } 5097 5098 /** 5099 * Dispatch a notification about a resource configuration change down 5100 * the view hierarchy. 5101 * ViewGroups should override to route to their children. 5102 * 5103 * @param newConfig The new resource configuration. 5104 * 5105 * @see #onConfigurationChanged(android.content.res.Configuration) 5106 */ 5107 public void dispatchConfigurationChanged(Configuration newConfig) { 5108 onConfigurationChanged(newConfig); 5109 } 5110 5111 /** 5112 * Called when the current configuration of the resources being used 5113 * by the application have changed. You can use this to decide when 5114 * to reload resources that can changed based on orientation and other 5115 * configuration characterstics. You only need to use this if you are 5116 * not relying on the normal {@link android.app.Activity} mechanism of 5117 * recreating the activity instance upon a configuration change. 5118 * 5119 * @param newConfig The new resource configuration. 5120 */ 5121 protected void onConfigurationChanged(Configuration newConfig) { 5122 } 5123 5124 /** 5125 * Private function to aggregate all per-view attributes in to the view 5126 * root. 5127 */ 5128 void dispatchCollectViewAttributes(int visibility) { 5129 performCollectViewAttributes(visibility); 5130 } 5131 5132 void performCollectViewAttributes(int visibility) { 5133 if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) { 5134 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 5135 mAttachInfo.mKeepScreenOn = true; 5136 } 5137 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility; 5138 if (mOnSystemUiVisibilityChangeListener != null) { 5139 mAttachInfo.mHasSystemUiListeners = true; 5140 } 5141 } 5142 } 5143 5144 void needGlobalAttributesUpdate(boolean force) { 5145 final AttachInfo ai = mAttachInfo; 5146 if (ai != null) { 5147 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 5148 || ai.mHasSystemUiListeners) { 5149 ai.mRecomputeGlobalAttributes = true; 5150 } 5151 } 5152 } 5153 5154 /** 5155 * Returns whether the device is currently in touch mode. Touch mode is entered 5156 * once the user begins interacting with the device by touch, and affects various 5157 * things like whether focus is always visible to the user. 5158 * 5159 * @return Whether the device is in touch mode. 5160 */ 5161 @ViewDebug.ExportedProperty 5162 public boolean isInTouchMode() { 5163 if (mAttachInfo != null) { 5164 return mAttachInfo.mInTouchMode; 5165 } else { 5166 return ViewAncestor.isInTouchMode(); 5167 } 5168 } 5169 5170 /** 5171 * Returns the context the view is running in, through which it can 5172 * access the current theme, resources, etc. 5173 * 5174 * @return The view's Context. 5175 */ 5176 @ViewDebug.CapturedViewProperty 5177 public final Context getContext() { 5178 return mContext; 5179 } 5180 5181 /** 5182 * Handle a key event before it is processed by any input method 5183 * associated with the view hierarchy. This can be used to intercept 5184 * key events in special situations before the IME consumes them; a 5185 * typical example would be handling the BACK key to update the application's 5186 * UI instead of allowing the IME to see it and close itself. 5187 * 5188 * @param keyCode The value in event.getKeyCode(). 5189 * @param event Description of the key event. 5190 * @return If you handled the event, return true. If you want to allow the 5191 * event to be handled by the next receiver, return false. 5192 */ 5193 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 5194 return false; 5195 } 5196 5197 /** 5198 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 5199 * KeyEvent.Callback.onKeyDown()}: perform press of the view 5200 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 5201 * is released, if the view is enabled and clickable. 5202 * 5203 * @param keyCode A key code that represents the button pressed, from 5204 * {@link android.view.KeyEvent}. 5205 * @param event The KeyEvent object that defines the button action. 5206 */ 5207 public boolean onKeyDown(int keyCode, KeyEvent event) { 5208 boolean result = false; 5209 5210 switch (keyCode) { 5211 case KeyEvent.KEYCODE_DPAD_CENTER: 5212 case KeyEvent.KEYCODE_ENTER: { 5213 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5214 return true; 5215 } 5216 // Long clickable items don't necessarily have to be clickable 5217 if (((mViewFlags & CLICKABLE) == CLICKABLE || 5218 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 5219 (event.getRepeatCount() == 0)) { 5220 setPressed(true); 5221 checkForLongClick(0); 5222 return true; 5223 } 5224 break; 5225 } 5226 } 5227 return result; 5228 } 5229 5230 /** 5231 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 5232 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 5233 * the event). 5234 */ 5235 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 5236 return false; 5237 } 5238 5239 /** 5240 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 5241 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 5242 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 5243 * {@link KeyEvent#KEYCODE_ENTER} is released. 5244 * 5245 * @param keyCode A key code that represents the button pressed, from 5246 * {@link android.view.KeyEvent}. 5247 * @param event The KeyEvent object that defines the button action. 5248 */ 5249 public boolean onKeyUp(int keyCode, KeyEvent event) { 5250 boolean result = false; 5251 5252 switch (keyCode) { 5253 case KeyEvent.KEYCODE_DPAD_CENTER: 5254 case KeyEvent.KEYCODE_ENTER: { 5255 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5256 return true; 5257 } 5258 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 5259 setPressed(false); 5260 5261 if (!mHasPerformedLongPress) { 5262 // This is a tap, so remove the longpress check 5263 removeLongPressCallback(); 5264 5265 result = performClick(); 5266 } 5267 } 5268 break; 5269 } 5270 } 5271 return result; 5272 } 5273 5274 /** 5275 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 5276 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 5277 * the event). 5278 * 5279 * @param keyCode A key code that represents the button pressed, from 5280 * {@link android.view.KeyEvent}. 5281 * @param repeatCount The number of times the action was made. 5282 * @param event The KeyEvent object that defines the button action. 5283 */ 5284 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 5285 return false; 5286 } 5287 5288 /** 5289 * Called on the focused view when a key shortcut event is not handled. 5290 * Override this method to implement local key shortcuts for the View. 5291 * Key shortcuts can also be implemented by setting the 5292 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 5293 * 5294 * @param keyCode The value in event.getKeyCode(). 5295 * @param event Description of the key event. 5296 * @return If you handled the event, return true. If you want to allow the 5297 * event to be handled by the next receiver, return false. 5298 */ 5299 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 5300 return false; 5301 } 5302 5303 /** 5304 * Check whether the called view is a text editor, in which case it 5305 * would make sense to automatically display a soft input window for 5306 * it. Subclasses should override this if they implement 5307 * {@link #onCreateInputConnection(EditorInfo)} to return true if 5308 * a call on that method would return a non-null InputConnection, and 5309 * they are really a first-class editor that the user would normally 5310 * start typing on when the go into a window containing your view. 5311 * 5312 * <p>The default implementation always returns false. This does 5313 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 5314 * will not be called or the user can not otherwise perform edits on your 5315 * view; it is just a hint to the system that this is not the primary 5316 * purpose of this view. 5317 * 5318 * @return Returns true if this view is a text editor, else false. 5319 */ 5320 public boolean onCheckIsTextEditor() { 5321 return false; 5322 } 5323 5324 /** 5325 * Create a new InputConnection for an InputMethod to interact 5326 * with the view. The default implementation returns null, since it doesn't 5327 * support input methods. You can override this to implement such support. 5328 * This is only needed for views that take focus and text input. 5329 * 5330 * <p>When implementing this, you probably also want to implement 5331 * {@link #onCheckIsTextEditor()} to indicate you will return a 5332 * non-null InputConnection. 5333 * 5334 * @param outAttrs Fill in with attribute information about the connection. 5335 */ 5336 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 5337 return null; 5338 } 5339 5340 /** 5341 * Called by the {@link android.view.inputmethod.InputMethodManager} 5342 * when a view who is not the current 5343 * input connection target is trying to make a call on the manager. The 5344 * default implementation returns false; you can override this to return 5345 * true for certain views if you are performing InputConnection proxying 5346 * to them. 5347 * @param view The View that is making the InputMethodManager call. 5348 * @return Return true to allow the call, false to reject. 5349 */ 5350 public boolean checkInputConnectionProxy(View view) { 5351 return false; 5352 } 5353 5354 /** 5355 * Show the context menu for this view. It is not safe to hold on to the 5356 * menu after returning from this method. 5357 * 5358 * You should normally not overload this method. Overload 5359 * {@link #onCreateContextMenu(ContextMenu)} or define an 5360 * {@link OnCreateContextMenuListener} to add items to the context menu. 5361 * 5362 * @param menu The context menu to populate 5363 */ 5364 public void createContextMenu(ContextMenu menu) { 5365 ContextMenuInfo menuInfo = getContextMenuInfo(); 5366 5367 // Sets the current menu info so all items added to menu will have 5368 // my extra info set. 5369 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 5370 5371 onCreateContextMenu(menu); 5372 if (mOnCreateContextMenuListener != null) { 5373 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 5374 } 5375 5376 // Clear the extra information so subsequent items that aren't mine don't 5377 // have my extra info. 5378 ((MenuBuilder)menu).setCurrentMenuInfo(null); 5379 5380 if (mParent != null) { 5381 mParent.createContextMenu(menu); 5382 } 5383 } 5384 5385 /** 5386 * Views should implement this if they have extra information to associate 5387 * with the context menu. The return result is supplied as a parameter to 5388 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 5389 * callback. 5390 * 5391 * @return Extra information about the item for which the context menu 5392 * should be shown. This information will vary across different 5393 * subclasses of View. 5394 */ 5395 protected ContextMenuInfo getContextMenuInfo() { 5396 return null; 5397 } 5398 5399 /** 5400 * Views should implement this if the view itself is going to add items to 5401 * the context menu. 5402 * 5403 * @param menu the context menu to populate 5404 */ 5405 protected void onCreateContextMenu(ContextMenu menu) { 5406 } 5407 5408 /** 5409 * Implement this method to handle trackball motion events. The 5410 * <em>relative</em> movement of the trackball since the last event 5411 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 5412 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 5413 * that a movement of 1 corresponds to the user pressing one DPAD key (so 5414 * they will often be fractional values, representing the more fine-grained 5415 * movement information available from a trackball). 5416 * 5417 * @param event The motion event. 5418 * @return True if the event was handled, false otherwise. 5419 */ 5420 public boolean onTrackballEvent(MotionEvent event) { 5421 return false; 5422 } 5423 5424 /** 5425 * Implement this method to handle generic motion events. 5426 * <p> 5427 * Generic motion events describe joystick movements, mouse hovers, track pad 5428 * touches, scroll wheel movements and other input events. The 5429 * {@link MotionEvent#getSource() source} of the motion event specifies 5430 * the class of input that was received. Implementations of this method 5431 * must examine the bits in the source before processing the event. 5432 * The following code example shows how this is done. 5433 * </p><p> 5434 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5435 * are delivered to the view under the pointer. All other generic motion events are 5436 * delivered to the focused view. 5437 * </p> 5438 * <code> 5439 * public boolean onGenericMotionEvent(MotionEvent event) { 5440 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 5441 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 5442 * // process the joystick movement... 5443 * return true; 5444 * } 5445 * } 5446 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5447 * switch (event.getAction()) { 5448 * case MotionEvent.ACTION_HOVER_MOVE: 5449 * // process the mouse hover movement... 5450 * return true; 5451 * case MotionEvent.ACTION_SCROLL: 5452 * // process the scroll wheel movement... 5453 * return true; 5454 * } 5455 * } 5456 * return super.onGenericMotionEvent(event); 5457 * } 5458 * </code> 5459 * 5460 * @param event The generic motion event being processed. 5461 * @return True if the event was handled, false otherwise. 5462 */ 5463 public boolean onGenericMotionEvent(MotionEvent event) { 5464 return false; 5465 } 5466 5467 /** 5468 * Implement this method to handle hover events. 5469 * <p> 5470 * Hover events are pointer events with action {@link MotionEvent#ACTION_HOVER_ENTER}, 5471 * {@link MotionEvent#ACTION_HOVER_MOVE}, or {@link MotionEvent#ACTION_HOVER_EXIT}. 5472 * </p><p> 5473 * The view receives hover enter as the pointer enters the bounds of the view and hover 5474 * exit as the pointer exits the bound of the view or just before the pointer goes down 5475 * (which implies that {@link #onTouchEvent(MotionEvent)} will be called soon). 5476 * </p><p> 5477 * If the view would like to handle the hover event itself and prevent its children 5478 * from receiving hover, it should return true from this method. If this method returns 5479 * true and a child has already received a hover enter event, the child will 5480 * automatically receive a hover exit event. 5481 * </p><p> 5482 * The default implementation sets the hovered state of the view if the view is 5483 * clickable. 5484 * </p> 5485 * 5486 * @param event The motion event that describes the hover. 5487 * @return True if this view handled the hover event and does not want its children 5488 * to receive the hover event. 5489 */ 5490 public boolean onHoverEvent(MotionEvent event) { 5491 switch (event.getAction()) { 5492 case MotionEvent.ACTION_HOVER_ENTER: 5493 setHovered(true); 5494 break; 5495 5496 case MotionEvent.ACTION_HOVER_EXIT: 5497 setHovered(false); 5498 break; 5499 } 5500 5501 return false; 5502 } 5503 5504 /** 5505 * Returns true if the view is currently hovered. 5506 * 5507 * @return True if the view is currently hovered. 5508 */ 5509 public boolean isHovered() { 5510 return (mPrivateFlags & HOVERED) != 0; 5511 } 5512 5513 /** 5514 * Sets whether the view is currently hovered. 5515 * 5516 * @param hovered True if the view is hovered. 5517 */ 5518 public void setHovered(boolean hovered) { 5519 if (hovered) { 5520 if ((mPrivateFlags & HOVERED) == 0) { 5521 mPrivateFlags |= HOVERED; 5522 refreshDrawableState(); 5523 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 5524 } 5525 } else { 5526 if ((mPrivateFlags & HOVERED) != 0) { 5527 mPrivateFlags &= ~HOVERED; 5528 refreshDrawableState(); 5529 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 5530 } 5531 } 5532 } 5533 5534 /** 5535 * Implement this method to handle touch screen motion events. 5536 * 5537 * @param event The motion event. 5538 * @return True if the event was handled, false otherwise. 5539 */ 5540 public boolean onTouchEvent(MotionEvent event) { 5541 final int viewFlags = mViewFlags; 5542 5543 if ((viewFlags & ENABLED_MASK) == DISABLED) { 5544 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) { 5545 mPrivateFlags &= ~PRESSED; 5546 refreshDrawableState(); 5547 } 5548 // A disabled view that is clickable still consumes the touch 5549 // events, it just doesn't respond to them. 5550 return (((viewFlags & CLICKABLE) == CLICKABLE || 5551 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 5552 } 5553 5554 if (mTouchDelegate != null) { 5555 if (mTouchDelegate.onTouchEvent(event)) { 5556 return true; 5557 } 5558 } 5559 5560 if (((viewFlags & CLICKABLE) == CLICKABLE || 5561 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 5562 switch (event.getAction()) { 5563 case MotionEvent.ACTION_UP: 5564 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; 5565 if ((mPrivateFlags & PRESSED) != 0 || prepressed) { 5566 // take focus if we don't have it already and we should in 5567 // touch mode. 5568 boolean focusTaken = false; 5569 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 5570 focusTaken = requestFocus(); 5571 } 5572 5573 if (prepressed) { 5574 // The button is being released before we actually 5575 // showed it as pressed. Make it show the pressed 5576 // state now (before scheduling the click) to ensure 5577 // the user sees it. 5578 mPrivateFlags |= PRESSED; 5579 refreshDrawableState(); 5580 } 5581 5582 if (!mHasPerformedLongPress) { 5583 // This is a tap, so remove the longpress check 5584 removeLongPressCallback(); 5585 5586 // Only perform take click actions if we were in the pressed state 5587 if (!focusTaken) { 5588 // Use a Runnable and post this rather than calling 5589 // performClick directly. This lets other visual state 5590 // of the view update before click actions start. 5591 if (mPerformClick == null) { 5592 mPerformClick = new PerformClick(); 5593 } 5594 if (!post(mPerformClick)) { 5595 performClick(); 5596 } 5597 } 5598 } 5599 5600 if (mUnsetPressedState == null) { 5601 mUnsetPressedState = new UnsetPressedState(); 5602 } 5603 5604 if (prepressed) { 5605 postDelayed(mUnsetPressedState, 5606 ViewConfiguration.getPressedStateDuration()); 5607 } else if (!post(mUnsetPressedState)) { 5608 // If the post failed, unpress right now 5609 mUnsetPressedState.run(); 5610 } 5611 removeTapCallback(); 5612 } 5613 break; 5614 5615 case MotionEvent.ACTION_DOWN: 5616 mHasPerformedLongPress = false; 5617 5618 if (performButtonActionOnTouchDown(event)) { 5619 break; 5620 } 5621 5622 // Walk up the hierarchy to determine if we're inside a scrolling container. 5623 boolean isInScrollingContainer = false; 5624 ViewParent p = getParent(); 5625 while (p != null && p instanceof ViewGroup) { 5626 if (((ViewGroup) p).shouldDelayChildPressedState()) { 5627 isInScrollingContainer = true; 5628 break; 5629 } 5630 p = p.getParent(); 5631 } 5632 5633 // For views inside a scrolling container, delay the pressed feedback for 5634 // a short period in case this is a scroll. 5635 if (isInScrollingContainer) { 5636 mPrivateFlags |= PREPRESSED; 5637 if (mPendingCheckForTap == null) { 5638 mPendingCheckForTap = new CheckForTap(); 5639 } 5640 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 5641 } else { 5642 // Not inside a scrolling container, so show the feedback right away 5643 mPrivateFlags |= PRESSED; 5644 refreshDrawableState(); 5645 checkForLongClick(0); 5646 } 5647 break; 5648 5649 case MotionEvent.ACTION_CANCEL: 5650 mPrivateFlags &= ~PRESSED; 5651 refreshDrawableState(); 5652 removeTapCallback(); 5653 break; 5654 5655 case MotionEvent.ACTION_MOVE: 5656 final int x = (int) event.getX(); 5657 final int y = (int) event.getY(); 5658 5659 // Be lenient about moving outside of buttons 5660 if (!pointInView(x, y, mTouchSlop)) { 5661 // Outside button 5662 removeTapCallback(); 5663 if ((mPrivateFlags & PRESSED) != 0) { 5664 // Remove any future long press/tap checks 5665 removeLongPressCallback(); 5666 5667 // Need to switch from pressed to not pressed 5668 mPrivateFlags &= ~PRESSED; 5669 refreshDrawableState(); 5670 } 5671 } 5672 break; 5673 } 5674 return true; 5675 } 5676 5677 return false; 5678 } 5679 5680 /** 5681 * Remove the longpress detection timer. 5682 */ 5683 private void removeLongPressCallback() { 5684 if (mPendingCheckForLongPress != null) { 5685 removeCallbacks(mPendingCheckForLongPress); 5686 } 5687 } 5688 5689 /** 5690 * Remove the pending click action 5691 */ 5692 private void removePerformClickCallback() { 5693 if (mPerformClick != null) { 5694 removeCallbacks(mPerformClick); 5695 } 5696 } 5697 5698 /** 5699 * Remove the prepress detection timer. 5700 */ 5701 private void removeUnsetPressCallback() { 5702 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) { 5703 setPressed(false); 5704 removeCallbacks(mUnsetPressedState); 5705 } 5706 } 5707 5708 /** 5709 * Remove the tap detection timer. 5710 */ 5711 private void removeTapCallback() { 5712 if (mPendingCheckForTap != null) { 5713 mPrivateFlags &= ~PREPRESSED; 5714 removeCallbacks(mPendingCheckForTap); 5715 } 5716 } 5717 5718 /** 5719 * Cancels a pending long press. Your subclass can use this if you 5720 * want the context menu to come up if the user presses and holds 5721 * at the same place, but you don't want it to come up if they press 5722 * and then move around enough to cause scrolling. 5723 */ 5724 public void cancelLongPress() { 5725 removeLongPressCallback(); 5726 5727 /* 5728 * The prepressed state handled by the tap callback is a display 5729 * construct, but the tap callback will post a long press callback 5730 * less its own timeout. Remove it here. 5731 */ 5732 removeTapCallback(); 5733 } 5734 5735 /** 5736 * Sets the TouchDelegate for this View. 5737 */ 5738 public void setTouchDelegate(TouchDelegate delegate) { 5739 mTouchDelegate = delegate; 5740 } 5741 5742 /** 5743 * Gets the TouchDelegate for this View. 5744 */ 5745 public TouchDelegate getTouchDelegate() { 5746 return mTouchDelegate; 5747 } 5748 5749 /** 5750 * Set flags controlling behavior of this view. 5751 * 5752 * @param flags Constant indicating the value which should be set 5753 * @param mask Constant indicating the bit range that should be changed 5754 */ 5755 void setFlags(int flags, int mask) { 5756 int old = mViewFlags; 5757 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 5758 5759 int changed = mViewFlags ^ old; 5760 if (changed == 0) { 5761 return; 5762 } 5763 int privateFlags = mPrivateFlags; 5764 5765 /* Check if the FOCUSABLE bit has changed */ 5766 if (((changed & FOCUSABLE_MASK) != 0) && 5767 ((privateFlags & HAS_BOUNDS) !=0)) { 5768 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 5769 && ((privateFlags & FOCUSED) != 0)) { 5770 /* Give up focus if we are no longer focusable */ 5771 clearFocus(); 5772 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 5773 && ((privateFlags & FOCUSED) == 0)) { 5774 /* 5775 * Tell the view system that we are now available to take focus 5776 * if no one else already has it. 5777 */ 5778 if (mParent != null) mParent.focusableViewAvailable(this); 5779 } 5780 } 5781 5782 if ((flags & VISIBILITY_MASK) == VISIBLE) { 5783 if ((changed & VISIBILITY_MASK) != 0) { 5784 /* 5785 * If this view is becoming visible, set the DRAWN flag so that 5786 * the next invalidate() will not be skipped. 5787 */ 5788 mPrivateFlags |= DRAWN; 5789 5790 needGlobalAttributesUpdate(true); 5791 5792 // a view becoming visible is worth notifying the parent 5793 // about in case nothing has focus. even if this specific view 5794 // isn't focusable, it may contain something that is, so let 5795 // the root view try to give this focus if nothing else does. 5796 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 5797 mParent.focusableViewAvailable(this); 5798 } 5799 } 5800 } 5801 5802 /* Check if the GONE bit has changed */ 5803 if ((changed & GONE) != 0) { 5804 needGlobalAttributesUpdate(false); 5805 requestLayout(); 5806 invalidate(true); 5807 5808 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 5809 if (hasFocus()) clearFocus(); 5810 destroyDrawingCache(); 5811 } 5812 if (mAttachInfo != null) { 5813 mAttachInfo.mViewVisibilityChanged = true; 5814 } 5815 } 5816 5817 /* Check if the VISIBLE bit has changed */ 5818 if ((changed & INVISIBLE) != 0) { 5819 needGlobalAttributesUpdate(false); 5820 invalidate(true); 5821 5822 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 5823 // root view becoming invisible shouldn't clear focus 5824 if (getRootView() != this) { 5825 clearFocus(); 5826 } 5827 } 5828 if (mAttachInfo != null) { 5829 mAttachInfo.mViewVisibilityChanged = true; 5830 } 5831 } 5832 5833 if ((changed & VISIBILITY_MASK) != 0) { 5834 if (mParent instanceof ViewGroup) { 5835 ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK)); 5836 ((View) mParent).invalidate(true); 5837 } 5838 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 5839 } 5840 5841 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 5842 destroyDrawingCache(); 5843 } 5844 5845 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 5846 destroyDrawingCache(); 5847 mPrivateFlags &= ~DRAWING_CACHE_VALID; 5848 invalidateParentCaches(); 5849 } 5850 5851 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 5852 destroyDrawingCache(); 5853 mPrivateFlags &= ~DRAWING_CACHE_VALID; 5854 } 5855 5856 if ((changed & DRAW_MASK) != 0) { 5857 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 5858 if (mBGDrawable != null) { 5859 mPrivateFlags &= ~SKIP_DRAW; 5860 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 5861 } else { 5862 mPrivateFlags |= SKIP_DRAW; 5863 } 5864 } else { 5865 mPrivateFlags &= ~SKIP_DRAW; 5866 } 5867 requestLayout(); 5868 invalidate(true); 5869 } 5870 5871 if ((changed & KEEP_SCREEN_ON) != 0) { 5872 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 5873 mParent.recomputeViewAttributes(this); 5874 } 5875 } 5876 } 5877 5878 /** 5879 * Change the view's z order in the tree, so it's on top of other sibling 5880 * views 5881 */ 5882 public void bringToFront() { 5883 if (mParent != null) { 5884 mParent.bringChildToFront(this); 5885 } 5886 } 5887 5888 /** 5889 * This is called in response to an internal scroll in this view (i.e., the 5890 * view scrolled its own contents). This is typically as a result of 5891 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 5892 * called. 5893 * 5894 * @param l Current horizontal scroll origin. 5895 * @param t Current vertical scroll origin. 5896 * @param oldl Previous horizontal scroll origin. 5897 * @param oldt Previous vertical scroll origin. 5898 */ 5899 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 5900 mBackgroundSizeChanged = true; 5901 5902 final AttachInfo ai = mAttachInfo; 5903 if (ai != null) { 5904 ai.mViewScrollChanged = true; 5905 } 5906 } 5907 5908 /** 5909 * Interface definition for a callback to be invoked when the layout bounds of a view 5910 * changes due to layout processing. 5911 */ 5912 public interface OnLayoutChangeListener { 5913 /** 5914 * Called when the focus state of a view has changed. 5915 * 5916 * @param v The view whose state has changed. 5917 * @param left The new value of the view's left property. 5918 * @param top The new value of the view's top property. 5919 * @param right The new value of the view's right property. 5920 * @param bottom The new value of the view's bottom property. 5921 * @param oldLeft The previous value of the view's left property. 5922 * @param oldTop The previous value of the view's top property. 5923 * @param oldRight The previous value of the view's right property. 5924 * @param oldBottom The previous value of the view's bottom property. 5925 */ 5926 void onLayoutChange(View v, int left, int top, int right, int bottom, 5927 int oldLeft, int oldTop, int oldRight, int oldBottom); 5928 } 5929 5930 /** 5931 * This is called during layout when the size of this view has changed. If 5932 * you were just added to the view hierarchy, you're called with the old 5933 * values of 0. 5934 * 5935 * @param w Current width of this view. 5936 * @param h Current height of this view. 5937 * @param oldw Old width of this view. 5938 * @param oldh Old height of this view. 5939 */ 5940 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 5941 } 5942 5943 /** 5944 * Called by draw to draw the child views. This may be overridden 5945 * by derived classes to gain control just before its children are drawn 5946 * (but after its own view has been drawn). 5947 * @param canvas the canvas on which to draw the view 5948 */ 5949 protected void dispatchDraw(Canvas canvas) { 5950 } 5951 5952 /** 5953 * Gets the parent of this view. Note that the parent is a 5954 * ViewParent and not necessarily a View. 5955 * 5956 * @return Parent of this view. 5957 */ 5958 public final ViewParent getParent() { 5959 return mParent; 5960 } 5961 5962 /** 5963 * Return the scrolled left position of this view. This is the left edge of 5964 * the displayed part of your view. You do not need to draw any pixels 5965 * farther left, since those are outside of the frame of your view on 5966 * screen. 5967 * 5968 * @return The left edge of the displayed part of your view, in pixels. 5969 */ 5970 public final int getScrollX() { 5971 return mScrollX; 5972 } 5973 5974 /** 5975 * Return the scrolled top position of this view. This is the top edge of 5976 * the displayed part of your view. You do not need to draw any pixels above 5977 * it, since those are outside of the frame of your view on screen. 5978 * 5979 * @return The top edge of the displayed part of your view, in pixels. 5980 */ 5981 public final int getScrollY() { 5982 return mScrollY; 5983 } 5984 5985 /** 5986 * Return the width of the your view. 5987 * 5988 * @return The width of your view, in pixels. 5989 */ 5990 @ViewDebug.ExportedProperty(category = "layout") 5991 public final int getWidth() { 5992 return mRight - mLeft; 5993 } 5994 5995 /** 5996 * Return the height of your view. 5997 * 5998 * @return The height of your view, in pixels. 5999 */ 6000 @ViewDebug.ExportedProperty(category = "layout") 6001 public final int getHeight() { 6002 return mBottom - mTop; 6003 } 6004 6005 /** 6006 * Return the visible drawing bounds of your view. Fills in the output 6007 * rectangle with the values from getScrollX(), getScrollY(), 6008 * getWidth(), and getHeight(). 6009 * 6010 * @param outRect The (scrolled) drawing bounds of the view. 6011 */ 6012 public void getDrawingRect(Rect outRect) { 6013 outRect.left = mScrollX; 6014 outRect.top = mScrollY; 6015 outRect.right = mScrollX + (mRight - mLeft); 6016 outRect.bottom = mScrollY + (mBottom - mTop); 6017 } 6018 6019 /** 6020 * Like {@link #getMeasuredWidthAndState()}, but only returns the 6021 * raw width component (that is the result is masked by 6022 * {@link #MEASURED_SIZE_MASK}). 6023 * 6024 * @return The raw measured width of this view. 6025 */ 6026 public final int getMeasuredWidth() { 6027 return mMeasuredWidth & MEASURED_SIZE_MASK; 6028 } 6029 6030 /** 6031 * Return the full width measurement information for this view as computed 6032 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6033 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6034 * This should be used during measurement and layout calculations only. Use 6035 * {@link #getWidth()} to see how wide a view is after layout. 6036 * 6037 * @return The measured width of this view as a bit mask. 6038 */ 6039 public final int getMeasuredWidthAndState() { 6040 return mMeasuredWidth; 6041 } 6042 6043 /** 6044 * Like {@link #getMeasuredHeightAndState()}, but only returns the 6045 * raw width component (that is the result is masked by 6046 * {@link #MEASURED_SIZE_MASK}). 6047 * 6048 * @return The raw measured height of this view. 6049 */ 6050 public final int getMeasuredHeight() { 6051 return mMeasuredHeight & MEASURED_SIZE_MASK; 6052 } 6053 6054 /** 6055 * Return the full height measurement information for this view as computed 6056 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6057 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6058 * This should be used during measurement and layout calculations only. Use 6059 * {@link #getHeight()} to see how wide a view is after layout. 6060 * 6061 * @return The measured width of this view as a bit mask. 6062 */ 6063 public final int getMeasuredHeightAndState() { 6064 return mMeasuredHeight; 6065 } 6066 6067 /** 6068 * Return only the state bits of {@link #getMeasuredWidthAndState()} 6069 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 6070 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 6071 * and the height component is at the shifted bits 6072 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 6073 */ 6074 public final int getMeasuredState() { 6075 return (mMeasuredWidth&MEASURED_STATE_MASK) 6076 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 6077 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 6078 } 6079 6080 /** 6081 * The transform matrix of this view, which is calculated based on the current 6082 * roation, scale, and pivot properties. 6083 * 6084 * @see #getRotation() 6085 * @see #getScaleX() 6086 * @see #getScaleY() 6087 * @see #getPivotX() 6088 * @see #getPivotY() 6089 * @return The current transform matrix for the view 6090 */ 6091 public Matrix getMatrix() { 6092 updateMatrix(); 6093 return mMatrix; 6094 } 6095 6096 /** 6097 * Utility function to determine if the value is far enough away from zero to be 6098 * considered non-zero. 6099 * @param value A floating point value to check for zero-ness 6100 * @return whether the passed-in value is far enough away from zero to be considered non-zero 6101 */ 6102 private static boolean nonzero(float value) { 6103 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 6104 } 6105 6106 /** 6107 * Returns true if the transform matrix is the identity matrix. 6108 * Recomputes the matrix if necessary. 6109 * 6110 * @return True if the transform matrix is the identity matrix, false otherwise. 6111 */ 6112 final boolean hasIdentityMatrix() { 6113 updateMatrix(); 6114 return mMatrixIsIdentity; 6115 } 6116 6117 /** 6118 * Recomputes the transform matrix if necessary. 6119 */ 6120 private void updateMatrix() { 6121 if (mMatrixDirty) { 6122 // transform-related properties have changed since the last time someone 6123 // asked for the matrix; recalculate it with the current values 6124 6125 // Figure out if we need to update the pivot point 6126 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6127 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) { 6128 mPrevWidth = mRight - mLeft; 6129 mPrevHeight = mBottom - mTop; 6130 mPivotX = mPrevWidth / 2f; 6131 mPivotY = mPrevHeight / 2f; 6132 } 6133 } 6134 mMatrix.reset(); 6135 if (!nonzero(mRotationX) && !nonzero(mRotationY)) { 6136 mMatrix.setTranslate(mTranslationX, mTranslationY); 6137 mMatrix.preRotate(mRotation, mPivotX, mPivotY); 6138 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY); 6139 } else { 6140 if (mCamera == null) { 6141 mCamera = new Camera(); 6142 matrix3D = new Matrix(); 6143 } 6144 mCamera.save(); 6145 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY); 6146 mCamera.rotate(mRotationX, mRotationY, -mRotation); 6147 mCamera.getMatrix(matrix3D); 6148 matrix3D.preTranslate(-mPivotX, -mPivotY); 6149 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY); 6150 mMatrix.postConcat(matrix3D); 6151 mCamera.restore(); 6152 } 6153 mMatrixDirty = false; 6154 mMatrixIsIdentity = mMatrix.isIdentity(); 6155 mInverseMatrixDirty = true; 6156 } 6157 } 6158 6159 /** 6160 * Utility method to retrieve the inverse of the current mMatrix property. 6161 * We cache the matrix to avoid recalculating it when transform properties 6162 * have not changed. 6163 * 6164 * @return The inverse of the current matrix of this view. 6165 */ 6166 final Matrix getInverseMatrix() { 6167 updateMatrix(); 6168 if (mInverseMatrixDirty) { 6169 if (mInverseMatrix == null) { 6170 mInverseMatrix = new Matrix(); 6171 } 6172 mMatrix.invert(mInverseMatrix); 6173 mInverseMatrixDirty = false; 6174 } 6175 return mInverseMatrix; 6176 } 6177 6178 /** 6179 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 6180 * views are drawn) from the camera to this view. The camera's distance 6181 * affects 3D transformations, for instance rotations around the X and Y 6182 * axis. If the rotationX or rotationY properties are changed and this view is 6183 * large (more than half the size of the screen), it is recommended to always 6184 * use a camera distance that's greater than the height (X axis rotation) or 6185 * the width (Y axis rotation) of this view.</p> 6186 * 6187 * <p>The distance of the camera from the view plane can have an affect on the 6188 * perspective distortion of the view when it is rotated around the x or y axis. 6189 * For example, a large distance will result in a large viewing angle, and there 6190 * will not be much perspective distortion of the view as it rotates. A short 6191 * distance may cause much more perspective distortion upon rotation, and can 6192 * also result in some drawing artifacts if the rotated view ends up partially 6193 * behind the camera (which is why the recommendation is to use a distance at 6194 * least as far as the size of the view, if the view is to be rotated.)</p> 6195 * 6196 * <p>The distance is expressed in "depth pixels." The default distance depends 6197 * on the screen density. For instance, on a medium density display, the 6198 * default distance is 1280. On a high density display, the default distance 6199 * is 1920.</p> 6200 * 6201 * <p>If you want to specify a distance that leads to visually consistent 6202 * results across various densities, use the following formula:</p> 6203 * <pre> 6204 * float scale = context.getResources().getDisplayMetrics().density; 6205 * view.setCameraDistance(distance * scale); 6206 * </pre> 6207 * 6208 * <p>The density scale factor of a high density display is 1.5, 6209 * and 1920 = 1280 * 1.5.</p> 6210 * 6211 * @param distance The distance in "depth pixels", if negative the opposite 6212 * value is used 6213 * 6214 * @see #setRotationX(float) 6215 * @see #setRotationY(float) 6216 */ 6217 public void setCameraDistance(float distance) { 6218 invalidateParentCaches(); 6219 invalidate(false); 6220 6221 final float dpi = mResources.getDisplayMetrics().densityDpi; 6222 if (mCamera == null) { 6223 mCamera = new Camera(); 6224 matrix3D = new Matrix(); 6225 } 6226 6227 mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 6228 mMatrixDirty = true; 6229 6230 invalidate(false); 6231 } 6232 6233 /** 6234 * The degrees that the view is rotated around the pivot point. 6235 * 6236 * @see #setRotation(float) 6237 * @see #getPivotX() 6238 * @see #getPivotY() 6239 * 6240 * @return The degrees of rotation. 6241 */ 6242 public float getRotation() { 6243 return mRotation; 6244 } 6245 6246 /** 6247 * Sets the degrees that the view is rotated around the pivot point. Increasing values 6248 * result in clockwise rotation. 6249 * 6250 * @param rotation The degrees of rotation. 6251 * 6252 * @see #getRotation() 6253 * @see #getPivotX() 6254 * @see #getPivotY() 6255 * @see #setRotationX(float) 6256 * @see #setRotationY(float) 6257 * 6258 * @attr ref android.R.styleable#View_rotation 6259 */ 6260 public void setRotation(float rotation) { 6261 if (mRotation != rotation) { 6262 invalidateParentCaches(); 6263 // Double-invalidation is necessary to capture view's old and new areas 6264 invalidate(false); 6265 mRotation = rotation; 6266 mMatrixDirty = true; 6267 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6268 invalidate(false); 6269 } 6270 } 6271 6272 /** 6273 * The degrees that the view is rotated around the vertical axis through the pivot point. 6274 * 6275 * @see #getPivotX() 6276 * @see #getPivotY() 6277 * @see #setRotationY(float) 6278 * 6279 * @return The degrees of Y rotation. 6280 */ 6281 public float getRotationY() { 6282 return mRotationY; 6283 } 6284 6285 /** 6286 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 6287 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 6288 * down the y axis. 6289 * 6290 * When rotating large views, it is recommended to adjust the camera distance 6291 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 6292 * 6293 * @param rotationY The degrees of Y rotation. 6294 * 6295 * @see #getRotationY() 6296 * @see #getPivotX() 6297 * @see #getPivotY() 6298 * @see #setRotation(float) 6299 * @see #setRotationX(float) 6300 * @see #setCameraDistance(float) 6301 * 6302 * @attr ref android.R.styleable#View_rotationY 6303 */ 6304 public void setRotationY(float rotationY) { 6305 if (mRotationY != rotationY) { 6306 invalidateParentCaches(); 6307 // Double-invalidation is necessary to capture view's old and new areas 6308 invalidate(false); 6309 mRotationY = rotationY; 6310 mMatrixDirty = true; 6311 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6312 invalidate(false); 6313 } 6314 } 6315 6316 /** 6317 * The degrees that the view is rotated around the horizontal axis through the pivot point. 6318 * 6319 * @see #getPivotX() 6320 * @see #getPivotY() 6321 * @see #setRotationX(float) 6322 * 6323 * @return The degrees of X rotation. 6324 */ 6325 public float getRotationX() { 6326 return mRotationX; 6327 } 6328 6329 /** 6330 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 6331 * Increasing values result in clockwise rotation from the viewpoint of looking down the 6332 * x axis. 6333 * 6334 * When rotating large views, it is recommended to adjust the camera distance 6335 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 6336 * 6337 * @param rotationX The degrees of X rotation. 6338 * 6339 * @see #getRotationX() 6340 * @see #getPivotX() 6341 * @see #getPivotY() 6342 * @see #setRotation(float) 6343 * @see #setRotationY(float) 6344 * @see #setCameraDistance(float) 6345 * 6346 * @attr ref android.R.styleable#View_rotationX 6347 */ 6348 public void setRotationX(float rotationX) { 6349 if (mRotationX != rotationX) { 6350 invalidateParentCaches(); 6351 // Double-invalidation is necessary to capture view's old and new areas 6352 invalidate(false); 6353 mRotationX = rotationX; 6354 mMatrixDirty = true; 6355 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6356 invalidate(false); 6357 } 6358 } 6359 6360 /** 6361 * The amount that the view is scaled in x around the pivot point, as a proportion of 6362 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 6363 * 6364 * <p>By default, this is 1.0f. 6365 * 6366 * @see #getPivotX() 6367 * @see #getPivotY() 6368 * @return The scaling factor. 6369 */ 6370 public float getScaleX() { 6371 return mScaleX; 6372 } 6373 6374 /** 6375 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 6376 * the view's unscaled width. A value of 1 means that no scaling is applied. 6377 * 6378 * @param scaleX The scaling factor. 6379 * @see #getPivotX() 6380 * @see #getPivotY() 6381 * 6382 * @attr ref android.R.styleable#View_scaleX 6383 */ 6384 public void setScaleX(float scaleX) { 6385 if (mScaleX != scaleX) { 6386 invalidateParentCaches(); 6387 // Double-invalidation is necessary to capture view's old and new areas 6388 invalidate(false); 6389 mScaleX = scaleX; 6390 mMatrixDirty = true; 6391 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6392 invalidate(false); 6393 } 6394 } 6395 6396 /** 6397 * The amount that the view is scaled in y around the pivot point, as a proportion of 6398 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 6399 * 6400 * <p>By default, this is 1.0f. 6401 * 6402 * @see #getPivotX() 6403 * @see #getPivotY() 6404 * @return The scaling factor. 6405 */ 6406 public float getScaleY() { 6407 return mScaleY; 6408 } 6409 6410 /** 6411 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 6412 * the view's unscaled width. A value of 1 means that no scaling is applied. 6413 * 6414 * @param scaleY The scaling factor. 6415 * @see #getPivotX() 6416 * @see #getPivotY() 6417 * 6418 * @attr ref android.R.styleable#View_scaleY 6419 */ 6420 public void setScaleY(float scaleY) { 6421 if (mScaleY != scaleY) { 6422 invalidateParentCaches(); 6423 // Double-invalidation is necessary to capture view's old and new areas 6424 invalidate(false); 6425 mScaleY = scaleY; 6426 mMatrixDirty = true; 6427 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6428 invalidate(false); 6429 } 6430 } 6431 6432 /** 6433 * The x location of the point around which the view is {@link #setRotation(float) rotated} 6434 * and {@link #setScaleX(float) scaled}. 6435 * 6436 * @see #getRotation() 6437 * @see #getScaleX() 6438 * @see #getScaleY() 6439 * @see #getPivotY() 6440 * @return The x location of the pivot point. 6441 */ 6442 public float getPivotX() { 6443 return mPivotX; 6444 } 6445 6446 /** 6447 * Sets the x location of the point around which the view is 6448 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 6449 * By default, the pivot point is centered on the object. 6450 * Setting this property disables this behavior and causes the view to use only the 6451 * explicitly set pivotX and pivotY values. 6452 * 6453 * @param pivotX The x location of the pivot point. 6454 * @see #getRotation() 6455 * @see #getScaleX() 6456 * @see #getScaleY() 6457 * @see #getPivotY() 6458 * 6459 * @attr ref android.R.styleable#View_transformPivotX 6460 */ 6461 public void setPivotX(float pivotX) { 6462 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 6463 if (mPivotX != pivotX) { 6464 invalidateParentCaches(); 6465 // Double-invalidation is necessary to capture view's old and new areas 6466 invalidate(false); 6467 mPivotX = pivotX; 6468 mMatrixDirty = true; 6469 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6470 invalidate(false); 6471 } 6472 } 6473 6474 /** 6475 * The y location of the point around which the view is {@link #setRotation(float) rotated} 6476 * and {@link #setScaleY(float) scaled}. 6477 * 6478 * @see #getRotation() 6479 * @see #getScaleX() 6480 * @see #getScaleY() 6481 * @see #getPivotY() 6482 * @return The y location of the pivot point. 6483 */ 6484 public float getPivotY() { 6485 return mPivotY; 6486 } 6487 6488 /** 6489 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 6490 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 6491 * Setting this property disables this behavior and causes the view to use only the 6492 * explicitly set pivotX and pivotY values. 6493 * 6494 * @param pivotY The y location of the pivot point. 6495 * @see #getRotation() 6496 * @see #getScaleX() 6497 * @see #getScaleY() 6498 * @see #getPivotY() 6499 * 6500 * @attr ref android.R.styleable#View_transformPivotY 6501 */ 6502 public void setPivotY(float pivotY) { 6503 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 6504 if (mPivotY != pivotY) { 6505 invalidateParentCaches(); 6506 // Double-invalidation is necessary to capture view's old and new areas 6507 invalidate(false); 6508 mPivotY = pivotY; 6509 mMatrixDirty = true; 6510 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6511 invalidate(false); 6512 } 6513 } 6514 6515 /** 6516 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 6517 * completely transparent and 1 means the view is completely opaque. 6518 * 6519 * <p>By default this is 1.0f. 6520 * @return The opacity of the view. 6521 */ 6522 public float getAlpha() { 6523 return mAlpha; 6524 } 6525 6526 /** 6527 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 6528 * completely transparent and 1 means the view is completely opaque.</p> 6529 * 6530 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 6531 * responsible for applying the opacity itself. Otherwise, calling this method is 6532 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 6533 * setting a hardware layer.</p> 6534 * 6535 * @param alpha The opacity of the view. 6536 * 6537 * @see #setLayerType(int, android.graphics.Paint) 6538 * 6539 * @attr ref android.R.styleable#View_alpha 6540 */ 6541 public void setAlpha(float alpha) { 6542 mAlpha = alpha; 6543 invalidateParentCaches(); 6544 if (onSetAlpha((int) (alpha * 255))) { 6545 mPrivateFlags |= ALPHA_SET; 6546 // subclass is handling alpha - don't optimize rendering cache invalidation 6547 invalidate(true); 6548 } else { 6549 mPrivateFlags &= ~ALPHA_SET; 6550 invalidate(false); 6551 } 6552 } 6553 6554 /** 6555 * Faster version of setAlpha() which performs the same steps except there are 6556 * no calls to invalidate(). The caller of this function should perform proper invalidation 6557 * on the parent and this object. The return value indicates whether the subclass handles 6558 * alpha (the return value for onSetAlpha()). 6559 * 6560 * @param alpha The new value for the alpha property 6561 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) 6562 */ 6563 boolean setAlphaNoInvalidation(float alpha) { 6564 mAlpha = alpha; 6565 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 6566 if (subclassHandlesAlpha) { 6567 mPrivateFlags |= ALPHA_SET; 6568 } else { 6569 mPrivateFlags &= ~ALPHA_SET; 6570 } 6571 return subclassHandlesAlpha; 6572 } 6573 6574 /** 6575 * Top position of this view relative to its parent. 6576 * 6577 * @return The top of this view, in pixels. 6578 */ 6579 @ViewDebug.CapturedViewProperty 6580 public final int getTop() { 6581 return mTop; 6582 } 6583 6584 /** 6585 * Sets the top position of this view relative to its parent. This method is meant to be called 6586 * by the layout system and should not generally be called otherwise, because the property 6587 * may be changed at any time by the layout. 6588 * 6589 * @param top The top of this view, in pixels. 6590 */ 6591 public final void setTop(int top) { 6592 if (top != mTop) { 6593 updateMatrix(); 6594 if (mMatrixIsIdentity) { 6595 if (mAttachInfo != null) { 6596 int minTop; 6597 int yLoc; 6598 if (top < mTop) { 6599 minTop = top; 6600 yLoc = top - mTop; 6601 } else { 6602 minTop = mTop; 6603 yLoc = 0; 6604 } 6605 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 6606 } 6607 } else { 6608 // Double-invalidation is necessary to capture view's old and new areas 6609 invalidate(true); 6610 } 6611 6612 int width = mRight - mLeft; 6613 int oldHeight = mBottom - mTop; 6614 6615 mTop = top; 6616 6617 onSizeChanged(width, mBottom - mTop, width, oldHeight); 6618 6619 if (!mMatrixIsIdentity) { 6620 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6621 // A change in dimension means an auto-centered pivot point changes, too 6622 mMatrixDirty = true; 6623 } 6624 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6625 invalidate(true); 6626 } 6627 mBackgroundSizeChanged = true; 6628 invalidateParentIfNeeded(); 6629 } 6630 } 6631 6632 /** 6633 * Bottom position of this view relative to its parent. 6634 * 6635 * @return The bottom of this view, in pixels. 6636 */ 6637 @ViewDebug.CapturedViewProperty 6638 public final int getBottom() { 6639 return mBottom; 6640 } 6641 6642 /** 6643 * True if this view has changed since the last time being drawn. 6644 * 6645 * @return The dirty state of this view. 6646 */ 6647 public boolean isDirty() { 6648 return (mPrivateFlags & DIRTY_MASK) != 0; 6649 } 6650 6651 /** 6652 * Sets the bottom position of this view relative to its parent. This method is meant to be 6653 * called by the layout system and should not generally be called otherwise, because the 6654 * property may be changed at any time by the layout. 6655 * 6656 * @param bottom The bottom of this view, in pixels. 6657 */ 6658 public final void setBottom(int bottom) { 6659 if (bottom != mBottom) { 6660 updateMatrix(); 6661 if (mMatrixIsIdentity) { 6662 if (mAttachInfo != null) { 6663 int maxBottom; 6664 if (bottom < mBottom) { 6665 maxBottom = mBottom; 6666 } else { 6667 maxBottom = bottom; 6668 } 6669 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 6670 } 6671 } else { 6672 // Double-invalidation is necessary to capture view's old and new areas 6673 invalidate(true); 6674 } 6675 6676 int width = mRight - mLeft; 6677 int oldHeight = mBottom - mTop; 6678 6679 mBottom = bottom; 6680 6681 onSizeChanged(width, mBottom - mTop, width, oldHeight); 6682 6683 if (!mMatrixIsIdentity) { 6684 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6685 // A change in dimension means an auto-centered pivot point changes, too 6686 mMatrixDirty = true; 6687 } 6688 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6689 invalidate(true); 6690 } 6691 mBackgroundSizeChanged = true; 6692 invalidateParentIfNeeded(); 6693 } 6694 } 6695 6696 /** 6697 * Left position of this view relative to its parent. 6698 * 6699 * @return The left edge of this view, in pixels. 6700 */ 6701 @ViewDebug.CapturedViewProperty 6702 public final int getLeft() { 6703 return mLeft; 6704 } 6705 6706 /** 6707 * Sets the left position of this view relative to its parent. This method is meant to be called 6708 * by the layout system and should not generally be called otherwise, because the property 6709 * may be changed at any time by the layout. 6710 * 6711 * @param left The bottom of this view, in pixels. 6712 */ 6713 public final void setLeft(int left) { 6714 if (left != mLeft) { 6715 updateMatrix(); 6716 if (mMatrixIsIdentity) { 6717 if (mAttachInfo != null) { 6718 int minLeft; 6719 int xLoc; 6720 if (left < mLeft) { 6721 minLeft = left; 6722 xLoc = left - mLeft; 6723 } else { 6724 minLeft = mLeft; 6725 xLoc = 0; 6726 } 6727 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 6728 } 6729 } else { 6730 // Double-invalidation is necessary to capture view's old and new areas 6731 invalidate(true); 6732 } 6733 6734 int oldWidth = mRight - mLeft; 6735 int height = mBottom - mTop; 6736 6737 mLeft = left; 6738 6739 onSizeChanged(mRight - mLeft, height, oldWidth, height); 6740 6741 if (!mMatrixIsIdentity) { 6742 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6743 // A change in dimension means an auto-centered pivot point changes, too 6744 mMatrixDirty = true; 6745 } 6746 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6747 invalidate(true); 6748 } 6749 mBackgroundSizeChanged = true; 6750 invalidateParentIfNeeded(); 6751 } 6752 } 6753 6754 /** 6755 * Right position of this view relative to its parent. 6756 * 6757 * @return The right edge of this view, in pixels. 6758 */ 6759 @ViewDebug.CapturedViewProperty 6760 public final int getRight() { 6761 return mRight; 6762 } 6763 6764 /** 6765 * Sets the right position of this view relative to its parent. This method is meant to be called 6766 * by the layout system and should not generally be called otherwise, because the property 6767 * may be changed at any time by the layout. 6768 * 6769 * @param right The bottom of this view, in pixels. 6770 */ 6771 public final void setRight(int right) { 6772 if (right != mRight) { 6773 updateMatrix(); 6774 if (mMatrixIsIdentity) { 6775 if (mAttachInfo != null) { 6776 int maxRight; 6777 if (right < mRight) { 6778 maxRight = mRight; 6779 } else { 6780 maxRight = right; 6781 } 6782 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 6783 } 6784 } else { 6785 // Double-invalidation is necessary to capture view's old and new areas 6786 invalidate(true); 6787 } 6788 6789 int oldWidth = mRight - mLeft; 6790 int height = mBottom - mTop; 6791 6792 mRight = right; 6793 6794 onSizeChanged(mRight - mLeft, height, oldWidth, height); 6795 6796 if (!mMatrixIsIdentity) { 6797 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6798 // A change in dimension means an auto-centered pivot point changes, too 6799 mMatrixDirty = true; 6800 } 6801 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6802 invalidate(true); 6803 } 6804 mBackgroundSizeChanged = true; 6805 invalidateParentIfNeeded(); 6806 } 6807 } 6808 6809 /** 6810 * The visual x position of this view, in pixels. This is equivalent to the 6811 * {@link #setTranslationX(float) translationX} property plus the current 6812 * {@link #getLeft() left} property. 6813 * 6814 * @return The visual x position of this view, in pixels. 6815 */ 6816 public float getX() { 6817 return mLeft + mTranslationX; 6818 } 6819 6820 /** 6821 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 6822 * {@link #setTranslationX(float) translationX} property to be the difference between 6823 * the x value passed in and the current {@link #getLeft() left} property. 6824 * 6825 * @param x The visual x position of this view, in pixels. 6826 */ 6827 public void setX(float x) { 6828 setTranslationX(x - mLeft); 6829 } 6830 6831 /** 6832 * The visual y position of this view, in pixels. This is equivalent to the 6833 * {@link #setTranslationY(float) translationY} property plus the current 6834 * {@link #getTop() top} property. 6835 * 6836 * @return The visual y position of this view, in pixels. 6837 */ 6838 public float getY() { 6839 return mTop + mTranslationY; 6840 } 6841 6842 /** 6843 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 6844 * {@link #setTranslationY(float) translationY} property to be the difference between 6845 * the y value passed in and the current {@link #getTop() top} property. 6846 * 6847 * @param y The visual y position of this view, in pixels. 6848 */ 6849 public void setY(float y) { 6850 setTranslationY(y - mTop); 6851 } 6852 6853 6854 /** 6855 * The horizontal location of this view relative to its {@link #getLeft() left} position. 6856 * This position is post-layout, in addition to wherever the object's 6857 * layout placed it. 6858 * 6859 * @return The horizontal position of this view relative to its left position, in pixels. 6860 */ 6861 public float getTranslationX() { 6862 return mTranslationX; 6863 } 6864 6865 /** 6866 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 6867 * This effectively positions the object post-layout, in addition to wherever the object's 6868 * layout placed it. 6869 * 6870 * @param translationX The horizontal position of this view relative to its left position, 6871 * in pixels. 6872 * 6873 * @attr ref android.R.styleable#View_translationX 6874 */ 6875 public void setTranslationX(float translationX) { 6876 if (mTranslationX != translationX) { 6877 invalidateParentCaches(); 6878 // Double-invalidation is necessary to capture view's old and new areas 6879 invalidate(false); 6880 mTranslationX = translationX; 6881 mMatrixDirty = true; 6882 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6883 invalidate(false); 6884 } 6885 } 6886 6887 /** 6888 * The horizontal location of this view relative to its {@link #getTop() top} position. 6889 * This position is post-layout, in addition to wherever the object's 6890 * layout placed it. 6891 * 6892 * @return The vertical position of this view relative to its top position, 6893 * in pixels. 6894 */ 6895 public float getTranslationY() { 6896 return mTranslationY; 6897 } 6898 6899 /** 6900 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 6901 * This effectively positions the object post-layout, in addition to wherever the object's 6902 * layout placed it. 6903 * 6904 * @param translationY The vertical position of this view relative to its top position, 6905 * in pixels. 6906 * 6907 * @attr ref android.R.styleable#View_translationY 6908 */ 6909 public void setTranslationY(float translationY) { 6910 if (mTranslationY != translationY) { 6911 invalidateParentCaches(); 6912 // Double-invalidation is necessary to capture view's old and new areas 6913 invalidate(false); 6914 mTranslationY = translationY; 6915 mMatrixDirty = true; 6916 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6917 invalidate(false); 6918 } 6919 } 6920 6921 /** 6922 * @hide 6923 */ 6924 public void setFastTranslationX(float x) { 6925 mTranslationX = x; 6926 mMatrixDirty = true; 6927 } 6928 6929 /** 6930 * @hide 6931 */ 6932 public void setFastTranslationY(float y) { 6933 mTranslationY = y; 6934 mMatrixDirty = true; 6935 } 6936 6937 /** 6938 * @hide 6939 */ 6940 public void setFastX(float x) { 6941 mTranslationX = x - mLeft; 6942 mMatrixDirty = true; 6943 } 6944 6945 /** 6946 * @hide 6947 */ 6948 public void setFastY(float y) { 6949 mTranslationY = y - mTop; 6950 mMatrixDirty = true; 6951 } 6952 6953 /** 6954 * @hide 6955 */ 6956 public void setFastScaleX(float x) { 6957 mScaleX = x; 6958 mMatrixDirty = true; 6959 } 6960 6961 /** 6962 * @hide 6963 */ 6964 public void setFastScaleY(float y) { 6965 mScaleY = y; 6966 mMatrixDirty = true; 6967 } 6968 6969 /** 6970 * @hide 6971 */ 6972 public void setFastAlpha(float alpha) { 6973 mAlpha = alpha; 6974 } 6975 6976 /** 6977 * @hide 6978 */ 6979 public void setFastRotationY(float y) { 6980 mRotationY = y; 6981 mMatrixDirty = true; 6982 } 6983 6984 /** 6985 * Hit rectangle in parent's coordinates 6986 * 6987 * @param outRect The hit rectangle of the view. 6988 */ 6989 public void getHitRect(Rect outRect) { 6990 updateMatrix(); 6991 if (mMatrixIsIdentity || mAttachInfo == null) { 6992 outRect.set(mLeft, mTop, mRight, mBottom); 6993 } else { 6994 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 6995 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY); 6996 mMatrix.mapRect(tmpRect); 6997 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 6998 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 6999 } 7000 } 7001 7002 /** 7003 * Determines whether the given point, in local coordinates is inside the view. 7004 */ 7005 /*package*/ final boolean pointInView(float localX, float localY) { 7006 return localX >= 0 && localX < (mRight - mLeft) 7007 && localY >= 0 && localY < (mBottom - mTop); 7008 } 7009 7010 /** 7011 * Utility method to determine whether the given point, in local coordinates, 7012 * is inside the view, where the area of the view is expanded by the slop factor. 7013 * This method is called while processing touch-move events to determine if the event 7014 * is still within the view. 7015 */ 7016 private boolean pointInView(float localX, float localY, float slop) { 7017 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 7018 localY < ((mBottom - mTop) + slop); 7019 } 7020 7021 /** 7022 * When a view has focus and the user navigates away from it, the next view is searched for 7023 * starting from the rectangle filled in by this method. 7024 * 7025 * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)}) 7026 * of the view. However, if your view maintains some idea of internal selection, 7027 * such as a cursor, or a selected row or column, you should override this method and 7028 * fill in a more specific rectangle. 7029 * 7030 * @param r The rectangle to fill in, in this view's coordinates. 7031 */ 7032 public void getFocusedRect(Rect r) { 7033 getDrawingRect(r); 7034 } 7035 7036 /** 7037 * If some part of this view is not clipped by any of its parents, then 7038 * return that area in r in global (root) coordinates. To convert r to local 7039 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x, 7040 * -globalOffset.y)) If the view is completely clipped or translated out, 7041 * return false. 7042 * 7043 * @param r If true is returned, r holds the global coordinates of the 7044 * visible portion of this view. 7045 * @param globalOffset If true is returned, globalOffset holds the dx,dy 7046 * between this view and its root. globalOffet may be null. 7047 * @return true if r is non-empty (i.e. part of the view is visible at the 7048 * root level. 7049 */ 7050 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 7051 int width = mRight - mLeft; 7052 int height = mBottom - mTop; 7053 if (width > 0 && height > 0) { 7054 r.set(0, 0, width, height); 7055 if (globalOffset != null) { 7056 globalOffset.set(-mScrollX, -mScrollY); 7057 } 7058 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 7059 } 7060 return false; 7061 } 7062 7063 public final boolean getGlobalVisibleRect(Rect r) { 7064 return getGlobalVisibleRect(r, null); 7065 } 7066 7067 public final boolean getLocalVisibleRect(Rect r) { 7068 Point offset = new Point(); 7069 if (getGlobalVisibleRect(r, offset)) { 7070 r.offset(-offset.x, -offset.y); // make r local 7071 return true; 7072 } 7073 return false; 7074 } 7075 7076 /** 7077 * Offset this view's vertical location by the specified number of pixels. 7078 * 7079 * @param offset the number of pixels to offset the view by 7080 */ 7081 public void offsetTopAndBottom(int offset) { 7082 if (offset != 0) { 7083 updateMatrix(); 7084 if (mMatrixIsIdentity) { 7085 final ViewParent p = mParent; 7086 if (p != null && mAttachInfo != null) { 7087 final Rect r = mAttachInfo.mTmpInvalRect; 7088 int minTop; 7089 int maxBottom; 7090 int yLoc; 7091 if (offset < 0) { 7092 minTop = mTop + offset; 7093 maxBottom = mBottom; 7094 yLoc = offset; 7095 } else { 7096 minTop = mTop; 7097 maxBottom = mBottom + offset; 7098 yLoc = 0; 7099 } 7100 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 7101 p.invalidateChild(this, r); 7102 } 7103 } else { 7104 invalidate(false); 7105 } 7106 7107 mTop += offset; 7108 mBottom += offset; 7109 7110 if (!mMatrixIsIdentity) { 7111 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7112 invalidate(false); 7113 } 7114 invalidateParentIfNeeded(); 7115 } 7116 } 7117 7118 /** 7119 * Offset this view's horizontal location by the specified amount of pixels. 7120 * 7121 * @param offset the numer of pixels to offset the view by 7122 */ 7123 public void offsetLeftAndRight(int offset) { 7124 if (offset != 0) { 7125 updateMatrix(); 7126 if (mMatrixIsIdentity) { 7127 final ViewParent p = mParent; 7128 if (p != null && mAttachInfo != null) { 7129 final Rect r = mAttachInfo.mTmpInvalRect; 7130 int minLeft; 7131 int maxRight; 7132 if (offset < 0) { 7133 minLeft = mLeft + offset; 7134 maxRight = mRight; 7135 } else { 7136 minLeft = mLeft; 7137 maxRight = mRight + offset; 7138 } 7139 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 7140 p.invalidateChild(this, r); 7141 } 7142 } else { 7143 invalidate(false); 7144 } 7145 7146 mLeft += offset; 7147 mRight += offset; 7148 7149 if (!mMatrixIsIdentity) { 7150 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7151 invalidate(false); 7152 } 7153 invalidateParentIfNeeded(); 7154 } 7155 } 7156 7157 /** 7158 * Get the LayoutParams associated with this view. All views should have 7159 * layout parameters. These supply parameters to the <i>parent</i> of this 7160 * view specifying how it should be arranged. There are many subclasses of 7161 * ViewGroup.LayoutParams, and these correspond to the different subclasses 7162 * of ViewGroup that are responsible for arranging their children. 7163 * 7164 * This method may return null if this View is not attached to a parent 7165 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 7166 * was not invoked successfully. When a View is attached to a parent 7167 * ViewGroup, this method must not return null. 7168 * 7169 * @return The LayoutParams associated with this view, or null if no 7170 * parameters have been set yet 7171 */ 7172 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 7173 public ViewGroup.LayoutParams getLayoutParams() { 7174 return mLayoutParams; 7175 } 7176 7177 /** 7178 * Set the layout parameters associated with this view. These supply 7179 * parameters to the <i>parent</i> of this view specifying how it should be 7180 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 7181 * correspond to the different subclasses of ViewGroup that are responsible 7182 * for arranging their children. 7183 * 7184 * @param params The layout parameters for this view, cannot be null 7185 */ 7186 public void setLayoutParams(ViewGroup.LayoutParams params) { 7187 if (params == null) { 7188 throw new NullPointerException("Layout parameters cannot be null"); 7189 } 7190 mLayoutParams = params; 7191 requestLayout(); 7192 } 7193 7194 /** 7195 * Set the scrolled position of your view. This will cause a call to 7196 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7197 * invalidated. 7198 * @param x the x position to scroll to 7199 * @param y the y position to scroll to 7200 */ 7201 public void scrollTo(int x, int y) { 7202 if (mScrollX != x || mScrollY != y) { 7203 int oldX = mScrollX; 7204 int oldY = mScrollY; 7205 mScrollX = x; 7206 mScrollY = y; 7207 invalidateParentCaches(); 7208 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 7209 if (!awakenScrollBars()) { 7210 invalidate(true); 7211 } 7212 } 7213 } 7214 7215 /** 7216 * Move the scrolled position of your view. This will cause a call to 7217 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7218 * invalidated. 7219 * @param x the amount of pixels to scroll by horizontally 7220 * @param y the amount of pixels to scroll by vertically 7221 */ 7222 public void scrollBy(int x, int y) { 7223 scrollTo(mScrollX + x, mScrollY + y); 7224 } 7225 7226 /** 7227 * <p>Trigger the scrollbars to draw. When invoked this method starts an 7228 * animation to fade the scrollbars out after a default delay. If a subclass 7229 * provides animated scrolling, the start delay should equal the duration 7230 * of the scrolling animation.</p> 7231 * 7232 * <p>The animation starts only if at least one of the scrollbars is 7233 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 7234 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 7235 * this method returns true, and false otherwise. If the animation is 7236 * started, this method calls {@link #invalidate()}; in that case the 7237 * caller should not call {@link #invalidate()}.</p> 7238 * 7239 * <p>This method should be invoked every time a subclass directly updates 7240 * the scroll parameters.</p> 7241 * 7242 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 7243 * and {@link #scrollTo(int, int)}.</p> 7244 * 7245 * @return true if the animation is played, false otherwise 7246 * 7247 * @see #awakenScrollBars(int) 7248 * @see #scrollBy(int, int) 7249 * @see #scrollTo(int, int) 7250 * @see #isHorizontalScrollBarEnabled() 7251 * @see #isVerticalScrollBarEnabled() 7252 * @see #setHorizontalScrollBarEnabled(boolean) 7253 * @see #setVerticalScrollBarEnabled(boolean) 7254 */ 7255 protected boolean awakenScrollBars() { 7256 return mScrollCache != null && 7257 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 7258 } 7259 7260 /** 7261 * Trigger the scrollbars to draw. 7262 * This method differs from awakenScrollBars() only in its default duration. 7263 * initialAwakenScrollBars() will show the scroll bars for longer than 7264 * usual to give the user more of a chance to notice them. 7265 * 7266 * @return true if the animation is played, false otherwise. 7267 */ 7268 private boolean initialAwakenScrollBars() { 7269 return mScrollCache != null && 7270 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 7271 } 7272 7273 /** 7274 * <p> 7275 * Trigger the scrollbars to draw. When invoked this method starts an 7276 * animation to fade the scrollbars out after a fixed delay. If a subclass 7277 * provides animated scrolling, the start delay should equal the duration of 7278 * the scrolling animation. 7279 * </p> 7280 * 7281 * <p> 7282 * The animation starts only if at least one of the scrollbars is enabled, 7283 * as specified by {@link #isHorizontalScrollBarEnabled()} and 7284 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 7285 * this method returns true, and false otherwise. If the animation is 7286 * started, this method calls {@link #invalidate()}; in that case the caller 7287 * should not call {@link #invalidate()}. 7288 * </p> 7289 * 7290 * <p> 7291 * This method should be invoked everytime a subclass directly updates the 7292 * scroll parameters. 7293 * </p> 7294 * 7295 * @param startDelay the delay, in milliseconds, after which the animation 7296 * should start; when the delay is 0, the animation starts 7297 * immediately 7298 * @return true if the animation is played, false otherwise 7299 * 7300 * @see #scrollBy(int, int) 7301 * @see #scrollTo(int, int) 7302 * @see #isHorizontalScrollBarEnabled() 7303 * @see #isVerticalScrollBarEnabled() 7304 * @see #setHorizontalScrollBarEnabled(boolean) 7305 * @see #setVerticalScrollBarEnabled(boolean) 7306 */ 7307 protected boolean awakenScrollBars(int startDelay) { 7308 return awakenScrollBars(startDelay, true); 7309 } 7310 7311 /** 7312 * <p> 7313 * Trigger the scrollbars to draw. When invoked this method starts an 7314 * animation to fade the scrollbars out after a fixed delay. If a subclass 7315 * provides animated scrolling, the start delay should equal the duration of 7316 * the scrolling animation. 7317 * </p> 7318 * 7319 * <p> 7320 * The animation starts only if at least one of the scrollbars is enabled, 7321 * as specified by {@link #isHorizontalScrollBarEnabled()} and 7322 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 7323 * this method returns true, and false otherwise. If the animation is 7324 * started, this method calls {@link #invalidate()} if the invalidate parameter 7325 * is set to true; in that case the caller 7326 * should not call {@link #invalidate()}. 7327 * </p> 7328 * 7329 * <p> 7330 * This method should be invoked everytime a subclass directly updates the 7331 * scroll parameters. 7332 * </p> 7333 * 7334 * @param startDelay the delay, in milliseconds, after which the animation 7335 * should start; when the delay is 0, the animation starts 7336 * immediately 7337 * 7338 * @param invalidate Wheter this method should call invalidate 7339 * 7340 * @return true if the animation is played, false otherwise 7341 * 7342 * @see #scrollBy(int, int) 7343 * @see #scrollTo(int, int) 7344 * @see #isHorizontalScrollBarEnabled() 7345 * @see #isVerticalScrollBarEnabled() 7346 * @see #setHorizontalScrollBarEnabled(boolean) 7347 * @see #setVerticalScrollBarEnabled(boolean) 7348 */ 7349 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 7350 final ScrollabilityCache scrollCache = mScrollCache; 7351 7352 if (scrollCache == null || !scrollCache.fadeScrollBars) { 7353 return false; 7354 } 7355 7356 if (scrollCache.scrollBar == null) { 7357 scrollCache.scrollBar = new ScrollBarDrawable(); 7358 } 7359 7360 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 7361 7362 if (invalidate) { 7363 // Invalidate to show the scrollbars 7364 invalidate(true); 7365 } 7366 7367 if (scrollCache.state == ScrollabilityCache.OFF) { 7368 // FIXME: this is copied from WindowManagerService. 7369 // We should get this value from the system when it 7370 // is possible to do so. 7371 final int KEY_REPEAT_FIRST_DELAY = 750; 7372 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 7373 } 7374 7375 // Tell mScrollCache when we should start fading. This may 7376 // extend the fade start time if one was already scheduled 7377 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 7378 scrollCache.fadeStartTime = fadeStartTime; 7379 scrollCache.state = ScrollabilityCache.ON; 7380 7381 // Schedule our fader to run, unscheduling any old ones first 7382 if (mAttachInfo != null) { 7383 mAttachInfo.mHandler.removeCallbacks(scrollCache); 7384 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 7385 } 7386 7387 return true; 7388 } 7389 7390 return false; 7391 } 7392 7393 /** 7394 * Mark the the area defined by dirty as needing to be drawn. If the view is 7395 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 7396 * in the future. This must be called from a UI thread. To call from a non-UI 7397 * thread, call {@link #postInvalidate()}. 7398 * 7399 * WARNING: This method is destructive to dirty. 7400 * @param dirty the rectangle representing the bounds of the dirty region 7401 */ 7402 public void invalidate(Rect dirty) { 7403 if (ViewDebug.TRACE_HIERARCHY) { 7404 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 7405 } 7406 7407 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 7408 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 7409 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 7410 mPrivateFlags &= ~DRAWING_CACHE_VALID; 7411 mPrivateFlags |= INVALIDATED; 7412 final ViewParent p = mParent; 7413 final AttachInfo ai = mAttachInfo; 7414 //noinspection PointlessBooleanExpression,ConstantConditions 7415 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 7416 if (p != null && ai != null && ai.mHardwareAccelerated) { 7417 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 7418 // with a null dirty rect, which tells the ViewAncestor to redraw everything 7419 p.invalidateChild(this, null); 7420 return; 7421 } 7422 } 7423 if (p != null && ai != null) { 7424 final int scrollX = mScrollX; 7425 final int scrollY = mScrollY; 7426 final Rect r = ai.mTmpInvalRect; 7427 r.set(dirty.left - scrollX, dirty.top - scrollY, 7428 dirty.right - scrollX, dirty.bottom - scrollY); 7429 mParent.invalidateChild(this, r); 7430 } 7431 } 7432 } 7433 7434 /** 7435 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn. 7436 * The coordinates of the dirty rect are relative to the view. 7437 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 7438 * will be called at some point in the future. This must be called from 7439 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 7440 * @param l the left position of the dirty region 7441 * @param t the top position of the dirty region 7442 * @param r the right position of the dirty region 7443 * @param b the bottom position of the dirty region 7444 */ 7445 public void invalidate(int l, int t, int r, int b) { 7446 if (ViewDebug.TRACE_HIERARCHY) { 7447 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 7448 } 7449 7450 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 7451 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 7452 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 7453 mPrivateFlags &= ~DRAWING_CACHE_VALID; 7454 mPrivateFlags |= INVALIDATED; 7455 final ViewParent p = mParent; 7456 final AttachInfo ai = mAttachInfo; 7457 //noinspection PointlessBooleanExpression,ConstantConditions 7458 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 7459 if (p != null && ai != null && ai.mHardwareAccelerated) { 7460 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 7461 // with a null dirty rect, which tells the ViewAncestor to redraw everything 7462 p.invalidateChild(this, null); 7463 return; 7464 } 7465 } 7466 if (p != null && ai != null && l < r && t < b) { 7467 final int scrollX = mScrollX; 7468 final int scrollY = mScrollY; 7469 final Rect tmpr = ai.mTmpInvalRect; 7470 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 7471 p.invalidateChild(this, tmpr); 7472 } 7473 } 7474 } 7475 7476 /** 7477 * Invalidate the whole view. If the view is visible, 7478 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 7479 * the future. This must be called from a UI thread. To call from a non-UI thread, 7480 * call {@link #postInvalidate()}. 7481 */ 7482 public void invalidate() { 7483 invalidate(true); 7484 } 7485 7486 /** 7487 * This is where the invalidate() work actually happens. A full invalidate() 7488 * causes the drawing cache to be invalidated, but this function can be called with 7489 * invalidateCache set to false to skip that invalidation step for cases that do not 7490 * need it (for example, a component that remains at the same dimensions with the same 7491 * content). 7492 * 7493 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 7494 * well. This is usually true for a full invalidate, but may be set to false if the 7495 * View's contents or dimensions have not changed. 7496 */ 7497 void invalidate(boolean invalidateCache) { 7498 if (ViewDebug.TRACE_HIERARCHY) { 7499 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 7500 } 7501 7502 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 7503 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) || 7504 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) { 7505 mLastIsOpaque = isOpaque(); 7506 mPrivateFlags &= ~DRAWN; 7507 if (invalidateCache) { 7508 mPrivateFlags |= INVALIDATED; 7509 mPrivateFlags &= ~DRAWING_CACHE_VALID; 7510 } 7511 final AttachInfo ai = mAttachInfo; 7512 final ViewParent p = mParent; 7513 //noinspection PointlessBooleanExpression,ConstantConditions 7514 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 7515 if (p != null && ai != null && ai.mHardwareAccelerated) { 7516 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 7517 // with a null dirty rect, which tells the ViewAncestor to redraw everything 7518 p.invalidateChild(this, null); 7519 return; 7520 } 7521 } 7522 7523 if (p != null && ai != null) { 7524 final Rect r = ai.mTmpInvalRect; 7525 r.set(0, 0, mRight - mLeft, mBottom - mTop); 7526 // Don't call invalidate -- we don't want to internally scroll 7527 // our own bounds 7528 p.invalidateChild(this, r); 7529 } 7530 } 7531 } 7532 7533 /** 7534 * @hide 7535 */ 7536 public void fastInvalidate() { 7537 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 7538 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 7539 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 7540 if (mParent instanceof View) { 7541 ((View) mParent).mPrivateFlags |= INVALIDATED; 7542 } 7543 mPrivateFlags &= ~DRAWN; 7544 mPrivateFlags |= INVALIDATED; 7545 mPrivateFlags &= ~DRAWING_CACHE_VALID; 7546 if (mParent != null && mAttachInfo != null) { 7547 if (mAttachInfo.mHardwareAccelerated) { 7548 mParent.invalidateChild(this, null); 7549 } else { 7550 final Rect r = mAttachInfo.mTmpInvalRect; 7551 r.set(0, 0, mRight - mLeft, mBottom - mTop); 7552 // Don't call invalidate -- we don't want to internally scroll 7553 // our own bounds 7554 mParent.invalidateChild(this, r); 7555 } 7556 } 7557 } 7558 } 7559 7560 /** 7561 * Used to indicate that the parent of this view should clear its caches. This functionality 7562 * is used to force the parent to rebuild its display list (when hardware-accelerated), 7563 * which is necessary when various parent-managed properties of the view change, such as 7564 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 7565 * clears the parent caches and does not causes an invalidate event. 7566 * 7567 * @hide 7568 */ 7569 protected void invalidateParentCaches() { 7570 if (mParent instanceof View) { 7571 ((View) mParent).mPrivateFlags |= INVALIDATED; 7572 } 7573 } 7574 7575 /** 7576 * Used to indicate that the parent of this view should be invalidated. This functionality 7577 * is used to force the parent to rebuild its display list (when hardware-accelerated), 7578 * which is necessary when various parent-managed properties of the view change, such as 7579 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 7580 * an invalidation event to the parent. 7581 * 7582 * @hide 7583 */ 7584 protected void invalidateParentIfNeeded() { 7585 if (isHardwareAccelerated() && mParent instanceof View) { 7586 ((View) mParent).invalidate(true); 7587 } 7588 } 7589 7590 /** 7591 * Indicates whether this View is opaque. An opaque View guarantees that it will 7592 * draw all the pixels overlapping its bounds using a fully opaque color. 7593 * 7594 * Subclasses of View should override this method whenever possible to indicate 7595 * whether an instance is opaque. Opaque Views are treated in a special way by 7596 * the View hierarchy, possibly allowing it to perform optimizations during 7597 * invalidate/draw passes. 7598 * 7599 * @return True if this View is guaranteed to be fully opaque, false otherwise. 7600 */ 7601 @ViewDebug.ExportedProperty(category = "drawing") 7602 public boolean isOpaque() { 7603 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK && 7604 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD); 7605 } 7606 7607 /** 7608 * @hide 7609 */ 7610 protected void computeOpaqueFlags() { 7611 // Opaque if: 7612 // - Has a background 7613 // - Background is opaque 7614 // - Doesn't have scrollbars or scrollbars are inside overlay 7615 7616 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) { 7617 mPrivateFlags |= OPAQUE_BACKGROUND; 7618 } else { 7619 mPrivateFlags &= ~OPAQUE_BACKGROUND; 7620 } 7621 7622 final int flags = mViewFlags; 7623 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 7624 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 7625 mPrivateFlags |= OPAQUE_SCROLLBARS; 7626 } else { 7627 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 7628 } 7629 } 7630 7631 /** 7632 * @hide 7633 */ 7634 protected boolean hasOpaqueScrollbars() { 7635 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 7636 } 7637 7638 /** 7639 * @return A handler associated with the thread running the View. This 7640 * handler can be used to pump events in the UI events queue. 7641 */ 7642 public Handler getHandler() { 7643 if (mAttachInfo != null) { 7644 return mAttachInfo.mHandler; 7645 } 7646 return null; 7647 } 7648 7649 /** 7650 * Causes the Runnable to be added to the message queue. 7651 * The runnable will be run on the user interface thread. 7652 * 7653 * @param action The Runnable that will be executed. 7654 * 7655 * @return Returns true if the Runnable was successfully placed in to the 7656 * message queue. Returns false on failure, usually because the 7657 * looper processing the message queue is exiting. 7658 */ 7659 public boolean post(Runnable action) { 7660 Handler handler; 7661 AttachInfo attachInfo = mAttachInfo; 7662 if (attachInfo != null) { 7663 handler = attachInfo.mHandler; 7664 } else { 7665 // Assume that post will succeed later 7666 ViewAncestor.getRunQueue().post(action); 7667 return true; 7668 } 7669 7670 return handler.post(action); 7671 } 7672 7673 /** 7674 * Causes the Runnable to be added to the message queue, to be run 7675 * after the specified amount of time elapses. 7676 * The runnable will be run on the user interface thread. 7677 * 7678 * @param action The Runnable that will be executed. 7679 * @param delayMillis The delay (in milliseconds) until the Runnable 7680 * will be executed. 7681 * 7682 * @return true if the Runnable was successfully placed in to the 7683 * message queue. Returns false on failure, usually because the 7684 * looper processing the message queue is exiting. Note that a 7685 * result of true does not mean the Runnable will be processed -- 7686 * if the looper is quit before the delivery time of the message 7687 * occurs then the message will be dropped. 7688 */ 7689 public boolean postDelayed(Runnable action, long delayMillis) { 7690 Handler handler; 7691 AttachInfo attachInfo = mAttachInfo; 7692 if (attachInfo != null) { 7693 handler = attachInfo.mHandler; 7694 } else { 7695 // Assume that post will succeed later 7696 ViewAncestor.getRunQueue().postDelayed(action, delayMillis); 7697 return true; 7698 } 7699 7700 return handler.postDelayed(action, delayMillis); 7701 } 7702 7703 /** 7704 * Removes the specified Runnable from the message queue. 7705 * 7706 * @param action The Runnable to remove from the message handling queue 7707 * 7708 * @return true if this view could ask the Handler to remove the Runnable, 7709 * false otherwise. When the returned value is true, the Runnable 7710 * may or may not have been actually removed from the message queue 7711 * (for instance, if the Runnable was not in the queue already.) 7712 */ 7713 public boolean removeCallbacks(Runnable action) { 7714 Handler handler; 7715 AttachInfo attachInfo = mAttachInfo; 7716 if (attachInfo != null) { 7717 handler = attachInfo.mHandler; 7718 } else { 7719 // Assume that post will succeed later 7720 ViewAncestor.getRunQueue().removeCallbacks(action); 7721 return true; 7722 } 7723 7724 handler.removeCallbacks(action); 7725 return true; 7726 } 7727 7728 /** 7729 * Cause an invalidate to happen on a subsequent cycle through the event loop. 7730 * Use this to invalidate the View from a non-UI thread. 7731 * 7732 * @see #invalidate() 7733 */ 7734 public void postInvalidate() { 7735 postInvalidateDelayed(0); 7736 } 7737 7738 /** 7739 * Cause an invalidate of the specified area to happen on a subsequent cycle 7740 * through the event loop. Use this to invalidate the View from a non-UI thread. 7741 * 7742 * @param left The left coordinate of the rectangle to invalidate. 7743 * @param top The top coordinate of the rectangle to invalidate. 7744 * @param right The right coordinate of the rectangle to invalidate. 7745 * @param bottom The bottom coordinate of the rectangle to invalidate. 7746 * 7747 * @see #invalidate(int, int, int, int) 7748 * @see #invalidate(Rect) 7749 */ 7750 public void postInvalidate(int left, int top, int right, int bottom) { 7751 postInvalidateDelayed(0, left, top, right, bottom); 7752 } 7753 7754 /** 7755 * Cause an invalidate to happen on a subsequent cycle through the event 7756 * loop. Waits for the specified amount of time. 7757 * 7758 * @param delayMilliseconds the duration in milliseconds to delay the 7759 * invalidation by 7760 */ 7761 public void postInvalidateDelayed(long delayMilliseconds) { 7762 // We try only with the AttachInfo because there's no point in invalidating 7763 // if we are not attached to our window 7764 AttachInfo attachInfo = mAttachInfo; 7765 if (attachInfo != null) { 7766 Message msg = Message.obtain(); 7767 msg.what = AttachInfo.INVALIDATE_MSG; 7768 msg.obj = this; 7769 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 7770 } 7771 } 7772 7773 /** 7774 * Cause an invalidate of the specified area to happen on a subsequent cycle 7775 * through the event loop. Waits for the specified amount of time. 7776 * 7777 * @param delayMilliseconds the duration in milliseconds to delay the 7778 * invalidation by 7779 * @param left The left coordinate of the rectangle to invalidate. 7780 * @param top The top coordinate of the rectangle to invalidate. 7781 * @param right The right coordinate of the rectangle to invalidate. 7782 * @param bottom The bottom coordinate of the rectangle to invalidate. 7783 */ 7784 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 7785 int right, int bottom) { 7786 7787 // We try only with the AttachInfo because there's no point in invalidating 7788 // if we are not attached to our window 7789 AttachInfo attachInfo = mAttachInfo; 7790 if (attachInfo != null) { 7791 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 7792 info.target = this; 7793 info.left = left; 7794 info.top = top; 7795 info.right = right; 7796 info.bottom = bottom; 7797 7798 final Message msg = Message.obtain(); 7799 msg.what = AttachInfo.INVALIDATE_RECT_MSG; 7800 msg.obj = info; 7801 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 7802 } 7803 } 7804 7805 /** 7806 * Called by a parent to request that a child update its values for mScrollX 7807 * and mScrollY if necessary. This will typically be done if the child is 7808 * animating a scroll using a {@link android.widget.Scroller Scroller} 7809 * object. 7810 */ 7811 public void computeScroll() { 7812 } 7813 7814 /** 7815 * <p>Indicate whether the horizontal edges are faded when the view is 7816 * scrolled horizontally.</p> 7817 * 7818 * @return true if the horizontal edges should are faded on scroll, false 7819 * otherwise 7820 * 7821 * @see #setHorizontalFadingEdgeEnabled(boolean) 7822 * @attr ref android.R.styleable#View_fadingEdge 7823 */ 7824 public boolean isHorizontalFadingEdgeEnabled() { 7825 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 7826 } 7827 7828 /** 7829 * <p>Define whether the horizontal edges should be faded when this view 7830 * is scrolled horizontally.</p> 7831 * 7832 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 7833 * be faded when the view is scrolled 7834 * horizontally 7835 * 7836 * @see #isHorizontalFadingEdgeEnabled() 7837 * @attr ref android.R.styleable#View_fadingEdge 7838 */ 7839 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 7840 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 7841 if (horizontalFadingEdgeEnabled) { 7842 initScrollCache(); 7843 } 7844 7845 mViewFlags ^= FADING_EDGE_HORIZONTAL; 7846 } 7847 } 7848 7849 /** 7850 * <p>Indicate whether the vertical edges are faded when the view is 7851 * scrolled horizontally.</p> 7852 * 7853 * @return true if the vertical edges should are faded on scroll, false 7854 * otherwise 7855 * 7856 * @see #setVerticalFadingEdgeEnabled(boolean) 7857 * @attr ref android.R.styleable#View_fadingEdge 7858 */ 7859 public boolean isVerticalFadingEdgeEnabled() { 7860 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 7861 } 7862 7863 /** 7864 * <p>Define whether the vertical edges should be faded when this view 7865 * is scrolled vertically.</p> 7866 * 7867 * @param verticalFadingEdgeEnabled true if the vertical edges should 7868 * be faded when the view is scrolled 7869 * vertically 7870 * 7871 * @see #isVerticalFadingEdgeEnabled() 7872 * @attr ref android.R.styleable#View_fadingEdge 7873 */ 7874 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 7875 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 7876 if (verticalFadingEdgeEnabled) { 7877 initScrollCache(); 7878 } 7879 7880 mViewFlags ^= FADING_EDGE_VERTICAL; 7881 } 7882 } 7883 7884 /** 7885 * Returns the strength, or intensity, of the top faded edge. The strength is 7886 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 7887 * returns 0.0 or 1.0 but no value in between. 7888 * 7889 * Subclasses should override this method to provide a smoother fade transition 7890 * when scrolling occurs. 7891 * 7892 * @return the intensity of the top fade as a float between 0.0f and 1.0f 7893 */ 7894 protected float getTopFadingEdgeStrength() { 7895 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 7896 } 7897 7898 /** 7899 * Returns the strength, or intensity, of the bottom faded edge. The strength is 7900 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 7901 * returns 0.0 or 1.0 but no value in between. 7902 * 7903 * Subclasses should override this method to provide a smoother fade transition 7904 * when scrolling occurs. 7905 * 7906 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 7907 */ 7908 protected float getBottomFadingEdgeStrength() { 7909 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 7910 computeVerticalScrollRange() ? 1.0f : 0.0f; 7911 } 7912 7913 /** 7914 * Returns the strength, or intensity, of the left faded edge. The strength is 7915 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 7916 * returns 0.0 or 1.0 but no value in between. 7917 * 7918 * Subclasses should override this method to provide a smoother fade transition 7919 * when scrolling occurs. 7920 * 7921 * @return the intensity of the left fade as a float between 0.0f and 1.0f 7922 */ 7923 protected float getLeftFadingEdgeStrength() { 7924 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 7925 } 7926 7927 /** 7928 * Returns the strength, or intensity, of the right faded edge. The strength is 7929 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 7930 * returns 0.0 or 1.0 but no value in between. 7931 * 7932 * Subclasses should override this method to provide a smoother fade transition 7933 * when scrolling occurs. 7934 * 7935 * @return the intensity of the right fade as a float between 0.0f and 1.0f 7936 */ 7937 protected float getRightFadingEdgeStrength() { 7938 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 7939 computeHorizontalScrollRange() ? 1.0f : 0.0f; 7940 } 7941 7942 /** 7943 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 7944 * scrollbar is not drawn by default.</p> 7945 * 7946 * @return true if the horizontal scrollbar should be painted, false 7947 * otherwise 7948 * 7949 * @see #setHorizontalScrollBarEnabled(boolean) 7950 */ 7951 public boolean isHorizontalScrollBarEnabled() { 7952 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 7953 } 7954 7955 /** 7956 * <p>Define whether the horizontal scrollbar should be drawn or not. The 7957 * scrollbar is not drawn by default.</p> 7958 * 7959 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 7960 * be painted 7961 * 7962 * @see #isHorizontalScrollBarEnabled() 7963 */ 7964 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 7965 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 7966 mViewFlags ^= SCROLLBARS_HORIZONTAL; 7967 computeOpaqueFlags(); 7968 recomputePadding(); 7969 } 7970 } 7971 7972 /** 7973 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 7974 * scrollbar is not drawn by default.</p> 7975 * 7976 * @return true if the vertical scrollbar should be painted, false 7977 * otherwise 7978 * 7979 * @see #setVerticalScrollBarEnabled(boolean) 7980 */ 7981 public boolean isVerticalScrollBarEnabled() { 7982 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 7983 } 7984 7985 /** 7986 * <p>Define whether the vertical scrollbar should be drawn or not. The 7987 * scrollbar is not drawn by default.</p> 7988 * 7989 * @param verticalScrollBarEnabled true if the vertical scrollbar should 7990 * be painted 7991 * 7992 * @see #isVerticalScrollBarEnabled() 7993 */ 7994 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 7995 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 7996 mViewFlags ^= SCROLLBARS_VERTICAL; 7997 computeOpaqueFlags(); 7998 recomputePadding(); 7999 } 8000 } 8001 8002 /** 8003 * @hide 8004 */ 8005 protected void recomputePadding() { 8006 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 8007 } 8008 8009 /** 8010 * Define whether scrollbars will fade when the view is not scrolling. 8011 * 8012 * @param fadeScrollbars wheter to enable fading 8013 * 8014 */ 8015 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 8016 initScrollCache(); 8017 final ScrollabilityCache scrollabilityCache = mScrollCache; 8018 scrollabilityCache.fadeScrollBars = fadeScrollbars; 8019 if (fadeScrollbars) { 8020 scrollabilityCache.state = ScrollabilityCache.OFF; 8021 } else { 8022 scrollabilityCache.state = ScrollabilityCache.ON; 8023 } 8024 } 8025 8026 /** 8027 * 8028 * Returns true if scrollbars will fade when this view is not scrolling 8029 * 8030 * @return true if scrollbar fading is enabled 8031 */ 8032 public boolean isScrollbarFadingEnabled() { 8033 return mScrollCache != null && mScrollCache.fadeScrollBars; 8034 } 8035 8036 /** 8037 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 8038 * inset. When inset, they add to the padding of the view. And the scrollbars 8039 * can be drawn inside the padding area or on the edge of the view. For example, 8040 * if a view has a background drawable and you want to draw the scrollbars 8041 * inside the padding specified by the drawable, you can use 8042 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 8043 * appear at the edge of the view, ignoring the padding, then you can use 8044 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 8045 * @param style the style of the scrollbars. Should be one of 8046 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 8047 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 8048 * @see #SCROLLBARS_INSIDE_OVERLAY 8049 * @see #SCROLLBARS_INSIDE_INSET 8050 * @see #SCROLLBARS_OUTSIDE_OVERLAY 8051 * @see #SCROLLBARS_OUTSIDE_INSET 8052 */ 8053 public void setScrollBarStyle(int style) { 8054 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 8055 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 8056 computeOpaqueFlags(); 8057 recomputePadding(); 8058 } 8059 } 8060 8061 /** 8062 * <p>Returns the current scrollbar style.</p> 8063 * @return the current scrollbar style 8064 * @see #SCROLLBARS_INSIDE_OVERLAY 8065 * @see #SCROLLBARS_INSIDE_INSET 8066 * @see #SCROLLBARS_OUTSIDE_OVERLAY 8067 * @see #SCROLLBARS_OUTSIDE_INSET 8068 */ 8069 public int getScrollBarStyle() { 8070 return mViewFlags & SCROLLBARS_STYLE_MASK; 8071 } 8072 8073 /** 8074 * <p>Compute the horizontal range that the horizontal scrollbar 8075 * represents.</p> 8076 * 8077 * <p>The range is expressed in arbitrary units that must be the same as the 8078 * units used by {@link #computeHorizontalScrollExtent()} and 8079 * {@link #computeHorizontalScrollOffset()}.</p> 8080 * 8081 * <p>The default range is the drawing width of this view.</p> 8082 * 8083 * @return the total horizontal range represented by the horizontal 8084 * scrollbar 8085 * 8086 * @see #computeHorizontalScrollExtent() 8087 * @see #computeHorizontalScrollOffset() 8088 * @see android.widget.ScrollBarDrawable 8089 */ 8090 protected int computeHorizontalScrollRange() { 8091 return getWidth(); 8092 } 8093 8094 /** 8095 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 8096 * within the horizontal range. This value is used to compute the position 8097 * of the thumb within the scrollbar's track.</p> 8098 * 8099 * <p>The range is expressed in arbitrary units that must be the same as the 8100 * units used by {@link #computeHorizontalScrollRange()} and 8101 * {@link #computeHorizontalScrollExtent()}.</p> 8102 * 8103 * <p>The default offset is the scroll offset of this view.</p> 8104 * 8105 * @return the horizontal offset of the scrollbar's thumb 8106 * 8107 * @see #computeHorizontalScrollRange() 8108 * @see #computeHorizontalScrollExtent() 8109 * @see android.widget.ScrollBarDrawable 8110 */ 8111 protected int computeHorizontalScrollOffset() { 8112 return mScrollX; 8113 } 8114 8115 /** 8116 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 8117 * within the horizontal range. This value is used to compute the length 8118 * of the thumb within the scrollbar's track.</p> 8119 * 8120 * <p>The range is expressed in arbitrary units that must be the same as the 8121 * units used by {@link #computeHorizontalScrollRange()} and 8122 * {@link #computeHorizontalScrollOffset()}.</p> 8123 * 8124 * <p>The default extent is the drawing width of this view.</p> 8125 * 8126 * @return the horizontal extent of the scrollbar's thumb 8127 * 8128 * @see #computeHorizontalScrollRange() 8129 * @see #computeHorizontalScrollOffset() 8130 * @see android.widget.ScrollBarDrawable 8131 */ 8132 protected int computeHorizontalScrollExtent() { 8133 return getWidth(); 8134 } 8135 8136 /** 8137 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 8138 * 8139 * <p>The range is expressed in arbitrary units that must be the same as the 8140 * units used by {@link #computeVerticalScrollExtent()} and 8141 * {@link #computeVerticalScrollOffset()}.</p> 8142 * 8143 * @return the total vertical range represented by the vertical scrollbar 8144 * 8145 * <p>The default range is the drawing height of this view.</p> 8146 * 8147 * @see #computeVerticalScrollExtent() 8148 * @see #computeVerticalScrollOffset() 8149 * @see android.widget.ScrollBarDrawable 8150 */ 8151 protected int computeVerticalScrollRange() { 8152 return getHeight(); 8153 } 8154 8155 /** 8156 * <p>Compute the vertical offset of the vertical scrollbar's thumb 8157 * within the horizontal range. This value is used to compute the position 8158 * of the thumb within the scrollbar's track.</p> 8159 * 8160 * <p>The range is expressed in arbitrary units that must be the same as the 8161 * units used by {@link #computeVerticalScrollRange()} and 8162 * {@link #computeVerticalScrollExtent()}.</p> 8163 * 8164 * <p>The default offset is the scroll offset of this view.</p> 8165 * 8166 * @return the vertical offset of the scrollbar's thumb 8167 * 8168 * @see #computeVerticalScrollRange() 8169 * @see #computeVerticalScrollExtent() 8170 * @see android.widget.ScrollBarDrawable 8171 */ 8172 protected int computeVerticalScrollOffset() { 8173 return mScrollY; 8174 } 8175 8176 /** 8177 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 8178 * within the vertical range. This value is used to compute the length 8179 * of the thumb within the scrollbar's track.</p> 8180 * 8181 * <p>The range is expressed in arbitrary units that must be the same as the 8182 * units used by {@link #computeVerticalScrollRange()} and 8183 * {@link #computeVerticalScrollOffset()}.</p> 8184 * 8185 * <p>The default extent is the drawing height of this view.</p> 8186 * 8187 * @return the vertical extent of the scrollbar's thumb 8188 * 8189 * @see #computeVerticalScrollRange() 8190 * @see #computeVerticalScrollOffset() 8191 * @see android.widget.ScrollBarDrawable 8192 */ 8193 protected int computeVerticalScrollExtent() { 8194 return getHeight(); 8195 } 8196 8197 /** 8198 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 8199 * scrollbars are painted only if they have been awakened first.</p> 8200 * 8201 * @param canvas the canvas on which to draw the scrollbars 8202 * 8203 * @see #awakenScrollBars(int) 8204 */ 8205 protected final void onDrawScrollBars(Canvas canvas) { 8206 // scrollbars are drawn only when the animation is running 8207 final ScrollabilityCache cache = mScrollCache; 8208 if (cache != null) { 8209 8210 int state = cache.state; 8211 8212 if (state == ScrollabilityCache.OFF) { 8213 return; 8214 } 8215 8216 boolean invalidate = false; 8217 8218 if (state == ScrollabilityCache.FADING) { 8219 // We're fading -- get our fade interpolation 8220 if (cache.interpolatorValues == null) { 8221 cache.interpolatorValues = new float[1]; 8222 } 8223 8224 float[] values = cache.interpolatorValues; 8225 8226 // Stops the animation if we're done 8227 if (cache.scrollBarInterpolator.timeToValues(values) == 8228 Interpolator.Result.FREEZE_END) { 8229 cache.state = ScrollabilityCache.OFF; 8230 } else { 8231 cache.scrollBar.setAlpha(Math.round(values[0])); 8232 } 8233 8234 // This will make the scroll bars inval themselves after 8235 // drawing. We only want this when we're fading so that 8236 // we prevent excessive redraws 8237 invalidate = true; 8238 } else { 8239 // We're just on -- but we may have been fading before so 8240 // reset alpha 8241 cache.scrollBar.setAlpha(255); 8242 } 8243 8244 8245 final int viewFlags = mViewFlags; 8246 8247 final boolean drawHorizontalScrollBar = 8248 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 8249 final boolean drawVerticalScrollBar = 8250 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 8251 && !isVerticalScrollBarHidden(); 8252 8253 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 8254 final int width = mRight - mLeft; 8255 final int height = mBottom - mTop; 8256 8257 final ScrollBarDrawable scrollBar = cache.scrollBar; 8258 8259 final int scrollX = mScrollX; 8260 final int scrollY = mScrollY; 8261 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 8262 8263 int left, top, right, bottom; 8264 8265 if (drawHorizontalScrollBar) { 8266 int size = scrollBar.getSize(false); 8267 if (size <= 0) { 8268 size = cache.scrollBarSize; 8269 } 8270 8271 scrollBar.setParameters(computeHorizontalScrollRange(), 8272 computeHorizontalScrollOffset(), 8273 computeHorizontalScrollExtent(), false); 8274 final int verticalScrollBarGap = drawVerticalScrollBar ? 8275 getVerticalScrollbarWidth() : 0; 8276 top = scrollY + height - size - (mUserPaddingBottom & inside); 8277 left = scrollX + (mPaddingLeft & inside); 8278 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 8279 bottom = top + size; 8280 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 8281 if (invalidate) { 8282 invalidate(left, top, right, bottom); 8283 } 8284 } 8285 8286 if (drawVerticalScrollBar) { 8287 int size = scrollBar.getSize(true); 8288 if (size <= 0) { 8289 size = cache.scrollBarSize; 8290 } 8291 8292 scrollBar.setParameters(computeVerticalScrollRange(), 8293 computeVerticalScrollOffset(), 8294 computeVerticalScrollExtent(), true); 8295 switch (mVerticalScrollbarPosition) { 8296 default: 8297 case SCROLLBAR_POSITION_DEFAULT: 8298 case SCROLLBAR_POSITION_RIGHT: 8299 left = scrollX + width - size - (mUserPaddingRight & inside); 8300 break; 8301 case SCROLLBAR_POSITION_LEFT: 8302 left = scrollX + (mUserPaddingLeft & inside); 8303 break; 8304 } 8305 top = scrollY + (mPaddingTop & inside); 8306 right = left + size; 8307 bottom = scrollY + height - (mUserPaddingBottom & inside); 8308 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 8309 if (invalidate) { 8310 invalidate(left, top, right, bottom); 8311 } 8312 } 8313 } 8314 } 8315 } 8316 8317 /** 8318 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 8319 * FastScroller is visible. 8320 * @return whether to temporarily hide the vertical scrollbar 8321 * @hide 8322 */ 8323 protected boolean isVerticalScrollBarHidden() { 8324 return false; 8325 } 8326 8327 /** 8328 * <p>Draw the horizontal scrollbar if 8329 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 8330 * 8331 * @param canvas the canvas on which to draw the scrollbar 8332 * @param scrollBar the scrollbar's drawable 8333 * 8334 * @see #isHorizontalScrollBarEnabled() 8335 * @see #computeHorizontalScrollRange() 8336 * @see #computeHorizontalScrollExtent() 8337 * @see #computeHorizontalScrollOffset() 8338 * @see android.widget.ScrollBarDrawable 8339 * @hide 8340 */ 8341 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 8342 int l, int t, int r, int b) { 8343 scrollBar.setBounds(l, t, r, b); 8344 scrollBar.draw(canvas); 8345 } 8346 8347 /** 8348 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 8349 * returns true.</p> 8350 * 8351 * @param canvas the canvas on which to draw the scrollbar 8352 * @param scrollBar the scrollbar's drawable 8353 * 8354 * @see #isVerticalScrollBarEnabled() 8355 * @see #computeVerticalScrollRange() 8356 * @see #computeVerticalScrollExtent() 8357 * @see #computeVerticalScrollOffset() 8358 * @see android.widget.ScrollBarDrawable 8359 * @hide 8360 */ 8361 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 8362 int l, int t, int r, int b) { 8363 scrollBar.setBounds(l, t, r, b); 8364 scrollBar.draw(canvas); 8365 } 8366 8367 /** 8368 * Implement this to do your drawing. 8369 * 8370 * @param canvas the canvas on which the background will be drawn 8371 */ 8372 protected void onDraw(Canvas canvas) { 8373 } 8374 8375 /* 8376 * Caller is responsible for calling requestLayout if necessary. 8377 * (This allows addViewInLayout to not request a new layout.) 8378 */ 8379 void assignParent(ViewParent parent) { 8380 if (mParent == null) { 8381 mParent = parent; 8382 } else if (parent == null) { 8383 mParent = null; 8384 } else { 8385 throw new RuntimeException("view " + this + " being added, but" 8386 + " it already has a parent"); 8387 } 8388 } 8389 8390 /** 8391 * This is called when the view is attached to a window. At this point it 8392 * has a Surface and will start drawing. Note that this function is 8393 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 8394 * however it may be called any time before the first onDraw -- including 8395 * before or after {@link #onMeasure(int, int)}. 8396 * 8397 * @see #onDetachedFromWindow() 8398 */ 8399 protected void onAttachedToWindow() { 8400 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 8401 mParent.requestTransparentRegion(this); 8402 } 8403 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 8404 initialAwakenScrollBars(); 8405 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH; 8406 } 8407 jumpDrawablesToCurrentState(); 8408 } 8409 8410 /** 8411 * This is called when the view is detached from a window. At this point it 8412 * no longer has a surface for drawing. 8413 * 8414 * @see #onAttachedToWindow() 8415 */ 8416 protected void onDetachedFromWindow() { 8417 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 8418 8419 removeUnsetPressCallback(); 8420 removeLongPressCallback(); 8421 removePerformClickCallback(); 8422 8423 destroyDrawingCache(); 8424 8425 if (mHardwareLayer != null) { 8426 mHardwareLayer.destroy(); 8427 mHardwareLayer = null; 8428 } 8429 8430 if (mDisplayList != null) { 8431 mDisplayList.invalidate(); 8432 } 8433 8434 if (mAttachInfo != null) { 8435 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this); 8436 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_RECT_MSG, this); 8437 } 8438 8439 mCurrentAnimation = null; 8440 } 8441 8442 /** 8443 * @return The number of times this view has been attached to a window 8444 */ 8445 protected int getWindowAttachCount() { 8446 return mWindowAttachCount; 8447 } 8448 8449 /** 8450 * Retrieve a unique token identifying the window this view is attached to. 8451 * @return Return the window's token for use in 8452 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 8453 */ 8454 public IBinder getWindowToken() { 8455 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 8456 } 8457 8458 /** 8459 * Retrieve a unique token identifying the top-level "real" window of 8460 * the window that this view is attached to. That is, this is like 8461 * {@link #getWindowToken}, except if the window this view in is a panel 8462 * window (attached to another containing window), then the token of 8463 * the containing window is returned instead. 8464 * 8465 * @return Returns the associated window token, either 8466 * {@link #getWindowToken()} or the containing window's token. 8467 */ 8468 public IBinder getApplicationWindowToken() { 8469 AttachInfo ai = mAttachInfo; 8470 if (ai != null) { 8471 IBinder appWindowToken = ai.mPanelParentWindowToken; 8472 if (appWindowToken == null) { 8473 appWindowToken = ai.mWindowToken; 8474 } 8475 return appWindowToken; 8476 } 8477 return null; 8478 } 8479 8480 /** 8481 * Retrieve private session object this view hierarchy is using to 8482 * communicate with the window manager. 8483 * @return the session object to communicate with the window manager 8484 */ 8485 /*package*/ IWindowSession getWindowSession() { 8486 return mAttachInfo != null ? mAttachInfo.mSession : null; 8487 } 8488 8489 /** 8490 * @param info the {@link android.view.View.AttachInfo} to associated with 8491 * this view 8492 */ 8493 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 8494 //System.out.println("Attached! " + this); 8495 mAttachInfo = info; 8496 mWindowAttachCount++; 8497 // We will need to evaluate the drawable state at least once. 8498 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 8499 if (mFloatingTreeObserver != null) { 8500 info.mTreeObserver.merge(mFloatingTreeObserver); 8501 mFloatingTreeObserver = null; 8502 } 8503 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 8504 mAttachInfo.mScrollContainers.add(this); 8505 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 8506 } 8507 performCollectViewAttributes(visibility); 8508 onAttachedToWindow(); 8509 8510 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 8511 mOnAttachStateChangeListeners; 8512 if (listeners != null && listeners.size() > 0) { 8513 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 8514 // perform the dispatching. The iterator is a safe guard against listeners that 8515 // could mutate the list by calling the various add/remove methods. This prevents 8516 // the array from being modified while we iterate it. 8517 for (OnAttachStateChangeListener listener : listeners) { 8518 listener.onViewAttachedToWindow(this); 8519 } 8520 } 8521 8522 int vis = info.mWindowVisibility; 8523 if (vis != GONE) { 8524 onWindowVisibilityChanged(vis); 8525 } 8526 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 8527 // If nobody has evaluated the drawable state yet, then do it now. 8528 refreshDrawableState(); 8529 } 8530 } 8531 8532 void dispatchDetachedFromWindow() { 8533 AttachInfo info = mAttachInfo; 8534 if (info != null) { 8535 int vis = info.mWindowVisibility; 8536 if (vis != GONE) { 8537 onWindowVisibilityChanged(GONE); 8538 } 8539 } 8540 8541 onDetachedFromWindow(); 8542 8543 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 8544 mOnAttachStateChangeListeners; 8545 if (listeners != null && listeners.size() > 0) { 8546 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 8547 // perform the dispatching. The iterator is a safe guard against listeners that 8548 // could mutate the list by calling the various add/remove methods. This prevents 8549 // the array from being modified while we iterate it. 8550 for (OnAttachStateChangeListener listener : listeners) { 8551 listener.onViewDetachedFromWindow(this); 8552 } 8553 } 8554 8555 if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) { 8556 mAttachInfo.mScrollContainers.remove(this); 8557 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 8558 } 8559 8560 mAttachInfo = null; 8561 } 8562 8563 /** 8564 * Store this view hierarchy's frozen state into the given container. 8565 * 8566 * @param container The SparseArray in which to save the view's state. 8567 * 8568 * @see #restoreHierarchyState(android.util.SparseArray) 8569 * @see #dispatchSaveInstanceState(android.util.SparseArray) 8570 * @see #onSaveInstanceState() 8571 */ 8572 public void saveHierarchyState(SparseArray<Parcelable> container) { 8573 dispatchSaveInstanceState(container); 8574 } 8575 8576 /** 8577 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 8578 * this view and its children. May be overridden to modify how freezing happens to a 8579 * view's children; for example, some views may want to not store state for their children. 8580 * 8581 * @param container The SparseArray in which to save the view's state. 8582 * 8583 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 8584 * @see #saveHierarchyState(android.util.SparseArray) 8585 * @see #onSaveInstanceState() 8586 */ 8587 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 8588 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 8589 mPrivateFlags &= ~SAVE_STATE_CALLED; 8590 Parcelable state = onSaveInstanceState(); 8591 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 8592 throw new IllegalStateException( 8593 "Derived class did not call super.onSaveInstanceState()"); 8594 } 8595 if (state != null) { 8596 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 8597 // + ": " + state); 8598 container.put(mID, state); 8599 } 8600 } 8601 } 8602 8603 /** 8604 * Hook allowing a view to generate a representation of its internal state 8605 * that can later be used to create a new instance with that same state. 8606 * This state should only contain information that is not persistent or can 8607 * not be reconstructed later. For example, you will never store your 8608 * current position on screen because that will be computed again when a 8609 * new instance of the view is placed in its view hierarchy. 8610 * <p> 8611 * Some examples of things you may store here: the current cursor position 8612 * in a text view (but usually not the text itself since that is stored in a 8613 * content provider or other persistent storage), the currently selected 8614 * item in a list view. 8615 * 8616 * @return Returns a Parcelable object containing the view's current dynamic 8617 * state, or null if there is nothing interesting to save. The 8618 * default implementation returns null. 8619 * @see #onRestoreInstanceState(android.os.Parcelable) 8620 * @see #saveHierarchyState(android.util.SparseArray) 8621 * @see #dispatchSaveInstanceState(android.util.SparseArray) 8622 * @see #setSaveEnabled(boolean) 8623 */ 8624 protected Parcelable onSaveInstanceState() { 8625 mPrivateFlags |= SAVE_STATE_CALLED; 8626 return BaseSavedState.EMPTY_STATE; 8627 } 8628 8629 /** 8630 * Restore this view hierarchy's frozen state from the given container. 8631 * 8632 * @param container The SparseArray which holds previously frozen states. 8633 * 8634 * @see #saveHierarchyState(android.util.SparseArray) 8635 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 8636 * @see #onRestoreInstanceState(android.os.Parcelable) 8637 */ 8638 public void restoreHierarchyState(SparseArray<Parcelable> container) { 8639 dispatchRestoreInstanceState(container); 8640 } 8641 8642 /** 8643 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 8644 * state for this view and its children. May be overridden to modify how restoring 8645 * happens to a view's children; for example, some views may want to not store state 8646 * for their children. 8647 * 8648 * @param container The SparseArray which holds previously saved state. 8649 * 8650 * @see #dispatchSaveInstanceState(android.util.SparseArray) 8651 * @see #restoreHierarchyState(android.util.SparseArray) 8652 * @see #onRestoreInstanceState(android.os.Parcelable) 8653 */ 8654 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 8655 if (mID != NO_ID) { 8656 Parcelable state = container.get(mID); 8657 if (state != null) { 8658 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 8659 // + ": " + state); 8660 mPrivateFlags &= ~SAVE_STATE_CALLED; 8661 onRestoreInstanceState(state); 8662 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 8663 throw new IllegalStateException( 8664 "Derived class did not call super.onRestoreInstanceState()"); 8665 } 8666 } 8667 } 8668 } 8669 8670 /** 8671 * Hook allowing a view to re-apply a representation of its internal state that had previously 8672 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 8673 * null state. 8674 * 8675 * @param state The frozen state that had previously been returned by 8676 * {@link #onSaveInstanceState}. 8677 * 8678 * @see #onSaveInstanceState() 8679 * @see #restoreHierarchyState(android.util.SparseArray) 8680 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 8681 */ 8682 protected void onRestoreInstanceState(Parcelable state) { 8683 mPrivateFlags |= SAVE_STATE_CALLED; 8684 if (state != BaseSavedState.EMPTY_STATE && state != null) { 8685 throw new IllegalArgumentException("Wrong state class, expecting View State but " 8686 + "received " + state.getClass().toString() + " instead. This usually happens " 8687 + "when two views of different type have the same id in the same hierarchy. " 8688 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 8689 + "other views do not use the same id."); 8690 } 8691 } 8692 8693 /** 8694 * <p>Return the time at which the drawing of the view hierarchy started.</p> 8695 * 8696 * @return the drawing start time in milliseconds 8697 */ 8698 public long getDrawingTime() { 8699 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 8700 } 8701 8702 /** 8703 * <p>Enables or disables the duplication of the parent's state into this view. When 8704 * duplication is enabled, this view gets its drawable state from its parent rather 8705 * than from its own internal properties.</p> 8706 * 8707 * <p>Note: in the current implementation, setting this property to true after the 8708 * view was added to a ViewGroup might have no effect at all. This property should 8709 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 8710 * 8711 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 8712 * property is enabled, an exception will be thrown.</p> 8713 * 8714 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 8715 * parent, these states should not be affected by this method.</p> 8716 * 8717 * @param enabled True to enable duplication of the parent's drawable state, false 8718 * to disable it. 8719 * 8720 * @see #getDrawableState() 8721 * @see #isDuplicateParentStateEnabled() 8722 */ 8723 public void setDuplicateParentStateEnabled(boolean enabled) { 8724 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 8725 } 8726 8727 /** 8728 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 8729 * 8730 * @return True if this view's drawable state is duplicated from the parent, 8731 * false otherwise 8732 * 8733 * @see #getDrawableState() 8734 * @see #setDuplicateParentStateEnabled(boolean) 8735 */ 8736 public boolean isDuplicateParentStateEnabled() { 8737 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 8738 } 8739 8740 /** 8741 * <p>Specifies the type of layer backing this view. The layer can be 8742 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 8743 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 8744 * 8745 * <p>A layer is associated with an optional {@link android.graphics.Paint} 8746 * instance that controls how the layer is composed on screen. The following 8747 * properties of the paint are taken into account when composing the layer:</p> 8748 * <ul> 8749 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 8750 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 8751 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 8752 * </ul> 8753 * 8754 * <p>If this view has an alpha value set to < 1.0 by calling 8755 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 8756 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 8757 * equivalent to setting a hardware layer on this view and providing a paint with 8758 * the desired alpha value.<p> 8759 * 8760 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 8761 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 8762 * for more information on when and how to use layers.</p> 8763 * 8764 * @param layerType The ype of layer to use with this view, must be one of 8765 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 8766 * {@link #LAYER_TYPE_HARDWARE} 8767 * @param paint The paint used to compose the layer. This argument is optional 8768 * and can be null. It is ignored when the layer type is 8769 * {@link #LAYER_TYPE_NONE} 8770 * 8771 * @see #getLayerType() 8772 * @see #LAYER_TYPE_NONE 8773 * @see #LAYER_TYPE_SOFTWARE 8774 * @see #LAYER_TYPE_HARDWARE 8775 * @see #setAlpha(float) 8776 * 8777 * @attr ref android.R.styleable#View_layerType 8778 */ 8779 public void setLayerType(int layerType, Paint paint) { 8780 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 8781 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 8782 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 8783 } 8784 8785 if (layerType == mLayerType) { 8786 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 8787 mLayerPaint = paint == null ? new Paint() : paint; 8788 invalidateParentCaches(); 8789 invalidate(true); 8790 } 8791 return; 8792 } 8793 8794 // Destroy any previous software drawing cache if needed 8795 switch (mLayerType) { 8796 case LAYER_TYPE_SOFTWARE: 8797 if (mDrawingCache != null) { 8798 mDrawingCache.recycle(); 8799 mDrawingCache = null; 8800 } 8801 8802 if (mUnscaledDrawingCache != null) { 8803 mUnscaledDrawingCache.recycle(); 8804 mUnscaledDrawingCache = null; 8805 } 8806 break; 8807 case LAYER_TYPE_HARDWARE: 8808 if (mHardwareLayer != null) { 8809 mHardwareLayer.destroy(); 8810 mHardwareLayer = null; 8811 } 8812 break; 8813 default: 8814 break; 8815 } 8816 8817 mLayerType = layerType; 8818 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 8819 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 8820 mLocalDirtyRect = layerDisabled ? null : new Rect(); 8821 8822 invalidateParentCaches(); 8823 invalidate(true); 8824 } 8825 8826 /** 8827 * Indicates what type of layer is currently associated with this view. By default 8828 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 8829 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 8830 * for more information on the different types of layers. 8831 * 8832 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 8833 * {@link #LAYER_TYPE_HARDWARE} 8834 * 8835 * @see #setLayerType(int, android.graphics.Paint) 8836 * @see #buildLayer() 8837 * @see #LAYER_TYPE_NONE 8838 * @see #LAYER_TYPE_SOFTWARE 8839 * @see #LAYER_TYPE_HARDWARE 8840 */ 8841 public int getLayerType() { 8842 return mLayerType; 8843 } 8844 8845 /** 8846 * Forces this view's layer to be created and this view to be rendered 8847 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 8848 * invoking this method will have no effect. 8849 * 8850 * This method can for instance be used to render a view into its layer before 8851 * starting an animation. If this view is complex, rendering into the layer 8852 * before starting the animation will avoid skipping frames. 8853 * 8854 * @throws IllegalStateException If this view is not attached to a window 8855 * 8856 * @see #setLayerType(int, android.graphics.Paint) 8857 */ 8858 public void buildLayer() { 8859 if (mLayerType == LAYER_TYPE_NONE) return; 8860 8861 if (mAttachInfo == null) { 8862 throw new IllegalStateException("This view must be attached to a window first"); 8863 } 8864 8865 switch (mLayerType) { 8866 case LAYER_TYPE_HARDWARE: 8867 getHardwareLayer(); 8868 break; 8869 case LAYER_TYPE_SOFTWARE: 8870 buildDrawingCache(true); 8871 break; 8872 } 8873 } 8874 8875 /** 8876 * <p>Returns a hardware layer that can be used to draw this view again 8877 * without executing its draw method.</p> 8878 * 8879 * @return A HardwareLayer ready to render, or null if an error occurred. 8880 */ 8881 HardwareLayer getHardwareLayer() { 8882 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) { 8883 return null; 8884 } 8885 8886 final int width = mRight - mLeft; 8887 final int height = mBottom - mTop; 8888 8889 if (width == 0 || height == 0) { 8890 return null; 8891 } 8892 8893 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 8894 if (mHardwareLayer == null) { 8895 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 8896 width, height, isOpaque()); 8897 mLocalDirtyRect.setEmpty(); 8898 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 8899 mHardwareLayer.resize(width, height); 8900 mLocalDirtyRect.setEmpty(); 8901 } 8902 8903 Canvas currentCanvas = mAttachInfo.mHardwareCanvas; 8904 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas); 8905 mAttachInfo.mHardwareCanvas = canvas; 8906 try { 8907 canvas.setViewport(width, height); 8908 canvas.onPreDraw(mLocalDirtyRect); 8909 mLocalDirtyRect.setEmpty(); 8910 8911 final int restoreCount = canvas.save(); 8912 8913 computeScroll(); 8914 canvas.translate(-mScrollX, -mScrollY); 8915 8916 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 8917 8918 // Fast path for layouts with no backgrounds 8919 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 8920 mPrivateFlags &= ~DIRTY_MASK; 8921 dispatchDraw(canvas); 8922 } else { 8923 draw(canvas); 8924 } 8925 8926 canvas.restoreToCount(restoreCount); 8927 } finally { 8928 canvas.onPostDraw(); 8929 mHardwareLayer.end(currentCanvas); 8930 mAttachInfo.mHardwareCanvas = currentCanvas; 8931 } 8932 } 8933 8934 return mHardwareLayer; 8935 } 8936 8937 /** 8938 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 8939 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 8940 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 8941 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 8942 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 8943 * null.</p> 8944 * 8945 * <p>Enabling the drawing cache is similar to 8946 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 8947 * acceleration is turned off. When hardware acceleration is turned on, enabling the 8948 * drawing cache has no effect on rendering because the system uses a different mechanism 8949 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 8950 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 8951 * for information on how to enable software and hardware layers.</p> 8952 * 8953 * <p>This API can be used to manually generate 8954 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 8955 * {@link #getDrawingCache()}.</p> 8956 * 8957 * @param enabled true to enable the drawing cache, false otherwise 8958 * 8959 * @see #isDrawingCacheEnabled() 8960 * @see #getDrawingCache() 8961 * @see #buildDrawingCache() 8962 * @see #setLayerType(int, android.graphics.Paint) 8963 */ 8964 public void setDrawingCacheEnabled(boolean enabled) { 8965 mCachingFailed = false; 8966 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 8967 } 8968 8969 /** 8970 * <p>Indicates whether the drawing cache is enabled for this view.</p> 8971 * 8972 * @return true if the drawing cache is enabled 8973 * 8974 * @see #setDrawingCacheEnabled(boolean) 8975 * @see #getDrawingCache() 8976 */ 8977 @ViewDebug.ExportedProperty(category = "drawing") 8978 public boolean isDrawingCacheEnabled() { 8979 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 8980 } 8981 8982 /** 8983 * Debugging utility which recursively outputs the dirty state of a view and its 8984 * descendants. 8985 * 8986 * @hide 8987 */ 8988 @SuppressWarnings({"UnusedDeclaration"}) 8989 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 8990 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) + 8991 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" + 8992 (mPrivateFlags & View.DRAWING_CACHE_VALID) + 8993 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")"); 8994 if (clear) { 8995 mPrivateFlags &= clearMask; 8996 } 8997 if (this instanceof ViewGroup) { 8998 ViewGroup parent = (ViewGroup) this; 8999 final int count = parent.getChildCount(); 9000 for (int i = 0; i < count; i++) { 9001 final View child = parent.getChildAt(i); 9002 child.outputDirtyFlags(indent + " ", clear, clearMask); 9003 } 9004 } 9005 } 9006 9007 /** 9008 * This method is used by ViewGroup to cause its children to restore or recreate their 9009 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 9010 * to recreate its own display list, which would happen if it went through the normal 9011 * draw/dispatchDraw mechanisms. 9012 * 9013 * @hide 9014 */ 9015 protected void dispatchGetDisplayList() {} 9016 9017 /** 9018 * A view that is not attached or hardware accelerated cannot create a display list. 9019 * This method checks these conditions and returns the appropriate result. 9020 * 9021 * @return true if view has the ability to create a display list, false otherwise. 9022 * 9023 * @hide 9024 */ 9025 public boolean canHaveDisplayList() { 9026 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 9027 } 9028 9029 /** 9030 * <p>Returns a display list that can be used to draw this view again 9031 * without executing its draw method.</p> 9032 * 9033 * @return A DisplayList ready to replay, or null if caching is not enabled. 9034 * 9035 * @hide 9036 */ 9037 public DisplayList getDisplayList() { 9038 if (!canHaveDisplayList()) { 9039 return null; 9040 } 9041 9042 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || 9043 mDisplayList == null || !mDisplayList.isValid() || 9044 mRecreateDisplayList)) { 9045 // Don't need to recreate the display list, just need to tell our 9046 // children to restore/recreate theirs 9047 if (mDisplayList != null && mDisplayList.isValid() && 9048 !mRecreateDisplayList) { 9049 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9050 mPrivateFlags &= ~DIRTY_MASK; 9051 dispatchGetDisplayList(); 9052 9053 return mDisplayList; 9054 } 9055 9056 // If we got here, we're recreating it. Mark it as such to ensure that 9057 // we copy in child display lists into ours in drawChild() 9058 mRecreateDisplayList = true; 9059 if (mDisplayList == null) { 9060 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(this); 9061 // If we're creating a new display list, make sure our parent gets invalidated 9062 // since they will need to recreate their display list to account for this 9063 // new child display list. 9064 invalidateParentCaches(); 9065 } 9066 9067 final HardwareCanvas canvas = mDisplayList.start(); 9068 try { 9069 int width = mRight - mLeft; 9070 int height = mBottom - mTop; 9071 9072 canvas.setViewport(width, height); 9073 // The dirty rect should always be null for a display list 9074 canvas.onPreDraw(null); 9075 9076 final int restoreCount = canvas.save(); 9077 9078 computeScroll(); 9079 canvas.translate(-mScrollX, -mScrollY); 9080 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9081 9082 // Fast path for layouts with no backgrounds 9083 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 9084 mPrivateFlags &= ~DIRTY_MASK; 9085 dispatchDraw(canvas); 9086 } else { 9087 draw(canvas); 9088 } 9089 9090 canvas.restoreToCount(restoreCount); 9091 } finally { 9092 canvas.onPostDraw(); 9093 9094 mDisplayList.end(); 9095 } 9096 } else { 9097 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9098 mPrivateFlags &= ~DIRTY_MASK; 9099 } 9100 9101 return mDisplayList; 9102 } 9103 9104 /** 9105 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 9106 * 9107 * @return A non-scaled bitmap representing this view or null if cache is disabled. 9108 * 9109 * @see #getDrawingCache(boolean) 9110 */ 9111 public Bitmap getDrawingCache() { 9112 return getDrawingCache(false); 9113 } 9114 9115 /** 9116 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 9117 * is null when caching is disabled. If caching is enabled and the cache is not ready, 9118 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 9119 * draw from the cache when the cache is enabled. To benefit from the cache, you must 9120 * request the drawing cache by calling this method and draw it on screen if the 9121 * returned bitmap is not null.</p> 9122 * 9123 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 9124 * this method will create a bitmap of the same size as this view. Because this bitmap 9125 * will be drawn scaled by the parent ViewGroup, the result on screen might show 9126 * scaling artifacts. To avoid such artifacts, you should call this method by setting 9127 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 9128 * size than the view. This implies that your application must be able to handle this 9129 * size.</p> 9130 * 9131 * @param autoScale Indicates whether the generated bitmap should be scaled based on 9132 * the current density of the screen when the application is in compatibility 9133 * mode. 9134 * 9135 * @return A bitmap representing this view or null if cache is disabled. 9136 * 9137 * @see #setDrawingCacheEnabled(boolean) 9138 * @see #isDrawingCacheEnabled() 9139 * @see #buildDrawingCache(boolean) 9140 * @see #destroyDrawingCache() 9141 */ 9142 public Bitmap getDrawingCache(boolean autoScale) { 9143 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 9144 return null; 9145 } 9146 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 9147 buildDrawingCache(autoScale); 9148 } 9149 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 9150 } 9151 9152 /** 9153 * <p>Frees the resources used by the drawing cache. If you call 9154 * {@link #buildDrawingCache()} manually without calling 9155 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 9156 * should cleanup the cache with this method afterwards.</p> 9157 * 9158 * @see #setDrawingCacheEnabled(boolean) 9159 * @see #buildDrawingCache() 9160 * @see #getDrawingCache() 9161 */ 9162 public void destroyDrawingCache() { 9163 if (mDrawingCache != null) { 9164 mDrawingCache.recycle(); 9165 mDrawingCache = null; 9166 } 9167 if (mUnscaledDrawingCache != null) { 9168 mUnscaledDrawingCache.recycle(); 9169 mUnscaledDrawingCache = null; 9170 } 9171 } 9172 9173 /** 9174 * Setting a solid background color for the drawing cache's bitmaps will improve 9175 * perfromance and memory usage. Note, though that this should only be used if this 9176 * view will always be drawn on top of a solid color. 9177 * 9178 * @param color The background color to use for the drawing cache's bitmap 9179 * 9180 * @see #setDrawingCacheEnabled(boolean) 9181 * @see #buildDrawingCache() 9182 * @see #getDrawingCache() 9183 */ 9184 public void setDrawingCacheBackgroundColor(int color) { 9185 if (color != mDrawingCacheBackgroundColor) { 9186 mDrawingCacheBackgroundColor = color; 9187 mPrivateFlags &= ~DRAWING_CACHE_VALID; 9188 } 9189 } 9190 9191 /** 9192 * @see #setDrawingCacheBackgroundColor(int) 9193 * 9194 * @return The background color to used for the drawing cache's bitmap 9195 */ 9196 public int getDrawingCacheBackgroundColor() { 9197 return mDrawingCacheBackgroundColor; 9198 } 9199 9200 /** 9201 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 9202 * 9203 * @see #buildDrawingCache(boolean) 9204 */ 9205 public void buildDrawingCache() { 9206 buildDrawingCache(false); 9207 } 9208 9209 /** 9210 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 9211 * 9212 * <p>If you call {@link #buildDrawingCache()} manually without calling 9213 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 9214 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 9215 * 9216 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 9217 * this method will create a bitmap of the same size as this view. Because this bitmap 9218 * will be drawn scaled by the parent ViewGroup, the result on screen might show 9219 * scaling artifacts. To avoid such artifacts, you should call this method by setting 9220 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 9221 * size than the view. This implies that your application must be able to handle this 9222 * size.</p> 9223 * 9224 * <p>You should avoid calling this method when hardware acceleration is enabled. If 9225 * you do not need the drawing cache bitmap, calling this method will increase memory 9226 * usage and cause the view to be rendered in software once, thus negatively impacting 9227 * performance.</p> 9228 * 9229 * @see #getDrawingCache() 9230 * @see #destroyDrawingCache() 9231 */ 9232 public void buildDrawingCache(boolean autoScale) { 9233 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 9234 mDrawingCache == null : mUnscaledDrawingCache == null)) { 9235 mCachingFailed = false; 9236 9237 if (ViewDebug.TRACE_HIERARCHY) { 9238 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 9239 } 9240 9241 int width = mRight - mLeft; 9242 int height = mBottom - mTop; 9243 9244 final AttachInfo attachInfo = mAttachInfo; 9245 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 9246 9247 if (autoScale && scalingRequired) { 9248 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 9249 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 9250 } 9251 9252 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 9253 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 9254 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 9255 9256 if (width <= 0 || height <= 0 || 9257 // Projected bitmap size in bytes 9258 (width * height * (opaque && !use32BitCache ? 2 : 4) > 9259 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 9260 destroyDrawingCache(); 9261 mCachingFailed = true; 9262 return; 9263 } 9264 9265 boolean clear = true; 9266 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 9267 9268 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 9269 Bitmap.Config quality; 9270 if (!opaque) { 9271 // Never pick ARGB_4444 because it looks awful 9272 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 9273 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 9274 case DRAWING_CACHE_QUALITY_AUTO: 9275 quality = Bitmap.Config.ARGB_8888; 9276 break; 9277 case DRAWING_CACHE_QUALITY_LOW: 9278 quality = Bitmap.Config.ARGB_8888; 9279 break; 9280 case DRAWING_CACHE_QUALITY_HIGH: 9281 quality = Bitmap.Config.ARGB_8888; 9282 break; 9283 default: 9284 quality = Bitmap.Config.ARGB_8888; 9285 break; 9286 } 9287 } else { 9288 // Optimization for translucent windows 9289 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 9290 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 9291 } 9292 9293 // Try to cleanup memory 9294 if (bitmap != null) bitmap.recycle(); 9295 9296 try { 9297 bitmap = Bitmap.createBitmap(width, height, quality); 9298 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 9299 if (autoScale) { 9300 mDrawingCache = bitmap; 9301 } else { 9302 mUnscaledDrawingCache = bitmap; 9303 } 9304 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 9305 } catch (OutOfMemoryError e) { 9306 // If there is not enough memory to create the bitmap cache, just 9307 // ignore the issue as bitmap caches are not required to draw the 9308 // view hierarchy 9309 if (autoScale) { 9310 mDrawingCache = null; 9311 } else { 9312 mUnscaledDrawingCache = null; 9313 } 9314 mCachingFailed = true; 9315 return; 9316 } 9317 9318 clear = drawingCacheBackgroundColor != 0; 9319 } 9320 9321 Canvas canvas; 9322 if (attachInfo != null) { 9323 canvas = attachInfo.mCanvas; 9324 if (canvas == null) { 9325 canvas = new Canvas(); 9326 } 9327 canvas.setBitmap(bitmap); 9328 // Temporarily clobber the cached Canvas in case one of our children 9329 // is also using a drawing cache. Without this, the children would 9330 // steal the canvas by attaching their own bitmap to it and bad, bad 9331 // thing would happen (invisible views, corrupted drawings, etc.) 9332 attachInfo.mCanvas = null; 9333 } else { 9334 // This case should hopefully never or seldom happen 9335 canvas = new Canvas(bitmap); 9336 } 9337 9338 if (clear) { 9339 bitmap.eraseColor(drawingCacheBackgroundColor); 9340 } 9341 9342 computeScroll(); 9343 final int restoreCount = canvas.save(); 9344 9345 if (autoScale && scalingRequired) { 9346 final float scale = attachInfo.mApplicationScale; 9347 canvas.scale(scale, scale); 9348 } 9349 9350 canvas.translate(-mScrollX, -mScrollY); 9351 9352 mPrivateFlags |= DRAWN; 9353 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 9354 mLayerType != LAYER_TYPE_NONE) { 9355 mPrivateFlags |= DRAWING_CACHE_VALID; 9356 } 9357 9358 // Fast path for layouts with no backgrounds 9359 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 9360 if (ViewDebug.TRACE_HIERARCHY) { 9361 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 9362 } 9363 mPrivateFlags &= ~DIRTY_MASK; 9364 dispatchDraw(canvas); 9365 } else { 9366 draw(canvas); 9367 } 9368 9369 canvas.restoreToCount(restoreCount); 9370 9371 if (attachInfo != null) { 9372 // Restore the cached Canvas for our siblings 9373 attachInfo.mCanvas = canvas; 9374 } 9375 } 9376 } 9377 9378 /** 9379 * Create a snapshot of the view into a bitmap. We should probably make 9380 * some form of this public, but should think about the API. 9381 */ 9382 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 9383 int width = mRight - mLeft; 9384 int height = mBottom - mTop; 9385 9386 final AttachInfo attachInfo = mAttachInfo; 9387 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 9388 width = (int) ((width * scale) + 0.5f); 9389 height = (int) ((height * scale) + 0.5f); 9390 9391 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 9392 if (bitmap == null) { 9393 throw new OutOfMemoryError(); 9394 } 9395 9396 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 9397 9398 Canvas canvas; 9399 if (attachInfo != null) { 9400 canvas = attachInfo.mCanvas; 9401 if (canvas == null) { 9402 canvas = new Canvas(); 9403 } 9404 canvas.setBitmap(bitmap); 9405 // Temporarily clobber the cached Canvas in case one of our children 9406 // is also using a drawing cache. Without this, the children would 9407 // steal the canvas by attaching their own bitmap to it and bad, bad 9408 // things would happen (invisible views, corrupted drawings, etc.) 9409 attachInfo.mCanvas = null; 9410 } else { 9411 // This case should hopefully never or seldom happen 9412 canvas = new Canvas(bitmap); 9413 } 9414 9415 if ((backgroundColor & 0xff000000) != 0) { 9416 bitmap.eraseColor(backgroundColor); 9417 } 9418 9419 computeScroll(); 9420 final int restoreCount = canvas.save(); 9421 canvas.scale(scale, scale); 9422 canvas.translate(-mScrollX, -mScrollY); 9423 9424 // Temporarily remove the dirty mask 9425 int flags = mPrivateFlags; 9426 mPrivateFlags &= ~DIRTY_MASK; 9427 9428 // Fast path for layouts with no backgrounds 9429 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 9430 dispatchDraw(canvas); 9431 } else { 9432 draw(canvas); 9433 } 9434 9435 mPrivateFlags = flags; 9436 9437 canvas.restoreToCount(restoreCount); 9438 9439 if (attachInfo != null) { 9440 // Restore the cached Canvas for our siblings 9441 attachInfo.mCanvas = canvas; 9442 } 9443 9444 return bitmap; 9445 } 9446 9447 /** 9448 * Indicates whether this View is currently in edit mode. A View is usually 9449 * in edit mode when displayed within a developer tool. For instance, if 9450 * this View is being drawn by a visual user interface builder, this method 9451 * should return true. 9452 * 9453 * Subclasses should check the return value of this method to provide 9454 * different behaviors if their normal behavior might interfere with the 9455 * host environment. For instance: the class spawns a thread in its 9456 * constructor, the drawing code relies on device-specific features, etc. 9457 * 9458 * This method is usually checked in the drawing code of custom widgets. 9459 * 9460 * @return True if this View is in edit mode, false otherwise. 9461 */ 9462 public boolean isInEditMode() { 9463 return false; 9464 } 9465 9466 /** 9467 * If the View draws content inside its padding and enables fading edges, 9468 * it needs to support padding offsets. Padding offsets are added to the 9469 * fading edges to extend the length of the fade so that it covers pixels 9470 * drawn inside the padding. 9471 * 9472 * Subclasses of this class should override this method if they need 9473 * to draw content inside the padding. 9474 * 9475 * @return True if padding offset must be applied, false otherwise. 9476 * 9477 * @see #getLeftPaddingOffset() 9478 * @see #getRightPaddingOffset() 9479 * @see #getTopPaddingOffset() 9480 * @see #getBottomPaddingOffset() 9481 * 9482 * @since CURRENT 9483 */ 9484 protected boolean isPaddingOffsetRequired() { 9485 return false; 9486 } 9487 9488 /** 9489 * Amount by which to extend the left fading region. Called only when 9490 * {@link #isPaddingOffsetRequired()} returns true. 9491 * 9492 * @return The left padding offset in pixels. 9493 * 9494 * @see #isPaddingOffsetRequired() 9495 * 9496 * @since CURRENT 9497 */ 9498 protected int getLeftPaddingOffset() { 9499 return 0; 9500 } 9501 9502 /** 9503 * Amount by which to extend the right fading region. Called only when 9504 * {@link #isPaddingOffsetRequired()} returns true. 9505 * 9506 * @return The right padding offset in pixels. 9507 * 9508 * @see #isPaddingOffsetRequired() 9509 * 9510 * @since CURRENT 9511 */ 9512 protected int getRightPaddingOffset() { 9513 return 0; 9514 } 9515 9516 /** 9517 * Amount by which to extend the top fading region. Called only when 9518 * {@link #isPaddingOffsetRequired()} returns true. 9519 * 9520 * @return The top padding offset in pixels. 9521 * 9522 * @see #isPaddingOffsetRequired() 9523 * 9524 * @since CURRENT 9525 */ 9526 protected int getTopPaddingOffset() { 9527 return 0; 9528 } 9529 9530 /** 9531 * Amount by which to extend the bottom fading region. Called only when 9532 * {@link #isPaddingOffsetRequired()} returns true. 9533 * 9534 * @return The bottom padding offset in pixels. 9535 * 9536 * @see #isPaddingOffsetRequired() 9537 * 9538 * @since CURRENT 9539 */ 9540 protected int getBottomPaddingOffset() { 9541 return 0; 9542 } 9543 9544 /** 9545 * <p>Indicates whether this view is attached to an hardware accelerated 9546 * window or not.</p> 9547 * 9548 * <p>Even if this method returns true, it does not mean that every call 9549 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 9550 * accelerated {@link android.graphics.Canvas}. For instance, if this view 9551 * is drawn onto an offscren {@link android.graphics.Bitmap} and its 9552 * window is hardware accelerated, 9553 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 9554 * return false, and this method will return true.</p> 9555 * 9556 * @return True if the view is attached to a window and the window is 9557 * hardware accelerated; false in any other case. 9558 */ 9559 public boolean isHardwareAccelerated() { 9560 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 9561 } 9562 9563 /** 9564 * Manually render this view (and all of its children) to the given Canvas. 9565 * The view must have already done a full layout before this function is 9566 * called. When implementing a view, implement 9567 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 9568 * If you do need to override this method, call the superclass version. 9569 * 9570 * @param canvas The Canvas to which the View is rendered. 9571 */ 9572 public void draw(Canvas canvas) { 9573 if (ViewDebug.TRACE_HIERARCHY) { 9574 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 9575 } 9576 9577 final int privateFlags = mPrivateFlags; 9578 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 9579 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 9580 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 9581 9582 /* 9583 * Draw traversal performs several drawing steps which must be executed 9584 * in the appropriate order: 9585 * 9586 * 1. Draw the background 9587 * 2. If necessary, save the canvas' layers to prepare for fading 9588 * 3. Draw view's content 9589 * 4. Draw children 9590 * 5. If necessary, draw the fading edges and restore layers 9591 * 6. Draw decorations (scrollbars for instance) 9592 */ 9593 9594 // Step 1, draw the background, if needed 9595 int saveCount; 9596 9597 if (!dirtyOpaque) { 9598 final Drawable background = mBGDrawable; 9599 if (background != null) { 9600 final int scrollX = mScrollX; 9601 final int scrollY = mScrollY; 9602 9603 if (mBackgroundSizeChanged) { 9604 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 9605 mBackgroundSizeChanged = false; 9606 } 9607 9608 if ((scrollX | scrollY) == 0) { 9609 background.draw(canvas); 9610 } else { 9611 canvas.translate(scrollX, scrollY); 9612 background.draw(canvas); 9613 canvas.translate(-scrollX, -scrollY); 9614 } 9615 } 9616 } 9617 9618 // skip step 2 & 5 if possible (common case) 9619 final int viewFlags = mViewFlags; 9620 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 9621 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 9622 if (!verticalEdges && !horizontalEdges) { 9623 // Step 3, draw the content 9624 if (!dirtyOpaque) onDraw(canvas); 9625 9626 // Step 4, draw the children 9627 dispatchDraw(canvas); 9628 9629 // Step 6, draw decorations (scrollbars) 9630 onDrawScrollBars(canvas); 9631 9632 // we're done... 9633 return; 9634 } 9635 9636 /* 9637 * Here we do the full fledged routine... 9638 * (this is an uncommon case where speed matters less, 9639 * this is why we repeat some of the tests that have been 9640 * done above) 9641 */ 9642 9643 boolean drawTop = false; 9644 boolean drawBottom = false; 9645 boolean drawLeft = false; 9646 boolean drawRight = false; 9647 9648 float topFadeStrength = 0.0f; 9649 float bottomFadeStrength = 0.0f; 9650 float leftFadeStrength = 0.0f; 9651 float rightFadeStrength = 0.0f; 9652 9653 // Step 2, save the canvas' layers 9654 int paddingLeft = mPaddingLeft; 9655 int paddingTop = mPaddingTop; 9656 9657 final boolean offsetRequired = isPaddingOffsetRequired(); 9658 if (offsetRequired) { 9659 paddingLeft += getLeftPaddingOffset(); 9660 paddingTop += getTopPaddingOffset(); 9661 } 9662 9663 int left = mScrollX + paddingLeft; 9664 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 9665 int top = mScrollY + paddingTop; 9666 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop; 9667 9668 if (offsetRequired) { 9669 right += getRightPaddingOffset(); 9670 bottom += getBottomPaddingOffset(); 9671 } 9672 9673 final ScrollabilityCache scrollabilityCache = mScrollCache; 9674 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 9675 int length = (int) fadeHeight; 9676 9677 // clip the fade length if top and bottom fades overlap 9678 // overlapping fades produce odd-looking artifacts 9679 if (verticalEdges && (top + length > bottom - length)) { 9680 length = (bottom - top) / 2; 9681 } 9682 9683 // also clip horizontal fades if necessary 9684 if (horizontalEdges && (left + length > right - length)) { 9685 length = (right - left) / 2; 9686 } 9687 9688 if (verticalEdges) { 9689 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 9690 drawTop = topFadeStrength * fadeHeight > 1.0f; 9691 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 9692 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 9693 } 9694 9695 if (horizontalEdges) { 9696 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 9697 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 9698 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 9699 drawRight = rightFadeStrength * fadeHeight > 1.0f; 9700 } 9701 9702 saveCount = canvas.getSaveCount(); 9703 9704 int solidColor = getSolidColor(); 9705 if (solidColor == 0) { 9706 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 9707 9708 if (drawTop) { 9709 canvas.saveLayer(left, top, right, top + length, null, flags); 9710 } 9711 9712 if (drawBottom) { 9713 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 9714 } 9715 9716 if (drawLeft) { 9717 canvas.saveLayer(left, top, left + length, bottom, null, flags); 9718 } 9719 9720 if (drawRight) { 9721 canvas.saveLayer(right - length, top, right, bottom, null, flags); 9722 } 9723 } else { 9724 scrollabilityCache.setFadeColor(solidColor); 9725 } 9726 9727 // Step 3, draw the content 9728 if (!dirtyOpaque) onDraw(canvas); 9729 9730 // Step 4, draw the children 9731 dispatchDraw(canvas); 9732 9733 // Step 5, draw the fade effect and restore layers 9734 final Paint p = scrollabilityCache.paint; 9735 final Matrix matrix = scrollabilityCache.matrix; 9736 final Shader fade = scrollabilityCache.shader; 9737 9738 if (drawTop) { 9739 matrix.setScale(1, fadeHeight * topFadeStrength); 9740 matrix.postTranslate(left, top); 9741 fade.setLocalMatrix(matrix); 9742 canvas.drawRect(left, top, right, top + length, p); 9743 } 9744 9745 if (drawBottom) { 9746 matrix.setScale(1, fadeHeight * bottomFadeStrength); 9747 matrix.postRotate(180); 9748 matrix.postTranslate(left, bottom); 9749 fade.setLocalMatrix(matrix); 9750 canvas.drawRect(left, bottom - length, right, bottom, p); 9751 } 9752 9753 if (drawLeft) { 9754 matrix.setScale(1, fadeHeight * leftFadeStrength); 9755 matrix.postRotate(-90); 9756 matrix.postTranslate(left, top); 9757 fade.setLocalMatrix(matrix); 9758 canvas.drawRect(left, top, left + length, bottom, p); 9759 } 9760 9761 if (drawRight) { 9762 matrix.setScale(1, fadeHeight * rightFadeStrength); 9763 matrix.postRotate(90); 9764 matrix.postTranslate(right, top); 9765 fade.setLocalMatrix(matrix); 9766 canvas.drawRect(right - length, top, right, bottom, p); 9767 } 9768 9769 canvas.restoreToCount(saveCount); 9770 9771 // Step 6, draw decorations (scrollbars) 9772 onDrawScrollBars(canvas); 9773 } 9774 9775 /** 9776 * Override this if your view is known to always be drawn on top of a solid color background, 9777 * and needs to draw fading edges. Returning a non-zero color enables the view system to 9778 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 9779 * should be set to 0xFF. 9780 * 9781 * @see #setVerticalFadingEdgeEnabled(boolean) 9782 * @see #setHorizontalFadingEdgeEnabled(boolean) 9783 * 9784 * @return The known solid color background for this view, or 0 if the color may vary 9785 */ 9786 @ViewDebug.ExportedProperty(category = "drawing") 9787 public int getSolidColor() { 9788 return 0; 9789 } 9790 9791 /** 9792 * Build a human readable string representation of the specified view flags. 9793 * 9794 * @param flags the view flags to convert to a string 9795 * @return a String representing the supplied flags 9796 */ 9797 private static String printFlags(int flags) { 9798 String output = ""; 9799 int numFlags = 0; 9800 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 9801 output += "TAKES_FOCUS"; 9802 numFlags++; 9803 } 9804 9805 switch (flags & VISIBILITY_MASK) { 9806 case INVISIBLE: 9807 if (numFlags > 0) { 9808 output += " "; 9809 } 9810 output += "INVISIBLE"; 9811 // USELESS HERE numFlags++; 9812 break; 9813 case GONE: 9814 if (numFlags > 0) { 9815 output += " "; 9816 } 9817 output += "GONE"; 9818 // USELESS HERE numFlags++; 9819 break; 9820 default: 9821 break; 9822 } 9823 return output; 9824 } 9825 9826 /** 9827 * Build a human readable string representation of the specified private 9828 * view flags. 9829 * 9830 * @param privateFlags the private view flags to convert to a string 9831 * @return a String representing the supplied flags 9832 */ 9833 private static String printPrivateFlags(int privateFlags) { 9834 String output = ""; 9835 int numFlags = 0; 9836 9837 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 9838 output += "WANTS_FOCUS"; 9839 numFlags++; 9840 } 9841 9842 if ((privateFlags & FOCUSED) == FOCUSED) { 9843 if (numFlags > 0) { 9844 output += " "; 9845 } 9846 output += "FOCUSED"; 9847 numFlags++; 9848 } 9849 9850 if ((privateFlags & SELECTED) == SELECTED) { 9851 if (numFlags > 0) { 9852 output += " "; 9853 } 9854 output += "SELECTED"; 9855 numFlags++; 9856 } 9857 9858 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 9859 if (numFlags > 0) { 9860 output += " "; 9861 } 9862 output += "IS_ROOT_NAMESPACE"; 9863 numFlags++; 9864 } 9865 9866 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 9867 if (numFlags > 0) { 9868 output += " "; 9869 } 9870 output += "HAS_BOUNDS"; 9871 numFlags++; 9872 } 9873 9874 if ((privateFlags & DRAWN) == DRAWN) { 9875 if (numFlags > 0) { 9876 output += " "; 9877 } 9878 output += "DRAWN"; 9879 // USELESS HERE numFlags++; 9880 } 9881 return output; 9882 } 9883 9884 /** 9885 * <p>Indicates whether or not this view's layout will be requested during 9886 * the next hierarchy layout pass.</p> 9887 * 9888 * @return true if the layout will be forced during next layout pass 9889 */ 9890 public boolean isLayoutRequested() { 9891 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 9892 } 9893 9894 /** 9895 * Assign a size and position to a view and all of its 9896 * descendants 9897 * 9898 * <p>This is the second phase of the layout mechanism. 9899 * (The first is measuring). In this phase, each parent calls 9900 * layout on all of its children to position them. 9901 * This is typically done using the child measurements 9902 * that were stored in the measure pass().</p> 9903 * 9904 * <p>Derived classes should not override this method. 9905 * Derived classes with children should override 9906 * onLayout. In that method, they should 9907 * call layout on each of their children.</p> 9908 * 9909 * @param l Left position, relative to parent 9910 * @param t Top position, relative to parent 9911 * @param r Right position, relative to parent 9912 * @param b Bottom position, relative to parent 9913 */ 9914 @SuppressWarnings({"unchecked"}) 9915 public void layout(int l, int t, int r, int b) { 9916 int oldL = mLeft; 9917 int oldT = mTop; 9918 int oldB = mBottom; 9919 int oldR = mRight; 9920 boolean changed = setFrame(l, t, r, b); 9921 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 9922 if (ViewDebug.TRACE_HIERARCHY) { 9923 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 9924 } 9925 9926 onLayout(changed, l, t, r, b); 9927 mPrivateFlags &= ~LAYOUT_REQUIRED; 9928 9929 if (mOnLayoutChangeListeners != null) { 9930 ArrayList<OnLayoutChangeListener> listenersCopy = 9931 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone(); 9932 int numListeners = listenersCopy.size(); 9933 for (int i = 0; i < numListeners; ++i) { 9934 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 9935 } 9936 } 9937 } 9938 mPrivateFlags &= ~FORCE_LAYOUT; 9939 } 9940 9941 /** 9942 * Called from layout when this view should 9943 * assign a size and position to each of its children. 9944 * 9945 * Derived classes with children should override 9946 * this method and call layout on each of 9947 * their children. 9948 * @param changed This is a new size or position for this view 9949 * @param left Left position, relative to parent 9950 * @param top Top position, relative to parent 9951 * @param right Right position, relative to parent 9952 * @param bottom Bottom position, relative to parent 9953 */ 9954 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 9955 } 9956 9957 /** 9958 * Assign a size and position to this view. 9959 * 9960 * This is called from layout. 9961 * 9962 * @param left Left position, relative to parent 9963 * @param top Top position, relative to parent 9964 * @param right Right position, relative to parent 9965 * @param bottom Bottom position, relative to parent 9966 * @return true if the new size and position are different than the 9967 * previous ones 9968 * {@hide} 9969 */ 9970 protected boolean setFrame(int left, int top, int right, int bottom) { 9971 boolean changed = false; 9972 9973 if (DBG) { 9974 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 9975 + right + "," + bottom + ")"); 9976 } 9977 9978 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 9979 changed = true; 9980 9981 // Remember our drawn bit 9982 int drawn = mPrivateFlags & DRAWN; 9983 9984 // Invalidate our old position 9985 invalidate(true); 9986 9987 9988 int oldWidth = mRight - mLeft; 9989 int oldHeight = mBottom - mTop; 9990 9991 mLeft = left; 9992 mTop = top; 9993 mRight = right; 9994 mBottom = bottom; 9995 9996 mPrivateFlags |= HAS_BOUNDS; 9997 9998 int newWidth = right - left; 9999 int newHeight = bottom - top; 10000 10001 if (newWidth != oldWidth || newHeight != oldHeight) { 10002 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 10003 // A change in dimension means an auto-centered pivot point changes, too 10004 mMatrixDirty = true; 10005 } 10006 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 10007 } 10008 10009 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 10010 // If we are visible, force the DRAWN bit to on so that 10011 // this invalidate will go through (at least to our parent). 10012 // This is because someone may have invalidated this view 10013 // before this call to setFrame came in, thereby clearing 10014 // the DRAWN bit. 10015 mPrivateFlags |= DRAWN; 10016 invalidate(true); 10017 // parent display list may need to be recreated based on a change in the bounds 10018 // of any child 10019 invalidateParentCaches(); 10020 } 10021 10022 // Reset drawn bit to original value (invalidate turns it off) 10023 mPrivateFlags |= drawn; 10024 10025 mBackgroundSizeChanged = true; 10026 } 10027 return changed; 10028 } 10029 10030 /** 10031 * Finalize inflating a view from XML. This is called as the last phase 10032 * of inflation, after all child views have been added. 10033 * 10034 * <p>Even if the subclass overrides onFinishInflate, they should always be 10035 * sure to call the super method, so that we get called. 10036 */ 10037 protected void onFinishInflate() { 10038 } 10039 10040 /** 10041 * Returns the resources associated with this view. 10042 * 10043 * @return Resources object. 10044 */ 10045 public Resources getResources() { 10046 return mResources; 10047 } 10048 10049 /** 10050 * Invalidates the specified Drawable. 10051 * 10052 * @param drawable the drawable to invalidate 10053 */ 10054 public void invalidateDrawable(Drawable drawable) { 10055 if (verifyDrawable(drawable)) { 10056 final Rect dirty = drawable.getBounds(); 10057 final int scrollX = mScrollX; 10058 final int scrollY = mScrollY; 10059 10060 invalidate(dirty.left + scrollX, dirty.top + scrollY, 10061 dirty.right + scrollX, dirty.bottom + scrollY); 10062 } 10063 } 10064 10065 /** 10066 * Schedules an action on a drawable to occur at a specified time. 10067 * 10068 * @param who the recipient of the action 10069 * @param what the action to run on the drawable 10070 * @param when the time at which the action must occur. Uses the 10071 * {@link SystemClock#uptimeMillis} timebase. 10072 */ 10073 public void scheduleDrawable(Drawable who, Runnable what, long when) { 10074 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 10075 mAttachInfo.mHandler.postAtTime(what, who, when); 10076 } 10077 } 10078 10079 /** 10080 * Cancels a scheduled action on a drawable. 10081 * 10082 * @param who the recipient of the action 10083 * @param what the action to cancel 10084 */ 10085 public void unscheduleDrawable(Drawable who, Runnable what) { 10086 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 10087 mAttachInfo.mHandler.removeCallbacks(what, who); 10088 } 10089 } 10090 10091 /** 10092 * Unschedule any events associated with the given Drawable. This can be 10093 * used when selecting a new Drawable into a view, so that the previous 10094 * one is completely unscheduled. 10095 * 10096 * @param who The Drawable to unschedule. 10097 * 10098 * @see #drawableStateChanged 10099 */ 10100 public void unscheduleDrawable(Drawable who) { 10101 if (mAttachInfo != null) { 10102 mAttachInfo.mHandler.removeCallbacksAndMessages(who); 10103 } 10104 } 10105 10106 /** 10107 * If your view subclass is displaying its own Drawable objects, it should 10108 * override this function and return true for any Drawable it is 10109 * displaying. This allows animations for those drawables to be 10110 * scheduled. 10111 * 10112 * <p>Be sure to call through to the super class when overriding this 10113 * function. 10114 * 10115 * @param who The Drawable to verify. Return true if it is one you are 10116 * displaying, else return the result of calling through to the 10117 * super class. 10118 * 10119 * @return boolean If true than the Drawable is being displayed in the 10120 * view; else false and it is not allowed to animate. 10121 * 10122 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 10123 * @see #drawableStateChanged() 10124 */ 10125 protected boolean verifyDrawable(Drawable who) { 10126 return who == mBGDrawable; 10127 } 10128 10129 /** 10130 * This function is called whenever the state of the view changes in such 10131 * a way that it impacts the state of drawables being shown. 10132 * 10133 * <p>Be sure to call through to the superclass when overriding this 10134 * function. 10135 * 10136 * @see Drawable#setState(int[]) 10137 */ 10138 protected void drawableStateChanged() { 10139 Drawable d = mBGDrawable; 10140 if (d != null && d.isStateful()) { 10141 d.setState(getDrawableState()); 10142 } 10143 } 10144 10145 /** 10146 * Call this to force a view to update its drawable state. This will cause 10147 * drawableStateChanged to be called on this view. Views that are interested 10148 * in the new state should call getDrawableState. 10149 * 10150 * @see #drawableStateChanged 10151 * @see #getDrawableState 10152 */ 10153 public void refreshDrawableState() { 10154 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 10155 drawableStateChanged(); 10156 10157 ViewParent parent = mParent; 10158 if (parent != null) { 10159 parent.childDrawableStateChanged(this); 10160 } 10161 } 10162 10163 /** 10164 * Return an array of resource IDs of the drawable states representing the 10165 * current state of the view. 10166 * 10167 * @return The current drawable state 10168 * 10169 * @see Drawable#setState(int[]) 10170 * @see #drawableStateChanged() 10171 * @see #onCreateDrawableState(int) 10172 */ 10173 public final int[] getDrawableState() { 10174 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 10175 return mDrawableState; 10176 } else { 10177 mDrawableState = onCreateDrawableState(0); 10178 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 10179 return mDrawableState; 10180 } 10181 } 10182 10183 /** 10184 * Generate the new {@link android.graphics.drawable.Drawable} state for 10185 * this view. This is called by the view 10186 * system when the cached Drawable state is determined to be invalid. To 10187 * retrieve the current state, you should use {@link #getDrawableState}. 10188 * 10189 * @param extraSpace if non-zero, this is the number of extra entries you 10190 * would like in the returned array in which you can place your own 10191 * states. 10192 * 10193 * @return Returns an array holding the current {@link Drawable} state of 10194 * the view. 10195 * 10196 * @see #mergeDrawableStates(int[], int[]) 10197 */ 10198 protected int[] onCreateDrawableState(int extraSpace) { 10199 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 10200 mParent instanceof View) { 10201 return ((View) mParent).onCreateDrawableState(extraSpace); 10202 } 10203 10204 int[] drawableState; 10205 10206 int privateFlags = mPrivateFlags; 10207 10208 int viewStateIndex = 0; 10209 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 10210 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 10211 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 10212 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 10213 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 10214 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 10215 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 10216 HardwareRenderer.isAvailable()) { 10217 // This is set if HW acceleration is requested, even if the current 10218 // process doesn't allow it. This is just to allow app preview 10219 // windows to better match their app. 10220 viewStateIndex |= VIEW_STATE_ACCELERATED; 10221 } 10222 if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 10223 10224 final int privateFlags2 = mPrivateFlags2; 10225 if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 10226 if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 10227 10228 drawableState = VIEW_STATE_SETS[viewStateIndex]; 10229 10230 //noinspection ConstantIfStatement 10231 if (false) { 10232 Log.i("View", "drawableStateIndex=" + viewStateIndex); 10233 Log.i("View", toString() 10234 + " pressed=" + ((privateFlags & PRESSED) != 0) 10235 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 10236 + " fo=" + hasFocus() 10237 + " sl=" + ((privateFlags & SELECTED) != 0) 10238 + " wf=" + hasWindowFocus() 10239 + ": " + Arrays.toString(drawableState)); 10240 } 10241 10242 if (extraSpace == 0) { 10243 return drawableState; 10244 } 10245 10246 final int[] fullState; 10247 if (drawableState != null) { 10248 fullState = new int[drawableState.length + extraSpace]; 10249 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 10250 } else { 10251 fullState = new int[extraSpace]; 10252 } 10253 10254 return fullState; 10255 } 10256 10257 /** 10258 * Merge your own state values in <var>additionalState</var> into the base 10259 * state values <var>baseState</var> that were returned by 10260 * {@link #onCreateDrawableState(int)}. 10261 * 10262 * @param baseState The base state values returned by 10263 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 10264 * own additional state values. 10265 * 10266 * @param additionalState The additional state values you would like 10267 * added to <var>baseState</var>; this array is not modified. 10268 * 10269 * @return As a convenience, the <var>baseState</var> array you originally 10270 * passed into the function is returned. 10271 * 10272 * @see #onCreateDrawableState(int) 10273 */ 10274 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 10275 final int N = baseState.length; 10276 int i = N - 1; 10277 while (i >= 0 && baseState[i] == 0) { 10278 i--; 10279 } 10280 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 10281 return baseState; 10282 } 10283 10284 /** 10285 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 10286 * on all Drawable objects associated with this view. 10287 */ 10288 public void jumpDrawablesToCurrentState() { 10289 if (mBGDrawable != null) { 10290 mBGDrawable.jumpToCurrentState(); 10291 } 10292 } 10293 10294 /** 10295 * Sets the background color for this view. 10296 * @param color the color of the background 10297 */ 10298 @RemotableViewMethod 10299 public void setBackgroundColor(int color) { 10300 if (mBGDrawable instanceof ColorDrawable) { 10301 ((ColorDrawable) mBGDrawable).setColor(color); 10302 } else { 10303 setBackgroundDrawable(new ColorDrawable(color)); 10304 } 10305 } 10306 10307 /** 10308 * Set the background to a given resource. The resource should refer to 10309 * a Drawable object or 0 to remove the background. 10310 * @param resid The identifier of the resource. 10311 * @attr ref android.R.styleable#View_background 10312 */ 10313 @RemotableViewMethod 10314 public void setBackgroundResource(int resid) { 10315 if (resid != 0 && resid == mBackgroundResource) { 10316 return; 10317 } 10318 10319 Drawable d= null; 10320 if (resid != 0) { 10321 d = mResources.getDrawable(resid); 10322 } 10323 setBackgroundDrawable(d); 10324 10325 mBackgroundResource = resid; 10326 } 10327 10328 /** 10329 * Set the background to a given Drawable, or remove the background. If the 10330 * background has padding, this View's padding is set to the background's 10331 * padding. However, when a background is removed, this View's padding isn't 10332 * touched. If setting the padding is desired, please use 10333 * {@link #setPadding(int, int, int, int)}. 10334 * 10335 * @param d The Drawable to use as the background, or null to remove the 10336 * background 10337 */ 10338 public void setBackgroundDrawable(Drawable d) { 10339 boolean requestLayout = false; 10340 10341 mBackgroundResource = 0; 10342 10343 /* 10344 * Regardless of whether we're setting a new background or not, we want 10345 * to clear the previous drawable. 10346 */ 10347 if (mBGDrawable != null) { 10348 mBGDrawable.setCallback(null); 10349 unscheduleDrawable(mBGDrawable); 10350 } 10351 10352 if (d != null) { 10353 Rect padding = sThreadLocal.get(); 10354 if (padding == null) { 10355 padding = new Rect(); 10356 sThreadLocal.set(padding); 10357 } 10358 if (d.getPadding(padding)) { 10359 setPadding(padding.left, padding.top, padding.right, padding.bottom); 10360 } 10361 10362 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 10363 // if it has a different minimum size, we should layout again 10364 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 10365 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 10366 requestLayout = true; 10367 } 10368 10369 d.setCallback(this); 10370 if (d.isStateful()) { 10371 d.setState(getDrawableState()); 10372 } 10373 d.setVisible(getVisibility() == VISIBLE, false); 10374 mBGDrawable = d; 10375 10376 if ((mPrivateFlags & SKIP_DRAW) != 0) { 10377 mPrivateFlags &= ~SKIP_DRAW; 10378 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 10379 requestLayout = true; 10380 } 10381 } else { 10382 /* Remove the background */ 10383 mBGDrawable = null; 10384 10385 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 10386 /* 10387 * This view ONLY drew the background before and we're removing 10388 * the background, so now it won't draw anything 10389 * (hence we SKIP_DRAW) 10390 */ 10391 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 10392 mPrivateFlags |= SKIP_DRAW; 10393 } 10394 10395 /* 10396 * When the background is set, we try to apply its padding to this 10397 * View. When the background is removed, we don't touch this View's 10398 * padding. This is noted in the Javadocs. Hence, we don't need to 10399 * requestLayout(), the invalidate() below is sufficient. 10400 */ 10401 10402 // The old background's minimum size could have affected this 10403 // View's layout, so let's requestLayout 10404 requestLayout = true; 10405 } 10406 10407 computeOpaqueFlags(); 10408 10409 if (requestLayout) { 10410 requestLayout(); 10411 } 10412 10413 mBackgroundSizeChanged = true; 10414 invalidate(true); 10415 } 10416 10417 /** 10418 * Gets the background drawable 10419 * @return The drawable used as the background for this view, if any. 10420 */ 10421 public Drawable getBackground() { 10422 return mBGDrawable; 10423 } 10424 10425 /** 10426 * Sets the padding. The view may add on the space required to display 10427 * the scrollbars, depending on the style and visibility of the scrollbars. 10428 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 10429 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 10430 * from the values set in this call. 10431 * 10432 * @attr ref android.R.styleable#View_padding 10433 * @attr ref android.R.styleable#View_paddingBottom 10434 * @attr ref android.R.styleable#View_paddingLeft 10435 * @attr ref android.R.styleable#View_paddingRight 10436 * @attr ref android.R.styleable#View_paddingTop 10437 * @param left the left padding in pixels 10438 * @param top the top padding in pixels 10439 * @param right the right padding in pixels 10440 * @param bottom the bottom padding in pixels 10441 */ 10442 public void setPadding(int left, int top, int right, int bottom) { 10443 boolean changed = false; 10444 10445 mUserPaddingLeft = left; 10446 mUserPaddingRight = right; 10447 mUserPaddingBottom = bottom; 10448 10449 final int viewFlags = mViewFlags; 10450 10451 // Common case is there are no scroll bars. 10452 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 10453 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 10454 // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings. 10455 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 10456 ? 0 : getVerticalScrollbarWidth(); 10457 switch (mVerticalScrollbarPosition) { 10458 case SCROLLBAR_POSITION_DEFAULT: 10459 case SCROLLBAR_POSITION_RIGHT: 10460 right += offset; 10461 break; 10462 case SCROLLBAR_POSITION_LEFT: 10463 left += offset; 10464 break; 10465 } 10466 } 10467 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 10468 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 10469 ? 0 : getHorizontalScrollbarHeight(); 10470 } 10471 } 10472 10473 if (mPaddingLeft != left) { 10474 changed = true; 10475 mPaddingLeft = left; 10476 } 10477 if (mPaddingTop != top) { 10478 changed = true; 10479 mPaddingTop = top; 10480 } 10481 if (mPaddingRight != right) { 10482 changed = true; 10483 mPaddingRight = right; 10484 } 10485 if (mPaddingBottom != bottom) { 10486 changed = true; 10487 mPaddingBottom = bottom; 10488 } 10489 10490 if (changed) { 10491 requestLayout(); 10492 } 10493 } 10494 10495 /** 10496 * Returns the top padding of this view. 10497 * 10498 * @return the top padding in pixels 10499 */ 10500 public int getPaddingTop() { 10501 return mPaddingTop; 10502 } 10503 10504 /** 10505 * Returns the bottom padding of this view. If there are inset and enabled 10506 * scrollbars, this value may include the space required to display the 10507 * scrollbars as well. 10508 * 10509 * @return the bottom padding in pixels 10510 */ 10511 public int getPaddingBottom() { 10512 return mPaddingBottom; 10513 } 10514 10515 /** 10516 * Returns the left padding of this view. If there are inset and enabled 10517 * scrollbars, this value may include the space required to display the 10518 * scrollbars as well. 10519 * 10520 * @return the left padding in pixels 10521 */ 10522 public int getPaddingLeft() { 10523 return mPaddingLeft; 10524 } 10525 10526 /** 10527 * Returns the right padding of this view. If there are inset and enabled 10528 * scrollbars, this value may include the space required to display the 10529 * scrollbars as well. 10530 * 10531 * @return the right padding in pixels 10532 */ 10533 public int getPaddingRight() { 10534 return mPaddingRight; 10535 } 10536 10537 /** 10538 * Changes the selection state of this view. A view can be selected or not. 10539 * Note that selection is not the same as focus. Views are typically 10540 * selected in the context of an AdapterView like ListView or GridView; 10541 * the selected view is the view that is highlighted. 10542 * 10543 * @param selected true if the view must be selected, false otherwise 10544 */ 10545 public void setSelected(boolean selected) { 10546 if (((mPrivateFlags & SELECTED) != 0) != selected) { 10547 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 10548 if (!selected) resetPressedState(); 10549 invalidate(true); 10550 refreshDrawableState(); 10551 dispatchSetSelected(selected); 10552 } 10553 } 10554 10555 /** 10556 * Dispatch setSelected to all of this View's children. 10557 * 10558 * @see #setSelected(boolean) 10559 * 10560 * @param selected The new selected state 10561 */ 10562 protected void dispatchSetSelected(boolean selected) { 10563 } 10564 10565 /** 10566 * Indicates the selection state of this view. 10567 * 10568 * @return true if the view is selected, false otherwise 10569 */ 10570 @ViewDebug.ExportedProperty 10571 public boolean isSelected() { 10572 return (mPrivateFlags & SELECTED) != 0; 10573 } 10574 10575 /** 10576 * Changes the activated state of this view. A view can be activated or not. 10577 * Note that activation is not the same as selection. Selection is 10578 * a transient property, representing the view (hierarchy) the user is 10579 * currently interacting with. Activation is a longer-term state that the 10580 * user can move views in and out of. For example, in a list view with 10581 * single or multiple selection enabled, the views in the current selection 10582 * set are activated. (Um, yeah, we are deeply sorry about the terminology 10583 * here.) The activated state is propagated down to children of the view it 10584 * is set on. 10585 * 10586 * @param activated true if the view must be activated, false otherwise 10587 */ 10588 public void setActivated(boolean activated) { 10589 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 10590 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 10591 invalidate(true); 10592 refreshDrawableState(); 10593 dispatchSetActivated(activated); 10594 } 10595 } 10596 10597 /** 10598 * Dispatch setActivated to all of this View's children. 10599 * 10600 * @see #setActivated(boolean) 10601 * 10602 * @param activated The new activated state 10603 */ 10604 protected void dispatchSetActivated(boolean activated) { 10605 } 10606 10607 /** 10608 * Indicates the activation state of this view. 10609 * 10610 * @return true if the view is activated, false otherwise 10611 */ 10612 @ViewDebug.ExportedProperty 10613 public boolean isActivated() { 10614 return (mPrivateFlags & ACTIVATED) != 0; 10615 } 10616 10617 /** 10618 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 10619 * observer can be used to get notifications when global events, like 10620 * layout, happen. 10621 * 10622 * The returned ViewTreeObserver observer is not guaranteed to remain 10623 * valid for the lifetime of this View. If the caller of this method keeps 10624 * a long-lived reference to ViewTreeObserver, it should always check for 10625 * the return value of {@link ViewTreeObserver#isAlive()}. 10626 * 10627 * @return The ViewTreeObserver for this view's hierarchy. 10628 */ 10629 public ViewTreeObserver getViewTreeObserver() { 10630 if (mAttachInfo != null) { 10631 return mAttachInfo.mTreeObserver; 10632 } 10633 if (mFloatingTreeObserver == null) { 10634 mFloatingTreeObserver = new ViewTreeObserver(); 10635 } 10636 return mFloatingTreeObserver; 10637 } 10638 10639 /** 10640 * <p>Finds the topmost view in the current view hierarchy.</p> 10641 * 10642 * @return the topmost view containing this view 10643 */ 10644 public View getRootView() { 10645 if (mAttachInfo != null) { 10646 final View v = mAttachInfo.mRootView; 10647 if (v != null) { 10648 return v; 10649 } 10650 } 10651 10652 View parent = this; 10653 10654 while (parent.mParent != null && parent.mParent instanceof View) { 10655 parent = (View) parent.mParent; 10656 } 10657 10658 return parent; 10659 } 10660 10661 /** 10662 * <p>Computes the coordinates of this view on the screen. The argument 10663 * must be an array of two integers. After the method returns, the array 10664 * contains the x and y location in that order.</p> 10665 * 10666 * @param location an array of two integers in which to hold the coordinates 10667 */ 10668 public void getLocationOnScreen(int[] location) { 10669 getLocationInWindow(location); 10670 10671 final AttachInfo info = mAttachInfo; 10672 if (info != null) { 10673 location[0] += info.mWindowLeft; 10674 location[1] += info.mWindowTop; 10675 } 10676 } 10677 10678 /** 10679 * <p>Computes the coordinates of this view in its window. The argument 10680 * must be an array of two integers. After the method returns, the array 10681 * contains the x and y location in that order.</p> 10682 * 10683 * @param location an array of two integers in which to hold the coordinates 10684 */ 10685 public void getLocationInWindow(int[] location) { 10686 if (location == null || location.length < 2) { 10687 throw new IllegalArgumentException("location must be an array of " 10688 + "two integers"); 10689 } 10690 10691 location[0] = mLeft + (int) (mTranslationX + 0.5f); 10692 location[1] = mTop + (int) (mTranslationY + 0.5f); 10693 10694 ViewParent viewParent = mParent; 10695 while (viewParent instanceof View) { 10696 final View view = (View)viewParent; 10697 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX; 10698 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY; 10699 viewParent = view.mParent; 10700 } 10701 10702 if (viewParent instanceof ViewAncestor) { 10703 // *cough* 10704 final ViewAncestor vr = (ViewAncestor)viewParent; 10705 location[1] -= vr.mCurScrollY; 10706 } 10707 } 10708 10709 /** 10710 * {@hide} 10711 * @param id the id of the view to be found 10712 * @return the view of the specified id, null if cannot be found 10713 */ 10714 protected View findViewTraversal(int id) { 10715 if (id == mID) { 10716 return this; 10717 } 10718 return null; 10719 } 10720 10721 /** 10722 * {@hide} 10723 * @param tag the tag of the view to be found 10724 * @return the view of specified tag, null if cannot be found 10725 */ 10726 protected View findViewWithTagTraversal(Object tag) { 10727 if (tag != null && tag.equals(mTag)) { 10728 return this; 10729 } 10730 return null; 10731 } 10732 10733 /** 10734 * {@hide} 10735 * @param predicate The predicate to evaluate. 10736 * @return The first view that matches the predicate or null. 10737 */ 10738 protected View findViewByPredicateTraversal(Predicate<View> predicate) { 10739 if (predicate.apply(this)) { 10740 return this; 10741 } 10742 return null; 10743 } 10744 10745 /** 10746 * Look for a child view with the given id. If this view has the given 10747 * id, return this view. 10748 * 10749 * @param id The id to search for. 10750 * @return The view that has the given id in the hierarchy or null 10751 */ 10752 public final View findViewById(int id) { 10753 if (id < 0) { 10754 return null; 10755 } 10756 return findViewTraversal(id); 10757 } 10758 10759 /** 10760 * Look for a child view with the given tag. If this view has the given 10761 * tag, return this view. 10762 * 10763 * @param tag The tag to search for, using "tag.equals(getTag())". 10764 * @return The View that has the given tag in the hierarchy or null 10765 */ 10766 public final View findViewWithTag(Object tag) { 10767 if (tag == null) { 10768 return null; 10769 } 10770 return findViewWithTagTraversal(tag); 10771 } 10772 10773 /** 10774 * {@hide} 10775 * Look for a child view that matches the specified predicate. 10776 * If this view matches the predicate, return this view. 10777 * 10778 * @param predicate The predicate to evaluate. 10779 * @return The first view that matches the predicate or null. 10780 */ 10781 public final View findViewByPredicate(Predicate<View> predicate) { 10782 return findViewByPredicateTraversal(predicate); 10783 } 10784 10785 /** 10786 * Sets the identifier for this view. The identifier does not have to be 10787 * unique in this view's hierarchy. The identifier should be a positive 10788 * number. 10789 * 10790 * @see #NO_ID 10791 * @see #getId() 10792 * @see #findViewById(int) 10793 * 10794 * @param id a number used to identify the view 10795 * 10796 * @attr ref android.R.styleable#View_id 10797 */ 10798 public void setId(int id) { 10799 mID = id; 10800 } 10801 10802 /** 10803 * {@hide} 10804 * 10805 * @param isRoot true if the view belongs to the root namespace, false 10806 * otherwise 10807 */ 10808 public void setIsRootNamespace(boolean isRoot) { 10809 if (isRoot) { 10810 mPrivateFlags |= IS_ROOT_NAMESPACE; 10811 } else { 10812 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 10813 } 10814 } 10815 10816 /** 10817 * {@hide} 10818 * 10819 * @return true if the view belongs to the root namespace, false otherwise 10820 */ 10821 public boolean isRootNamespace() { 10822 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 10823 } 10824 10825 /** 10826 * Returns this view's identifier. 10827 * 10828 * @return a positive integer used to identify the view or {@link #NO_ID} 10829 * if the view has no ID 10830 * 10831 * @see #setId(int) 10832 * @see #findViewById(int) 10833 * @attr ref android.R.styleable#View_id 10834 */ 10835 @ViewDebug.CapturedViewProperty 10836 public int getId() { 10837 return mID; 10838 } 10839 10840 /** 10841 * Returns this view's tag. 10842 * 10843 * @return the Object stored in this view as a tag 10844 * 10845 * @see #setTag(Object) 10846 * @see #getTag(int) 10847 */ 10848 @ViewDebug.ExportedProperty 10849 public Object getTag() { 10850 return mTag; 10851 } 10852 10853 /** 10854 * Sets the tag associated with this view. A tag can be used to mark 10855 * a view in its hierarchy and does not have to be unique within the 10856 * hierarchy. Tags can also be used to store data within a view without 10857 * resorting to another data structure. 10858 * 10859 * @param tag an Object to tag the view with 10860 * 10861 * @see #getTag() 10862 * @see #setTag(int, Object) 10863 */ 10864 public void setTag(final Object tag) { 10865 mTag = tag; 10866 } 10867 10868 /** 10869 * Returns the tag associated with this view and the specified key. 10870 * 10871 * @param key The key identifying the tag 10872 * 10873 * @return the Object stored in this view as a tag 10874 * 10875 * @see #setTag(int, Object) 10876 * @see #getTag() 10877 */ 10878 public Object getTag(int key) { 10879 SparseArray<Object> tags = null; 10880 synchronized (sTagsLock) { 10881 if (sTags != null) { 10882 tags = sTags.get(this); 10883 } 10884 } 10885 10886 if (tags != null) return tags.get(key); 10887 return null; 10888 } 10889 10890 /** 10891 * Sets a tag associated with this view and a key. A tag can be used 10892 * to mark a view in its hierarchy and does not have to be unique within 10893 * the hierarchy. Tags can also be used to store data within a view 10894 * without resorting to another data structure. 10895 * 10896 * The specified key should be an id declared in the resources of the 10897 * application to ensure it is unique (see the <a 10898 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 10899 * Keys identified as belonging to 10900 * the Android framework or not associated with any package will cause 10901 * an {@link IllegalArgumentException} to be thrown. 10902 * 10903 * @param key The key identifying the tag 10904 * @param tag An Object to tag the view with 10905 * 10906 * @throws IllegalArgumentException If they specified key is not valid 10907 * 10908 * @see #setTag(Object) 10909 * @see #getTag(int) 10910 */ 10911 public void setTag(int key, final Object tag) { 10912 // If the package id is 0x00 or 0x01, it's either an undefined package 10913 // or a framework id 10914 if ((key >>> 24) < 2) { 10915 throw new IllegalArgumentException("The key must be an application-specific " 10916 + "resource id."); 10917 } 10918 10919 setTagInternal(this, key, tag); 10920 } 10921 10922 /** 10923 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 10924 * framework id. 10925 * 10926 * @hide 10927 */ 10928 public void setTagInternal(int key, Object tag) { 10929 if ((key >>> 24) != 0x1) { 10930 throw new IllegalArgumentException("The key must be a framework-specific " 10931 + "resource id."); 10932 } 10933 10934 setTagInternal(this, key, tag); 10935 } 10936 10937 private static void setTagInternal(View view, int key, Object tag) { 10938 SparseArray<Object> tags = null; 10939 synchronized (sTagsLock) { 10940 if (sTags == null) { 10941 sTags = new WeakHashMap<View, SparseArray<Object>>(); 10942 } else { 10943 tags = sTags.get(view); 10944 } 10945 } 10946 10947 if (tags == null) { 10948 tags = new SparseArray<Object>(2); 10949 synchronized (sTagsLock) { 10950 sTags.put(view, tags); 10951 } 10952 } 10953 10954 tags.put(key, tag); 10955 } 10956 10957 /** 10958 * @param consistency The type of consistency. See ViewDebug for more information. 10959 * 10960 * @hide 10961 */ 10962 protected boolean dispatchConsistencyCheck(int consistency) { 10963 return onConsistencyCheck(consistency); 10964 } 10965 10966 /** 10967 * Method that subclasses should implement to check their consistency. The type of 10968 * consistency check is indicated by the bit field passed as a parameter. 10969 * 10970 * @param consistency The type of consistency. See ViewDebug for more information. 10971 * 10972 * @throws IllegalStateException if the view is in an inconsistent state. 10973 * 10974 * @hide 10975 */ 10976 protected boolean onConsistencyCheck(int consistency) { 10977 boolean result = true; 10978 10979 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 10980 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 10981 10982 if (checkLayout) { 10983 if (getParent() == null) { 10984 result = false; 10985 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 10986 "View " + this + " does not have a parent."); 10987 } 10988 10989 if (mAttachInfo == null) { 10990 result = false; 10991 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 10992 "View " + this + " is not attached to a window."); 10993 } 10994 } 10995 10996 if (checkDrawing) { 10997 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 10998 // from their draw() method 10999 11000 if ((mPrivateFlags & DRAWN) != DRAWN && 11001 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 11002 result = false; 11003 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 11004 "View " + this + " was invalidated but its drawing cache is valid."); 11005 } 11006 } 11007 11008 return result; 11009 } 11010 11011 /** 11012 * Prints information about this view in the log output, with the tag 11013 * {@link #VIEW_LOG_TAG}. 11014 * 11015 * @hide 11016 */ 11017 public void debug() { 11018 debug(0); 11019 } 11020 11021 /** 11022 * Prints information about this view in the log output, with the tag 11023 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 11024 * indentation defined by the <code>depth</code>. 11025 * 11026 * @param depth the indentation level 11027 * 11028 * @hide 11029 */ 11030 protected void debug(int depth) { 11031 String output = debugIndent(depth - 1); 11032 11033 output += "+ " + this; 11034 int id = getId(); 11035 if (id != -1) { 11036 output += " (id=" + id + ")"; 11037 } 11038 Object tag = getTag(); 11039 if (tag != null) { 11040 output += " (tag=" + tag + ")"; 11041 } 11042 Log.d(VIEW_LOG_TAG, output); 11043 11044 if ((mPrivateFlags & FOCUSED) != 0) { 11045 output = debugIndent(depth) + " FOCUSED"; 11046 Log.d(VIEW_LOG_TAG, output); 11047 } 11048 11049 output = debugIndent(depth); 11050 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 11051 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 11052 + "} "; 11053 Log.d(VIEW_LOG_TAG, output); 11054 11055 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 11056 || mPaddingBottom != 0) { 11057 output = debugIndent(depth); 11058 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 11059 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 11060 Log.d(VIEW_LOG_TAG, output); 11061 } 11062 11063 output = debugIndent(depth); 11064 output += "mMeasureWidth=" + mMeasuredWidth + 11065 " mMeasureHeight=" + mMeasuredHeight; 11066 Log.d(VIEW_LOG_TAG, output); 11067 11068 output = debugIndent(depth); 11069 if (mLayoutParams == null) { 11070 output += "BAD! no layout params"; 11071 } else { 11072 output = mLayoutParams.debug(output); 11073 } 11074 Log.d(VIEW_LOG_TAG, output); 11075 11076 output = debugIndent(depth); 11077 output += "flags={"; 11078 output += View.printFlags(mViewFlags); 11079 output += "}"; 11080 Log.d(VIEW_LOG_TAG, output); 11081 11082 output = debugIndent(depth); 11083 output += "privateFlags={"; 11084 output += View.printPrivateFlags(mPrivateFlags); 11085 output += "}"; 11086 Log.d(VIEW_LOG_TAG, output); 11087 } 11088 11089 /** 11090 * Creates an string of whitespaces used for indentation. 11091 * 11092 * @param depth the indentation level 11093 * @return a String containing (depth * 2 + 3) * 2 white spaces 11094 * 11095 * @hide 11096 */ 11097 protected static String debugIndent(int depth) { 11098 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 11099 for (int i = 0; i < (depth * 2) + 3; i++) { 11100 spaces.append(' ').append(' '); 11101 } 11102 return spaces.toString(); 11103 } 11104 11105 /** 11106 * <p>Return the offset of the widget's text baseline from the widget's top 11107 * boundary. If this widget does not support baseline alignment, this 11108 * method returns -1. </p> 11109 * 11110 * @return the offset of the baseline within the widget's bounds or -1 11111 * if baseline alignment is not supported 11112 */ 11113 @ViewDebug.ExportedProperty(category = "layout") 11114 public int getBaseline() { 11115 return -1; 11116 } 11117 11118 /** 11119 * Call this when something has changed which has invalidated the 11120 * layout of this view. This will schedule a layout pass of the view 11121 * tree. 11122 */ 11123 public void requestLayout() { 11124 if (ViewDebug.TRACE_HIERARCHY) { 11125 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 11126 } 11127 11128 mPrivateFlags |= FORCE_LAYOUT; 11129 mPrivateFlags |= INVALIDATED; 11130 11131 if (mParent != null && !mParent.isLayoutRequested()) { 11132 mParent.requestLayout(); 11133 } 11134 } 11135 11136 /** 11137 * Forces this view to be laid out during the next layout pass. 11138 * This method does not call requestLayout() or forceLayout() 11139 * on the parent. 11140 */ 11141 public void forceLayout() { 11142 mPrivateFlags |= FORCE_LAYOUT; 11143 mPrivateFlags |= INVALIDATED; 11144 } 11145 11146 /** 11147 * <p> 11148 * This is called to find out how big a view should be. The parent 11149 * supplies constraint information in the width and height parameters. 11150 * </p> 11151 * 11152 * <p> 11153 * The actual mesurement work of a view is performed in 11154 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 11155 * {@link #onMeasure(int, int)} can and must be overriden by subclasses. 11156 * </p> 11157 * 11158 * 11159 * @param widthMeasureSpec Horizontal space requirements as imposed by the 11160 * parent 11161 * @param heightMeasureSpec Vertical space requirements as imposed by the 11162 * parent 11163 * 11164 * @see #onMeasure(int, int) 11165 */ 11166 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 11167 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 11168 widthMeasureSpec != mOldWidthMeasureSpec || 11169 heightMeasureSpec != mOldHeightMeasureSpec) { 11170 11171 // first clears the measured dimension flag 11172 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 11173 11174 if (ViewDebug.TRACE_HIERARCHY) { 11175 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 11176 } 11177 11178 // measure ourselves, this should set the measured dimension flag back 11179 onMeasure(widthMeasureSpec, heightMeasureSpec); 11180 11181 // flag not set, setMeasuredDimension() was not invoked, we raise 11182 // an exception to warn the developer 11183 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 11184 throw new IllegalStateException("onMeasure() did not set the" 11185 + " measured dimension by calling" 11186 + " setMeasuredDimension()"); 11187 } 11188 11189 mPrivateFlags |= LAYOUT_REQUIRED; 11190 } 11191 11192 mOldWidthMeasureSpec = widthMeasureSpec; 11193 mOldHeightMeasureSpec = heightMeasureSpec; 11194 } 11195 11196 /** 11197 * <p> 11198 * Measure the view and its content to determine the measured width and the 11199 * measured height. This method is invoked by {@link #measure(int, int)} and 11200 * should be overriden by subclasses to provide accurate and efficient 11201 * measurement of their contents. 11202 * </p> 11203 * 11204 * <p> 11205 * <strong>CONTRACT:</strong> When overriding this method, you 11206 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 11207 * measured width and height of this view. Failure to do so will trigger an 11208 * <code>IllegalStateException</code>, thrown by 11209 * {@link #measure(int, int)}. Calling the superclass' 11210 * {@link #onMeasure(int, int)} is a valid use. 11211 * </p> 11212 * 11213 * <p> 11214 * The base class implementation of measure defaults to the background size, 11215 * unless a larger size is allowed by the MeasureSpec. Subclasses should 11216 * override {@link #onMeasure(int, int)} to provide better measurements of 11217 * their content. 11218 * </p> 11219 * 11220 * <p> 11221 * If this method is overridden, it is the subclass's responsibility to make 11222 * sure the measured height and width are at least the view's minimum height 11223 * and width ({@link #getSuggestedMinimumHeight()} and 11224 * {@link #getSuggestedMinimumWidth()}). 11225 * </p> 11226 * 11227 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 11228 * The requirements are encoded with 11229 * {@link android.view.View.MeasureSpec}. 11230 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 11231 * The requirements are encoded with 11232 * {@link android.view.View.MeasureSpec}. 11233 * 11234 * @see #getMeasuredWidth() 11235 * @see #getMeasuredHeight() 11236 * @see #setMeasuredDimension(int, int) 11237 * @see #getSuggestedMinimumHeight() 11238 * @see #getSuggestedMinimumWidth() 11239 * @see android.view.View.MeasureSpec#getMode(int) 11240 * @see android.view.View.MeasureSpec#getSize(int) 11241 */ 11242 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 11243 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 11244 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 11245 } 11246 11247 /** 11248 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 11249 * measured width and measured height. Failing to do so will trigger an 11250 * exception at measurement time.</p> 11251 * 11252 * @param measuredWidth The measured width of this view. May be a complex 11253 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 11254 * {@link #MEASURED_STATE_TOO_SMALL}. 11255 * @param measuredHeight The measured height of this view. May be a complex 11256 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 11257 * {@link #MEASURED_STATE_TOO_SMALL}. 11258 */ 11259 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 11260 mMeasuredWidth = measuredWidth; 11261 mMeasuredHeight = measuredHeight; 11262 11263 mPrivateFlags |= MEASURED_DIMENSION_SET; 11264 } 11265 11266 /** 11267 * Merge two states as returned by {@link #getMeasuredState()}. 11268 * @param curState The current state as returned from a view or the result 11269 * of combining multiple views. 11270 * @param newState The new view state to combine. 11271 * @return Returns a new integer reflecting the combination of the two 11272 * states. 11273 */ 11274 public static int combineMeasuredStates(int curState, int newState) { 11275 return curState | newState; 11276 } 11277 11278 /** 11279 * Version of {@link #resolveSizeAndState(int, int, int)} 11280 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 11281 */ 11282 public static int resolveSize(int size, int measureSpec) { 11283 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 11284 } 11285 11286 /** 11287 * Utility to reconcile a desired size and state, with constraints imposed 11288 * by a MeasureSpec. Will take the desired size, unless a different size 11289 * is imposed by the constraints. The returned value is a compound integer, 11290 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 11291 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 11292 * size is smaller than the size the view wants to be. 11293 * 11294 * @param size How big the view wants to be 11295 * @param measureSpec Constraints imposed by the parent 11296 * @return Size information bit mask as defined by 11297 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11298 */ 11299 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 11300 int result = size; 11301 int specMode = MeasureSpec.getMode(measureSpec); 11302 int specSize = MeasureSpec.getSize(measureSpec); 11303 switch (specMode) { 11304 case MeasureSpec.UNSPECIFIED: 11305 result = size; 11306 break; 11307 case MeasureSpec.AT_MOST: 11308 if (specSize < size) { 11309 result = specSize | MEASURED_STATE_TOO_SMALL; 11310 } else { 11311 result = size; 11312 } 11313 break; 11314 case MeasureSpec.EXACTLY: 11315 result = specSize; 11316 break; 11317 } 11318 return result | (childMeasuredState&MEASURED_STATE_MASK); 11319 } 11320 11321 /** 11322 * Utility to return a default size. Uses the supplied size if the 11323 * MeasureSpec imposed no contraints. Will get larger if allowed 11324 * by the MeasureSpec. 11325 * 11326 * @param size Default size for this view 11327 * @param measureSpec Constraints imposed by the parent 11328 * @return The size this view should be. 11329 */ 11330 public static int getDefaultSize(int size, int measureSpec) { 11331 int result = size; 11332 int specMode = MeasureSpec.getMode(measureSpec); 11333 int specSize = MeasureSpec.getSize(measureSpec); 11334 11335 switch (specMode) { 11336 case MeasureSpec.UNSPECIFIED: 11337 result = size; 11338 break; 11339 case MeasureSpec.AT_MOST: 11340 case MeasureSpec.EXACTLY: 11341 result = specSize; 11342 break; 11343 } 11344 return result; 11345 } 11346 11347 /** 11348 * Returns the suggested minimum height that the view should use. This 11349 * returns the maximum of the view's minimum height 11350 * and the background's minimum height 11351 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 11352 * <p> 11353 * When being used in {@link #onMeasure(int, int)}, the caller should still 11354 * ensure the returned height is within the requirements of the parent. 11355 * 11356 * @return The suggested minimum height of the view. 11357 */ 11358 protected int getSuggestedMinimumHeight() { 11359 int suggestedMinHeight = mMinHeight; 11360 11361 if (mBGDrawable != null) { 11362 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 11363 if (suggestedMinHeight < bgMinHeight) { 11364 suggestedMinHeight = bgMinHeight; 11365 } 11366 } 11367 11368 return suggestedMinHeight; 11369 } 11370 11371 /** 11372 * Returns the suggested minimum width that the view should use. This 11373 * returns the maximum of the view's minimum width) 11374 * and the background's minimum width 11375 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 11376 * <p> 11377 * When being used in {@link #onMeasure(int, int)}, the caller should still 11378 * ensure the returned width is within the requirements of the parent. 11379 * 11380 * @return The suggested minimum width of the view. 11381 */ 11382 protected int getSuggestedMinimumWidth() { 11383 int suggestedMinWidth = mMinWidth; 11384 11385 if (mBGDrawable != null) { 11386 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 11387 if (suggestedMinWidth < bgMinWidth) { 11388 suggestedMinWidth = bgMinWidth; 11389 } 11390 } 11391 11392 return suggestedMinWidth; 11393 } 11394 11395 /** 11396 * Sets the minimum height of the view. It is not guaranteed the view will 11397 * be able to achieve this minimum height (for example, if its parent layout 11398 * constrains it with less available height). 11399 * 11400 * @param minHeight The minimum height the view will try to be. 11401 */ 11402 public void setMinimumHeight(int minHeight) { 11403 mMinHeight = minHeight; 11404 } 11405 11406 /** 11407 * Sets the minimum width of the view. It is not guaranteed the view will 11408 * be able to achieve this minimum width (for example, if its parent layout 11409 * constrains it with less available width). 11410 * 11411 * @param minWidth The minimum width the view will try to be. 11412 */ 11413 public void setMinimumWidth(int minWidth) { 11414 mMinWidth = minWidth; 11415 } 11416 11417 /** 11418 * Get the animation currently associated with this view. 11419 * 11420 * @return The animation that is currently playing or 11421 * scheduled to play for this view. 11422 */ 11423 public Animation getAnimation() { 11424 return mCurrentAnimation; 11425 } 11426 11427 /** 11428 * Start the specified animation now. 11429 * 11430 * @param animation the animation to start now 11431 */ 11432 public void startAnimation(Animation animation) { 11433 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 11434 setAnimation(animation); 11435 invalidateParentCaches(); 11436 invalidate(true); 11437 } 11438 11439 /** 11440 * Cancels any animations for this view. 11441 */ 11442 public void clearAnimation() { 11443 if (mCurrentAnimation != null) { 11444 mCurrentAnimation.detach(); 11445 } 11446 mCurrentAnimation = null; 11447 invalidateParentIfNeeded(); 11448 } 11449 11450 /** 11451 * Sets the next animation to play for this view. 11452 * If you want the animation to play immediately, use 11453 * startAnimation. This method provides allows fine-grained 11454 * control over the start time and invalidation, but you 11455 * must make sure that 1) the animation has a start time set, and 11456 * 2) the view will be invalidated when the animation is supposed to 11457 * start. 11458 * 11459 * @param animation The next animation, or null. 11460 */ 11461 public void setAnimation(Animation animation) { 11462 mCurrentAnimation = animation; 11463 if (animation != null) { 11464 animation.reset(); 11465 } 11466 } 11467 11468 /** 11469 * Invoked by a parent ViewGroup to notify the start of the animation 11470 * currently associated with this view. If you override this method, 11471 * always call super.onAnimationStart(); 11472 * 11473 * @see #setAnimation(android.view.animation.Animation) 11474 * @see #getAnimation() 11475 */ 11476 protected void onAnimationStart() { 11477 mPrivateFlags |= ANIMATION_STARTED; 11478 } 11479 11480 /** 11481 * Invoked by a parent ViewGroup to notify the end of the animation 11482 * currently associated with this view. If you override this method, 11483 * always call super.onAnimationEnd(); 11484 * 11485 * @see #setAnimation(android.view.animation.Animation) 11486 * @see #getAnimation() 11487 */ 11488 protected void onAnimationEnd() { 11489 mPrivateFlags &= ~ANIMATION_STARTED; 11490 } 11491 11492 /** 11493 * Invoked if there is a Transform that involves alpha. Subclass that can 11494 * draw themselves with the specified alpha should return true, and then 11495 * respect that alpha when their onDraw() is called. If this returns false 11496 * then the view may be redirected to draw into an offscreen buffer to 11497 * fulfill the request, which will look fine, but may be slower than if the 11498 * subclass handles it internally. The default implementation returns false. 11499 * 11500 * @param alpha The alpha (0..255) to apply to the view's drawing 11501 * @return true if the view can draw with the specified alpha. 11502 */ 11503 protected boolean onSetAlpha(int alpha) { 11504 return false; 11505 } 11506 11507 /** 11508 * This is used by the RootView to perform an optimization when 11509 * the view hierarchy contains one or several SurfaceView. 11510 * SurfaceView is always considered transparent, but its children are not, 11511 * therefore all View objects remove themselves from the global transparent 11512 * region (passed as a parameter to this function). 11513 * 11514 * @param region The transparent region for this ViewAncestor (window). 11515 * 11516 * @return Returns true if the effective visibility of the view at this 11517 * point is opaque, regardless of the transparent region; returns false 11518 * if it is possible for underlying windows to be seen behind the view. 11519 * 11520 * {@hide} 11521 */ 11522 public boolean gatherTransparentRegion(Region region) { 11523 final AttachInfo attachInfo = mAttachInfo; 11524 if (region != null && attachInfo != null) { 11525 final int pflags = mPrivateFlags; 11526 if ((pflags & SKIP_DRAW) == 0) { 11527 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 11528 // remove it from the transparent region. 11529 final int[] location = attachInfo.mTransparentLocation; 11530 getLocationInWindow(location); 11531 region.op(location[0], location[1], location[0] + mRight - mLeft, 11532 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 11533 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 11534 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 11535 // exists, so we remove the background drawable's non-transparent 11536 // parts from this transparent region. 11537 applyDrawableToTransparentRegion(mBGDrawable, region); 11538 } 11539 } 11540 return true; 11541 } 11542 11543 /** 11544 * Play a sound effect for this view. 11545 * 11546 * <p>The framework will play sound effects for some built in actions, such as 11547 * clicking, but you may wish to play these effects in your widget, 11548 * for instance, for internal navigation. 11549 * 11550 * <p>The sound effect will only be played if sound effects are enabled by the user, and 11551 * {@link #isSoundEffectsEnabled()} is true. 11552 * 11553 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 11554 */ 11555 public void playSoundEffect(int soundConstant) { 11556 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 11557 return; 11558 } 11559 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 11560 } 11561 11562 /** 11563 * BZZZTT!!1! 11564 * 11565 * <p>Provide haptic feedback to the user for this view. 11566 * 11567 * <p>The framework will provide haptic feedback for some built in actions, 11568 * such as long presses, but you may wish to provide feedback for your 11569 * own widget. 11570 * 11571 * <p>The feedback will only be performed if 11572 * {@link #isHapticFeedbackEnabled()} is true. 11573 * 11574 * @param feedbackConstant One of the constants defined in 11575 * {@link HapticFeedbackConstants} 11576 */ 11577 public boolean performHapticFeedback(int feedbackConstant) { 11578 return performHapticFeedback(feedbackConstant, 0); 11579 } 11580 11581 /** 11582 * BZZZTT!!1! 11583 * 11584 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 11585 * 11586 * @param feedbackConstant One of the constants defined in 11587 * {@link HapticFeedbackConstants} 11588 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 11589 */ 11590 public boolean performHapticFeedback(int feedbackConstant, int flags) { 11591 if (mAttachInfo == null) { 11592 return false; 11593 } 11594 //noinspection SimplifiableIfStatement 11595 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 11596 && !isHapticFeedbackEnabled()) { 11597 return false; 11598 } 11599 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 11600 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 11601 } 11602 11603 /** 11604 * Request that the visibility of the status bar be changed. 11605 */ 11606 public void setSystemUiVisibility(int visibility) { 11607 if (visibility != mSystemUiVisibility) { 11608 mSystemUiVisibility = visibility; 11609 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 11610 mParent.recomputeViewAttributes(this); 11611 } 11612 } 11613 } 11614 11615 /** 11616 * Returns the status bar visibility that this view has requested. 11617 */ 11618 public int getSystemUiVisibility() { 11619 return mSystemUiVisibility; 11620 } 11621 11622 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 11623 mOnSystemUiVisibilityChangeListener = l; 11624 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 11625 mParent.recomputeViewAttributes(this); 11626 } 11627 } 11628 11629 /** 11630 */ 11631 public void dispatchSystemUiVisibilityChanged(int visibility) { 11632 if (mOnSystemUiVisibilityChangeListener != null) { 11633 mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 11634 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 11635 } 11636 } 11637 11638 /** 11639 * Creates an image that the system displays during the drag and drop 11640 * operation. This is called a "drag shadow". The default implementation 11641 * for a DragShadowBuilder based on a View returns an image that has exactly the same 11642 * appearance as the given View. The default also positions the center of the drag shadow 11643 * directly under the touch point. If no View is provided (the constructor with no parameters 11644 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 11645 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 11646 * default is an invisible drag shadow. 11647 * <p> 11648 * You are not required to use the View you provide to the constructor as the basis of the 11649 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 11650 * anything you want as the drag shadow. 11651 * </p> 11652 * <p> 11653 * You pass a DragShadowBuilder object to the system when you start the drag. The system 11654 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 11655 * size and position of the drag shadow. It uses this data to construct a 11656 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 11657 * so that your application can draw the shadow image in the Canvas. 11658 * </p> 11659 */ 11660 public static class DragShadowBuilder { 11661 private final WeakReference<View> mView; 11662 11663 /** 11664 * Constructs a shadow image builder based on a View. By default, the resulting drag 11665 * shadow will have the same appearance and dimensions as the View, with the touch point 11666 * over the center of the View. 11667 * @param view A View. Any View in scope can be used. 11668 */ 11669 public DragShadowBuilder(View view) { 11670 mView = new WeakReference<View>(view); 11671 } 11672 11673 /** 11674 * Construct a shadow builder object with no associated View. This 11675 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 11676 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 11677 * to supply the drag shadow's dimensions and appearance without 11678 * reference to any View object. If they are not overridden, then the result is an 11679 * invisible drag shadow. 11680 */ 11681 public DragShadowBuilder() { 11682 mView = new WeakReference<View>(null); 11683 } 11684 11685 /** 11686 * Returns the View object that had been passed to the 11687 * {@link #View.DragShadowBuilder(View)} 11688 * constructor. If that View parameter was {@code null} or if the 11689 * {@link #View.DragShadowBuilder()} 11690 * constructor was used to instantiate the builder object, this method will return 11691 * null. 11692 * 11693 * @return The View object associate with this builder object. 11694 */ 11695 @SuppressWarnings({"JavadocReference"}) 11696 final public View getView() { 11697 return mView.get(); 11698 } 11699 11700 /** 11701 * Provides the metrics for the shadow image. These include the dimensions of 11702 * the shadow image, and the point within that shadow that should 11703 * be centered under the touch location while dragging. 11704 * <p> 11705 * The default implementation sets the dimensions of the shadow to be the 11706 * same as the dimensions of the View itself and centers the shadow under 11707 * the touch point. 11708 * </p> 11709 * 11710 * @param shadowSize A {@link android.graphics.Point} containing the width and height 11711 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 11712 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 11713 * image. 11714 * 11715 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 11716 * shadow image that should be underneath the touch point during the drag and drop 11717 * operation. Your application must set {@link android.graphics.Point#x} to the 11718 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 11719 */ 11720 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 11721 final View view = mView.get(); 11722 if (view != null) { 11723 shadowSize.set(view.getWidth(), view.getHeight()); 11724 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 11725 } else { 11726 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 11727 } 11728 } 11729 11730 /** 11731 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 11732 * based on the dimensions it received from the 11733 * {@link #onProvideShadowMetrics(Point, Point)} callback. 11734 * 11735 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 11736 */ 11737 public void onDrawShadow(Canvas canvas) { 11738 final View view = mView.get(); 11739 if (view != null) { 11740 view.draw(canvas); 11741 } else { 11742 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 11743 } 11744 } 11745 } 11746 11747 /** 11748 * Starts a drag and drop operation. When your application calls this method, it passes a 11749 * {@link android.view.View.DragShadowBuilder} object to the system. The 11750 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 11751 * to get metrics for the drag shadow, and then calls the object's 11752 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 11753 * <p> 11754 * Once the system has the drag shadow, it begins the drag and drop operation by sending 11755 * drag events to all the View objects in your application that are currently visible. It does 11756 * this either by calling the View object's drag listener (an implementation of 11757 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 11758 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 11759 * Both are passed a {@link android.view.DragEvent} object that has a 11760 * {@link android.view.DragEvent#getAction()} value of 11761 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 11762 * </p> 11763 * <p> 11764 * Your application can invoke startDrag() on any attached View object. The View object does not 11765 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 11766 * be related to the View the user selected for dragging. 11767 * </p> 11768 * @param data A {@link android.content.ClipData} object pointing to the data to be 11769 * transferred by the drag and drop operation. 11770 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 11771 * drag shadow. 11772 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 11773 * drop operation. This Object is put into every DragEvent object sent by the system during the 11774 * current drag. 11775 * <p> 11776 * myLocalState is a lightweight mechanism for the sending information from the dragged View 11777 * to the target Views. For example, it can contain flags that differentiate between a 11778 * a copy operation and a move operation. 11779 * </p> 11780 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 11781 * so the parameter should be set to 0. 11782 * @return {@code true} if the method completes successfully, or 11783 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 11784 * do a drag, and so no drag operation is in progress. 11785 */ 11786 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 11787 Object myLocalState, int flags) { 11788 if (ViewDebug.DEBUG_DRAG) { 11789 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 11790 } 11791 boolean okay = false; 11792 11793 Point shadowSize = new Point(); 11794 Point shadowTouchPoint = new Point(); 11795 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 11796 11797 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 11798 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 11799 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 11800 } 11801 11802 if (ViewDebug.DEBUG_DRAG) { 11803 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 11804 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 11805 } 11806 Surface surface = new Surface(); 11807 try { 11808 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 11809 flags, shadowSize.x, shadowSize.y, surface); 11810 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 11811 + " surface=" + surface); 11812 if (token != null) { 11813 Canvas canvas = surface.lockCanvas(null); 11814 try { 11815 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 11816 shadowBuilder.onDrawShadow(canvas); 11817 } finally { 11818 surface.unlockCanvasAndPost(canvas); 11819 } 11820 11821 final ViewAncestor root = getViewAncestor(); 11822 11823 // Cache the local state object for delivery with DragEvents 11824 root.setLocalDragState(myLocalState); 11825 11826 // repurpose 'shadowSize' for the last touch point 11827 root.getLastTouchPoint(shadowSize); 11828 11829 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 11830 shadowSize.x, shadowSize.y, 11831 shadowTouchPoint.x, shadowTouchPoint.y, data); 11832 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 11833 } 11834 } catch (Exception e) { 11835 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 11836 surface.destroy(); 11837 } 11838 11839 return okay; 11840 } 11841 11842 /** 11843 * Handles drag events sent by the system following a call to 11844 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 11845 *<p> 11846 * When the system calls this method, it passes a 11847 * {@link android.view.DragEvent} object. A call to 11848 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 11849 * in DragEvent. The method uses these to determine what is happening in the drag and drop 11850 * operation. 11851 * @param event The {@link android.view.DragEvent} sent by the system. 11852 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 11853 * in DragEvent, indicating the type of drag event represented by this object. 11854 * @return {@code true} if the method was successful, otherwise {@code false}. 11855 * <p> 11856 * The method should return {@code true} in response to an action type of 11857 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 11858 * operation. 11859 * </p> 11860 * <p> 11861 * The method should also return {@code true} in response to an action type of 11862 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 11863 * {@code false} if it didn't. 11864 * </p> 11865 */ 11866 public boolean onDragEvent(DragEvent event) { 11867 return false; 11868 } 11869 11870 /** 11871 * Detects if this View is enabled and has a drag event listener. 11872 * If both are true, then it calls the drag event listener with the 11873 * {@link android.view.DragEvent} it received. If the drag event listener returns 11874 * {@code true}, then dispatchDragEvent() returns {@code true}. 11875 * <p> 11876 * For all other cases, the method calls the 11877 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 11878 * method and returns its result. 11879 * </p> 11880 * <p> 11881 * This ensures that a drag event is always consumed, even if the View does not have a drag 11882 * event listener. However, if the View has a listener and the listener returns true, then 11883 * onDragEvent() is not called. 11884 * </p> 11885 */ 11886 public boolean dispatchDragEvent(DragEvent event) { 11887 //noinspection SimplifiableIfStatement 11888 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 11889 && mOnDragListener.onDrag(this, event)) { 11890 return true; 11891 } 11892 return onDragEvent(event); 11893 } 11894 11895 boolean canAcceptDrag() { 11896 return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0; 11897 } 11898 11899 /** 11900 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 11901 * it is ever exposed at all. 11902 * @hide 11903 */ 11904 public void onCloseSystemDialogs(String reason) { 11905 } 11906 11907 /** 11908 * Given a Drawable whose bounds have been set to draw into this view, 11909 * update a Region being computed for 11910 * {@link #gatherTransparentRegion(android.graphics.Region)} so 11911 * that any non-transparent parts of the Drawable are removed from the 11912 * given transparent region. 11913 * 11914 * @param dr The Drawable whose transparency is to be applied to the region. 11915 * @param region A Region holding the current transparency information, 11916 * where any parts of the region that are set are considered to be 11917 * transparent. On return, this region will be modified to have the 11918 * transparency information reduced by the corresponding parts of the 11919 * Drawable that are not transparent. 11920 * {@hide} 11921 */ 11922 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 11923 if (DBG) { 11924 Log.i("View", "Getting transparent region for: " + this); 11925 } 11926 final Region r = dr.getTransparentRegion(); 11927 final Rect db = dr.getBounds(); 11928 final AttachInfo attachInfo = mAttachInfo; 11929 if (r != null && attachInfo != null) { 11930 final int w = getRight()-getLeft(); 11931 final int h = getBottom()-getTop(); 11932 if (db.left > 0) { 11933 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 11934 r.op(0, 0, db.left, h, Region.Op.UNION); 11935 } 11936 if (db.right < w) { 11937 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 11938 r.op(db.right, 0, w, h, Region.Op.UNION); 11939 } 11940 if (db.top > 0) { 11941 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 11942 r.op(0, 0, w, db.top, Region.Op.UNION); 11943 } 11944 if (db.bottom < h) { 11945 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 11946 r.op(0, db.bottom, w, h, Region.Op.UNION); 11947 } 11948 final int[] location = attachInfo.mTransparentLocation; 11949 getLocationInWindow(location); 11950 r.translate(location[0], location[1]); 11951 region.op(r, Region.Op.INTERSECT); 11952 } else { 11953 region.op(db, Region.Op.DIFFERENCE); 11954 } 11955 } 11956 11957 private void checkForLongClick(int delayOffset) { 11958 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 11959 mHasPerformedLongPress = false; 11960 11961 if (mPendingCheckForLongPress == null) { 11962 mPendingCheckForLongPress = new CheckForLongPress(); 11963 } 11964 mPendingCheckForLongPress.rememberWindowAttachCount(); 11965 postDelayed(mPendingCheckForLongPress, 11966 ViewConfiguration.getLongPressTimeout() - delayOffset); 11967 } 11968 } 11969 11970 /** 11971 * Inflate a view from an XML resource. This convenience method wraps the {@link 11972 * LayoutInflater} class, which provides a full range of options for view inflation. 11973 * 11974 * @param context The Context object for your activity or application. 11975 * @param resource The resource ID to inflate 11976 * @param root A view group that will be the parent. Used to properly inflate the 11977 * layout_* parameters. 11978 * @see LayoutInflater 11979 */ 11980 public static View inflate(Context context, int resource, ViewGroup root) { 11981 LayoutInflater factory = LayoutInflater.from(context); 11982 return factory.inflate(resource, root); 11983 } 11984 11985 /** 11986 * Scroll the view with standard behavior for scrolling beyond the normal 11987 * content boundaries. Views that call this method should override 11988 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 11989 * results of an over-scroll operation. 11990 * 11991 * Views can use this method to handle any touch or fling-based scrolling. 11992 * 11993 * @param deltaX Change in X in pixels 11994 * @param deltaY Change in Y in pixels 11995 * @param scrollX Current X scroll value in pixels before applying deltaX 11996 * @param scrollY Current Y scroll value in pixels before applying deltaY 11997 * @param scrollRangeX Maximum content scroll range along the X axis 11998 * @param scrollRangeY Maximum content scroll range along the Y axis 11999 * @param maxOverScrollX Number of pixels to overscroll by in either direction 12000 * along the X axis. 12001 * @param maxOverScrollY Number of pixels to overscroll by in either direction 12002 * along the Y axis. 12003 * @param isTouchEvent true if this scroll operation is the result of a touch event. 12004 * @return true if scrolling was clamped to an over-scroll boundary along either 12005 * axis, false otherwise. 12006 */ 12007 @SuppressWarnings({"UnusedParameters"}) 12008 protected boolean overScrollBy(int deltaX, int deltaY, 12009 int scrollX, int scrollY, 12010 int scrollRangeX, int scrollRangeY, 12011 int maxOverScrollX, int maxOverScrollY, 12012 boolean isTouchEvent) { 12013 final int overScrollMode = mOverScrollMode; 12014 final boolean canScrollHorizontal = 12015 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 12016 final boolean canScrollVertical = 12017 computeVerticalScrollRange() > computeVerticalScrollExtent(); 12018 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 12019 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 12020 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 12021 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 12022 12023 int newScrollX = scrollX + deltaX; 12024 if (!overScrollHorizontal) { 12025 maxOverScrollX = 0; 12026 } 12027 12028 int newScrollY = scrollY + deltaY; 12029 if (!overScrollVertical) { 12030 maxOverScrollY = 0; 12031 } 12032 12033 // Clamp values if at the limits and record 12034 final int left = -maxOverScrollX; 12035 final int right = maxOverScrollX + scrollRangeX; 12036 final int top = -maxOverScrollY; 12037 final int bottom = maxOverScrollY + scrollRangeY; 12038 12039 boolean clampedX = false; 12040 if (newScrollX > right) { 12041 newScrollX = right; 12042 clampedX = true; 12043 } else if (newScrollX < left) { 12044 newScrollX = left; 12045 clampedX = true; 12046 } 12047 12048 boolean clampedY = false; 12049 if (newScrollY > bottom) { 12050 newScrollY = bottom; 12051 clampedY = true; 12052 } else if (newScrollY < top) { 12053 newScrollY = top; 12054 clampedY = true; 12055 } 12056 12057 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 12058 12059 return clampedX || clampedY; 12060 } 12061 12062 /** 12063 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 12064 * respond to the results of an over-scroll operation. 12065 * 12066 * @param scrollX New X scroll value in pixels 12067 * @param scrollY New Y scroll value in pixels 12068 * @param clampedX True if scrollX was clamped to an over-scroll boundary 12069 * @param clampedY True if scrollY was clamped to an over-scroll boundary 12070 */ 12071 protected void onOverScrolled(int scrollX, int scrollY, 12072 boolean clampedX, boolean clampedY) { 12073 // Intentionally empty. 12074 } 12075 12076 /** 12077 * Returns the over-scroll mode for this view. The result will be 12078 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 12079 * (allow over-scrolling only if the view content is larger than the container), 12080 * or {@link #OVER_SCROLL_NEVER}. 12081 * 12082 * @return This view's over-scroll mode. 12083 */ 12084 public int getOverScrollMode() { 12085 return mOverScrollMode; 12086 } 12087 12088 /** 12089 * Set the over-scroll mode for this view. Valid over-scroll modes are 12090 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 12091 * (allow over-scrolling only if the view content is larger than the container), 12092 * or {@link #OVER_SCROLL_NEVER}. 12093 * 12094 * Setting the over-scroll mode of a view will have an effect only if the 12095 * view is capable of scrolling. 12096 * 12097 * @param overScrollMode The new over-scroll mode for this view. 12098 */ 12099 public void setOverScrollMode(int overScrollMode) { 12100 if (overScrollMode != OVER_SCROLL_ALWAYS && 12101 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 12102 overScrollMode != OVER_SCROLL_NEVER) { 12103 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 12104 } 12105 mOverScrollMode = overScrollMode; 12106 } 12107 12108 /** 12109 * Gets a scale factor that determines the distance the view should scroll 12110 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 12111 * @return The vertical scroll scale factor. 12112 * @hide 12113 */ 12114 protected float getVerticalScrollFactor() { 12115 if (mVerticalScrollFactor == 0) { 12116 TypedValue outValue = new TypedValue(); 12117 if (!mContext.getTheme().resolveAttribute( 12118 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 12119 throw new IllegalStateException( 12120 "Expected theme to define listPreferredItemHeight."); 12121 } 12122 mVerticalScrollFactor = outValue.getDimension( 12123 mContext.getResources().getDisplayMetrics()); 12124 } 12125 return mVerticalScrollFactor; 12126 } 12127 12128 /** 12129 * Gets a scale factor that determines the distance the view should scroll 12130 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 12131 * @return The horizontal scroll scale factor. 12132 * @hide 12133 */ 12134 protected float getHorizontalScrollFactor() { 12135 // TODO: Should use something else. 12136 return getVerticalScrollFactor(); 12137 } 12138 12139 /** 12140 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 12141 * Each MeasureSpec represents a requirement for either the width or the height. 12142 * A MeasureSpec is comprised of a size and a mode. There are three possible 12143 * modes: 12144 * <dl> 12145 * <dt>UNSPECIFIED</dt> 12146 * <dd> 12147 * The parent has not imposed any constraint on the child. It can be whatever size 12148 * it wants. 12149 * </dd> 12150 * 12151 * <dt>EXACTLY</dt> 12152 * <dd> 12153 * The parent has determined an exact size for the child. The child is going to be 12154 * given those bounds regardless of how big it wants to be. 12155 * </dd> 12156 * 12157 * <dt>AT_MOST</dt> 12158 * <dd> 12159 * The child can be as large as it wants up to the specified size. 12160 * </dd> 12161 * </dl> 12162 * 12163 * MeasureSpecs are implemented as ints to reduce object allocation. This class 12164 * is provided to pack and unpack the <size, mode> tuple into the int. 12165 */ 12166 public static class MeasureSpec { 12167 private static final int MODE_SHIFT = 30; 12168 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 12169 12170 /** 12171 * Measure specification mode: The parent has not imposed any constraint 12172 * on the child. It can be whatever size it wants. 12173 */ 12174 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 12175 12176 /** 12177 * Measure specification mode: The parent has determined an exact size 12178 * for the child. The child is going to be given those bounds regardless 12179 * of how big it wants to be. 12180 */ 12181 public static final int EXACTLY = 1 << MODE_SHIFT; 12182 12183 /** 12184 * Measure specification mode: The child can be as large as it wants up 12185 * to the specified size. 12186 */ 12187 public static final int AT_MOST = 2 << MODE_SHIFT; 12188 12189 /** 12190 * Creates a measure specification based on the supplied size and mode. 12191 * 12192 * The mode must always be one of the following: 12193 * <ul> 12194 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 12195 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 12196 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 12197 * </ul> 12198 * 12199 * @param size the size of the measure specification 12200 * @param mode the mode of the measure specification 12201 * @return the measure specification based on size and mode 12202 */ 12203 public static int makeMeasureSpec(int size, int mode) { 12204 return size + mode; 12205 } 12206 12207 /** 12208 * Extracts the mode from the supplied measure specification. 12209 * 12210 * @param measureSpec the measure specification to extract the mode from 12211 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 12212 * {@link android.view.View.MeasureSpec#AT_MOST} or 12213 * {@link android.view.View.MeasureSpec#EXACTLY} 12214 */ 12215 public static int getMode(int measureSpec) { 12216 return (measureSpec & MODE_MASK); 12217 } 12218 12219 /** 12220 * Extracts the size from the supplied measure specification. 12221 * 12222 * @param measureSpec the measure specification to extract the size from 12223 * @return the size in pixels defined in the supplied measure specification 12224 */ 12225 public static int getSize(int measureSpec) { 12226 return (measureSpec & ~MODE_MASK); 12227 } 12228 12229 /** 12230 * Returns a String representation of the specified measure 12231 * specification. 12232 * 12233 * @param measureSpec the measure specification to convert to a String 12234 * @return a String with the following format: "MeasureSpec: MODE SIZE" 12235 */ 12236 public static String toString(int measureSpec) { 12237 int mode = getMode(measureSpec); 12238 int size = getSize(measureSpec); 12239 12240 StringBuilder sb = new StringBuilder("MeasureSpec: "); 12241 12242 if (mode == UNSPECIFIED) 12243 sb.append("UNSPECIFIED "); 12244 else if (mode == EXACTLY) 12245 sb.append("EXACTLY "); 12246 else if (mode == AT_MOST) 12247 sb.append("AT_MOST "); 12248 else 12249 sb.append(mode).append(" "); 12250 12251 sb.append(size); 12252 return sb.toString(); 12253 } 12254 } 12255 12256 class CheckForLongPress implements Runnable { 12257 12258 private int mOriginalWindowAttachCount; 12259 12260 public void run() { 12261 if (isPressed() && (mParent != null) 12262 && mOriginalWindowAttachCount == mWindowAttachCount) { 12263 if (performLongClick()) { 12264 mHasPerformedLongPress = true; 12265 } 12266 } 12267 } 12268 12269 public void rememberWindowAttachCount() { 12270 mOriginalWindowAttachCount = mWindowAttachCount; 12271 } 12272 } 12273 12274 private final class CheckForTap implements Runnable { 12275 public void run() { 12276 mPrivateFlags &= ~PREPRESSED; 12277 mPrivateFlags |= PRESSED; 12278 refreshDrawableState(); 12279 checkForLongClick(ViewConfiguration.getTapTimeout()); 12280 } 12281 } 12282 12283 private final class PerformClick implements Runnable { 12284 public void run() { 12285 performClick(); 12286 } 12287 } 12288 12289 /** @hide */ 12290 public void hackTurnOffWindowResizeAnim(boolean off) { 12291 mAttachInfo.mTurnOffWindowResizeAnim = off; 12292 } 12293 12294 /** 12295 * This method returns a ViewPropertyAnimator object, which can be used to animate 12296 * specific properties on this View. 12297 * 12298 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 12299 */ 12300 public ViewPropertyAnimator animate() { 12301 if (mAnimator == null) { 12302 mAnimator = new ViewPropertyAnimator(this); 12303 } 12304 return mAnimator; 12305 } 12306 12307 /** 12308 * Interface definition for a callback to be invoked when a key event is 12309 * dispatched to this view. The callback will be invoked before the key 12310 * event is given to the view. 12311 */ 12312 public interface OnKeyListener { 12313 /** 12314 * Called when a key is dispatched to a view. This allows listeners to 12315 * get a chance to respond before the target view. 12316 * 12317 * @param v The view the key has been dispatched to. 12318 * @param keyCode The code for the physical key that was pressed 12319 * @param event The KeyEvent object containing full information about 12320 * the event. 12321 * @return True if the listener has consumed the event, false otherwise. 12322 */ 12323 boolean onKey(View v, int keyCode, KeyEvent event); 12324 } 12325 12326 /** 12327 * Interface definition for a callback to be invoked when a touch event is 12328 * dispatched to this view. The callback will be invoked before the touch 12329 * event is given to the view. 12330 */ 12331 public interface OnTouchListener { 12332 /** 12333 * Called when a touch event is dispatched to a view. This allows listeners to 12334 * get a chance to respond before the target view. 12335 * 12336 * @param v The view the touch event has been dispatched to. 12337 * @param event The MotionEvent object containing full information about 12338 * the event. 12339 * @return True if the listener has consumed the event, false otherwise. 12340 */ 12341 boolean onTouch(View v, MotionEvent event); 12342 } 12343 12344 /** 12345 * Interface definition for a callback to be invoked when a generic motion event is 12346 * dispatched to this view. The callback will be invoked before the generic motion 12347 * event is given to the view. 12348 */ 12349 public interface OnGenericMotionListener { 12350 /** 12351 * Called when a generic motion event is dispatched to a view. This allows listeners to 12352 * get a chance to respond before the target view. 12353 * 12354 * @param v The view the generic motion event has been dispatched to. 12355 * @param event The MotionEvent object containing full information about 12356 * the event. 12357 * @return True if the listener has consumed the event, false otherwise. 12358 */ 12359 boolean onGenericMotion(View v, MotionEvent event); 12360 } 12361 12362 /** 12363 * Interface definition for a callback to be invoked when a view has been clicked and held. 12364 */ 12365 public interface OnLongClickListener { 12366 /** 12367 * Called when a view has been clicked and held. 12368 * 12369 * @param v The view that was clicked and held. 12370 * 12371 * @return true if the callback consumed the long click, false otherwise. 12372 */ 12373 boolean onLongClick(View v); 12374 } 12375 12376 /** 12377 * Interface definition for a callback to be invoked when a drag is being dispatched 12378 * to this view. The callback will be invoked before the hosting view's own 12379 * onDrag(event) method. If the listener wants to fall back to the hosting view's 12380 * onDrag(event) behavior, it should return 'false' from this callback. 12381 */ 12382 public interface OnDragListener { 12383 /** 12384 * Called when a drag event is dispatched to a view. This allows listeners 12385 * to get a chance to override base View behavior. 12386 * 12387 * @param v The View that received the drag event. 12388 * @param event The {@link android.view.DragEvent} object for the drag event. 12389 * @return {@code true} if the drag event was handled successfully, or {@code false} 12390 * if the drag event was not handled. Note that {@code false} will trigger the View 12391 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 12392 */ 12393 boolean onDrag(View v, DragEvent event); 12394 } 12395 12396 /** 12397 * Interface definition for a callback to be invoked when the focus state of 12398 * a view changed. 12399 */ 12400 public interface OnFocusChangeListener { 12401 /** 12402 * Called when the focus state of a view has changed. 12403 * 12404 * @param v The view whose state has changed. 12405 * @param hasFocus The new focus state of v. 12406 */ 12407 void onFocusChange(View v, boolean hasFocus); 12408 } 12409 12410 /** 12411 * Interface definition for a callback to be invoked when a view is clicked. 12412 */ 12413 public interface OnClickListener { 12414 /** 12415 * Called when a view has been clicked. 12416 * 12417 * @param v The view that was clicked. 12418 */ 12419 void onClick(View v); 12420 } 12421 12422 /** 12423 * Interface definition for a callback to be invoked when the context menu 12424 * for this view is being built. 12425 */ 12426 public interface OnCreateContextMenuListener { 12427 /** 12428 * Called when the context menu for this view is being built. It is not 12429 * safe to hold onto the menu after this method returns. 12430 * 12431 * @param menu The context menu that is being built 12432 * @param v The view for which the context menu is being built 12433 * @param menuInfo Extra information about the item for which the 12434 * context menu should be shown. This information will vary 12435 * depending on the class of v. 12436 */ 12437 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 12438 } 12439 12440 /** 12441 * Interface definition for a callback to be invoked when the status bar changes 12442 * visibility. 12443 * 12444 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 12445 */ 12446 public interface OnSystemUiVisibilityChangeListener { 12447 /** 12448 * Called when the status bar changes visibility because of a call to 12449 * {@link View#setSystemUiVisibility(int)}. 12450 * 12451 * @param visibility {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}. 12452 */ 12453 public void onSystemUiVisibilityChange(int visibility); 12454 } 12455 12456 /** 12457 * Interface definition for a callback to be invoked when this view is attached 12458 * or detached from its window. 12459 */ 12460 public interface OnAttachStateChangeListener { 12461 /** 12462 * Called when the view is attached to a window. 12463 * @param v The view that was attached 12464 */ 12465 public void onViewAttachedToWindow(View v); 12466 /** 12467 * Called when the view is detached from a window. 12468 * @param v The view that was detached 12469 */ 12470 public void onViewDetachedFromWindow(View v); 12471 } 12472 12473 private final class UnsetPressedState implements Runnable { 12474 public void run() { 12475 setPressed(false); 12476 } 12477 } 12478 12479 /** 12480 * Base class for derived classes that want to save and restore their own 12481 * state in {@link android.view.View#onSaveInstanceState()}. 12482 */ 12483 public static class BaseSavedState extends AbsSavedState { 12484 /** 12485 * Constructor used when reading from a parcel. Reads the state of the superclass. 12486 * 12487 * @param source 12488 */ 12489 public BaseSavedState(Parcel source) { 12490 super(source); 12491 } 12492 12493 /** 12494 * Constructor called by derived classes when creating their SavedState objects 12495 * 12496 * @param superState The state of the superclass of this view 12497 */ 12498 public BaseSavedState(Parcelable superState) { 12499 super(superState); 12500 } 12501 12502 public static final Parcelable.Creator<BaseSavedState> CREATOR = 12503 new Parcelable.Creator<BaseSavedState>() { 12504 public BaseSavedState createFromParcel(Parcel in) { 12505 return new BaseSavedState(in); 12506 } 12507 12508 public BaseSavedState[] newArray(int size) { 12509 return new BaseSavedState[size]; 12510 } 12511 }; 12512 } 12513 12514 /** 12515 * A set of information given to a view when it is attached to its parent 12516 * window. 12517 */ 12518 static class AttachInfo { 12519 interface Callbacks { 12520 void playSoundEffect(int effectId); 12521 boolean performHapticFeedback(int effectId, boolean always); 12522 } 12523 12524 /** 12525 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 12526 * to a Handler. This class contains the target (View) to invalidate and 12527 * the coordinates of the dirty rectangle. 12528 * 12529 * For performance purposes, this class also implements a pool of up to 12530 * POOL_LIMIT objects that get reused. This reduces memory allocations 12531 * whenever possible. 12532 */ 12533 static class InvalidateInfo implements Poolable<InvalidateInfo> { 12534 private static final int POOL_LIMIT = 10; 12535 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 12536 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 12537 public InvalidateInfo newInstance() { 12538 return new InvalidateInfo(); 12539 } 12540 12541 public void onAcquired(InvalidateInfo element) { 12542 } 12543 12544 public void onReleased(InvalidateInfo element) { 12545 } 12546 }, POOL_LIMIT) 12547 ); 12548 12549 private InvalidateInfo mNext; 12550 12551 View target; 12552 12553 int left; 12554 int top; 12555 int right; 12556 int bottom; 12557 12558 public void setNextPoolable(InvalidateInfo element) { 12559 mNext = element; 12560 } 12561 12562 public InvalidateInfo getNextPoolable() { 12563 return mNext; 12564 } 12565 12566 static InvalidateInfo acquire() { 12567 return sPool.acquire(); 12568 } 12569 12570 void release() { 12571 sPool.release(this); 12572 } 12573 } 12574 12575 final IWindowSession mSession; 12576 12577 final IWindow mWindow; 12578 12579 final IBinder mWindowToken; 12580 12581 final Callbacks mRootCallbacks; 12582 12583 Canvas mHardwareCanvas; 12584 12585 /** 12586 * The top view of the hierarchy. 12587 */ 12588 View mRootView; 12589 12590 IBinder mPanelParentWindowToken; 12591 Surface mSurface; 12592 12593 boolean mHardwareAccelerated; 12594 boolean mHardwareAccelerationRequested; 12595 HardwareRenderer mHardwareRenderer; 12596 12597 /** 12598 * Scale factor used by the compatibility mode 12599 */ 12600 float mApplicationScale; 12601 12602 /** 12603 * Indicates whether the application is in compatibility mode 12604 */ 12605 boolean mScalingRequired; 12606 12607 /** 12608 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 12609 */ 12610 boolean mTurnOffWindowResizeAnim; 12611 12612 /** 12613 * Left position of this view's window 12614 */ 12615 int mWindowLeft; 12616 12617 /** 12618 * Top position of this view's window 12619 */ 12620 int mWindowTop; 12621 12622 /** 12623 * Indicates whether views need to use 32-bit drawing caches 12624 */ 12625 boolean mUse32BitDrawingCache; 12626 12627 /** 12628 * For windows that are full-screen but using insets to layout inside 12629 * of the screen decorations, these are the current insets for the 12630 * content of the window. 12631 */ 12632 final Rect mContentInsets = new Rect(); 12633 12634 /** 12635 * For windows that are full-screen but using insets to layout inside 12636 * of the screen decorations, these are the current insets for the 12637 * actual visible parts of the window. 12638 */ 12639 final Rect mVisibleInsets = new Rect(); 12640 12641 /** 12642 * The internal insets given by this window. This value is 12643 * supplied by the client (through 12644 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 12645 * be given to the window manager when changed to be used in laying 12646 * out windows behind it. 12647 */ 12648 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 12649 = new ViewTreeObserver.InternalInsetsInfo(); 12650 12651 /** 12652 * All views in the window's hierarchy that serve as scroll containers, 12653 * used to determine if the window can be resized or must be panned 12654 * to adjust for a soft input area. 12655 */ 12656 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 12657 12658 final KeyEvent.DispatcherState mKeyDispatchState 12659 = new KeyEvent.DispatcherState(); 12660 12661 /** 12662 * Indicates whether the view's window currently has the focus. 12663 */ 12664 boolean mHasWindowFocus; 12665 12666 /** 12667 * The current visibility of the window. 12668 */ 12669 int mWindowVisibility; 12670 12671 /** 12672 * Indicates the time at which drawing started to occur. 12673 */ 12674 long mDrawingTime; 12675 12676 /** 12677 * Indicates whether or not ignoring the DIRTY_MASK flags. 12678 */ 12679 boolean mIgnoreDirtyState; 12680 12681 /** 12682 * Indicates whether the view's window is currently in touch mode. 12683 */ 12684 boolean mInTouchMode; 12685 12686 /** 12687 * Indicates that ViewAncestor should trigger a global layout change 12688 * the next time it performs a traversal 12689 */ 12690 boolean mRecomputeGlobalAttributes; 12691 12692 /** 12693 * Set during a traveral if any views want to keep the screen on. 12694 */ 12695 boolean mKeepScreenOn; 12696 12697 /** 12698 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 12699 */ 12700 int mSystemUiVisibility; 12701 12702 /** 12703 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 12704 * attached. 12705 */ 12706 boolean mHasSystemUiListeners; 12707 12708 /** 12709 * Set if the visibility of any views has changed. 12710 */ 12711 boolean mViewVisibilityChanged; 12712 12713 /** 12714 * Set to true if a view has been scrolled. 12715 */ 12716 boolean mViewScrollChanged; 12717 12718 /** 12719 * Global to the view hierarchy used as a temporary for dealing with 12720 * x/y points in the transparent region computations. 12721 */ 12722 final int[] mTransparentLocation = new int[2]; 12723 12724 /** 12725 * Global to the view hierarchy used as a temporary for dealing with 12726 * x/y points in the ViewGroup.invalidateChild implementation. 12727 */ 12728 final int[] mInvalidateChildLocation = new int[2]; 12729 12730 12731 /** 12732 * Global to the view hierarchy used as a temporary for dealing with 12733 * x/y location when view is transformed. 12734 */ 12735 final float[] mTmpTransformLocation = new float[2]; 12736 12737 /** 12738 * The view tree observer used to dispatch global events like 12739 * layout, pre-draw, touch mode change, etc. 12740 */ 12741 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 12742 12743 /** 12744 * A Canvas used by the view hierarchy to perform bitmap caching. 12745 */ 12746 Canvas mCanvas; 12747 12748 /** 12749 * A Handler supplied by a view's {@link android.view.ViewAncestor}. This 12750 * handler can be used to pump events in the UI events queue. 12751 */ 12752 final Handler mHandler; 12753 12754 /** 12755 * Identifier for messages requesting the view to be invalidated. 12756 * Such messages should be sent to {@link #mHandler}. 12757 */ 12758 static final int INVALIDATE_MSG = 0x1; 12759 12760 /** 12761 * Identifier for messages requesting the view to invalidate a region. 12762 * Such messages should be sent to {@link #mHandler}. 12763 */ 12764 static final int INVALIDATE_RECT_MSG = 0x2; 12765 12766 /** 12767 * Temporary for use in computing invalidate rectangles while 12768 * calling up the hierarchy. 12769 */ 12770 final Rect mTmpInvalRect = new Rect(); 12771 12772 /** 12773 * Temporary for use in computing hit areas with transformed views 12774 */ 12775 final RectF mTmpTransformRect = new RectF(); 12776 12777 /** 12778 * Temporary list for use in collecting focusable descendents of a view. 12779 */ 12780 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 12781 12782 /** 12783 * Creates a new set of attachment information with the specified 12784 * events handler and thread. 12785 * 12786 * @param handler the events handler the view must use 12787 */ 12788 AttachInfo(IWindowSession session, IWindow window, 12789 Handler handler, Callbacks effectPlayer) { 12790 mSession = session; 12791 mWindow = window; 12792 mWindowToken = window.asBinder(); 12793 mHandler = handler; 12794 mRootCallbacks = effectPlayer; 12795 } 12796 } 12797 12798 /** 12799 * <p>ScrollabilityCache holds various fields used by a View when scrolling 12800 * is supported. This avoids keeping too many unused fields in most 12801 * instances of View.</p> 12802 */ 12803 private static class ScrollabilityCache implements Runnable { 12804 12805 /** 12806 * Scrollbars are not visible 12807 */ 12808 public static final int OFF = 0; 12809 12810 /** 12811 * Scrollbars are visible 12812 */ 12813 public static final int ON = 1; 12814 12815 /** 12816 * Scrollbars are fading away 12817 */ 12818 public static final int FADING = 2; 12819 12820 public boolean fadeScrollBars; 12821 12822 public int fadingEdgeLength; 12823 public int scrollBarDefaultDelayBeforeFade; 12824 public int scrollBarFadeDuration; 12825 12826 public int scrollBarSize; 12827 public ScrollBarDrawable scrollBar; 12828 public float[] interpolatorValues; 12829 public View host; 12830 12831 public final Paint paint; 12832 public final Matrix matrix; 12833 public Shader shader; 12834 12835 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 12836 12837 private static final float[] OPAQUE = { 255 }; 12838 private static final float[] TRANSPARENT = { 0.0f }; 12839 12840 /** 12841 * When fading should start. This time moves into the future every time 12842 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 12843 */ 12844 public long fadeStartTime; 12845 12846 12847 /** 12848 * The current state of the scrollbars: ON, OFF, or FADING 12849 */ 12850 public int state = OFF; 12851 12852 private int mLastColor; 12853 12854 public ScrollabilityCache(ViewConfiguration configuration, View host) { 12855 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 12856 scrollBarSize = configuration.getScaledScrollBarSize(); 12857 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 12858 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 12859 12860 paint = new Paint(); 12861 matrix = new Matrix(); 12862 // use use a height of 1, and then wack the matrix each time we 12863 // actually use it. 12864 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 12865 12866 paint.setShader(shader); 12867 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 12868 this.host = host; 12869 } 12870 12871 public void setFadeColor(int color) { 12872 if (color != 0 && color != mLastColor) { 12873 mLastColor = color; 12874 color |= 0xFF000000; 12875 12876 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 12877 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 12878 12879 paint.setShader(shader); 12880 // Restore the default transfer mode (src_over) 12881 paint.setXfermode(null); 12882 } 12883 } 12884 12885 public void run() { 12886 long now = AnimationUtils.currentAnimationTimeMillis(); 12887 if (now >= fadeStartTime) { 12888 12889 // the animation fades the scrollbars out by changing 12890 // the opacity (alpha) from fully opaque to fully 12891 // transparent 12892 int nextFrame = (int) now; 12893 int framesCount = 0; 12894 12895 Interpolator interpolator = scrollBarInterpolator; 12896 12897 // Start opaque 12898 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 12899 12900 // End transparent 12901 nextFrame += scrollBarFadeDuration; 12902 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 12903 12904 state = FADING; 12905 12906 // Kick off the fade animation 12907 host.invalidate(true); 12908 } 12909 } 12910 12911 } 12912} 12913