View.java revision 57f3b566db630233087b121d3d43ecd81a6dfd95
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.content.ClipData; 20import android.content.Context; 21import android.content.res.Configuration; 22import android.content.res.Resources; 23import android.content.res.TypedArray; 24import android.graphics.Bitmap; 25import android.graphics.Camera; 26import android.graphics.Canvas; 27import android.graphics.Interpolator; 28import android.graphics.LinearGradient; 29import android.graphics.Matrix; 30import android.graphics.Paint; 31import android.graphics.PixelFormat; 32import android.graphics.Point; 33import android.graphics.PorterDuff; 34import android.graphics.PorterDuffXfermode; 35import android.graphics.Rect; 36import android.graphics.RectF; 37import android.graphics.Region; 38import android.graphics.Shader; 39import android.graphics.drawable.ColorDrawable; 40import android.graphics.drawable.Drawable; 41import android.os.Handler; 42import android.os.IBinder; 43import android.os.Message; 44import android.os.Parcel; 45import android.os.Parcelable; 46import android.os.RemoteException; 47import android.os.SystemClock; 48import android.text.TextUtils; 49import android.util.AttributeSet; 50import android.util.FloatProperty; 51import android.util.LocaleUtil; 52import android.util.Log; 53import android.util.Pool; 54import android.util.Poolable; 55import android.util.PoolableManager; 56import android.util.Pools; 57import android.util.Property; 58import android.util.SparseArray; 59import android.util.TypedValue; 60import android.view.ContextMenu.ContextMenuInfo; 61import android.view.accessibility.AccessibilityEvent; 62import android.view.accessibility.AccessibilityEventSource; 63import android.view.accessibility.AccessibilityManager; 64import android.view.accessibility.AccessibilityNodeInfo; 65import android.view.animation.Animation; 66import android.view.animation.AnimationUtils; 67import android.view.inputmethod.EditorInfo; 68import android.view.inputmethod.InputConnection; 69import android.view.inputmethod.InputMethodManager; 70import android.widget.ScrollBarDrawable; 71 72import static android.os.Build.VERSION_CODES.*; 73 74import com.android.internal.R; 75import com.android.internal.util.Predicate; 76import com.android.internal.view.menu.MenuBuilder; 77 78import java.lang.ref.WeakReference; 79import java.lang.reflect.InvocationTargetException; 80import java.lang.reflect.Method; 81import java.util.ArrayList; 82import java.util.Arrays; 83import java.util.Locale; 84import java.util.concurrent.CopyOnWriteArrayList; 85 86/** 87 * <p> 88 * This class represents the basic building block for user interface components. A View 89 * occupies a rectangular area on the screen and is responsible for drawing and 90 * event handling. View is the base class for <em>widgets</em>, which are 91 * used to create interactive UI components (buttons, text fields, etc.). The 92 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 93 * are invisible containers that hold other Views (or other ViewGroups) and define 94 * their layout properties. 95 * </p> 96 * 97 * <div class="special reference"> 98 * <h3>Developer Guides</h3> 99 * <p>For information about using this class to develop your application's user interface, 100 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 101 * </div> 102 * 103 * <a name="Using"></a> 104 * <h3>Using Views</h3> 105 * <p> 106 * All of the views in a window are arranged in a single tree. You can add views 107 * either from code or by specifying a tree of views in one or more XML layout 108 * files. There are many specialized subclasses of views that act as controls or 109 * are capable of displaying text, images, or other content. 110 * </p> 111 * <p> 112 * Once you have created a tree of views, there are typically a few types of 113 * common operations you may wish to perform: 114 * <ul> 115 * <li><strong>Set properties:</strong> for example setting the text of a 116 * {@link android.widget.TextView}. The available properties and the methods 117 * that set them will vary among the different subclasses of views. Note that 118 * properties that are known at build time can be set in the XML layout 119 * files.</li> 120 * <li><strong>Set focus:</strong> The framework will handled moving focus in 121 * response to user input. To force focus to a specific view, call 122 * {@link #requestFocus}.</li> 123 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 124 * that will be notified when something interesting happens to the view. For 125 * example, all views will let you set a listener to be notified when the view 126 * gains or loses focus. You can register such a listener using 127 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 128 * Other view subclasses offer more specialized listeners. For example, a Button 129 * exposes a listener to notify clients when the button is clicked.</li> 130 * <li><strong>Set visibility:</strong> You can hide or show views using 131 * {@link #setVisibility(int)}.</li> 132 * </ul> 133 * </p> 134 * <p><em> 135 * Note: The Android framework is responsible for measuring, laying out and 136 * drawing views. You should not call methods that perform these actions on 137 * views yourself unless you are actually implementing a 138 * {@link android.view.ViewGroup}. 139 * </em></p> 140 * 141 * <a name="Lifecycle"></a> 142 * <h3>Implementing a Custom View</h3> 143 * 144 * <p> 145 * To implement a custom view, you will usually begin by providing overrides for 146 * some of the standard methods that the framework calls on all views. You do 147 * not need to override all of these methods. In fact, you can start by just 148 * overriding {@link #onDraw(android.graphics.Canvas)}. 149 * <table border="2" width="85%" align="center" cellpadding="5"> 150 * <thead> 151 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 152 * </thead> 153 * 154 * <tbody> 155 * <tr> 156 * <td rowspan="2">Creation</td> 157 * <td>Constructors</td> 158 * <td>There is a form of the constructor that are called when the view 159 * is created from code and a form that is called when the view is 160 * inflated from a layout file. The second form should parse and apply 161 * any attributes defined in the layout file. 162 * </td> 163 * </tr> 164 * <tr> 165 * <td><code>{@link #onFinishInflate()}</code></td> 166 * <td>Called after a view and all of its children has been inflated 167 * from XML.</td> 168 * </tr> 169 * 170 * <tr> 171 * <td rowspan="3">Layout</td> 172 * <td><code>{@link #onMeasure(int, int)}</code></td> 173 * <td>Called to determine the size requirements for this view and all 174 * of its children. 175 * </td> 176 * </tr> 177 * <tr> 178 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 179 * <td>Called when this view should assign a size and position to all 180 * of its children. 181 * </td> 182 * </tr> 183 * <tr> 184 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 185 * <td>Called when the size of this view has changed. 186 * </td> 187 * </tr> 188 * 189 * <tr> 190 * <td>Drawing</td> 191 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 192 * <td>Called when the view should render its content. 193 * </td> 194 * </tr> 195 * 196 * <tr> 197 * <td rowspan="4">Event processing</td> 198 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 199 * <td>Called when a new key event occurs. 200 * </td> 201 * </tr> 202 * <tr> 203 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 204 * <td>Called when a key up event occurs. 205 * </td> 206 * </tr> 207 * <tr> 208 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 209 * <td>Called when a trackball motion event occurs. 210 * </td> 211 * </tr> 212 * <tr> 213 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 214 * <td>Called when a touch screen motion event occurs. 215 * </td> 216 * </tr> 217 * 218 * <tr> 219 * <td rowspan="2">Focus</td> 220 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 221 * <td>Called when the view gains or loses focus. 222 * </td> 223 * </tr> 224 * 225 * <tr> 226 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 227 * <td>Called when the window containing the view gains or loses focus. 228 * </td> 229 * </tr> 230 * 231 * <tr> 232 * <td rowspan="3">Attaching</td> 233 * <td><code>{@link #onAttachedToWindow()}</code></td> 234 * <td>Called when the view is attached to a window. 235 * </td> 236 * </tr> 237 * 238 * <tr> 239 * <td><code>{@link #onDetachedFromWindow}</code></td> 240 * <td>Called when the view is detached from its window. 241 * </td> 242 * </tr> 243 * 244 * <tr> 245 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 246 * <td>Called when the visibility of the window containing the view 247 * has changed. 248 * </td> 249 * </tr> 250 * </tbody> 251 * 252 * </table> 253 * </p> 254 * 255 * <a name="IDs"></a> 256 * <h3>IDs</h3> 257 * Views may have an integer id associated with them. These ids are typically 258 * assigned in the layout XML files, and are used to find specific views within 259 * the view tree. A common pattern is to: 260 * <ul> 261 * <li>Define a Button in the layout file and assign it a unique ID. 262 * <pre> 263 * <Button 264 * android:id="@+id/my_button" 265 * android:layout_width="wrap_content" 266 * android:layout_height="wrap_content" 267 * android:text="@string/my_button_text"/> 268 * </pre></li> 269 * <li>From the onCreate method of an Activity, find the Button 270 * <pre class="prettyprint"> 271 * Button myButton = (Button) findViewById(R.id.my_button); 272 * </pre></li> 273 * </ul> 274 * <p> 275 * View IDs need not be unique throughout the tree, but it is good practice to 276 * ensure that they are at least unique within the part of the tree you are 277 * searching. 278 * </p> 279 * 280 * <a name="Position"></a> 281 * <h3>Position</h3> 282 * <p> 283 * The geometry of a view is that of a rectangle. A view has a location, 284 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 285 * two dimensions, expressed as a width and a height. The unit for location 286 * and dimensions is the pixel. 287 * </p> 288 * 289 * <p> 290 * It is possible to retrieve the location of a view by invoking the methods 291 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 292 * coordinate of the rectangle representing the view. The latter returns the 293 * top, or Y, coordinate of the rectangle representing the view. These methods 294 * both return the location of the view relative to its parent. For instance, 295 * when getLeft() returns 20, that means the view is located 20 pixels to the 296 * right of the left edge of its direct parent. 297 * </p> 298 * 299 * <p> 300 * In addition, several convenience methods are offered to avoid unnecessary 301 * computations, namely {@link #getRight()} and {@link #getBottom()}. 302 * These methods return the coordinates of the right and bottom edges of the 303 * rectangle representing the view. For instance, calling {@link #getRight()} 304 * is similar to the following computation: <code>getLeft() + getWidth()</code> 305 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 306 * </p> 307 * 308 * <a name="SizePaddingMargins"></a> 309 * <h3>Size, padding and margins</h3> 310 * <p> 311 * The size of a view is expressed with a width and a height. A view actually 312 * possess two pairs of width and height values. 313 * </p> 314 * 315 * <p> 316 * The first pair is known as <em>measured width</em> and 317 * <em>measured height</em>. These dimensions define how big a view wants to be 318 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 319 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 320 * and {@link #getMeasuredHeight()}. 321 * </p> 322 * 323 * <p> 324 * The second pair is simply known as <em>width</em> and <em>height</em>, or 325 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 326 * dimensions define the actual size of the view on screen, at drawing time and 327 * after layout. These values may, but do not have to, be different from the 328 * measured width and height. The width and height can be obtained by calling 329 * {@link #getWidth()} and {@link #getHeight()}. 330 * </p> 331 * 332 * <p> 333 * To measure its dimensions, a view takes into account its padding. The padding 334 * is expressed in pixels for the left, top, right and bottom parts of the view. 335 * Padding can be used to offset the content of the view by a specific amount of 336 * pixels. For instance, a left padding of 2 will push the view's content by 337 * 2 pixels to the right of the left edge. Padding can be set using the 338 * {@link #setPadding(int, int, int, int)} method and queried by calling 339 * {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 340 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}. 341 * </p> 342 * 343 * <p> 344 * Even though a view can define a padding, it does not provide any support for 345 * margins. However, view groups provide such a support. Refer to 346 * {@link android.view.ViewGroup} and 347 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 348 * </p> 349 * 350 * <a name="Layout"></a> 351 * <h3>Layout</h3> 352 * <p> 353 * Layout is a two pass process: a measure pass and a layout pass. The measuring 354 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 355 * of the view tree. Each view pushes dimension specifications down the tree 356 * during the recursion. At the end of the measure pass, every view has stored 357 * its measurements. The second pass happens in 358 * {@link #layout(int,int,int,int)} and is also top-down. During 359 * this pass each parent is responsible for positioning all of its children 360 * using the sizes computed in the measure pass. 361 * </p> 362 * 363 * <p> 364 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 365 * {@link #getMeasuredHeight()} values must be set, along with those for all of 366 * that view's descendants. A view's measured width and measured height values 367 * must respect the constraints imposed by the view's parents. This guarantees 368 * that at the end of the measure pass, all parents accept all of their 369 * children's measurements. A parent view may call measure() more than once on 370 * its children. For example, the parent may measure each child once with 371 * unspecified dimensions to find out how big they want to be, then call 372 * measure() on them again with actual numbers if the sum of all the children's 373 * unconstrained sizes is too big or too small. 374 * </p> 375 * 376 * <p> 377 * The measure pass uses two classes to communicate dimensions. The 378 * {@link MeasureSpec} class is used by views to tell their parents how they 379 * want to be measured and positioned. The base LayoutParams class just 380 * describes how big the view wants to be for both width and height. For each 381 * dimension, it can specify one of: 382 * <ul> 383 * <li> an exact number 384 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 385 * (minus padding) 386 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 387 * enclose its content (plus padding). 388 * </ul> 389 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 390 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 391 * an X and Y value. 392 * </p> 393 * 394 * <p> 395 * MeasureSpecs are used to push requirements down the tree from parent to 396 * child. A MeasureSpec can be in one of three modes: 397 * <ul> 398 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 399 * of a child view. For example, a LinearLayout may call measure() on its child 400 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 401 * tall the child view wants to be given a width of 240 pixels. 402 * <li>EXACTLY: This is used by the parent to impose an exact size on the 403 * child. The child must use this size, and guarantee that all of its 404 * descendants will fit within this size. 405 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 406 * child. The child must gurantee that it and all of its descendants will fit 407 * within this size. 408 * </ul> 409 * </p> 410 * 411 * <p> 412 * To intiate a layout, call {@link #requestLayout}. This method is typically 413 * called by a view on itself when it believes that is can no longer fit within 414 * its current bounds. 415 * </p> 416 * 417 * <a name="Drawing"></a> 418 * <h3>Drawing</h3> 419 * <p> 420 * Drawing is handled by walking the tree and rendering each view that 421 * intersects the invalid region. Because the tree is traversed in-order, 422 * this means that parents will draw before (i.e., behind) their children, with 423 * siblings drawn in the order they appear in the tree. 424 * If you set a background drawable for a View, then the View will draw it for you 425 * before calling back to its <code>onDraw()</code> method. 426 * </p> 427 * 428 * <p> 429 * Note that the framework will not draw views that are not in the invalid region. 430 * </p> 431 * 432 * <p> 433 * To force a view to draw, call {@link #invalidate()}. 434 * </p> 435 * 436 * <a name="EventHandlingThreading"></a> 437 * <h3>Event Handling and Threading</h3> 438 * <p> 439 * The basic cycle of a view is as follows: 440 * <ol> 441 * <li>An event comes in and is dispatched to the appropriate view. The view 442 * handles the event and notifies any listeners.</li> 443 * <li>If in the course of processing the event, the view's bounds may need 444 * to be changed, the view will call {@link #requestLayout()}.</li> 445 * <li>Similarly, if in the course of processing the event the view's appearance 446 * may need to be changed, the view will call {@link #invalidate()}.</li> 447 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 448 * the framework will take care of measuring, laying out, and drawing the tree 449 * as appropriate.</li> 450 * </ol> 451 * </p> 452 * 453 * <p><em>Note: The entire view tree is single threaded. You must always be on 454 * the UI thread when calling any method on any view.</em> 455 * If you are doing work on other threads and want to update the state of a view 456 * from that thread, you should use a {@link Handler}. 457 * </p> 458 * 459 * <a name="FocusHandling"></a> 460 * <h3>Focus Handling</h3> 461 * <p> 462 * The framework will handle routine focus movement in response to user input. 463 * This includes changing the focus as views are removed or hidden, or as new 464 * views become available. Views indicate their willingness to take focus 465 * through the {@link #isFocusable} method. To change whether a view can take 466 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 467 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 468 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 469 * </p> 470 * <p> 471 * Focus movement is based on an algorithm which finds the nearest neighbor in a 472 * given direction. In rare cases, the default algorithm may not match the 473 * intended behavior of the developer. In these situations, you can provide 474 * explicit overrides by using these XML attributes in the layout file: 475 * <pre> 476 * nextFocusDown 477 * nextFocusLeft 478 * nextFocusRight 479 * nextFocusUp 480 * </pre> 481 * </p> 482 * 483 * 484 * <p> 485 * To get a particular view to take focus, call {@link #requestFocus()}. 486 * </p> 487 * 488 * <a name="TouchMode"></a> 489 * <h3>Touch Mode</h3> 490 * <p> 491 * When a user is navigating a user interface via directional keys such as a D-pad, it is 492 * necessary to give focus to actionable items such as buttons so the user can see 493 * what will take input. If the device has touch capabilities, however, and the user 494 * begins interacting with the interface by touching it, it is no longer necessary to 495 * always highlight, or give focus to, a particular view. This motivates a mode 496 * for interaction named 'touch mode'. 497 * </p> 498 * <p> 499 * For a touch capable device, once the user touches the screen, the device 500 * will enter touch mode. From this point onward, only views for which 501 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 502 * Other views that are touchable, like buttons, will not take focus when touched; they will 503 * only fire the on click listeners. 504 * </p> 505 * <p> 506 * Any time a user hits a directional key, such as a D-pad direction, the view device will 507 * exit touch mode, and find a view to take focus, so that the user may resume interacting 508 * with the user interface without touching the screen again. 509 * </p> 510 * <p> 511 * The touch mode state is maintained across {@link android.app.Activity}s. Call 512 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 513 * </p> 514 * 515 * <a name="Scrolling"></a> 516 * <h3>Scrolling</h3> 517 * <p> 518 * The framework provides basic support for views that wish to internally 519 * scroll their content. This includes keeping track of the X and Y scroll 520 * offset as well as mechanisms for drawing scrollbars. See 521 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 522 * {@link #awakenScrollBars()} for more details. 523 * </p> 524 * 525 * <a name="Tags"></a> 526 * <h3>Tags</h3> 527 * <p> 528 * Unlike IDs, tags are not used to identify views. Tags are essentially an 529 * extra piece of information that can be associated with a view. They are most 530 * often used as a convenience to store data related to views in the views 531 * themselves rather than by putting them in a separate structure. 532 * </p> 533 * 534 * <a name="Animation"></a> 535 * <h3>Animation</h3> 536 * <p> 537 * You can attach an {@link Animation} object to a view using 538 * {@link #setAnimation(Animation)} or 539 * {@link #startAnimation(Animation)}. The animation can alter the scale, 540 * rotation, translation and alpha of a view over time. If the animation is 541 * attached to a view that has children, the animation will affect the entire 542 * subtree rooted by that node. When an animation is started, the framework will 543 * take care of redrawing the appropriate views until the animation completes. 544 * </p> 545 * <p> 546 * Starting with Android 3.0, the preferred way of animating views is to use the 547 * {@link android.animation} package APIs. 548 * </p> 549 * 550 * <a name="Security"></a> 551 * <h3>Security</h3> 552 * <p> 553 * Sometimes it is essential that an application be able to verify that an action 554 * is being performed with the full knowledge and consent of the user, such as 555 * granting a permission request, making a purchase or clicking on an advertisement. 556 * Unfortunately, a malicious application could try to spoof the user into 557 * performing these actions, unaware, by concealing the intended purpose of the view. 558 * As a remedy, the framework offers a touch filtering mechanism that can be used to 559 * improve the security of views that provide access to sensitive functionality. 560 * </p><p> 561 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 562 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 563 * will discard touches that are received whenever the view's window is obscured by 564 * another visible window. As a result, the view will not receive touches whenever a 565 * toast, dialog or other window appears above the view's window. 566 * </p><p> 567 * For more fine-grained control over security, consider overriding the 568 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 569 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 570 * </p> 571 * 572 * @attr ref android.R.styleable#View_alpha 573 * @attr ref android.R.styleable#View_background 574 * @attr ref android.R.styleable#View_clickable 575 * @attr ref android.R.styleable#View_contentDescription 576 * @attr ref android.R.styleable#View_drawingCacheQuality 577 * @attr ref android.R.styleable#View_duplicateParentState 578 * @attr ref android.R.styleable#View_id 579 * @attr ref android.R.styleable#View_requiresFadingEdge 580 * @attr ref android.R.styleable#View_fadingEdgeLength 581 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 582 * @attr ref android.R.styleable#View_fitsSystemWindows 583 * @attr ref android.R.styleable#View_isScrollContainer 584 * @attr ref android.R.styleable#View_focusable 585 * @attr ref android.R.styleable#View_focusableInTouchMode 586 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 587 * @attr ref android.R.styleable#View_keepScreenOn 588 * @attr ref android.R.styleable#View_layerType 589 * @attr ref android.R.styleable#View_longClickable 590 * @attr ref android.R.styleable#View_minHeight 591 * @attr ref android.R.styleable#View_minWidth 592 * @attr ref android.R.styleable#View_nextFocusDown 593 * @attr ref android.R.styleable#View_nextFocusLeft 594 * @attr ref android.R.styleable#View_nextFocusRight 595 * @attr ref android.R.styleable#View_nextFocusUp 596 * @attr ref android.R.styleable#View_onClick 597 * @attr ref android.R.styleable#View_padding 598 * @attr ref android.R.styleable#View_paddingBottom 599 * @attr ref android.R.styleable#View_paddingLeft 600 * @attr ref android.R.styleable#View_paddingRight 601 * @attr ref android.R.styleable#View_paddingTop 602 * @attr ref android.R.styleable#View_saveEnabled 603 * @attr ref android.R.styleable#View_rotation 604 * @attr ref android.R.styleable#View_rotationX 605 * @attr ref android.R.styleable#View_rotationY 606 * @attr ref android.R.styleable#View_scaleX 607 * @attr ref android.R.styleable#View_scaleY 608 * @attr ref android.R.styleable#View_scrollX 609 * @attr ref android.R.styleable#View_scrollY 610 * @attr ref android.R.styleable#View_scrollbarSize 611 * @attr ref android.R.styleable#View_scrollbarStyle 612 * @attr ref android.R.styleable#View_scrollbars 613 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 614 * @attr ref android.R.styleable#View_scrollbarFadeDuration 615 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 616 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 617 * @attr ref android.R.styleable#View_scrollbarThumbVertical 618 * @attr ref android.R.styleable#View_scrollbarTrackVertical 619 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 620 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 621 * @attr ref android.R.styleable#View_soundEffectsEnabled 622 * @attr ref android.R.styleable#View_tag 623 * @attr ref android.R.styleable#View_transformPivotX 624 * @attr ref android.R.styleable#View_transformPivotY 625 * @attr ref android.R.styleable#View_translationX 626 * @attr ref android.R.styleable#View_translationY 627 * @attr ref android.R.styleable#View_visibility 628 * 629 * @see android.view.ViewGroup 630 */ 631public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback, 632 AccessibilityEventSource { 633 private static final boolean DBG = false; 634 635 /** 636 * The logging tag used by this class with android.util.Log. 637 */ 638 protected static final String VIEW_LOG_TAG = "View"; 639 640 /** 641 * Used to mark a View that has no ID. 642 */ 643 public static final int NO_ID = -1; 644 645 /** 646 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 647 * calling setFlags. 648 */ 649 private static final int NOT_FOCUSABLE = 0x00000000; 650 651 /** 652 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 653 * setFlags. 654 */ 655 private static final int FOCUSABLE = 0x00000001; 656 657 /** 658 * Mask for use with setFlags indicating bits used for focus. 659 */ 660 private static final int FOCUSABLE_MASK = 0x00000001; 661 662 /** 663 * This view will adjust its padding to fit sytem windows (e.g. status bar) 664 */ 665 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 666 667 /** 668 * This view is visible. 669 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 670 * android:visibility}. 671 */ 672 public static final int VISIBLE = 0x00000000; 673 674 /** 675 * This view is invisible, but it still takes up space for layout purposes. 676 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 677 * android:visibility}. 678 */ 679 public static final int INVISIBLE = 0x00000004; 680 681 /** 682 * This view is invisible, and it doesn't take any space for layout 683 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 684 * android:visibility}. 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 * Horizontal direction of this view is from Left to Right. 955 * Use with {@link #setLayoutDirection}. 956 * {@hide} 957 */ 958 public static final int LAYOUT_DIRECTION_LTR = 0x00000000; 959 960 /** 961 * Horizontal direction of this view is from Right to Left. 962 * Use with {@link #setLayoutDirection}. 963 * {@hide} 964 */ 965 public static final int LAYOUT_DIRECTION_RTL = 0x40000000; 966 967 /** 968 * Horizontal direction of this view is inherited from its parent. 969 * Use with {@link #setLayoutDirection}. 970 * {@hide} 971 */ 972 public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000; 973 974 /** 975 * Horizontal direction of this view is from deduced from the default language 976 * script for the locale. Use with {@link #setLayoutDirection}. 977 * {@hide} 978 */ 979 public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000; 980 981 /** 982 * Mask for use with setFlags indicating bits used for horizontalDirection. 983 * {@hide} 984 */ 985 static final int LAYOUT_DIRECTION_MASK = 0xC0000000; 986 987 /* 988 * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct 989 * flag value. 990 * {@hide} 991 */ 992 private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR, 993 LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE}; 994 995 /** 996 * Default horizontalDirection. 997 * {@hide} 998 */ 999 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1000 1001 /** 1002 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1003 * should add all focusable Views regardless if they are focusable in touch mode. 1004 */ 1005 public static final int FOCUSABLES_ALL = 0x00000000; 1006 1007 /** 1008 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1009 * should add only Views focusable in touch mode. 1010 */ 1011 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1012 1013 /** 1014 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1015 * item. 1016 */ 1017 public static final int FOCUS_BACKWARD = 0x00000001; 1018 1019 /** 1020 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1021 * item. 1022 */ 1023 public static final int FOCUS_FORWARD = 0x00000002; 1024 1025 /** 1026 * Use with {@link #focusSearch(int)}. Move focus to the left. 1027 */ 1028 public static final int FOCUS_LEFT = 0x00000011; 1029 1030 /** 1031 * Use with {@link #focusSearch(int)}. Move focus up. 1032 */ 1033 public static final int FOCUS_UP = 0x00000021; 1034 1035 /** 1036 * Use with {@link #focusSearch(int)}. Move focus to the right. 1037 */ 1038 public static final int FOCUS_RIGHT = 0x00000042; 1039 1040 /** 1041 * Use with {@link #focusSearch(int)}. Move focus down. 1042 */ 1043 public static final int FOCUS_DOWN = 0x00000082; 1044 1045 /** 1046 * Bits of {@link #getMeasuredWidthAndState()} and 1047 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1048 */ 1049 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1050 1051 /** 1052 * Bits of {@link #getMeasuredWidthAndState()} and 1053 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1054 */ 1055 public static final int MEASURED_STATE_MASK = 0xff000000; 1056 1057 /** 1058 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1059 * for functions that combine both width and height into a single int, 1060 * such as {@link #getMeasuredState()} and the childState argument of 1061 * {@link #resolveSizeAndState(int, int, int)}. 1062 */ 1063 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1064 1065 /** 1066 * Bit of {@link #getMeasuredWidthAndState()} and 1067 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1068 * is smaller that the space the view would like to have. 1069 */ 1070 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1071 1072 /** 1073 * Base View state sets 1074 */ 1075 // Singles 1076 /** 1077 * Indicates the view has no states set. States are used with 1078 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1079 * view depending on its state. 1080 * 1081 * @see android.graphics.drawable.Drawable 1082 * @see #getDrawableState() 1083 */ 1084 protected static final int[] EMPTY_STATE_SET; 1085 /** 1086 * Indicates the view is enabled. States are used with 1087 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1088 * view depending on its state. 1089 * 1090 * @see android.graphics.drawable.Drawable 1091 * @see #getDrawableState() 1092 */ 1093 protected static final int[] ENABLED_STATE_SET; 1094 /** 1095 * Indicates the view is focused. States are used with 1096 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1097 * view depending on its state. 1098 * 1099 * @see android.graphics.drawable.Drawable 1100 * @see #getDrawableState() 1101 */ 1102 protected static final int[] FOCUSED_STATE_SET; 1103 /** 1104 * Indicates the view is selected. States are used with 1105 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1106 * view depending on its state. 1107 * 1108 * @see android.graphics.drawable.Drawable 1109 * @see #getDrawableState() 1110 */ 1111 protected static final int[] SELECTED_STATE_SET; 1112 /** 1113 * Indicates the view is pressed. States are used with 1114 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1115 * view depending on its state. 1116 * 1117 * @see android.graphics.drawable.Drawable 1118 * @see #getDrawableState() 1119 * @hide 1120 */ 1121 protected static final int[] PRESSED_STATE_SET; 1122 /** 1123 * Indicates the view's window has focus. States are used with 1124 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1125 * view depending on its state. 1126 * 1127 * @see android.graphics.drawable.Drawable 1128 * @see #getDrawableState() 1129 */ 1130 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1131 // Doubles 1132 /** 1133 * Indicates the view is enabled and has the focus. 1134 * 1135 * @see #ENABLED_STATE_SET 1136 * @see #FOCUSED_STATE_SET 1137 */ 1138 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1139 /** 1140 * Indicates the view is enabled and selected. 1141 * 1142 * @see #ENABLED_STATE_SET 1143 * @see #SELECTED_STATE_SET 1144 */ 1145 protected static final int[] ENABLED_SELECTED_STATE_SET; 1146 /** 1147 * Indicates the view is enabled and that its window has focus. 1148 * 1149 * @see #ENABLED_STATE_SET 1150 * @see #WINDOW_FOCUSED_STATE_SET 1151 */ 1152 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1153 /** 1154 * Indicates the view is focused and selected. 1155 * 1156 * @see #FOCUSED_STATE_SET 1157 * @see #SELECTED_STATE_SET 1158 */ 1159 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1160 /** 1161 * Indicates the view has the focus and that its window has the focus. 1162 * 1163 * @see #FOCUSED_STATE_SET 1164 * @see #WINDOW_FOCUSED_STATE_SET 1165 */ 1166 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1167 /** 1168 * Indicates the view is selected and that its window has the focus. 1169 * 1170 * @see #SELECTED_STATE_SET 1171 * @see #WINDOW_FOCUSED_STATE_SET 1172 */ 1173 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1174 // Triples 1175 /** 1176 * Indicates the view is enabled, focused and selected. 1177 * 1178 * @see #ENABLED_STATE_SET 1179 * @see #FOCUSED_STATE_SET 1180 * @see #SELECTED_STATE_SET 1181 */ 1182 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1183 /** 1184 * Indicates the view is enabled, focused and its window has the focus. 1185 * 1186 * @see #ENABLED_STATE_SET 1187 * @see #FOCUSED_STATE_SET 1188 * @see #WINDOW_FOCUSED_STATE_SET 1189 */ 1190 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1191 /** 1192 * Indicates the view is enabled, selected and its window has the focus. 1193 * 1194 * @see #ENABLED_STATE_SET 1195 * @see #SELECTED_STATE_SET 1196 * @see #WINDOW_FOCUSED_STATE_SET 1197 */ 1198 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1199 /** 1200 * Indicates the view is focused, selected and its window has the focus. 1201 * 1202 * @see #FOCUSED_STATE_SET 1203 * @see #SELECTED_STATE_SET 1204 * @see #WINDOW_FOCUSED_STATE_SET 1205 */ 1206 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1207 /** 1208 * Indicates the view is enabled, focused, selected and its window 1209 * has the focus. 1210 * 1211 * @see #ENABLED_STATE_SET 1212 * @see #FOCUSED_STATE_SET 1213 * @see #SELECTED_STATE_SET 1214 * @see #WINDOW_FOCUSED_STATE_SET 1215 */ 1216 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1217 /** 1218 * Indicates the view is pressed and its window has the focus. 1219 * 1220 * @see #PRESSED_STATE_SET 1221 * @see #WINDOW_FOCUSED_STATE_SET 1222 */ 1223 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1224 /** 1225 * Indicates the view is pressed and selected. 1226 * 1227 * @see #PRESSED_STATE_SET 1228 * @see #SELECTED_STATE_SET 1229 */ 1230 protected static final int[] PRESSED_SELECTED_STATE_SET; 1231 /** 1232 * Indicates the view is pressed, selected and its window has the focus. 1233 * 1234 * @see #PRESSED_STATE_SET 1235 * @see #SELECTED_STATE_SET 1236 * @see #WINDOW_FOCUSED_STATE_SET 1237 */ 1238 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1239 /** 1240 * Indicates the view is pressed and focused. 1241 * 1242 * @see #PRESSED_STATE_SET 1243 * @see #FOCUSED_STATE_SET 1244 */ 1245 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1246 /** 1247 * Indicates the view is pressed, focused and its window has the focus. 1248 * 1249 * @see #PRESSED_STATE_SET 1250 * @see #FOCUSED_STATE_SET 1251 * @see #WINDOW_FOCUSED_STATE_SET 1252 */ 1253 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1254 /** 1255 * Indicates the view is pressed, focused and selected. 1256 * 1257 * @see #PRESSED_STATE_SET 1258 * @see #SELECTED_STATE_SET 1259 * @see #FOCUSED_STATE_SET 1260 */ 1261 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1262 /** 1263 * Indicates the view is pressed, focused, selected and its window has the focus. 1264 * 1265 * @see #PRESSED_STATE_SET 1266 * @see #FOCUSED_STATE_SET 1267 * @see #SELECTED_STATE_SET 1268 * @see #WINDOW_FOCUSED_STATE_SET 1269 */ 1270 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1271 /** 1272 * Indicates the view is pressed and enabled. 1273 * 1274 * @see #PRESSED_STATE_SET 1275 * @see #ENABLED_STATE_SET 1276 */ 1277 protected static final int[] PRESSED_ENABLED_STATE_SET; 1278 /** 1279 * Indicates the view is pressed, enabled and its window has the focus. 1280 * 1281 * @see #PRESSED_STATE_SET 1282 * @see #ENABLED_STATE_SET 1283 * @see #WINDOW_FOCUSED_STATE_SET 1284 */ 1285 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1286 /** 1287 * Indicates the view is pressed, enabled and selected. 1288 * 1289 * @see #PRESSED_STATE_SET 1290 * @see #ENABLED_STATE_SET 1291 * @see #SELECTED_STATE_SET 1292 */ 1293 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1294 /** 1295 * Indicates the view is pressed, enabled, selected and its window has the 1296 * focus. 1297 * 1298 * @see #PRESSED_STATE_SET 1299 * @see #ENABLED_STATE_SET 1300 * @see #SELECTED_STATE_SET 1301 * @see #WINDOW_FOCUSED_STATE_SET 1302 */ 1303 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1304 /** 1305 * Indicates the view is pressed, enabled and focused. 1306 * 1307 * @see #PRESSED_STATE_SET 1308 * @see #ENABLED_STATE_SET 1309 * @see #FOCUSED_STATE_SET 1310 */ 1311 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1312 /** 1313 * Indicates the view is pressed, enabled, focused and its window has the 1314 * focus. 1315 * 1316 * @see #PRESSED_STATE_SET 1317 * @see #ENABLED_STATE_SET 1318 * @see #FOCUSED_STATE_SET 1319 * @see #WINDOW_FOCUSED_STATE_SET 1320 */ 1321 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1322 /** 1323 * Indicates the view is pressed, enabled, focused and selected. 1324 * 1325 * @see #PRESSED_STATE_SET 1326 * @see #ENABLED_STATE_SET 1327 * @see #SELECTED_STATE_SET 1328 * @see #FOCUSED_STATE_SET 1329 */ 1330 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1331 /** 1332 * Indicates the view is pressed, enabled, focused, selected and its window 1333 * has the focus. 1334 * 1335 * @see #PRESSED_STATE_SET 1336 * @see #ENABLED_STATE_SET 1337 * @see #SELECTED_STATE_SET 1338 * @see #FOCUSED_STATE_SET 1339 * @see #WINDOW_FOCUSED_STATE_SET 1340 */ 1341 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1342 1343 /** 1344 * The order here is very important to {@link #getDrawableState()} 1345 */ 1346 private static final int[][] VIEW_STATE_SETS; 1347 1348 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1349 static final int VIEW_STATE_SELECTED = 1 << 1; 1350 static final int VIEW_STATE_FOCUSED = 1 << 2; 1351 static final int VIEW_STATE_ENABLED = 1 << 3; 1352 static final int VIEW_STATE_PRESSED = 1 << 4; 1353 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1354 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1355 static final int VIEW_STATE_HOVERED = 1 << 7; 1356 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1357 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1358 1359 static final int[] VIEW_STATE_IDS = new int[] { 1360 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1361 R.attr.state_selected, VIEW_STATE_SELECTED, 1362 R.attr.state_focused, VIEW_STATE_FOCUSED, 1363 R.attr.state_enabled, VIEW_STATE_ENABLED, 1364 R.attr.state_pressed, VIEW_STATE_PRESSED, 1365 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1366 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1367 R.attr.state_hovered, VIEW_STATE_HOVERED, 1368 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1369 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED, 1370 }; 1371 1372 static { 1373 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1374 throw new IllegalStateException( 1375 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1376 } 1377 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1378 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1379 int viewState = R.styleable.ViewDrawableStates[i]; 1380 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1381 if (VIEW_STATE_IDS[j] == viewState) { 1382 orderedIds[i * 2] = viewState; 1383 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1384 } 1385 } 1386 } 1387 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1388 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1389 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1390 int numBits = Integer.bitCount(i); 1391 int[] set = new int[numBits]; 1392 int pos = 0; 1393 for (int j = 0; j < orderedIds.length; j += 2) { 1394 if ((i & orderedIds[j+1]) != 0) { 1395 set[pos++] = orderedIds[j]; 1396 } 1397 } 1398 VIEW_STATE_SETS[i] = set; 1399 } 1400 1401 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1402 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1403 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1404 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1405 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1406 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1407 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1408 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1409 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1410 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1411 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1412 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1413 | VIEW_STATE_FOCUSED]; 1414 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1415 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1416 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1417 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1418 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1419 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1420 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1421 | VIEW_STATE_ENABLED]; 1422 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1423 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1424 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1425 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1426 | VIEW_STATE_ENABLED]; 1427 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1428 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1429 | VIEW_STATE_ENABLED]; 1430 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1431 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1432 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1433 1434 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1435 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1436 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1437 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1438 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1439 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1440 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1441 | VIEW_STATE_PRESSED]; 1442 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1443 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1444 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1445 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1446 | VIEW_STATE_PRESSED]; 1447 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1448 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1449 | VIEW_STATE_PRESSED]; 1450 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1451 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1452 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1453 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1454 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1455 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1456 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1457 | VIEW_STATE_PRESSED]; 1458 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1459 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1460 | VIEW_STATE_PRESSED]; 1461 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1462 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1463 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1464 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1465 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1466 | VIEW_STATE_PRESSED]; 1467 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1468 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1469 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1470 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1471 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1472 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1473 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1474 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1475 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1476 | VIEW_STATE_PRESSED]; 1477 } 1478 1479 /** 1480 * Accessibility event types that are dispatched for text population. 1481 */ 1482 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1483 AccessibilityEvent.TYPE_VIEW_CLICKED 1484 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1485 | AccessibilityEvent.TYPE_VIEW_SELECTED 1486 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1487 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1488 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1489 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1490 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED; 1491 1492 /** 1493 * Temporary Rect currently for use in setBackground(). This will probably 1494 * be extended in the future to hold our own class with more than just 1495 * a Rect. :) 1496 */ 1497 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1498 1499 /** 1500 * Map used to store views' tags. 1501 */ 1502 private SparseArray<Object> mKeyedTags; 1503 1504 /** 1505 * The next available accessiiblity id. 1506 */ 1507 private static int sNextAccessibilityViewId; 1508 1509 /** 1510 * The animation currently associated with this view. 1511 * @hide 1512 */ 1513 protected Animation mCurrentAnimation = null; 1514 1515 /** 1516 * Width as measured during measure pass. 1517 * {@hide} 1518 */ 1519 @ViewDebug.ExportedProperty(category = "measurement") 1520 int mMeasuredWidth; 1521 1522 /** 1523 * Height as measured during measure pass. 1524 * {@hide} 1525 */ 1526 @ViewDebug.ExportedProperty(category = "measurement") 1527 int mMeasuredHeight; 1528 1529 /** 1530 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1531 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1532 * its display list. This flag, used only when hw accelerated, allows us to clear the 1533 * flag while retaining this information until it's needed (at getDisplayList() time and 1534 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1535 * 1536 * {@hide} 1537 */ 1538 boolean mRecreateDisplayList = false; 1539 1540 /** 1541 * The view's identifier. 1542 * {@hide} 1543 * 1544 * @see #setId(int) 1545 * @see #getId() 1546 */ 1547 @ViewDebug.ExportedProperty(resolveId = true) 1548 int mID = NO_ID; 1549 1550 /** 1551 * The stable ID of this view for accessibility porposes. 1552 */ 1553 int mAccessibilityViewId = NO_ID; 1554 1555 /** 1556 * The view's tag. 1557 * {@hide} 1558 * 1559 * @see #setTag(Object) 1560 * @see #getTag() 1561 */ 1562 protected Object mTag; 1563 1564 // for mPrivateFlags: 1565 /** {@hide} */ 1566 static final int WANTS_FOCUS = 0x00000001; 1567 /** {@hide} */ 1568 static final int FOCUSED = 0x00000002; 1569 /** {@hide} */ 1570 static final int SELECTED = 0x00000004; 1571 /** {@hide} */ 1572 static final int IS_ROOT_NAMESPACE = 0x00000008; 1573 /** {@hide} */ 1574 static final int HAS_BOUNDS = 0x00000010; 1575 /** {@hide} */ 1576 static final int DRAWN = 0x00000020; 1577 /** 1578 * When this flag is set, this view is running an animation on behalf of its 1579 * children and should therefore not cancel invalidate requests, even if they 1580 * lie outside of this view's bounds. 1581 * 1582 * {@hide} 1583 */ 1584 static final int DRAW_ANIMATION = 0x00000040; 1585 /** {@hide} */ 1586 static final int SKIP_DRAW = 0x00000080; 1587 /** {@hide} */ 1588 static final int ONLY_DRAWS_BACKGROUND = 0x00000100; 1589 /** {@hide} */ 1590 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1591 /** {@hide} */ 1592 static final int DRAWABLE_STATE_DIRTY = 0x00000400; 1593 /** {@hide} */ 1594 static final int MEASURED_DIMENSION_SET = 0x00000800; 1595 /** {@hide} */ 1596 static final int FORCE_LAYOUT = 0x00001000; 1597 /** {@hide} */ 1598 static final int LAYOUT_REQUIRED = 0x00002000; 1599 1600 private static final int PRESSED = 0x00004000; 1601 1602 /** {@hide} */ 1603 static final int DRAWING_CACHE_VALID = 0x00008000; 1604 /** 1605 * Flag used to indicate that this view should be drawn once more (and only once 1606 * more) after its animation has completed. 1607 * {@hide} 1608 */ 1609 static final int ANIMATION_STARTED = 0x00010000; 1610 1611 private static final int SAVE_STATE_CALLED = 0x00020000; 1612 1613 /** 1614 * Indicates that the View returned true when onSetAlpha() was called and that 1615 * the alpha must be restored. 1616 * {@hide} 1617 */ 1618 static final int ALPHA_SET = 0x00040000; 1619 1620 /** 1621 * Set by {@link #setScrollContainer(boolean)}. 1622 */ 1623 static final int SCROLL_CONTAINER = 0x00080000; 1624 1625 /** 1626 * Set by {@link #setScrollContainer(boolean)}. 1627 */ 1628 static final int SCROLL_CONTAINER_ADDED = 0x00100000; 1629 1630 /** 1631 * View flag indicating whether this view was invalidated (fully or partially.) 1632 * 1633 * @hide 1634 */ 1635 static final int DIRTY = 0x00200000; 1636 1637 /** 1638 * View flag indicating whether this view was invalidated by an opaque 1639 * invalidate request. 1640 * 1641 * @hide 1642 */ 1643 static final int DIRTY_OPAQUE = 0x00400000; 1644 1645 /** 1646 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}. 1647 * 1648 * @hide 1649 */ 1650 static final int DIRTY_MASK = 0x00600000; 1651 1652 /** 1653 * Indicates whether the background is opaque. 1654 * 1655 * @hide 1656 */ 1657 static final int OPAQUE_BACKGROUND = 0x00800000; 1658 1659 /** 1660 * Indicates whether the scrollbars are opaque. 1661 * 1662 * @hide 1663 */ 1664 static final int OPAQUE_SCROLLBARS = 0x01000000; 1665 1666 /** 1667 * Indicates whether the view is opaque. 1668 * 1669 * @hide 1670 */ 1671 static final int OPAQUE_MASK = 0x01800000; 1672 1673 /** 1674 * Indicates a prepressed state; 1675 * the short time between ACTION_DOWN and recognizing 1676 * a 'real' press. Prepressed is used to recognize quick taps 1677 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1678 * 1679 * @hide 1680 */ 1681 private static final int PREPRESSED = 0x02000000; 1682 1683 /** 1684 * Indicates whether the view is temporarily detached. 1685 * 1686 * @hide 1687 */ 1688 static final int CANCEL_NEXT_UP_EVENT = 0x04000000; 1689 1690 /** 1691 * Indicates that we should awaken scroll bars once attached 1692 * 1693 * @hide 1694 */ 1695 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1696 1697 /** 1698 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1699 * @hide 1700 */ 1701 private static final int HOVERED = 0x10000000; 1702 1703 /** 1704 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1705 * for transform operations 1706 * 1707 * @hide 1708 */ 1709 private static final int PIVOT_EXPLICITLY_SET = 0x20000000; 1710 1711 /** {@hide} */ 1712 static final int ACTIVATED = 0x40000000; 1713 1714 /** 1715 * Indicates that this view was specifically invalidated, not just dirtied because some 1716 * child view was invalidated. The flag is used to determine when we need to recreate 1717 * a view's display list (as opposed to just returning a reference to its existing 1718 * display list). 1719 * 1720 * @hide 1721 */ 1722 static final int INVALIDATED = 0x80000000; 1723 1724 /* Masks for mPrivateFlags2 */ 1725 1726 /** 1727 * Indicates that this view has reported that it can accept the current drag's content. 1728 * Cleared when the drag operation concludes. 1729 * @hide 1730 */ 1731 static final int DRAG_CAN_ACCEPT = 0x00000001; 1732 1733 /** 1734 * Indicates that this view is currently directly under the drag location in a 1735 * drag-and-drop operation involving content that it can accept. Cleared when 1736 * the drag exits the view, or when the drag operation concludes. 1737 * @hide 1738 */ 1739 static final int DRAG_HOVERED = 0x00000002; 1740 1741 /** 1742 * Indicates whether the view layout direction has been resolved and drawn to the 1743 * right-to-left direction. 1744 * 1745 * @hide 1746 */ 1747 static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004; 1748 1749 /** 1750 * Indicates whether the view layout direction has been resolved. 1751 * 1752 * @hide 1753 */ 1754 static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008; 1755 1756 1757 /* End of masks for mPrivateFlags2 */ 1758 1759 static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED; 1760 1761 /** 1762 * Always allow a user to over-scroll this view, provided it is a 1763 * view that can scroll. 1764 * 1765 * @see #getOverScrollMode() 1766 * @see #setOverScrollMode(int) 1767 */ 1768 public static final int OVER_SCROLL_ALWAYS = 0; 1769 1770 /** 1771 * Allow a user to over-scroll this view only if the content is large 1772 * enough to meaningfully scroll, provided it is a view that can scroll. 1773 * 1774 * @see #getOverScrollMode() 1775 * @see #setOverScrollMode(int) 1776 */ 1777 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 1778 1779 /** 1780 * Never allow a user to over-scroll this view. 1781 * 1782 * @see #getOverScrollMode() 1783 * @see #setOverScrollMode(int) 1784 */ 1785 public static final int OVER_SCROLL_NEVER = 2; 1786 1787 /** 1788 * View has requested the system UI (status bar) to be visible (the default). 1789 * 1790 * @see #setSystemUiVisibility(int) 1791 */ 1792 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 1793 1794 /** 1795 * View has requested the system UI to enter an unobtrusive "low profile" mode. 1796 * 1797 * This is for use in games, book readers, video players, or any other "immersive" application 1798 * where the usual system chrome is deemed too distracting. 1799 * 1800 * In low profile mode, the status bar and/or navigation icons may dim. 1801 * 1802 * @see #setSystemUiVisibility(int) 1803 */ 1804 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 1805 1806 /** 1807 * View has requested that the system navigation be temporarily hidden. 1808 * 1809 * This is an even less obtrusive state than that called for by 1810 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 1811 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 1812 * those to disappear. This is useful (in conjunction with the 1813 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 1814 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 1815 * window flags) for displaying content using every last pixel on the display. 1816 * 1817 * There is a limitation: because navigation controls are so important, the least user 1818 * interaction will cause them to reappear immediately. 1819 * 1820 * @see #setSystemUiVisibility(int) 1821 */ 1822 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 1823 1824 /** 1825 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 1826 */ 1827 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 1828 1829 /** 1830 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 1831 */ 1832 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 1833 1834 /** 1835 * @hide 1836 * 1837 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1838 * out of the public fields to keep the undefined bits out of the developer's way. 1839 * 1840 * Flag to make the status bar not expandable. Unless you also 1841 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 1842 */ 1843 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 1844 1845 /** 1846 * @hide 1847 * 1848 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1849 * out of the public fields to keep the undefined bits out of the developer's way. 1850 * 1851 * Flag to hide notification icons and scrolling ticker text. 1852 */ 1853 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 1854 1855 /** 1856 * @hide 1857 * 1858 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1859 * out of the public fields to keep the undefined bits out of the developer's way. 1860 * 1861 * Flag to disable incoming notification alerts. This will not block 1862 * icons, but it will block sound, vibrating and other visual or aural notifications. 1863 */ 1864 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 1865 1866 /** 1867 * @hide 1868 * 1869 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1870 * out of the public fields to keep the undefined bits out of the developer's way. 1871 * 1872 * Flag to hide only the scrolling ticker. Note that 1873 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 1874 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 1875 */ 1876 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 1877 1878 /** 1879 * @hide 1880 * 1881 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1882 * out of the public fields to keep the undefined bits out of the developer's way. 1883 * 1884 * Flag to hide the center system info area. 1885 */ 1886 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 1887 1888 /** 1889 * @hide 1890 * 1891 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1892 * out of the public fields to keep the undefined bits out of the developer's way. 1893 * 1894 * Flag to hide only the home button. Don't use this 1895 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1896 */ 1897 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 1898 1899 /** 1900 * @hide 1901 * 1902 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1903 * out of the public fields to keep the undefined bits out of the developer's way. 1904 * 1905 * Flag to hide only the back button. Don't use this 1906 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1907 */ 1908 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 1909 1910 /** 1911 * @hide 1912 * 1913 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1914 * out of the public fields to keep the undefined bits out of the developer's way. 1915 * 1916 * Flag to hide only the clock. You might use this if your activity has 1917 * its own clock making the status bar's clock redundant. 1918 */ 1919 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 1920 1921 /** 1922 * @hide 1923 * 1924 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1925 * out of the public fields to keep the undefined bits out of the developer's way. 1926 * 1927 * Flag to hide only the recent apps button. Don't use this 1928 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1929 */ 1930 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 1931 1932 /** 1933 * @hide 1934 * 1935 * NOTE: This flag may only be used in subtreeSystemUiVisibility, etc. etc. 1936 * 1937 * This hides HOME and RECENT and is provided for compatibility with interim implementations. 1938 */ 1939 @Deprecated 1940 public static final int STATUS_BAR_DISABLE_NAVIGATION = 1941 STATUS_BAR_DISABLE_HOME | STATUS_BAR_DISABLE_RECENT; 1942 1943 /** 1944 * @hide 1945 */ 1946 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 1947 1948 /** 1949 * These are the system UI flags that can be cleared by events outside 1950 * of an application. Currently this is just the ability to tap on the 1951 * screen while hiding the navigation bar to have it return. 1952 * @hide 1953 */ 1954 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 1955 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION; 1956 1957 /** 1958 * Find views that render the specified text. 1959 * 1960 * @see #findViewsWithText(ArrayList, CharSequence, int) 1961 */ 1962 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 1963 1964 /** 1965 * Find find views that contain the specified content description. 1966 * 1967 * @see #findViewsWithText(ArrayList, CharSequence, int) 1968 */ 1969 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 1970 1971 /** 1972 * Controls the over-scroll mode for this view. 1973 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 1974 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 1975 * and {@link #OVER_SCROLL_NEVER}. 1976 */ 1977 private int mOverScrollMode; 1978 1979 /** 1980 * The parent this view is attached to. 1981 * {@hide} 1982 * 1983 * @see #getParent() 1984 */ 1985 protected ViewParent mParent; 1986 1987 /** 1988 * {@hide} 1989 */ 1990 AttachInfo mAttachInfo; 1991 1992 /** 1993 * {@hide} 1994 */ 1995 @ViewDebug.ExportedProperty(flagMapping = { 1996 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT, 1997 name = "FORCE_LAYOUT"), 1998 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED, 1999 name = "LAYOUT_REQUIRED"), 2000 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID, 2001 name = "DRAWING_CACHE_INVALID", outputIf = false), 2002 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true), 2003 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false), 2004 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2005 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY") 2006 }) 2007 int mPrivateFlags; 2008 int mPrivateFlags2; 2009 2010 /** 2011 * This view's request for the visibility of the status bar. 2012 * @hide 2013 */ 2014 @ViewDebug.ExportedProperty(flagMapping = { 2015 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2016 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2017 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2018 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2019 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2020 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2021 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2022 equals = SYSTEM_UI_FLAG_VISIBLE, 2023 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2024 }) 2025 int mSystemUiVisibility; 2026 2027 /** 2028 * Count of how many windows this view has been attached to. 2029 */ 2030 int mWindowAttachCount; 2031 2032 /** 2033 * The layout parameters associated with this view and used by the parent 2034 * {@link android.view.ViewGroup} to determine how this view should be 2035 * laid out. 2036 * {@hide} 2037 */ 2038 protected ViewGroup.LayoutParams mLayoutParams; 2039 2040 /** 2041 * The view flags hold various views states. 2042 * {@hide} 2043 */ 2044 @ViewDebug.ExportedProperty 2045 int mViewFlags; 2046 2047 static class TransformationInfo { 2048 /** 2049 * The transform matrix for the View. This transform is calculated internally 2050 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2051 * is used by default. Do *not* use this variable directly; instead call 2052 * getMatrix(), which will automatically recalculate the matrix if necessary 2053 * to get the correct matrix based on the latest rotation and scale properties. 2054 */ 2055 private final Matrix mMatrix = new Matrix(); 2056 2057 /** 2058 * The transform matrix for the View. This transform is calculated internally 2059 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2060 * is used by default. Do *not* use this variable directly; instead call 2061 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2062 * to get the correct matrix based on the latest rotation and scale properties. 2063 */ 2064 private Matrix mInverseMatrix; 2065 2066 /** 2067 * An internal variable that tracks whether we need to recalculate the 2068 * transform matrix, based on whether the rotation or scaleX/Y properties 2069 * have changed since the matrix was last calculated. 2070 */ 2071 boolean mMatrixDirty = false; 2072 2073 /** 2074 * An internal variable that tracks whether we need to recalculate the 2075 * transform matrix, based on whether the rotation or scaleX/Y properties 2076 * have changed since the matrix was last calculated. 2077 */ 2078 private boolean mInverseMatrixDirty = true; 2079 2080 /** 2081 * A variable that tracks whether we need to recalculate the 2082 * transform matrix, based on whether the rotation or scaleX/Y properties 2083 * have changed since the matrix was last calculated. This variable 2084 * is only valid after a call to updateMatrix() or to a function that 2085 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2086 */ 2087 private boolean mMatrixIsIdentity = true; 2088 2089 /** 2090 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2091 */ 2092 private Camera mCamera = null; 2093 2094 /** 2095 * This matrix is used when computing the matrix for 3D rotations. 2096 */ 2097 private Matrix matrix3D = null; 2098 2099 /** 2100 * These prev values are used to recalculate a centered pivot point when necessary. The 2101 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2102 * set), so thes values are only used then as well. 2103 */ 2104 private int mPrevWidth = -1; 2105 private int mPrevHeight = -1; 2106 2107 /** 2108 * The degrees rotation around the vertical axis through the pivot point. 2109 */ 2110 @ViewDebug.ExportedProperty 2111 float mRotationY = 0f; 2112 2113 /** 2114 * The degrees rotation around the horizontal axis through the pivot point. 2115 */ 2116 @ViewDebug.ExportedProperty 2117 float mRotationX = 0f; 2118 2119 /** 2120 * The degrees rotation around the pivot point. 2121 */ 2122 @ViewDebug.ExportedProperty 2123 float mRotation = 0f; 2124 2125 /** 2126 * The amount of translation of the object away from its left property (post-layout). 2127 */ 2128 @ViewDebug.ExportedProperty 2129 float mTranslationX = 0f; 2130 2131 /** 2132 * The amount of translation of the object away from its top property (post-layout). 2133 */ 2134 @ViewDebug.ExportedProperty 2135 float mTranslationY = 0f; 2136 2137 /** 2138 * The amount of scale in the x direction around the pivot point. A 2139 * value of 1 means no scaling is applied. 2140 */ 2141 @ViewDebug.ExportedProperty 2142 float mScaleX = 1f; 2143 2144 /** 2145 * The amount of scale in the y direction around the pivot point. A 2146 * value of 1 means no scaling is applied. 2147 */ 2148 @ViewDebug.ExportedProperty 2149 float mScaleY = 1f; 2150 2151 /** 2152 * The amount of scale in the x direction around the pivot point. A 2153 * value of 1 means no scaling is applied. 2154 */ 2155 @ViewDebug.ExportedProperty 2156 float mPivotX = 0f; 2157 2158 /** 2159 * The amount of scale in the y direction around the pivot point. A 2160 * value of 1 means no scaling is applied. 2161 */ 2162 @ViewDebug.ExportedProperty 2163 float mPivotY = 0f; 2164 2165 /** 2166 * The opacity of the View. This is a value from 0 to 1, where 0 means 2167 * completely transparent and 1 means completely opaque. 2168 */ 2169 @ViewDebug.ExportedProperty 2170 float mAlpha = 1f; 2171 } 2172 2173 TransformationInfo mTransformationInfo; 2174 2175 private boolean mLastIsOpaque; 2176 2177 /** 2178 * Convenience value to check for float values that are close enough to zero to be considered 2179 * zero. 2180 */ 2181 private static final float NONZERO_EPSILON = .001f; 2182 2183 /** 2184 * The distance in pixels from the left edge of this view's parent 2185 * to the left edge of this view. 2186 * {@hide} 2187 */ 2188 @ViewDebug.ExportedProperty(category = "layout") 2189 protected int mLeft; 2190 /** 2191 * The distance in pixels from the left edge of this view's parent 2192 * to the right edge of this view. 2193 * {@hide} 2194 */ 2195 @ViewDebug.ExportedProperty(category = "layout") 2196 protected int mRight; 2197 /** 2198 * The distance in pixels from the top edge of this view's parent 2199 * to the top edge of this view. 2200 * {@hide} 2201 */ 2202 @ViewDebug.ExportedProperty(category = "layout") 2203 protected int mTop; 2204 /** 2205 * The distance in pixels from the top edge of this view's parent 2206 * to the bottom edge of this view. 2207 * {@hide} 2208 */ 2209 @ViewDebug.ExportedProperty(category = "layout") 2210 protected int mBottom; 2211 2212 /** 2213 * The offset, in pixels, by which the content of this view is scrolled 2214 * horizontally. 2215 * {@hide} 2216 */ 2217 @ViewDebug.ExportedProperty(category = "scrolling") 2218 protected int mScrollX; 2219 /** 2220 * The offset, in pixels, by which the content of this view is scrolled 2221 * vertically. 2222 * {@hide} 2223 */ 2224 @ViewDebug.ExportedProperty(category = "scrolling") 2225 protected int mScrollY; 2226 2227 /** 2228 * The left padding in pixels, that is the distance in pixels between the 2229 * left edge of this view and the left edge of its content. 2230 * {@hide} 2231 */ 2232 @ViewDebug.ExportedProperty(category = "padding") 2233 protected int mPaddingLeft; 2234 /** 2235 * The right padding in pixels, that is the distance in pixels between the 2236 * right edge of this view and the right edge of its content. 2237 * {@hide} 2238 */ 2239 @ViewDebug.ExportedProperty(category = "padding") 2240 protected int mPaddingRight; 2241 /** 2242 * The top padding in pixels, that is the distance in pixels between the 2243 * top edge of this view and the top edge of its content. 2244 * {@hide} 2245 */ 2246 @ViewDebug.ExportedProperty(category = "padding") 2247 protected int mPaddingTop; 2248 /** 2249 * The bottom padding in pixels, that is the distance in pixels between the 2250 * bottom edge of this view and the bottom edge of its content. 2251 * {@hide} 2252 */ 2253 @ViewDebug.ExportedProperty(category = "padding") 2254 protected int mPaddingBottom; 2255 2256 /** 2257 * Briefly describes the view and is primarily used for accessibility support. 2258 */ 2259 private CharSequence mContentDescription; 2260 2261 /** 2262 * Cache the paddingRight set by the user to append to the scrollbar's size. 2263 * 2264 * @hide 2265 */ 2266 @ViewDebug.ExportedProperty(category = "padding") 2267 protected int mUserPaddingRight; 2268 2269 /** 2270 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2271 * 2272 * @hide 2273 */ 2274 @ViewDebug.ExportedProperty(category = "padding") 2275 protected int mUserPaddingBottom; 2276 2277 /** 2278 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2279 * 2280 * @hide 2281 */ 2282 @ViewDebug.ExportedProperty(category = "padding") 2283 protected int mUserPaddingLeft; 2284 2285 /** 2286 * Cache if the user padding is relative. 2287 * 2288 */ 2289 @ViewDebug.ExportedProperty(category = "padding") 2290 boolean mUserPaddingRelative; 2291 2292 /** 2293 * Cache the paddingStart set by the user to append to the scrollbar's size. 2294 * 2295 */ 2296 @ViewDebug.ExportedProperty(category = "padding") 2297 int mUserPaddingStart; 2298 2299 /** 2300 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2301 * 2302 */ 2303 @ViewDebug.ExportedProperty(category = "padding") 2304 int mUserPaddingEnd; 2305 2306 /** 2307 * @hide 2308 */ 2309 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2310 /** 2311 * @hide 2312 */ 2313 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2314 2315 private Drawable mBGDrawable; 2316 2317 private int mBackgroundResource; 2318 private boolean mBackgroundSizeChanged; 2319 2320 /** 2321 * Listener used to dispatch focus change events. 2322 * This field should be made private, so it is hidden from the SDK. 2323 * {@hide} 2324 */ 2325 protected OnFocusChangeListener mOnFocusChangeListener; 2326 2327 /** 2328 * Listeners for layout change events. 2329 */ 2330 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2331 2332 /** 2333 * Listeners for attach events. 2334 */ 2335 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2336 2337 /** 2338 * Listener used to dispatch click events. 2339 * This field should be made private, so it is hidden from the SDK. 2340 * {@hide} 2341 */ 2342 protected OnClickListener mOnClickListener; 2343 2344 /** 2345 * Listener used to dispatch long click events. 2346 * This field should be made private, so it is hidden from the SDK. 2347 * {@hide} 2348 */ 2349 protected OnLongClickListener mOnLongClickListener; 2350 2351 /** 2352 * Listener used to build the context menu. 2353 * This field should be made private, so it is hidden from the SDK. 2354 * {@hide} 2355 */ 2356 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2357 2358 private OnKeyListener mOnKeyListener; 2359 2360 private OnTouchListener mOnTouchListener; 2361 2362 private OnHoverListener mOnHoverListener; 2363 2364 private OnGenericMotionListener mOnGenericMotionListener; 2365 2366 private OnDragListener mOnDragListener; 2367 2368 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2369 2370 /** 2371 * The application environment this view lives in. 2372 * This field should be made private, so it is hidden from the SDK. 2373 * {@hide} 2374 */ 2375 protected Context mContext; 2376 2377 private final Resources mResources; 2378 2379 private ScrollabilityCache mScrollCache; 2380 2381 private int[] mDrawableState = null; 2382 2383 /** 2384 * Set to true when drawing cache is enabled and cannot be created. 2385 * 2386 * @hide 2387 */ 2388 public boolean mCachingFailed; 2389 2390 private Bitmap mDrawingCache; 2391 private Bitmap mUnscaledDrawingCache; 2392 private HardwareLayer mHardwareLayer; 2393 DisplayList mDisplayList; 2394 2395 /** 2396 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2397 * the user may specify which view to go to next. 2398 */ 2399 private int mNextFocusLeftId = View.NO_ID; 2400 2401 /** 2402 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2403 * the user may specify which view to go to next. 2404 */ 2405 private int mNextFocusRightId = View.NO_ID; 2406 2407 /** 2408 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2409 * the user may specify which view to go to next. 2410 */ 2411 private int mNextFocusUpId = View.NO_ID; 2412 2413 /** 2414 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2415 * the user may specify which view to go to next. 2416 */ 2417 private int mNextFocusDownId = View.NO_ID; 2418 2419 /** 2420 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 2421 * the user may specify which view to go to next. 2422 */ 2423 int mNextFocusForwardId = View.NO_ID; 2424 2425 private CheckForLongPress mPendingCheckForLongPress; 2426 private CheckForTap mPendingCheckForTap = null; 2427 private PerformClick mPerformClick; 2428 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 2429 2430 private UnsetPressedState mUnsetPressedState; 2431 2432 /** 2433 * Whether the long press's action has been invoked. The tap's action is invoked on the 2434 * up event while a long press is invoked as soon as the long press duration is reached, so 2435 * a long press could be performed before the tap is checked, in which case the tap's action 2436 * should not be invoked. 2437 */ 2438 private boolean mHasPerformedLongPress; 2439 2440 /** 2441 * The minimum height of the view. We'll try our best to have the height 2442 * of this view to at least this amount. 2443 */ 2444 @ViewDebug.ExportedProperty(category = "measurement") 2445 private int mMinHeight; 2446 2447 /** 2448 * The minimum width of the view. We'll try our best to have the width 2449 * of this view to at least this amount. 2450 */ 2451 @ViewDebug.ExportedProperty(category = "measurement") 2452 private int mMinWidth; 2453 2454 /** 2455 * The delegate to handle touch events that are physically in this view 2456 * but should be handled by another view. 2457 */ 2458 private TouchDelegate mTouchDelegate = null; 2459 2460 /** 2461 * Solid color to use as a background when creating the drawing cache. Enables 2462 * the cache to use 16 bit bitmaps instead of 32 bit. 2463 */ 2464 private int mDrawingCacheBackgroundColor = 0; 2465 2466 /** 2467 * Special tree observer used when mAttachInfo is null. 2468 */ 2469 private ViewTreeObserver mFloatingTreeObserver; 2470 2471 /** 2472 * Cache the touch slop from the context that created the view. 2473 */ 2474 private int mTouchSlop; 2475 2476 /** 2477 * Object that handles automatic animation of view properties. 2478 */ 2479 private ViewPropertyAnimator mAnimator = null; 2480 2481 /** 2482 * Flag indicating that a drag can cross window boundaries. When 2483 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 2484 * with this flag set, all visible applications will be able to participate 2485 * in the drag operation and receive the dragged content. 2486 * 2487 * @hide 2488 */ 2489 public static final int DRAG_FLAG_GLOBAL = 1; 2490 2491 /** 2492 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 2493 */ 2494 private float mVerticalScrollFactor; 2495 2496 /** 2497 * Position of the vertical scroll bar. 2498 */ 2499 private int mVerticalScrollbarPosition; 2500 2501 /** 2502 * Position the scroll bar at the default position as determined by the system. 2503 */ 2504 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 2505 2506 /** 2507 * Position the scroll bar along the left edge. 2508 */ 2509 public static final int SCROLLBAR_POSITION_LEFT = 1; 2510 2511 /** 2512 * Position the scroll bar along the right edge. 2513 */ 2514 public static final int SCROLLBAR_POSITION_RIGHT = 2; 2515 2516 /** 2517 * Indicates that the view does not have a layer. 2518 * 2519 * @see #getLayerType() 2520 * @see #setLayerType(int, android.graphics.Paint) 2521 * @see #LAYER_TYPE_SOFTWARE 2522 * @see #LAYER_TYPE_HARDWARE 2523 */ 2524 public static final int LAYER_TYPE_NONE = 0; 2525 2526 /** 2527 * <p>Indicates that the view has a software layer. A software layer is backed 2528 * by a bitmap and causes the view to be rendered using Android's software 2529 * rendering pipeline, even if hardware acceleration is enabled.</p> 2530 * 2531 * <p>Software layers have various usages:</p> 2532 * <p>When the application is not using hardware acceleration, a software layer 2533 * is useful to apply a specific color filter and/or blending mode and/or 2534 * translucency to a view and all its children.</p> 2535 * <p>When the application is using hardware acceleration, a software layer 2536 * is useful to render drawing primitives not supported by the hardware 2537 * accelerated pipeline. It can also be used to cache a complex view tree 2538 * into a texture and reduce the complexity of drawing operations. For instance, 2539 * when animating a complex view tree with a translation, a software layer can 2540 * be used to render the view tree only once.</p> 2541 * <p>Software layers should be avoided when the affected view tree updates 2542 * often. Every update will require to re-render the software layer, which can 2543 * potentially be slow (particularly when hardware acceleration is turned on 2544 * since the layer will have to be uploaded into a hardware texture after every 2545 * update.)</p> 2546 * 2547 * @see #getLayerType() 2548 * @see #setLayerType(int, android.graphics.Paint) 2549 * @see #LAYER_TYPE_NONE 2550 * @see #LAYER_TYPE_HARDWARE 2551 */ 2552 public static final int LAYER_TYPE_SOFTWARE = 1; 2553 2554 /** 2555 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 2556 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 2557 * OpenGL hardware) and causes the view to be rendered using Android's hardware 2558 * rendering pipeline, but only if hardware acceleration is turned on for the 2559 * view hierarchy. When hardware acceleration is turned off, hardware layers 2560 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 2561 * 2562 * <p>A hardware layer is useful to apply a specific color filter and/or 2563 * blending mode and/or translucency to a view and all its children.</p> 2564 * <p>A hardware layer can be used to cache a complex view tree into a 2565 * texture and reduce the complexity of drawing operations. For instance, 2566 * when animating a complex view tree with a translation, a hardware layer can 2567 * be used to render the view tree only once.</p> 2568 * <p>A hardware layer can also be used to increase the rendering quality when 2569 * rotation transformations are applied on a view. It can also be used to 2570 * prevent potential clipping issues when applying 3D transforms on a view.</p> 2571 * 2572 * @see #getLayerType() 2573 * @see #setLayerType(int, android.graphics.Paint) 2574 * @see #LAYER_TYPE_NONE 2575 * @see #LAYER_TYPE_SOFTWARE 2576 */ 2577 public static final int LAYER_TYPE_HARDWARE = 2; 2578 2579 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 2580 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 2581 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 2582 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 2583 }) 2584 int mLayerType = LAYER_TYPE_NONE; 2585 Paint mLayerPaint; 2586 Rect mLocalDirtyRect; 2587 2588 /** 2589 * Set to true when the view is sending hover accessibility events because it 2590 * is the innermost hovered view. 2591 */ 2592 private boolean mSendingHoverAccessibilityEvents; 2593 2594 /** 2595 * Delegate for injecting accessiblity functionality. 2596 */ 2597 AccessibilityDelegate mAccessibilityDelegate; 2598 2599 /** 2600 * Text direction is inherited thru {@link ViewGroup} 2601 * @hide 2602 */ 2603 public static final int TEXT_DIRECTION_INHERIT = 0; 2604 2605 /** 2606 * Text direction is using "first strong algorithm". The first strong directional character 2607 * determines the paragraph direction. If there is no strong directional character, the 2608 * paragraph direction is the view's resolved ayout direction. 2609 * 2610 * @hide 2611 */ 2612 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 2613 2614 /** 2615 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 2616 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 2617 * If there are neither, the paragraph direction is the view's resolved layout direction. 2618 * 2619 * @hide 2620 */ 2621 public static final int TEXT_DIRECTION_ANY_RTL = 2; 2622 2623 /** 2624 * Text direction is forced to LTR. 2625 * 2626 * @hide 2627 */ 2628 public static final int TEXT_DIRECTION_LTR = 3; 2629 2630 /** 2631 * Text direction is forced to RTL. 2632 * 2633 * @hide 2634 */ 2635 public static final int TEXT_DIRECTION_RTL = 4; 2636 2637 /** 2638 * Default text direction is inherited 2639 * 2640 * @hide 2641 */ 2642 protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT; 2643 2644 /** 2645 * The text direction that has been defined by {@link #setTextDirection(int)}. 2646 * 2647 * {@hide} 2648 */ 2649 @ViewDebug.ExportedProperty(category = "text", mapping = { 2650 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 2651 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 2652 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 2653 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 2654 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL") 2655 }) 2656 private int mTextDirection = DEFAULT_TEXT_DIRECTION; 2657 2658 /** 2659 * The resolved text direction. This needs resolution if the value is 2660 * TEXT_DIRECTION_INHERIT. The resolution matches mTextDirection if that is 2661 * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent 2662 * chain of the view. 2663 * 2664 * {@hide} 2665 */ 2666 @ViewDebug.ExportedProperty(category = "text", mapping = { 2667 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 2668 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 2669 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 2670 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 2671 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL") 2672 }) 2673 private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT; 2674 2675 /** 2676 * Consistency verifier for debugging purposes. 2677 * @hide 2678 */ 2679 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 2680 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 2681 new InputEventConsistencyVerifier(this, 0) : null; 2682 2683 /** 2684 * Simple constructor to use when creating a view from code. 2685 * 2686 * @param context The Context the view is running in, through which it can 2687 * access the current theme, resources, etc. 2688 */ 2689 public View(Context context) { 2690 mContext = context; 2691 mResources = context != null ? context.getResources() : null; 2692 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT; 2693 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 2694 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 2695 mUserPaddingStart = -1; 2696 mUserPaddingEnd = -1; 2697 mUserPaddingRelative = false; 2698 } 2699 2700 /** 2701 * Constructor that is called when inflating a view from XML. This is called 2702 * when a view is being constructed from an XML file, supplying attributes 2703 * that were specified in the XML file. This version uses a default style of 2704 * 0, so the only attribute values applied are those in the Context's Theme 2705 * and the given AttributeSet. 2706 * 2707 * <p> 2708 * The method onFinishInflate() will be called after all children have been 2709 * added. 2710 * 2711 * @param context The Context the view is running in, through which it can 2712 * access the current theme, resources, etc. 2713 * @param attrs The attributes of the XML tag that is inflating the view. 2714 * @see #View(Context, AttributeSet, int) 2715 */ 2716 public View(Context context, AttributeSet attrs) { 2717 this(context, attrs, 0); 2718 } 2719 2720 /** 2721 * Perform inflation from XML and apply a class-specific base style. This 2722 * constructor of View allows subclasses to use their own base style when 2723 * they are inflating. For example, a Button class's constructor would call 2724 * this version of the super class constructor and supply 2725 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 2726 * the theme's button style to modify all of the base view attributes (in 2727 * particular its background) as well as the Button class's attributes. 2728 * 2729 * @param context The Context the view is running in, through which it can 2730 * access the current theme, resources, etc. 2731 * @param attrs The attributes of the XML tag that is inflating the view. 2732 * @param defStyle The default style to apply to this view. If 0, no style 2733 * will be applied (beyond what is included in the theme). This may 2734 * either be an attribute resource, whose value will be retrieved 2735 * from the current theme, or an explicit style resource. 2736 * @see #View(Context, AttributeSet) 2737 */ 2738 public View(Context context, AttributeSet attrs, int defStyle) { 2739 this(context); 2740 2741 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 2742 defStyle, 0); 2743 2744 Drawable background = null; 2745 2746 int leftPadding = -1; 2747 int topPadding = -1; 2748 int rightPadding = -1; 2749 int bottomPadding = -1; 2750 int startPadding = -1; 2751 int endPadding = -1; 2752 2753 int padding = -1; 2754 2755 int viewFlagValues = 0; 2756 int viewFlagMasks = 0; 2757 2758 boolean setScrollContainer = false; 2759 2760 int x = 0; 2761 int y = 0; 2762 2763 float tx = 0; 2764 float ty = 0; 2765 float rotation = 0; 2766 float rotationX = 0; 2767 float rotationY = 0; 2768 float sx = 1f; 2769 float sy = 1f; 2770 boolean transformSet = false; 2771 2772 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 2773 2774 int overScrollMode = mOverScrollMode; 2775 final int N = a.getIndexCount(); 2776 for (int i = 0; i < N; i++) { 2777 int attr = a.getIndex(i); 2778 switch (attr) { 2779 case com.android.internal.R.styleable.View_background: 2780 background = a.getDrawable(attr); 2781 break; 2782 case com.android.internal.R.styleable.View_padding: 2783 padding = a.getDimensionPixelSize(attr, -1); 2784 break; 2785 case com.android.internal.R.styleable.View_paddingLeft: 2786 leftPadding = a.getDimensionPixelSize(attr, -1); 2787 break; 2788 case com.android.internal.R.styleable.View_paddingTop: 2789 topPadding = a.getDimensionPixelSize(attr, -1); 2790 break; 2791 case com.android.internal.R.styleable.View_paddingRight: 2792 rightPadding = a.getDimensionPixelSize(attr, -1); 2793 break; 2794 case com.android.internal.R.styleable.View_paddingBottom: 2795 bottomPadding = a.getDimensionPixelSize(attr, -1); 2796 break; 2797 case com.android.internal.R.styleable.View_paddingStart: 2798 startPadding = a.getDimensionPixelSize(attr, -1); 2799 break; 2800 case com.android.internal.R.styleable.View_paddingEnd: 2801 endPadding = a.getDimensionPixelSize(attr, -1); 2802 break; 2803 case com.android.internal.R.styleable.View_scrollX: 2804 x = a.getDimensionPixelOffset(attr, 0); 2805 break; 2806 case com.android.internal.R.styleable.View_scrollY: 2807 y = a.getDimensionPixelOffset(attr, 0); 2808 break; 2809 case com.android.internal.R.styleable.View_alpha: 2810 setAlpha(a.getFloat(attr, 1f)); 2811 break; 2812 case com.android.internal.R.styleable.View_transformPivotX: 2813 setPivotX(a.getDimensionPixelOffset(attr, 0)); 2814 break; 2815 case com.android.internal.R.styleable.View_transformPivotY: 2816 setPivotY(a.getDimensionPixelOffset(attr, 0)); 2817 break; 2818 case com.android.internal.R.styleable.View_translationX: 2819 tx = a.getDimensionPixelOffset(attr, 0); 2820 transformSet = true; 2821 break; 2822 case com.android.internal.R.styleable.View_translationY: 2823 ty = a.getDimensionPixelOffset(attr, 0); 2824 transformSet = true; 2825 break; 2826 case com.android.internal.R.styleable.View_rotation: 2827 rotation = a.getFloat(attr, 0); 2828 transformSet = true; 2829 break; 2830 case com.android.internal.R.styleable.View_rotationX: 2831 rotationX = a.getFloat(attr, 0); 2832 transformSet = true; 2833 break; 2834 case com.android.internal.R.styleable.View_rotationY: 2835 rotationY = a.getFloat(attr, 0); 2836 transformSet = true; 2837 break; 2838 case com.android.internal.R.styleable.View_scaleX: 2839 sx = a.getFloat(attr, 1f); 2840 transformSet = true; 2841 break; 2842 case com.android.internal.R.styleable.View_scaleY: 2843 sy = a.getFloat(attr, 1f); 2844 transformSet = true; 2845 break; 2846 case com.android.internal.R.styleable.View_id: 2847 mID = a.getResourceId(attr, NO_ID); 2848 break; 2849 case com.android.internal.R.styleable.View_tag: 2850 mTag = a.getText(attr); 2851 break; 2852 case com.android.internal.R.styleable.View_fitsSystemWindows: 2853 if (a.getBoolean(attr, false)) { 2854 viewFlagValues |= FITS_SYSTEM_WINDOWS; 2855 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 2856 } 2857 break; 2858 case com.android.internal.R.styleable.View_focusable: 2859 if (a.getBoolean(attr, false)) { 2860 viewFlagValues |= FOCUSABLE; 2861 viewFlagMasks |= FOCUSABLE_MASK; 2862 } 2863 break; 2864 case com.android.internal.R.styleable.View_focusableInTouchMode: 2865 if (a.getBoolean(attr, false)) { 2866 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 2867 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 2868 } 2869 break; 2870 case com.android.internal.R.styleable.View_clickable: 2871 if (a.getBoolean(attr, false)) { 2872 viewFlagValues |= CLICKABLE; 2873 viewFlagMasks |= CLICKABLE; 2874 } 2875 break; 2876 case com.android.internal.R.styleable.View_longClickable: 2877 if (a.getBoolean(attr, false)) { 2878 viewFlagValues |= LONG_CLICKABLE; 2879 viewFlagMasks |= LONG_CLICKABLE; 2880 } 2881 break; 2882 case com.android.internal.R.styleable.View_saveEnabled: 2883 if (!a.getBoolean(attr, true)) { 2884 viewFlagValues |= SAVE_DISABLED; 2885 viewFlagMasks |= SAVE_DISABLED_MASK; 2886 } 2887 break; 2888 case com.android.internal.R.styleable.View_duplicateParentState: 2889 if (a.getBoolean(attr, false)) { 2890 viewFlagValues |= DUPLICATE_PARENT_STATE; 2891 viewFlagMasks |= DUPLICATE_PARENT_STATE; 2892 } 2893 break; 2894 case com.android.internal.R.styleable.View_visibility: 2895 final int visibility = a.getInt(attr, 0); 2896 if (visibility != 0) { 2897 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 2898 viewFlagMasks |= VISIBILITY_MASK; 2899 } 2900 break; 2901 case com.android.internal.R.styleable.View_layoutDirection: 2902 // Clear any HORIZONTAL_DIRECTION flag already set 2903 viewFlagValues &= ~LAYOUT_DIRECTION_MASK; 2904 // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute 2905 final int layoutDirection = a.getInt(attr, -1); 2906 if (layoutDirection != -1) { 2907 viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection]; 2908 } else { 2909 // Set to default (LAYOUT_DIRECTION_INHERIT) 2910 viewFlagValues |= LAYOUT_DIRECTION_DEFAULT; 2911 } 2912 viewFlagMasks |= LAYOUT_DIRECTION_MASK; 2913 break; 2914 case com.android.internal.R.styleable.View_drawingCacheQuality: 2915 final int cacheQuality = a.getInt(attr, 0); 2916 if (cacheQuality != 0) { 2917 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 2918 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 2919 } 2920 break; 2921 case com.android.internal.R.styleable.View_contentDescription: 2922 mContentDescription = a.getString(attr); 2923 break; 2924 case com.android.internal.R.styleable.View_soundEffectsEnabled: 2925 if (!a.getBoolean(attr, true)) { 2926 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 2927 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 2928 } 2929 break; 2930 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 2931 if (!a.getBoolean(attr, true)) { 2932 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 2933 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 2934 } 2935 break; 2936 case R.styleable.View_scrollbars: 2937 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 2938 if (scrollbars != SCROLLBARS_NONE) { 2939 viewFlagValues |= scrollbars; 2940 viewFlagMasks |= SCROLLBARS_MASK; 2941 initializeScrollbars(a); 2942 } 2943 break; 2944 //noinspection deprecation 2945 case R.styleable.View_fadingEdge: 2946 if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) { 2947 // Ignore the attribute starting with ICS 2948 break; 2949 } 2950 // With builds < ICS, fall through and apply fading edges 2951 case R.styleable.View_requiresFadingEdge: 2952 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 2953 if (fadingEdge != FADING_EDGE_NONE) { 2954 viewFlagValues |= fadingEdge; 2955 viewFlagMasks |= FADING_EDGE_MASK; 2956 initializeFadingEdge(a); 2957 } 2958 break; 2959 case R.styleable.View_scrollbarStyle: 2960 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 2961 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 2962 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 2963 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 2964 } 2965 break; 2966 case R.styleable.View_isScrollContainer: 2967 setScrollContainer = true; 2968 if (a.getBoolean(attr, false)) { 2969 setScrollContainer(true); 2970 } 2971 break; 2972 case com.android.internal.R.styleable.View_keepScreenOn: 2973 if (a.getBoolean(attr, false)) { 2974 viewFlagValues |= KEEP_SCREEN_ON; 2975 viewFlagMasks |= KEEP_SCREEN_ON; 2976 } 2977 break; 2978 case R.styleable.View_filterTouchesWhenObscured: 2979 if (a.getBoolean(attr, false)) { 2980 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 2981 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 2982 } 2983 break; 2984 case R.styleable.View_nextFocusLeft: 2985 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 2986 break; 2987 case R.styleable.View_nextFocusRight: 2988 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 2989 break; 2990 case R.styleable.View_nextFocusUp: 2991 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 2992 break; 2993 case R.styleable.View_nextFocusDown: 2994 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 2995 break; 2996 case R.styleable.View_nextFocusForward: 2997 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 2998 break; 2999 case R.styleable.View_minWidth: 3000 mMinWidth = a.getDimensionPixelSize(attr, 0); 3001 break; 3002 case R.styleable.View_minHeight: 3003 mMinHeight = a.getDimensionPixelSize(attr, 0); 3004 break; 3005 case R.styleable.View_onClick: 3006 if (context.isRestricted()) { 3007 throw new IllegalStateException("The android:onClick attribute cannot " 3008 + "be used within a restricted context"); 3009 } 3010 3011 final String handlerName = a.getString(attr); 3012 if (handlerName != null) { 3013 setOnClickListener(new OnClickListener() { 3014 private Method mHandler; 3015 3016 public void onClick(View v) { 3017 if (mHandler == null) { 3018 try { 3019 mHandler = getContext().getClass().getMethod(handlerName, 3020 View.class); 3021 } catch (NoSuchMethodException e) { 3022 int id = getId(); 3023 String idText = id == NO_ID ? "" : " with id '" 3024 + getContext().getResources().getResourceEntryName( 3025 id) + "'"; 3026 throw new IllegalStateException("Could not find a method " + 3027 handlerName + "(View) in the activity " 3028 + getContext().getClass() + " for onClick handler" 3029 + " on view " + View.this.getClass() + idText, e); 3030 } 3031 } 3032 3033 try { 3034 mHandler.invoke(getContext(), View.this); 3035 } catch (IllegalAccessException e) { 3036 throw new IllegalStateException("Could not execute non " 3037 + "public method of the activity", e); 3038 } catch (InvocationTargetException e) { 3039 throw new IllegalStateException("Could not execute " 3040 + "method of the activity", e); 3041 } 3042 } 3043 }); 3044 } 3045 break; 3046 case R.styleable.View_overScrollMode: 3047 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3048 break; 3049 case R.styleable.View_verticalScrollbarPosition: 3050 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3051 break; 3052 case R.styleable.View_layerType: 3053 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3054 break; 3055 case R.styleable.View_textDirection: 3056 mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION); 3057 break; 3058 } 3059 } 3060 3061 a.recycle(); 3062 3063 setOverScrollMode(overScrollMode); 3064 3065 if (background != null) { 3066 setBackgroundDrawable(background); 3067 } 3068 3069 mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0); 3070 3071 // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved 3072 // layout direction). Those cached values will be used later during padding resolution. 3073 mUserPaddingStart = startPadding; 3074 mUserPaddingEnd = endPadding; 3075 3076 if (padding >= 0) { 3077 leftPadding = padding; 3078 topPadding = padding; 3079 rightPadding = padding; 3080 bottomPadding = padding; 3081 } 3082 3083 // If the user specified the padding (either with android:padding or 3084 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 3085 // use the default padding or the padding from the background drawable 3086 // (stored at this point in mPadding*) 3087 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft, 3088 topPadding >= 0 ? topPadding : mPaddingTop, 3089 rightPadding >= 0 ? rightPadding : mPaddingRight, 3090 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3091 3092 if (viewFlagMasks != 0) { 3093 setFlags(viewFlagValues, viewFlagMasks); 3094 } 3095 3096 // Needs to be called after mViewFlags is set 3097 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3098 recomputePadding(); 3099 } 3100 3101 if (x != 0 || y != 0) { 3102 scrollTo(x, y); 3103 } 3104 3105 if (transformSet) { 3106 setTranslationX(tx); 3107 setTranslationY(ty); 3108 setRotation(rotation); 3109 setRotationX(rotationX); 3110 setRotationY(rotationY); 3111 setScaleX(sx); 3112 setScaleY(sy); 3113 } 3114 3115 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3116 setScrollContainer(true); 3117 } 3118 3119 computeOpaqueFlags(); 3120 } 3121 3122 /** 3123 * Non-public constructor for use in testing 3124 */ 3125 View() { 3126 mResources = null; 3127 } 3128 3129 /** 3130 * <p> 3131 * Initializes the fading edges from a given set of styled attributes. This 3132 * method should be called by subclasses that need fading edges and when an 3133 * instance of these subclasses is created programmatically rather than 3134 * being inflated from XML. This method is automatically called when the XML 3135 * is inflated. 3136 * </p> 3137 * 3138 * @param a the styled attributes set to initialize the fading edges from 3139 */ 3140 protected void initializeFadingEdge(TypedArray a) { 3141 initScrollCache(); 3142 3143 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3144 R.styleable.View_fadingEdgeLength, 3145 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3146 } 3147 3148 /** 3149 * Returns the size of the vertical faded edges used to indicate that more 3150 * content in this view is visible. 3151 * 3152 * @return The size in pixels of the vertical faded edge or 0 if vertical 3153 * faded edges are not enabled for this view. 3154 * @attr ref android.R.styleable#View_fadingEdgeLength 3155 */ 3156 public int getVerticalFadingEdgeLength() { 3157 if (isVerticalFadingEdgeEnabled()) { 3158 ScrollabilityCache cache = mScrollCache; 3159 if (cache != null) { 3160 return cache.fadingEdgeLength; 3161 } 3162 } 3163 return 0; 3164 } 3165 3166 /** 3167 * Set the size of the faded edge used to indicate that more content in this 3168 * view is available. Will not change whether the fading edge is enabled; use 3169 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3170 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3171 * for the vertical or horizontal fading edges. 3172 * 3173 * @param length The size in pixels of the faded edge used to indicate that more 3174 * content in this view is visible. 3175 */ 3176 public void setFadingEdgeLength(int length) { 3177 initScrollCache(); 3178 mScrollCache.fadingEdgeLength = length; 3179 } 3180 3181 /** 3182 * Returns the size of the horizontal faded edges used to indicate that more 3183 * content in this view is visible. 3184 * 3185 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3186 * faded edges are not enabled for this view. 3187 * @attr ref android.R.styleable#View_fadingEdgeLength 3188 */ 3189 public int getHorizontalFadingEdgeLength() { 3190 if (isHorizontalFadingEdgeEnabled()) { 3191 ScrollabilityCache cache = mScrollCache; 3192 if (cache != null) { 3193 return cache.fadingEdgeLength; 3194 } 3195 } 3196 return 0; 3197 } 3198 3199 /** 3200 * Returns the width of the vertical scrollbar. 3201 * 3202 * @return The width in pixels of the vertical scrollbar or 0 if there 3203 * is no vertical scrollbar. 3204 */ 3205 public int getVerticalScrollbarWidth() { 3206 ScrollabilityCache cache = mScrollCache; 3207 if (cache != null) { 3208 ScrollBarDrawable scrollBar = cache.scrollBar; 3209 if (scrollBar != null) { 3210 int size = scrollBar.getSize(true); 3211 if (size <= 0) { 3212 size = cache.scrollBarSize; 3213 } 3214 return size; 3215 } 3216 return 0; 3217 } 3218 return 0; 3219 } 3220 3221 /** 3222 * Returns the height of the horizontal scrollbar. 3223 * 3224 * @return The height in pixels of the horizontal scrollbar or 0 if 3225 * there is no horizontal scrollbar. 3226 */ 3227 protected int getHorizontalScrollbarHeight() { 3228 ScrollabilityCache cache = mScrollCache; 3229 if (cache != null) { 3230 ScrollBarDrawable scrollBar = cache.scrollBar; 3231 if (scrollBar != null) { 3232 int size = scrollBar.getSize(false); 3233 if (size <= 0) { 3234 size = cache.scrollBarSize; 3235 } 3236 return size; 3237 } 3238 return 0; 3239 } 3240 return 0; 3241 } 3242 3243 /** 3244 * <p> 3245 * Initializes the scrollbars from a given set of styled attributes. This 3246 * method should be called by subclasses that need scrollbars and when an 3247 * instance of these subclasses is created programmatically rather than 3248 * being inflated from XML. This method is automatically called when the XML 3249 * is inflated. 3250 * </p> 3251 * 3252 * @param a the styled attributes set to initialize the scrollbars from 3253 */ 3254 protected void initializeScrollbars(TypedArray a) { 3255 initScrollCache(); 3256 3257 final ScrollabilityCache scrollabilityCache = mScrollCache; 3258 3259 if (scrollabilityCache.scrollBar == null) { 3260 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 3261 } 3262 3263 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 3264 3265 if (!fadeScrollbars) { 3266 scrollabilityCache.state = ScrollabilityCache.ON; 3267 } 3268 scrollabilityCache.fadeScrollBars = fadeScrollbars; 3269 3270 3271 scrollabilityCache.scrollBarFadeDuration = a.getInt( 3272 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 3273 .getScrollBarFadeDuration()); 3274 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 3275 R.styleable.View_scrollbarDefaultDelayBeforeFade, 3276 ViewConfiguration.getScrollDefaultDelay()); 3277 3278 3279 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 3280 com.android.internal.R.styleable.View_scrollbarSize, 3281 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3282 3283 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3284 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3285 3286 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3287 if (thumb != null) { 3288 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3289 } 3290 3291 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3292 false); 3293 if (alwaysDraw) { 3294 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3295 } 3296 3297 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3298 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3299 3300 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3301 if (thumb != null) { 3302 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3303 } 3304 3305 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3306 false); 3307 if (alwaysDraw) { 3308 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3309 } 3310 3311 // Re-apply user/background padding so that scrollbar(s) get added 3312 resolvePadding(); 3313 } 3314 3315 /** 3316 * <p> 3317 * Initalizes the scrollability cache if necessary. 3318 * </p> 3319 */ 3320 private void initScrollCache() { 3321 if (mScrollCache == null) { 3322 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 3323 } 3324 } 3325 3326 /** 3327 * Set the position of the vertical scroll bar. Should be one of 3328 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 3329 * {@link #SCROLLBAR_POSITION_RIGHT}. 3330 * 3331 * @param position Where the vertical scroll bar should be positioned. 3332 */ 3333 public void setVerticalScrollbarPosition(int position) { 3334 if (mVerticalScrollbarPosition != position) { 3335 mVerticalScrollbarPosition = position; 3336 computeOpaqueFlags(); 3337 resolvePadding(); 3338 } 3339 } 3340 3341 /** 3342 * @return The position where the vertical scroll bar will show, if applicable. 3343 * @see #setVerticalScrollbarPosition(int) 3344 */ 3345 public int getVerticalScrollbarPosition() { 3346 return mVerticalScrollbarPosition; 3347 } 3348 3349 /** 3350 * Register a callback to be invoked when focus of this view changed. 3351 * 3352 * @param l The callback that will run. 3353 */ 3354 public void setOnFocusChangeListener(OnFocusChangeListener l) { 3355 mOnFocusChangeListener = l; 3356 } 3357 3358 /** 3359 * Add a listener that will be called when the bounds of the view change due to 3360 * layout processing. 3361 * 3362 * @param listener The listener that will be called when layout bounds change. 3363 */ 3364 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 3365 if (mOnLayoutChangeListeners == null) { 3366 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 3367 } 3368 if (!mOnLayoutChangeListeners.contains(listener)) { 3369 mOnLayoutChangeListeners.add(listener); 3370 } 3371 } 3372 3373 /** 3374 * Remove a listener for layout changes. 3375 * 3376 * @param listener The listener for layout bounds change. 3377 */ 3378 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 3379 if (mOnLayoutChangeListeners == null) { 3380 return; 3381 } 3382 mOnLayoutChangeListeners.remove(listener); 3383 } 3384 3385 /** 3386 * Add a listener for attach state changes. 3387 * 3388 * This listener will be called whenever this view is attached or detached 3389 * from a window. Remove the listener using 3390 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 3391 * 3392 * @param listener Listener to attach 3393 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 3394 */ 3395 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3396 if (mOnAttachStateChangeListeners == null) { 3397 mOnAttachStateChangeListeners = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 3398 } 3399 mOnAttachStateChangeListeners.add(listener); 3400 } 3401 3402 /** 3403 * Remove a listener for attach state changes. The listener will receive no further 3404 * notification of window attach/detach events. 3405 * 3406 * @param listener Listener to remove 3407 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 3408 */ 3409 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3410 if (mOnAttachStateChangeListeners == null) { 3411 return; 3412 } 3413 mOnAttachStateChangeListeners.remove(listener); 3414 } 3415 3416 /** 3417 * Returns the focus-change callback registered for this view. 3418 * 3419 * @return The callback, or null if one is not registered. 3420 */ 3421 public OnFocusChangeListener getOnFocusChangeListener() { 3422 return mOnFocusChangeListener; 3423 } 3424 3425 /** 3426 * Register a callback to be invoked when this view is clicked. If this view is not 3427 * clickable, it becomes clickable. 3428 * 3429 * @param l The callback that will run 3430 * 3431 * @see #setClickable(boolean) 3432 */ 3433 public void setOnClickListener(OnClickListener l) { 3434 if (!isClickable()) { 3435 setClickable(true); 3436 } 3437 mOnClickListener = l; 3438 } 3439 3440 /** 3441 * Register a callback to be invoked when this view is clicked and held. If this view is not 3442 * long clickable, it becomes long clickable. 3443 * 3444 * @param l The callback that will run 3445 * 3446 * @see #setLongClickable(boolean) 3447 */ 3448 public void setOnLongClickListener(OnLongClickListener l) { 3449 if (!isLongClickable()) { 3450 setLongClickable(true); 3451 } 3452 mOnLongClickListener = l; 3453 } 3454 3455 /** 3456 * Register a callback to be invoked when the context menu for this view is 3457 * being built. If this view is not long clickable, it becomes long clickable. 3458 * 3459 * @param l The callback that will run 3460 * 3461 */ 3462 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 3463 if (!isLongClickable()) { 3464 setLongClickable(true); 3465 } 3466 mOnCreateContextMenuListener = l; 3467 } 3468 3469 /** 3470 * Call this view's OnClickListener, if it is defined. 3471 * 3472 * @return True there was an assigned OnClickListener that was called, false 3473 * otherwise is returned. 3474 */ 3475 public boolean performClick() { 3476 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 3477 3478 if (mOnClickListener != null) { 3479 playSoundEffect(SoundEffectConstants.CLICK); 3480 mOnClickListener.onClick(this); 3481 return true; 3482 } 3483 3484 return false; 3485 } 3486 3487 /** 3488 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 3489 * OnLongClickListener did not consume the event. 3490 * 3491 * @return True if one of the above receivers consumed the event, false otherwise. 3492 */ 3493 public boolean performLongClick() { 3494 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 3495 3496 boolean handled = false; 3497 if (mOnLongClickListener != null) { 3498 handled = mOnLongClickListener.onLongClick(View.this); 3499 } 3500 if (!handled) { 3501 handled = showContextMenu(); 3502 } 3503 if (handled) { 3504 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 3505 } 3506 return handled; 3507 } 3508 3509 /** 3510 * Performs button-related actions during a touch down event. 3511 * 3512 * @param event The event. 3513 * @return True if the down was consumed. 3514 * 3515 * @hide 3516 */ 3517 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 3518 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 3519 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 3520 return true; 3521 } 3522 } 3523 return false; 3524 } 3525 3526 /** 3527 * Bring up the context menu for this view. 3528 * 3529 * @return Whether a context menu was displayed. 3530 */ 3531 public boolean showContextMenu() { 3532 return getParent().showContextMenuForChild(this); 3533 } 3534 3535 /** 3536 * Bring up the context menu for this view, referring to the item under the specified point. 3537 * 3538 * @param x The referenced x coordinate. 3539 * @param y The referenced y coordinate. 3540 * @param metaState The keyboard modifiers that were pressed. 3541 * @return Whether a context menu was displayed. 3542 * 3543 * @hide 3544 */ 3545 public boolean showContextMenu(float x, float y, int metaState) { 3546 return showContextMenu(); 3547 } 3548 3549 /** 3550 * Start an action mode. 3551 * 3552 * @param callback Callback that will control the lifecycle of the action mode 3553 * @return The new action mode if it is started, null otherwise 3554 * 3555 * @see ActionMode 3556 */ 3557 public ActionMode startActionMode(ActionMode.Callback callback) { 3558 return getParent().startActionModeForChild(this, callback); 3559 } 3560 3561 /** 3562 * Register a callback to be invoked when a key is pressed in this view. 3563 * @param l the key listener to attach to this view 3564 */ 3565 public void setOnKeyListener(OnKeyListener l) { 3566 mOnKeyListener = l; 3567 } 3568 3569 /** 3570 * Register a callback to be invoked when a touch event is sent to this view. 3571 * @param l the touch listener to attach to this view 3572 */ 3573 public void setOnTouchListener(OnTouchListener l) { 3574 mOnTouchListener = l; 3575 } 3576 3577 /** 3578 * Register a callback to be invoked when a generic motion event is sent to this view. 3579 * @param l the generic motion listener to attach to this view 3580 */ 3581 public void setOnGenericMotionListener(OnGenericMotionListener l) { 3582 mOnGenericMotionListener = l; 3583 } 3584 3585 /** 3586 * Register a callback to be invoked when a hover event is sent to this view. 3587 * @param l the hover listener to attach to this view 3588 */ 3589 public void setOnHoverListener(OnHoverListener l) { 3590 mOnHoverListener = l; 3591 } 3592 3593 /** 3594 * Register a drag event listener callback object for this View. The parameter is 3595 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 3596 * View, the system calls the 3597 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 3598 * @param l An implementation of {@link android.view.View.OnDragListener}. 3599 */ 3600 public void setOnDragListener(OnDragListener l) { 3601 mOnDragListener = l; 3602 } 3603 3604 /** 3605 * Give this view focus. This will cause 3606 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3607 * 3608 * Note: this does not check whether this {@link View} should get focus, it just 3609 * gives it focus no matter what. It should only be called internally by framework 3610 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 3611 * 3612 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 3613 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 3614 * focus moved when requestFocus() is called. It may not always 3615 * apply, in which case use the default View.FOCUS_DOWN. 3616 * @param previouslyFocusedRect The rectangle of the view that had focus 3617 * prior in this View's coordinate system. 3618 */ 3619 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 3620 if (DBG) { 3621 System.out.println(this + " requestFocus()"); 3622 } 3623 3624 if ((mPrivateFlags & FOCUSED) == 0) { 3625 mPrivateFlags |= FOCUSED; 3626 3627 if (mParent != null) { 3628 mParent.requestChildFocus(this, this); 3629 } 3630 3631 onFocusChanged(true, direction, previouslyFocusedRect); 3632 refreshDrawableState(); 3633 } 3634 } 3635 3636 /** 3637 * Request that a rectangle of this view be visible on the screen, 3638 * scrolling if necessary just enough. 3639 * 3640 * <p>A View should call this if it maintains some notion of which part 3641 * of its content is interesting. For example, a text editing view 3642 * should call this when its cursor moves. 3643 * 3644 * @param rectangle The rectangle. 3645 * @return Whether any parent scrolled. 3646 */ 3647 public boolean requestRectangleOnScreen(Rect rectangle) { 3648 return requestRectangleOnScreen(rectangle, false); 3649 } 3650 3651 /** 3652 * Request that a rectangle of this view be visible on the screen, 3653 * scrolling if necessary just enough. 3654 * 3655 * <p>A View should call this if it maintains some notion of which part 3656 * of its content is interesting. For example, a text editing view 3657 * should call this when its cursor moves. 3658 * 3659 * <p>When <code>immediate</code> is set to true, scrolling will not be 3660 * animated. 3661 * 3662 * @param rectangle The rectangle. 3663 * @param immediate True to forbid animated scrolling, false otherwise 3664 * @return Whether any parent scrolled. 3665 */ 3666 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 3667 View child = this; 3668 ViewParent parent = mParent; 3669 boolean scrolled = false; 3670 while (parent != null) { 3671 scrolled |= parent.requestChildRectangleOnScreen(child, 3672 rectangle, immediate); 3673 3674 // offset rect so next call has the rectangle in the 3675 // coordinate system of its direct child. 3676 rectangle.offset(child.getLeft(), child.getTop()); 3677 rectangle.offset(-child.getScrollX(), -child.getScrollY()); 3678 3679 if (!(parent instanceof View)) { 3680 break; 3681 } 3682 3683 child = (View) parent; 3684 parent = child.getParent(); 3685 } 3686 return scrolled; 3687 } 3688 3689 /** 3690 * Called when this view wants to give up focus. This will cause 3691 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3692 */ 3693 public void clearFocus() { 3694 if (DBG) { 3695 System.out.println(this + " clearFocus()"); 3696 } 3697 3698 if ((mPrivateFlags & FOCUSED) != 0) { 3699 mPrivateFlags &= ~FOCUSED; 3700 3701 if (mParent != null) { 3702 mParent.clearChildFocus(this); 3703 } 3704 3705 onFocusChanged(false, 0, null); 3706 refreshDrawableState(); 3707 } 3708 } 3709 3710 /** 3711 * Called to clear the focus of a view that is about to be removed. 3712 * Doesn't call clearChildFocus, which prevents this view from taking 3713 * focus again before it has been removed from the parent 3714 */ 3715 void clearFocusForRemoval() { 3716 if ((mPrivateFlags & FOCUSED) != 0) { 3717 mPrivateFlags &= ~FOCUSED; 3718 3719 onFocusChanged(false, 0, null); 3720 refreshDrawableState(); 3721 } 3722 } 3723 3724 /** 3725 * Called internally by the view system when a new view is getting focus. 3726 * This is what clears the old focus. 3727 */ 3728 void unFocus() { 3729 if (DBG) { 3730 System.out.println(this + " unFocus()"); 3731 } 3732 3733 if ((mPrivateFlags & FOCUSED) != 0) { 3734 mPrivateFlags &= ~FOCUSED; 3735 3736 onFocusChanged(false, 0, null); 3737 refreshDrawableState(); 3738 } 3739 } 3740 3741 /** 3742 * Returns true if this view has focus iteself, or is the ancestor of the 3743 * view that has focus. 3744 * 3745 * @return True if this view has or contains focus, false otherwise. 3746 */ 3747 @ViewDebug.ExportedProperty(category = "focus") 3748 public boolean hasFocus() { 3749 return (mPrivateFlags & FOCUSED) != 0; 3750 } 3751 3752 /** 3753 * Returns true if this view is focusable or if it contains a reachable View 3754 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 3755 * is a View whose parents do not block descendants focus. 3756 * 3757 * Only {@link #VISIBLE} views are considered focusable. 3758 * 3759 * @return True if the view is focusable or if the view contains a focusable 3760 * View, false otherwise. 3761 * 3762 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 3763 */ 3764 public boolean hasFocusable() { 3765 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 3766 } 3767 3768 /** 3769 * Called by the view system when the focus state of this view changes. 3770 * When the focus change event is caused by directional navigation, direction 3771 * and previouslyFocusedRect provide insight into where the focus is coming from. 3772 * When overriding, be sure to call up through to the super class so that 3773 * the standard focus handling will occur. 3774 * 3775 * @param gainFocus True if the View has focus; false otherwise. 3776 * @param direction The direction focus has moved when requestFocus() 3777 * is called to give this view focus. Values are 3778 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 3779 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 3780 * It may not always apply, in which case use the default. 3781 * @param previouslyFocusedRect The rectangle, in this view's coordinate 3782 * system, of the previously focused view. If applicable, this will be 3783 * passed in as finer grained information about where the focus is coming 3784 * from (in addition to direction). Will be <code>null</code> otherwise. 3785 */ 3786 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 3787 if (gainFocus) { 3788 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 3789 } 3790 3791 InputMethodManager imm = InputMethodManager.peekInstance(); 3792 if (!gainFocus) { 3793 if (isPressed()) { 3794 setPressed(false); 3795 } 3796 if (imm != null && mAttachInfo != null 3797 && mAttachInfo.mHasWindowFocus) { 3798 imm.focusOut(this); 3799 } 3800 onFocusLost(); 3801 } else if (imm != null && mAttachInfo != null 3802 && mAttachInfo.mHasWindowFocus) { 3803 imm.focusIn(this); 3804 } 3805 3806 invalidate(true); 3807 if (mOnFocusChangeListener != null) { 3808 mOnFocusChangeListener.onFocusChange(this, gainFocus); 3809 } 3810 3811 if (mAttachInfo != null) { 3812 mAttachInfo.mKeyDispatchState.reset(this); 3813 } 3814 } 3815 3816 /** 3817 * Sends an accessibility event of the given type. If accessiiblity is 3818 * not enabled this method has no effect. The default implementation calls 3819 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 3820 * to populate information about the event source (this View), then calls 3821 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 3822 * populate the text content of the event source including its descendants, 3823 * and last calls 3824 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 3825 * on its parent to resuest sending of the event to interested parties. 3826 * <p> 3827 * If an {@link AccessibilityDelegate} has been specified via calling 3828 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3829 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 3830 * responsible for handling this call. 3831 * </p> 3832 * 3833 * @param eventType The type of the event to send, as defined by several types from 3834 * {@link android.view.accessibility.AccessibilityEvent}, such as 3835 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 3836 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 3837 * 3838 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 3839 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3840 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 3841 * @see AccessibilityDelegate 3842 */ 3843 public void sendAccessibilityEvent(int eventType) { 3844 if (mAccessibilityDelegate != null) { 3845 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 3846 } else { 3847 sendAccessibilityEventInternal(eventType); 3848 } 3849 } 3850 3851 /** 3852 * @see #sendAccessibilityEvent(int) 3853 * 3854 * Note: Called from the default {@link AccessibilityDelegate}. 3855 */ 3856 void sendAccessibilityEventInternal(int eventType) { 3857 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 3858 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 3859 } 3860 } 3861 3862 /** 3863 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 3864 * takes as an argument an empty {@link AccessibilityEvent} and does not 3865 * perform a check whether accessibility is enabled. 3866 * <p> 3867 * If an {@link AccessibilityDelegate} has been specified via calling 3868 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3869 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 3870 * is responsible for handling this call. 3871 * </p> 3872 * 3873 * @param event The event to send. 3874 * 3875 * @see #sendAccessibilityEvent(int) 3876 */ 3877 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 3878 if (mAccessibilityDelegate != null) { 3879 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 3880 } else { 3881 sendAccessibilityEventUncheckedInternal(event); 3882 } 3883 } 3884 3885 /** 3886 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 3887 * 3888 * Note: Called from the default {@link AccessibilityDelegate}. 3889 */ 3890 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 3891 if (!isShown()) { 3892 return; 3893 } 3894 onInitializeAccessibilityEvent(event); 3895 // Only a subset of accessibility events populates text content. 3896 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 3897 dispatchPopulateAccessibilityEvent(event); 3898 } 3899 // In the beginning we called #isShown(), so we know that getParent() is not null. 3900 getParent().requestSendAccessibilityEvent(this, event); 3901 } 3902 3903 /** 3904 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 3905 * to its children for adding their text content to the event. Note that the 3906 * event text is populated in a separate dispatch path since we add to the 3907 * event not only the text of the source but also the text of all its descendants. 3908 * A typical implementation will call 3909 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 3910 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3911 * on each child. Override this method if custom population of the event text 3912 * content is required. 3913 * <p> 3914 * If an {@link AccessibilityDelegate} has been specified via calling 3915 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3916 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 3917 * is responsible for handling this call. 3918 * </p> 3919 * <p> 3920 * <em>Note:</em> Accessibility events of certain types are not dispatched for 3921 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 3922 * </p> 3923 * 3924 * @param event The event. 3925 * 3926 * @return True if the event population was completed. 3927 */ 3928 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 3929 if (mAccessibilityDelegate != null) { 3930 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 3931 } else { 3932 return dispatchPopulateAccessibilityEventInternal(event); 3933 } 3934 } 3935 3936 /** 3937 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3938 * 3939 * Note: Called from the default {@link AccessibilityDelegate}. 3940 */ 3941 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 3942 onPopulateAccessibilityEvent(event); 3943 return false; 3944 } 3945 3946 /** 3947 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3948 * giving a chance to this View to populate the accessibility event with its 3949 * text content. While this method is free to modify event 3950 * attributes other than text content, doing so should normally be performed in 3951 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 3952 * <p> 3953 * Example: Adding formatted date string to an accessibility event in addition 3954 * to the text added by the super implementation: 3955 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3956 * super.onPopulateAccessibilityEvent(event); 3957 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 3958 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 3959 * mCurrentDate.getTimeInMillis(), flags); 3960 * event.getText().add(selectedDateUtterance); 3961 * }</pre> 3962 * <p> 3963 * If an {@link AccessibilityDelegate} has been specified via calling 3964 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3965 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 3966 * is responsible for handling this call. 3967 * </p> 3968 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 3969 * information to the event, in case the default implementation has basic information to add. 3970 * </p> 3971 * 3972 * @param event The accessibility event which to populate. 3973 * 3974 * @see #sendAccessibilityEvent(int) 3975 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3976 */ 3977 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3978 if (mAccessibilityDelegate != null) { 3979 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 3980 } else { 3981 onPopulateAccessibilityEventInternal(event); 3982 } 3983 } 3984 3985 /** 3986 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 3987 * 3988 * Note: Called from the default {@link AccessibilityDelegate}. 3989 */ 3990 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 3991 3992 } 3993 3994 /** 3995 * Initializes an {@link AccessibilityEvent} with information about 3996 * this View which is the event source. In other words, the source of 3997 * an accessibility event is the view whose state change triggered firing 3998 * the event. 3999 * <p> 4000 * Example: Setting the password property of an event in addition 4001 * to properties set by the super implementation: 4002 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4003 * super.onInitializeAccessibilityEvent(event); 4004 * event.setPassword(true); 4005 * }</pre> 4006 * <p> 4007 * If an {@link AccessibilityDelegate} has been specified via calling 4008 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4009 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 4010 * is responsible for handling this call. 4011 * </p> 4012 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4013 * information to the event, in case the default implementation has basic information to add. 4014 * </p> 4015 * @param event The event to initialize. 4016 * 4017 * @see #sendAccessibilityEvent(int) 4018 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4019 */ 4020 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4021 if (mAccessibilityDelegate != null) { 4022 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 4023 } else { 4024 onInitializeAccessibilityEventInternal(event); 4025 } 4026 } 4027 4028 /** 4029 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4030 * 4031 * Note: Called from the default {@link AccessibilityDelegate}. 4032 */ 4033 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 4034 event.setSource(this); 4035 event.setClassName(getClass().getName()); 4036 event.setPackageName(getContext().getPackageName()); 4037 event.setEnabled(isEnabled()); 4038 event.setContentDescription(mContentDescription); 4039 4040 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) { 4041 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList; 4042 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, 4043 FOCUSABLES_ALL); 4044 event.setItemCount(focusablesTempList.size()); 4045 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 4046 focusablesTempList.clear(); 4047 } 4048 } 4049 4050 /** 4051 * Returns an {@link AccessibilityNodeInfo} representing this view from the 4052 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 4053 * This method is responsible for obtaining an accessibility node info from a 4054 * pool of reusable instances and calling 4055 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 4056 * initialize the former. 4057 * <p> 4058 * Note: The client is responsible for recycling the obtained instance by calling 4059 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 4060 * </p> 4061 * @return A populated {@link AccessibilityNodeInfo}. 4062 * 4063 * @see AccessibilityNodeInfo 4064 */ 4065 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 4066 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 4067 onInitializeAccessibilityNodeInfo(info); 4068 return info; 4069 } 4070 4071 /** 4072 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 4073 * The base implementation sets: 4074 * <ul> 4075 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 4076 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 4077 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 4078 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 4079 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 4080 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 4081 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 4082 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 4083 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 4084 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 4085 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 4086 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 4087 * </ul> 4088 * <p> 4089 * Subclasses should override this method, call the super implementation, 4090 * and set additional attributes. 4091 * </p> 4092 * <p> 4093 * If an {@link AccessibilityDelegate} has been specified via calling 4094 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4095 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 4096 * is responsible for handling this call. 4097 * </p> 4098 * 4099 * @param info The instance to initialize. 4100 */ 4101 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 4102 if (mAccessibilityDelegate != null) { 4103 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 4104 } else { 4105 onInitializeAccessibilityNodeInfoInternal(info); 4106 } 4107 } 4108 4109 /** 4110 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 4111 * 4112 * Note: Called from the default {@link AccessibilityDelegate}. 4113 */ 4114 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 4115 Rect bounds = mAttachInfo.mTmpInvalRect; 4116 getDrawingRect(bounds); 4117 info.setBoundsInParent(bounds); 4118 4119 int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation; 4120 getLocationOnScreen(locationOnScreen); 4121 bounds.offsetTo(0, 0); 4122 bounds.offset(locationOnScreen[0], locationOnScreen[1]); 4123 info.setBoundsInScreen(bounds); 4124 4125 if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { 4126 ViewParent parent = getParent(); 4127 if (parent instanceof View) { 4128 View parentView = (View) parent; 4129 info.setParent(parentView); 4130 } 4131 } 4132 4133 info.setPackageName(mContext.getPackageName()); 4134 info.setClassName(getClass().getName()); 4135 info.setContentDescription(getContentDescription()); 4136 4137 info.setEnabled(isEnabled()); 4138 info.setClickable(isClickable()); 4139 info.setFocusable(isFocusable()); 4140 info.setFocused(isFocused()); 4141 info.setSelected(isSelected()); 4142 info.setLongClickable(isLongClickable()); 4143 4144 // TODO: These make sense only if we are in an AdapterView but all 4145 // views can be selected. Maybe from accessiiblity perspective 4146 // we should report as selectable view in an AdapterView. 4147 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 4148 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 4149 4150 if (isFocusable()) { 4151 if (isFocused()) { 4152 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 4153 } else { 4154 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 4155 } 4156 } 4157 } 4158 4159 /** 4160 * Sets a delegate for implementing accessibility support via compositon as 4161 * opposed to inheritance. The delegate's primary use is for implementing 4162 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 4163 * 4164 * @param delegate The delegate instance. 4165 * 4166 * @see AccessibilityDelegate 4167 */ 4168 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 4169 mAccessibilityDelegate = delegate; 4170 } 4171 4172 /** 4173 * Gets the unique identifier of this view on the screen for accessibility purposes. 4174 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 4175 * 4176 * @return The view accessibility id. 4177 * 4178 * @hide 4179 */ 4180 public int getAccessibilityViewId() { 4181 if (mAccessibilityViewId == NO_ID) { 4182 mAccessibilityViewId = sNextAccessibilityViewId++; 4183 } 4184 return mAccessibilityViewId; 4185 } 4186 4187 /** 4188 * Gets the unique identifier of the window in which this View reseides. 4189 * 4190 * @return The window accessibility id. 4191 * 4192 * @hide 4193 */ 4194 public int getAccessibilityWindowId() { 4195 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 4196 } 4197 4198 /** 4199 * Gets the {@link View} description. It briefly describes the view and is 4200 * primarily used for accessibility support. Set this property to enable 4201 * better accessibility support for your application. This is especially 4202 * true for views that do not have textual representation (For example, 4203 * ImageButton). 4204 * 4205 * @return The content descriptiopn. 4206 * 4207 * @attr ref android.R.styleable#View_contentDescription 4208 */ 4209 public CharSequence getContentDescription() { 4210 return mContentDescription; 4211 } 4212 4213 /** 4214 * Sets the {@link View} description. It briefly describes the view and is 4215 * primarily used for accessibility support. Set this property to enable 4216 * better accessibility support for your application. This is especially 4217 * true for views that do not have textual representation (For example, 4218 * ImageButton). 4219 * 4220 * @param contentDescription The content description. 4221 * 4222 * @attr ref android.R.styleable#View_contentDescription 4223 */ 4224 @RemotableViewMethod 4225 public void setContentDescription(CharSequence contentDescription) { 4226 mContentDescription = contentDescription; 4227 } 4228 4229 /** 4230 * Invoked whenever this view loses focus, either by losing window focus or by losing 4231 * focus within its window. This method can be used to clear any state tied to the 4232 * focus. For instance, if a button is held pressed with the trackball and the window 4233 * loses focus, this method can be used to cancel the press. 4234 * 4235 * Subclasses of View overriding this method should always call super.onFocusLost(). 4236 * 4237 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 4238 * @see #onWindowFocusChanged(boolean) 4239 * 4240 * @hide pending API council approval 4241 */ 4242 protected void onFocusLost() { 4243 resetPressedState(); 4244 } 4245 4246 private void resetPressedState() { 4247 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 4248 return; 4249 } 4250 4251 if (isPressed()) { 4252 setPressed(false); 4253 4254 if (!mHasPerformedLongPress) { 4255 removeLongPressCallback(); 4256 } 4257 } 4258 } 4259 4260 /** 4261 * Returns true if this view has focus 4262 * 4263 * @return True if this view has focus, false otherwise. 4264 */ 4265 @ViewDebug.ExportedProperty(category = "focus") 4266 public boolean isFocused() { 4267 return (mPrivateFlags & FOCUSED) != 0; 4268 } 4269 4270 /** 4271 * Find the view in the hierarchy rooted at this view that currently has 4272 * focus. 4273 * 4274 * @return The view that currently has focus, or null if no focused view can 4275 * be found. 4276 */ 4277 public View findFocus() { 4278 return (mPrivateFlags & FOCUSED) != 0 ? this : null; 4279 } 4280 4281 /** 4282 * Change whether this view is one of the set of scrollable containers in 4283 * its window. This will be used to determine whether the window can 4284 * resize or must pan when a soft input area is open -- scrollable 4285 * containers allow the window to use resize mode since the container 4286 * will appropriately shrink. 4287 */ 4288 public void setScrollContainer(boolean isScrollContainer) { 4289 if (isScrollContainer) { 4290 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) { 4291 mAttachInfo.mScrollContainers.add(this); 4292 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 4293 } 4294 mPrivateFlags |= SCROLL_CONTAINER; 4295 } else { 4296 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 4297 mAttachInfo.mScrollContainers.remove(this); 4298 } 4299 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED); 4300 } 4301 } 4302 4303 /** 4304 * Returns the quality of the drawing cache. 4305 * 4306 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4307 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4308 * 4309 * @see #setDrawingCacheQuality(int) 4310 * @see #setDrawingCacheEnabled(boolean) 4311 * @see #isDrawingCacheEnabled() 4312 * 4313 * @attr ref android.R.styleable#View_drawingCacheQuality 4314 */ 4315 public int getDrawingCacheQuality() { 4316 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 4317 } 4318 4319 /** 4320 * Set the drawing cache quality of this view. This value is used only when the 4321 * drawing cache is enabled 4322 * 4323 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4324 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4325 * 4326 * @see #getDrawingCacheQuality() 4327 * @see #setDrawingCacheEnabled(boolean) 4328 * @see #isDrawingCacheEnabled() 4329 * 4330 * @attr ref android.R.styleable#View_drawingCacheQuality 4331 */ 4332 public void setDrawingCacheQuality(int quality) { 4333 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 4334 } 4335 4336 /** 4337 * Returns whether the screen should remain on, corresponding to the current 4338 * value of {@link #KEEP_SCREEN_ON}. 4339 * 4340 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 4341 * 4342 * @see #setKeepScreenOn(boolean) 4343 * 4344 * @attr ref android.R.styleable#View_keepScreenOn 4345 */ 4346 public boolean getKeepScreenOn() { 4347 return (mViewFlags & KEEP_SCREEN_ON) != 0; 4348 } 4349 4350 /** 4351 * Controls whether the screen should remain on, modifying the 4352 * value of {@link #KEEP_SCREEN_ON}. 4353 * 4354 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 4355 * 4356 * @see #getKeepScreenOn() 4357 * 4358 * @attr ref android.R.styleable#View_keepScreenOn 4359 */ 4360 public void setKeepScreenOn(boolean keepScreenOn) { 4361 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 4362 } 4363 4364 /** 4365 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4366 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4367 * 4368 * @attr ref android.R.styleable#View_nextFocusLeft 4369 */ 4370 public int getNextFocusLeftId() { 4371 return mNextFocusLeftId; 4372 } 4373 4374 /** 4375 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4376 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 4377 * decide automatically. 4378 * 4379 * @attr ref android.R.styleable#View_nextFocusLeft 4380 */ 4381 public void setNextFocusLeftId(int nextFocusLeftId) { 4382 mNextFocusLeftId = nextFocusLeftId; 4383 } 4384 4385 /** 4386 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4387 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4388 * 4389 * @attr ref android.R.styleable#View_nextFocusRight 4390 */ 4391 public int getNextFocusRightId() { 4392 return mNextFocusRightId; 4393 } 4394 4395 /** 4396 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4397 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 4398 * decide automatically. 4399 * 4400 * @attr ref android.R.styleable#View_nextFocusRight 4401 */ 4402 public void setNextFocusRightId(int nextFocusRightId) { 4403 mNextFocusRightId = nextFocusRightId; 4404 } 4405 4406 /** 4407 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4408 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4409 * 4410 * @attr ref android.R.styleable#View_nextFocusUp 4411 */ 4412 public int getNextFocusUpId() { 4413 return mNextFocusUpId; 4414 } 4415 4416 /** 4417 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4418 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 4419 * decide automatically. 4420 * 4421 * @attr ref android.R.styleable#View_nextFocusUp 4422 */ 4423 public void setNextFocusUpId(int nextFocusUpId) { 4424 mNextFocusUpId = nextFocusUpId; 4425 } 4426 4427 /** 4428 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4429 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4430 * 4431 * @attr ref android.R.styleable#View_nextFocusDown 4432 */ 4433 public int getNextFocusDownId() { 4434 return mNextFocusDownId; 4435 } 4436 4437 /** 4438 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4439 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 4440 * decide automatically. 4441 * 4442 * @attr ref android.R.styleable#View_nextFocusDown 4443 */ 4444 public void setNextFocusDownId(int nextFocusDownId) { 4445 mNextFocusDownId = nextFocusDownId; 4446 } 4447 4448 /** 4449 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4450 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4451 * 4452 * @attr ref android.R.styleable#View_nextFocusForward 4453 */ 4454 public int getNextFocusForwardId() { 4455 return mNextFocusForwardId; 4456 } 4457 4458 /** 4459 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4460 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 4461 * decide automatically. 4462 * 4463 * @attr ref android.R.styleable#View_nextFocusForward 4464 */ 4465 public void setNextFocusForwardId(int nextFocusForwardId) { 4466 mNextFocusForwardId = nextFocusForwardId; 4467 } 4468 4469 /** 4470 * Returns the visibility of this view and all of its ancestors 4471 * 4472 * @return True if this view and all of its ancestors are {@link #VISIBLE} 4473 */ 4474 public boolean isShown() { 4475 View current = this; 4476 //noinspection ConstantConditions 4477 do { 4478 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 4479 return false; 4480 } 4481 ViewParent parent = current.mParent; 4482 if (parent == null) { 4483 return false; // We are not attached to the view root 4484 } 4485 if (!(parent instanceof View)) { 4486 return true; 4487 } 4488 current = (View) parent; 4489 } while (current != null); 4490 4491 return false; 4492 } 4493 4494 /** 4495 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag 4496 * is set 4497 * 4498 * @param insets Insets for system windows 4499 * 4500 * @return True if this view applied the insets, false otherwise 4501 */ 4502 protected boolean fitSystemWindows(Rect insets) { 4503 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 4504 mPaddingLeft = insets.left; 4505 mPaddingTop = insets.top; 4506 mPaddingRight = insets.right; 4507 mPaddingBottom = insets.bottom; 4508 requestLayout(); 4509 return true; 4510 } 4511 return false; 4512 } 4513 4514 /** 4515 * Set whether or not this view should account for system screen decorations 4516 * such as the status bar and inset its content. This allows this view to be 4517 * positioned in absolute screen coordinates and remain visible to the user. 4518 * 4519 * <p>This should only be used by top-level window decor views. 4520 * 4521 * @param fitSystemWindows true to inset content for system screen decorations, false for 4522 * default behavior. 4523 * 4524 * @attr ref android.R.styleable#View_fitsSystemWindows 4525 */ 4526 public void setFitsSystemWindows(boolean fitSystemWindows) { 4527 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 4528 } 4529 4530 /** 4531 * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view 4532 * will account for system screen decorations such as the status bar and inset its 4533 * content. This allows the view to be positioned in absolute screen coordinates 4534 * and remain visible to the user. 4535 * 4536 * @return true if this view will adjust its content bounds for system screen decorations. 4537 * 4538 * @attr ref android.R.styleable#View_fitsSystemWindows 4539 */ 4540 public boolean fitsSystemWindows() { 4541 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 4542 } 4543 4544 /** 4545 * Returns the visibility status for this view. 4546 * 4547 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4548 * @attr ref android.R.styleable#View_visibility 4549 */ 4550 @ViewDebug.ExportedProperty(mapping = { 4551 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 4552 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 4553 @ViewDebug.IntToString(from = GONE, to = "GONE") 4554 }) 4555 public int getVisibility() { 4556 return mViewFlags & VISIBILITY_MASK; 4557 } 4558 4559 /** 4560 * Set the enabled state of this view. 4561 * 4562 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4563 * @attr ref android.R.styleable#View_visibility 4564 */ 4565 @RemotableViewMethod 4566 public void setVisibility(int visibility) { 4567 setFlags(visibility, VISIBILITY_MASK); 4568 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); 4569 } 4570 4571 /** 4572 * Returns the enabled status for this view. The interpretation of the 4573 * enabled state varies by subclass. 4574 * 4575 * @return True if this view is enabled, false otherwise. 4576 */ 4577 @ViewDebug.ExportedProperty 4578 public boolean isEnabled() { 4579 return (mViewFlags & ENABLED_MASK) == ENABLED; 4580 } 4581 4582 /** 4583 * Set the enabled state of this view. The interpretation of the enabled 4584 * state varies by subclass. 4585 * 4586 * @param enabled True if this view is enabled, false otherwise. 4587 */ 4588 @RemotableViewMethod 4589 public void setEnabled(boolean enabled) { 4590 if (enabled == isEnabled()) return; 4591 4592 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 4593 4594 /* 4595 * The View most likely has to change its appearance, so refresh 4596 * the drawable state. 4597 */ 4598 refreshDrawableState(); 4599 4600 // Invalidate too, since the default behavior for views is to be 4601 // be drawn at 50% alpha rather than to change the drawable. 4602 invalidate(true); 4603 } 4604 4605 /** 4606 * Set whether this view can receive the focus. 4607 * 4608 * Setting this to false will also ensure that this view is not focusable 4609 * in touch mode. 4610 * 4611 * @param focusable If true, this view can receive the focus. 4612 * 4613 * @see #setFocusableInTouchMode(boolean) 4614 * @attr ref android.R.styleable#View_focusable 4615 */ 4616 public void setFocusable(boolean focusable) { 4617 if (!focusable) { 4618 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 4619 } 4620 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 4621 } 4622 4623 /** 4624 * Set whether this view can receive focus while in touch mode. 4625 * 4626 * Setting this to true will also ensure that this view is focusable. 4627 * 4628 * @param focusableInTouchMode If true, this view can receive the focus while 4629 * in touch mode. 4630 * 4631 * @see #setFocusable(boolean) 4632 * @attr ref android.R.styleable#View_focusableInTouchMode 4633 */ 4634 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 4635 // Focusable in touch mode should always be set before the focusable flag 4636 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 4637 // which, in touch mode, will not successfully request focus on this view 4638 // because the focusable in touch mode flag is not set 4639 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 4640 if (focusableInTouchMode) { 4641 setFlags(FOCUSABLE, FOCUSABLE_MASK); 4642 } 4643 } 4644 4645 /** 4646 * Set whether this view should have sound effects enabled for events such as 4647 * clicking and touching. 4648 * 4649 * <p>You may wish to disable sound effects for a view if you already play sounds, 4650 * for instance, a dial key that plays dtmf tones. 4651 * 4652 * @param soundEffectsEnabled whether sound effects are enabled for this view. 4653 * @see #isSoundEffectsEnabled() 4654 * @see #playSoundEffect(int) 4655 * @attr ref android.R.styleable#View_soundEffectsEnabled 4656 */ 4657 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 4658 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 4659 } 4660 4661 /** 4662 * @return whether this view should have sound effects enabled for events such as 4663 * clicking and touching. 4664 * 4665 * @see #setSoundEffectsEnabled(boolean) 4666 * @see #playSoundEffect(int) 4667 * @attr ref android.R.styleable#View_soundEffectsEnabled 4668 */ 4669 @ViewDebug.ExportedProperty 4670 public boolean isSoundEffectsEnabled() { 4671 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 4672 } 4673 4674 /** 4675 * Set whether this view should have haptic feedback for events such as 4676 * long presses. 4677 * 4678 * <p>You may wish to disable haptic feedback if your view already controls 4679 * its own haptic feedback. 4680 * 4681 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 4682 * @see #isHapticFeedbackEnabled() 4683 * @see #performHapticFeedback(int) 4684 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4685 */ 4686 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 4687 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 4688 } 4689 4690 /** 4691 * @return whether this view should have haptic feedback enabled for events 4692 * long presses. 4693 * 4694 * @see #setHapticFeedbackEnabled(boolean) 4695 * @see #performHapticFeedback(int) 4696 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4697 */ 4698 @ViewDebug.ExportedProperty 4699 public boolean isHapticFeedbackEnabled() { 4700 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 4701 } 4702 4703 /** 4704 * Returns the layout direction for this view. 4705 * 4706 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 4707 * {@link #LAYOUT_DIRECTION_RTL}, 4708 * {@link #LAYOUT_DIRECTION_INHERIT} or 4709 * {@link #LAYOUT_DIRECTION_LOCALE}. 4710 * @attr ref android.R.styleable#View_layoutDirection 4711 * 4712 * @hide 4713 */ 4714 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4715 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 4716 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 4717 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 4718 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 4719 }) 4720 public int getLayoutDirection() { 4721 return mViewFlags & LAYOUT_DIRECTION_MASK; 4722 } 4723 4724 /** 4725 * Set the layout direction for this view. This will propagate a reset of layout direction 4726 * resolution to the view's children and resolve layout direction for this view. 4727 * 4728 * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR}, 4729 * {@link #LAYOUT_DIRECTION_RTL}, 4730 * {@link #LAYOUT_DIRECTION_INHERIT} or 4731 * {@link #LAYOUT_DIRECTION_LOCALE}. 4732 * 4733 * @attr ref android.R.styleable#View_layoutDirection 4734 * 4735 * @hide 4736 */ 4737 @RemotableViewMethod 4738 public void setLayoutDirection(int layoutDirection) { 4739 if (getLayoutDirection() != layoutDirection) { 4740 resetResolvedLayoutDirection(); 4741 // Setting the flag will also request a layout. 4742 setFlags(layoutDirection, LAYOUT_DIRECTION_MASK); 4743 } 4744 } 4745 4746 /** 4747 * Returns the resolved layout direction for this view. 4748 * 4749 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 4750 * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL. 4751 * 4752 * @hide 4753 */ 4754 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4755 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 4756 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 4757 }) 4758 public int getResolvedLayoutDirection() { 4759 resolveLayoutDirectionIfNeeded(); 4760 return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ? 4761 LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 4762 } 4763 4764 /** 4765 * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from 4766 * layout attribute and/or the inherited value from the parent.</p> 4767 * 4768 * @return true if the layout is right-to-left. 4769 * 4770 * @hide 4771 */ 4772 @ViewDebug.ExportedProperty(category = "layout") 4773 public boolean isLayoutRtl() { 4774 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 4775 } 4776 4777 /** 4778 * If this view doesn't do any drawing on its own, set this flag to 4779 * allow further optimizations. By default, this flag is not set on 4780 * View, but could be set on some View subclasses such as ViewGroup. 4781 * 4782 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 4783 * you should clear this flag. 4784 * 4785 * @param willNotDraw whether or not this View draw on its own 4786 */ 4787 public void setWillNotDraw(boolean willNotDraw) { 4788 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 4789 } 4790 4791 /** 4792 * Returns whether or not this View draws on its own. 4793 * 4794 * @return true if this view has nothing to draw, false otherwise 4795 */ 4796 @ViewDebug.ExportedProperty(category = "drawing") 4797 public boolean willNotDraw() { 4798 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 4799 } 4800 4801 /** 4802 * When a View's drawing cache is enabled, drawing is redirected to an 4803 * offscreen bitmap. Some views, like an ImageView, must be able to 4804 * bypass this mechanism if they already draw a single bitmap, to avoid 4805 * unnecessary usage of the memory. 4806 * 4807 * @param willNotCacheDrawing true if this view does not cache its 4808 * drawing, false otherwise 4809 */ 4810 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 4811 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 4812 } 4813 4814 /** 4815 * Returns whether or not this View can cache its drawing or not. 4816 * 4817 * @return true if this view does not cache its drawing, false otherwise 4818 */ 4819 @ViewDebug.ExportedProperty(category = "drawing") 4820 public boolean willNotCacheDrawing() { 4821 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 4822 } 4823 4824 /** 4825 * Indicates whether this view reacts to click events or not. 4826 * 4827 * @return true if the view is clickable, false otherwise 4828 * 4829 * @see #setClickable(boolean) 4830 * @attr ref android.R.styleable#View_clickable 4831 */ 4832 @ViewDebug.ExportedProperty 4833 public boolean isClickable() { 4834 return (mViewFlags & CLICKABLE) == CLICKABLE; 4835 } 4836 4837 /** 4838 * Enables or disables click events for this view. When a view 4839 * is clickable it will change its state to "pressed" on every click. 4840 * Subclasses should set the view clickable to visually react to 4841 * user's clicks. 4842 * 4843 * @param clickable true to make the view clickable, false otherwise 4844 * 4845 * @see #isClickable() 4846 * @attr ref android.R.styleable#View_clickable 4847 */ 4848 public void setClickable(boolean clickable) { 4849 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 4850 } 4851 4852 /** 4853 * Indicates whether this view reacts to long click events or not. 4854 * 4855 * @return true if the view is long clickable, false otherwise 4856 * 4857 * @see #setLongClickable(boolean) 4858 * @attr ref android.R.styleable#View_longClickable 4859 */ 4860 public boolean isLongClickable() { 4861 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 4862 } 4863 4864 /** 4865 * Enables or disables long click events for this view. When a view is long 4866 * clickable it reacts to the user holding down the button for a longer 4867 * duration than a tap. This event can either launch the listener or a 4868 * context menu. 4869 * 4870 * @param longClickable true to make the view long clickable, false otherwise 4871 * @see #isLongClickable() 4872 * @attr ref android.R.styleable#View_longClickable 4873 */ 4874 public void setLongClickable(boolean longClickable) { 4875 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 4876 } 4877 4878 /** 4879 * Sets the pressed state for this view. 4880 * 4881 * @see #isClickable() 4882 * @see #setClickable(boolean) 4883 * 4884 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 4885 * the View's internal state from a previously set "pressed" state. 4886 */ 4887 public void setPressed(boolean pressed) { 4888 if (pressed) { 4889 mPrivateFlags |= PRESSED; 4890 } else { 4891 mPrivateFlags &= ~PRESSED; 4892 } 4893 refreshDrawableState(); 4894 dispatchSetPressed(pressed); 4895 } 4896 4897 /** 4898 * Dispatch setPressed to all of this View's children. 4899 * 4900 * @see #setPressed(boolean) 4901 * 4902 * @param pressed The new pressed state 4903 */ 4904 protected void dispatchSetPressed(boolean pressed) { 4905 } 4906 4907 /** 4908 * Indicates whether the view is currently in pressed state. Unless 4909 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 4910 * the pressed state. 4911 * 4912 * @see #setPressed(boolean) 4913 * @see #isClickable() 4914 * @see #setClickable(boolean) 4915 * 4916 * @return true if the view is currently pressed, false otherwise 4917 */ 4918 public boolean isPressed() { 4919 return (mPrivateFlags & PRESSED) == PRESSED; 4920 } 4921 4922 /** 4923 * Indicates whether this view will save its state (that is, 4924 * whether its {@link #onSaveInstanceState} method will be called). 4925 * 4926 * @return Returns true if the view state saving is enabled, else false. 4927 * 4928 * @see #setSaveEnabled(boolean) 4929 * @attr ref android.R.styleable#View_saveEnabled 4930 */ 4931 public boolean isSaveEnabled() { 4932 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 4933 } 4934 4935 /** 4936 * Controls whether the saving of this view's state is 4937 * enabled (that is, whether its {@link #onSaveInstanceState} method 4938 * will be called). Note that even if freezing is enabled, the 4939 * view still must have an id assigned to it (via {@link #setId(int)}) 4940 * for its state to be saved. This flag can only disable the 4941 * saving of this view; any child views may still have their state saved. 4942 * 4943 * @param enabled Set to false to <em>disable</em> state saving, or true 4944 * (the default) to allow it. 4945 * 4946 * @see #isSaveEnabled() 4947 * @see #setId(int) 4948 * @see #onSaveInstanceState() 4949 * @attr ref android.R.styleable#View_saveEnabled 4950 */ 4951 public void setSaveEnabled(boolean enabled) { 4952 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 4953 } 4954 4955 /** 4956 * Gets whether the framework should discard touches when the view's 4957 * window is obscured by another visible window. 4958 * Refer to the {@link View} security documentation for more details. 4959 * 4960 * @return True if touch filtering is enabled. 4961 * 4962 * @see #setFilterTouchesWhenObscured(boolean) 4963 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4964 */ 4965 @ViewDebug.ExportedProperty 4966 public boolean getFilterTouchesWhenObscured() { 4967 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 4968 } 4969 4970 /** 4971 * Sets whether the framework should discard touches when the view's 4972 * window is obscured by another visible window. 4973 * Refer to the {@link View} security documentation for more details. 4974 * 4975 * @param enabled True if touch filtering should be enabled. 4976 * 4977 * @see #getFilterTouchesWhenObscured 4978 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4979 */ 4980 public void setFilterTouchesWhenObscured(boolean enabled) { 4981 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 4982 FILTER_TOUCHES_WHEN_OBSCURED); 4983 } 4984 4985 /** 4986 * Indicates whether the entire hierarchy under this view will save its 4987 * state when a state saving traversal occurs from its parent. The default 4988 * is true; if false, these views will not be saved unless 4989 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4990 * 4991 * @return Returns true if the view state saving from parent is enabled, else false. 4992 * 4993 * @see #setSaveFromParentEnabled(boolean) 4994 */ 4995 public boolean isSaveFromParentEnabled() { 4996 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 4997 } 4998 4999 /** 5000 * Controls whether the entire hierarchy under this view will save its 5001 * state when a state saving traversal occurs from its parent. The default 5002 * is true; if false, these views will not be saved unless 5003 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 5004 * 5005 * @param enabled Set to false to <em>disable</em> state saving, or true 5006 * (the default) to allow it. 5007 * 5008 * @see #isSaveFromParentEnabled() 5009 * @see #setId(int) 5010 * @see #onSaveInstanceState() 5011 */ 5012 public void setSaveFromParentEnabled(boolean enabled) { 5013 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 5014 } 5015 5016 5017 /** 5018 * Returns whether this View is able to take focus. 5019 * 5020 * @return True if this view can take focus, or false otherwise. 5021 * @attr ref android.R.styleable#View_focusable 5022 */ 5023 @ViewDebug.ExportedProperty(category = "focus") 5024 public final boolean isFocusable() { 5025 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 5026 } 5027 5028 /** 5029 * When a view is focusable, it may not want to take focus when in touch mode. 5030 * For example, a button would like focus when the user is navigating via a D-pad 5031 * so that the user can click on it, but once the user starts touching the screen, 5032 * the button shouldn't take focus 5033 * @return Whether the view is focusable in touch mode. 5034 * @attr ref android.R.styleable#View_focusableInTouchMode 5035 */ 5036 @ViewDebug.ExportedProperty 5037 public final boolean isFocusableInTouchMode() { 5038 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 5039 } 5040 5041 /** 5042 * Find the nearest view in the specified direction that can take focus. 5043 * This does not actually give focus to that view. 5044 * 5045 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5046 * 5047 * @return The nearest focusable in the specified direction, or null if none 5048 * can be found. 5049 */ 5050 public View focusSearch(int direction) { 5051 if (mParent != null) { 5052 return mParent.focusSearch(this, direction); 5053 } else { 5054 return null; 5055 } 5056 } 5057 5058 /** 5059 * This method is the last chance for the focused view and its ancestors to 5060 * respond to an arrow key. This is called when the focused view did not 5061 * consume the key internally, nor could the view system find a new view in 5062 * the requested direction to give focus to. 5063 * 5064 * @param focused The currently focused view. 5065 * @param direction The direction focus wants to move. One of FOCUS_UP, 5066 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 5067 * @return True if the this view consumed this unhandled move. 5068 */ 5069 public boolean dispatchUnhandledMove(View focused, int direction) { 5070 return false; 5071 } 5072 5073 /** 5074 * If a user manually specified the next view id for a particular direction, 5075 * use the root to look up the view. 5076 * @param root The root view of the hierarchy containing this view. 5077 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 5078 * or FOCUS_BACKWARD. 5079 * @return The user specified next view, or null if there is none. 5080 */ 5081 View findUserSetNextFocus(View root, int direction) { 5082 switch (direction) { 5083 case FOCUS_LEFT: 5084 if (mNextFocusLeftId == View.NO_ID) return null; 5085 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 5086 case FOCUS_RIGHT: 5087 if (mNextFocusRightId == View.NO_ID) return null; 5088 return findViewInsideOutShouldExist(root, mNextFocusRightId); 5089 case FOCUS_UP: 5090 if (mNextFocusUpId == View.NO_ID) return null; 5091 return findViewInsideOutShouldExist(root, mNextFocusUpId); 5092 case FOCUS_DOWN: 5093 if (mNextFocusDownId == View.NO_ID) return null; 5094 return findViewInsideOutShouldExist(root, mNextFocusDownId); 5095 case FOCUS_FORWARD: 5096 if (mNextFocusForwardId == View.NO_ID) return null; 5097 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 5098 case FOCUS_BACKWARD: { 5099 final int id = mID; 5100 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5101 @Override 5102 public boolean apply(View t) { 5103 return t.mNextFocusForwardId == id; 5104 } 5105 }); 5106 } 5107 } 5108 return null; 5109 } 5110 5111 private View findViewInsideOutShouldExist(View root, final int childViewId) { 5112 View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5113 @Override 5114 public boolean apply(View t) { 5115 return t.mID == childViewId; 5116 } 5117 }); 5118 5119 if (result == null) { 5120 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified " 5121 + "by user for id " + childViewId); 5122 } 5123 return result; 5124 } 5125 5126 /** 5127 * Find and return all focusable views that are descendants of this view, 5128 * possibly including this view if it is focusable itself. 5129 * 5130 * @param direction The direction of the focus 5131 * @return A list of focusable views 5132 */ 5133 public ArrayList<View> getFocusables(int direction) { 5134 ArrayList<View> result = new ArrayList<View>(24); 5135 addFocusables(result, direction); 5136 return result; 5137 } 5138 5139 /** 5140 * Add any focusable views that are descendants of this view (possibly 5141 * including this view if it is focusable itself) to views. If we are in touch mode, 5142 * only add views that are also focusable in touch mode. 5143 * 5144 * @param views Focusable views found so far 5145 * @param direction The direction of the focus 5146 */ 5147 public void addFocusables(ArrayList<View> views, int direction) { 5148 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 5149 } 5150 5151 /** 5152 * Adds any focusable views that are descendants of this view (possibly 5153 * including this view if it is focusable itself) to views. This method 5154 * adds all focusable views regardless if we are in touch mode or 5155 * only views focusable in touch mode if we are in touch mode depending on 5156 * the focusable mode paramater. 5157 * 5158 * @param views Focusable views found so far or null if all we are interested is 5159 * the number of focusables. 5160 * @param direction The direction of the focus. 5161 * @param focusableMode The type of focusables to be added. 5162 * 5163 * @see #FOCUSABLES_ALL 5164 * @see #FOCUSABLES_TOUCH_MODE 5165 */ 5166 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 5167 if (!isFocusable()) { 5168 return; 5169 } 5170 5171 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 5172 isInTouchMode() && !isFocusableInTouchMode()) { 5173 return; 5174 } 5175 5176 if (views != null) { 5177 views.add(this); 5178 } 5179 } 5180 5181 /** 5182 * Finds the Views that contain given text. The containment is case insensitive. 5183 * The search is performed by either the text that the View renders or the content 5184 * description that describes the view for accessibility purposes and the view does 5185 * not render or both. Clients can specify how the search is to be performed via 5186 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 5187 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 5188 * 5189 * @param outViews The output list of matching Views. 5190 * @param searched The text to match against. 5191 * 5192 * @see #FIND_VIEWS_WITH_TEXT 5193 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 5194 * @see #setContentDescription(CharSequence) 5195 */ 5196 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 5197 if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 && !TextUtils.isEmpty(searched) 5198 && !TextUtils.isEmpty(mContentDescription)) { 5199 String searchedLowerCase = searched.toString().toLowerCase(); 5200 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 5201 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 5202 outViews.add(this); 5203 } 5204 } 5205 } 5206 5207 /** 5208 * Find and return all touchable views that are descendants of this view, 5209 * possibly including this view if it is touchable itself. 5210 * 5211 * @return A list of touchable views 5212 */ 5213 public ArrayList<View> getTouchables() { 5214 ArrayList<View> result = new ArrayList<View>(); 5215 addTouchables(result); 5216 return result; 5217 } 5218 5219 /** 5220 * Add any touchable views that are descendants of this view (possibly 5221 * including this view if it is touchable itself) to views. 5222 * 5223 * @param views Touchable views found so far 5224 */ 5225 public void addTouchables(ArrayList<View> views) { 5226 final int viewFlags = mViewFlags; 5227 5228 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 5229 && (viewFlags & ENABLED_MASK) == ENABLED) { 5230 views.add(this); 5231 } 5232 } 5233 5234 /** 5235 * Call this to try to give focus to a specific view or to one of its 5236 * descendants. 5237 * 5238 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5239 * false), or if it is focusable and it is not focusable in touch mode 5240 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5241 * 5242 * See also {@link #focusSearch(int)}, which is what you call to say that you 5243 * have focus, and you want your parent to look for the next one. 5244 * 5245 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 5246 * {@link #FOCUS_DOWN} and <code>null</code>. 5247 * 5248 * @return Whether this view or one of its descendants actually took focus. 5249 */ 5250 public final boolean requestFocus() { 5251 return requestFocus(View.FOCUS_DOWN); 5252 } 5253 5254 5255 /** 5256 * Call this to try to give focus to a specific view or to one of its 5257 * descendants and give it a hint about what direction focus is heading. 5258 * 5259 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5260 * false), or if it is focusable and it is not focusable in touch mode 5261 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5262 * 5263 * See also {@link #focusSearch(int)}, which is what you call to say that you 5264 * have focus, and you want your parent to look for the next one. 5265 * 5266 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 5267 * <code>null</code> set for the previously focused rectangle. 5268 * 5269 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5270 * @return Whether this view or one of its descendants actually took focus. 5271 */ 5272 public final boolean requestFocus(int direction) { 5273 return requestFocus(direction, null); 5274 } 5275 5276 /** 5277 * Call this to try to give focus to a specific view or to one of its descendants 5278 * and give it hints about the direction and a specific rectangle that the focus 5279 * is coming from. The rectangle can help give larger views a finer grained hint 5280 * about where focus is coming from, and therefore, where to show selection, or 5281 * forward focus change internally. 5282 * 5283 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5284 * false), or if it is focusable and it is not focusable in touch mode 5285 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5286 * 5287 * A View will not take focus if it is not visible. 5288 * 5289 * A View will not take focus if one of its parents has 5290 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 5291 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 5292 * 5293 * See also {@link #focusSearch(int)}, which is what you call to say that you 5294 * have focus, and you want your parent to look for the next one. 5295 * 5296 * You may wish to override this method if your custom {@link View} has an internal 5297 * {@link View} that it wishes to forward the request to. 5298 * 5299 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5300 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 5301 * to give a finer grained hint about where focus is coming from. May be null 5302 * if there is no hint. 5303 * @return Whether this view or one of its descendants actually took focus. 5304 */ 5305 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 5306 // need to be focusable 5307 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 5308 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5309 return false; 5310 } 5311 5312 // need to be focusable in touch mode if in touch mode 5313 if (isInTouchMode() && 5314 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 5315 return false; 5316 } 5317 5318 // need to not have any parents blocking us 5319 if (hasAncestorThatBlocksDescendantFocus()) { 5320 return false; 5321 } 5322 5323 handleFocusGainInternal(direction, previouslyFocusedRect); 5324 return true; 5325 } 5326 5327 /** Gets the ViewAncestor, or null if not attached. */ 5328 /*package*/ ViewRootImpl getViewRootImpl() { 5329 View root = getRootView(); 5330 return root != null ? (ViewRootImpl)root.getParent() : null; 5331 } 5332 5333 /** 5334 * Call this to try to give focus to a specific view or to one of its descendants. This is a 5335 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 5336 * touch mode to request focus when they are touched. 5337 * 5338 * @return Whether this view or one of its descendants actually took focus. 5339 * 5340 * @see #isInTouchMode() 5341 * 5342 */ 5343 public final boolean requestFocusFromTouch() { 5344 // Leave touch mode if we need to 5345 if (isInTouchMode()) { 5346 ViewRootImpl viewRoot = getViewRootImpl(); 5347 if (viewRoot != null) { 5348 viewRoot.ensureTouchMode(false); 5349 } 5350 } 5351 return requestFocus(View.FOCUS_DOWN); 5352 } 5353 5354 /** 5355 * @return Whether any ancestor of this view blocks descendant focus. 5356 */ 5357 private boolean hasAncestorThatBlocksDescendantFocus() { 5358 ViewParent ancestor = mParent; 5359 while (ancestor instanceof ViewGroup) { 5360 final ViewGroup vgAncestor = (ViewGroup) ancestor; 5361 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 5362 return true; 5363 } else { 5364 ancestor = vgAncestor.getParent(); 5365 } 5366 } 5367 return false; 5368 } 5369 5370 /** 5371 * @hide 5372 */ 5373 public void dispatchStartTemporaryDetach() { 5374 onStartTemporaryDetach(); 5375 } 5376 5377 /** 5378 * This is called when a container is going to temporarily detach a child, with 5379 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 5380 * It will either be followed by {@link #onFinishTemporaryDetach()} or 5381 * {@link #onDetachedFromWindow()} when the container is done. 5382 */ 5383 public void onStartTemporaryDetach() { 5384 removeUnsetPressCallback(); 5385 mPrivateFlags |= CANCEL_NEXT_UP_EVENT; 5386 } 5387 5388 /** 5389 * @hide 5390 */ 5391 public void dispatchFinishTemporaryDetach() { 5392 onFinishTemporaryDetach(); 5393 } 5394 5395 /** 5396 * Called after {@link #onStartTemporaryDetach} when the container is done 5397 * changing the view. 5398 */ 5399 public void onFinishTemporaryDetach() { 5400 } 5401 5402 /** 5403 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 5404 * for this view's window. Returns null if the view is not currently attached 5405 * to the window. Normally you will not need to use this directly, but 5406 * just use the standard high-level event callbacks like 5407 * {@link #onKeyDown(int, KeyEvent)}. 5408 */ 5409 public KeyEvent.DispatcherState getKeyDispatcherState() { 5410 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 5411 } 5412 5413 /** 5414 * Dispatch a key event before it is processed by any input method 5415 * associated with the view hierarchy. This can be used to intercept 5416 * key events in special situations before the IME consumes them; a 5417 * typical example would be handling the BACK key to update the application's 5418 * UI instead of allowing the IME to see it and close itself. 5419 * 5420 * @param event The key event to be dispatched. 5421 * @return True if the event was handled, false otherwise. 5422 */ 5423 public boolean dispatchKeyEventPreIme(KeyEvent event) { 5424 return onKeyPreIme(event.getKeyCode(), event); 5425 } 5426 5427 /** 5428 * Dispatch a key event to the next view on the focus path. This path runs 5429 * from the top of the view tree down to the currently focused view. If this 5430 * view has focus, it will dispatch to itself. Otherwise it will dispatch 5431 * the next node down the focus path. This method also fires any key 5432 * listeners. 5433 * 5434 * @param event The key event to be dispatched. 5435 * @return True if the event was handled, false otherwise. 5436 */ 5437 public boolean dispatchKeyEvent(KeyEvent event) { 5438 if (mInputEventConsistencyVerifier != null) { 5439 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 5440 } 5441 5442 // Give any attached key listener a first crack at the event. 5443 //noinspection SimplifiableIfStatement 5444 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5445 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 5446 return true; 5447 } 5448 5449 if (event.dispatch(this, mAttachInfo != null 5450 ? mAttachInfo.mKeyDispatchState : null, this)) { 5451 return true; 5452 } 5453 5454 if (mInputEventConsistencyVerifier != null) { 5455 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5456 } 5457 return false; 5458 } 5459 5460 /** 5461 * Dispatches a key shortcut event. 5462 * 5463 * @param event The key event to be dispatched. 5464 * @return True if the event was handled by the view, false otherwise. 5465 */ 5466 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 5467 return onKeyShortcut(event.getKeyCode(), event); 5468 } 5469 5470 /** 5471 * Pass the touch screen motion event down to the target view, or this 5472 * view if it is the target. 5473 * 5474 * @param event The motion event to be dispatched. 5475 * @return True if the event was handled by the view, false otherwise. 5476 */ 5477 public boolean dispatchTouchEvent(MotionEvent event) { 5478 if (mInputEventConsistencyVerifier != null) { 5479 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 5480 } 5481 5482 if (onFilterTouchEventForSecurity(event)) { 5483 //noinspection SimplifiableIfStatement 5484 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && 5485 mOnTouchListener.onTouch(this, event)) { 5486 return true; 5487 } 5488 5489 if (onTouchEvent(event)) { 5490 return true; 5491 } 5492 } 5493 5494 if (mInputEventConsistencyVerifier != null) { 5495 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5496 } 5497 return false; 5498 } 5499 5500 /** 5501 * Filter the touch event to apply security policies. 5502 * 5503 * @param event The motion event to be filtered. 5504 * @return True if the event should be dispatched, false if the event should be dropped. 5505 * 5506 * @see #getFilterTouchesWhenObscured 5507 */ 5508 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 5509 //noinspection RedundantIfStatement 5510 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 5511 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 5512 // Window is obscured, drop this touch. 5513 return false; 5514 } 5515 return true; 5516 } 5517 5518 /** 5519 * Pass a trackball motion event down to the focused view. 5520 * 5521 * @param event The motion event to be dispatched. 5522 * @return True if the event was handled by the view, false otherwise. 5523 */ 5524 public boolean dispatchTrackballEvent(MotionEvent event) { 5525 if (mInputEventConsistencyVerifier != null) { 5526 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 5527 } 5528 5529 return onTrackballEvent(event); 5530 } 5531 5532 /** 5533 * Dispatch a generic motion event. 5534 * <p> 5535 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5536 * are delivered to the view under the pointer. All other generic motion events are 5537 * delivered to the focused view. Hover events are handled specially and are delivered 5538 * to {@link #onHoverEvent(MotionEvent)}. 5539 * </p> 5540 * 5541 * @param event The motion event to be dispatched. 5542 * @return True if the event was handled by the view, false otherwise. 5543 */ 5544 public boolean dispatchGenericMotionEvent(MotionEvent event) { 5545 if (mInputEventConsistencyVerifier != null) { 5546 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 5547 } 5548 5549 final int source = event.getSource(); 5550 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5551 final int action = event.getAction(); 5552 if (action == MotionEvent.ACTION_HOVER_ENTER 5553 || action == MotionEvent.ACTION_HOVER_MOVE 5554 || action == MotionEvent.ACTION_HOVER_EXIT) { 5555 if (dispatchHoverEvent(event)) { 5556 return true; 5557 } 5558 } else if (dispatchGenericPointerEvent(event)) { 5559 return true; 5560 } 5561 } else if (dispatchGenericFocusedEvent(event)) { 5562 return true; 5563 } 5564 5565 if (dispatchGenericMotionEventInternal(event)) { 5566 return true; 5567 } 5568 5569 if (mInputEventConsistencyVerifier != null) { 5570 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5571 } 5572 return false; 5573 } 5574 5575 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 5576 //noinspection SimplifiableIfStatement 5577 if (mOnGenericMotionListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5578 && mOnGenericMotionListener.onGenericMotion(this, event)) { 5579 return true; 5580 } 5581 5582 if (onGenericMotionEvent(event)) { 5583 return true; 5584 } 5585 5586 if (mInputEventConsistencyVerifier != null) { 5587 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5588 } 5589 return false; 5590 } 5591 5592 /** 5593 * Dispatch a hover event. 5594 * <p> 5595 * Do not call this method directly. 5596 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5597 * </p> 5598 * 5599 * @param event The motion event to be dispatched. 5600 * @return True if the event was handled by the view, false otherwise. 5601 */ 5602 protected boolean dispatchHoverEvent(MotionEvent event) { 5603 //noinspection SimplifiableIfStatement 5604 if (mOnHoverListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5605 && mOnHoverListener.onHover(this, event)) { 5606 return true; 5607 } 5608 5609 return onHoverEvent(event); 5610 } 5611 5612 /** 5613 * Returns true if the view has a child to which it has recently sent 5614 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 5615 * it does not have a hovered child, then it must be the innermost hovered view. 5616 * @hide 5617 */ 5618 protected boolean hasHoveredChild() { 5619 return false; 5620 } 5621 5622 /** 5623 * Dispatch a generic motion event to the view under the first pointer. 5624 * <p> 5625 * Do not call this method directly. 5626 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5627 * </p> 5628 * 5629 * @param event The motion event to be dispatched. 5630 * @return True if the event was handled by the view, false otherwise. 5631 */ 5632 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 5633 return false; 5634 } 5635 5636 /** 5637 * Dispatch a generic motion event to the currently focused view. 5638 * <p> 5639 * Do not call this method directly. 5640 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5641 * </p> 5642 * 5643 * @param event The motion event to be dispatched. 5644 * @return True if the event was handled by the view, false otherwise. 5645 */ 5646 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 5647 return false; 5648 } 5649 5650 /** 5651 * Dispatch a pointer event. 5652 * <p> 5653 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 5654 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 5655 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 5656 * and should not be expected to handle other pointing device features. 5657 * </p> 5658 * 5659 * @param event The motion event to be dispatched. 5660 * @return True if the event was handled by the view, false otherwise. 5661 * @hide 5662 */ 5663 public final boolean dispatchPointerEvent(MotionEvent event) { 5664 if (event.isTouchEvent()) { 5665 return dispatchTouchEvent(event); 5666 } else { 5667 return dispatchGenericMotionEvent(event); 5668 } 5669 } 5670 5671 /** 5672 * Called when the window containing this view gains or loses window focus. 5673 * ViewGroups should override to route to their children. 5674 * 5675 * @param hasFocus True if the window containing this view now has focus, 5676 * false otherwise. 5677 */ 5678 public void dispatchWindowFocusChanged(boolean hasFocus) { 5679 onWindowFocusChanged(hasFocus); 5680 } 5681 5682 /** 5683 * Called when the window containing this view gains or loses focus. Note 5684 * that this is separate from view focus: to receive key events, both 5685 * your view and its window must have focus. If a window is displayed 5686 * on top of yours that takes input focus, then your own window will lose 5687 * focus but the view focus will remain unchanged. 5688 * 5689 * @param hasWindowFocus True if the window containing this view now has 5690 * focus, false otherwise. 5691 */ 5692 public void onWindowFocusChanged(boolean hasWindowFocus) { 5693 InputMethodManager imm = InputMethodManager.peekInstance(); 5694 if (!hasWindowFocus) { 5695 if (isPressed()) { 5696 setPressed(false); 5697 } 5698 if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5699 imm.focusOut(this); 5700 } 5701 removeLongPressCallback(); 5702 removeTapCallback(); 5703 onFocusLost(); 5704 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5705 imm.focusIn(this); 5706 } 5707 refreshDrawableState(); 5708 } 5709 5710 /** 5711 * Returns true if this view is in a window that currently has window focus. 5712 * Note that this is not the same as the view itself having focus. 5713 * 5714 * @return True if this view is in a window that currently has window focus. 5715 */ 5716 public boolean hasWindowFocus() { 5717 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 5718 } 5719 5720 /** 5721 * Dispatch a view visibility change down the view hierarchy. 5722 * ViewGroups should override to route to their children. 5723 * @param changedView The view whose visibility changed. Could be 'this' or 5724 * an ancestor view. 5725 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5726 * {@link #INVISIBLE} or {@link #GONE}. 5727 */ 5728 protected void dispatchVisibilityChanged(View changedView, int visibility) { 5729 onVisibilityChanged(changedView, visibility); 5730 } 5731 5732 /** 5733 * Called when the visibility of the view or an ancestor of the view is changed. 5734 * @param changedView The view whose visibility changed. Could be 'this' or 5735 * an ancestor view. 5736 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5737 * {@link #INVISIBLE} or {@link #GONE}. 5738 */ 5739 protected void onVisibilityChanged(View changedView, int visibility) { 5740 if (visibility == VISIBLE) { 5741 if (mAttachInfo != null) { 5742 initialAwakenScrollBars(); 5743 } else { 5744 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH; 5745 } 5746 } 5747 } 5748 5749 /** 5750 * Dispatch a hint about whether this view is displayed. For instance, when 5751 * a View moves out of the screen, it might receives a display hint indicating 5752 * the view is not displayed. Applications should not <em>rely</em> on this hint 5753 * as there is no guarantee that they will receive one. 5754 * 5755 * @param hint A hint about whether or not this view is displayed: 5756 * {@link #VISIBLE} or {@link #INVISIBLE}. 5757 */ 5758 public void dispatchDisplayHint(int hint) { 5759 onDisplayHint(hint); 5760 } 5761 5762 /** 5763 * Gives this view a hint about whether is displayed or not. For instance, when 5764 * a View moves out of the screen, it might receives a display hint indicating 5765 * the view is not displayed. Applications should not <em>rely</em> on this hint 5766 * as there is no guarantee that they will receive one. 5767 * 5768 * @param hint A hint about whether or not this view is displayed: 5769 * {@link #VISIBLE} or {@link #INVISIBLE}. 5770 */ 5771 protected void onDisplayHint(int hint) { 5772 } 5773 5774 /** 5775 * Dispatch a window visibility change down the view hierarchy. 5776 * ViewGroups should override to route to their children. 5777 * 5778 * @param visibility The new visibility of the window. 5779 * 5780 * @see #onWindowVisibilityChanged(int) 5781 */ 5782 public void dispatchWindowVisibilityChanged(int visibility) { 5783 onWindowVisibilityChanged(visibility); 5784 } 5785 5786 /** 5787 * Called when the window containing has change its visibility 5788 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 5789 * that this tells you whether or not your window is being made visible 5790 * to the window manager; this does <em>not</em> tell you whether or not 5791 * your window is obscured by other windows on the screen, even if it 5792 * is itself visible. 5793 * 5794 * @param visibility The new visibility of the window. 5795 */ 5796 protected void onWindowVisibilityChanged(int visibility) { 5797 if (visibility == VISIBLE) { 5798 initialAwakenScrollBars(); 5799 } 5800 } 5801 5802 /** 5803 * Returns the current visibility of the window this view is attached to 5804 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 5805 * 5806 * @return Returns the current visibility of the view's window. 5807 */ 5808 public int getWindowVisibility() { 5809 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 5810 } 5811 5812 /** 5813 * Retrieve the overall visible display size in which the window this view is 5814 * attached to has been positioned in. This takes into account screen 5815 * decorations above the window, for both cases where the window itself 5816 * is being position inside of them or the window is being placed under 5817 * then and covered insets are used for the window to position its content 5818 * inside. In effect, this tells you the available area where content can 5819 * be placed and remain visible to users. 5820 * 5821 * <p>This function requires an IPC back to the window manager to retrieve 5822 * the requested information, so should not be used in performance critical 5823 * code like drawing. 5824 * 5825 * @param outRect Filled in with the visible display frame. If the view 5826 * is not attached to a window, this is simply the raw display size. 5827 */ 5828 public void getWindowVisibleDisplayFrame(Rect outRect) { 5829 if (mAttachInfo != null) { 5830 try { 5831 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 5832 } catch (RemoteException e) { 5833 return; 5834 } 5835 // XXX This is really broken, and probably all needs to be done 5836 // in the window manager, and we need to know more about whether 5837 // we want the area behind or in front of the IME. 5838 final Rect insets = mAttachInfo.mVisibleInsets; 5839 outRect.left += insets.left; 5840 outRect.top += insets.top; 5841 outRect.right -= insets.right; 5842 outRect.bottom -= insets.bottom; 5843 return; 5844 } 5845 Display d = WindowManagerImpl.getDefault().getDefaultDisplay(); 5846 d.getRectSize(outRect); 5847 } 5848 5849 /** 5850 * Dispatch a notification about a resource configuration change down 5851 * the view hierarchy. 5852 * ViewGroups should override to route to their children. 5853 * 5854 * @param newConfig The new resource configuration. 5855 * 5856 * @see #onConfigurationChanged(android.content.res.Configuration) 5857 */ 5858 public void dispatchConfigurationChanged(Configuration newConfig) { 5859 onConfigurationChanged(newConfig); 5860 } 5861 5862 /** 5863 * Called when the current configuration of the resources being used 5864 * by the application have changed. You can use this to decide when 5865 * to reload resources that can changed based on orientation and other 5866 * configuration characterstics. You only need to use this if you are 5867 * not relying on the normal {@link android.app.Activity} mechanism of 5868 * recreating the activity instance upon a configuration change. 5869 * 5870 * @param newConfig The new resource configuration. 5871 */ 5872 protected void onConfigurationChanged(Configuration newConfig) { 5873 } 5874 5875 /** 5876 * Private function to aggregate all per-view attributes in to the view 5877 * root. 5878 */ 5879 void dispatchCollectViewAttributes(int visibility) { 5880 performCollectViewAttributes(visibility); 5881 } 5882 5883 void performCollectViewAttributes(int visibility) { 5884 if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) { 5885 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 5886 mAttachInfo.mKeepScreenOn = true; 5887 } 5888 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility; 5889 if (mOnSystemUiVisibilityChangeListener != null) { 5890 mAttachInfo.mHasSystemUiListeners = true; 5891 } 5892 } 5893 } 5894 5895 void needGlobalAttributesUpdate(boolean force) { 5896 final AttachInfo ai = mAttachInfo; 5897 if (ai != null) { 5898 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 5899 || ai.mHasSystemUiListeners) { 5900 ai.mRecomputeGlobalAttributes = true; 5901 } 5902 } 5903 } 5904 5905 /** 5906 * Returns whether the device is currently in touch mode. Touch mode is entered 5907 * once the user begins interacting with the device by touch, and affects various 5908 * things like whether focus is always visible to the user. 5909 * 5910 * @return Whether the device is in touch mode. 5911 */ 5912 @ViewDebug.ExportedProperty 5913 public boolean isInTouchMode() { 5914 if (mAttachInfo != null) { 5915 return mAttachInfo.mInTouchMode; 5916 } else { 5917 return ViewRootImpl.isInTouchMode(); 5918 } 5919 } 5920 5921 /** 5922 * Returns the context the view is running in, through which it can 5923 * access the current theme, resources, etc. 5924 * 5925 * @return The view's Context. 5926 */ 5927 @ViewDebug.CapturedViewProperty 5928 public final Context getContext() { 5929 return mContext; 5930 } 5931 5932 /** 5933 * Handle a key event before it is processed by any input method 5934 * associated with the view hierarchy. This can be used to intercept 5935 * key events in special situations before the IME consumes them; a 5936 * typical example would be handling the BACK key to update the application's 5937 * UI instead of allowing the IME to see it and close itself. 5938 * 5939 * @param keyCode The value in event.getKeyCode(). 5940 * @param event Description of the key event. 5941 * @return If you handled the event, return true. If you want to allow the 5942 * event to be handled by the next receiver, return false. 5943 */ 5944 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 5945 return false; 5946 } 5947 5948 /** 5949 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 5950 * KeyEvent.Callback.onKeyDown()}: perform press of the view 5951 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 5952 * is released, if the view is enabled and clickable. 5953 * 5954 * @param keyCode A key code that represents the button pressed, from 5955 * {@link android.view.KeyEvent}. 5956 * @param event The KeyEvent object that defines the button action. 5957 */ 5958 public boolean onKeyDown(int keyCode, KeyEvent event) { 5959 boolean result = false; 5960 5961 switch (keyCode) { 5962 case KeyEvent.KEYCODE_DPAD_CENTER: 5963 case KeyEvent.KEYCODE_ENTER: { 5964 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5965 return true; 5966 } 5967 // Long clickable items don't necessarily have to be clickable 5968 if (((mViewFlags & CLICKABLE) == CLICKABLE || 5969 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 5970 (event.getRepeatCount() == 0)) { 5971 setPressed(true); 5972 checkForLongClick(0); 5973 return true; 5974 } 5975 break; 5976 } 5977 } 5978 return result; 5979 } 5980 5981 /** 5982 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 5983 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 5984 * the event). 5985 */ 5986 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 5987 return false; 5988 } 5989 5990 /** 5991 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 5992 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 5993 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 5994 * {@link KeyEvent#KEYCODE_ENTER} is released. 5995 * 5996 * @param keyCode A key code that represents the button pressed, from 5997 * {@link android.view.KeyEvent}. 5998 * @param event The KeyEvent object that defines the button action. 5999 */ 6000 public boolean onKeyUp(int keyCode, KeyEvent event) { 6001 boolean result = false; 6002 6003 switch (keyCode) { 6004 case KeyEvent.KEYCODE_DPAD_CENTER: 6005 case KeyEvent.KEYCODE_ENTER: { 6006 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6007 return true; 6008 } 6009 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 6010 setPressed(false); 6011 6012 if (!mHasPerformedLongPress) { 6013 // This is a tap, so remove the longpress check 6014 removeLongPressCallback(); 6015 6016 result = performClick(); 6017 } 6018 } 6019 break; 6020 } 6021 } 6022 return result; 6023 } 6024 6025 /** 6026 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 6027 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 6028 * the event). 6029 * 6030 * @param keyCode A key code that represents the button pressed, from 6031 * {@link android.view.KeyEvent}. 6032 * @param repeatCount The number of times the action was made. 6033 * @param event The KeyEvent object that defines the button action. 6034 */ 6035 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 6036 return false; 6037 } 6038 6039 /** 6040 * Called on the focused view when a key shortcut event is not handled. 6041 * Override this method to implement local key shortcuts for the View. 6042 * Key shortcuts can also be implemented by setting the 6043 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 6044 * 6045 * @param keyCode The value in event.getKeyCode(). 6046 * @param event Description of the key event. 6047 * @return If you handled the event, return true. If you want to allow the 6048 * event to be handled by the next receiver, return false. 6049 */ 6050 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 6051 return false; 6052 } 6053 6054 /** 6055 * Check whether the called view is a text editor, in which case it 6056 * would make sense to automatically display a soft input window for 6057 * it. Subclasses should override this if they implement 6058 * {@link #onCreateInputConnection(EditorInfo)} to return true if 6059 * a call on that method would return a non-null InputConnection, and 6060 * they are really a first-class editor that the user would normally 6061 * start typing on when the go into a window containing your view. 6062 * 6063 * <p>The default implementation always returns false. This does 6064 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 6065 * will not be called or the user can not otherwise perform edits on your 6066 * view; it is just a hint to the system that this is not the primary 6067 * purpose of this view. 6068 * 6069 * @return Returns true if this view is a text editor, else false. 6070 */ 6071 public boolean onCheckIsTextEditor() { 6072 return false; 6073 } 6074 6075 /** 6076 * Create a new InputConnection for an InputMethod to interact 6077 * with the view. The default implementation returns null, since it doesn't 6078 * support input methods. You can override this to implement such support. 6079 * This is only needed for views that take focus and text input. 6080 * 6081 * <p>When implementing this, you probably also want to implement 6082 * {@link #onCheckIsTextEditor()} to indicate you will return a 6083 * non-null InputConnection. 6084 * 6085 * @param outAttrs Fill in with attribute information about the connection. 6086 */ 6087 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 6088 return null; 6089 } 6090 6091 /** 6092 * Called by the {@link android.view.inputmethod.InputMethodManager} 6093 * when a view who is not the current 6094 * input connection target is trying to make a call on the manager. The 6095 * default implementation returns false; you can override this to return 6096 * true for certain views if you are performing InputConnection proxying 6097 * to them. 6098 * @param view The View that is making the InputMethodManager call. 6099 * @return Return true to allow the call, false to reject. 6100 */ 6101 public boolean checkInputConnectionProxy(View view) { 6102 return false; 6103 } 6104 6105 /** 6106 * Show the context menu for this view. It is not safe to hold on to the 6107 * menu after returning from this method. 6108 * 6109 * You should normally not overload this method. Overload 6110 * {@link #onCreateContextMenu(ContextMenu)} or define an 6111 * {@link OnCreateContextMenuListener} to add items to the context menu. 6112 * 6113 * @param menu The context menu to populate 6114 */ 6115 public void createContextMenu(ContextMenu menu) { 6116 ContextMenuInfo menuInfo = getContextMenuInfo(); 6117 6118 // Sets the current menu info so all items added to menu will have 6119 // my extra info set. 6120 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 6121 6122 onCreateContextMenu(menu); 6123 if (mOnCreateContextMenuListener != null) { 6124 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 6125 } 6126 6127 // Clear the extra information so subsequent items that aren't mine don't 6128 // have my extra info. 6129 ((MenuBuilder)menu).setCurrentMenuInfo(null); 6130 6131 if (mParent != null) { 6132 mParent.createContextMenu(menu); 6133 } 6134 } 6135 6136 /** 6137 * Views should implement this if they have extra information to associate 6138 * with the context menu. The return result is supplied as a parameter to 6139 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 6140 * callback. 6141 * 6142 * @return Extra information about the item for which the context menu 6143 * should be shown. This information will vary across different 6144 * subclasses of View. 6145 */ 6146 protected ContextMenuInfo getContextMenuInfo() { 6147 return null; 6148 } 6149 6150 /** 6151 * Views should implement this if the view itself is going to add items to 6152 * the context menu. 6153 * 6154 * @param menu the context menu to populate 6155 */ 6156 protected void onCreateContextMenu(ContextMenu menu) { 6157 } 6158 6159 /** 6160 * Implement this method to handle trackball motion events. The 6161 * <em>relative</em> movement of the trackball since the last event 6162 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 6163 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 6164 * that a movement of 1 corresponds to the user pressing one DPAD key (so 6165 * they will often be fractional values, representing the more fine-grained 6166 * movement information available from a trackball). 6167 * 6168 * @param event The motion event. 6169 * @return True if the event was handled, false otherwise. 6170 */ 6171 public boolean onTrackballEvent(MotionEvent event) { 6172 return false; 6173 } 6174 6175 /** 6176 * Implement this method to handle generic motion events. 6177 * <p> 6178 * Generic motion events describe joystick movements, mouse hovers, track pad 6179 * touches, scroll wheel movements and other input events. The 6180 * {@link MotionEvent#getSource() source} of the motion event specifies 6181 * the class of input that was received. Implementations of this method 6182 * must examine the bits in the source before processing the event. 6183 * The following code example shows how this is done. 6184 * </p><p> 6185 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 6186 * are delivered to the view under the pointer. All other generic motion events are 6187 * delivered to the focused view. 6188 * </p> 6189 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 6190 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 6191 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 6192 * // process the joystick movement... 6193 * return true; 6194 * } 6195 * } 6196 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 6197 * switch (event.getAction()) { 6198 * case MotionEvent.ACTION_HOVER_MOVE: 6199 * // process the mouse hover movement... 6200 * return true; 6201 * case MotionEvent.ACTION_SCROLL: 6202 * // process the scroll wheel movement... 6203 * return true; 6204 * } 6205 * } 6206 * return super.onGenericMotionEvent(event); 6207 * }</pre> 6208 * 6209 * @param event The generic motion event being processed. 6210 * @return True if the event was handled, false otherwise. 6211 */ 6212 public boolean onGenericMotionEvent(MotionEvent event) { 6213 return false; 6214 } 6215 6216 /** 6217 * Implement this method to handle hover events. 6218 * <p> 6219 * This method is called whenever a pointer is hovering into, over, or out of the 6220 * bounds of a view and the view is not currently being touched. 6221 * Hover events are represented as pointer events with action 6222 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 6223 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 6224 * </p> 6225 * <ul> 6226 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 6227 * when the pointer enters the bounds of the view.</li> 6228 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 6229 * when the pointer has already entered the bounds of the view and has moved.</li> 6230 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 6231 * when the pointer has exited the bounds of the view or when the pointer is 6232 * about to go down due to a button click, tap, or similar user action that 6233 * causes the view to be touched.</li> 6234 * </ul> 6235 * <p> 6236 * The view should implement this method to return true to indicate that it is 6237 * handling the hover event, such as by changing its drawable state. 6238 * </p><p> 6239 * The default implementation calls {@link #setHovered} to update the hovered state 6240 * of the view when a hover enter or hover exit event is received, if the view 6241 * is enabled and is clickable. The default implementation also sends hover 6242 * accessibility events. 6243 * </p> 6244 * 6245 * @param event The motion event that describes the hover. 6246 * @return True if the view handled the hover event. 6247 * 6248 * @see #isHovered 6249 * @see #setHovered 6250 * @see #onHoverChanged 6251 */ 6252 public boolean onHoverEvent(MotionEvent event) { 6253 // The root view may receive hover (or touch) events that are outside the bounds of 6254 // the window. This code ensures that we only send accessibility events for 6255 // hovers that are actually within the bounds of the root view. 6256 final int action = event.getAction(); 6257 if (!mSendingHoverAccessibilityEvents) { 6258 if ((action == MotionEvent.ACTION_HOVER_ENTER 6259 || action == MotionEvent.ACTION_HOVER_MOVE) 6260 && !hasHoveredChild() 6261 && pointInView(event.getX(), event.getY())) { 6262 mSendingHoverAccessibilityEvents = true; 6263 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 6264 } 6265 } else { 6266 if (action == MotionEvent.ACTION_HOVER_EXIT 6267 || (action == MotionEvent.ACTION_HOVER_MOVE 6268 && !pointInView(event.getX(), event.getY()))) { 6269 mSendingHoverAccessibilityEvents = false; 6270 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 6271 } 6272 } 6273 6274 if (isHoverable()) { 6275 switch (action) { 6276 case MotionEvent.ACTION_HOVER_ENTER: 6277 setHovered(true); 6278 break; 6279 case MotionEvent.ACTION_HOVER_EXIT: 6280 setHovered(false); 6281 break; 6282 } 6283 6284 // Dispatch the event to onGenericMotionEvent before returning true. 6285 // This is to provide compatibility with existing applications that 6286 // handled HOVER_MOVE events in onGenericMotionEvent and that would 6287 // break because of the new default handling for hoverable views 6288 // in onHoverEvent. 6289 // Note that onGenericMotionEvent will be called by default when 6290 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 6291 dispatchGenericMotionEventInternal(event); 6292 return true; 6293 } 6294 return false; 6295 } 6296 6297 /** 6298 * Returns true if the view should handle {@link #onHoverEvent} 6299 * by calling {@link #setHovered} to change its hovered state. 6300 * 6301 * @return True if the view is hoverable. 6302 */ 6303 private boolean isHoverable() { 6304 final int viewFlags = mViewFlags; 6305 //noinspection SimplifiableIfStatement 6306 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6307 return false; 6308 } 6309 6310 return (viewFlags & CLICKABLE) == CLICKABLE 6311 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6312 } 6313 6314 /** 6315 * Returns true if the view is currently hovered. 6316 * 6317 * @return True if the view is currently hovered. 6318 * 6319 * @see #setHovered 6320 * @see #onHoverChanged 6321 */ 6322 @ViewDebug.ExportedProperty 6323 public boolean isHovered() { 6324 return (mPrivateFlags & HOVERED) != 0; 6325 } 6326 6327 /** 6328 * Sets whether the view is currently hovered. 6329 * <p> 6330 * Calling this method also changes the drawable state of the view. This 6331 * enables the view to react to hover by using different drawable resources 6332 * to change its appearance. 6333 * </p><p> 6334 * The {@link #onHoverChanged} method is called when the hovered state changes. 6335 * </p> 6336 * 6337 * @param hovered True if the view is hovered. 6338 * 6339 * @see #isHovered 6340 * @see #onHoverChanged 6341 */ 6342 public void setHovered(boolean hovered) { 6343 if (hovered) { 6344 if ((mPrivateFlags & HOVERED) == 0) { 6345 mPrivateFlags |= HOVERED; 6346 refreshDrawableState(); 6347 onHoverChanged(true); 6348 } 6349 } else { 6350 if ((mPrivateFlags & HOVERED) != 0) { 6351 mPrivateFlags &= ~HOVERED; 6352 refreshDrawableState(); 6353 onHoverChanged(false); 6354 } 6355 } 6356 } 6357 6358 /** 6359 * Implement this method to handle hover state changes. 6360 * <p> 6361 * This method is called whenever the hover state changes as a result of a 6362 * call to {@link #setHovered}. 6363 * </p> 6364 * 6365 * @param hovered The current hover state, as returned by {@link #isHovered}. 6366 * 6367 * @see #isHovered 6368 * @see #setHovered 6369 */ 6370 public void onHoverChanged(boolean hovered) { 6371 } 6372 6373 /** 6374 * Implement this method to handle touch screen motion events. 6375 * 6376 * @param event The motion event. 6377 * @return True if the event was handled, false otherwise. 6378 */ 6379 public boolean onTouchEvent(MotionEvent event) { 6380 final int viewFlags = mViewFlags; 6381 6382 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6383 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) { 6384 mPrivateFlags &= ~PRESSED; 6385 refreshDrawableState(); 6386 } 6387 // A disabled view that is clickable still consumes the touch 6388 // events, it just doesn't respond to them. 6389 return (((viewFlags & CLICKABLE) == CLICKABLE || 6390 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 6391 } 6392 6393 if (mTouchDelegate != null) { 6394 if (mTouchDelegate.onTouchEvent(event)) { 6395 return true; 6396 } 6397 } 6398 6399 if (((viewFlags & CLICKABLE) == CLICKABLE || 6400 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 6401 switch (event.getAction()) { 6402 case MotionEvent.ACTION_UP: 6403 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; 6404 if ((mPrivateFlags & PRESSED) != 0 || prepressed) { 6405 // take focus if we don't have it already and we should in 6406 // touch mode. 6407 boolean focusTaken = false; 6408 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 6409 focusTaken = requestFocus(); 6410 } 6411 6412 if (prepressed) { 6413 // The button is being released before we actually 6414 // showed it as pressed. Make it show the pressed 6415 // state now (before scheduling the click) to ensure 6416 // the user sees it. 6417 mPrivateFlags |= PRESSED; 6418 refreshDrawableState(); 6419 } 6420 6421 if (!mHasPerformedLongPress) { 6422 // This is a tap, so remove the longpress check 6423 removeLongPressCallback(); 6424 6425 // Only perform take click actions if we were in the pressed state 6426 if (!focusTaken) { 6427 // Use a Runnable and post this rather than calling 6428 // performClick directly. This lets other visual state 6429 // of the view update before click actions start. 6430 if (mPerformClick == null) { 6431 mPerformClick = new PerformClick(); 6432 } 6433 if (!post(mPerformClick)) { 6434 performClick(); 6435 } 6436 } 6437 } 6438 6439 if (mUnsetPressedState == null) { 6440 mUnsetPressedState = new UnsetPressedState(); 6441 } 6442 6443 if (prepressed) { 6444 postDelayed(mUnsetPressedState, 6445 ViewConfiguration.getPressedStateDuration()); 6446 } else if (!post(mUnsetPressedState)) { 6447 // If the post failed, unpress right now 6448 mUnsetPressedState.run(); 6449 } 6450 removeTapCallback(); 6451 } 6452 break; 6453 6454 case MotionEvent.ACTION_DOWN: 6455 mHasPerformedLongPress = false; 6456 6457 if (performButtonActionOnTouchDown(event)) { 6458 break; 6459 } 6460 6461 // Walk up the hierarchy to determine if we're inside a scrolling container. 6462 boolean isInScrollingContainer = isInScrollingContainer(); 6463 6464 // For views inside a scrolling container, delay the pressed feedback for 6465 // a short period in case this is a scroll. 6466 if (isInScrollingContainer) { 6467 mPrivateFlags |= PREPRESSED; 6468 if (mPendingCheckForTap == null) { 6469 mPendingCheckForTap = new CheckForTap(); 6470 } 6471 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 6472 } else { 6473 // Not inside a scrolling container, so show the feedback right away 6474 mPrivateFlags |= PRESSED; 6475 refreshDrawableState(); 6476 checkForLongClick(0); 6477 } 6478 break; 6479 6480 case MotionEvent.ACTION_CANCEL: 6481 mPrivateFlags &= ~PRESSED; 6482 refreshDrawableState(); 6483 removeTapCallback(); 6484 break; 6485 6486 case MotionEvent.ACTION_MOVE: 6487 final int x = (int) event.getX(); 6488 final int y = (int) event.getY(); 6489 6490 // Be lenient about moving outside of buttons 6491 if (!pointInView(x, y, mTouchSlop)) { 6492 // Outside button 6493 removeTapCallback(); 6494 if ((mPrivateFlags & PRESSED) != 0) { 6495 // Remove any future long press/tap checks 6496 removeLongPressCallback(); 6497 6498 // Need to switch from pressed to not pressed 6499 mPrivateFlags &= ~PRESSED; 6500 refreshDrawableState(); 6501 } 6502 } 6503 break; 6504 } 6505 return true; 6506 } 6507 6508 return false; 6509 } 6510 6511 /** 6512 * @hide 6513 */ 6514 public boolean isInScrollingContainer() { 6515 ViewParent p = getParent(); 6516 while (p != null && p instanceof ViewGroup) { 6517 if (((ViewGroup) p).shouldDelayChildPressedState()) { 6518 return true; 6519 } 6520 p = p.getParent(); 6521 } 6522 return false; 6523 } 6524 6525 /** 6526 * Remove the longpress detection timer. 6527 */ 6528 private void removeLongPressCallback() { 6529 if (mPendingCheckForLongPress != null) { 6530 removeCallbacks(mPendingCheckForLongPress); 6531 } 6532 } 6533 6534 /** 6535 * Remove the pending click action 6536 */ 6537 private void removePerformClickCallback() { 6538 if (mPerformClick != null) { 6539 removeCallbacks(mPerformClick); 6540 } 6541 } 6542 6543 /** 6544 * Remove the prepress detection timer. 6545 */ 6546 private void removeUnsetPressCallback() { 6547 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) { 6548 setPressed(false); 6549 removeCallbacks(mUnsetPressedState); 6550 } 6551 } 6552 6553 /** 6554 * Remove the tap detection timer. 6555 */ 6556 private void removeTapCallback() { 6557 if (mPendingCheckForTap != null) { 6558 mPrivateFlags &= ~PREPRESSED; 6559 removeCallbacks(mPendingCheckForTap); 6560 } 6561 } 6562 6563 /** 6564 * Cancels a pending long press. Your subclass can use this if you 6565 * want the context menu to come up if the user presses and holds 6566 * at the same place, but you don't want it to come up if they press 6567 * and then move around enough to cause scrolling. 6568 */ 6569 public void cancelLongPress() { 6570 removeLongPressCallback(); 6571 6572 /* 6573 * The prepressed state handled by the tap callback is a display 6574 * construct, but the tap callback will post a long press callback 6575 * less its own timeout. Remove it here. 6576 */ 6577 removeTapCallback(); 6578 } 6579 6580 /** 6581 * Remove the pending callback for sending a 6582 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 6583 */ 6584 private void removeSendViewScrolledAccessibilityEventCallback() { 6585 if (mSendViewScrolledAccessibilityEvent != null) { 6586 removeCallbacks(mSendViewScrolledAccessibilityEvent); 6587 } 6588 } 6589 6590 /** 6591 * Sets the TouchDelegate for this View. 6592 */ 6593 public void setTouchDelegate(TouchDelegate delegate) { 6594 mTouchDelegate = delegate; 6595 } 6596 6597 /** 6598 * Gets the TouchDelegate for this View. 6599 */ 6600 public TouchDelegate getTouchDelegate() { 6601 return mTouchDelegate; 6602 } 6603 6604 /** 6605 * Set flags controlling behavior of this view. 6606 * 6607 * @param flags Constant indicating the value which should be set 6608 * @param mask Constant indicating the bit range that should be changed 6609 */ 6610 void setFlags(int flags, int mask) { 6611 int old = mViewFlags; 6612 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 6613 6614 int changed = mViewFlags ^ old; 6615 if (changed == 0) { 6616 return; 6617 } 6618 int privateFlags = mPrivateFlags; 6619 6620 /* Check if the FOCUSABLE bit has changed */ 6621 if (((changed & FOCUSABLE_MASK) != 0) && 6622 ((privateFlags & HAS_BOUNDS) !=0)) { 6623 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 6624 && ((privateFlags & FOCUSED) != 0)) { 6625 /* Give up focus if we are no longer focusable */ 6626 clearFocus(); 6627 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 6628 && ((privateFlags & FOCUSED) == 0)) { 6629 /* 6630 * Tell the view system that we are now available to take focus 6631 * if no one else already has it. 6632 */ 6633 if (mParent != null) mParent.focusableViewAvailable(this); 6634 } 6635 } 6636 6637 if ((flags & VISIBILITY_MASK) == VISIBLE) { 6638 if ((changed & VISIBILITY_MASK) != 0) { 6639 /* 6640 * If this view is becoming visible, invalidate it in case it changed while 6641 * it was not visible. Marking it drawn ensures that the invalidation will 6642 * go through. 6643 */ 6644 mPrivateFlags |= DRAWN; 6645 invalidate(true); 6646 6647 needGlobalAttributesUpdate(true); 6648 6649 // a view becoming visible is worth notifying the parent 6650 // about in case nothing has focus. even if this specific view 6651 // isn't focusable, it may contain something that is, so let 6652 // the root view try to give this focus if nothing else does. 6653 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 6654 mParent.focusableViewAvailable(this); 6655 } 6656 } 6657 } 6658 6659 /* Check if the GONE bit has changed */ 6660 if ((changed & GONE) != 0) { 6661 needGlobalAttributesUpdate(false); 6662 requestLayout(); 6663 6664 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 6665 if (hasFocus()) clearFocus(); 6666 destroyDrawingCache(); 6667 if (mParent instanceof View) { 6668 // GONE views noop invalidation, so invalidate the parent 6669 ((View) mParent).invalidate(true); 6670 } 6671 // Mark the view drawn to ensure that it gets invalidated properly the next 6672 // time it is visible and gets invalidated 6673 mPrivateFlags |= DRAWN; 6674 } 6675 if (mAttachInfo != null) { 6676 mAttachInfo.mViewVisibilityChanged = true; 6677 } 6678 } 6679 6680 /* Check if the VISIBLE bit has changed */ 6681 if ((changed & INVISIBLE) != 0) { 6682 needGlobalAttributesUpdate(false); 6683 /* 6684 * If this view is becoming invisible, set the DRAWN flag so that 6685 * the next invalidate() will not be skipped. 6686 */ 6687 mPrivateFlags |= DRAWN; 6688 6689 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 6690 // root view becoming invisible shouldn't clear focus 6691 if (getRootView() != this) { 6692 clearFocus(); 6693 } 6694 } 6695 if (mAttachInfo != null) { 6696 mAttachInfo.mViewVisibilityChanged = true; 6697 } 6698 } 6699 6700 if ((changed & VISIBILITY_MASK) != 0) { 6701 if (mParent instanceof ViewGroup) { 6702 ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6703 ((View) mParent).invalidate(true); 6704 } else if (mParent != null) { 6705 mParent.invalidateChild(this, null); 6706 } 6707 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6708 } 6709 6710 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 6711 destroyDrawingCache(); 6712 } 6713 6714 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 6715 destroyDrawingCache(); 6716 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6717 invalidateParentCaches(); 6718 } 6719 6720 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 6721 destroyDrawingCache(); 6722 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6723 } 6724 6725 if ((changed & DRAW_MASK) != 0) { 6726 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 6727 if (mBGDrawable != null) { 6728 mPrivateFlags &= ~SKIP_DRAW; 6729 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 6730 } else { 6731 mPrivateFlags |= SKIP_DRAW; 6732 } 6733 } else { 6734 mPrivateFlags &= ~SKIP_DRAW; 6735 } 6736 requestLayout(); 6737 invalidate(true); 6738 } 6739 6740 if ((changed & KEEP_SCREEN_ON) != 0) { 6741 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 6742 mParent.recomputeViewAttributes(this); 6743 } 6744 } 6745 6746 if ((changed & LAYOUT_DIRECTION_MASK) != 0) { 6747 requestLayout(); 6748 } 6749 } 6750 6751 /** 6752 * Change the view's z order in the tree, so it's on top of other sibling 6753 * views 6754 */ 6755 public void bringToFront() { 6756 if (mParent != null) { 6757 mParent.bringChildToFront(this); 6758 } 6759 } 6760 6761 /** 6762 * This is called in response to an internal scroll in this view (i.e., the 6763 * view scrolled its own contents). This is typically as a result of 6764 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 6765 * called. 6766 * 6767 * @param l Current horizontal scroll origin. 6768 * @param t Current vertical scroll origin. 6769 * @param oldl Previous horizontal scroll origin. 6770 * @param oldt Previous vertical scroll origin. 6771 */ 6772 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 6773 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6774 postSendViewScrolledAccessibilityEventCallback(); 6775 } 6776 6777 mBackgroundSizeChanged = true; 6778 6779 final AttachInfo ai = mAttachInfo; 6780 if (ai != null) { 6781 ai.mViewScrollChanged = true; 6782 } 6783 } 6784 6785 /** 6786 * Interface definition for a callback to be invoked when the layout bounds of a view 6787 * changes due to layout processing. 6788 */ 6789 public interface OnLayoutChangeListener { 6790 /** 6791 * Called when the focus state of a view has changed. 6792 * 6793 * @param v The view whose state has changed. 6794 * @param left The new value of the view's left property. 6795 * @param top The new value of the view's top property. 6796 * @param right The new value of the view's right property. 6797 * @param bottom The new value of the view's bottom property. 6798 * @param oldLeft The previous value of the view's left property. 6799 * @param oldTop The previous value of the view's top property. 6800 * @param oldRight The previous value of the view's right property. 6801 * @param oldBottom The previous value of the view's bottom property. 6802 */ 6803 void onLayoutChange(View v, int left, int top, int right, int bottom, 6804 int oldLeft, int oldTop, int oldRight, int oldBottom); 6805 } 6806 6807 /** 6808 * This is called during layout when the size of this view has changed. If 6809 * you were just added to the view hierarchy, you're called with the old 6810 * values of 0. 6811 * 6812 * @param w Current width of this view. 6813 * @param h Current height of this view. 6814 * @param oldw Old width of this view. 6815 * @param oldh Old height of this view. 6816 */ 6817 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 6818 } 6819 6820 /** 6821 * Called by draw to draw the child views. This may be overridden 6822 * by derived classes to gain control just before its children are drawn 6823 * (but after its own view has been drawn). 6824 * @param canvas the canvas on which to draw the view 6825 */ 6826 protected void dispatchDraw(Canvas canvas) { 6827 } 6828 6829 /** 6830 * Gets the parent of this view. Note that the parent is a 6831 * ViewParent and not necessarily a View. 6832 * 6833 * @return Parent of this view. 6834 */ 6835 public final ViewParent getParent() { 6836 return mParent; 6837 } 6838 6839 /** 6840 * Set the horizontal scrolled position of your view. This will cause a call to 6841 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6842 * invalidated. 6843 * @param value the x position to scroll to 6844 */ 6845 public void setScrollX(int value) { 6846 scrollTo(value, mScrollY); 6847 } 6848 6849 /** 6850 * Set the vertical scrolled position of your view. This will cause a call to 6851 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6852 * invalidated. 6853 * @param value the y position to scroll to 6854 */ 6855 public void setScrollY(int value) { 6856 scrollTo(mScrollX, value); 6857 } 6858 6859 /** 6860 * Return the scrolled left position of this view. This is the left edge of 6861 * the displayed part of your view. You do not need to draw any pixels 6862 * farther left, since those are outside of the frame of your view on 6863 * screen. 6864 * 6865 * @return The left edge of the displayed part of your view, in pixels. 6866 */ 6867 public final int getScrollX() { 6868 return mScrollX; 6869 } 6870 6871 /** 6872 * Return the scrolled top position of this view. This is the top edge of 6873 * the displayed part of your view. You do not need to draw any pixels above 6874 * it, since those are outside of the frame of your view on screen. 6875 * 6876 * @return The top edge of the displayed part of your view, in pixels. 6877 */ 6878 public final int getScrollY() { 6879 return mScrollY; 6880 } 6881 6882 /** 6883 * Return the width of the your view. 6884 * 6885 * @return The width of your view, in pixels. 6886 */ 6887 @ViewDebug.ExportedProperty(category = "layout") 6888 public final int getWidth() { 6889 return mRight - mLeft; 6890 } 6891 6892 /** 6893 * Return the height of your view. 6894 * 6895 * @return The height of your view, in pixels. 6896 */ 6897 @ViewDebug.ExportedProperty(category = "layout") 6898 public final int getHeight() { 6899 return mBottom - mTop; 6900 } 6901 6902 /** 6903 * Return the visible drawing bounds of your view. Fills in the output 6904 * rectangle with the values from getScrollX(), getScrollY(), 6905 * getWidth(), and getHeight(). 6906 * 6907 * @param outRect The (scrolled) drawing bounds of the view. 6908 */ 6909 public void getDrawingRect(Rect outRect) { 6910 outRect.left = mScrollX; 6911 outRect.top = mScrollY; 6912 outRect.right = mScrollX + (mRight - mLeft); 6913 outRect.bottom = mScrollY + (mBottom - mTop); 6914 } 6915 6916 /** 6917 * Like {@link #getMeasuredWidthAndState()}, but only returns the 6918 * raw width component (that is the result is masked by 6919 * {@link #MEASURED_SIZE_MASK}). 6920 * 6921 * @return The raw measured width of this view. 6922 */ 6923 public final int getMeasuredWidth() { 6924 return mMeasuredWidth & MEASURED_SIZE_MASK; 6925 } 6926 6927 /** 6928 * Return the full width measurement information for this view as computed 6929 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6930 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6931 * This should be used during measurement and layout calculations only. Use 6932 * {@link #getWidth()} to see how wide a view is after layout. 6933 * 6934 * @return The measured width of this view as a bit mask. 6935 */ 6936 public final int getMeasuredWidthAndState() { 6937 return mMeasuredWidth; 6938 } 6939 6940 /** 6941 * Like {@link #getMeasuredHeightAndState()}, but only returns the 6942 * raw width component (that is the result is masked by 6943 * {@link #MEASURED_SIZE_MASK}). 6944 * 6945 * @return The raw measured height of this view. 6946 */ 6947 public final int getMeasuredHeight() { 6948 return mMeasuredHeight & MEASURED_SIZE_MASK; 6949 } 6950 6951 /** 6952 * Return the full height measurement information for this view as computed 6953 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6954 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6955 * This should be used during measurement and layout calculations only. Use 6956 * {@link #getHeight()} to see how wide a view is after layout. 6957 * 6958 * @return The measured width of this view as a bit mask. 6959 */ 6960 public final int getMeasuredHeightAndState() { 6961 return mMeasuredHeight; 6962 } 6963 6964 /** 6965 * Return only the state bits of {@link #getMeasuredWidthAndState()} 6966 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 6967 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 6968 * and the height component is at the shifted bits 6969 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 6970 */ 6971 public final int getMeasuredState() { 6972 return (mMeasuredWidth&MEASURED_STATE_MASK) 6973 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 6974 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 6975 } 6976 6977 /** 6978 * The transform matrix of this view, which is calculated based on the current 6979 * roation, scale, and pivot properties. 6980 * 6981 * @see #getRotation() 6982 * @see #getScaleX() 6983 * @see #getScaleY() 6984 * @see #getPivotX() 6985 * @see #getPivotY() 6986 * @return The current transform matrix for the view 6987 */ 6988 public Matrix getMatrix() { 6989 if (mTransformationInfo != null) { 6990 updateMatrix(); 6991 return mTransformationInfo.mMatrix; 6992 } 6993 return Matrix.IDENTITY_MATRIX; 6994 } 6995 6996 /** 6997 * Utility function to determine if the value is far enough away from zero to be 6998 * considered non-zero. 6999 * @param value A floating point value to check for zero-ness 7000 * @return whether the passed-in value is far enough away from zero to be considered non-zero 7001 */ 7002 private static boolean nonzero(float value) { 7003 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 7004 } 7005 7006 /** 7007 * Returns true if the transform matrix is the identity matrix. 7008 * Recomputes the matrix if necessary. 7009 * 7010 * @return True if the transform matrix is the identity matrix, false otherwise. 7011 */ 7012 final boolean hasIdentityMatrix() { 7013 if (mTransformationInfo != null) { 7014 updateMatrix(); 7015 return mTransformationInfo.mMatrixIsIdentity; 7016 } 7017 return true; 7018 } 7019 7020 void ensureTransformationInfo() { 7021 if (mTransformationInfo == null) { 7022 mTransformationInfo = new TransformationInfo(); 7023 } 7024 } 7025 7026 /** 7027 * Recomputes the transform matrix if necessary. 7028 */ 7029 private void updateMatrix() { 7030 final TransformationInfo info = mTransformationInfo; 7031 if (info == null) { 7032 return; 7033 } 7034 if (info.mMatrixDirty) { 7035 // transform-related properties have changed since the last time someone 7036 // asked for the matrix; recalculate it with the current values 7037 7038 // Figure out if we need to update the pivot point 7039 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7040 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 7041 info.mPrevWidth = mRight - mLeft; 7042 info.mPrevHeight = mBottom - mTop; 7043 info.mPivotX = info.mPrevWidth / 2f; 7044 info.mPivotY = info.mPrevHeight / 2f; 7045 } 7046 } 7047 info.mMatrix.reset(); 7048 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 7049 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 7050 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 7051 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 7052 } else { 7053 if (info.mCamera == null) { 7054 info.mCamera = new Camera(); 7055 info.matrix3D = new Matrix(); 7056 } 7057 info.mCamera.save(); 7058 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 7059 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 7060 info.mCamera.getMatrix(info.matrix3D); 7061 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 7062 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 7063 info.mPivotY + info.mTranslationY); 7064 info.mMatrix.postConcat(info.matrix3D); 7065 info.mCamera.restore(); 7066 } 7067 info.mMatrixDirty = false; 7068 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 7069 info.mInverseMatrixDirty = true; 7070 } 7071 } 7072 7073 /** 7074 * Utility method to retrieve the inverse of the current mMatrix property. 7075 * We cache the matrix to avoid recalculating it when transform properties 7076 * have not changed. 7077 * 7078 * @return The inverse of the current matrix of this view. 7079 */ 7080 final Matrix getInverseMatrix() { 7081 final TransformationInfo info = mTransformationInfo; 7082 if (info != null) { 7083 updateMatrix(); 7084 if (info.mInverseMatrixDirty) { 7085 if (info.mInverseMatrix == null) { 7086 info.mInverseMatrix = new Matrix(); 7087 } 7088 info.mMatrix.invert(info.mInverseMatrix); 7089 info.mInverseMatrixDirty = false; 7090 } 7091 return info.mInverseMatrix; 7092 } 7093 return Matrix.IDENTITY_MATRIX; 7094 } 7095 7096 /** 7097 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 7098 * views are drawn) from the camera to this view. The camera's distance 7099 * affects 3D transformations, for instance rotations around the X and Y 7100 * axis. If the rotationX or rotationY properties are changed and this view is 7101 * large (more than half the size of the screen), it is recommended to always 7102 * use a camera distance that's greater than the height (X axis rotation) or 7103 * the width (Y axis rotation) of this view.</p> 7104 * 7105 * <p>The distance of the camera from the view plane can have an affect on the 7106 * perspective distortion of the view when it is rotated around the x or y axis. 7107 * For example, a large distance will result in a large viewing angle, and there 7108 * will not be much perspective distortion of the view as it rotates. A short 7109 * distance may cause much more perspective distortion upon rotation, and can 7110 * also result in some drawing artifacts if the rotated view ends up partially 7111 * behind the camera (which is why the recommendation is to use a distance at 7112 * least as far as the size of the view, if the view is to be rotated.)</p> 7113 * 7114 * <p>The distance is expressed in "depth pixels." The default distance depends 7115 * on the screen density. For instance, on a medium density display, the 7116 * default distance is 1280. On a high density display, the default distance 7117 * is 1920.</p> 7118 * 7119 * <p>If you want to specify a distance that leads to visually consistent 7120 * results across various densities, use the following formula:</p> 7121 * <pre> 7122 * float scale = context.getResources().getDisplayMetrics().density; 7123 * view.setCameraDistance(distance * scale); 7124 * </pre> 7125 * 7126 * <p>The density scale factor of a high density display is 1.5, 7127 * and 1920 = 1280 * 1.5.</p> 7128 * 7129 * @param distance The distance in "depth pixels", if negative the opposite 7130 * value is used 7131 * 7132 * @see #setRotationX(float) 7133 * @see #setRotationY(float) 7134 */ 7135 public void setCameraDistance(float distance) { 7136 invalidateParentCaches(); 7137 invalidate(false); 7138 7139 ensureTransformationInfo(); 7140 final float dpi = mResources.getDisplayMetrics().densityDpi; 7141 final TransformationInfo info = mTransformationInfo; 7142 if (info.mCamera == null) { 7143 info.mCamera = new Camera(); 7144 info.matrix3D = new Matrix(); 7145 } 7146 7147 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 7148 info.mMatrixDirty = true; 7149 7150 invalidate(false); 7151 } 7152 7153 /** 7154 * The degrees that the view is rotated around the pivot point. 7155 * 7156 * @see #setRotation(float) 7157 * @see #getPivotX() 7158 * @see #getPivotY() 7159 * 7160 * @return The degrees of rotation. 7161 */ 7162 public float getRotation() { 7163 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 7164 } 7165 7166 /** 7167 * Sets the degrees that the view is rotated around the pivot point. Increasing values 7168 * result in clockwise rotation. 7169 * 7170 * @param rotation The degrees of rotation. 7171 * 7172 * @see #getRotation() 7173 * @see #getPivotX() 7174 * @see #getPivotY() 7175 * @see #setRotationX(float) 7176 * @see #setRotationY(float) 7177 * 7178 * @attr ref android.R.styleable#View_rotation 7179 */ 7180 public void setRotation(float rotation) { 7181 ensureTransformationInfo(); 7182 final TransformationInfo info = mTransformationInfo; 7183 if (info.mRotation != rotation) { 7184 invalidateParentCaches(); 7185 // Double-invalidation is necessary to capture view's old and new areas 7186 invalidate(false); 7187 info.mRotation = rotation; 7188 info.mMatrixDirty = true; 7189 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7190 invalidate(false); 7191 } 7192 } 7193 7194 /** 7195 * The degrees that the view is rotated around the vertical axis through the pivot point. 7196 * 7197 * @see #getPivotX() 7198 * @see #getPivotY() 7199 * @see #setRotationY(float) 7200 * 7201 * @return The degrees of Y rotation. 7202 */ 7203 public float getRotationY() { 7204 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 7205 } 7206 7207 /** 7208 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 7209 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 7210 * down the y axis. 7211 * 7212 * When rotating large views, it is recommended to adjust the camera distance 7213 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 7214 * 7215 * @param rotationY The degrees of Y rotation. 7216 * 7217 * @see #getRotationY() 7218 * @see #getPivotX() 7219 * @see #getPivotY() 7220 * @see #setRotation(float) 7221 * @see #setRotationX(float) 7222 * @see #setCameraDistance(float) 7223 * 7224 * @attr ref android.R.styleable#View_rotationY 7225 */ 7226 public void setRotationY(float rotationY) { 7227 ensureTransformationInfo(); 7228 final TransformationInfo info = mTransformationInfo; 7229 if (info.mRotationY != rotationY) { 7230 invalidateParentCaches(); 7231 // Double-invalidation is necessary to capture view's old and new areas 7232 invalidate(false); 7233 info.mRotationY = rotationY; 7234 info.mMatrixDirty = true; 7235 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7236 invalidate(false); 7237 } 7238 } 7239 7240 /** 7241 * The degrees that the view is rotated around the horizontal axis through the pivot point. 7242 * 7243 * @see #getPivotX() 7244 * @see #getPivotY() 7245 * @see #setRotationX(float) 7246 * 7247 * @return The degrees of X rotation. 7248 */ 7249 public float getRotationX() { 7250 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 7251 } 7252 7253 /** 7254 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 7255 * Increasing values result in clockwise rotation from the viewpoint of looking down the 7256 * x axis. 7257 * 7258 * When rotating large views, it is recommended to adjust the camera distance 7259 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 7260 * 7261 * @param rotationX The degrees of X rotation. 7262 * 7263 * @see #getRotationX() 7264 * @see #getPivotX() 7265 * @see #getPivotY() 7266 * @see #setRotation(float) 7267 * @see #setRotationY(float) 7268 * @see #setCameraDistance(float) 7269 * 7270 * @attr ref android.R.styleable#View_rotationX 7271 */ 7272 public void setRotationX(float rotationX) { 7273 ensureTransformationInfo(); 7274 final TransformationInfo info = mTransformationInfo; 7275 if (info.mRotationX != rotationX) { 7276 invalidateParentCaches(); 7277 // Double-invalidation is necessary to capture view's old and new areas 7278 invalidate(false); 7279 info.mRotationX = rotationX; 7280 info.mMatrixDirty = true; 7281 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7282 invalidate(false); 7283 } 7284 } 7285 7286 /** 7287 * The amount that the view is scaled in x around the pivot point, as a proportion of 7288 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 7289 * 7290 * <p>By default, this is 1.0f. 7291 * 7292 * @see #getPivotX() 7293 * @see #getPivotY() 7294 * @return The scaling factor. 7295 */ 7296 public float getScaleX() { 7297 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 7298 } 7299 7300 /** 7301 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 7302 * the view's unscaled width. A value of 1 means that no scaling is applied. 7303 * 7304 * @param scaleX The scaling factor. 7305 * @see #getPivotX() 7306 * @see #getPivotY() 7307 * 7308 * @attr ref android.R.styleable#View_scaleX 7309 */ 7310 public void setScaleX(float scaleX) { 7311 ensureTransformationInfo(); 7312 final TransformationInfo info = mTransformationInfo; 7313 if (info.mScaleX != scaleX) { 7314 invalidateParentCaches(); 7315 // Double-invalidation is necessary to capture view's old and new areas 7316 invalidate(false); 7317 info.mScaleX = scaleX; 7318 info.mMatrixDirty = true; 7319 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7320 invalidate(false); 7321 } 7322 } 7323 7324 /** 7325 * The amount that the view is scaled in y around the pivot point, as a proportion of 7326 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 7327 * 7328 * <p>By default, this is 1.0f. 7329 * 7330 * @see #getPivotX() 7331 * @see #getPivotY() 7332 * @return The scaling factor. 7333 */ 7334 public float getScaleY() { 7335 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 7336 } 7337 7338 /** 7339 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 7340 * the view's unscaled width. A value of 1 means that no scaling is applied. 7341 * 7342 * @param scaleY The scaling factor. 7343 * @see #getPivotX() 7344 * @see #getPivotY() 7345 * 7346 * @attr ref android.R.styleable#View_scaleY 7347 */ 7348 public void setScaleY(float scaleY) { 7349 ensureTransformationInfo(); 7350 final TransformationInfo info = mTransformationInfo; 7351 if (info.mScaleY != scaleY) { 7352 invalidateParentCaches(); 7353 // Double-invalidation is necessary to capture view's old and new areas 7354 invalidate(false); 7355 info.mScaleY = scaleY; 7356 info.mMatrixDirty = true; 7357 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7358 invalidate(false); 7359 } 7360 } 7361 7362 /** 7363 * The x location of the point around which the view is {@link #setRotation(float) rotated} 7364 * and {@link #setScaleX(float) scaled}. 7365 * 7366 * @see #getRotation() 7367 * @see #getScaleX() 7368 * @see #getScaleY() 7369 * @see #getPivotY() 7370 * @return The x location of the pivot point. 7371 */ 7372 public float getPivotX() { 7373 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 7374 } 7375 7376 /** 7377 * Sets the x location of the point around which the view is 7378 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 7379 * By default, the pivot point is centered on the object. 7380 * Setting this property disables this behavior and causes the view to use only the 7381 * explicitly set pivotX and pivotY values. 7382 * 7383 * @param pivotX The x location of the pivot point. 7384 * @see #getRotation() 7385 * @see #getScaleX() 7386 * @see #getScaleY() 7387 * @see #getPivotY() 7388 * 7389 * @attr ref android.R.styleable#View_transformPivotX 7390 */ 7391 public void setPivotX(float pivotX) { 7392 ensureTransformationInfo(); 7393 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7394 final TransformationInfo info = mTransformationInfo; 7395 if (info.mPivotX != pivotX) { 7396 invalidateParentCaches(); 7397 // Double-invalidation is necessary to capture view's old and new areas 7398 invalidate(false); 7399 info.mPivotX = pivotX; 7400 info.mMatrixDirty = true; 7401 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7402 invalidate(false); 7403 } 7404 } 7405 7406 /** 7407 * The y location of the point around which the view is {@link #setRotation(float) rotated} 7408 * and {@link #setScaleY(float) scaled}. 7409 * 7410 * @see #getRotation() 7411 * @see #getScaleX() 7412 * @see #getScaleY() 7413 * @see #getPivotY() 7414 * @return The y location of the pivot point. 7415 */ 7416 public float getPivotY() { 7417 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 7418 } 7419 7420 /** 7421 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 7422 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 7423 * Setting this property disables this behavior and causes the view to use only the 7424 * explicitly set pivotX and pivotY values. 7425 * 7426 * @param pivotY The y location of the pivot point. 7427 * @see #getRotation() 7428 * @see #getScaleX() 7429 * @see #getScaleY() 7430 * @see #getPivotY() 7431 * 7432 * @attr ref android.R.styleable#View_transformPivotY 7433 */ 7434 public void setPivotY(float pivotY) { 7435 ensureTransformationInfo(); 7436 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7437 final TransformationInfo info = mTransformationInfo; 7438 if (info.mPivotY != pivotY) { 7439 invalidateParentCaches(); 7440 // Double-invalidation is necessary to capture view's old and new areas 7441 invalidate(false); 7442 info.mPivotY = pivotY; 7443 info.mMatrixDirty = true; 7444 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7445 invalidate(false); 7446 } 7447 } 7448 7449 /** 7450 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 7451 * completely transparent and 1 means the view is completely opaque. 7452 * 7453 * <p>By default this is 1.0f. 7454 * @return The opacity of the view. 7455 */ 7456 public float getAlpha() { 7457 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 7458 } 7459 7460 /** 7461 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 7462 * completely transparent and 1 means the view is completely opaque.</p> 7463 * 7464 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 7465 * responsible for applying the opacity itself. Otherwise, calling this method is 7466 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 7467 * setting a hardware layer.</p> 7468 * 7469 * @param alpha The opacity of the view. 7470 * 7471 * @see #setLayerType(int, android.graphics.Paint) 7472 * 7473 * @attr ref android.R.styleable#View_alpha 7474 */ 7475 public void setAlpha(float alpha) { 7476 ensureTransformationInfo(); 7477 mTransformationInfo.mAlpha = alpha; 7478 invalidateParentCaches(); 7479 if (onSetAlpha((int) (alpha * 255))) { 7480 mPrivateFlags |= ALPHA_SET; 7481 // subclass is handling alpha - don't optimize rendering cache invalidation 7482 invalidate(true); 7483 } else { 7484 mPrivateFlags &= ~ALPHA_SET; 7485 invalidate(false); 7486 } 7487 } 7488 7489 /** 7490 * Faster version of setAlpha() which performs the same steps except there are 7491 * no calls to invalidate(). The caller of this function should perform proper invalidation 7492 * on the parent and this object. The return value indicates whether the subclass handles 7493 * alpha (the return value for onSetAlpha()). 7494 * 7495 * @param alpha The new value for the alpha property 7496 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) 7497 */ 7498 boolean setAlphaNoInvalidation(float alpha) { 7499 ensureTransformationInfo(); 7500 mTransformationInfo.mAlpha = alpha; 7501 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 7502 if (subclassHandlesAlpha) { 7503 mPrivateFlags |= ALPHA_SET; 7504 } else { 7505 mPrivateFlags &= ~ALPHA_SET; 7506 } 7507 return subclassHandlesAlpha; 7508 } 7509 7510 /** 7511 * Top position of this view relative to its parent. 7512 * 7513 * @return The top of this view, in pixels. 7514 */ 7515 @ViewDebug.CapturedViewProperty 7516 public final int getTop() { 7517 return mTop; 7518 } 7519 7520 /** 7521 * Sets the top position of this view relative to its parent. This method is meant to be called 7522 * by the layout system and should not generally be called otherwise, because the property 7523 * may be changed at any time by the layout. 7524 * 7525 * @param top The top of this view, in pixels. 7526 */ 7527 public final void setTop(int top) { 7528 if (top != mTop) { 7529 updateMatrix(); 7530 final boolean matrixIsIdentity = mTransformationInfo == null 7531 || mTransformationInfo.mMatrixIsIdentity; 7532 if (matrixIsIdentity) { 7533 if (mAttachInfo != null) { 7534 int minTop; 7535 int yLoc; 7536 if (top < mTop) { 7537 minTop = top; 7538 yLoc = top - mTop; 7539 } else { 7540 minTop = mTop; 7541 yLoc = 0; 7542 } 7543 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 7544 } 7545 } else { 7546 // Double-invalidation is necessary to capture view's old and new areas 7547 invalidate(true); 7548 } 7549 7550 int width = mRight - mLeft; 7551 int oldHeight = mBottom - mTop; 7552 7553 mTop = top; 7554 7555 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7556 7557 if (!matrixIsIdentity) { 7558 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7559 // A change in dimension means an auto-centered pivot point changes, too 7560 mTransformationInfo.mMatrixDirty = true; 7561 } 7562 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7563 invalidate(true); 7564 } 7565 mBackgroundSizeChanged = true; 7566 invalidateParentIfNeeded(); 7567 } 7568 } 7569 7570 /** 7571 * Bottom position of this view relative to its parent. 7572 * 7573 * @return The bottom of this view, in pixels. 7574 */ 7575 @ViewDebug.CapturedViewProperty 7576 public final int getBottom() { 7577 return mBottom; 7578 } 7579 7580 /** 7581 * True if this view has changed since the last time being drawn. 7582 * 7583 * @return The dirty state of this view. 7584 */ 7585 public boolean isDirty() { 7586 return (mPrivateFlags & DIRTY_MASK) != 0; 7587 } 7588 7589 /** 7590 * Sets the bottom position of this view relative to its parent. This method is meant to be 7591 * called by the layout system and should not generally be called otherwise, because the 7592 * property may be changed at any time by the layout. 7593 * 7594 * @param bottom The bottom of this view, in pixels. 7595 */ 7596 public final void setBottom(int bottom) { 7597 if (bottom != mBottom) { 7598 updateMatrix(); 7599 final boolean matrixIsIdentity = mTransformationInfo == null 7600 || mTransformationInfo.mMatrixIsIdentity; 7601 if (matrixIsIdentity) { 7602 if (mAttachInfo != null) { 7603 int maxBottom; 7604 if (bottom < mBottom) { 7605 maxBottom = mBottom; 7606 } else { 7607 maxBottom = bottom; 7608 } 7609 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 7610 } 7611 } else { 7612 // Double-invalidation is necessary to capture view's old and new areas 7613 invalidate(true); 7614 } 7615 7616 int width = mRight - mLeft; 7617 int oldHeight = mBottom - mTop; 7618 7619 mBottom = bottom; 7620 7621 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7622 7623 if (!matrixIsIdentity) { 7624 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7625 // A change in dimension means an auto-centered pivot point changes, too 7626 mTransformationInfo.mMatrixDirty = true; 7627 } 7628 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7629 invalidate(true); 7630 } 7631 mBackgroundSizeChanged = true; 7632 invalidateParentIfNeeded(); 7633 } 7634 } 7635 7636 /** 7637 * Left position of this view relative to its parent. 7638 * 7639 * @return The left edge of this view, in pixels. 7640 */ 7641 @ViewDebug.CapturedViewProperty 7642 public final int getLeft() { 7643 return mLeft; 7644 } 7645 7646 /** 7647 * Sets the left position of this view relative to its parent. This method is meant to be called 7648 * by the layout system and should not generally be called otherwise, because the property 7649 * may be changed at any time by the layout. 7650 * 7651 * @param left The bottom of this view, in pixels. 7652 */ 7653 public final void setLeft(int left) { 7654 if (left != mLeft) { 7655 updateMatrix(); 7656 final boolean matrixIsIdentity = mTransformationInfo == null 7657 || mTransformationInfo.mMatrixIsIdentity; 7658 if (matrixIsIdentity) { 7659 if (mAttachInfo != null) { 7660 int minLeft; 7661 int xLoc; 7662 if (left < mLeft) { 7663 minLeft = left; 7664 xLoc = left - mLeft; 7665 } else { 7666 minLeft = mLeft; 7667 xLoc = 0; 7668 } 7669 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 7670 } 7671 } else { 7672 // Double-invalidation is necessary to capture view's old and new areas 7673 invalidate(true); 7674 } 7675 7676 int oldWidth = mRight - mLeft; 7677 int height = mBottom - mTop; 7678 7679 mLeft = left; 7680 7681 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7682 7683 if (!matrixIsIdentity) { 7684 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7685 // A change in dimension means an auto-centered pivot point changes, too 7686 mTransformationInfo.mMatrixDirty = true; 7687 } 7688 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7689 invalidate(true); 7690 } 7691 mBackgroundSizeChanged = true; 7692 invalidateParentIfNeeded(); 7693 } 7694 } 7695 7696 /** 7697 * Right position of this view relative to its parent. 7698 * 7699 * @return The right edge of this view, in pixels. 7700 */ 7701 @ViewDebug.CapturedViewProperty 7702 public final int getRight() { 7703 return mRight; 7704 } 7705 7706 /** 7707 * Sets the right position of this view relative to its parent. This method is meant to be called 7708 * by the layout system and should not generally be called otherwise, because the property 7709 * may be changed at any time by the layout. 7710 * 7711 * @param right The bottom of this view, in pixels. 7712 */ 7713 public final void setRight(int right) { 7714 if (right != mRight) { 7715 updateMatrix(); 7716 final boolean matrixIsIdentity = mTransformationInfo == null 7717 || mTransformationInfo.mMatrixIsIdentity; 7718 if (matrixIsIdentity) { 7719 if (mAttachInfo != null) { 7720 int maxRight; 7721 if (right < mRight) { 7722 maxRight = mRight; 7723 } else { 7724 maxRight = right; 7725 } 7726 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 7727 } 7728 } else { 7729 // Double-invalidation is necessary to capture view's old and new areas 7730 invalidate(true); 7731 } 7732 7733 int oldWidth = mRight - mLeft; 7734 int height = mBottom - mTop; 7735 7736 mRight = right; 7737 7738 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7739 7740 if (!matrixIsIdentity) { 7741 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7742 // A change in dimension means an auto-centered pivot point changes, too 7743 mTransformationInfo.mMatrixDirty = true; 7744 } 7745 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7746 invalidate(true); 7747 } 7748 mBackgroundSizeChanged = true; 7749 invalidateParentIfNeeded(); 7750 } 7751 } 7752 7753 /** 7754 * The visual x position of this view, in pixels. This is equivalent to the 7755 * {@link #setTranslationX(float) translationX} property plus the current 7756 * {@link #getLeft() left} property. 7757 * 7758 * @return The visual x position of this view, in pixels. 7759 */ 7760 public float getX() { 7761 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 7762 } 7763 7764 /** 7765 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 7766 * {@link #setTranslationX(float) translationX} property to be the difference between 7767 * the x value passed in and the current {@link #getLeft() left} property. 7768 * 7769 * @param x The visual x position of this view, in pixels. 7770 */ 7771 public void setX(float x) { 7772 setTranslationX(x - mLeft); 7773 } 7774 7775 /** 7776 * The visual y position of this view, in pixels. This is equivalent to the 7777 * {@link #setTranslationY(float) translationY} property plus the current 7778 * {@link #getTop() top} property. 7779 * 7780 * @return The visual y position of this view, in pixels. 7781 */ 7782 public float getY() { 7783 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 7784 } 7785 7786 /** 7787 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 7788 * {@link #setTranslationY(float) translationY} property to be the difference between 7789 * the y value passed in and the current {@link #getTop() top} property. 7790 * 7791 * @param y The visual y position of this view, in pixels. 7792 */ 7793 public void setY(float y) { 7794 setTranslationY(y - mTop); 7795 } 7796 7797 7798 /** 7799 * The horizontal location of this view relative to its {@link #getLeft() left} position. 7800 * This position is post-layout, in addition to wherever the object's 7801 * layout placed it. 7802 * 7803 * @return The horizontal position of this view relative to its left position, in pixels. 7804 */ 7805 public float getTranslationX() { 7806 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 7807 } 7808 7809 /** 7810 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 7811 * This effectively positions the object post-layout, in addition to wherever the object's 7812 * layout placed it. 7813 * 7814 * @param translationX The horizontal position of this view relative to its left position, 7815 * in pixels. 7816 * 7817 * @attr ref android.R.styleable#View_translationX 7818 */ 7819 public void setTranslationX(float translationX) { 7820 ensureTransformationInfo(); 7821 final TransformationInfo info = mTransformationInfo; 7822 if (info.mTranslationX != translationX) { 7823 invalidateParentCaches(); 7824 // Double-invalidation is necessary to capture view's old and new areas 7825 invalidate(false); 7826 info.mTranslationX = translationX; 7827 info.mMatrixDirty = true; 7828 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7829 invalidate(false); 7830 } 7831 } 7832 7833 /** 7834 * The horizontal location of this view relative to its {@link #getTop() top} position. 7835 * This position is post-layout, in addition to wherever the object's 7836 * layout placed it. 7837 * 7838 * @return The vertical position of this view relative to its top position, 7839 * in pixels. 7840 */ 7841 public float getTranslationY() { 7842 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 7843 } 7844 7845 /** 7846 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 7847 * This effectively positions the object post-layout, in addition to wherever the object's 7848 * layout placed it. 7849 * 7850 * @param translationY The vertical position of this view relative to its top position, 7851 * in pixels. 7852 * 7853 * @attr ref android.R.styleable#View_translationY 7854 */ 7855 public void setTranslationY(float translationY) { 7856 ensureTransformationInfo(); 7857 final TransformationInfo info = mTransformationInfo; 7858 if (info.mTranslationY != translationY) { 7859 invalidateParentCaches(); 7860 // Double-invalidation is necessary to capture view's old and new areas 7861 invalidate(false); 7862 info.mTranslationY = translationY; 7863 info.mMatrixDirty = true; 7864 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7865 invalidate(false); 7866 } 7867 } 7868 7869 /** 7870 * @hide 7871 */ 7872 public void setFastTranslationX(float x) { 7873 ensureTransformationInfo(); 7874 final TransformationInfo info = mTransformationInfo; 7875 info.mTranslationX = x; 7876 info.mMatrixDirty = true; 7877 } 7878 7879 /** 7880 * @hide 7881 */ 7882 public void setFastTranslationY(float y) { 7883 ensureTransformationInfo(); 7884 final TransformationInfo info = mTransformationInfo; 7885 info.mTranslationY = y; 7886 info.mMatrixDirty = true; 7887 } 7888 7889 /** 7890 * @hide 7891 */ 7892 public void setFastX(float x) { 7893 ensureTransformationInfo(); 7894 final TransformationInfo info = mTransformationInfo; 7895 info.mTranslationX = x - mLeft; 7896 info.mMatrixDirty = true; 7897 } 7898 7899 /** 7900 * @hide 7901 */ 7902 public void setFastY(float y) { 7903 ensureTransformationInfo(); 7904 final TransformationInfo info = mTransformationInfo; 7905 info.mTranslationY = y - mTop; 7906 info.mMatrixDirty = true; 7907 } 7908 7909 /** 7910 * @hide 7911 */ 7912 public void setFastScaleX(float x) { 7913 ensureTransformationInfo(); 7914 final TransformationInfo info = mTransformationInfo; 7915 info.mScaleX = x; 7916 info.mMatrixDirty = true; 7917 } 7918 7919 /** 7920 * @hide 7921 */ 7922 public void setFastScaleY(float y) { 7923 ensureTransformationInfo(); 7924 final TransformationInfo info = mTransformationInfo; 7925 info.mScaleY = y; 7926 info.mMatrixDirty = true; 7927 } 7928 7929 /** 7930 * @hide 7931 */ 7932 public void setFastAlpha(float alpha) { 7933 ensureTransformationInfo(); 7934 mTransformationInfo.mAlpha = alpha; 7935 } 7936 7937 /** 7938 * @hide 7939 */ 7940 public void setFastRotationY(float y) { 7941 ensureTransformationInfo(); 7942 final TransformationInfo info = mTransformationInfo; 7943 info.mRotationY = y; 7944 info.mMatrixDirty = true; 7945 } 7946 7947 /** 7948 * Hit rectangle in parent's coordinates 7949 * 7950 * @param outRect The hit rectangle of the view. 7951 */ 7952 public void getHitRect(Rect outRect) { 7953 updateMatrix(); 7954 final TransformationInfo info = mTransformationInfo; 7955 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 7956 outRect.set(mLeft, mTop, mRight, mBottom); 7957 } else { 7958 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 7959 tmpRect.set(-info.mPivotX, -info.mPivotY, 7960 getWidth() - info.mPivotX, getHeight() - info.mPivotY); 7961 info.mMatrix.mapRect(tmpRect); 7962 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 7963 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 7964 } 7965 } 7966 7967 /** 7968 * Determines whether the given point, in local coordinates is inside the view. 7969 */ 7970 /*package*/ final boolean pointInView(float localX, float localY) { 7971 return localX >= 0 && localX < (mRight - mLeft) 7972 && localY >= 0 && localY < (mBottom - mTop); 7973 } 7974 7975 /** 7976 * Utility method to determine whether the given point, in local coordinates, 7977 * is inside the view, where the area of the view is expanded by the slop factor. 7978 * This method is called while processing touch-move events to determine if the event 7979 * is still within the view. 7980 */ 7981 private boolean pointInView(float localX, float localY, float slop) { 7982 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 7983 localY < ((mBottom - mTop) + slop); 7984 } 7985 7986 /** 7987 * When a view has focus and the user navigates away from it, the next view is searched for 7988 * starting from the rectangle filled in by this method. 7989 * 7990 * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)}) 7991 * of the view. However, if your view maintains some idea of internal selection, 7992 * such as a cursor, or a selected row or column, you should override this method and 7993 * fill in a more specific rectangle. 7994 * 7995 * @param r The rectangle to fill in, in this view's coordinates. 7996 */ 7997 public void getFocusedRect(Rect r) { 7998 getDrawingRect(r); 7999 } 8000 8001 /** 8002 * If some part of this view is not clipped by any of its parents, then 8003 * return that area in r in global (root) coordinates. To convert r to local 8004 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x, 8005 * -globalOffset.y)) If the view is completely clipped or translated out, 8006 * return false. 8007 * 8008 * @param r If true is returned, r holds the global coordinates of the 8009 * visible portion of this view. 8010 * @param globalOffset If true is returned, globalOffset holds the dx,dy 8011 * between this view and its root. globalOffet may be null. 8012 * @return true if r is non-empty (i.e. part of the view is visible at the 8013 * root level. 8014 */ 8015 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 8016 int width = mRight - mLeft; 8017 int height = mBottom - mTop; 8018 if (width > 0 && height > 0) { 8019 r.set(0, 0, width, height); 8020 if (globalOffset != null) { 8021 globalOffset.set(-mScrollX, -mScrollY); 8022 } 8023 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 8024 } 8025 return false; 8026 } 8027 8028 public final boolean getGlobalVisibleRect(Rect r) { 8029 return getGlobalVisibleRect(r, null); 8030 } 8031 8032 public final boolean getLocalVisibleRect(Rect r) { 8033 Point offset = new Point(); 8034 if (getGlobalVisibleRect(r, offset)) { 8035 r.offset(-offset.x, -offset.y); // make r local 8036 return true; 8037 } 8038 return false; 8039 } 8040 8041 /** 8042 * Offset this view's vertical location by the specified number of pixels. 8043 * 8044 * @param offset the number of pixels to offset the view by 8045 */ 8046 public void offsetTopAndBottom(int offset) { 8047 if (offset != 0) { 8048 updateMatrix(); 8049 final boolean matrixIsIdentity = mTransformationInfo == null 8050 || mTransformationInfo.mMatrixIsIdentity; 8051 if (matrixIsIdentity) { 8052 final ViewParent p = mParent; 8053 if (p != null && mAttachInfo != null) { 8054 final Rect r = mAttachInfo.mTmpInvalRect; 8055 int minTop; 8056 int maxBottom; 8057 int yLoc; 8058 if (offset < 0) { 8059 minTop = mTop + offset; 8060 maxBottom = mBottom; 8061 yLoc = offset; 8062 } else { 8063 minTop = mTop; 8064 maxBottom = mBottom + offset; 8065 yLoc = 0; 8066 } 8067 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 8068 p.invalidateChild(this, r); 8069 } 8070 } else { 8071 invalidate(false); 8072 } 8073 8074 mTop += offset; 8075 mBottom += offset; 8076 8077 if (!matrixIsIdentity) { 8078 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8079 invalidate(false); 8080 } 8081 invalidateParentIfNeeded(); 8082 } 8083 } 8084 8085 /** 8086 * Offset this view's horizontal location by the specified amount of pixels. 8087 * 8088 * @param offset the numer of pixels to offset the view by 8089 */ 8090 public void offsetLeftAndRight(int offset) { 8091 if (offset != 0) { 8092 updateMatrix(); 8093 final boolean matrixIsIdentity = mTransformationInfo == null 8094 || mTransformationInfo.mMatrixIsIdentity; 8095 if (matrixIsIdentity) { 8096 final ViewParent p = mParent; 8097 if (p != null && mAttachInfo != null) { 8098 final Rect r = mAttachInfo.mTmpInvalRect; 8099 int minLeft; 8100 int maxRight; 8101 if (offset < 0) { 8102 minLeft = mLeft + offset; 8103 maxRight = mRight; 8104 } else { 8105 minLeft = mLeft; 8106 maxRight = mRight + offset; 8107 } 8108 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 8109 p.invalidateChild(this, r); 8110 } 8111 } else { 8112 invalidate(false); 8113 } 8114 8115 mLeft += offset; 8116 mRight += offset; 8117 8118 if (!matrixIsIdentity) { 8119 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8120 invalidate(false); 8121 } 8122 invalidateParentIfNeeded(); 8123 } 8124 } 8125 8126 /** 8127 * Get the LayoutParams associated with this view. All views should have 8128 * layout parameters. These supply parameters to the <i>parent</i> of this 8129 * view specifying how it should be arranged. There are many subclasses of 8130 * ViewGroup.LayoutParams, and these correspond to the different subclasses 8131 * of ViewGroup that are responsible for arranging their children. 8132 * 8133 * This method may return null if this View is not attached to a parent 8134 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 8135 * was not invoked successfully. When a View is attached to a parent 8136 * ViewGroup, this method must not return null. 8137 * 8138 * @return The LayoutParams associated with this view, or null if no 8139 * parameters have been set yet 8140 */ 8141 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 8142 public ViewGroup.LayoutParams getLayoutParams() { 8143 return mLayoutParams; 8144 } 8145 8146 /** 8147 * Set the layout parameters associated with this view. These supply 8148 * parameters to the <i>parent</i> of this view specifying how it should be 8149 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 8150 * correspond to the different subclasses of ViewGroup that are responsible 8151 * for arranging their children. 8152 * 8153 * @param params The layout parameters for this view, cannot be null 8154 */ 8155 public void setLayoutParams(ViewGroup.LayoutParams params) { 8156 if (params == null) { 8157 throw new NullPointerException("Layout parameters cannot be null"); 8158 } 8159 mLayoutParams = params; 8160 requestLayout(); 8161 } 8162 8163 /** 8164 * Set the scrolled position of your view. This will cause a call to 8165 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8166 * invalidated. 8167 * @param x the x position to scroll to 8168 * @param y the y position to scroll to 8169 */ 8170 public void scrollTo(int x, int y) { 8171 if (mScrollX != x || mScrollY != y) { 8172 int oldX = mScrollX; 8173 int oldY = mScrollY; 8174 mScrollX = x; 8175 mScrollY = y; 8176 invalidateParentCaches(); 8177 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 8178 if (!awakenScrollBars()) { 8179 invalidate(true); 8180 } 8181 } 8182 } 8183 8184 /** 8185 * Move the scrolled position of your view. This will cause a call to 8186 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8187 * invalidated. 8188 * @param x the amount of pixels to scroll by horizontally 8189 * @param y the amount of pixels to scroll by vertically 8190 */ 8191 public void scrollBy(int x, int y) { 8192 scrollTo(mScrollX + x, mScrollY + y); 8193 } 8194 8195 /** 8196 * <p>Trigger the scrollbars to draw. When invoked this method starts an 8197 * animation to fade the scrollbars out after a default delay. If a subclass 8198 * provides animated scrolling, the start delay should equal the duration 8199 * of the scrolling animation.</p> 8200 * 8201 * <p>The animation starts only if at least one of the scrollbars is 8202 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 8203 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8204 * this method returns true, and false otherwise. If the animation is 8205 * started, this method calls {@link #invalidate()}; in that case the 8206 * caller should not call {@link #invalidate()}.</p> 8207 * 8208 * <p>This method should be invoked every time a subclass directly updates 8209 * the scroll parameters.</p> 8210 * 8211 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 8212 * and {@link #scrollTo(int, int)}.</p> 8213 * 8214 * @return true if the animation is played, false otherwise 8215 * 8216 * @see #awakenScrollBars(int) 8217 * @see #scrollBy(int, int) 8218 * @see #scrollTo(int, int) 8219 * @see #isHorizontalScrollBarEnabled() 8220 * @see #isVerticalScrollBarEnabled() 8221 * @see #setHorizontalScrollBarEnabled(boolean) 8222 * @see #setVerticalScrollBarEnabled(boolean) 8223 */ 8224 protected boolean awakenScrollBars() { 8225 return mScrollCache != null && 8226 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 8227 } 8228 8229 /** 8230 * Trigger the scrollbars to draw. 8231 * This method differs from awakenScrollBars() only in its default duration. 8232 * initialAwakenScrollBars() will show the scroll bars for longer than 8233 * usual to give the user more of a chance to notice them. 8234 * 8235 * @return true if the animation is played, false otherwise. 8236 */ 8237 private boolean initialAwakenScrollBars() { 8238 return mScrollCache != null && 8239 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 8240 } 8241 8242 /** 8243 * <p> 8244 * Trigger the scrollbars to draw. When invoked this method starts an 8245 * animation to fade the scrollbars out after a fixed delay. If a subclass 8246 * provides animated scrolling, the start delay should equal the duration of 8247 * the scrolling animation. 8248 * </p> 8249 * 8250 * <p> 8251 * The animation starts only if at least one of the scrollbars is enabled, 8252 * as specified by {@link #isHorizontalScrollBarEnabled()} and 8253 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8254 * this method returns true, and false otherwise. If the animation is 8255 * started, this method calls {@link #invalidate()}; in that case the caller 8256 * should not call {@link #invalidate()}. 8257 * </p> 8258 * 8259 * <p> 8260 * This method should be invoked everytime a subclass directly updates the 8261 * scroll parameters. 8262 * </p> 8263 * 8264 * @param startDelay the delay, in milliseconds, after which the animation 8265 * should start; when the delay is 0, the animation starts 8266 * immediately 8267 * @return true if the animation is played, false otherwise 8268 * 8269 * @see #scrollBy(int, int) 8270 * @see #scrollTo(int, int) 8271 * @see #isHorizontalScrollBarEnabled() 8272 * @see #isVerticalScrollBarEnabled() 8273 * @see #setHorizontalScrollBarEnabled(boolean) 8274 * @see #setVerticalScrollBarEnabled(boolean) 8275 */ 8276 protected boolean awakenScrollBars(int startDelay) { 8277 return awakenScrollBars(startDelay, true); 8278 } 8279 8280 /** 8281 * <p> 8282 * Trigger the scrollbars to draw. When invoked this method starts an 8283 * animation to fade the scrollbars out after a fixed delay. If a subclass 8284 * provides animated scrolling, the start delay should equal the duration of 8285 * the scrolling animation. 8286 * </p> 8287 * 8288 * <p> 8289 * The animation starts only if at least one of the scrollbars is enabled, 8290 * as specified by {@link #isHorizontalScrollBarEnabled()} and 8291 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8292 * this method returns true, and false otherwise. If the animation is 8293 * started, this method calls {@link #invalidate()} if the invalidate parameter 8294 * is set to true; in that case the caller 8295 * should not call {@link #invalidate()}. 8296 * </p> 8297 * 8298 * <p> 8299 * This method should be invoked everytime a subclass directly updates the 8300 * scroll parameters. 8301 * </p> 8302 * 8303 * @param startDelay the delay, in milliseconds, after which the animation 8304 * should start; when the delay is 0, the animation starts 8305 * immediately 8306 * 8307 * @param invalidate Wheter this method should call invalidate 8308 * 8309 * @return true if the animation is played, false otherwise 8310 * 8311 * @see #scrollBy(int, int) 8312 * @see #scrollTo(int, int) 8313 * @see #isHorizontalScrollBarEnabled() 8314 * @see #isVerticalScrollBarEnabled() 8315 * @see #setHorizontalScrollBarEnabled(boolean) 8316 * @see #setVerticalScrollBarEnabled(boolean) 8317 */ 8318 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 8319 final ScrollabilityCache scrollCache = mScrollCache; 8320 8321 if (scrollCache == null || !scrollCache.fadeScrollBars) { 8322 return false; 8323 } 8324 8325 if (scrollCache.scrollBar == null) { 8326 scrollCache.scrollBar = new ScrollBarDrawable(); 8327 } 8328 8329 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 8330 8331 if (invalidate) { 8332 // Invalidate to show the scrollbars 8333 invalidate(true); 8334 } 8335 8336 if (scrollCache.state == ScrollabilityCache.OFF) { 8337 // FIXME: this is copied from WindowManagerService. 8338 // We should get this value from the system when it 8339 // is possible to do so. 8340 final int KEY_REPEAT_FIRST_DELAY = 750; 8341 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 8342 } 8343 8344 // Tell mScrollCache when we should start fading. This may 8345 // extend the fade start time if one was already scheduled 8346 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 8347 scrollCache.fadeStartTime = fadeStartTime; 8348 scrollCache.state = ScrollabilityCache.ON; 8349 8350 // Schedule our fader to run, unscheduling any old ones first 8351 if (mAttachInfo != null) { 8352 mAttachInfo.mHandler.removeCallbacks(scrollCache); 8353 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 8354 } 8355 8356 return true; 8357 } 8358 8359 return false; 8360 } 8361 8362 /** 8363 * Do not invalidate views which are not visible and which are not running an animation. They 8364 * will not get drawn and they should not set dirty flags as if they will be drawn 8365 */ 8366 private boolean skipInvalidate() { 8367 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 8368 (!(mParent instanceof ViewGroup) || 8369 !((ViewGroup) mParent).isViewTransitioning(this)); 8370 } 8371 /** 8372 * Mark the area defined by dirty as needing to be drawn. If the view is 8373 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 8374 * in the future. This must be called from a UI thread. To call from a non-UI 8375 * thread, call {@link #postInvalidate()}. 8376 * 8377 * WARNING: This method is destructive to dirty. 8378 * @param dirty the rectangle representing the bounds of the dirty region 8379 */ 8380 public void invalidate(Rect dirty) { 8381 if (ViewDebug.TRACE_HIERARCHY) { 8382 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8383 } 8384 8385 if (skipInvalidate()) { 8386 return; 8387 } 8388 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8389 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8390 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8391 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8392 mPrivateFlags |= INVALIDATED; 8393 mPrivateFlags |= DIRTY; 8394 final ViewParent p = mParent; 8395 final AttachInfo ai = mAttachInfo; 8396 //noinspection PointlessBooleanExpression,ConstantConditions 8397 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8398 if (p != null && ai != null && ai.mHardwareAccelerated) { 8399 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8400 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8401 p.invalidateChild(this, null); 8402 return; 8403 } 8404 } 8405 if (p != null && ai != null) { 8406 final int scrollX = mScrollX; 8407 final int scrollY = mScrollY; 8408 final Rect r = ai.mTmpInvalRect; 8409 r.set(dirty.left - scrollX, dirty.top - scrollY, 8410 dirty.right - scrollX, dirty.bottom - scrollY); 8411 mParent.invalidateChild(this, r); 8412 } 8413 } 8414 } 8415 8416 /** 8417 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 8418 * The coordinates of the dirty rect are relative to the view. 8419 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 8420 * will be called at some point in the future. This must be called from 8421 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 8422 * @param l the left position of the dirty region 8423 * @param t the top position of the dirty region 8424 * @param r the right position of the dirty region 8425 * @param b the bottom position of the dirty region 8426 */ 8427 public void invalidate(int l, int t, int r, int b) { 8428 if (ViewDebug.TRACE_HIERARCHY) { 8429 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8430 } 8431 8432 if (skipInvalidate()) { 8433 return; 8434 } 8435 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8436 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8437 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8438 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8439 mPrivateFlags |= INVALIDATED; 8440 mPrivateFlags |= DIRTY; 8441 final ViewParent p = mParent; 8442 final AttachInfo ai = mAttachInfo; 8443 //noinspection PointlessBooleanExpression,ConstantConditions 8444 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8445 if (p != null && ai != null && ai.mHardwareAccelerated) { 8446 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8447 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8448 p.invalidateChild(this, null); 8449 return; 8450 } 8451 } 8452 if (p != null && ai != null && l < r && t < b) { 8453 final int scrollX = mScrollX; 8454 final int scrollY = mScrollY; 8455 final Rect tmpr = ai.mTmpInvalRect; 8456 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 8457 p.invalidateChild(this, tmpr); 8458 } 8459 } 8460 } 8461 8462 /** 8463 * Invalidate the whole view. If the view is visible, 8464 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 8465 * the future. This must be called from a UI thread. To call from a non-UI thread, 8466 * call {@link #postInvalidate()}. 8467 */ 8468 public void invalidate() { 8469 invalidate(true); 8470 } 8471 8472 /** 8473 * This is where the invalidate() work actually happens. A full invalidate() 8474 * causes the drawing cache to be invalidated, but this function can be called with 8475 * invalidateCache set to false to skip that invalidation step for cases that do not 8476 * need it (for example, a component that remains at the same dimensions with the same 8477 * content). 8478 * 8479 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 8480 * well. This is usually true for a full invalidate, but may be set to false if the 8481 * View's contents or dimensions have not changed. 8482 */ 8483 void invalidate(boolean invalidateCache) { 8484 if (ViewDebug.TRACE_HIERARCHY) { 8485 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8486 } 8487 8488 if (skipInvalidate()) { 8489 return; 8490 } 8491 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8492 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) || 8493 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) { 8494 mLastIsOpaque = isOpaque(); 8495 mPrivateFlags &= ~DRAWN; 8496 mPrivateFlags |= DIRTY; 8497 if (invalidateCache) { 8498 mPrivateFlags |= INVALIDATED; 8499 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8500 } 8501 final AttachInfo ai = mAttachInfo; 8502 final ViewParent p = mParent; 8503 //noinspection PointlessBooleanExpression,ConstantConditions 8504 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8505 if (p != null && ai != null && ai.mHardwareAccelerated) { 8506 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8507 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8508 p.invalidateChild(this, null); 8509 return; 8510 } 8511 } 8512 8513 if (p != null && ai != null) { 8514 final Rect r = ai.mTmpInvalRect; 8515 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8516 // Don't call invalidate -- we don't want to internally scroll 8517 // our own bounds 8518 p.invalidateChild(this, r); 8519 } 8520 } 8521 } 8522 8523 /** 8524 * @hide 8525 */ 8526 public void fastInvalidate() { 8527 if (skipInvalidate()) { 8528 return; 8529 } 8530 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8531 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8532 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8533 if (mParent instanceof View) { 8534 ((View) mParent).mPrivateFlags |= INVALIDATED; 8535 } 8536 mPrivateFlags &= ~DRAWN; 8537 mPrivateFlags |= DIRTY; 8538 mPrivateFlags |= INVALIDATED; 8539 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8540 if (mParent != null && mAttachInfo != null) { 8541 if (mAttachInfo.mHardwareAccelerated) { 8542 mParent.invalidateChild(this, null); 8543 } else { 8544 final Rect r = mAttachInfo.mTmpInvalRect; 8545 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8546 // Don't call invalidate -- we don't want to internally scroll 8547 // our own bounds 8548 mParent.invalidateChild(this, r); 8549 } 8550 } 8551 } 8552 } 8553 8554 /** 8555 * Used to indicate that the parent of this view should clear its caches. This functionality 8556 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8557 * which is necessary when various parent-managed properties of the view change, such as 8558 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 8559 * clears the parent caches and does not causes an invalidate event. 8560 * 8561 * @hide 8562 */ 8563 protected void invalidateParentCaches() { 8564 if (mParent instanceof View) { 8565 ((View) mParent).mPrivateFlags |= INVALIDATED; 8566 } 8567 } 8568 8569 /** 8570 * Used to indicate that the parent of this view should be invalidated. This functionality 8571 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8572 * which is necessary when various parent-managed properties of the view change, such as 8573 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 8574 * an invalidation event to the parent. 8575 * 8576 * @hide 8577 */ 8578 protected void invalidateParentIfNeeded() { 8579 if (isHardwareAccelerated() && mParent instanceof View) { 8580 ((View) mParent).invalidate(true); 8581 } 8582 } 8583 8584 /** 8585 * Indicates whether this View is opaque. An opaque View guarantees that it will 8586 * draw all the pixels overlapping its bounds using a fully opaque color. 8587 * 8588 * Subclasses of View should override this method whenever possible to indicate 8589 * whether an instance is opaque. Opaque Views are treated in a special way by 8590 * the View hierarchy, possibly allowing it to perform optimizations during 8591 * invalidate/draw passes. 8592 * 8593 * @return True if this View is guaranteed to be fully opaque, false otherwise. 8594 */ 8595 @ViewDebug.ExportedProperty(category = "drawing") 8596 public boolean isOpaque() { 8597 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK && 8598 ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1) 8599 >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD); 8600 } 8601 8602 /** 8603 * @hide 8604 */ 8605 protected void computeOpaqueFlags() { 8606 // Opaque if: 8607 // - Has a background 8608 // - Background is opaque 8609 // - Doesn't have scrollbars or scrollbars are inside overlay 8610 8611 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) { 8612 mPrivateFlags |= OPAQUE_BACKGROUND; 8613 } else { 8614 mPrivateFlags &= ~OPAQUE_BACKGROUND; 8615 } 8616 8617 final int flags = mViewFlags; 8618 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 8619 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 8620 mPrivateFlags |= OPAQUE_SCROLLBARS; 8621 } else { 8622 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 8623 } 8624 } 8625 8626 /** 8627 * @hide 8628 */ 8629 protected boolean hasOpaqueScrollbars() { 8630 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 8631 } 8632 8633 /** 8634 * @return A handler associated with the thread running the View. This 8635 * handler can be used to pump events in the UI events queue. 8636 */ 8637 public Handler getHandler() { 8638 if (mAttachInfo != null) { 8639 return mAttachInfo.mHandler; 8640 } 8641 return null; 8642 } 8643 8644 /** 8645 * <p>Causes the Runnable to be added to the message queue. 8646 * The runnable will be run on the user interface thread.</p> 8647 * 8648 * <p>This method can be invoked from outside of the UI thread 8649 * only when this View is attached to a window.</p> 8650 * 8651 * @param action The Runnable that will be executed. 8652 * 8653 * @return Returns true if the Runnable was successfully placed in to the 8654 * message queue. Returns false on failure, usually because the 8655 * looper processing the message queue is exiting. 8656 */ 8657 public boolean post(Runnable action) { 8658 Handler handler; 8659 AttachInfo attachInfo = mAttachInfo; 8660 if (attachInfo != null) { 8661 handler = attachInfo.mHandler; 8662 } else { 8663 // Assume that post will succeed later 8664 ViewRootImpl.getRunQueue().post(action); 8665 return true; 8666 } 8667 8668 return handler.post(action); 8669 } 8670 8671 /** 8672 * <p>Causes the Runnable to be added to the message queue, to be run 8673 * after the specified amount of time elapses. 8674 * The runnable will be run on the user interface thread.</p> 8675 * 8676 * <p>This method can be invoked from outside of the UI thread 8677 * only when this View is attached to a window.</p> 8678 * 8679 * @param action The Runnable that will be executed. 8680 * @param delayMillis The delay (in milliseconds) until the Runnable 8681 * will be executed. 8682 * 8683 * @return true if the Runnable was successfully placed in to the 8684 * message queue. Returns false on failure, usually because the 8685 * looper processing the message queue is exiting. Note that a 8686 * result of true does not mean the Runnable will be processed -- 8687 * if the looper is quit before the delivery time of the message 8688 * occurs then the message will be dropped. 8689 */ 8690 public boolean postDelayed(Runnable action, long delayMillis) { 8691 Handler handler; 8692 AttachInfo attachInfo = mAttachInfo; 8693 if (attachInfo != null) { 8694 handler = attachInfo.mHandler; 8695 } else { 8696 // Assume that post will succeed later 8697 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 8698 return true; 8699 } 8700 8701 return handler.postDelayed(action, delayMillis); 8702 } 8703 8704 /** 8705 * <p>Removes the specified Runnable from the message queue.</p> 8706 * 8707 * <p>This method can be invoked from outside of the UI thread 8708 * only when this View is attached to a window.</p> 8709 * 8710 * @param action The Runnable to remove from the message handling queue 8711 * 8712 * @return true if this view could ask the Handler to remove the Runnable, 8713 * false otherwise. When the returned value is true, the Runnable 8714 * may or may not have been actually removed from the message queue 8715 * (for instance, if the Runnable was not in the queue already.) 8716 */ 8717 public boolean removeCallbacks(Runnable action) { 8718 Handler handler; 8719 AttachInfo attachInfo = mAttachInfo; 8720 if (attachInfo != null) { 8721 handler = attachInfo.mHandler; 8722 } else { 8723 // Assume that post will succeed later 8724 ViewRootImpl.getRunQueue().removeCallbacks(action); 8725 return true; 8726 } 8727 8728 handler.removeCallbacks(action); 8729 return true; 8730 } 8731 8732 /** 8733 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 8734 * Use this to invalidate the View from a non-UI thread.</p> 8735 * 8736 * <p>This method can be invoked from outside of the UI thread 8737 * only when this View is attached to a window.</p> 8738 * 8739 * @see #invalidate() 8740 */ 8741 public void postInvalidate() { 8742 postInvalidateDelayed(0); 8743 } 8744 8745 /** 8746 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 8747 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 8748 * 8749 * <p>This method can be invoked from outside of the UI thread 8750 * only when this View is attached to a window.</p> 8751 * 8752 * @param left The left coordinate of the rectangle to invalidate. 8753 * @param top The top coordinate of the rectangle to invalidate. 8754 * @param right The right coordinate of the rectangle to invalidate. 8755 * @param bottom The bottom coordinate of the rectangle to invalidate. 8756 * 8757 * @see #invalidate(int, int, int, int) 8758 * @see #invalidate(Rect) 8759 */ 8760 public void postInvalidate(int left, int top, int right, int bottom) { 8761 postInvalidateDelayed(0, left, top, right, bottom); 8762 } 8763 8764 /** 8765 * <p>Cause an invalidate to happen on a subsequent cycle through the event 8766 * loop. Waits for the specified amount of time.</p> 8767 * 8768 * <p>This method can be invoked from outside of the UI thread 8769 * only when this View is attached to a window.</p> 8770 * 8771 * @param delayMilliseconds the duration in milliseconds to delay the 8772 * invalidation by 8773 */ 8774 public void postInvalidateDelayed(long delayMilliseconds) { 8775 // We try only with the AttachInfo because there's no point in invalidating 8776 // if we are not attached to our window 8777 AttachInfo attachInfo = mAttachInfo; 8778 if (attachInfo != null) { 8779 Message msg = Message.obtain(); 8780 msg.what = AttachInfo.INVALIDATE_MSG; 8781 msg.obj = this; 8782 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8783 } 8784 } 8785 8786 /** 8787 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 8788 * through the event loop. Waits for the specified amount of time.</p> 8789 * 8790 * <p>This method can be invoked from outside of the UI thread 8791 * only when this View is attached to a window.</p> 8792 * 8793 * @param delayMilliseconds the duration in milliseconds to delay the 8794 * invalidation by 8795 * @param left The left coordinate of the rectangle to invalidate. 8796 * @param top The top coordinate of the rectangle to invalidate. 8797 * @param right The right coordinate of the rectangle to invalidate. 8798 * @param bottom The bottom coordinate of the rectangle to invalidate. 8799 */ 8800 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 8801 int right, int bottom) { 8802 8803 // We try only with the AttachInfo because there's no point in invalidating 8804 // if we are not attached to our window 8805 AttachInfo attachInfo = mAttachInfo; 8806 if (attachInfo != null) { 8807 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 8808 info.target = this; 8809 info.left = left; 8810 info.top = top; 8811 info.right = right; 8812 info.bottom = bottom; 8813 8814 final Message msg = Message.obtain(); 8815 msg.what = AttachInfo.INVALIDATE_RECT_MSG; 8816 msg.obj = info; 8817 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8818 } 8819 } 8820 8821 /** 8822 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 8823 * This event is sent at most once every 8824 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 8825 */ 8826 private void postSendViewScrolledAccessibilityEventCallback() { 8827 if (mSendViewScrolledAccessibilityEvent == null) { 8828 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 8829 } 8830 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 8831 mSendViewScrolledAccessibilityEvent.mIsPending = true; 8832 postDelayed(mSendViewScrolledAccessibilityEvent, 8833 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 8834 } 8835 } 8836 8837 /** 8838 * Called by a parent to request that a child update its values for mScrollX 8839 * and mScrollY if necessary. This will typically be done if the child is 8840 * animating a scroll using a {@link android.widget.Scroller Scroller} 8841 * object. 8842 */ 8843 public void computeScroll() { 8844 } 8845 8846 /** 8847 * <p>Indicate whether the horizontal edges are faded when the view is 8848 * scrolled horizontally.</p> 8849 * 8850 * @return true if the horizontal edges should are faded on scroll, false 8851 * otherwise 8852 * 8853 * @see #setHorizontalFadingEdgeEnabled(boolean) 8854 * @attr ref android.R.styleable#View_requiresFadingEdge 8855 */ 8856 public boolean isHorizontalFadingEdgeEnabled() { 8857 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 8858 } 8859 8860 /** 8861 * <p>Define whether the horizontal edges should be faded when this view 8862 * is scrolled horizontally.</p> 8863 * 8864 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 8865 * be faded when the view is scrolled 8866 * horizontally 8867 * 8868 * @see #isHorizontalFadingEdgeEnabled() 8869 * @attr ref android.R.styleable#View_requiresFadingEdge 8870 */ 8871 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 8872 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 8873 if (horizontalFadingEdgeEnabled) { 8874 initScrollCache(); 8875 } 8876 8877 mViewFlags ^= FADING_EDGE_HORIZONTAL; 8878 } 8879 } 8880 8881 /** 8882 * <p>Indicate whether the vertical edges are faded when the view is 8883 * scrolled horizontally.</p> 8884 * 8885 * @return true if the vertical edges should are faded on scroll, false 8886 * otherwise 8887 * 8888 * @see #setVerticalFadingEdgeEnabled(boolean) 8889 * @attr ref android.R.styleable#View_requiresFadingEdge 8890 */ 8891 public boolean isVerticalFadingEdgeEnabled() { 8892 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 8893 } 8894 8895 /** 8896 * <p>Define whether the vertical edges should be faded when this view 8897 * is scrolled vertically.</p> 8898 * 8899 * @param verticalFadingEdgeEnabled true if the vertical edges should 8900 * be faded when the view is scrolled 8901 * vertically 8902 * 8903 * @see #isVerticalFadingEdgeEnabled() 8904 * @attr ref android.R.styleable#View_requiresFadingEdge 8905 */ 8906 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 8907 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 8908 if (verticalFadingEdgeEnabled) { 8909 initScrollCache(); 8910 } 8911 8912 mViewFlags ^= FADING_EDGE_VERTICAL; 8913 } 8914 } 8915 8916 /** 8917 * Returns the strength, or intensity, of the top faded edge. The strength is 8918 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8919 * returns 0.0 or 1.0 but no value in between. 8920 * 8921 * Subclasses should override this method to provide a smoother fade transition 8922 * when scrolling occurs. 8923 * 8924 * @return the intensity of the top fade as a float between 0.0f and 1.0f 8925 */ 8926 protected float getTopFadingEdgeStrength() { 8927 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 8928 } 8929 8930 /** 8931 * Returns the strength, or intensity, of the bottom faded edge. The strength is 8932 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8933 * returns 0.0 or 1.0 but no value in between. 8934 * 8935 * Subclasses should override this method to provide a smoother fade transition 8936 * when scrolling occurs. 8937 * 8938 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 8939 */ 8940 protected float getBottomFadingEdgeStrength() { 8941 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 8942 computeVerticalScrollRange() ? 1.0f : 0.0f; 8943 } 8944 8945 /** 8946 * Returns the strength, or intensity, of the left faded edge. The strength is 8947 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8948 * returns 0.0 or 1.0 but no value in between. 8949 * 8950 * Subclasses should override this method to provide a smoother fade transition 8951 * when scrolling occurs. 8952 * 8953 * @return the intensity of the left fade as a float between 0.0f and 1.0f 8954 */ 8955 protected float getLeftFadingEdgeStrength() { 8956 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 8957 } 8958 8959 /** 8960 * Returns the strength, or intensity, of the right faded edge. The strength is 8961 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8962 * returns 0.0 or 1.0 but no value in between. 8963 * 8964 * Subclasses should override this method to provide a smoother fade transition 8965 * when scrolling occurs. 8966 * 8967 * @return the intensity of the right fade as a float between 0.0f and 1.0f 8968 */ 8969 protected float getRightFadingEdgeStrength() { 8970 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 8971 computeHorizontalScrollRange() ? 1.0f : 0.0f; 8972 } 8973 8974 /** 8975 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 8976 * scrollbar is not drawn by default.</p> 8977 * 8978 * @return true if the horizontal scrollbar should be painted, false 8979 * otherwise 8980 * 8981 * @see #setHorizontalScrollBarEnabled(boolean) 8982 */ 8983 public boolean isHorizontalScrollBarEnabled() { 8984 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 8985 } 8986 8987 /** 8988 * <p>Define whether the horizontal scrollbar should be drawn or not. The 8989 * scrollbar is not drawn by default.</p> 8990 * 8991 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 8992 * be painted 8993 * 8994 * @see #isHorizontalScrollBarEnabled() 8995 */ 8996 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 8997 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 8998 mViewFlags ^= SCROLLBARS_HORIZONTAL; 8999 computeOpaqueFlags(); 9000 resolvePadding(); 9001 } 9002 } 9003 9004 /** 9005 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 9006 * scrollbar is not drawn by default.</p> 9007 * 9008 * @return true if the vertical scrollbar should be painted, false 9009 * otherwise 9010 * 9011 * @see #setVerticalScrollBarEnabled(boolean) 9012 */ 9013 public boolean isVerticalScrollBarEnabled() { 9014 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 9015 } 9016 9017 /** 9018 * <p>Define whether the vertical scrollbar should be drawn or not. The 9019 * scrollbar is not drawn by default.</p> 9020 * 9021 * @param verticalScrollBarEnabled true if the vertical scrollbar should 9022 * be painted 9023 * 9024 * @see #isVerticalScrollBarEnabled() 9025 */ 9026 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 9027 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 9028 mViewFlags ^= SCROLLBARS_VERTICAL; 9029 computeOpaqueFlags(); 9030 resolvePadding(); 9031 } 9032 } 9033 9034 /** 9035 * @hide 9036 */ 9037 protected void recomputePadding() { 9038 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 9039 } 9040 9041 /** 9042 * Define whether scrollbars will fade when the view is not scrolling. 9043 * 9044 * @param fadeScrollbars wheter to enable fading 9045 * 9046 */ 9047 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 9048 initScrollCache(); 9049 final ScrollabilityCache scrollabilityCache = mScrollCache; 9050 scrollabilityCache.fadeScrollBars = fadeScrollbars; 9051 if (fadeScrollbars) { 9052 scrollabilityCache.state = ScrollabilityCache.OFF; 9053 } else { 9054 scrollabilityCache.state = ScrollabilityCache.ON; 9055 } 9056 } 9057 9058 /** 9059 * 9060 * Returns true if scrollbars will fade when this view is not scrolling 9061 * 9062 * @return true if scrollbar fading is enabled 9063 */ 9064 public boolean isScrollbarFadingEnabled() { 9065 return mScrollCache != null && mScrollCache.fadeScrollBars; 9066 } 9067 9068 /** 9069 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 9070 * inset. When inset, they add to the padding of the view. And the scrollbars 9071 * can be drawn inside the padding area or on the edge of the view. For example, 9072 * if a view has a background drawable and you want to draw the scrollbars 9073 * inside the padding specified by the drawable, you can use 9074 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 9075 * appear at the edge of the view, ignoring the padding, then you can use 9076 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 9077 * @param style the style of the scrollbars. Should be one of 9078 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 9079 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 9080 * @see #SCROLLBARS_INSIDE_OVERLAY 9081 * @see #SCROLLBARS_INSIDE_INSET 9082 * @see #SCROLLBARS_OUTSIDE_OVERLAY 9083 * @see #SCROLLBARS_OUTSIDE_INSET 9084 */ 9085 public void setScrollBarStyle(int style) { 9086 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 9087 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 9088 computeOpaqueFlags(); 9089 resolvePadding(); 9090 } 9091 } 9092 9093 /** 9094 * <p>Returns the current scrollbar style.</p> 9095 * @return the current scrollbar style 9096 * @see #SCROLLBARS_INSIDE_OVERLAY 9097 * @see #SCROLLBARS_INSIDE_INSET 9098 * @see #SCROLLBARS_OUTSIDE_OVERLAY 9099 * @see #SCROLLBARS_OUTSIDE_INSET 9100 */ 9101 @ViewDebug.ExportedProperty(mapping = { 9102 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 9103 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 9104 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 9105 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 9106 }) 9107 public int getScrollBarStyle() { 9108 return mViewFlags & SCROLLBARS_STYLE_MASK; 9109 } 9110 9111 /** 9112 * <p>Compute the horizontal range that the horizontal scrollbar 9113 * represents.</p> 9114 * 9115 * <p>The range is expressed in arbitrary units that must be the same as the 9116 * units used by {@link #computeHorizontalScrollExtent()} and 9117 * {@link #computeHorizontalScrollOffset()}.</p> 9118 * 9119 * <p>The default range is the drawing width of this view.</p> 9120 * 9121 * @return the total horizontal range represented by the horizontal 9122 * scrollbar 9123 * 9124 * @see #computeHorizontalScrollExtent() 9125 * @see #computeHorizontalScrollOffset() 9126 * @see android.widget.ScrollBarDrawable 9127 */ 9128 protected int computeHorizontalScrollRange() { 9129 return getWidth(); 9130 } 9131 9132 /** 9133 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 9134 * within the horizontal range. This value is used to compute the position 9135 * of the thumb within the scrollbar's track.</p> 9136 * 9137 * <p>The range is expressed in arbitrary units that must be the same as the 9138 * units used by {@link #computeHorizontalScrollRange()} and 9139 * {@link #computeHorizontalScrollExtent()}.</p> 9140 * 9141 * <p>The default offset is the scroll offset of this view.</p> 9142 * 9143 * @return the horizontal offset of the scrollbar's thumb 9144 * 9145 * @see #computeHorizontalScrollRange() 9146 * @see #computeHorizontalScrollExtent() 9147 * @see android.widget.ScrollBarDrawable 9148 */ 9149 protected int computeHorizontalScrollOffset() { 9150 return mScrollX; 9151 } 9152 9153 /** 9154 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 9155 * within the horizontal range. This value is used to compute the length 9156 * of the thumb within the scrollbar's track.</p> 9157 * 9158 * <p>The range is expressed in arbitrary units that must be the same as the 9159 * units used by {@link #computeHorizontalScrollRange()} and 9160 * {@link #computeHorizontalScrollOffset()}.</p> 9161 * 9162 * <p>The default extent is the drawing width of this view.</p> 9163 * 9164 * @return the horizontal extent of the scrollbar's thumb 9165 * 9166 * @see #computeHorizontalScrollRange() 9167 * @see #computeHorizontalScrollOffset() 9168 * @see android.widget.ScrollBarDrawable 9169 */ 9170 protected int computeHorizontalScrollExtent() { 9171 return getWidth(); 9172 } 9173 9174 /** 9175 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 9176 * 9177 * <p>The range is expressed in arbitrary units that must be the same as the 9178 * units used by {@link #computeVerticalScrollExtent()} and 9179 * {@link #computeVerticalScrollOffset()}.</p> 9180 * 9181 * @return the total vertical range represented by the vertical scrollbar 9182 * 9183 * <p>The default range is the drawing height of this view.</p> 9184 * 9185 * @see #computeVerticalScrollExtent() 9186 * @see #computeVerticalScrollOffset() 9187 * @see android.widget.ScrollBarDrawable 9188 */ 9189 protected int computeVerticalScrollRange() { 9190 return getHeight(); 9191 } 9192 9193 /** 9194 * <p>Compute the vertical offset of the vertical scrollbar's thumb 9195 * within the horizontal range. This value is used to compute the position 9196 * of the thumb within the scrollbar's track.</p> 9197 * 9198 * <p>The range is expressed in arbitrary units that must be the same as the 9199 * units used by {@link #computeVerticalScrollRange()} and 9200 * {@link #computeVerticalScrollExtent()}.</p> 9201 * 9202 * <p>The default offset is the scroll offset of this view.</p> 9203 * 9204 * @return the vertical offset of the scrollbar's thumb 9205 * 9206 * @see #computeVerticalScrollRange() 9207 * @see #computeVerticalScrollExtent() 9208 * @see android.widget.ScrollBarDrawable 9209 */ 9210 protected int computeVerticalScrollOffset() { 9211 return mScrollY; 9212 } 9213 9214 /** 9215 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 9216 * within the vertical range. This value is used to compute the length 9217 * of the thumb within the scrollbar's track.</p> 9218 * 9219 * <p>The range is expressed in arbitrary units that must be the same as the 9220 * units used by {@link #computeVerticalScrollRange()} and 9221 * {@link #computeVerticalScrollOffset()}.</p> 9222 * 9223 * <p>The default extent is the drawing height of this view.</p> 9224 * 9225 * @return the vertical extent of the scrollbar's thumb 9226 * 9227 * @see #computeVerticalScrollRange() 9228 * @see #computeVerticalScrollOffset() 9229 * @see android.widget.ScrollBarDrawable 9230 */ 9231 protected int computeVerticalScrollExtent() { 9232 return getHeight(); 9233 } 9234 9235 /** 9236 * Check if this view can be scrolled horizontally in a certain direction. 9237 * 9238 * @param direction Negative to check scrolling left, positive to check scrolling right. 9239 * @return true if this view can be scrolled in the specified direction, false otherwise. 9240 */ 9241 public boolean canScrollHorizontally(int direction) { 9242 final int offset = computeHorizontalScrollOffset(); 9243 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 9244 if (range == 0) return false; 9245 if (direction < 0) { 9246 return offset > 0; 9247 } else { 9248 return offset < range - 1; 9249 } 9250 } 9251 9252 /** 9253 * Check if this view can be scrolled vertically in a certain direction. 9254 * 9255 * @param direction Negative to check scrolling up, positive to check scrolling down. 9256 * @return true if this view can be scrolled in the specified direction, false otherwise. 9257 */ 9258 public boolean canScrollVertically(int direction) { 9259 final int offset = computeVerticalScrollOffset(); 9260 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 9261 if (range == 0) return false; 9262 if (direction < 0) { 9263 return offset > 0; 9264 } else { 9265 return offset < range - 1; 9266 } 9267 } 9268 9269 /** 9270 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 9271 * scrollbars are painted only if they have been awakened first.</p> 9272 * 9273 * @param canvas the canvas on which to draw the scrollbars 9274 * 9275 * @see #awakenScrollBars(int) 9276 */ 9277 protected final void onDrawScrollBars(Canvas canvas) { 9278 // scrollbars are drawn only when the animation is running 9279 final ScrollabilityCache cache = mScrollCache; 9280 if (cache != null) { 9281 9282 int state = cache.state; 9283 9284 if (state == ScrollabilityCache.OFF) { 9285 return; 9286 } 9287 9288 boolean invalidate = false; 9289 9290 if (state == ScrollabilityCache.FADING) { 9291 // We're fading -- get our fade interpolation 9292 if (cache.interpolatorValues == null) { 9293 cache.interpolatorValues = new float[1]; 9294 } 9295 9296 float[] values = cache.interpolatorValues; 9297 9298 // Stops the animation if we're done 9299 if (cache.scrollBarInterpolator.timeToValues(values) == 9300 Interpolator.Result.FREEZE_END) { 9301 cache.state = ScrollabilityCache.OFF; 9302 } else { 9303 cache.scrollBar.setAlpha(Math.round(values[0])); 9304 } 9305 9306 // This will make the scroll bars inval themselves after 9307 // drawing. We only want this when we're fading so that 9308 // we prevent excessive redraws 9309 invalidate = true; 9310 } else { 9311 // We're just on -- but we may have been fading before so 9312 // reset alpha 9313 cache.scrollBar.setAlpha(255); 9314 } 9315 9316 9317 final int viewFlags = mViewFlags; 9318 9319 final boolean drawHorizontalScrollBar = 9320 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 9321 final boolean drawVerticalScrollBar = 9322 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 9323 && !isVerticalScrollBarHidden(); 9324 9325 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 9326 final int width = mRight - mLeft; 9327 final int height = mBottom - mTop; 9328 9329 final ScrollBarDrawable scrollBar = cache.scrollBar; 9330 9331 final int scrollX = mScrollX; 9332 final int scrollY = mScrollY; 9333 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 9334 9335 int left, top, right, bottom; 9336 9337 if (drawHorizontalScrollBar) { 9338 int size = scrollBar.getSize(false); 9339 if (size <= 0) { 9340 size = cache.scrollBarSize; 9341 } 9342 9343 scrollBar.setParameters(computeHorizontalScrollRange(), 9344 computeHorizontalScrollOffset(), 9345 computeHorizontalScrollExtent(), false); 9346 final int verticalScrollBarGap = drawVerticalScrollBar ? 9347 getVerticalScrollbarWidth() : 0; 9348 top = scrollY + height - size - (mUserPaddingBottom & inside); 9349 left = scrollX + (mPaddingLeft & inside); 9350 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 9351 bottom = top + size; 9352 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 9353 if (invalidate) { 9354 invalidate(left, top, right, bottom); 9355 } 9356 } 9357 9358 if (drawVerticalScrollBar) { 9359 int size = scrollBar.getSize(true); 9360 if (size <= 0) { 9361 size = cache.scrollBarSize; 9362 } 9363 9364 scrollBar.setParameters(computeVerticalScrollRange(), 9365 computeVerticalScrollOffset(), 9366 computeVerticalScrollExtent(), true); 9367 switch (mVerticalScrollbarPosition) { 9368 default: 9369 case SCROLLBAR_POSITION_DEFAULT: 9370 case SCROLLBAR_POSITION_RIGHT: 9371 left = scrollX + width - size - (mUserPaddingRight & inside); 9372 break; 9373 case SCROLLBAR_POSITION_LEFT: 9374 left = scrollX + (mUserPaddingLeft & inside); 9375 break; 9376 } 9377 top = scrollY + (mPaddingTop & inside); 9378 right = left + size; 9379 bottom = scrollY + height - (mUserPaddingBottom & inside); 9380 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 9381 if (invalidate) { 9382 invalidate(left, top, right, bottom); 9383 } 9384 } 9385 } 9386 } 9387 } 9388 9389 /** 9390 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 9391 * FastScroller is visible. 9392 * @return whether to temporarily hide the vertical scrollbar 9393 * @hide 9394 */ 9395 protected boolean isVerticalScrollBarHidden() { 9396 return false; 9397 } 9398 9399 /** 9400 * <p>Draw the horizontal scrollbar if 9401 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 9402 * 9403 * @param canvas the canvas on which to draw the scrollbar 9404 * @param scrollBar the scrollbar's drawable 9405 * 9406 * @see #isHorizontalScrollBarEnabled() 9407 * @see #computeHorizontalScrollRange() 9408 * @see #computeHorizontalScrollExtent() 9409 * @see #computeHorizontalScrollOffset() 9410 * @see android.widget.ScrollBarDrawable 9411 * @hide 9412 */ 9413 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 9414 int l, int t, int r, int b) { 9415 scrollBar.setBounds(l, t, r, b); 9416 scrollBar.draw(canvas); 9417 } 9418 9419 /** 9420 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 9421 * returns true.</p> 9422 * 9423 * @param canvas the canvas on which to draw the scrollbar 9424 * @param scrollBar the scrollbar's drawable 9425 * 9426 * @see #isVerticalScrollBarEnabled() 9427 * @see #computeVerticalScrollRange() 9428 * @see #computeVerticalScrollExtent() 9429 * @see #computeVerticalScrollOffset() 9430 * @see android.widget.ScrollBarDrawable 9431 * @hide 9432 */ 9433 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 9434 int l, int t, int r, int b) { 9435 scrollBar.setBounds(l, t, r, b); 9436 scrollBar.draw(canvas); 9437 } 9438 9439 /** 9440 * Implement this to do your drawing. 9441 * 9442 * @param canvas the canvas on which the background will be drawn 9443 */ 9444 protected void onDraw(Canvas canvas) { 9445 } 9446 9447 /* 9448 * Caller is responsible for calling requestLayout if necessary. 9449 * (This allows addViewInLayout to not request a new layout.) 9450 */ 9451 void assignParent(ViewParent parent) { 9452 if (mParent == null) { 9453 mParent = parent; 9454 } else if (parent == null) { 9455 mParent = null; 9456 } else { 9457 throw new RuntimeException("view " + this + " being added, but" 9458 + " it already has a parent"); 9459 } 9460 } 9461 9462 /** 9463 * This is called when the view is attached to a window. At this point it 9464 * has a Surface and will start drawing. Note that this function is 9465 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 9466 * however it may be called any time before the first onDraw -- including 9467 * before or after {@link #onMeasure(int, int)}. 9468 * 9469 * @see #onDetachedFromWindow() 9470 */ 9471 protected void onAttachedToWindow() { 9472 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 9473 mParent.requestTransparentRegion(this); 9474 } 9475 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 9476 initialAwakenScrollBars(); 9477 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH; 9478 } 9479 jumpDrawablesToCurrentState(); 9480 // Order is important here: LayoutDirection MUST be resolved before Padding 9481 // and TextDirection 9482 resolveLayoutDirectionIfNeeded(); 9483 resolvePadding(); 9484 resolveTextDirection(); 9485 if (isFocused()) { 9486 InputMethodManager imm = InputMethodManager.peekInstance(); 9487 imm.focusIn(this); 9488 } 9489 } 9490 9491 /** 9492 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 9493 * that the parent directionality can and will be resolved before its children. 9494 */ 9495 private void resolveLayoutDirectionIfNeeded() { 9496 // Do not resolve if it is not needed 9497 if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return; 9498 9499 // Clear any previous layout direction resolution 9500 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL; 9501 9502 // Reset also TextDirection as a change into LayoutDirection may impact the selected 9503 // TextDirectionHeuristic 9504 resetResolvedTextDirection(); 9505 9506 // Set resolved depending on layout direction 9507 switch (getLayoutDirection()) { 9508 case LAYOUT_DIRECTION_INHERIT: 9509 // We cannot do the resolution if there is no parent 9510 if (mParent == null) return; 9511 9512 // If this is root view, no need to look at parent's layout dir. 9513 if (mParent instanceof ViewGroup) { 9514 ViewGroup viewGroup = ((ViewGroup) mParent); 9515 9516 // Check if the parent view group can resolve 9517 if (! viewGroup.canResolveLayoutDirection()) { 9518 return; 9519 } 9520 if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 9521 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9522 } 9523 } 9524 break; 9525 case LAYOUT_DIRECTION_RTL: 9526 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9527 break; 9528 case LAYOUT_DIRECTION_LOCALE: 9529 if(isLayoutDirectionRtl(Locale.getDefault())) { 9530 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9531 } 9532 break; 9533 default: 9534 // Nothing to do, LTR by default 9535 } 9536 9537 // Set to resolved 9538 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED; 9539 } 9540 9541 /** 9542 * @hide 9543 */ 9544 protected void resolvePadding() { 9545 // If the user specified the absolute padding (either with android:padding or 9546 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 9547 // use the default padding or the padding from the background drawable 9548 // (stored at this point in mPadding*) 9549 switch (getResolvedLayoutDirection()) { 9550 case LAYOUT_DIRECTION_RTL: 9551 // Start user padding override Right user padding. Otherwise, if Right user 9552 // padding is not defined, use the default Right padding. If Right user padding 9553 // is defined, just use it. 9554 if (mUserPaddingStart >= 0) { 9555 mUserPaddingRight = mUserPaddingStart; 9556 } else if (mUserPaddingRight < 0) { 9557 mUserPaddingRight = mPaddingRight; 9558 } 9559 if (mUserPaddingEnd >= 0) { 9560 mUserPaddingLeft = mUserPaddingEnd; 9561 } else if (mUserPaddingLeft < 0) { 9562 mUserPaddingLeft = mPaddingLeft; 9563 } 9564 break; 9565 case LAYOUT_DIRECTION_LTR: 9566 default: 9567 // Start user padding override Left user padding. Otherwise, if Left user 9568 // padding is not defined, use the default left padding. If Left user padding 9569 // is defined, just use it. 9570 if (mUserPaddingStart >= 0) { 9571 mUserPaddingLeft = mUserPaddingStart; 9572 } else if (mUserPaddingLeft < 0) { 9573 mUserPaddingLeft = mPaddingLeft; 9574 } 9575 if (mUserPaddingEnd >= 0) { 9576 mUserPaddingRight = mUserPaddingEnd; 9577 } else if (mUserPaddingRight < 0) { 9578 mUserPaddingRight = mPaddingRight; 9579 } 9580 } 9581 9582 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 9583 9584 recomputePadding(); 9585 } 9586 9587 /** 9588 * Return true if layout direction resolution can be done 9589 * 9590 * @hide 9591 */ 9592 protected boolean canResolveLayoutDirection() { 9593 switch (getLayoutDirection()) { 9594 case LAYOUT_DIRECTION_INHERIT: 9595 return (mParent != null); 9596 default: 9597 return true; 9598 } 9599 } 9600 9601 /** 9602 * Reset the resolved layout direction. 9603 * 9604 * Subclasses need to override this method to clear cached information that depends on the 9605 * resolved layout direction, or to inform child views that inherit their layout direction. 9606 * Overrides must also call the superclass implementation at the start of their implementation. 9607 * 9608 * @hide 9609 */ 9610 protected void resetResolvedLayoutDirection() { 9611 // Reset the current View resolution 9612 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED; 9613 } 9614 9615 /** 9616 * Check if a Locale is corresponding to a RTL script. 9617 * 9618 * @param locale Locale to check 9619 * @return true if a Locale is corresponding to a RTL script. 9620 * 9621 * @hide 9622 */ 9623 protected static boolean isLayoutDirectionRtl(Locale locale) { 9624 return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE == 9625 LocaleUtil.getLayoutDirectionFromLocale(locale)); 9626 } 9627 9628 /** 9629 * This is called when the view is detached from a window. At this point it 9630 * no longer has a surface for drawing. 9631 * 9632 * @see #onAttachedToWindow() 9633 */ 9634 protected void onDetachedFromWindow() { 9635 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 9636 9637 removeUnsetPressCallback(); 9638 removeLongPressCallback(); 9639 removePerformClickCallback(); 9640 removeSendViewScrolledAccessibilityEventCallback(); 9641 9642 destroyDrawingCache(); 9643 9644 destroyLayer(); 9645 9646 if (mDisplayList != null) { 9647 mDisplayList.invalidate(); 9648 } 9649 9650 if (mAttachInfo != null) { 9651 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this); 9652 } 9653 9654 mCurrentAnimation = null; 9655 9656 resetResolvedLayoutDirection(); 9657 resetResolvedTextDirection(); 9658 } 9659 9660 /** 9661 * @return The number of times this view has been attached to a window 9662 */ 9663 protected int getWindowAttachCount() { 9664 return mWindowAttachCount; 9665 } 9666 9667 /** 9668 * Retrieve a unique token identifying the window this view is attached to. 9669 * @return Return the window's token for use in 9670 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 9671 */ 9672 public IBinder getWindowToken() { 9673 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 9674 } 9675 9676 /** 9677 * Retrieve a unique token identifying the top-level "real" window of 9678 * the window that this view is attached to. That is, this is like 9679 * {@link #getWindowToken}, except if the window this view in is a panel 9680 * window (attached to another containing window), then the token of 9681 * the containing window is returned instead. 9682 * 9683 * @return Returns the associated window token, either 9684 * {@link #getWindowToken()} or the containing window's token. 9685 */ 9686 public IBinder getApplicationWindowToken() { 9687 AttachInfo ai = mAttachInfo; 9688 if (ai != null) { 9689 IBinder appWindowToken = ai.mPanelParentWindowToken; 9690 if (appWindowToken == null) { 9691 appWindowToken = ai.mWindowToken; 9692 } 9693 return appWindowToken; 9694 } 9695 return null; 9696 } 9697 9698 /** 9699 * Retrieve private session object this view hierarchy is using to 9700 * communicate with the window manager. 9701 * @return the session object to communicate with the window manager 9702 */ 9703 /*package*/ IWindowSession getWindowSession() { 9704 return mAttachInfo != null ? mAttachInfo.mSession : null; 9705 } 9706 9707 /** 9708 * @param info the {@link android.view.View.AttachInfo} to associated with 9709 * this view 9710 */ 9711 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 9712 //System.out.println("Attached! " + this); 9713 mAttachInfo = info; 9714 mWindowAttachCount++; 9715 // We will need to evaluate the drawable state at least once. 9716 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 9717 if (mFloatingTreeObserver != null) { 9718 info.mTreeObserver.merge(mFloatingTreeObserver); 9719 mFloatingTreeObserver = null; 9720 } 9721 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 9722 mAttachInfo.mScrollContainers.add(this); 9723 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 9724 } 9725 performCollectViewAttributes(visibility); 9726 onAttachedToWindow(); 9727 9728 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9729 mOnAttachStateChangeListeners; 9730 if (listeners != null && listeners.size() > 0) { 9731 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9732 // perform the dispatching. The iterator is a safe guard against listeners that 9733 // could mutate the list by calling the various add/remove methods. This prevents 9734 // the array from being modified while we iterate it. 9735 for (OnAttachStateChangeListener listener : listeners) { 9736 listener.onViewAttachedToWindow(this); 9737 } 9738 } 9739 9740 int vis = info.mWindowVisibility; 9741 if (vis != GONE) { 9742 onWindowVisibilityChanged(vis); 9743 } 9744 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 9745 // If nobody has evaluated the drawable state yet, then do it now. 9746 refreshDrawableState(); 9747 } 9748 } 9749 9750 void dispatchDetachedFromWindow() { 9751 AttachInfo info = mAttachInfo; 9752 if (info != null) { 9753 int vis = info.mWindowVisibility; 9754 if (vis != GONE) { 9755 onWindowVisibilityChanged(GONE); 9756 } 9757 } 9758 9759 onDetachedFromWindow(); 9760 9761 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9762 mOnAttachStateChangeListeners; 9763 if (listeners != null && listeners.size() > 0) { 9764 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9765 // perform the dispatching. The iterator is a safe guard against listeners that 9766 // could mutate the list by calling the various add/remove methods. This prevents 9767 // the array from being modified while we iterate it. 9768 for (OnAttachStateChangeListener listener : listeners) { 9769 listener.onViewDetachedFromWindow(this); 9770 } 9771 } 9772 9773 if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) { 9774 mAttachInfo.mScrollContainers.remove(this); 9775 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 9776 } 9777 9778 mAttachInfo = null; 9779 } 9780 9781 /** 9782 * Store this view hierarchy's frozen state into the given container. 9783 * 9784 * @param container The SparseArray in which to save the view's state. 9785 * 9786 * @see #restoreHierarchyState(android.util.SparseArray) 9787 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9788 * @see #onSaveInstanceState() 9789 */ 9790 public void saveHierarchyState(SparseArray<Parcelable> container) { 9791 dispatchSaveInstanceState(container); 9792 } 9793 9794 /** 9795 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 9796 * this view and its children. May be overridden to modify how freezing happens to a 9797 * view's children; for example, some views may want to not store state for their children. 9798 * 9799 * @param container The SparseArray in which to save the view's state. 9800 * 9801 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9802 * @see #saveHierarchyState(android.util.SparseArray) 9803 * @see #onSaveInstanceState() 9804 */ 9805 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 9806 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 9807 mPrivateFlags &= ~SAVE_STATE_CALLED; 9808 Parcelable state = onSaveInstanceState(); 9809 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9810 throw new IllegalStateException( 9811 "Derived class did not call super.onSaveInstanceState()"); 9812 } 9813 if (state != null) { 9814 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 9815 // + ": " + state); 9816 container.put(mID, state); 9817 } 9818 } 9819 } 9820 9821 /** 9822 * Hook allowing a view to generate a representation of its internal state 9823 * that can later be used to create a new instance with that same state. 9824 * This state should only contain information that is not persistent or can 9825 * not be reconstructed later. For example, you will never store your 9826 * current position on screen because that will be computed again when a 9827 * new instance of the view is placed in its view hierarchy. 9828 * <p> 9829 * Some examples of things you may store here: the current cursor position 9830 * in a text view (but usually not the text itself since that is stored in a 9831 * content provider or other persistent storage), the currently selected 9832 * item in a list view. 9833 * 9834 * @return Returns a Parcelable object containing the view's current dynamic 9835 * state, or null if there is nothing interesting to save. The 9836 * default implementation returns null. 9837 * @see #onRestoreInstanceState(android.os.Parcelable) 9838 * @see #saveHierarchyState(android.util.SparseArray) 9839 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9840 * @see #setSaveEnabled(boolean) 9841 */ 9842 protected Parcelable onSaveInstanceState() { 9843 mPrivateFlags |= SAVE_STATE_CALLED; 9844 return BaseSavedState.EMPTY_STATE; 9845 } 9846 9847 /** 9848 * Restore this view hierarchy's frozen state from the given container. 9849 * 9850 * @param container The SparseArray which holds previously frozen states. 9851 * 9852 * @see #saveHierarchyState(android.util.SparseArray) 9853 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9854 * @see #onRestoreInstanceState(android.os.Parcelable) 9855 */ 9856 public void restoreHierarchyState(SparseArray<Parcelable> container) { 9857 dispatchRestoreInstanceState(container); 9858 } 9859 9860 /** 9861 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 9862 * state for this view and its children. May be overridden to modify how restoring 9863 * happens to a view's children; for example, some views may want to not store state 9864 * for their children. 9865 * 9866 * @param container The SparseArray which holds previously saved state. 9867 * 9868 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9869 * @see #restoreHierarchyState(android.util.SparseArray) 9870 * @see #onRestoreInstanceState(android.os.Parcelable) 9871 */ 9872 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 9873 if (mID != NO_ID) { 9874 Parcelable state = container.get(mID); 9875 if (state != null) { 9876 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 9877 // + ": " + state); 9878 mPrivateFlags &= ~SAVE_STATE_CALLED; 9879 onRestoreInstanceState(state); 9880 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9881 throw new IllegalStateException( 9882 "Derived class did not call super.onRestoreInstanceState()"); 9883 } 9884 } 9885 } 9886 } 9887 9888 /** 9889 * Hook allowing a view to re-apply a representation of its internal state that had previously 9890 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 9891 * null state. 9892 * 9893 * @param state The frozen state that had previously been returned by 9894 * {@link #onSaveInstanceState}. 9895 * 9896 * @see #onSaveInstanceState() 9897 * @see #restoreHierarchyState(android.util.SparseArray) 9898 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9899 */ 9900 protected void onRestoreInstanceState(Parcelable state) { 9901 mPrivateFlags |= SAVE_STATE_CALLED; 9902 if (state != BaseSavedState.EMPTY_STATE && state != null) { 9903 throw new IllegalArgumentException("Wrong state class, expecting View State but " 9904 + "received " + state.getClass().toString() + " instead. This usually happens " 9905 + "when two views of different type have the same id in the same hierarchy. " 9906 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 9907 + "other views do not use the same id."); 9908 } 9909 } 9910 9911 /** 9912 * <p>Return the time at which the drawing of the view hierarchy started.</p> 9913 * 9914 * @return the drawing start time in milliseconds 9915 */ 9916 public long getDrawingTime() { 9917 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 9918 } 9919 9920 /** 9921 * <p>Enables or disables the duplication of the parent's state into this view. When 9922 * duplication is enabled, this view gets its drawable state from its parent rather 9923 * than from its own internal properties.</p> 9924 * 9925 * <p>Note: in the current implementation, setting this property to true after the 9926 * view was added to a ViewGroup might have no effect at all. This property should 9927 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 9928 * 9929 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 9930 * property is enabled, an exception will be thrown.</p> 9931 * 9932 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 9933 * parent, these states should not be affected by this method.</p> 9934 * 9935 * @param enabled True to enable duplication of the parent's drawable state, false 9936 * to disable it. 9937 * 9938 * @see #getDrawableState() 9939 * @see #isDuplicateParentStateEnabled() 9940 */ 9941 public void setDuplicateParentStateEnabled(boolean enabled) { 9942 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 9943 } 9944 9945 /** 9946 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 9947 * 9948 * @return True if this view's drawable state is duplicated from the parent, 9949 * false otherwise 9950 * 9951 * @see #getDrawableState() 9952 * @see #setDuplicateParentStateEnabled(boolean) 9953 */ 9954 public boolean isDuplicateParentStateEnabled() { 9955 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 9956 } 9957 9958 /** 9959 * <p>Specifies the type of layer backing this view. The layer can be 9960 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 9961 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 9962 * 9963 * <p>A layer is associated with an optional {@link android.graphics.Paint} 9964 * instance that controls how the layer is composed on screen. The following 9965 * properties of the paint are taken into account when composing the layer:</p> 9966 * <ul> 9967 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 9968 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 9969 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 9970 * </ul> 9971 * 9972 * <p>If this view has an alpha value set to < 1.0 by calling 9973 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 9974 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 9975 * equivalent to setting a hardware layer on this view and providing a paint with 9976 * the desired alpha value.<p> 9977 * 9978 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 9979 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 9980 * for more information on when and how to use layers.</p> 9981 * 9982 * @param layerType The ype of layer to use with this view, must be one of 9983 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 9984 * {@link #LAYER_TYPE_HARDWARE} 9985 * @param paint The paint used to compose the layer. This argument is optional 9986 * and can be null. It is ignored when the layer type is 9987 * {@link #LAYER_TYPE_NONE} 9988 * 9989 * @see #getLayerType() 9990 * @see #LAYER_TYPE_NONE 9991 * @see #LAYER_TYPE_SOFTWARE 9992 * @see #LAYER_TYPE_HARDWARE 9993 * @see #setAlpha(float) 9994 * 9995 * @attr ref android.R.styleable#View_layerType 9996 */ 9997 public void setLayerType(int layerType, Paint paint) { 9998 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 9999 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 10000 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 10001 } 10002 10003 if (layerType == mLayerType) { 10004 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 10005 mLayerPaint = paint == null ? new Paint() : paint; 10006 invalidateParentCaches(); 10007 invalidate(true); 10008 } 10009 return; 10010 } 10011 10012 // Destroy any previous software drawing cache if needed 10013 switch (mLayerType) { 10014 case LAYER_TYPE_HARDWARE: 10015 destroyLayer(); 10016 // fall through - unaccelerated views may use software layer mechanism instead 10017 case LAYER_TYPE_SOFTWARE: 10018 destroyDrawingCache(); 10019 break; 10020 default: 10021 break; 10022 } 10023 10024 mLayerType = layerType; 10025 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 10026 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 10027 mLocalDirtyRect = layerDisabled ? null : new Rect(); 10028 10029 invalidateParentCaches(); 10030 invalidate(true); 10031 } 10032 10033 /** 10034 * Indicates whether this view has a static layer. A view with layer type 10035 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 10036 * dynamic. 10037 */ 10038 boolean hasStaticLayer() { 10039 return mLayerType == LAYER_TYPE_NONE; 10040 } 10041 10042 /** 10043 * Indicates what type of layer is currently associated with this view. By default 10044 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 10045 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 10046 * for more information on the different types of layers. 10047 * 10048 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 10049 * {@link #LAYER_TYPE_HARDWARE} 10050 * 10051 * @see #setLayerType(int, android.graphics.Paint) 10052 * @see #buildLayer() 10053 * @see #LAYER_TYPE_NONE 10054 * @see #LAYER_TYPE_SOFTWARE 10055 * @see #LAYER_TYPE_HARDWARE 10056 */ 10057 public int getLayerType() { 10058 return mLayerType; 10059 } 10060 10061 /** 10062 * Forces this view's layer to be created and this view to be rendered 10063 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 10064 * invoking this method will have no effect. 10065 * 10066 * This method can for instance be used to render a view into its layer before 10067 * starting an animation. If this view is complex, rendering into the layer 10068 * before starting the animation will avoid skipping frames. 10069 * 10070 * @throws IllegalStateException If this view is not attached to a window 10071 * 10072 * @see #setLayerType(int, android.graphics.Paint) 10073 */ 10074 public void buildLayer() { 10075 if (mLayerType == LAYER_TYPE_NONE) return; 10076 10077 if (mAttachInfo == null) { 10078 throw new IllegalStateException("This view must be attached to a window first"); 10079 } 10080 10081 switch (mLayerType) { 10082 case LAYER_TYPE_HARDWARE: 10083 getHardwareLayer(); 10084 break; 10085 case LAYER_TYPE_SOFTWARE: 10086 buildDrawingCache(true); 10087 break; 10088 } 10089 } 10090 10091 /** 10092 * <p>Returns a hardware layer that can be used to draw this view again 10093 * without executing its draw method.</p> 10094 * 10095 * @return A HardwareLayer ready to render, or null if an error occurred. 10096 */ 10097 HardwareLayer getHardwareLayer() { 10098 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 10099 !mAttachInfo.mHardwareRenderer.isEnabled()) { 10100 return null; 10101 } 10102 10103 final int width = mRight - mLeft; 10104 final int height = mBottom - mTop; 10105 10106 if (width == 0 || height == 0) { 10107 return null; 10108 } 10109 10110 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 10111 if (mHardwareLayer == null) { 10112 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 10113 width, height, isOpaque()); 10114 mLocalDirtyRect.setEmpty(); 10115 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 10116 mHardwareLayer.resize(width, height); 10117 mLocalDirtyRect.setEmpty(); 10118 } 10119 10120 // The layer is not valid if the underlying GPU resources cannot be allocated 10121 if (!mHardwareLayer.isValid()) { 10122 return null; 10123 } 10124 10125 HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas; 10126 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas); 10127 10128 // Make sure all the GPU resources have been properly allocated 10129 if (canvas == null) { 10130 mHardwareLayer.end(currentCanvas); 10131 return null; 10132 } 10133 10134 mAttachInfo.mHardwareCanvas = canvas; 10135 try { 10136 canvas.setViewport(width, height); 10137 canvas.onPreDraw(mLocalDirtyRect); 10138 mLocalDirtyRect.setEmpty(); 10139 10140 final int restoreCount = canvas.save(); 10141 10142 computeScroll(); 10143 canvas.translate(-mScrollX, -mScrollY); 10144 10145 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10146 10147 // Fast path for layouts with no backgrounds 10148 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10149 mPrivateFlags &= ~DIRTY_MASK; 10150 dispatchDraw(canvas); 10151 } else { 10152 draw(canvas); 10153 } 10154 10155 canvas.restoreToCount(restoreCount); 10156 } finally { 10157 canvas.onPostDraw(); 10158 mHardwareLayer.end(currentCanvas); 10159 mAttachInfo.mHardwareCanvas = currentCanvas; 10160 } 10161 } 10162 10163 return mHardwareLayer; 10164 } 10165 10166 /** 10167 * Destroys this View's hardware layer if possible. 10168 * 10169 * @return True if the layer was destroyed, false otherwise. 10170 * 10171 * @see #setLayerType(int, android.graphics.Paint) 10172 * @see #LAYER_TYPE_HARDWARE 10173 */ 10174 boolean destroyLayer() { 10175 if (mHardwareLayer != null) { 10176 mHardwareLayer.destroy(); 10177 mHardwareLayer = null; 10178 return true; 10179 } 10180 return false; 10181 } 10182 10183 /** 10184 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 10185 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 10186 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 10187 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 10188 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 10189 * null.</p> 10190 * 10191 * <p>Enabling the drawing cache is similar to 10192 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 10193 * acceleration is turned off. When hardware acceleration is turned on, enabling the 10194 * drawing cache has no effect on rendering because the system uses a different mechanism 10195 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 10196 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 10197 * for information on how to enable software and hardware layers.</p> 10198 * 10199 * <p>This API can be used to manually generate 10200 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 10201 * {@link #getDrawingCache()}.</p> 10202 * 10203 * @param enabled true to enable the drawing cache, false otherwise 10204 * 10205 * @see #isDrawingCacheEnabled() 10206 * @see #getDrawingCache() 10207 * @see #buildDrawingCache() 10208 * @see #setLayerType(int, android.graphics.Paint) 10209 */ 10210 public void setDrawingCacheEnabled(boolean enabled) { 10211 mCachingFailed = false; 10212 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 10213 } 10214 10215 /** 10216 * <p>Indicates whether the drawing cache is enabled for this view.</p> 10217 * 10218 * @return true if the drawing cache is enabled 10219 * 10220 * @see #setDrawingCacheEnabled(boolean) 10221 * @see #getDrawingCache() 10222 */ 10223 @ViewDebug.ExportedProperty(category = "drawing") 10224 public boolean isDrawingCacheEnabled() { 10225 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 10226 } 10227 10228 /** 10229 * Debugging utility which recursively outputs the dirty state of a view and its 10230 * descendants. 10231 * 10232 * @hide 10233 */ 10234 @SuppressWarnings({"UnusedDeclaration"}) 10235 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 10236 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) + 10237 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" + 10238 (mPrivateFlags & View.DRAWING_CACHE_VALID) + 10239 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")"); 10240 if (clear) { 10241 mPrivateFlags &= clearMask; 10242 } 10243 if (this instanceof ViewGroup) { 10244 ViewGroup parent = (ViewGroup) this; 10245 final int count = parent.getChildCount(); 10246 for (int i = 0; i < count; i++) { 10247 final View child = parent.getChildAt(i); 10248 child.outputDirtyFlags(indent + " ", clear, clearMask); 10249 } 10250 } 10251 } 10252 10253 /** 10254 * This method is used by ViewGroup to cause its children to restore or recreate their 10255 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 10256 * to recreate its own display list, which would happen if it went through the normal 10257 * draw/dispatchDraw mechanisms. 10258 * 10259 * @hide 10260 */ 10261 protected void dispatchGetDisplayList() {} 10262 10263 /** 10264 * A view that is not attached or hardware accelerated cannot create a display list. 10265 * This method checks these conditions and returns the appropriate result. 10266 * 10267 * @return true if view has the ability to create a display list, false otherwise. 10268 * 10269 * @hide 10270 */ 10271 public boolean canHaveDisplayList() { 10272 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 10273 } 10274 10275 /** 10276 * <p>Returns a display list that can be used to draw this view again 10277 * without executing its draw method.</p> 10278 * 10279 * @return A DisplayList ready to replay, or null if caching is not enabled. 10280 * 10281 * @hide 10282 */ 10283 public DisplayList getDisplayList() { 10284 if (!canHaveDisplayList()) { 10285 return null; 10286 } 10287 10288 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || 10289 mDisplayList == null || !mDisplayList.isValid() || 10290 mRecreateDisplayList)) { 10291 // Don't need to recreate the display list, just need to tell our 10292 // children to restore/recreate theirs 10293 if (mDisplayList != null && mDisplayList.isValid() && 10294 !mRecreateDisplayList) { 10295 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10296 mPrivateFlags &= ~DIRTY_MASK; 10297 dispatchGetDisplayList(); 10298 10299 return mDisplayList; 10300 } 10301 10302 // If we got here, we're recreating it. Mark it as such to ensure that 10303 // we copy in child display lists into ours in drawChild() 10304 mRecreateDisplayList = true; 10305 if (mDisplayList == null) { 10306 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(); 10307 // If we're creating a new display list, make sure our parent gets invalidated 10308 // since they will need to recreate their display list to account for this 10309 // new child display list. 10310 invalidateParentCaches(); 10311 } 10312 10313 final HardwareCanvas canvas = mDisplayList.start(); 10314 int restoreCount = 0; 10315 try { 10316 int width = mRight - mLeft; 10317 int height = mBottom - mTop; 10318 10319 canvas.setViewport(width, height); 10320 // The dirty rect should always be null for a display list 10321 canvas.onPreDraw(null); 10322 10323 computeScroll(); 10324 10325 restoreCount = canvas.save(); 10326 canvas.translate(-mScrollX, -mScrollY); 10327 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10328 mPrivateFlags &= ~DIRTY_MASK; 10329 10330 // Fast path for layouts with no backgrounds 10331 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10332 dispatchDraw(canvas); 10333 } else { 10334 draw(canvas); 10335 } 10336 } finally { 10337 canvas.restoreToCount(restoreCount); 10338 canvas.onPostDraw(); 10339 10340 mDisplayList.end(); 10341 } 10342 } else { 10343 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10344 mPrivateFlags &= ~DIRTY_MASK; 10345 } 10346 10347 return mDisplayList; 10348 } 10349 10350 /** 10351 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 10352 * 10353 * @return A non-scaled bitmap representing this view or null if cache is disabled. 10354 * 10355 * @see #getDrawingCache(boolean) 10356 */ 10357 public Bitmap getDrawingCache() { 10358 return getDrawingCache(false); 10359 } 10360 10361 /** 10362 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 10363 * is null when caching is disabled. If caching is enabled and the cache is not ready, 10364 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 10365 * draw from the cache when the cache is enabled. To benefit from the cache, you must 10366 * request the drawing cache by calling this method and draw it on screen if the 10367 * returned bitmap is not null.</p> 10368 * 10369 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10370 * this method will create a bitmap of the same size as this view. Because this bitmap 10371 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10372 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10373 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10374 * size than the view. This implies that your application must be able to handle this 10375 * size.</p> 10376 * 10377 * @param autoScale Indicates whether the generated bitmap should be scaled based on 10378 * the current density of the screen when the application is in compatibility 10379 * mode. 10380 * 10381 * @return A bitmap representing this view or null if cache is disabled. 10382 * 10383 * @see #setDrawingCacheEnabled(boolean) 10384 * @see #isDrawingCacheEnabled() 10385 * @see #buildDrawingCache(boolean) 10386 * @see #destroyDrawingCache() 10387 */ 10388 public Bitmap getDrawingCache(boolean autoScale) { 10389 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 10390 return null; 10391 } 10392 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 10393 buildDrawingCache(autoScale); 10394 } 10395 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 10396 } 10397 10398 /** 10399 * <p>Frees the resources used by the drawing cache. If you call 10400 * {@link #buildDrawingCache()} manually without calling 10401 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10402 * should cleanup the cache with this method afterwards.</p> 10403 * 10404 * @see #setDrawingCacheEnabled(boolean) 10405 * @see #buildDrawingCache() 10406 * @see #getDrawingCache() 10407 */ 10408 public void destroyDrawingCache() { 10409 if (mDrawingCache != null) { 10410 mDrawingCache.recycle(); 10411 mDrawingCache = null; 10412 } 10413 if (mUnscaledDrawingCache != null) { 10414 mUnscaledDrawingCache.recycle(); 10415 mUnscaledDrawingCache = null; 10416 } 10417 } 10418 10419 /** 10420 * Setting a solid background color for the drawing cache's bitmaps will improve 10421 * performance and memory usage. Note, though that this should only be used if this 10422 * view will always be drawn on top of a solid color. 10423 * 10424 * @param color The background color to use for the drawing cache's bitmap 10425 * 10426 * @see #setDrawingCacheEnabled(boolean) 10427 * @see #buildDrawingCache() 10428 * @see #getDrawingCache() 10429 */ 10430 public void setDrawingCacheBackgroundColor(int color) { 10431 if (color != mDrawingCacheBackgroundColor) { 10432 mDrawingCacheBackgroundColor = color; 10433 mPrivateFlags &= ~DRAWING_CACHE_VALID; 10434 } 10435 } 10436 10437 /** 10438 * @see #setDrawingCacheBackgroundColor(int) 10439 * 10440 * @return The background color to used for the drawing cache's bitmap 10441 */ 10442 public int getDrawingCacheBackgroundColor() { 10443 return mDrawingCacheBackgroundColor; 10444 } 10445 10446 /** 10447 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 10448 * 10449 * @see #buildDrawingCache(boolean) 10450 */ 10451 public void buildDrawingCache() { 10452 buildDrawingCache(false); 10453 } 10454 10455 /** 10456 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 10457 * 10458 * <p>If you call {@link #buildDrawingCache()} manually without calling 10459 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10460 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 10461 * 10462 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10463 * this method will create a bitmap of the same size as this view. Because this bitmap 10464 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10465 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10466 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10467 * size than the view. This implies that your application must be able to handle this 10468 * size.</p> 10469 * 10470 * <p>You should avoid calling this method when hardware acceleration is enabled. If 10471 * you do not need the drawing cache bitmap, calling this method will increase memory 10472 * usage and cause the view to be rendered in software once, thus negatively impacting 10473 * performance.</p> 10474 * 10475 * @see #getDrawingCache() 10476 * @see #destroyDrawingCache() 10477 */ 10478 public void buildDrawingCache(boolean autoScale) { 10479 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 10480 mDrawingCache == null : mUnscaledDrawingCache == null)) { 10481 mCachingFailed = false; 10482 10483 if (ViewDebug.TRACE_HIERARCHY) { 10484 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 10485 } 10486 10487 int width = mRight - mLeft; 10488 int height = mBottom - mTop; 10489 10490 final AttachInfo attachInfo = mAttachInfo; 10491 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 10492 10493 if (autoScale && scalingRequired) { 10494 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 10495 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 10496 } 10497 10498 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 10499 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 10500 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 10501 10502 if (width <= 0 || height <= 0 || 10503 // Projected bitmap size in bytes 10504 (width * height * (opaque && !use32BitCache ? 2 : 4) > 10505 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 10506 destroyDrawingCache(); 10507 mCachingFailed = true; 10508 return; 10509 } 10510 10511 boolean clear = true; 10512 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 10513 10514 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 10515 Bitmap.Config quality; 10516 if (!opaque) { 10517 // Never pick ARGB_4444 because it looks awful 10518 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 10519 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 10520 case DRAWING_CACHE_QUALITY_AUTO: 10521 quality = Bitmap.Config.ARGB_8888; 10522 break; 10523 case DRAWING_CACHE_QUALITY_LOW: 10524 quality = Bitmap.Config.ARGB_8888; 10525 break; 10526 case DRAWING_CACHE_QUALITY_HIGH: 10527 quality = Bitmap.Config.ARGB_8888; 10528 break; 10529 default: 10530 quality = Bitmap.Config.ARGB_8888; 10531 break; 10532 } 10533 } else { 10534 // Optimization for translucent windows 10535 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 10536 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 10537 } 10538 10539 // Try to cleanup memory 10540 if (bitmap != null) bitmap.recycle(); 10541 10542 try { 10543 bitmap = Bitmap.createBitmap(width, height, quality); 10544 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 10545 if (autoScale) { 10546 mDrawingCache = bitmap; 10547 } else { 10548 mUnscaledDrawingCache = bitmap; 10549 } 10550 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 10551 } catch (OutOfMemoryError e) { 10552 // If there is not enough memory to create the bitmap cache, just 10553 // ignore the issue as bitmap caches are not required to draw the 10554 // view hierarchy 10555 if (autoScale) { 10556 mDrawingCache = null; 10557 } else { 10558 mUnscaledDrawingCache = null; 10559 } 10560 mCachingFailed = true; 10561 return; 10562 } 10563 10564 clear = drawingCacheBackgroundColor != 0; 10565 } 10566 10567 Canvas canvas; 10568 if (attachInfo != null) { 10569 canvas = attachInfo.mCanvas; 10570 if (canvas == null) { 10571 canvas = new Canvas(); 10572 } 10573 canvas.setBitmap(bitmap); 10574 // Temporarily clobber the cached Canvas in case one of our children 10575 // is also using a drawing cache. Without this, the children would 10576 // steal the canvas by attaching their own bitmap to it and bad, bad 10577 // thing would happen (invisible views, corrupted drawings, etc.) 10578 attachInfo.mCanvas = null; 10579 } else { 10580 // This case should hopefully never or seldom happen 10581 canvas = new Canvas(bitmap); 10582 } 10583 10584 if (clear) { 10585 bitmap.eraseColor(drawingCacheBackgroundColor); 10586 } 10587 10588 computeScroll(); 10589 final int restoreCount = canvas.save(); 10590 10591 if (autoScale && scalingRequired) { 10592 final float scale = attachInfo.mApplicationScale; 10593 canvas.scale(scale, scale); 10594 } 10595 10596 canvas.translate(-mScrollX, -mScrollY); 10597 10598 mPrivateFlags |= DRAWN; 10599 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 10600 mLayerType != LAYER_TYPE_NONE) { 10601 mPrivateFlags |= DRAWING_CACHE_VALID; 10602 } 10603 10604 // Fast path for layouts with no backgrounds 10605 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10606 if (ViewDebug.TRACE_HIERARCHY) { 10607 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 10608 } 10609 mPrivateFlags &= ~DIRTY_MASK; 10610 dispatchDraw(canvas); 10611 } else { 10612 draw(canvas); 10613 } 10614 10615 canvas.restoreToCount(restoreCount); 10616 canvas.setBitmap(null); 10617 10618 if (attachInfo != null) { 10619 // Restore the cached Canvas for our siblings 10620 attachInfo.mCanvas = canvas; 10621 } 10622 } 10623 } 10624 10625 /** 10626 * Create a snapshot of the view into a bitmap. We should probably make 10627 * some form of this public, but should think about the API. 10628 */ 10629 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 10630 int width = mRight - mLeft; 10631 int height = mBottom - mTop; 10632 10633 final AttachInfo attachInfo = mAttachInfo; 10634 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 10635 width = (int) ((width * scale) + 0.5f); 10636 height = (int) ((height * scale) + 0.5f); 10637 10638 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 10639 if (bitmap == null) { 10640 throw new OutOfMemoryError(); 10641 } 10642 10643 Resources resources = getResources(); 10644 if (resources != null) { 10645 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 10646 } 10647 10648 Canvas canvas; 10649 if (attachInfo != null) { 10650 canvas = attachInfo.mCanvas; 10651 if (canvas == null) { 10652 canvas = new Canvas(); 10653 } 10654 canvas.setBitmap(bitmap); 10655 // Temporarily clobber the cached Canvas in case one of our children 10656 // is also using a drawing cache. Without this, the children would 10657 // steal the canvas by attaching their own bitmap to it and bad, bad 10658 // things would happen (invisible views, corrupted drawings, etc.) 10659 attachInfo.mCanvas = null; 10660 } else { 10661 // This case should hopefully never or seldom happen 10662 canvas = new Canvas(bitmap); 10663 } 10664 10665 if ((backgroundColor & 0xff000000) != 0) { 10666 bitmap.eraseColor(backgroundColor); 10667 } 10668 10669 computeScroll(); 10670 final int restoreCount = canvas.save(); 10671 canvas.scale(scale, scale); 10672 canvas.translate(-mScrollX, -mScrollY); 10673 10674 // Temporarily remove the dirty mask 10675 int flags = mPrivateFlags; 10676 mPrivateFlags &= ~DIRTY_MASK; 10677 10678 // Fast path for layouts with no backgrounds 10679 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10680 dispatchDraw(canvas); 10681 } else { 10682 draw(canvas); 10683 } 10684 10685 mPrivateFlags = flags; 10686 10687 canvas.restoreToCount(restoreCount); 10688 canvas.setBitmap(null); 10689 10690 if (attachInfo != null) { 10691 // Restore the cached Canvas for our siblings 10692 attachInfo.mCanvas = canvas; 10693 } 10694 10695 return bitmap; 10696 } 10697 10698 /** 10699 * Indicates whether this View is currently in edit mode. A View is usually 10700 * in edit mode when displayed within a developer tool. For instance, if 10701 * this View is being drawn by a visual user interface builder, this method 10702 * should return true. 10703 * 10704 * Subclasses should check the return value of this method to provide 10705 * different behaviors if their normal behavior might interfere with the 10706 * host environment. For instance: the class spawns a thread in its 10707 * constructor, the drawing code relies on device-specific features, etc. 10708 * 10709 * This method is usually checked in the drawing code of custom widgets. 10710 * 10711 * @return True if this View is in edit mode, false otherwise. 10712 */ 10713 public boolean isInEditMode() { 10714 return false; 10715 } 10716 10717 /** 10718 * If the View draws content inside its padding and enables fading edges, 10719 * it needs to support padding offsets. Padding offsets are added to the 10720 * fading edges to extend the length of the fade so that it covers pixels 10721 * drawn inside the padding. 10722 * 10723 * Subclasses of this class should override this method if they need 10724 * to draw content inside the padding. 10725 * 10726 * @return True if padding offset must be applied, false otherwise. 10727 * 10728 * @see #getLeftPaddingOffset() 10729 * @see #getRightPaddingOffset() 10730 * @see #getTopPaddingOffset() 10731 * @see #getBottomPaddingOffset() 10732 * 10733 * @since CURRENT 10734 */ 10735 protected boolean isPaddingOffsetRequired() { 10736 return false; 10737 } 10738 10739 /** 10740 * Amount by which to extend the left fading region. Called only when 10741 * {@link #isPaddingOffsetRequired()} returns true. 10742 * 10743 * @return The left padding offset in pixels. 10744 * 10745 * @see #isPaddingOffsetRequired() 10746 * 10747 * @since CURRENT 10748 */ 10749 protected int getLeftPaddingOffset() { 10750 return 0; 10751 } 10752 10753 /** 10754 * Amount by which to extend the right fading region. Called only when 10755 * {@link #isPaddingOffsetRequired()} returns true. 10756 * 10757 * @return The right padding offset in pixels. 10758 * 10759 * @see #isPaddingOffsetRequired() 10760 * 10761 * @since CURRENT 10762 */ 10763 protected int getRightPaddingOffset() { 10764 return 0; 10765 } 10766 10767 /** 10768 * Amount by which to extend the top fading region. Called only when 10769 * {@link #isPaddingOffsetRequired()} returns true. 10770 * 10771 * @return The top padding offset in pixels. 10772 * 10773 * @see #isPaddingOffsetRequired() 10774 * 10775 * @since CURRENT 10776 */ 10777 protected int getTopPaddingOffset() { 10778 return 0; 10779 } 10780 10781 /** 10782 * Amount by which to extend the bottom fading region. Called only when 10783 * {@link #isPaddingOffsetRequired()} returns true. 10784 * 10785 * @return The bottom padding offset in pixels. 10786 * 10787 * @see #isPaddingOffsetRequired() 10788 * 10789 * @since CURRENT 10790 */ 10791 protected int getBottomPaddingOffset() { 10792 return 0; 10793 } 10794 10795 /** 10796 * @hide 10797 * @param offsetRequired 10798 */ 10799 protected int getFadeTop(boolean offsetRequired) { 10800 int top = mPaddingTop; 10801 if (offsetRequired) top += getTopPaddingOffset(); 10802 return top; 10803 } 10804 10805 /** 10806 * @hide 10807 * @param offsetRequired 10808 */ 10809 protected int getFadeHeight(boolean offsetRequired) { 10810 int padding = mPaddingTop; 10811 if (offsetRequired) padding += getTopPaddingOffset(); 10812 return mBottom - mTop - mPaddingBottom - padding; 10813 } 10814 10815 /** 10816 * <p>Indicates whether this view is attached to an hardware accelerated 10817 * window or not.</p> 10818 * 10819 * <p>Even if this method returns true, it does not mean that every call 10820 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 10821 * accelerated {@link android.graphics.Canvas}. For instance, if this view 10822 * is drawn onto an offscren {@link android.graphics.Bitmap} and its 10823 * window is hardware accelerated, 10824 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 10825 * return false, and this method will return true.</p> 10826 * 10827 * @return True if the view is attached to a window and the window is 10828 * hardware accelerated; false in any other case. 10829 */ 10830 public boolean isHardwareAccelerated() { 10831 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 10832 } 10833 10834 /** 10835 * Manually render this view (and all of its children) to the given Canvas. 10836 * The view must have already done a full layout before this function is 10837 * called. When implementing a view, implement 10838 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 10839 * If you do need to override this method, call the superclass version. 10840 * 10841 * @param canvas The Canvas to which the View is rendered. 10842 */ 10843 public void draw(Canvas canvas) { 10844 if (ViewDebug.TRACE_HIERARCHY) { 10845 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 10846 } 10847 10848 final int privateFlags = mPrivateFlags; 10849 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 10850 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 10851 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 10852 10853 /* 10854 * Draw traversal performs several drawing steps which must be executed 10855 * in the appropriate order: 10856 * 10857 * 1. Draw the background 10858 * 2. If necessary, save the canvas' layers to prepare for fading 10859 * 3. Draw view's content 10860 * 4. Draw children 10861 * 5. If necessary, draw the fading edges and restore layers 10862 * 6. Draw decorations (scrollbars for instance) 10863 */ 10864 10865 // Step 1, draw the background, if needed 10866 int saveCount; 10867 10868 if (!dirtyOpaque) { 10869 final Drawable background = mBGDrawable; 10870 if (background != null) { 10871 final int scrollX = mScrollX; 10872 final int scrollY = mScrollY; 10873 10874 if (mBackgroundSizeChanged) { 10875 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 10876 mBackgroundSizeChanged = false; 10877 } 10878 10879 if ((scrollX | scrollY) == 0) { 10880 background.draw(canvas); 10881 } else { 10882 canvas.translate(scrollX, scrollY); 10883 background.draw(canvas); 10884 canvas.translate(-scrollX, -scrollY); 10885 } 10886 } 10887 } 10888 10889 // skip step 2 & 5 if possible (common case) 10890 final int viewFlags = mViewFlags; 10891 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 10892 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 10893 if (!verticalEdges && !horizontalEdges) { 10894 // Step 3, draw the content 10895 if (!dirtyOpaque) onDraw(canvas); 10896 10897 // Step 4, draw the children 10898 dispatchDraw(canvas); 10899 10900 // Step 6, draw decorations (scrollbars) 10901 onDrawScrollBars(canvas); 10902 10903 // we're done... 10904 return; 10905 } 10906 10907 /* 10908 * Here we do the full fledged routine... 10909 * (this is an uncommon case where speed matters less, 10910 * this is why we repeat some of the tests that have been 10911 * done above) 10912 */ 10913 10914 boolean drawTop = false; 10915 boolean drawBottom = false; 10916 boolean drawLeft = false; 10917 boolean drawRight = false; 10918 10919 float topFadeStrength = 0.0f; 10920 float bottomFadeStrength = 0.0f; 10921 float leftFadeStrength = 0.0f; 10922 float rightFadeStrength = 0.0f; 10923 10924 // Step 2, save the canvas' layers 10925 int paddingLeft = mPaddingLeft; 10926 10927 final boolean offsetRequired = isPaddingOffsetRequired(); 10928 if (offsetRequired) { 10929 paddingLeft += getLeftPaddingOffset(); 10930 } 10931 10932 int left = mScrollX + paddingLeft; 10933 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 10934 int top = mScrollY + getFadeTop(offsetRequired); 10935 int bottom = top + getFadeHeight(offsetRequired); 10936 10937 if (offsetRequired) { 10938 right += getRightPaddingOffset(); 10939 bottom += getBottomPaddingOffset(); 10940 } 10941 10942 final ScrollabilityCache scrollabilityCache = mScrollCache; 10943 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 10944 int length = (int) fadeHeight; 10945 10946 // clip the fade length if top and bottom fades overlap 10947 // overlapping fades produce odd-looking artifacts 10948 if (verticalEdges && (top + length > bottom - length)) { 10949 length = (bottom - top) / 2; 10950 } 10951 10952 // also clip horizontal fades if necessary 10953 if (horizontalEdges && (left + length > right - length)) { 10954 length = (right - left) / 2; 10955 } 10956 10957 if (verticalEdges) { 10958 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 10959 drawTop = topFadeStrength * fadeHeight > 1.0f; 10960 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 10961 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 10962 } 10963 10964 if (horizontalEdges) { 10965 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 10966 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 10967 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 10968 drawRight = rightFadeStrength * fadeHeight > 1.0f; 10969 } 10970 10971 saveCount = canvas.getSaveCount(); 10972 10973 int solidColor = getSolidColor(); 10974 if (solidColor == 0) { 10975 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 10976 10977 if (drawTop) { 10978 canvas.saveLayer(left, top, right, top + length, null, flags); 10979 } 10980 10981 if (drawBottom) { 10982 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 10983 } 10984 10985 if (drawLeft) { 10986 canvas.saveLayer(left, top, left + length, bottom, null, flags); 10987 } 10988 10989 if (drawRight) { 10990 canvas.saveLayer(right - length, top, right, bottom, null, flags); 10991 } 10992 } else { 10993 scrollabilityCache.setFadeColor(solidColor); 10994 } 10995 10996 // Step 3, draw the content 10997 if (!dirtyOpaque) onDraw(canvas); 10998 10999 // Step 4, draw the children 11000 dispatchDraw(canvas); 11001 11002 // Step 5, draw the fade effect and restore layers 11003 final Paint p = scrollabilityCache.paint; 11004 final Matrix matrix = scrollabilityCache.matrix; 11005 final Shader fade = scrollabilityCache.shader; 11006 11007 if (drawTop) { 11008 matrix.setScale(1, fadeHeight * topFadeStrength); 11009 matrix.postTranslate(left, top); 11010 fade.setLocalMatrix(matrix); 11011 canvas.drawRect(left, top, right, top + length, p); 11012 } 11013 11014 if (drawBottom) { 11015 matrix.setScale(1, fadeHeight * bottomFadeStrength); 11016 matrix.postRotate(180); 11017 matrix.postTranslate(left, bottom); 11018 fade.setLocalMatrix(matrix); 11019 canvas.drawRect(left, bottom - length, right, bottom, p); 11020 } 11021 11022 if (drawLeft) { 11023 matrix.setScale(1, fadeHeight * leftFadeStrength); 11024 matrix.postRotate(-90); 11025 matrix.postTranslate(left, top); 11026 fade.setLocalMatrix(matrix); 11027 canvas.drawRect(left, top, left + length, bottom, p); 11028 } 11029 11030 if (drawRight) { 11031 matrix.setScale(1, fadeHeight * rightFadeStrength); 11032 matrix.postRotate(90); 11033 matrix.postTranslate(right, top); 11034 fade.setLocalMatrix(matrix); 11035 canvas.drawRect(right - length, top, right, bottom, p); 11036 } 11037 11038 canvas.restoreToCount(saveCount); 11039 11040 // Step 6, draw decorations (scrollbars) 11041 onDrawScrollBars(canvas); 11042 } 11043 11044 /** 11045 * Override this if your view is known to always be drawn on top of a solid color background, 11046 * and needs to draw fading edges. Returning a non-zero color enables the view system to 11047 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 11048 * should be set to 0xFF. 11049 * 11050 * @see #setVerticalFadingEdgeEnabled(boolean) 11051 * @see #setHorizontalFadingEdgeEnabled(boolean) 11052 * 11053 * @return The known solid color background for this view, or 0 if the color may vary 11054 */ 11055 @ViewDebug.ExportedProperty(category = "drawing") 11056 public int getSolidColor() { 11057 return 0; 11058 } 11059 11060 /** 11061 * Build a human readable string representation of the specified view flags. 11062 * 11063 * @param flags the view flags to convert to a string 11064 * @return a String representing the supplied flags 11065 */ 11066 private static String printFlags(int flags) { 11067 String output = ""; 11068 int numFlags = 0; 11069 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 11070 output += "TAKES_FOCUS"; 11071 numFlags++; 11072 } 11073 11074 switch (flags & VISIBILITY_MASK) { 11075 case INVISIBLE: 11076 if (numFlags > 0) { 11077 output += " "; 11078 } 11079 output += "INVISIBLE"; 11080 // USELESS HERE numFlags++; 11081 break; 11082 case GONE: 11083 if (numFlags > 0) { 11084 output += " "; 11085 } 11086 output += "GONE"; 11087 // USELESS HERE numFlags++; 11088 break; 11089 default: 11090 break; 11091 } 11092 return output; 11093 } 11094 11095 /** 11096 * Build a human readable string representation of the specified private 11097 * view flags. 11098 * 11099 * @param privateFlags the private view flags to convert to a string 11100 * @return a String representing the supplied flags 11101 */ 11102 private static String printPrivateFlags(int privateFlags) { 11103 String output = ""; 11104 int numFlags = 0; 11105 11106 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 11107 output += "WANTS_FOCUS"; 11108 numFlags++; 11109 } 11110 11111 if ((privateFlags & FOCUSED) == FOCUSED) { 11112 if (numFlags > 0) { 11113 output += " "; 11114 } 11115 output += "FOCUSED"; 11116 numFlags++; 11117 } 11118 11119 if ((privateFlags & SELECTED) == SELECTED) { 11120 if (numFlags > 0) { 11121 output += " "; 11122 } 11123 output += "SELECTED"; 11124 numFlags++; 11125 } 11126 11127 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 11128 if (numFlags > 0) { 11129 output += " "; 11130 } 11131 output += "IS_ROOT_NAMESPACE"; 11132 numFlags++; 11133 } 11134 11135 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 11136 if (numFlags > 0) { 11137 output += " "; 11138 } 11139 output += "HAS_BOUNDS"; 11140 numFlags++; 11141 } 11142 11143 if ((privateFlags & DRAWN) == DRAWN) { 11144 if (numFlags > 0) { 11145 output += " "; 11146 } 11147 output += "DRAWN"; 11148 // USELESS HERE numFlags++; 11149 } 11150 return output; 11151 } 11152 11153 /** 11154 * <p>Indicates whether or not this view's layout will be requested during 11155 * the next hierarchy layout pass.</p> 11156 * 11157 * @return true if the layout will be forced during next layout pass 11158 */ 11159 public boolean isLayoutRequested() { 11160 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 11161 } 11162 11163 /** 11164 * Assign a size and position to a view and all of its 11165 * descendants 11166 * 11167 * <p>This is the second phase of the layout mechanism. 11168 * (The first is measuring). In this phase, each parent calls 11169 * layout on all of its children to position them. 11170 * This is typically done using the child measurements 11171 * that were stored in the measure pass().</p> 11172 * 11173 * <p>Derived classes should not override this method. 11174 * Derived classes with children should override 11175 * onLayout. In that method, they should 11176 * call layout on each of their children.</p> 11177 * 11178 * @param l Left position, relative to parent 11179 * @param t Top position, relative to parent 11180 * @param r Right position, relative to parent 11181 * @param b Bottom position, relative to parent 11182 */ 11183 @SuppressWarnings({"unchecked"}) 11184 public void layout(int l, int t, int r, int b) { 11185 int oldL = mLeft; 11186 int oldT = mTop; 11187 int oldB = mBottom; 11188 int oldR = mRight; 11189 boolean changed = setFrame(l, t, r, b); 11190 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 11191 if (ViewDebug.TRACE_HIERARCHY) { 11192 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 11193 } 11194 11195 onLayout(changed, l, t, r, b); 11196 mPrivateFlags &= ~LAYOUT_REQUIRED; 11197 11198 if (mOnLayoutChangeListeners != null) { 11199 ArrayList<OnLayoutChangeListener> listenersCopy = 11200 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone(); 11201 int numListeners = listenersCopy.size(); 11202 for (int i = 0; i < numListeners; ++i) { 11203 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 11204 } 11205 } 11206 } 11207 mPrivateFlags &= ~FORCE_LAYOUT; 11208 } 11209 11210 /** 11211 * Called from layout when this view should 11212 * assign a size and position to each of its children. 11213 * 11214 * Derived classes with children should override 11215 * this method and call layout on each of 11216 * their children. 11217 * @param changed This is a new size or position for this view 11218 * @param left Left position, relative to parent 11219 * @param top Top position, relative to parent 11220 * @param right Right position, relative to parent 11221 * @param bottom Bottom position, relative to parent 11222 */ 11223 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 11224 } 11225 11226 /** 11227 * Assign a size and position to this view. 11228 * 11229 * This is called from layout. 11230 * 11231 * @param left Left position, relative to parent 11232 * @param top Top position, relative to parent 11233 * @param right Right position, relative to parent 11234 * @param bottom Bottom position, relative to parent 11235 * @return true if the new size and position are different than the 11236 * previous ones 11237 * {@hide} 11238 */ 11239 protected boolean setFrame(int left, int top, int right, int bottom) { 11240 boolean changed = false; 11241 11242 if (DBG) { 11243 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 11244 + right + "," + bottom + ")"); 11245 } 11246 11247 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 11248 changed = true; 11249 11250 // Remember our drawn bit 11251 int drawn = mPrivateFlags & DRAWN; 11252 11253 int oldWidth = mRight - mLeft; 11254 int oldHeight = mBottom - mTop; 11255 int newWidth = right - left; 11256 int newHeight = bottom - top; 11257 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 11258 11259 // Invalidate our old position 11260 invalidate(sizeChanged); 11261 11262 mLeft = left; 11263 mTop = top; 11264 mRight = right; 11265 mBottom = bottom; 11266 11267 mPrivateFlags |= HAS_BOUNDS; 11268 11269 11270 if (sizeChanged) { 11271 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 11272 // A change in dimension means an auto-centered pivot point changes, too 11273 if (mTransformationInfo != null) { 11274 mTransformationInfo.mMatrixDirty = true; 11275 } 11276 } 11277 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 11278 } 11279 11280 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 11281 // If we are visible, force the DRAWN bit to on so that 11282 // this invalidate will go through (at least to our parent). 11283 // This is because someone may have invalidated this view 11284 // before this call to setFrame came in, thereby clearing 11285 // the DRAWN bit. 11286 mPrivateFlags |= DRAWN; 11287 invalidate(sizeChanged); 11288 // parent display list may need to be recreated based on a change in the bounds 11289 // of any child 11290 invalidateParentCaches(); 11291 } 11292 11293 // Reset drawn bit to original value (invalidate turns it off) 11294 mPrivateFlags |= drawn; 11295 11296 mBackgroundSizeChanged = true; 11297 } 11298 return changed; 11299 } 11300 11301 /** 11302 * Finalize inflating a view from XML. This is called as the last phase 11303 * of inflation, after all child views have been added. 11304 * 11305 * <p>Even if the subclass overrides onFinishInflate, they should always be 11306 * sure to call the super method, so that we get called. 11307 */ 11308 protected void onFinishInflate() { 11309 } 11310 11311 /** 11312 * Returns the resources associated with this view. 11313 * 11314 * @return Resources object. 11315 */ 11316 public Resources getResources() { 11317 return mResources; 11318 } 11319 11320 /** 11321 * Invalidates the specified Drawable. 11322 * 11323 * @param drawable the drawable to invalidate 11324 */ 11325 public void invalidateDrawable(Drawable drawable) { 11326 if (verifyDrawable(drawable)) { 11327 final Rect dirty = drawable.getBounds(); 11328 final int scrollX = mScrollX; 11329 final int scrollY = mScrollY; 11330 11331 invalidate(dirty.left + scrollX, dirty.top + scrollY, 11332 dirty.right + scrollX, dirty.bottom + scrollY); 11333 } 11334 } 11335 11336 /** 11337 * Schedules an action on a drawable to occur at a specified time. 11338 * 11339 * @param who the recipient of the action 11340 * @param what the action to run on the drawable 11341 * @param when the time at which the action must occur. Uses the 11342 * {@link SystemClock#uptimeMillis} timebase. 11343 */ 11344 public void scheduleDrawable(Drawable who, Runnable what, long when) { 11345 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 11346 mAttachInfo.mHandler.postAtTime(what, who, when); 11347 } 11348 } 11349 11350 /** 11351 * Cancels a scheduled action on a drawable. 11352 * 11353 * @param who the recipient of the action 11354 * @param what the action to cancel 11355 */ 11356 public void unscheduleDrawable(Drawable who, Runnable what) { 11357 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 11358 mAttachInfo.mHandler.removeCallbacks(what, who); 11359 } 11360 } 11361 11362 /** 11363 * Unschedule any events associated with the given Drawable. This can be 11364 * used when selecting a new Drawable into a view, so that the previous 11365 * one is completely unscheduled. 11366 * 11367 * @param who The Drawable to unschedule. 11368 * 11369 * @see #drawableStateChanged 11370 */ 11371 public void unscheduleDrawable(Drawable who) { 11372 if (mAttachInfo != null) { 11373 mAttachInfo.mHandler.removeCallbacksAndMessages(who); 11374 } 11375 } 11376 11377 /** 11378 * Return the layout direction of a given Drawable. 11379 * 11380 * @param who the Drawable to query 11381 * 11382 * @hide 11383 */ 11384 public int getResolvedLayoutDirection(Drawable who) { 11385 return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT; 11386 } 11387 11388 /** 11389 * If your view subclass is displaying its own Drawable objects, it should 11390 * override this function and return true for any Drawable it is 11391 * displaying. This allows animations for those drawables to be 11392 * scheduled. 11393 * 11394 * <p>Be sure to call through to the super class when overriding this 11395 * function. 11396 * 11397 * @param who The Drawable to verify. Return true if it is one you are 11398 * displaying, else return the result of calling through to the 11399 * super class. 11400 * 11401 * @return boolean If true than the Drawable is being displayed in the 11402 * view; else false and it is not allowed to animate. 11403 * 11404 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 11405 * @see #drawableStateChanged() 11406 */ 11407 protected boolean verifyDrawable(Drawable who) { 11408 return who == mBGDrawable; 11409 } 11410 11411 /** 11412 * This function is called whenever the state of the view changes in such 11413 * a way that it impacts the state of drawables being shown. 11414 * 11415 * <p>Be sure to call through to the superclass when overriding this 11416 * function. 11417 * 11418 * @see Drawable#setState(int[]) 11419 */ 11420 protected void drawableStateChanged() { 11421 Drawable d = mBGDrawable; 11422 if (d != null && d.isStateful()) { 11423 d.setState(getDrawableState()); 11424 } 11425 } 11426 11427 /** 11428 * Call this to force a view to update its drawable state. This will cause 11429 * drawableStateChanged to be called on this view. Views that are interested 11430 * in the new state should call getDrawableState. 11431 * 11432 * @see #drawableStateChanged 11433 * @see #getDrawableState 11434 */ 11435 public void refreshDrawableState() { 11436 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 11437 drawableStateChanged(); 11438 11439 ViewParent parent = mParent; 11440 if (parent != null) { 11441 parent.childDrawableStateChanged(this); 11442 } 11443 } 11444 11445 /** 11446 * Return an array of resource IDs of the drawable states representing the 11447 * current state of the view. 11448 * 11449 * @return The current drawable state 11450 * 11451 * @see Drawable#setState(int[]) 11452 * @see #drawableStateChanged() 11453 * @see #onCreateDrawableState(int) 11454 */ 11455 public final int[] getDrawableState() { 11456 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 11457 return mDrawableState; 11458 } else { 11459 mDrawableState = onCreateDrawableState(0); 11460 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 11461 return mDrawableState; 11462 } 11463 } 11464 11465 /** 11466 * Generate the new {@link android.graphics.drawable.Drawable} state for 11467 * this view. This is called by the view 11468 * system when the cached Drawable state is determined to be invalid. To 11469 * retrieve the current state, you should use {@link #getDrawableState}. 11470 * 11471 * @param extraSpace if non-zero, this is the number of extra entries you 11472 * would like in the returned array in which you can place your own 11473 * states. 11474 * 11475 * @return Returns an array holding the current {@link Drawable} state of 11476 * the view. 11477 * 11478 * @see #mergeDrawableStates(int[], int[]) 11479 */ 11480 protected int[] onCreateDrawableState(int extraSpace) { 11481 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 11482 mParent instanceof View) { 11483 return ((View) mParent).onCreateDrawableState(extraSpace); 11484 } 11485 11486 int[] drawableState; 11487 11488 int privateFlags = mPrivateFlags; 11489 11490 int viewStateIndex = 0; 11491 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 11492 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 11493 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 11494 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 11495 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 11496 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 11497 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 11498 HardwareRenderer.isAvailable()) { 11499 // This is set if HW acceleration is requested, even if the current 11500 // process doesn't allow it. This is just to allow app preview 11501 // windows to better match their app. 11502 viewStateIndex |= VIEW_STATE_ACCELERATED; 11503 } 11504 if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 11505 11506 final int privateFlags2 = mPrivateFlags2; 11507 if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 11508 if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 11509 11510 drawableState = VIEW_STATE_SETS[viewStateIndex]; 11511 11512 //noinspection ConstantIfStatement 11513 if (false) { 11514 Log.i("View", "drawableStateIndex=" + viewStateIndex); 11515 Log.i("View", toString() 11516 + " pressed=" + ((privateFlags & PRESSED) != 0) 11517 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 11518 + " fo=" + hasFocus() 11519 + " sl=" + ((privateFlags & SELECTED) != 0) 11520 + " wf=" + hasWindowFocus() 11521 + ": " + Arrays.toString(drawableState)); 11522 } 11523 11524 if (extraSpace == 0) { 11525 return drawableState; 11526 } 11527 11528 final int[] fullState; 11529 if (drawableState != null) { 11530 fullState = new int[drawableState.length + extraSpace]; 11531 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 11532 } else { 11533 fullState = new int[extraSpace]; 11534 } 11535 11536 return fullState; 11537 } 11538 11539 /** 11540 * Merge your own state values in <var>additionalState</var> into the base 11541 * state values <var>baseState</var> that were returned by 11542 * {@link #onCreateDrawableState(int)}. 11543 * 11544 * @param baseState The base state values returned by 11545 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 11546 * own additional state values. 11547 * 11548 * @param additionalState The additional state values you would like 11549 * added to <var>baseState</var>; this array is not modified. 11550 * 11551 * @return As a convenience, the <var>baseState</var> array you originally 11552 * passed into the function is returned. 11553 * 11554 * @see #onCreateDrawableState(int) 11555 */ 11556 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 11557 final int N = baseState.length; 11558 int i = N - 1; 11559 while (i >= 0 && baseState[i] == 0) { 11560 i--; 11561 } 11562 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 11563 return baseState; 11564 } 11565 11566 /** 11567 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 11568 * on all Drawable objects associated with this view. 11569 */ 11570 public void jumpDrawablesToCurrentState() { 11571 if (mBGDrawable != null) { 11572 mBGDrawable.jumpToCurrentState(); 11573 } 11574 } 11575 11576 /** 11577 * Sets the background color for this view. 11578 * @param color the color of the background 11579 */ 11580 @RemotableViewMethod 11581 public void setBackgroundColor(int color) { 11582 if (mBGDrawable instanceof ColorDrawable) { 11583 ((ColorDrawable) mBGDrawable).setColor(color); 11584 } else { 11585 setBackgroundDrawable(new ColorDrawable(color)); 11586 } 11587 } 11588 11589 /** 11590 * Set the background to a given resource. The resource should refer to 11591 * a Drawable object or 0 to remove the background. 11592 * @param resid The identifier of the resource. 11593 * @attr ref android.R.styleable#View_background 11594 */ 11595 @RemotableViewMethod 11596 public void setBackgroundResource(int resid) { 11597 if (resid != 0 && resid == mBackgroundResource) { 11598 return; 11599 } 11600 11601 Drawable d= null; 11602 if (resid != 0) { 11603 d = mResources.getDrawable(resid); 11604 } 11605 setBackgroundDrawable(d); 11606 11607 mBackgroundResource = resid; 11608 } 11609 11610 /** 11611 * Set the background to a given Drawable, or remove the background. If the 11612 * background has padding, this View's padding is set to the background's 11613 * padding. However, when a background is removed, this View's padding isn't 11614 * touched. If setting the padding is desired, please use 11615 * {@link #setPadding(int, int, int, int)}. 11616 * 11617 * @param d The Drawable to use as the background, or null to remove the 11618 * background 11619 */ 11620 public void setBackgroundDrawable(Drawable d) { 11621 if (d == mBGDrawable) { 11622 return; 11623 } 11624 11625 boolean requestLayout = false; 11626 11627 mBackgroundResource = 0; 11628 11629 /* 11630 * Regardless of whether we're setting a new background or not, we want 11631 * to clear the previous drawable. 11632 */ 11633 if (mBGDrawable != null) { 11634 mBGDrawable.setCallback(null); 11635 unscheduleDrawable(mBGDrawable); 11636 } 11637 11638 if (d != null) { 11639 Rect padding = sThreadLocal.get(); 11640 if (padding == null) { 11641 padding = new Rect(); 11642 sThreadLocal.set(padding); 11643 } 11644 if (d.getPadding(padding)) { 11645 switch (d.getResolvedLayoutDirectionSelf()) { 11646 case LAYOUT_DIRECTION_RTL: 11647 setPadding(padding.right, padding.top, padding.left, padding.bottom); 11648 break; 11649 case LAYOUT_DIRECTION_LTR: 11650 default: 11651 setPadding(padding.left, padding.top, padding.right, padding.bottom); 11652 } 11653 } 11654 11655 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 11656 // if it has a different minimum size, we should layout again 11657 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 11658 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 11659 requestLayout = true; 11660 } 11661 11662 d.setCallback(this); 11663 if (d.isStateful()) { 11664 d.setState(getDrawableState()); 11665 } 11666 d.setVisible(getVisibility() == VISIBLE, false); 11667 mBGDrawable = d; 11668 11669 if ((mPrivateFlags & SKIP_DRAW) != 0) { 11670 mPrivateFlags &= ~SKIP_DRAW; 11671 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 11672 requestLayout = true; 11673 } 11674 } else { 11675 /* Remove the background */ 11676 mBGDrawable = null; 11677 11678 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 11679 /* 11680 * This view ONLY drew the background before and we're removing 11681 * the background, so now it won't draw anything 11682 * (hence we SKIP_DRAW) 11683 */ 11684 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 11685 mPrivateFlags |= SKIP_DRAW; 11686 } 11687 11688 /* 11689 * When the background is set, we try to apply its padding to this 11690 * View. When the background is removed, we don't touch this View's 11691 * padding. This is noted in the Javadocs. Hence, we don't need to 11692 * requestLayout(), the invalidate() below is sufficient. 11693 */ 11694 11695 // The old background's minimum size could have affected this 11696 // View's layout, so let's requestLayout 11697 requestLayout = true; 11698 } 11699 11700 computeOpaqueFlags(); 11701 11702 if (requestLayout) { 11703 requestLayout(); 11704 } 11705 11706 mBackgroundSizeChanged = true; 11707 invalidate(true); 11708 } 11709 11710 /** 11711 * Gets the background drawable 11712 * @return The drawable used as the background for this view, if any. 11713 */ 11714 public Drawable getBackground() { 11715 return mBGDrawable; 11716 } 11717 11718 /** 11719 * Sets the padding. The view may add on the space required to display 11720 * the scrollbars, depending on the style and visibility of the scrollbars. 11721 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 11722 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 11723 * from the values set in this call. 11724 * 11725 * @attr ref android.R.styleable#View_padding 11726 * @attr ref android.R.styleable#View_paddingBottom 11727 * @attr ref android.R.styleable#View_paddingLeft 11728 * @attr ref android.R.styleable#View_paddingRight 11729 * @attr ref android.R.styleable#View_paddingTop 11730 * @param left the left padding in pixels 11731 * @param top the top padding in pixels 11732 * @param right the right padding in pixels 11733 * @param bottom the bottom padding in pixels 11734 */ 11735 public void setPadding(int left, int top, int right, int bottom) { 11736 boolean changed = false; 11737 11738 mUserPaddingRelative = false; 11739 11740 mUserPaddingLeft = left; 11741 mUserPaddingRight = right; 11742 mUserPaddingBottom = bottom; 11743 11744 final int viewFlags = mViewFlags; 11745 11746 // Common case is there are no scroll bars. 11747 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 11748 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 11749 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 11750 ? 0 : getVerticalScrollbarWidth(); 11751 switch (mVerticalScrollbarPosition) { 11752 case SCROLLBAR_POSITION_DEFAULT: 11753 if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 11754 left += offset; 11755 } else { 11756 right += offset; 11757 } 11758 break; 11759 case SCROLLBAR_POSITION_RIGHT: 11760 right += offset; 11761 break; 11762 case SCROLLBAR_POSITION_LEFT: 11763 left += offset; 11764 break; 11765 } 11766 } 11767 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 11768 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 11769 ? 0 : getHorizontalScrollbarHeight(); 11770 } 11771 } 11772 11773 if (mPaddingLeft != left) { 11774 changed = true; 11775 mPaddingLeft = left; 11776 } 11777 if (mPaddingTop != top) { 11778 changed = true; 11779 mPaddingTop = top; 11780 } 11781 if (mPaddingRight != right) { 11782 changed = true; 11783 mPaddingRight = right; 11784 } 11785 if (mPaddingBottom != bottom) { 11786 changed = true; 11787 mPaddingBottom = bottom; 11788 } 11789 11790 if (changed) { 11791 requestLayout(); 11792 } 11793 } 11794 11795 /** 11796 * Sets the relative padding. The view may add on the space required to display 11797 * the scrollbars, depending on the style and visibility of the scrollbars. 11798 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 11799 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 11800 * from the values set in this call. 11801 * 11802 * @attr ref android.R.styleable#View_padding 11803 * @attr ref android.R.styleable#View_paddingBottom 11804 * @attr ref android.R.styleable#View_paddingStart 11805 * @attr ref android.R.styleable#View_paddingEnd 11806 * @attr ref android.R.styleable#View_paddingTop 11807 * @param start the start padding in pixels 11808 * @param top the top padding in pixels 11809 * @param end the end padding in pixels 11810 * @param bottom the bottom padding in pixels 11811 * 11812 * @hide 11813 */ 11814 public void setPaddingRelative(int start, int top, int end, int bottom) { 11815 mUserPaddingRelative = true; 11816 11817 mUserPaddingStart = start; 11818 mUserPaddingEnd = end; 11819 11820 switch(getResolvedLayoutDirection()) { 11821 case LAYOUT_DIRECTION_RTL: 11822 setPadding(end, top, start, bottom); 11823 break; 11824 case LAYOUT_DIRECTION_LTR: 11825 default: 11826 setPadding(start, top, end, bottom); 11827 } 11828 } 11829 11830 /** 11831 * Returns the top padding of this view. 11832 * 11833 * @return the top padding in pixels 11834 */ 11835 public int getPaddingTop() { 11836 return mPaddingTop; 11837 } 11838 11839 /** 11840 * Returns the bottom padding of this view. If there are inset and enabled 11841 * scrollbars, this value may include the space required to display the 11842 * scrollbars as well. 11843 * 11844 * @return the bottom padding in pixels 11845 */ 11846 public int getPaddingBottom() { 11847 return mPaddingBottom; 11848 } 11849 11850 /** 11851 * Returns the left padding of this view. If there are inset and enabled 11852 * scrollbars, this value may include the space required to display the 11853 * scrollbars as well. 11854 * 11855 * @return the left padding in pixels 11856 */ 11857 public int getPaddingLeft() { 11858 return mPaddingLeft; 11859 } 11860 11861 /** 11862 * Returns the start padding of this view. If there are inset and enabled 11863 * scrollbars, this value may include the space required to display the 11864 * scrollbars as well. 11865 * 11866 * @return the start padding in pixels 11867 * 11868 * @hide 11869 */ 11870 public int getPaddingStart() { 11871 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 11872 mPaddingRight : mPaddingLeft; 11873 } 11874 11875 /** 11876 * Returns the right padding of this view. If there are inset and enabled 11877 * scrollbars, this value may include the space required to display the 11878 * scrollbars as well. 11879 * 11880 * @return the right padding in pixels 11881 */ 11882 public int getPaddingRight() { 11883 return mPaddingRight; 11884 } 11885 11886 /** 11887 * Returns the end padding of this view. If there are inset and enabled 11888 * scrollbars, this value may include the space required to display the 11889 * scrollbars as well. 11890 * 11891 * @return the end padding in pixels 11892 * 11893 * @hide 11894 */ 11895 public int getPaddingEnd() { 11896 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 11897 mPaddingLeft : mPaddingRight; 11898 } 11899 11900 /** 11901 * Return if the padding as been set thru relative values 11902 * {@link #setPaddingRelative(int, int, int, int)} or thru 11903 * @attr ref android.R.styleable#View_paddingStart or 11904 * @attr ref android.R.styleable#View_paddingEnd 11905 * 11906 * @return true if the padding is relative or false if it is not. 11907 * 11908 * @hide 11909 */ 11910 public boolean isPaddingRelative() { 11911 return mUserPaddingRelative; 11912 } 11913 11914 /** 11915 * Changes the selection state of this view. A view can be selected or not. 11916 * Note that selection is not the same as focus. Views are typically 11917 * selected in the context of an AdapterView like ListView or GridView; 11918 * the selected view is the view that is highlighted. 11919 * 11920 * @param selected true if the view must be selected, false otherwise 11921 */ 11922 public void setSelected(boolean selected) { 11923 if (((mPrivateFlags & SELECTED) != 0) != selected) { 11924 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 11925 if (!selected) resetPressedState(); 11926 invalidate(true); 11927 refreshDrawableState(); 11928 dispatchSetSelected(selected); 11929 } 11930 } 11931 11932 /** 11933 * Dispatch setSelected to all of this View's children. 11934 * 11935 * @see #setSelected(boolean) 11936 * 11937 * @param selected The new selected state 11938 */ 11939 protected void dispatchSetSelected(boolean selected) { 11940 } 11941 11942 /** 11943 * Indicates the selection state of this view. 11944 * 11945 * @return true if the view is selected, false otherwise 11946 */ 11947 @ViewDebug.ExportedProperty 11948 public boolean isSelected() { 11949 return (mPrivateFlags & SELECTED) != 0; 11950 } 11951 11952 /** 11953 * Changes the activated state of this view. A view can be activated or not. 11954 * Note that activation is not the same as selection. Selection is 11955 * a transient property, representing the view (hierarchy) the user is 11956 * currently interacting with. Activation is a longer-term state that the 11957 * user can move views in and out of. For example, in a list view with 11958 * single or multiple selection enabled, the views in the current selection 11959 * set are activated. (Um, yeah, we are deeply sorry about the terminology 11960 * here.) The activated state is propagated down to children of the view it 11961 * is set on. 11962 * 11963 * @param activated true if the view must be activated, false otherwise 11964 */ 11965 public void setActivated(boolean activated) { 11966 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 11967 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 11968 invalidate(true); 11969 refreshDrawableState(); 11970 dispatchSetActivated(activated); 11971 } 11972 } 11973 11974 /** 11975 * Dispatch setActivated to all of this View's children. 11976 * 11977 * @see #setActivated(boolean) 11978 * 11979 * @param activated The new activated state 11980 */ 11981 protected void dispatchSetActivated(boolean activated) { 11982 } 11983 11984 /** 11985 * Indicates the activation state of this view. 11986 * 11987 * @return true if the view is activated, false otherwise 11988 */ 11989 @ViewDebug.ExportedProperty 11990 public boolean isActivated() { 11991 return (mPrivateFlags & ACTIVATED) != 0; 11992 } 11993 11994 /** 11995 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 11996 * observer can be used to get notifications when global events, like 11997 * layout, happen. 11998 * 11999 * The returned ViewTreeObserver observer is not guaranteed to remain 12000 * valid for the lifetime of this View. If the caller of this method keeps 12001 * a long-lived reference to ViewTreeObserver, it should always check for 12002 * the return value of {@link ViewTreeObserver#isAlive()}. 12003 * 12004 * @return The ViewTreeObserver for this view's hierarchy. 12005 */ 12006 public ViewTreeObserver getViewTreeObserver() { 12007 if (mAttachInfo != null) { 12008 return mAttachInfo.mTreeObserver; 12009 } 12010 if (mFloatingTreeObserver == null) { 12011 mFloatingTreeObserver = new ViewTreeObserver(); 12012 } 12013 return mFloatingTreeObserver; 12014 } 12015 12016 /** 12017 * <p>Finds the topmost view in the current view hierarchy.</p> 12018 * 12019 * @return the topmost view containing this view 12020 */ 12021 public View getRootView() { 12022 if (mAttachInfo != null) { 12023 final View v = mAttachInfo.mRootView; 12024 if (v != null) { 12025 return v; 12026 } 12027 } 12028 12029 View parent = this; 12030 12031 while (parent.mParent != null && parent.mParent instanceof View) { 12032 parent = (View) parent.mParent; 12033 } 12034 12035 return parent; 12036 } 12037 12038 /** 12039 * <p>Computes the coordinates of this view on the screen. The argument 12040 * must be an array of two integers. After the method returns, the array 12041 * contains the x and y location in that order.</p> 12042 * 12043 * @param location an array of two integers in which to hold the coordinates 12044 */ 12045 public void getLocationOnScreen(int[] location) { 12046 getLocationInWindow(location); 12047 12048 final AttachInfo info = mAttachInfo; 12049 if (info != null) { 12050 location[0] += info.mWindowLeft; 12051 location[1] += info.mWindowTop; 12052 } 12053 } 12054 12055 /** 12056 * <p>Computes the coordinates of this view in its window. The argument 12057 * must be an array of two integers. After the method returns, the array 12058 * contains the x and y location in that order.</p> 12059 * 12060 * @param location an array of two integers in which to hold the coordinates 12061 */ 12062 public void getLocationInWindow(int[] location) { 12063 if (location == null || location.length < 2) { 12064 throw new IllegalArgumentException("location must be an array of " 12065 + "two integers"); 12066 } 12067 12068 location[0] = mLeft; 12069 location[1] = mTop; 12070 if (mTransformationInfo != null) { 12071 location[0] += (int) (mTransformationInfo.mTranslationX + 0.5f); 12072 location[1] += (int) (mTransformationInfo.mTranslationY + 0.5f); 12073 } 12074 12075 ViewParent viewParent = mParent; 12076 while (viewParent instanceof View) { 12077 final View view = (View)viewParent; 12078 location[0] += view.mLeft - view.mScrollX; 12079 location[1] += view.mTop - view.mScrollY; 12080 if (view.mTransformationInfo != null) { 12081 location[0] += (int) (view.mTransformationInfo.mTranslationX + 0.5f); 12082 location[1] += (int) (view.mTransformationInfo.mTranslationY + 0.5f); 12083 } 12084 viewParent = view.mParent; 12085 } 12086 12087 if (viewParent instanceof ViewRootImpl) { 12088 // *cough* 12089 final ViewRootImpl vr = (ViewRootImpl)viewParent; 12090 location[1] -= vr.mCurScrollY; 12091 } 12092 } 12093 12094 /** 12095 * {@hide} 12096 * @param id the id of the view to be found 12097 * @return the view of the specified id, null if cannot be found 12098 */ 12099 protected View findViewTraversal(int id) { 12100 if (id == mID) { 12101 return this; 12102 } 12103 return null; 12104 } 12105 12106 /** 12107 * {@hide} 12108 * @param tag the tag of the view to be found 12109 * @return the view of specified tag, null if cannot be found 12110 */ 12111 protected View findViewWithTagTraversal(Object tag) { 12112 if (tag != null && tag.equals(mTag)) { 12113 return this; 12114 } 12115 return null; 12116 } 12117 12118 /** 12119 * {@hide} 12120 * @param predicate The predicate to evaluate. 12121 * @param childToSkip If not null, ignores this child during the recursive traversal. 12122 * @return The first view that matches the predicate or null. 12123 */ 12124 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 12125 if (predicate.apply(this)) { 12126 return this; 12127 } 12128 return null; 12129 } 12130 12131 /** 12132 * Look for a child view with the given id. If this view has the given 12133 * id, return this view. 12134 * 12135 * @param id The id to search for. 12136 * @return The view that has the given id in the hierarchy or null 12137 */ 12138 public final View findViewById(int id) { 12139 if (id < 0) { 12140 return null; 12141 } 12142 return findViewTraversal(id); 12143 } 12144 12145 /** 12146 * Finds a view by its unuque and stable accessibility id. 12147 * 12148 * @param accessibilityId The searched accessibility id. 12149 * @return The found view. 12150 */ 12151 final View findViewByAccessibilityId(int accessibilityId) { 12152 if (accessibilityId < 0) { 12153 return null; 12154 } 12155 return findViewByAccessibilityIdTraversal(accessibilityId); 12156 } 12157 12158 /** 12159 * Performs the traversal to find a view by its unuque and stable accessibility id. 12160 * 12161 * <strong>Note:</strong>This method does not stop at the root namespace 12162 * boundary since the user can touch the screen at an arbitrary location 12163 * potentially crossing the root namespace bounday which will send an 12164 * accessibility event to accessibility services and they should be able 12165 * to obtain the event source. Also accessibility ids are guaranteed to be 12166 * unique in the window. 12167 * 12168 * @param accessibilityId The accessibility id. 12169 * @return The found view. 12170 */ 12171 View findViewByAccessibilityIdTraversal(int accessibilityId) { 12172 if (getAccessibilityViewId() == accessibilityId) { 12173 return this; 12174 } 12175 return null; 12176 } 12177 12178 /** 12179 * Look for a child view with the given tag. If this view has the given 12180 * tag, return this view. 12181 * 12182 * @param tag The tag to search for, using "tag.equals(getTag())". 12183 * @return The View that has the given tag in the hierarchy or null 12184 */ 12185 public final View findViewWithTag(Object tag) { 12186 if (tag == null) { 12187 return null; 12188 } 12189 return findViewWithTagTraversal(tag); 12190 } 12191 12192 /** 12193 * {@hide} 12194 * Look for a child view that matches the specified predicate. 12195 * If this view matches the predicate, return this view. 12196 * 12197 * @param predicate The predicate to evaluate. 12198 * @return The first view that matches the predicate or null. 12199 */ 12200 public final View findViewByPredicate(Predicate<View> predicate) { 12201 return findViewByPredicateTraversal(predicate, null); 12202 } 12203 12204 /** 12205 * {@hide} 12206 * Look for a child view that matches the specified predicate, 12207 * starting with the specified view and its descendents and then 12208 * recusively searching the ancestors and siblings of that view 12209 * until this view is reached. 12210 * 12211 * This method is useful in cases where the predicate does not match 12212 * a single unique view (perhaps multiple views use the same id) 12213 * and we are trying to find the view that is "closest" in scope to the 12214 * starting view. 12215 * 12216 * @param start The view to start from. 12217 * @param predicate The predicate to evaluate. 12218 * @return The first view that matches the predicate or null. 12219 */ 12220 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 12221 View childToSkip = null; 12222 for (;;) { 12223 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 12224 if (view != null || start == this) { 12225 return view; 12226 } 12227 12228 ViewParent parent = start.getParent(); 12229 if (parent == null || !(parent instanceof View)) { 12230 return null; 12231 } 12232 12233 childToSkip = start; 12234 start = (View) parent; 12235 } 12236 } 12237 12238 /** 12239 * Sets the identifier for this view. The identifier does not have to be 12240 * unique in this view's hierarchy. The identifier should be a positive 12241 * number. 12242 * 12243 * @see #NO_ID 12244 * @see #getId() 12245 * @see #findViewById(int) 12246 * 12247 * @param id a number used to identify the view 12248 * 12249 * @attr ref android.R.styleable#View_id 12250 */ 12251 public void setId(int id) { 12252 mID = id; 12253 } 12254 12255 /** 12256 * {@hide} 12257 * 12258 * @param isRoot true if the view belongs to the root namespace, false 12259 * otherwise 12260 */ 12261 public void setIsRootNamespace(boolean isRoot) { 12262 if (isRoot) { 12263 mPrivateFlags |= IS_ROOT_NAMESPACE; 12264 } else { 12265 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 12266 } 12267 } 12268 12269 /** 12270 * {@hide} 12271 * 12272 * @return true if the view belongs to the root namespace, false otherwise 12273 */ 12274 public boolean isRootNamespace() { 12275 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 12276 } 12277 12278 /** 12279 * Returns this view's identifier. 12280 * 12281 * @return a positive integer used to identify the view or {@link #NO_ID} 12282 * if the view has no ID 12283 * 12284 * @see #setId(int) 12285 * @see #findViewById(int) 12286 * @attr ref android.R.styleable#View_id 12287 */ 12288 @ViewDebug.CapturedViewProperty 12289 public int getId() { 12290 return mID; 12291 } 12292 12293 /** 12294 * Returns this view's tag. 12295 * 12296 * @return the Object stored in this view as a tag 12297 * 12298 * @see #setTag(Object) 12299 * @see #getTag(int) 12300 */ 12301 @ViewDebug.ExportedProperty 12302 public Object getTag() { 12303 return mTag; 12304 } 12305 12306 /** 12307 * Sets the tag associated with this view. A tag can be used to mark 12308 * a view in its hierarchy and does not have to be unique within the 12309 * hierarchy. Tags can also be used to store data within a view without 12310 * resorting to another data structure. 12311 * 12312 * @param tag an Object to tag the view with 12313 * 12314 * @see #getTag() 12315 * @see #setTag(int, Object) 12316 */ 12317 public void setTag(final Object tag) { 12318 mTag = tag; 12319 } 12320 12321 /** 12322 * Returns the tag associated with this view and the specified key. 12323 * 12324 * @param key The key identifying the tag 12325 * 12326 * @return the Object stored in this view as a tag 12327 * 12328 * @see #setTag(int, Object) 12329 * @see #getTag() 12330 */ 12331 public Object getTag(int key) { 12332 if (mKeyedTags != null) return mKeyedTags.get(key); 12333 return null; 12334 } 12335 12336 /** 12337 * Sets a tag associated with this view and a key. A tag can be used 12338 * to mark a view in its hierarchy and does not have to be unique within 12339 * the hierarchy. Tags can also be used to store data within a view 12340 * without resorting to another data structure. 12341 * 12342 * The specified key should be an id declared in the resources of the 12343 * application to ensure it is unique (see the <a 12344 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 12345 * Keys identified as belonging to 12346 * the Android framework or not associated with any package will cause 12347 * an {@link IllegalArgumentException} to be thrown. 12348 * 12349 * @param key The key identifying the tag 12350 * @param tag An Object to tag the view with 12351 * 12352 * @throws IllegalArgumentException If they specified key is not valid 12353 * 12354 * @see #setTag(Object) 12355 * @see #getTag(int) 12356 */ 12357 public void setTag(int key, final Object tag) { 12358 // If the package id is 0x00 or 0x01, it's either an undefined package 12359 // or a framework id 12360 if ((key >>> 24) < 2) { 12361 throw new IllegalArgumentException("The key must be an application-specific " 12362 + "resource id."); 12363 } 12364 12365 setKeyedTag(key, tag); 12366 } 12367 12368 /** 12369 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 12370 * framework id. 12371 * 12372 * @hide 12373 */ 12374 public void setTagInternal(int key, Object tag) { 12375 if ((key >>> 24) != 0x1) { 12376 throw new IllegalArgumentException("The key must be a framework-specific " 12377 + "resource id."); 12378 } 12379 12380 setKeyedTag(key, tag); 12381 } 12382 12383 private void setKeyedTag(int key, Object tag) { 12384 if (mKeyedTags == null) { 12385 mKeyedTags = new SparseArray<Object>(); 12386 } 12387 12388 mKeyedTags.put(key, tag); 12389 } 12390 12391 /** 12392 * @param consistency The type of consistency. See ViewDebug for more information. 12393 * 12394 * @hide 12395 */ 12396 protected boolean dispatchConsistencyCheck(int consistency) { 12397 return onConsistencyCheck(consistency); 12398 } 12399 12400 /** 12401 * Method that subclasses should implement to check their consistency. The type of 12402 * consistency check is indicated by the bit field passed as a parameter. 12403 * 12404 * @param consistency The type of consistency. See ViewDebug for more information. 12405 * 12406 * @throws IllegalStateException if the view is in an inconsistent state. 12407 * 12408 * @hide 12409 */ 12410 protected boolean onConsistencyCheck(int consistency) { 12411 boolean result = true; 12412 12413 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 12414 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 12415 12416 if (checkLayout) { 12417 if (getParent() == null) { 12418 result = false; 12419 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12420 "View " + this + " does not have a parent."); 12421 } 12422 12423 if (mAttachInfo == null) { 12424 result = false; 12425 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12426 "View " + this + " is not attached to a window."); 12427 } 12428 } 12429 12430 if (checkDrawing) { 12431 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 12432 // from their draw() method 12433 12434 if ((mPrivateFlags & DRAWN) != DRAWN && 12435 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 12436 result = false; 12437 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12438 "View " + this + " was invalidated but its drawing cache is valid."); 12439 } 12440 } 12441 12442 return result; 12443 } 12444 12445 /** 12446 * Prints information about this view in the log output, with the tag 12447 * {@link #VIEW_LOG_TAG}. 12448 * 12449 * @hide 12450 */ 12451 public void debug() { 12452 debug(0); 12453 } 12454 12455 /** 12456 * Prints information about this view in the log output, with the tag 12457 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 12458 * indentation defined by the <code>depth</code>. 12459 * 12460 * @param depth the indentation level 12461 * 12462 * @hide 12463 */ 12464 protected void debug(int depth) { 12465 String output = debugIndent(depth - 1); 12466 12467 output += "+ " + this; 12468 int id = getId(); 12469 if (id != -1) { 12470 output += " (id=" + id + ")"; 12471 } 12472 Object tag = getTag(); 12473 if (tag != null) { 12474 output += " (tag=" + tag + ")"; 12475 } 12476 Log.d(VIEW_LOG_TAG, output); 12477 12478 if ((mPrivateFlags & FOCUSED) != 0) { 12479 output = debugIndent(depth) + " FOCUSED"; 12480 Log.d(VIEW_LOG_TAG, output); 12481 } 12482 12483 output = debugIndent(depth); 12484 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 12485 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 12486 + "} "; 12487 Log.d(VIEW_LOG_TAG, output); 12488 12489 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 12490 || mPaddingBottom != 0) { 12491 output = debugIndent(depth); 12492 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 12493 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 12494 Log.d(VIEW_LOG_TAG, output); 12495 } 12496 12497 output = debugIndent(depth); 12498 output += "mMeasureWidth=" + mMeasuredWidth + 12499 " mMeasureHeight=" + mMeasuredHeight; 12500 Log.d(VIEW_LOG_TAG, output); 12501 12502 output = debugIndent(depth); 12503 if (mLayoutParams == null) { 12504 output += "BAD! no layout params"; 12505 } else { 12506 output = mLayoutParams.debug(output); 12507 } 12508 Log.d(VIEW_LOG_TAG, output); 12509 12510 output = debugIndent(depth); 12511 output += "flags={"; 12512 output += View.printFlags(mViewFlags); 12513 output += "}"; 12514 Log.d(VIEW_LOG_TAG, output); 12515 12516 output = debugIndent(depth); 12517 output += "privateFlags={"; 12518 output += View.printPrivateFlags(mPrivateFlags); 12519 output += "}"; 12520 Log.d(VIEW_LOG_TAG, output); 12521 } 12522 12523 /** 12524 * Creates an string of whitespaces used for indentation. 12525 * 12526 * @param depth the indentation level 12527 * @return a String containing (depth * 2 + 3) * 2 white spaces 12528 * 12529 * @hide 12530 */ 12531 protected static String debugIndent(int depth) { 12532 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 12533 for (int i = 0; i < (depth * 2) + 3; i++) { 12534 spaces.append(' ').append(' '); 12535 } 12536 return spaces.toString(); 12537 } 12538 12539 /** 12540 * <p>Return the offset of the widget's text baseline from the widget's top 12541 * boundary. If this widget does not support baseline alignment, this 12542 * method returns -1. </p> 12543 * 12544 * @return the offset of the baseline within the widget's bounds or -1 12545 * if baseline alignment is not supported 12546 */ 12547 @ViewDebug.ExportedProperty(category = "layout") 12548 public int getBaseline() { 12549 return -1; 12550 } 12551 12552 /** 12553 * Call this when something has changed which has invalidated the 12554 * layout of this view. This will schedule a layout pass of the view 12555 * tree. 12556 */ 12557 public void requestLayout() { 12558 if (ViewDebug.TRACE_HIERARCHY) { 12559 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 12560 } 12561 12562 mPrivateFlags |= FORCE_LAYOUT; 12563 mPrivateFlags |= INVALIDATED; 12564 12565 if (mParent != null) { 12566 if (mLayoutParams != null) { 12567 mLayoutParams.resolveWithDirection(getResolvedLayoutDirection()); 12568 } 12569 if (!mParent.isLayoutRequested()) { 12570 mParent.requestLayout(); 12571 } 12572 } 12573 } 12574 12575 /** 12576 * Forces this view to be laid out during the next layout pass. 12577 * This method does not call requestLayout() or forceLayout() 12578 * on the parent. 12579 */ 12580 public void forceLayout() { 12581 mPrivateFlags |= FORCE_LAYOUT; 12582 mPrivateFlags |= INVALIDATED; 12583 } 12584 12585 /** 12586 * <p> 12587 * This is called to find out how big a view should be. The parent 12588 * supplies constraint information in the width and height parameters. 12589 * </p> 12590 * 12591 * <p> 12592 * The actual mesurement work of a view is performed in 12593 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 12594 * {@link #onMeasure(int, int)} can and must be overriden by subclasses. 12595 * </p> 12596 * 12597 * 12598 * @param widthMeasureSpec Horizontal space requirements as imposed by the 12599 * parent 12600 * @param heightMeasureSpec Vertical space requirements as imposed by the 12601 * parent 12602 * 12603 * @see #onMeasure(int, int) 12604 */ 12605 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 12606 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 12607 widthMeasureSpec != mOldWidthMeasureSpec || 12608 heightMeasureSpec != mOldHeightMeasureSpec) { 12609 12610 // first clears the measured dimension flag 12611 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 12612 12613 if (ViewDebug.TRACE_HIERARCHY) { 12614 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 12615 } 12616 12617 // measure ourselves, this should set the measured dimension flag back 12618 onMeasure(widthMeasureSpec, heightMeasureSpec); 12619 12620 // flag not set, setMeasuredDimension() was not invoked, we raise 12621 // an exception to warn the developer 12622 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 12623 throw new IllegalStateException("onMeasure() did not set the" 12624 + " measured dimension by calling" 12625 + " setMeasuredDimension()"); 12626 } 12627 12628 mPrivateFlags |= LAYOUT_REQUIRED; 12629 } 12630 12631 mOldWidthMeasureSpec = widthMeasureSpec; 12632 mOldHeightMeasureSpec = heightMeasureSpec; 12633 } 12634 12635 /** 12636 * <p> 12637 * Measure the view and its content to determine the measured width and the 12638 * measured height. This method is invoked by {@link #measure(int, int)} and 12639 * should be overriden by subclasses to provide accurate and efficient 12640 * measurement of their contents. 12641 * </p> 12642 * 12643 * <p> 12644 * <strong>CONTRACT:</strong> When overriding this method, you 12645 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 12646 * measured width and height of this view. Failure to do so will trigger an 12647 * <code>IllegalStateException</code>, thrown by 12648 * {@link #measure(int, int)}. Calling the superclass' 12649 * {@link #onMeasure(int, int)} is a valid use. 12650 * </p> 12651 * 12652 * <p> 12653 * The base class implementation of measure defaults to the background size, 12654 * unless a larger size is allowed by the MeasureSpec. Subclasses should 12655 * override {@link #onMeasure(int, int)} to provide better measurements of 12656 * their content. 12657 * </p> 12658 * 12659 * <p> 12660 * If this method is overridden, it is the subclass's responsibility to make 12661 * sure the measured height and width are at least the view's minimum height 12662 * and width ({@link #getSuggestedMinimumHeight()} and 12663 * {@link #getSuggestedMinimumWidth()}). 12664 * </p> 12665 * 12666 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 12667 * The requirements are encoded with 12668 * {@link android.view.View.MeasureSpec}. 12669 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 12670 * The requirements are encoded with 12671 * {@link android.view.View.MeasureSpec}. 12672 * 12673 * @see #getMeasuredWidth() 12674 * @see #getMeasuredHeight() 12675 * @see #setMeasuredDimension(int, int) 12676 * @see #getSuggestedMinimumHeight() 12677 * @see #getSuggestedMinimumWidth() 12678 * @see android.view.View.MeasureSpec#getMode(int) 12679 * @see android.view.View.MeasureSpec#getSize(int) 12680 */ 12681 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 12682 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 12683 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 12684 } 12685 12686 /** 12687 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 12688 * measured width and measured height. Failing to do so will trigger an 12689 * exception at measurement time.</p> 12690 * 12691 * @param measuredWidth The measured width of this view. May be a complex 12692 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 12693 * {@link #MEASURED_STATE_TOO_SMALL}. 12694 * @param measuredHeight The measured height of this view. May be a complex 12695 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 12696 * {@link #MEASURED_STATE_TOO_SMALL}. 12697 */ 12698 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 12699 mMeasuredWidth = measuredWidth; 12700 mMeasuredHeight = measuredHeight; 12701 12702 mPrivateFlags |= MEASURED_DIMENSION_SET; 12703 } 12704 12705 /** 12706 * Merge two states as returned by {@link #getMeasuredState()}. 12707 * @param curState The current state as returned from a view or the result 12708 * of combining multiple views. 12709 * @param newState The new view state to combine. 12710 * @return Returns a new integer reflecting the combination of the two 12711 * states. 12712 */ 12713 public static int combineMeasuredStates(int curState, int newState) { 12714 return curState | newState; 12715 } 12716 12717 /** 12718 * Version of {@link #resolveSizeAndState(int, int, int)} 12719 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 12720 */ 12721 public static int resolveSize(int size, int measureSpec) { 12722 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 12723 } 12724 12725 /** 12726 * Utility to reconcile a desired size and state, with constraints imposed 12727 * by a MeasureSpec. Will take the desired size, unless a different size 12728 * is imposed by the constraints. The returned value is a compound integer, 12729 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 12730 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 12731 * size is smaller than the size the view wants to be. 12732 * 12733 * @param size How big the view wants to be 12734 * @param measureSpec Constraints imposed by the parent 12735 * @return Size information bit mask as defined by 12736 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 12737 */ 12738 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 12739 int result = size; 12740 int specMode = MeasureSpec.getMode(measureSpec); 12741 int specSize = MeasureSpec.getSize(measureSpec); 12742 switch (specMode) { 12743 case MeasureSpec.UNSPECIFIED: 12744 result = size; 12745 break; 12746 case MeasureSpec.AT_MOST: 12747 if (specSize < size) { 12748 result = specSize | MEASURED_STATE_TOO_SMALL; 12749 } else { 12750 result = size; 12751 } 12752 break; 12753 case MeasureSpec.EXACTLY: 12754 result = specSize; 12755 break; 12756 } 12757 return result | (childMeasuredState&MEASURED_STATE_MASK); 12758 } 12759 12760 /** 12761 * Utility to return a default size. Uses the supplied size if the 12762 * MeasureSpec imposed no constraints. Will get larger if allowed 12763 * by the MeasureSpec. 12764 * 12765 * @param size Default size for this view 12766 * @param measureSpec Constraints imposed by the parent 12767 * @return The size this view should be. 12768 */ 12769 public static int getDefaultSize(int size, int measureSpec) { 12770 int result = size; 12771 int specMode = MeasureSpec.getMode(measureSpec); 12772 int specSize = MeasureSpec.getSize(measureSpec); 12773 12774 switch (specMode) { 12775 case MeasureSpec.UNSPECIFIED: 12776 result = size; 12777 break; 12778 case MeasureSpec.AT_MOST: 12779 case MeasureSpec.EXACTLY: 12780 result = specSize; 12781 break; 12782 } 12783 return result; 12784 } 12785 12786 /** 12787 * Returns the suggested minimum height that the view should use. This 12788 * returns the maximum of the view's minimum height 12789 * and the background's minimum height 12790 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 12791 * <p> 12792 * When being used in {@link #onMeasure(int, int)}, the caller should still 12793 * ensure the returned height is within the requirements of the parent. 12794 * 12795 * @return The suggested minimum height of the view. 12796 */ 12797 protected int getSuggestedMinimumHeight() { 12798 int suggestedMinHeight = mMinHeight; 12799 12800 if (mBGDrawable != null) { 12801 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 12802 if (suggestedMinHeight < bgMinHeight) { 12803 suggestedMinHeight = bgMinHeight; 12804 } 12805 } 12806 12807 return suggestedMinHeight; 12808 } 12809 12810 /** 12811 * Returns the suggested minimum width that the view should use. This 12812 * returns the maximum of the view's minimum width) 12813 * and the background's minimum width 12814 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 12815 * <p> 12816 * When being used in {@link #onMeasure(int, int)}, the caller should still 12817 * ensure the returned width is within the requirements of the parent. 12818 * 12819 * @return The suggested minimum width of the view. 12820 */ 12821 protected int getSuggestedMinimumWidth() { 12822 int suggestedMinWidth = mMinWidth; 12823 12824 if (mBGDrawable != null) { 12825 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 12826 if (suggestedMinWidth < bgMinWidth) { 12827 suggestedMinWidth = bgMinWidth; 12828 } 12829 } 12830 12831 return suggestedMinWidth; 12832 } 12833 12834 /** 12835 * Sets the minimum height of the view. It is not guaranteed the view will 12836 * be able to achieve this minimum height (for example, if its parent layout 12837 * constrains it with less available height). 12838 * 12839 * @param minHeight The minimum height the view will try to be. 12840 */ 12841 public void setMinimumHeight(int minHeight) { 12842 mMinHeight = minHeight; 12843 } 12844 12845 /** 12846 * Sets the minimum width of the view. It is not guaranteed the view will 12847 * be able to achieve this minimum width (for example, if its parent layout 12848 * constrains it with less available width). 12849 * 12850 * @param minWidth The minimum width the view will try to be. 12851 */ 12852 public void setMinimumWidth(int minWidth) { 12853 mMinWidth = minWidth; 12854 } 12855 12856 /** 12857 * Get the animation currently associated with this view. 12858 * 12859 * @return The animation that is currently playing or 12860 * scheduled to play for this view. 12861 */ 12862 public Animation getAnimation() { 12863 return mCurrentAnimation; 12864 } 12865 12866 /** 12867 * Start the specified animation now. 12868 * 12869 * @param animation the animation to start now 12870 */ 12871 public void startAnimation(Animation animation) { 12872 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 12873 setAnimation(animation); 12874 invalidateParentCaches(); 12875 invalidate(true); 12876 } 12877 12878 /** 12879 * Cancels any animations for this view. 12880 */ 12881 public void clearAnimation() { 12882 if (mCurrentAnimation != null) { 12883 mCurrentAnimation.detach(); 12884 } 12885 mCurrentAnimation = null; 12886 invalidateParentIfNeeded(); 12887 } 12888 12889 /** 12890 * Sets the next animation to play for this view. 12891 * If you want the animation to play immediately, use 12892 * startAnimation. This method provides allows fine-grained 12893 * control over the start time and invalidation, but you 12894 * must make sure that 1) the animation has a start time set, and 12895 * 2) the view will be invalidated when the animation is supposed to 12896 * start. 12897 * 12898 * @param animation The next animation, or null. 12899 */ 12900 public void setAnimation(Animation animation) { 12901 mCurrentAnimation = animation; 12902 if (animation != null) { 12903 animation.reset(); 12904 } 12905 } 12906 12907 /** 12908 * Invoked by a parent ViewGroup to notify the start of the animation 12909 * currently associated with this view. If you override this method, 12910 * always call super.onAnimationStart(); 12911 * 12912 * @see #setAnimation(android.view.animation.Animation) 12913 * @see #getAnimation() 12914 */ 12915 protected void onAnimationStart() { 12916 mPrivateFlags |= ANIMATION_STARTED; 12917 } 12918 12919 /** 12920 * Invoked by a parent ViewGroup to notify the end of the animation 12921 * currently associated with this view. If you override this method, 12922 * always call super.onAnimationEnd(); 12923 * 12924 * @see #setAnimation(android.view.animation.Animation) 12925 * @see #getAnimation() 12926 */ 12927 protected void onAnimationEnd() { 12928 mPrivateFlags &= ~ANIMATION_STARTED; 12929 } 12930 12931 /** 12932 * Invoked if there is a Transform that involves alpha. Subclass that can 12933 * draw themselves with the specified alpha should return true, and then 12934 * respect that alpha when their onDraw() is called. If this returns false 12935 * then the view may be redirected to draw into an offscreen buffer to 12936 * fulfill the request, which will look fine, but may be slower than if the 12937 * subclass handles it internally. The default implementation returns false. 12938 * 12939 * @param alpha The alpha (0..255) to apply to the view's drawing 12940 * @return true if the view can draw with the specified alpha. 12941 */ 12942 protected boolean onSetAlpha(int alpha) { 12943 return false; 12944 } 12945 12946 /** 12947 * This is used by the RootView to perform an optimization when 12948 * the view hierarchy contains one or several SurfaceView. 12949 * SurfaceView is always considered transparent, but its children are not, 12950 * therefore all View objects remove themselves from the global transparent 12951 * region (passed as a parameter to this function). 12952 * 12953 * @param region The transparent region for this ViewAncestor (window). 12954 * 12955 * @return Returns true if the effective visibility of the view at this 12956 * point is opaque, regardless of the transparent region; returns false 12957 * if it is possible for underlying windows to be seen behind the view. 12958 * 12959 * {@hide} 12960 */ 12961 public boolean gatherTransparentRegion(Region region) { 12962 final AttachInfo attachInfo = mAttachInfo; 12963 if (region != null && attachInfo != null) { 12964 final int pflags = mPrivateFlags; 12965 if ((pflags & SKIP_DRAW) == 0) { 12966 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 12967 // remove it from the transparent region. 12968 final int[] location = attachInfo.mTransparentLocation; 12969 getLocationInWindow(location); 12970 region.op(location[0], location[1], location[0] + mRight - mLeft, 12971 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 12972 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 12973 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 12974 // exists, so we remove the background drawable's non-transparent 12975 // parts from this transparent region. 12976 applyDrawableToTransparentRegion(mBGDrawable, region); 12977 } 12978 } 12979 return true; 12980 } 12981 12982 /** 12983 * Play a sound effect for this view. 12984 * 12985 * <p>The framework will play sound effects for some built in actions, such as 12986 * clicking, but you may wish to play these effects in your widget, 12987 * for instance, for internal navigation. 12988 * 12989 * <p>The sound effect will only be played if sound effects are enabled by the user, and 12990 * {@link #isSoundEffectsEnabled()} is true. 12991 * 12992 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 12993 */ 12994 public void playSoundEffect(int soundConstant) { 12995 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 12996 return; 12997 } 12998 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 12999 } 13000 13001 /** 13002 * BZZZTT!!1! 13003 * 13004 * <p>Provide haptic feedback to the user for this view. 13005 * 13006 * <p>The framework will provide haptic feedback for some built in actions, 13007 * such as long presses, but you may wish to provide feedback for your 13008 * own widget. 13009 * 13010 * <p>The feedback will only be performed if 13011 * {@link #isHapticFeedbackEnabled()} is true. 13012 * 13013 * @param feedbackConstant One of the constants defined in 13014 * {@link HapticFeedbackConstants} 13015 */ 13016 public boolean performHapticFeedback(int feedbackConstant) { 13017 return performHapticFeedback(feedbackConstant, 0); 13018 } 13019 13020 /** 13021 * BZZZTT!!1! 13022 * 13023 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 13024 * 13025 * @param feedbackConstant One of the constants defined in 13026 * {@link HapticFeedbackConstants} 13027 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 13028 */ 13029 public boolean performHapticFeedback(int feedbackConstant, int flags) { 13030 if (mAttachInfo == null) { 13031 return false; 13032 } 13033 //noinspection SimplifiableIfStatement 13034 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 13035 && !isHapticFeedbackEnabled()) { 13036 return false; 13037 } 13038 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 13039 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 13040 } 13041 13042 /** 13043 * Request that the visibility of the status bar be changed. 13044 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 13045 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 13046 */ 13047 public void setSystemUiVisibility(int visibility) { 13048 if (visibility != mSystemUiVisibility) { 13049 mSystemUiVisibility = visibility; 13050 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 13051 mParent.recomputeViewAttributes(this); 13052 } 13053 } 13054 } 13055 13056 /** 13057 * Returns the status bar visibility that this view has requested. 13058 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 13059 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 13060 */ 13061 public int getSystemUiVisibility() { 13062 return mSystemUiVisibility; 13063 } 13064 13065 /** 13066 * Set a listener to receive callbacks when the visibility of the system bar changes. 13067 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 13068 */ 13069 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 13070 mOnSystemUiVisibilityChangeListener = l; 13071 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 13072 mParent.recomputeViewAttributes(this); 13073 } 13074 } 13075 13076 /** 13077 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 13078 * the view hierarchy. 13079 */ 13080 public void dispatchSystemUiVisibilityChanged(int visibility) { 13081 if (mOnSystemUiVisibilityChangeListener != null) { 13082 mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 13083 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 13084 } 13085 } 13086 13087 void updateLocalSystemUiVisibility(int localValue, int localChanges) { 13088 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 13089 if (val != mSystemUiVisibility) { 13090 setSystemUiVisibility(val); 13091 } 13092 } 13093 13094 /** 13095 * Creates an image that the system displays during the drag and drop 13096 * operation. This is called a "drag shadow". The default implementation 13097 * for a DragShadowBuilder based on a View returns an image that has exactly the same 13098 * appearance as the given View. The default also positions the center of the drag shadow 13099 * directly under the touch point. If no View is provided (the constructor with no parameters 13100 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 13101 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 13102 * default is an invisible drag shadow. 13103 * <p> 13104 * You are not required to use the View you provide to the constructor as the basis of the 13105 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 13106 * anything you want as the drag shadow. 13107 * </p> 13108 * <p> 13109 * You pass a DragShadowBuilder object to the system when you start the drag. The system 13110 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 13111 * size and position of the drag shadow. It uses this data to construct a 13112 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 13113 * so that your application can draw the shadow image in the Canvas. 13114 * </p> 13115 * 13116 * <div class="special reference"> 13117 * <h3>Developer Guides</h3> 13118 * <p>For a guide to implementing drag and drop features, read the 13119 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 13120 * </div> 13121 */ 13122 public static class DragShadowBuilder { 13123 private final WeakReference<View> mView; 13124 13125 /** 13126 * Constructs a shadow image builder based on a View. By default, the resulting drag 13127 * shadow will have the same appearance and dimensions as the View, with the touch point 13128 * over the center of the View. 13129 * @param view A View. Any View in scope can be used. 13130 */ 13131 public DragShadowBuilder(View view) { 13132 mView = new WeakReference<View>(view); 13133 } 13134 13135 /** 13136 * Construct a shadow builder object with no associated View. This 13137 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 13138 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 13139 * to supply the drag shadow's dimensions and appearance without 13140 * reference to any View object. If they are not overridden, then the result is an 13141 * invisible drag shadow. 13142 */ 13143 public DragShadowBuilder() { 13144 mView = new WeakReference<View>(null); 13145 } 13146 13147 /** 13148 * Returns the View object that had been passed to the 13149 * {@link #View.DragShadowBuilder(View)} 13150 * constructor. If that View parameter was {@code null} or if the 13151 * {@link #View.DragShadowBuilder()} 13152 * constructor was used to instantiate the builder object, this method will return 13153 * null. 13154 * 13155 * @return The View object associate with this builder object. 13156 */ 13157 @SuppressWarnings({"JavadocReference"}) 13158 final public View getView() { 13159 return mView.get(); 13160 } 13161 13162 /** 13163 * Provides the metrics for the shadow image. These include the dimensions of 13164 * the shadow image, and the point within that shadow that should 13165 * be centered under the touch location while dragging. 13166 * <p> 13167 * The default implementation sets the dimensions of the shadow to be the 13168 * same as the dimensions of the View itself and centers the shadow under 13169 * the touch point. 13170 * </p> 13171 * 13172 * @param shadowSize A {@link android.graphics.Point} containing the width and height 13173 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 13174 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 13175 * image. 13176 * 13177 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 13178 * shadow image that should be underneath the touch point during the drag and drop 13179 * operation. Your application must set {@link android.graphics.Point#x} to the 13180 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 13181 */ 13182 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 13183 final View view = mView.get(); 13184 if (view != null) { 13185 shadowSize.set(view.getWidth(), view.getHeight()); 13186 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 13187 } else { 13188 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 13189 } 13190 } 13191 13192 /** 13193 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 13194 * based on the dimensions it received from the 13195 * {@link #onProvideShadowMetrics(Point, Point)} callback. 13196 * 13197 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 13198 */ 13199 public void onDrawShadow(Canvas canvas) { 13200 final View view = mView.get(); 13201 if (view != null) { 13202 view.draw(canvas); 13203 } else { 13204 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 13205 } 13206 } 13207 } 13208 13209 /** 13210 * Starts a drag and drop operation. When your application calls this method, it passes a 13211 * {@link android.view.View.DragShadowBuilder} object to the system. The 13212 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 13213 * to get metrics for the drag shadow, and then calls the object's 13214 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 13215 * <p> 13216 * Once the system has the drag shadow, it begins the drag and drop operation by sending 13217 * drag events to all the View objects in your application that are currently visible. It does 13218 * this either by calling the View object's drag listener (an implementation of 13219 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 13220 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 13221 * Both are passed a {@link android.view.DragEvent} object that has a 13222 * {@link android.view.DragEvent#getAction()} value of 13223 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 13224 * </p> 13225 * <p> 13226 * Your application can invoke startDrag() on any attached View object. The View object does not 13227 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 13228 * be related to the View the user selected for dragging. 13229 * </p> 13230 * @param data A {@link android.content.ClipData} object pointing to the data to be 13231 * transferred by the drag and drop operation. 13232 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 13233 * drag shadow. 13234 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 13235 * drop operation. This Object is put into every DragEvent object sent by the system during the 13236 * current drag. 13237 * <p> 13238 * myLocalState is a lightweight mechanism for the sending information from the dragged View 13239 * to the target Views. For example, it can contain flags that differentiate between a 13240 * a copy operation and a move operation. 13241 * </p> 13242 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 13243 * so the parameter should be set to 0. 13244 * @return {@code true} if the method completes successfully, or 13245 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 13246 * do a drag, and so no drag operation is in progress. 13247 */ 13248 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 13249 Object myLocalState, int flags) { 13250 if (ViewDebug.DEBUG_DRAG) { 13251 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 13252 } 13253 boolean okay = false; 13254 13255 Point shadowSize = new Point(); 13256 Point shadowTouchPoint = new Point(); 13257 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 13258 13259 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 13260 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 13261 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 13262 } 13263 13264 if (ViewDebug.DEBUG_DRAG) { 13265 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 13266 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 13267 } 13268 Surface surface = new Surface(); 13269 try { 13270 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 13271 flags, shadowSize.x, shadowSize.y, surface); 13272 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 13273 + " surface=" + surface); 13274 if (token != null) { 13275 Canvas canvas = surface.lockCanvas(null); 13276 try { 13277 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 13278 shadowBuilder.onDrawShadow(canvas); 13279 } finally { 13280 surface.unlockCanvasAndPost(canvas); 13281 } 13282 13283 final ViewRootImpl root = getViewRootImpl(); 13284 13285 // Cache the local state object for delivery with DragEvents 13286 root.setLocalDragState(myLocalState); 13287 13288 // repurpose 'shadowSize' for the last touch point 13289 root.getLastTouchPoint(shadowSize); 13290 13291 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 13292 shadowSize.x, shadowSize.y, 13293 shadowTouchPoint.x, shadowTouchPoint.y, data); 13294 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 13295 13296 // Off and running! Release our local surface instance; the drag 13297 // shadow surface is now managed by the system process. 13298 surface.release(); 13299 } 13300 } catch (Exception e) { 13301 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 13302 surface.destroy(); 13303 } 13304 13305 return okay; 13306 } 13307 13308 /** 13309 * Handles drag events sent by the system following a call to 13310 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 13311 *<p> 13312 * When the system calls this method, it passes a 13313 * {@link android.view.DragEvent} object. A call to 13314 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 13315 * in DragEvent. The method uses these to determine what is happening in the drag and drop 13316 * operation. 13317 * @param event The {@link android.view.DragEvent} sent by the system. 13318 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 13319 * in DragEvent, indicating the type of drag event represented by this object. 13320 * @return {@code true} if the method was successful, otherwise {@code false}. 13321 * <p> 13322 * The method should return {@code true} in response to an action type of 13323 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 13324 * operation. 13325 * </p> 13326 * <p> 13327 * The method should also return {@code true} in response to an action type of 13328 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 13329 * {@code false} if it didn't. 13330 * </p> 13331 */ 13332 public boolean onDragEvent(DragEvent event) { 13333 return false; 13334 } 13335 13336 /** 13337 * Detects if this View is enabled and has a drag event listener. 13338 * If both are true, then it calls the drag event listener with the 13339 * {@link android.view.DragEvent} it received. If the drag event listener returns 13340 * {@code true}, then dispatchDragEvent() returns {@code true}. 13341 * <p> 13342 * For all other cases, the method calls the 13343 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 13344 * method and returns its result. 13345 * </p> 13346 * <p> 13347 * This ensures that a drag event is always consumed, even if the View does not have a drag 13348 * event listener. However, if the View has a listener and the listener returns true, then 13349 * onDragEvent() is not called. 13350 * </p> 13351 */ 13352 public boolean dispatchDragEvent(DragEvent event) { 13353 //noinspection SimplifiableIfStatement 13354 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 13355 && mOnDragListener.onDrag(this, event)) { 13356 return true; 13357 } 13358 return onDragEvent(event); 13359 } 13360 13361 boolean canAcceptDrag() { 13362 return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0; 13363 } 13364 13365 /** 13366 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 13367 * it is ever exposed at all. 13368 * @hide 13369 */ 13370 public void onCloseSystemDialogs(String reason) { 13371 } 13372 13373 /** 13374 * Given a Drawable whose bounds have been set to draw into this view, 13375 * update a Region being computed for 13376 * {@link #gatherTransparentRegion(android.graphics.Region)} so 13377 * that any non-transparent parts of the Drawable are removed from the 13378 * given transparent region. 13379 * 13380 * @param dr The Drawable whose transparency is to be applied to the region. 13381 * @param region A Region holding the current transparency information, 13382 * where any parts of the region that are set are considered to be 13383 * transparent. On return, this region will be modified to have the 13384 * transparency information reduced by the corresponding parts of the 13385 * Drawable that are not transparent. 13386 * {@hide} 13387 */ 13388 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 13389 if (DBG) { 13390 Log.i("View", "Getting transparent region for: " + this); 13391 } 13392 final Region r = dr.getTransparentRegion(); 13393 final Rect db = dr.getBounds(); 13394 final AttachInfo attachInfo = mAttachInfo; 13395 if (r != null && attachInfo != null) { 13396 final int w = getRight()-getLeft(); 13397 final int h = getBottom()-getTop(); 13398 if (db.left > 0) { 13399 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 13400 r.op(0, 0, db.left, h, Region.Op.UNION); 13401 } 13402 if (db.right < w) { 13403 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 13404 r.op(db.right, 0, w, h, Region.Op.UNION); 13405 } 13406 if (db.top > 0) { 13407 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 13408 r.op(0, 0, w, db.top, Region.Op.UNION); 13409 } 13410 if (db.bottom < h) { 13411 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 13412 r.op(0, db.bottom, w, h, Region.Op.UNION); 13413 } 13414 final int[] location = attachInfo.mTransparentLocation; 13415 getLocationInWindow(location); 13416 r.translate(location[0], location[1]); 13417 region.op(r, Region.Op.INTERSECT); 13418 } else { 13419 region.op(db, Region.Op.DIFFERENCE); 13420 } 13421 } 13422 13423 private void checkForLongClick(int delayOffset) { 13424 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 13425 mHasPerformedLongPress = false; 13426 13427 if (mPendingCheckForLongPress == null) { 13428 mPendingCheckForLongPress = new CheckForLongPress(); 13429 } 13430 mPendingCheckForLongPress.rememberWindowAttachCount(); 13431 postDelayed(mPendingCheckForLongPress, 13432 ViewConfiguration.getLongPressTimeout() - delayOffset); 13433 } 13434 } 13435 13436 /** 13437 * Inflate a view from an XML resource. This convenience method wraps the {@link 13438 * LayoutInflater} class, which provides a full range of options for view inflation. 13439 * 13440 * @param context The Context object for your activity or application. 13441 * @param resource The resource ID to inflate 13442 * @param root A view group that will be the parent. Used to properly inflate the 13443 * layout_* parameters. 13444 * @see LayoutInflater 13445 */ 13446 public static View inflate(Context context, int resource, ViewGroup root) { 13447 LayoutInflater factory = LayoutInflater.from(context); 13448 return factory.inflate(resource, root); 13449 } 13450 13451 /** 13452 * Scroll the view with standard behavior for scrolling beyond the normal 13453 * content boundaries. Views that call this method should override 13454 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 13455 * results of an over-scroll operation. 13456 * 13457 * Views can use this method to handle any touch or fling-based scrolling. 13458 * 13459 * @param deltaX Change in X in pixels 13460 * @param deltaY Change in Y in pixels 13461 * @param scrollX Current X scroll value in pixels before applying deltaX 13462 * @param scrollY Current Y scroll value in pixels before applying deltaY 13463 * @param scrollRangeX Maximum content scroll range along the X axis 13464 * @param scrollRangeY Maximum content scroll range along the Y axis 13465 * @param maxOverScrollX Number of pixels to overscroll by in either direction 13466 * along the X axis. 13467 * @param maxOverScrollY Number of pixels to overscroll by in either direction 13468 * along the Y axis. 13469 * @param isTouchEvent true if this scroll operation is the result of a touch event. 13470 * @return true if scrolling was clamped to an over-scroll boundary along either 13471 * axis, false otherwise. 13472 */ 13473 @SuppressWarnings({"UnusedParameters"}) 13474 protected boolean overScrollBy(int deltaX, int deltaY, 13475 int scrollX, int scrollY, 13476 int scrollRangeX, int scrollRangeY, 13477 int maxOverScrollX, int maxOverScrollY, 13478 boolean isTouchEvent) { 13479 final int overScrollMode = mOverScrollMode; 13480 final boolean canScrollHorizontal = 13481 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 13482 final boolean canScrollVertical = 13483 computeVerticalScrollRange() > computeVerticalScrollExtent(); 13484 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 13485 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 13486 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 13487 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 13488 13489 int newScrollX = scrollX + deltaX; 13490 if (!overScrollHorizontal) { 13491 maxOverScrollX = 0; 13492 } 13493 13494 int newScrollY = scrollY + deltaY; 13495 if (!overScrollVertical) { 13496 maxOverScrollY = 0; 13497 } 13498 13499 // Clamp values if at the limits and record 13500 final int left = -maxOverScrollX; 13501 final int right = maxOverScrollX + scrollRangeX; 13502 final int top = -maxOverScrollY; 13503 final int bottom = maxOverScrollY + scrollRangeY; 13504 13505 boolean clampedX = false; 13506 if (newScrollX > right) { 13507 newScrollX = right; 13508 clampedX = true; 13509 } else if (newScrollX < left) { 13510 newScrollX = left; 13511 clampedX = true; 13512 } 13513 13514 boolean clampedY = false; 13515 if (newScrollY > bottom) { 13516 newScrollY = bottom; 13517 clampedY = true; 13518 } else if (newScrollY < top) { 13519 newScrollY = top; 13520 clampedY = true; 13521 } 13522 13523 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 13524 13525 return clampedX || clampedY; 13526 } 13527 13528 /** 13529 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 13530 * respond to the results of an over-scroll operation. 13531 * 13532 * @param scrollX New X scroll value in pixels 13533 * @param scrollY New Y scroll value in pixels 13534 * @param clampedX True if scrollX was clamped to an over-scroll boundary 13535 * @param clampedY True if scrollY was clamped to an over-scroll boundary 13536 */ 13537 protected void onOverScrolled(int scrollX, int scrollY, 13538 boolean clampedX, boolean clampedY) { 13539 // Intentionally empty. 13540 } 13541 13542 /** 13543 * Returns the over-scroll mode for this view. The result will be 13544 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 13545 * (allow over-scrolling only if the view content is larger than the container), 13546 * or {@link #OVER_SCROLL_NEVER}. 13547 * 13548 * @return This view's over-scroll mode. 13549 */ 13550 public int getOverScrollMode() { 13551 return mOverScrollMode; 13552 } 13553 13554 /** 13555 * Set the over-scroll mode for this view. Valid over-scroll modes are 13556 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 13557 * (allow over-scrolling only if the view content is larger than the container), 13558 * or {@link #OVER_SCROLL_NEVER}. 13559 * 13560 * Setting the over-scroll mode of a view will have an effect only if the 13561 * view is capable of scrolling. 13562 * 13563 * @param overScrollMode The new over-scroll mode for this view. 13564 */ 13565 public void setOverScrollMode(int overScrollMode) { 13566 if (overScrollMode != OVER_SCROLL_ALWAYS && 13567 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 13568 overScrollMode != OVER_SCROLL_NEVER) { 13569 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 13570 } 13571 mOverScrollMode = overScrollMode; 13572 } 13573 13574 /** 13575 * Gets a scale factor that determines the distance the view should scroll 13576 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 13577 * @return The vertical scroll scale factor. 13578 * @hide 13579 */ 13580 protected float getVerticalScrollFactor() { 13581 if (mVerticalScrollFactor == 0) { 13582 TypedValue outValue = new TypedValue(); 13583 if (!mContext.getTheme().resolveAttribute( 13584 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 13585 throw new IllegalStateException( 13586 "Expected theme to define listPreferredItemHeight."); 13587 } 13588 mVerticalScrollFactor = outValue.getDimension( 13589 mContext.getResources().getDisplayMetrics()); 13590 } 13591 return mVerticalScrollFactor; 13592 } 13593 13594 /** 13595 * Gets a scale factor that determines the distance the view should scroll 13596 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 13597 * @return The horizontal scroll scale factor. 13598 * @hide 13599 */ 13600 protected float getHorizontalScrollFactor() { 13601 // TODO: Should use something else. 13602 return getVerticalScrollFactor(); 13603 } 13604 13605 /** 13606 * Return the value specifying the text direction or policy that was set with 13607 * {@link #setTextDirection(int)}. 13608 * 13609 * @return the defined text direction. It can be one of: 13610 * 13611 * {@link #TEXT_DIRECTION_INHERIT}, 13612 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13613 * {@link #TEXT_DIRECTION_ANY_RTL}, 13614 * {@link #TEXT_DIRECTION_LTR}, 13615 * {@link #TEXT_DIRECTION_RTL}, 13616 * 13617 * @hide 13618 */ 13619 public int getTextDirection() { 13620 return mTextDirection; 13621 } 13622 13623 /** 13624 * Set the text direction. 13625 * 13626 * @param textDirection the direction to set. Should be one of: 13627 * 13628 * {@link #TEXT_DIRECTION_INHERIT}, 13629 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13630 * {@link #TEXT_DIRECTION_ANY_RTL}, 13631 * {@link #TEXT_DIRECTION_LTR}, 13632 * {@link #TEXT_DIRECTION_RTL}, 13633 * 13634 * @hide 13635 */ 13636 public void setTextDirection(int textDirection) { 13637 if (textDirection != mTextDirection) { 13638 mTextDirection = textDirection; 13639 resetResolvedTextDirection(); 13640 requestLayout(); 13641 } 13642 } 13643 13644 /** 13645 * Return the resolved text direction. 13646 * 13647 * @return the resolved text direction. Return one of: 13648 * 13649 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13650 * {@link #TEXT_DIRECTION_ANY_RTL}, 13651 * {@link #TEXT_DIRECTION_LTR}, 13652 * {@link #TEXT_DIRECTION_RTL}, 13653 * 13654 * @hide 13655 */ 13656 public int getResolvedTextDirection() { 13657 if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) { 13658 resolveTextDirection(); 13659 } 13660 return mResolvedTextDirection; 13661 } 13662 13663 /** 13664 * Resolve the text direction. 13665 * 13666 * @hide 13667 */ 13668 protected void resolveTextDirection() { 13669 if (mTextDirection != TEXT_DIRECTION_INHERIT) { 13670 mResolvedTextDirection = mTextDirection; 13671 return; 13672 } 13673 if (mParent != null && mParent instanceof ViewGroup) { 13674 mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection(); 13675 return; 13676 } 13677 mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG; 13678 } 13679 13680 /** 13681 * Reset resolved text direction. Will be resolved during a call to getResolvedTextDirection(). 13682 * 13683 * @hide 13684 */ 13685 protected void resetResolvedTextDirection() { 13686 mResolvedTextDirection = TEXT_DIRECTION_INHERIT; 13687 } 13688 13689 // 13690 // Properties 13691 // 13692 /** 13693 * A Property wrapper around the <code>alpha</code> functionality handled by the 13694 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 13695 */ 13696 public static Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 13697 @Override 13698 public void setValue(View object, float value) { 13699 object.setAlpha(value); 13700 } 13701 13702 @Override 13703 public Float get(View object) { 13704 return object.getAlpha(); 13705 } 13706 }; 13707 13708 /** 13709 * A Property wrapper around the <code>translationX</code> functionality handled by the 13710 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 13711 */ 13712 public static Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 13713 @Override 13714 public void setValue(View object, float value) { 13715 object.setTranslationX(value); 13716 } 13717 13718 @Override 13719 public Float get(View object) { 13720 return object.getTranslationX(); 13721 } 13722 }; 13723 13724 /** 13725 * A Property wrapper around the <code>translationY</code> functionality handled by the 13726 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 13727 */ 13728 public static Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 13729 @Override 13730 public void setValue(View object, float value) { 13731 object.setTranslationY(value); 13732 } 13733 13734 @Override 13735 public Float get(View object) { 13736 return object.getTranslationY(); 13737 } 13738 }; 13739 13740 /** 13741 * A Property wrapper around the <code>x</code> functionality handled by the 13742 * {@link View#setX(float)} and {@link View#getX()} methods. 13743 */ 13744 public static Property<View, Float> X = new FloatProperty<View>("x") { 13745 @Override 13746 public void setValue(View object, float value) { 13747 object.setX(value); 13748 } 13749 13750 @Override 13751 public Float get(View object) { 13752 return object.getX(); 13753 } 13754 }; 13755 13756 /** 13757 * A Property wrapper around the <code>y</code> functionality handled by the 13758 * {@link View#setY(float)} and {@link View#getY()} methods. 13759 */ 13760 public static Property<View, Float> Y = new FloatProperty<View>("y") { 13761 @Override 13762 public void setValue(View object, float value) { 13763 object.setY(value); 13764 } 13765 13766 @Override 13767 public Float get(View object) { 13768 return object.getY(); 13769 } 13770 }; 13771 13772 /** 13773 * A Property wrapper around the <code>rotation</code> functionality handled by the 13774 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 13775 */ 13776 public static Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 13777 @Override 13778 public void setValue(View object, float value) { 13779 object.setRotation(value); 13780 } 13781 13782 @Override 13783 public Float get(View object) { 13784 return object.getRotation(); 13785 } 13786 }; 13787 13788 /** 13789 * A Property wrapper around the <code>rotationX</code> functionality handled by the 13790 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 13791 */ 13792 public static Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 13793 @Override 13794 public void setValue(View object, float value) { 13795 object.setRotationX(value); 13796 } 13797 13798 @Override 13799 public Float get(View object) { 13800 return object.getRotationX(); 13801 } 13802 }; 13803 13804 /** 13805 * A Property wrapper around the <code>rotationY</code> functionality handled by the 13806 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 13807 */ 13808 public static Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 13809 @Override 13810 public void setValue(View object, float value) { 13811 object.setRotationY(value); 13812 } 13813 13814 @Override 13815 public Float get(View object) { 13816 return object.getRotationY(); 13817 } 13818 }; 13819 13820 /** 13821 * A Property wrapper around the <code>scaleX</code> functionality handled by the 13822 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 13823 */ 13824 public static Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 13825 @Override 13826 public void setValue(View object, float value) { 13827 object.setScaleX(value); 13828 } 13829 13830 @Override 13831 public Float get(View object) { 13832 return object.getScaleX(); 13833 } 13834 }; 13835 13836 /** 13837 * A Property wrapper around the <code>scaleY</code> functionality handled by the 13838 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 13839 */ 13840 public static Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 13841 @Override 13842 public void setValue(View object, float value) { 13843 object.setScaleY(value); 13844 } 13845 13846 @Override 13847 public Float get(View object) { 13848 return object.getScaleY(); 13849 } 13850 }; 13851 13852 /** 13853 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 13854 * Each MeasureSpec represents a requirement for either the width or the height. 13855 * A MeasureSpec is comprised of a size and a mode. There are three possible 13856 * modes: 13857 * <dl> 13858 * <dt>UNSPECIFIED</dt> 13859 * <dd> 13860 * The parent has not imposed any constraint on the child. It can be whatever size 13861 * it wants. 13862 * </dd> 13863 * 13864 * <dt>EXACTLY</dt> 13865 * <dd> 13866 * The parent has determined an exact size for the child. The child is going to be 13867 * given those bounds regardless of how big it wants to be. 13868 * </dd> 13869 * 13870 * <dt>AT_MOST</dt> 13871 * <dd> 13872 * The child can be as large as it wants up to the specified size. 13873 * </dd> 13874 * </dl> 13875 * 13876 * MeasureSpecs are implemented as ints to reduce object allocation. This class 13877 * is provided to pack and unpack the <size, mode> tuple into the int. 13878 */ 13879 public static class MeasureSpec { 13880 private static final int MODE_SHIFT = 30; 13881 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 13882 13883 /** 13884 * Measure specification mode: The parent has not imposed any constraint 13885 * on the child. It can be whatever size it wants. 13886 */ 13887 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 13888 13889 /** 13890 * Measure specification mode: The parent has determined an exact size 13891 * for the child. The child is going to be given those bounds regardless 13892 * of how big it wants to be. 13893 */ 13894 public static final int EXACTLY = 1 << MODE_SHIFT; 13895 13896 /** 13897 * Measure specification mode: The child can be as large as it wants up 13898 * to the specified size. 13899 */ 13900 public static final int AT_MOST = 2 << MODE_SHIFT; 13901 13902 /** 13903 * Creates a measure specification based on the supplied size and mode. 13904 * 13905 * The mode must always be one of the following: 13906 * <ul> 13907 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 13908 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 13909 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 13910 * </ul> 13911 * 13912 * @param size the size of the measure specification 13913 * @param mode the mode of the measure specification 13914 * @return the measure specification based on size and mode 13915 */ 13916 public static int makeMeasureSpec(int size, int mode) { 13917 return size + mode; 13918 } 13919 13920 /** 13921 * Extracts the mode from the supplied measure specification. 13922 * 13923 * @param measureSpec the measure specification to extract the mode from 13924 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 13925 * {@link android.view.View.MeasureSpec#AT_MOST} or 13926 * {@link android.view.View.MeasureSpec#EXACTLY} 13927 */ 13928 public static int getMode(int measureSpec) { 13929 return (measureSpec & MODE_MASK); 13930 } 13931 13932 /** 13933 * Extracts the size from the supplied measure specification. 13934 * 13935 * @param measureSpec the measure specification to extract the size from 13936 * @return the size in pixels defined in the supplied measure specification 13937 */ 13938 public static int getSize(int measureSpec) { 13939 return (measureSpec & ~MODE_MASK); 13940 } 13941 13942 /** 13943 * Returns a String representation of the specified measure 13944 * specification. 13945 * 13946 * @param measureSpec the measure specification to convert to a String 13947 * @return a String with the following format: "MeasureSpec: MODE SIZE" 13948 */ 13949 public static String toString(int measureSpec) { 13950 int mode = getMode(measureSpec); 13951 int size = getSize(measureSpec); 13952 13953 StringBuilder sb = new StringBuilder("MeasureSpec: "); 13954 13955 if (mode == UNSPECIFIED) 13956 sb.append("UNSPECIFIED "); 13957 else if (mode == EXACTLY) 13958 sb.append("EXACTLY "); 13959 else if (mode == AT_MOST) 13960 sb.append("AT_MOST "); 13961 else 13962 sb.append(mode).append(" "); 13963 13964 sb.append(size); 13965 return sb.toString(); 13966 } 13967 } 13968 13969 class CheckForLongPress implements Runnable { 13970 13971 private int mOriginalWindowAttachCount; 13972 13973 public void run() { 13974 if (isPressed() && (mParent != null) 13975 && mOriginalWindowAttachCount == mWindowAttachCount) { 13976 if (performLongClick()) { 13977 mHasPerformedLongPress = true; 13978 } 13979 } 13980 } 13981 13982 public void rememberWindowAttachCount() { 13983 mOriginalWindowAttachCount = mWindowAttachCount; 13984 } 13985 } 13986 13987 private final class CheckForTap implements Runnable { 13988 public void run() { 13989 mPrivateFlags &= ~PREPRESSED; 13990 mPrivateFlags |= PRESSED; 13991 refreshDrawableState(); 13992 checkForLongClick(ViewConfiguration.getTapTimeout()); 13993 } 13994 } 13995 13996 private final class PerformClick implements Runnable { 13997 public void run() { 13998 performClick(); 13999 } 14000 } 14001 14002 /** @hide */ 14003 public void hackTurnOffWindowResizeAnim(boolean off) { 14004 mAttachInfo.mTurnOffWindowResizeAnim = off; 14005 } 14006 14007 /** 14008 * This method returns a ViewPropertyAnimator object, which can be used to animate 14009 * specific properties on this View. 14010 * 14011 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 14012 */ 14013 public ViewPropertyAnimator animate() { 14014 if (mAnimator == null) { 14015 mAnimator = new ViewPropertyAnimator(this); 14016 } 14017 return mAnimator; 14018 } 14019 14020 /** 14021 * Interface definition for a callback to be invoked when a key event is 14022 * dispatched to this view. The callback will be invoked before the key 14023 * event is given to the view. 14024 */ 14025 public interface OnKeyListener { 14026 /** 14027 * Called when a key is dispatched to a view. This allows listeners to 14028 * get a chance to respond before the target view. 14029 * 14030 * @param v The view the key has been dispatched to. 14031 * @param keyCode The code for the physical key that was pressed 14032 * @param event The KeyEvent object containing full information about 14033 * the event. 14034 * @return True if the listener has consumed the event, false otherwise. 14035 */ 14036 boolean onKey(View v, int keyCode, KeyEvent event); 14037 } 14038 14039 /** 14040 * Interface definition for a callback to be invoked when a touch event is 14041 * dispatched to this view. The callback will be invoked before the touch 14042 * event is given to the view. 14043 */ 14044 public interface OnTouchListener { 14045 /** 14046 * Called when a touch event is dispatched to a view. This allows listeners to 14047 * get a chance to respond before the target view. 14048 * 14049 * @param v The view the touch event has been dispatched to. 14050 * @param event The MotionEvent object containing full information about 14051 * the event. 14052 * @return True if the listener has consumed the event, false otherwise. 14053 */ 14054 boolean onTouch(View v, MotionEvent event); 14055 } 14056 14057 /** 14058 * Interface definition for a callback to be invoked when a hover event is 14059 * dispatched to this view. The callback will be invoked before the hover 14060 * event is given to the view. 14061 */ 14062 public interface OnHoverListener { 14063 /** 14064 * Called when a hover event is dispatched to a view. This allows listeners to 14065 * get a chance to respond before the target view. 14066 * 14067 * @param v The view the hover event has been dispatched to. 14068 * @param event The MotionEvent object containing full information about 14069 * the event. 14070 * @return True if the listener has consumed the event, false otherwise. 14071 */ 14072 boolean onHover(View v, MotionEvent event); 14073 } 14074 14075 /** 14076 * Interface definition for a callback to be invoked when a generic motion event is 14077 * dispatched to this view. The callback will be invoked before the generic motion 14078 * event is given to the view. 14079 */ 14080 public interface OnGenericMotionListener { 14081 /** 14082 * Called when a generic motion event is dispatched to a view. This allows listeners to 14083 * get a chance to respond before the target view. 14084 * 14085 * @param v The view the generic motion event has been dispatched to. 14086 * @param event The MotionEvent object containing full information about 14087 * the event. 14088 * @return True if the listener has consumed the event, false otherwise. 14089 */ 14090 boolean onGenericMotion(View v, MotionEvent event); 14091 } 14092 14093 /** 14094 * Interface definition for a callback to be invoked when a view has been clicked and held. 14095 */ 14096 public interface OnLongClickListener { 14097 /** 14098 * Called when a view has been clicked and held. 14099 * 14100 * @param v The view that was clicked and held. 14101 * 14102 * @return true if the callback consumed the long click, false otherwise. 14103 */ 14104 boolean onLongClick(View v); 14105 } 14106 14107 /** 14108 * Interface definition for a callback to be invoked when a drag is being dispatched 14109 * to this view. The callback will be invoked before the hosting view's own 14110 * onDrag(event) method. If the listener wants to fall back to the hosting view's 14111 * onDrag(event) behavior, it should return 'false' from this callback. 14112 * 14113 * <div class="special reference"> 14114 * <h3>Developer Guides</h3> 14115 * <p>For a guide to implementing drag and drop features, read the 14116 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 14117 * </div> 14118 */ 14119 public interface OnDragListener { 14120 /** 14121 * Called when a drag event is dispatched to a view. This allows listeners 14122 * to get a chance to override base View behavior. 14123 * 14124 * @param v The View that received the drag event. 14125 * @param event The {@link android.view.DragEvent} object for the drag event. 14126 * @return {@code true} if the drag event was handled successfully, or {@code false} 14127 * if the drag event was not handled. Note that {@code false} will trigger the View 14128 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 14129 */ 14130 boolean onDrag(View v, DragEvent event); 14131 } 14132 14133 /** 14134 * Interface definition for a callback to be invoked when the focus state of 14135 * a view changed. 14136 */ 14137 public interface OnFocusChangeListener { 14138 /** 14139 * Called when the focus state of a view has changed. 14140 * 14141 * @param v The view whose state has changed. 14142 * @param hasFocus The new focus state of v. 14143 */ 14144 void onFocusChange(View v, boolean hasFocus); 14145 } 14146 14147 /** 14148 * Interface definition for a callback to be invoked when a view is clicked. 14149 */ 14150 public interface OnClickListener { 14151 /** 14152 * Called when a view has been clicked. 14153 * 14154 * @param v The view that was clicked. 14155 */ 14156 void onClick(View v); 14157 } 14158 14159 /** 14160 * Interface definition for a callback to be invoked when the context menu 14161 * for this view is being built. 14162 */ 14163 public interface OnCreateContextMenuListener { 14164 /** 14165 * Called when the context menu for this view is being built. It is not 14166 * safe to hold onto the menu after this method returns. 14167 * 14168 * @param menu The context menu that is being built 14169 * @param v The view for which the context menu is being built 14170 * @param menuInfo Extra information about the item for which the 14171 * context menu should be shown. This information will vary 14172 * depending on the class of v. 14173 */ 14174 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 14175 } 14176 14177 /** 14178 * Interface definition for a callback to be invoked when the status bar changes 14179 * visibility. This reports <strong>global</strong> changes to the system UI 14180 * state, not just what the application is requesting. 14181 * 14182 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 14183 */ 14184 public interface OnSystemUiVisibilityChangeListener { 14185 /** 14186 * Called when the status bar changes visibility because of a call to 14187 * {@link View#setSystemUiVisibility(int)}. 14188 * 14189 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 14190 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. This tells you the 14191 * <strong>global</strong> state of the UI visibility flags, not what your 14192 * app is currently applying. 14193 */ 14194 public void onSystemUiVisibilityChange(int visibility); 14195 } 14196 14197 /** 14198 * Interface definition for a callback to be invoked when this view is attached 14199 * or detached from its window. 14200 */ 14201 public interface OnAttachStateChangeListener { 14202 /** 14203 * Called when the view is attached to a window. 14204 * @param v The view that was attached 14205 */ 14206 public void onViewAttachedToWindow(View v); 14207 /** 14208 * Called when the view is detached from a window. 14209 * @param v The view that was detached 14210 */ 14211 public void onViewDetachedFromWindow(View v); 14212 } 14213 14214 private final class UnsetPressedState implements Runnable { 14215 public void run() { 14216 setPressed(false); 14217 } 14218 } 14219 14220 /** 14221 * Base class for derived classes that want to save and restore their own 14222 * state in {@link android.view.View#onSaveInstanceState()}. 14223 */ 14224 public static class BaseSavedState extends AbsSavedState { 14225 /** 14226 * Constructor used when reading from a parcel. Reads the state of the superclass. 14227 * 14228 * @param source 14229 */ 14230 public BaseSavedState(Parcel source) { 14231 super(source); 14232 } 14233 14234 /** 14235 * Constructor called by derived classes when creating their SavedState objects 14236 * 14237 * @param superState The state of the superclass of this view 14238 */ 14239 public BaseSavedState(Parcelable superState) { 14240 super(superState); 14241 } 14242 14243 public static final Parcelable.Creator<BaseSavedState> CREATOR = 14244 new Parcelable.Creator<BaseSavedState>() { 14245 public BaseSavedState createFromParcel(Parcel in) { 14246 return new BaseSavedState(in); 14247 } 14248 14249 public BaseSavedState[] newArray(int size) { 14250 return new BaseSavedState[size]; 14251 } 14252 }; 14253 } 14254 14255 /** 14256 * A set of information given to a view when it is attached to its parent 14257 * window. 14258 */ 14259 static class AttachInfo { 14260 interface Callbacks { 14261 void playSoundEffect(int effectId); 14262 boolean performHapticFeedback(int effectId, boolean always); 14263 } 14264 14265 /** 14266 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 14267 * to a Handler. This class contains the target (View) to invalidate and 14268 * the coordinates of the dirty rectangle. 14269 * 14270 * For performance purposes, this class also implements a pool of up to 14271 * POOL_LIMIT objects that get reused. This reduces memory allocations 14272 * whenever possible. 14273 */ 14274 static class InvalidateInfo implements Poolable<InvalidateInfo> { 14275 private static final int POOL_LIMIT = 10; 14276 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 14277 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 14278 public InvalidateInfo newInstance() { 14279 return new InvalidateInfo(); 14280 } 14281 14282 public void onAcquired(InvalidateInfo element) { 14283 } 14284 14285 public void onReleased(InvalidateInfo element) { 14286 element.target = null; 14287 } 14288 }, POOL_LIMIT) 14289 ); 14290 14291 private InvalidateInfo mNext; 14292 private boolean mIsPooled; 14293 14294 View target; 14295 14296 int left; 14297 int top; 14298 int right; 14299 int bottom; 14300 14301 public void setNextPoolable(InvalidateInfo element) { 14302 mNext = element; 14303 } 14304 14305 public InvalidateInfo getNextPoolable() { 14306 return mNext; 14307 } 14308 14309 static InvalidateInfo acquire() { 14310 return sPool.acquire(); 14311 } 14312 14313 void release() { 14314 sPool.release(this); 14315 } 14316 14317 public boolean isPooled() { 14318 return mIsPooled; 14319 } 14320 14321 public void setPooled(boolean isPooled) { 14322 mIsPooled = isPooled; 14323 } 14324 } 14325 14326 final IWindowSession mSession; 14327 14328 final IWindow mWindow; 14329 14330 final IBinder mWindowToken; 14331 14332 final Callbacks mRootCallbacks; 14333 14334 HardwareCanvas mHardwareCanvas; 14335 14336 /** 14337 * The top view of the hierarchy. 14338 */ 14339 View mRootView; 14340 14341 IBinder mPanelParentWindowToken; 14342 Surface mSurface; 14343 14344 boolean mHardwareAccelerated; 14345 boolean mHardwareAccelerationRequested; 14346 HardwareRenderer mHardwareRenderer; 14347 14348 /** 14349 * Scale factor used by the compatibility mode 14350 */ 14351 float mApplicationScale; 14352 14353 /** 14354 * Indicates whether the application is in compatibility mode 14355 */ 14356 boolean mScalingRequired; 14357 14358 /** 14359 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 14360 */ 14361 boolean mTurnOffWindowResizeAnim; 14362 14363 /** 14364 * Left position of this view's window 14365 */ 14366 int mWindowLeft; 14367 14368 /** 14369 * Top position of this view's window 14370 */ 14371 int mWindowTop; 14372 14373 /** 14374 * Indicates whether views need to use 32-bit drawing caches 14375 */ 14376 boolean mUse32BitDrawingCache; 14377 14378 /** 14379 * For windows that are full-screen but using insets to layout inside 14380 * of the screen decorations, these are the current insets for the 14381 * content of the window. 14382 */ 14383 final Rect mContentInsets = new Rect(); 14384 14385 /** 14386 * For windows that are full-screen but using insets to layout inside 14387 * of the screen decorations, these are the current insets for the 14388 * actual visible parts of the window. 14389 */ 14390 final Rect mVisibleInsets = new Rect(); 14391 14392 /** 14393 * The internal insets given by this window. This value is 14394 * supplied by the client (through 14395 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 14396 * be given to the window manager when changed to be used in laying 14397 * out windows behind it. 14398 */ 14399 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 14400 = new ViewTreeObserver.InternalInsetsInfo(); 14401 14402 /** 14403 * All views in the window's hierarchy that serve as scroll containers, 14404 * used to determine if the window can be resized or must be panned 14405 * to adjust for a soft input area. 14406 */ 14407 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 14408 14409 final KeyEvent.DispatcherState mKeyDispatchState 14410 = new KeyEvent.DispatcherState(); 14411 14412 /** 14413 * Indicates whether the view's window currently has the focus. 14414 */ 14415 boolean mHasWindowFocus; 14416 14417 /** 14418 * The current visibility of the window. 14419 */ 14420 int mWindowVisibility; 14421 14422 /** 14423 * Indicates the time at which drawing started to occur. 14424 */ 14425 long mDrawingTime; 14426 14427 /** 14428 * Indicates whether or not ignoring the DIRTY_MASK flags. 14429 */ 14430 boolean mIgnoreDirtyState; 14431 14432 /** 14433 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 14434 * to avoid clearing that flag prematurely. 14435 */ 14436 boolean mSetIgnoreDirtyState = false; 14437 14438 /** 14439 * Indicates whether the view's window is currently in touch mode. 14440 */ 14441 boolean mInTouchMode; 14442 14443 /** 14444 * Indicates that ViewAncestor should trigger a global layout change 14445 * the next time it performs a traversal 14446 */ 14447 boolean mRecomputeGlobalAttributes; 14448 14449 /** 14450 * Always report new attributes at next traversal. 14451 */ 14452 boolean mForceReportNewAttributes; 14453 14454 /** 14455 * Set during a traveral if any views want to keep the screen on. 14456 */ 14457 boolean mKeepScreenOn; 14458 14459 /** 14460 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 14461 */ 14462 int mSystemUiVisibility; 14463 14464 /** 14465 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 14466 * attached. 14467 */ 14468 boolean mHasSystemUiListeners; 14469 14470 /** 14471 * Set if the visibility of any views has changed. 14472 */ 14473 boolean mViewVisibilityChanged; 14474 14475 /** 14476 * Set to true if a view has been scrolled. 14477 */ 14478 boolean mViewScrollChanged; 14479 14480 /** 14481 * Global to the view hierarchy used as a temporary for dealing with 14482 * x/y points in the transparent region computations. 14483 */ 14484 final int[] mTransparentLocation = new int[2]; 14485 14486 /** 14487 * Global to the view hierarchy used as a temporary for dealing with 14488 * x/y points in the ViewGroup.invalidateChild implementation. 14489 */ 14490 final int[] mInvalidateChildLocation = new int[2]; 14491 14492 14493 /** 14494 * Global to the view hierarchy used as a temporary for dealing with 14495 * x/y location when view is transformed. 14496 */ 14497 final float[] mTmpTransformLocation = new float[2]; 14498 14499 /** 14500 * The view tree observer used to dispatch global events like 14501 * layout, pre-draw, touch mode change, etc. 14502 */ 14503 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 14504 14505 /** 14506 * A Canvas used by the view hierarchy to perform bitmap caching. 14507 */ 14508 Canvas mCanvas; 14509 14510 /** 14511 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 14512 * handler can be used to pump events in the UI events queue. 14513 */ 14514 final Handler mHandler; 14515 14516 /** 14517 * Identifier for messages requesting the view to be invalidated. 14518 * Such messages should be sent to {@link #mHandler}. 14519 */ 14520 static final int INVALIDATE_MSG = 0x1; 14521 14522 /** 14523 * Identifier for messages requesting the view to invalidate a region. 14524 * Such messages should be sent to {@link #mHandler}. 14525 */ 14526 static final int INVALIDATE_RECT_MSG = 0x2; 14527 14528 /** 14529 * Temporary for use in computing invalidate rectangles while 14530 * calling up the hierarchy. 14531 */ 14532 final Rect mTmpInvalRect = new Rect(); 14533 14534 /** 14535 * Temporary for use in computing hit areas with transformed views 14536 */ 14537 final RectF mTmpTransformRect = new RectF(); 14538 14539 /** 14540 * Temporary list for use in collecting focusable descendents of a view. 14541 */ 14542 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 14543 14544 /** 14545 * The id of the window for accessibility purposes. 14546 */ 14547 int mAccessibilityWindowId = View.NO_ID; 14548 14549 /** 14550 * Creates a new set of attachment information with the specified 14551 * events handler and thread. 14552 * 14553 * @param handler the events handler the view must use 14554 */ 14555 AttachInfo(IWindowSession session, IWindow window, 14556 Handler handler, Callbacks effectPlayer) { 14557 mSession = session; 14558 mWindow = window; 14559 mWindowToken = window.asBinder(); 14560 mHandler = handler; 14561 mRootCallbacks = effectPlayer; 14562 } 14563 } 14564 14565 /** 14566 * <p>ScrollabilityCache holds various fields used by a View when scrolling 14567 * is supported. This avoids keeping too many unused fields in most 14568 * instances of View.</p> 14569 */ 14570 private static class ScrollabilityCache implements Runnable { 14571 14572 /** 14573 * Scrollbars are not visible 14574 */ 14575 public static final int OFF = 0; 14576 14577 /** 14578 * Scrollbars are visible 14579 */ 14580 public static final int ON = 1; 14581 14582 /** 14583 * Scrollbars are fading away 14584 */ 14585 public static final int FADING = 2; 14586 14587 public boolean fadeScrollBars; 14588 14589 public int fadingEdgeLength; 14590 public int scrollBarDefaultDelayBeforeFade; 14591 public int scrollBarFadeDuration; 14592 14593 public int scrollBarSize; 14594 public ScrollBarDrawable scrollBar; 14595 public float[] interpolatorValues; 14596 public View host; 14597 14598 public final Paint paint; 14599 public final Matrix matrix; 14600 public Shader shader; 14601 14602 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 14603 14604 private static final float[] OPAQUE = { 255 }; 14605 private static final float[] TRANSPARENT = { 0.0f }; 14606 14607 /** 14608 * When fading should start. This time moves into the future every time 14609 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 14610 */ 14611 public long fadeStartTime; 14612 14613 14614 /** 14615 * The current state of the scrollbars: ON, OFF, or FADING 14616 */ 14617 public int state = OFF; 14618 14619 private int mLastColor; 14620 14621 public ScrollabilityCache(ViewConfiguration configuration, View host) { 14622 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 14623 scrollBarSize = configuration.getScaledScrollBarSize(); 14624 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 14625 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 14626 14627 paint = new Paint(); 14628 matrix = new Matrix(); 14629 // use use a height of 1, and then wack the matrix each time we 14630 // actually use it. 14631 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 14632 14633 paint.setShader(shader); 14634 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 14635 this.host = host; 14636 } 14637 14638 public void setFadeColor(int color) { 14639 if (color != 0 && color != mLastColor) { 14640 mLastColor = color; 14641 color |= 0xFF000000; 14642 14643 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 14644 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 14645 14646 paint.setShader(shader); 14647 // Restore the default transfer mode (src_over) 14648 paint.setXfermode(null); 14649 } 14650 } 14651 14652 public void run() { 14653 long now = AnimationUtils.currentAnimationTimeMillis(); 14654 if (now >= fadeStartTime) { 14655 14656 // the animation fades the scrollbars out by changing 14657 // the opacity (alpha) from fully opaque to fully 14658 // transparent 14659 int nextFrame = (int) now; 14660 int framesCount = 0; 14661 14662 Interpolator interpolator = scrollBarInterpolator; 14663 14664 // Start opaque 14665 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 14666 14667 // End transparent 14668 nextFrame += scrollBarFadeDuration; 14669 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 14670 14671 state = FADING; 14672 14673 // Kick off the fade animation 14674 host.invalidate(true); 14675 } 14676 } 14677 } 14678 14679 /** 14680 * Resuable callback for sending 14681 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 14682 */ 14683 private class SendViewScrolledAccessibilityEvent implements Runnable { 14684 public volatile boolean mIsPending; 14685 14686 public void run() { 14687 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 14688 mIsPending = false; 14689 } 14690 } 14691 14692 /** 14693 * <p> 14694 * This class represents a delegate that can be registered in a {@link View} 14695 * to enhance accessibility support via composition rather via inheritance. 14696 * It is specifically targeted to widget developers that extend basic View 14697 * classes i.e. classes in package android.view, that would like their 14698 * applications to be backwards compatible. 14699 * </p> 14700 * <p> 14701 * A scenario in which a developer would like to use an accessibility delegate 14702 * is overriding a method introduced in a later API version then the minimal API 14703 * version supported by the application. For example, the method 14704 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 14705 * in API version 4 when the accessibility APIs were first introduced. If a 14706 * developer would like his application to run on API version 4 devices (assuming 14707 * all other APIs used by the application are version 4 or lower) and take advantage 14708 * of this method, instead of overriding the method which would break the application's 14709 * backwards compatibility, he can override the corresponding method in this 14710 * delegate and register the delegate in the target View if the API version of 14711 * the system is high enough i.e. the API version is same or higher to the API 14712 * version that introduced 14713 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 14714 * </p> 14715 * <p> 14716 * Here is an example implementation: 14717 * </p> 14718 * <code><pre><p> 14719 * if (Build.VERSION.SDK_INT >= 14) { 14720 * // If the API version is equal of higher than the version in 14721 * // which onInitializeAccessibilityNodeInfo was introduced we 14722 * // register a delegate with a customized implementation. 14723 * View view = findViewById(R.id.view_id); 14724 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 14725 * public void onInitializeAccessibilityNodeInfo(View host, 14726 * AccessibilityNodeInfo info) { 14727 * // Let the default implementation populate the info. 14728 * super.onInitializeAccessibilityNodeInfo(host, info); 14729 * // Set some other information. 14730 * info.setEnabled(host.isEnabled()); 14731 * } 14732 * }); 14733 * } 14734 * </code></pre></p> 14735 * <p> 14736 * This delegate contains methods that correspond to the accessibility methods 14737 * in View. If a delegate has been specified the implementation in View hands 14738 * off handling to the corresponding method in this delegate. The default 14739 * implementation the delegate methods behaves exactly as the corresponding 14740 * method in View for the case of no accessibility delegate been set. Hence, 14741 * to customize the behavior of a View method, clients can override only the 14742 * corresponding delegate method without altering the behavior of the rest 14743 * accessibility related methods of the host view. 14744 * </p> 14745 */ 14746 public static class AccessibilityDelegate { 14747 14748 /** 14749 * Sends an accessibility event of the given type. If accessibility is not 14750 * enabled this method has no effect. 14751 * <p> 14752 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 14753 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 14754 * been set. 14755 * </p> 14756 * 14757 * @param host The View hosting the delegate. 14758 * @param eventType The type of the event to send. 14759 * 14760 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 14761 */ 14762 public void sendAccessibilityEvent(View host, int eventType) { 14763 host.sendAccessibilityEventInternal(eventType); 14764 } 14765 14766 /** 14767 * Sends an accessibility event. This method behaves exactly as 14768 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 14769 * empty {@link AccessibilityEvent} and does not perform a check whether 14770 * accessibility is enabled. 14771 * <p> 14772 * The default implementation behaves as 14773 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 14774 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 14775 * the case of no accessibility delegate been set. 14776 * </p> 14777 * 14778 * @param host The View hosting the delegate. 14779 * @param event The event to send. 14780 * 14781 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 14782 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 14783 */ 14784 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 14785 host.sendAccessibilityEventUncheckedInternal(event); 14786 } 14787 14788 /** 14789 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 14790 * to its children for adding their text content to the event. 14791 * <p> 14792 * The default implementation behaves as 14793 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 14794 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 14795 * the case of no accessibility delegate been set. 14796 * </p> 14797 * 14798 * @param host The View hosting the delegate. 14799 * @param event The event. 14800 * @return True if the event population was completed. 14801 * 14802 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 14803 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 14804 */ 14805 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 14806 return host.dispatchPopulateAccessibilityEventInternal(event); 14807 } 14808 14809 /** 14810 * Gives a chance to the host View to populate the accessibility event with its 14811 * text content. 14812 * <p> 14813 * The default implementation behaves as 14814 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 14815 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 14816 * the case of no accessibility delegate been set. 14817 * </p> 14818 * 14819 * @param host The View hosting the delegate. 14820 * @param event The accessibility event which to populate. 14821 * 14822 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 14823 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 14824 */ 14825 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 14826 host.onPopulateAccessibilityEventInternal(event); 14827 } 14828 14829 /** 14830 * Initializes an {@link AccessibilityEvent} with information about the 14831 * the host View which is the event source. 14832 * <p> 14833 * The default implementation behaves as 14834 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 14835 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 14836 * the case of no accessibility delegate been set. 14837 * </p> 14838 * 14839 * @param host The View hosting the delegate. 14840 * @param event The event to initialize. 14841 * 14842 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 14843 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 14844 */ 14845 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 14846 host.onInitializeAccessibilityEventInternal(event); 14847 } 14848 14849 /** 14850 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 14851 * <p> 14852 * The default implementation behaves as 14853 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 14854 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 14855 * the case of no accessibility delegate been set. 14856 * </p> 14857 * 14858 * @param host The View hosting the delegate. 14859 * @param info The instance to initialize. 14860 * 14861 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 14862 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 14863 */ 14864 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 14865 host.onInitializeAccessibilityNodeInfoInternal(info); 14866 } 14867 14868 /** 14869 * Called when a child of the host View has requested sending an 14870 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 14871 * to augment the event. 14872 * <p> 14873 * The default implementation behaves as 14874 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 14875 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 14876 * the case of no accessibility delegate been set. 14877 * </p> 14878 * 14879 * @param host The View hosting the delegate. 14880 * @param child The child which requests sending the event. 14881 * @param event The event to be sent. 14882 * @return True if the event should be sent 14883 * 14884 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 14885 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 14886 */ 14887 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 14888 AccessibilityEvent event) { 14889 return host.onRequestSendAccessibilityEventInternal(child, event); 14890 } 14891 } 14892} 14893