View.java revision e261e283eaedd38235fc93b2a5c35758c613b10c
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 ViewParent parent = getParent(); 4126 if (parent instanceof View) { 4127 View parentView = (View) parent; 4128 info.setParent(parentView); 4129 } 4130 4131 info.setPackageName(mContext.getPackageName()); 4132 info.setClassName(getClass().getName()); 4133 info.setContentDescription(getContentDescription()); 4134 4135 info.setEnabled(isEnabled()); 4136 info.setClickable(isClickable()); 4137 info.setFocusable(isFocusable()); 4138 info.setFocused(isFocused()); 4139 info.setSelected(isSelected()); 4140 info.setLongClickable(isLongClickable()); 4141 4142 // TODO: These make sense only if we are in an AdapterView but all 4143 // views can be selected. Maybe from accessiiblity perspective 4144 // we should report as selectable view in an AdapterView. 4145 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 4146 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 4147 4148 if (isFocusable()) { 4149 if (isFocused()) { 4150 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 4151 } else { 4152 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 4153 } 4154 } 4155 } 4156 4157 /** 4158 * Sets a delegate for implementing accessibility support via compositon as 4159 * opposed to inheritance. The delegate's primary use is for implementing 4160 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 4161 * 4162 * @param delegate The delegate instance. 4163 * 4164 * @see AccessibilityDelegate 4165 */ 4166 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 4167 mAccessibilityDelegate = delegate; 4168 } 4169 4170 /** 4171 * Gets the unique identifier of this view on the screen for accessibility purposes. 4172 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 4173 * 4174 * @return The view accessibility id. 4175 * 4176 * @hide 4177 */ 4178 public int getAccessibilityViewId() { 4179 if (mAccessibilityViewId == NO_ID) { 4180 mAccessibilityViewId = sNextAccessibilityViewId++; 4181 } 4182 return mAccessibilityViewId; 4183 } 4184 4185 /** 4186 * Gets the unique identifier of the window in which this View reseides. 4187 * 4188 * @return The window accessibility id. 4189 * 4190 * @hide 4191 */ 4192 public int getAccessibilityWindowId() { 4193 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 4194 } 4195 4196 /** 4197 * Gets the {@link View} description. It briefly describes the view and is 4198 * primarily used for accessibility support. Set this property to enable 4199 * better accessibility support for your application. This is especially 4200 * true for views that do not have textual representation (For example, 4201 * ImageButton). 4202 * 4203 * @return The content descriptiopn. 4204 * 4205 * @attr ref android.R.styleable#View_contentDescription 4206 */ 4207 public CharSequence getContentDescription() { 4208 return mContentDescription; 4209 } 4210 4211 /** 4212 * Sets the {@link View} description. It briefly describes the view and is 4213 * primarily used for accessibility support. Set this property to enable 4214 * better accessibility support for your application. This is especially 4215 * true for views that do not have textual representation (For example, 4216 * ImageButton). 4217 * 4218 * @param contentDescription The content description. 4219 * 4220 * @attr ref android.R.styleable#View_contentDescription 4221 */ 4222 @RemotableViewMethod 4223 public void setContentDescription(CharSequence contentDescription) { 4224 mContentDescription = contentDescription; 4225 } 4226 4227 /** 4228 * Invoked whenever this view loses focus, either by losing window focus or by losing 4229 * focus within its window. This method can be used to clear any state tied to the 4230 * focus. For instance, if a button is held pressed with the trackball and the window 4231 * loses focus, this method can be used to cancel the press. 4232 * 4233 * Subclasses of View overriding this method should always call super.onFocusLost(). 4234 * 4235 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 4236 * @see #onWindowFocusChanged(boolean) 4237 * 4238 * @hide pending API council approval 4239 */ 4240 protected void onFocusLost() { 4241 resetPressedState(); 4242 } 4243 4244 private void resetPressedState() { 4245 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 4246 return; 4247 } 4248 4249 if (isPressed()) { 4250 setPressed(false); 4251 4252 if (!mHasPerformedLongPress) { 4253 removeLongPressCallback(); 4254 } 4255 } 4256 } 4257 4258 /** 4259 * Returns true if this view has focus 4260 * 4261 * @return True if this view has focus, false otherwise. 4262 */ 4263 @ViewDebug.ExportedProperty(category = "focus") 4264 public boolean isFocused() { 4265 return (mPrivateFlags & FOCUSED) != 0; 4266 } 4267 4268 /** 4269 * Find the view in the hierarchy rooted at this view that currently has 4270 * focus. 4271 * 4272 * @return The view that currently has focus, or null if no focused view can 4273 * be found. 4274 */ 4275 public View findFocus() { 4276 return (mPrivateFlags & FOCUSED) != 0 ? this : null; 4277 } 4278 4279 /** 4280 * Change whether this view is one of the set of scrollable containers in 4281 * its window. This will be used to determine whether the window can 4282 * resize or must pan when a soft input area is open -- scrollable 4283 * containers allow the window to use resize mode since the container 4284 * will appropriately shrink. 4285 */ 4286 public void setScrollContainer(boolean isScrollContainer) { 4287 if (isScrollContainer) { 4288 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) { 4289 mAttachInfo.mScrollContainers.add(this); 4290 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 4291 } 4292 mPrivateFlags |= SCROLL_CONTAINER; 4293 } else { 4294 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 4295 mAttachInfo.mScrollContainers.remove(this); 4296 } 4297 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED); 4298 } 4299 } 4300 4301 /** 4302 * Returns the quality of the drawing cache. 4303 * 4304 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4305 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4306 * 4307 * @see #setDrawingCacheQuality(int) 4308 * @see #setDrawingCacheEnabled(boolean) 4309 * @see #isDrawingCacheEnabled() 4310 * 4311 * @attr ref android.R.styleable#View_drawingCacheQuality 4312 */ 4313 public int getDrawingCacheQuality() { 4314 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 4315 } 4316 4317 /** 4318 * Set the drawing cache quality of this view. This value is used only when the 4319 * drawing cache is enabled 4320 * 4321 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4322 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4323 * 4324 * @see #getDrawingCacheQuality() 4325 * @see #setDrawingCacheEnabled(boolean) 4326 * @see #isDrawingCacheEnabled() 4327 * 4328 * @attr ref android.R.styleable#View_drawingCacheQuality 4329 */ 4330 public void setDrawingCacheQuality(int quality) { 4331 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 4332 } 4333 4334 /** 4335 * Returns whether the screen should remain on, corresponding to the current 4336 * value of {@link #KEEP_SCREEN_ON}. 4337 * 4338 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 4339 * 4340 * @see #setKeepScreenOn(boolean) 4341 * 4342 * @attr ref android.R.styleable#View_keepScreenOn 4343 */ 4344 public boolean getKeepScreenOn() { 4345 return (mViewFlags & KEEP_SCREEN_ON) != 0; 4346 } 4347 4348 /** 4349 * Controls whether the screen should remain on, modifying the 4350 * value of {@link #KEEP_SCREEN_ON}. 4351 * 4352 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 4353 * 4354 * @see #getKeepScreenOn() 4355 * 4356 * @attr ref android.R.styleable#View_keepScreenOn 4357 */ 4358 public void setKeepScreenOn(boolean keepScreenOn) { 4359 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 4360 } 4361 4362 /** 4363 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4364 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4365 * 4366 * @attr ref android.R.styleable#View_nextFocusLeft 4367 */ 4368 public int getNextFocusLeftId() { 4369 return mNextFocusLeftId; 4370 } 4371 4372 /** 4373 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4374 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 4375 * decide automatically. 4376 * 4377 * @attr ref android.R.styleable#View_nextFocusLeft 4378 */ 4379 public void setNextFocusLeftId(int nextFocusLeftId) { 4380 mNextFocusLeftId = nextFocusLeftId; 4381 } 4382 4383 /** 4384 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4385 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4386 * 4387 * @attr ref android.R.styleable#View_nextFocusRight 4388 */ 4389 public int getNextFocusRightId() { 4390 return mNextFocusRightId; 4391 } 4392 4393 /** 4394 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4395 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 4396 * decide automatically. 4397 * 4398 * @attr ref android.R.styleable#View_nextFocusRight 4399 */ 4400 public void setNextFocusRightId(int nextFocusRightId) { 4401 mNextFocusRightId = nextFocusRightId; 4402 } 4403 4404 /** 4405 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4406 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4407 * 4408 * @attr ref android.R.styleable#View_nextFocusUp 4409 */ 4410 public int getNextFocusUpId() { 4411 return mNextFocusUpId; 4412 } 4413 4414 /** 4415 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4416 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 4417 * decide automatically. 4418 * 4419 * @attr ref android.R.styleable#View_nextFocusUp 4420 */ 4421 public void setNextFocusUpId(int nextFocusUpId) { 4422 mNextFocusUpId = nextFocusUpId; 4423 } 4424 4425 /** 4426 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4427 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4428 * 4429 * @attr ref android.R.styleable#View_nextFocusDown 4430 */ 4431 public int getNextFocusDownId() { 4432 return mNextFocusDownId; 4433 } 4434 4435 /** 4436 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4437 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 4438 * decide automatically. 4439 * 4440 * @attr ref android.R.styleable#View_nextFocusDown 4441 */ 4442 public void setNextFocusDownId(int nextFocusDownId) { 4443 mNextFocusDownId = nextFocusDownId; 4444 } 4445 4446 /** 4447 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4448 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4449 * 4450 * @attr ref android.R.styleable#View_nextFocusForward 4451 */ 4452 public int getNextFocusForwardId() { 4453 return mNextFocusForwardId; 4454 } 4455 4456 /** 4457 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4458 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 4459 * decide automatically. 4460 * 4461 * @attr ref android.R.styleable#View_nextFocusForward 4462 */ 4463 public void setNextFocusForwardId(int nextFocusForwardId) { 4464 mNextFocusForwardId = nextFocusForwardId; 4465 } 4466 4467 /** 4468 * Returns the visibility of this view and all of its ancestors 4469 * 4470 * @return True if this view and all of its ancestors are {@link #VISIBLE} 4471 */ 4472 public boolean isShown() { 4473 View current = this; 4474 //noinspection ConstantConditions 4475 do { 4476 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 4477 return false; 4478 } 4479 ViewParent parent = current.mParent; 4480 if (parent == null) { 4481 return false; // We are not attached to the view root 4482 } 4483 if (!(parent instanceof View)) { 4484 return true; 4485 } 4486 current = (View) parent; 4487 } while (current != null); 4488 4489 return false; 4490 } 4491 4492 /** 4493 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag 4494 * is set 4495 * 4496 * @param insets Insets for system windows 4497 * 4498 * @return True if this view applied the insets, false otherwise 4499 */ 4500 protected boolean fitSystemWindows(Rect insets) { 4501 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 4502 mPaddingLeft = insets.left; 4503 mPaddingTop = insets.top; 4504 mPaddingRight = insets.right; 4505 mPaddingBottom = insets.bottom; 4506 requestLayout(); 4507 return true; 4508 } 4509 return false; 4510 } 4511 4512 /** 4513 * Set whether or not this view should account for system screen decorations 4514 * such as the status bar and inset its content. This allows this view to be 4515 * positioned in absolute screen coordinates and remain visible to the user. 4516 * 4517 * <p>This should only be used by top-level window decor views. 4518 * 4519 * @param fitSystemWindows true to inset content for system screen decorations, false for 4520 * default behavior. 4521 * 4522 * @attr ref android.R.styleable#View_fitsSystemWindows 4523 */ 4524 public void setFitsSystemWindows(boolean fitSystemWindows) { 4525 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 4526 } 4527 4528 /** 4529 * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view 4530 * will account for system screen decorations such as the status bar and inset its 4531 * content. This allows the view to be positioned in absolute screen coordinates 4532 * and remain visible to the user. 4533 * 4534 * @return true if this view will adjust its content bounds for system screen decorations. 4535 * 4536 * @attr ref android.R.styleable#View_fitsSystemWindows 4537 */ 4538 public boolean fitsSystemWindows() { 4539 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 4540 } 4541 4542 /** 4543 * Returns the visibility status for this view. 4544 * 4545 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4546 * @attr ref android.R.styleable#View_visibility 4547 */ 4548 @ViewDebug.ExportedProperty(mapping = { 4549 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 4550 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 4551 @ViewDebug.IntToString(from = GONE, to = "GONE") 4552 }) 4553 public int getVisibility() { 4554 return mViewFlags & VISIBILITY_MASK; 4555 } 4556 4557 /** 4558 * Set the enabled state of this view. 4559 * 4560 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4561 * @attr ref android.R.styleable#View_visibility 4562 */ 4563 @RemotableViewMethod 4564 public void setVisibility(int visibility) { 4565 setFlags(visibility, VISIBILITY_MASK); 4566 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); 4567 } 4568 4569 /** 4570 * Returns the enabled status for this view. The interpretation of the 4571 * enabled state varies by subclass. 4572 * 4573 * @return True if this view is enabled, false otherwise. 4574 */ 4575 @ViewDebug.ExportedProperty 4576 public boolean isEnabled() { 4577 return (mViewFlags & ENABLED_MASK) == ENABLED; 4578 } 4579 4580 /** 4581 * Set the enabled state of this view. The interpretation of the enabled 4582 * state varies by subclass. 4583 * 4584 * @param enabled True if this view is enabled, false otherwise. 4585 */ 4586 @RemotableViewMethod 4587 public void setEnabled(boolean enabled) { 4588 if (enabled == isEnabled()) return; 4589 4590 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 4591 4592 /* 4593 * The View most likely has to change its appearance, so refresh 4594 * the drawable state. 4595 */ 4596 refreshDrawableState(); 4597 4598 // Invalidate too, since the default behavior for views is to be 4599 // be drawn at 50% alpha rather than to change the drawable. 4600 invalidate(true); 4601 } 4602 4603 /** 4604 * Set whether this view can receive the focus. 4605 * 4606 * Setting this to false will also ensure that this view is not focusable 4607 * in touch mode. 4608 * 4609 * @param focusable If true, this view can receive the focus. 4610 * 4611 * @see #setFocusableInTouchMode(boolean) 4612 * @attr ref android.R.styleable#View_focusable 4613 */ 4614 public void setFocusable(boolean focusable) { 4615 if (!focusable) { 4616 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 4617 } 4618 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 4619 } 4620 4621 /** 4622 * Set whether this view can receive focus while in touch mode. 4623 * 4624 * Setting this to true will also ensure that this view is focusable. 4625 * 4626 * @param focusableInTouchMode If true, this view can receive the focus while 4627 * in touch mode. 4628 * 4629 * @see #setFocusable(boolean) 4630 * @attr ref android.R.styleable#View_focusableInTouchMode 4631 */ 4632 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 4633 // Focusable in touch mode should always be set before the focusable flag 4634 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 4635 // which, in touch mode, will not successfully request focus on this view 4636 // because the focusable in touch mode flag is not set 4637 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 4638 if (focusableInTouchMode) { 4639 setFlags(FOCUSABLE, FOCUSABLE_MASK); 4640 } 4641 } 4642 4643 /** 4644 * Set whether this view should have sound effects enabled for events such as 4645 * clicking and touching. 4646 * 4647 * <p>You may wish to disable sound effects for a view if you already play sounds, 4648 * for instance, a dial key that plays dtmf tones. 4649 * 4650 * @param soundEffectsEnabled whether sound effects are enabled for this view. 4651 * @see #isSoundEffectsEnabled() 4652 * @see #playSoundEffect(int) 4653 * @attr ref android.R.styleable#View_soundEffectsEnabled 4654 */ 4655 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 4656 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 4657 } 4658 4659 /** 4660 * @return whether this view should have sound effects enabled for events such as 4661 * clicking and touching. 4662 * 4663 * @see #setSoundEffectsEnabled(boolean) 4664 * @see #playSoundEffect(int) 4665 * @attr ref android.R.styleable#View_soundEffectsEnabled 4666 */ 4667 @ViewDebug.ExportedProperty 4668 public boolean isSoundEffectsEnabled() { 4669 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 4670 } 4671 4672 /** 4673 * Set whether this view should have haptic feedback for events such as 4674 * long presses. 4675 * 4676 * <p>You may wish to disable haptic feedback if your view already controls 4677 * its own haptic feedback. 4678 * 4679 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 4680 * @see #isHapticFeedbackEnabled() 4681 * @see #performHapticFeedback(int) 4682 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4683 */ 4684 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 4685 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 4686 } 4687 4688 /** 4689 * @return whether this view should have haptic feedback enabled for events 4690 * long presses. 4691 * 4692 * @see #setHapticFeedbackEnabled(boolean) 4693 * @see #performHapticFeedback(int) 4694 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4695 */ 4696 @ViewDebug.ExportedProperty 4697 public boolean isHapticFeedbackEnabled() { 4698 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 4699 } 4700 4701 /** 4702 * Returns the layout direction for this view. 4703 * 4704 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 4705 * {@link #LAYOUT_DIRECTION_RTL}, 4706 * {@link #LAYOUT_DIRECTION_INHERIT} or 4707 * {@link #LAYOUT_DIRECTION_LOCALE}. 4708 * @attr ref android.R.styleable#View_layoutDirection 4709 * 4710 * @hide 4711 */ 4712 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4713 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 4714 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 4715 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 4716 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 4717 }) 4718 public int getLayoutDirection() { 4719 return mViewFlags & LAYOUT_DIRECTION_MASK; 4720 } 4721 4722 /** 4723 * Set the layout direction for this view. This will propagate a reset of layout direction 4724 * resolution to the view's children and resolve layout direction for this view. 4725 * 4726 * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR}, 4727 * {@link #LAYOUT_DIRECTION_RTL}, 4728 * {@link #LAYOUT_DIRECTION_INHERIT} or 4729 * {@link #LAYOUT_DIRECTION_LOCALE}. 4730 * 4731 * @attr ref android.R.styleable#View_layoutDirection 4732 * 4733 * @hide 4734 */ 4735 @RemotableViewMethod 4736 public void setLayoutDirection(int layoutDirection) { 4737 if (getLayoutDirection() != layoutDirection) { 4738 resetResolvedLayoutDirection(); 4739 // Setting the flag will also request a layout. 4740 setFlags(layoutDirection, LAYOUT_DIRECTION_MASK); 4741 } 4742 } 4743 4744 /** 4745 * Returns the resolved layout direction for this view. 4746 * 4747 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 4748 * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL. 4749 * 4750 * @hide 4751 */ 4752 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4753 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 4754 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 4755 }) 4756 public int getResolvedLayoutDirection() { 4757 resolveLayoutDirectionIfNeeded(); 4758 return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ? 4759 LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 4760 } 4761 4762 /** 4763 * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from 4764 * layout attribute and/or the inherited value from the parent.</p> 4765 * 4766 * @return true if the layout is right-to-left. 4767 * 4768 * @hide 4769 */ 4770 @ViewDebug.ExportedProperty(category = "layout") 4771 public boolean isLayoutRtl() { 4772 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 4773 } 4774 4775 /** 4776 * If this view doesn't do any drawing on its own, set this flag to 4777 * allow further optimizations. By default, this flag is not set on 4778 * View, but could be set on some View subclasses such as ViewGroup. 4779 * 4780 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 4781 * you should clear this flag. 4782 * 4783 * @param willNotDraw whether or not this View draw on its own 4784 */ 4785 public void setWillNotDraw(boolean willNotDraw) { 4786 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 4787 } 4788 4789 /** 4790 * Returns whether or not this View draws on its own. 4791 * 4792 * @return true if this view has nothing to draw, false otherwise 4793 */ 4794 @ViewDebug.ExportedProperty(category = "drawing") 4795 public boolean willNotDraw() { 4796 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 4797 } 4798 4799 /** 4800 * When a View's drawing cache is enabled, drawing is redirected to an 4801 * offscreen bitmap. Some views, like an ImageView, must be able to 4802 * bypass this mechanism if they already draw a single bitmap, to avoid 4803 * unnecessary usage of the memory. 4804 * 4805 * @param willNotCacheDrawing true if this view does not cache its 4806 * drawing, false otherwise 4807 */ 4808 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 4809 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 4810 } 4811 4812 /** 4813 * Returns whether or not this View can cache its drawing or not. 4814 * 4815 * @return true if this view does not cache its drawing, false otherwise 4816 */ 4817 @ViewDebug.ExportedProperty(category = "drawing") 4818 public boolean willNotCacheDrawing() { 4819 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 4820 } 4821 4822 /** 4823 * Indicates whether this view reacts to click events or not. 4824 * 4825 * @return true if the view is clickable, false otherwise 4826 * 4827 * @see #setClickable(boolean) 4828 * @attr ref android.R.styleable#View_clickable 4829 */ 4830 @ViewDebug.ExportedProperty 4831 public boolean isClickable() { 4832 return (mViewFlags & CLICKABLE) == CLICKABLE; 4833 } 4834 4835 /** 4836 * Enables or disables click events for this view. When a view 4837 * is clickable it will change its state to "pressed" on every click. 4838 * Subclasses should set the view clickable to visually react to 4839 * user's clicks. 4840 * 4841 * @param clickable true to make the view clickable, false otherwise 4842 * 4843 * @see #isClickable() 4844 * @attr ref android.R.styleable#View_clickable 4845 */ 4846 public void setClickable(boolean clickable) { 4847 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 4848 } 4849 4850 /** 4851 * Indicates whether this view reacts to long click events or not. 4852 * 4853 * @return true if the view is long clickable, false otherwise 4854 * 4855 * @see #setLongClickable(boolean) 4856 * @attr ref android.R.styleable#View_longClickable 4857 */ 4858 public boolean isLongClickable() { 4859 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 4860 } 4861 4862 /** 4863 * Enables or disables long click events for this view. When a view is long 4864 * clickable it reacts to the user holding down the button for a longer 4865 * duration than a tap. This event can either launch the listener or a 4866 * context menu. 4867 * 4868 * @param longClickable true to make the view long clickable, false otherwise 4869 * @see #isLongClickable() 4870 * @attr ref android.R.styleable#View_longClickable 4871 */ 4872 public void setLongClickable(boolean longClickable) { 4873 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 4874 } 4875 4876 /** 4877 * Sets the pressed state for this view. 4878 * 4879 * @see #isClickable() 4880 * @see #setClickable(boolean) 4881 * 4882 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 4883 * the View's internal state from a previously set "pressed" state. 4884 */ 4885 public void setPressed(boolean pressed) { 4886 if (pressed) { 4887 mPrivateFlags |= PRESSED; 4888 } else { 4889 mPrivateFlags &= ~PRESSED; 4890 } 4891 refreshDrawableState(); 4892 dispatchSetPressed(pressed); 4893 } 4894 4895 /** 4896 * Dispatch setPressed to all of this View's children. 4897 * 4898 * @see #setPressed(boolean) 4899 * 4900 * @param pressed The new pressed state 4901 */ 4902 protected void dispatchSetPressed(boolean pressed) { 4903 } 4904 4905 /** 4906 * Indicates whether the view is currently in pressed state. Unless 4907 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 4908 * the pressed state. 4909 * 4910 * @see #setPressed(boolean) 4911 * @see #isClickable() 4912 * @see #setClickable(boolean) 4913 * 4914 * @return true if the view is currently pressed, false otherwise 4915 */ 4916 public boolean isPressed() { 4917 return (mPrivateFlags & PRESSED) == PRESSED; 4918 } 4919 4920 /** 4921 * Indicates whether this view will save its state (that is, 4922 * whether its {@link #onSaveInstanceState} method will be called). 4923 * 4924 * @return Returns true if the view state saving is enabled, else false. 4925 * 4926 * @see #setSaveEnabled(boolean) 4927 * @attr ref android.R.styleable#View_saveEnabled 4928 */ 4929 public boolean isSaveEnabled() { 4930 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 4931 } 4932 4933 /** 4934 * Controls whether the saving of this view's state is 4935 * enabled (that is, whether its {@link #onSaveInstanceState} method 4936 * will be called). Note that even if freezing is enabled, the 4937 * view still must have an id assigned to it (via {@link #setId(int)}) 4938 * for its state to be saved. This flag can only disable the 4939 * saving of this view; any child views may still have their state saved. 4940 * 4941 * @param enabled Set to false to <em>disable</em> state saving, or true 4942 * (the default) to allow it. 4943 * 4944 * @see #isSaveEnabled() 4945 * @see #setId(int) 4946 * @see #onSaveInstanceState() 4947 * @attr ref android.R.styleable#View_saveEnabled 4948 */ 4949 public void setSaveEnabled(boolean enabled) { 4950 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 4951 } 4952 4953 /** 4954 * Gets whether the framework should discard touches when the view's 4955 * window is obscured by another visible window. 4956 * Refer to the {@link View} security documentation for more details. 4957 * 4958 * @return True if touch filtering is enabled. 4959 * 4960 * @see #setFilterTouchesWhenObscured(boolean) 4961 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4962 */ 4963 @ViewDebug.ExportedProperty 4964 public boolean getFilterTouchesWhenObscured() { 4965 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 4966 } 4967 4968 /** 4969 * Sets whether the framework should discard touches when the view's 4970 * window is obscured by another visible window. 4971 * Refer to the {@link View} security documentation for more details. 4972 * 4973 * @param enabled True if touch filtering should be enabled. 4974 * 4975 * @see #getFilterTouchesWhenObscured 4976 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4977 */ 4978 public void setFilterTouchesWhenObscured(boolean enabled) { 4979 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 4980 FILTER_TOUCHES_WHEN_OBSCURED); 4981 } 4982 4983 /** 4984 * Indicates whether the entire hierarchy under this view will save its 4985 * state when a state saving traversal occurs from its parent. The default 4986 * is true; if false, these views will not be saved unless 4987 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4988 * 4989 * @return Returns true if the view state saving from parent is enabled, else false. 4990 * 4991 * @see #setSaveFromParentEnabled(boolean) 4992 */ 4993 public boolean isSaveFromParentEnabled() { 4994 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 4995 } 4996 4997 /** 4998 * Controls whether the entire hierarchy under this view will save its 4999 * state when a state saving traversal occurs from its parent. The default 5000 * is true; if false, these views will not be saved unless 5001 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 5002 * 5003 * @param enabled Set to false to <em>disable</em> state saving, or true 5004 * (the default) to allow it. 5005 * 5006 * @see #isSaveFromParentEnabled() 5007 * @see #setId(int) 5008 * @see #onSaveInstanceState() 5009 */ 5010 public void setSaveFromParentEnabled(boolean enabled) { 5011 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 5012 } 5013 5014 5015 /** 5016 * Returns whether this View is able to take focus. 5017 * 5018 * @return True if this view can take focus, or false otherwise. 5019 * @attr ref android.R.styleable#View_focusable 5020 */ 5021 @ViewDebug.ExportedProperty(category = "focus") 5022 public final boolean isFocusable() { 5023 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 5024 } 5025 5026 /** 5027 * When a view is focusable, it may not want to take focus when in touch mode. 5028 * For example, a button would like focus when the user is navigating via a D-pad 5029 * so that the user can click on it, but once the user starts touching the screen, 5030 * the button shouldn't take focus 5031 * @return Whether the view is focusable in touch mode. 5032 * @attr ref android.R.styleable#View_focusableInTouchMode 5033 */ 5034 @ViewDebug.ExportedProperty 5035 public final boolean isFocusableInTouchMode() { 5036 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 5037 } 5038 5039 /** 5040 * Find the nearest view in the specified direction that can take focus. 5041 * This does not actually give focus to that view. 5042 * 5043 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5044 * 5045 * @return The nearest focusable in the specified direction, or null if none 5046 * can be found. 5047 */ 5048 public View focusSearch(int direction) { 5049 if (mParent != null) { 5050 return mParent.focusSearch(this, direction); 5051 } else { 5052 return null; 5053 } 5054 } 5055 5056 /** 5057 * This method is the last chance for the focused view and its ancestors to 5058 * respond to an arrow key. This is called when the focused view did not 5059 * consume the key internally, nor could the view system find a new view in 5060 * the requested direction to give focus to. 5061 * 5062 * @param focused The currently focused view. 5063 * @param direction The direction focus wants to move. One of FOCUS_UP, 5064 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 5065 * @return True if the this view consumed this unhandled move. 5066 */ 5067 public boolean dispatchUnhandledMove(View focused, int direction) { 5068 return false; 5069 } 5070 5071 /** 5072 * If a user manually specified the next view id for a particular direction, 5073 * use the root to look up the view. 5074 * @param root The root view of the hierarchy containing this view. 5075 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 5076 * or FOCUS_BACKWARD. 5077 * @return The user specified next view, or null if there is none. 5078 */ 5079 View findUserSetNextFocus(View root, int direction) { 5080 switch (direction) { 5081 case FOCUS_LEFT: 5082 if (mNextFocusLeftId == View.NO_ID) return null; 5083 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 5084 case FOCUS_RIGHT: 5085 if (mNextFocusRightId == View.NO_ID) return null; 5086 return findViewInsideOutShouldExist(root, mNextFocusRightId); 5087 case FOCUS_UP: 5088 if (mNextFocusUpId == View.NO_ID) return null; 5089 return findViewInsideOutShouldExist(root, mNextFocusUpId); 5090 case FOCUS_DOWN: 5091 if (mNextFocusDownId == View.NO_ID) return null; 5092 return findViewInsideOutShouldExist(root, mNextFocusDownId); 5093 case FOCUS_FORWARD: 5094 if (mNextFocusForwardId == View.NO_ID) return null; 5095 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 5096 case FOCUS_BACKWARD: { 5097 final int id = mID; 5098 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5099 @Override 5100 public boolean apply(View t) { 5101 return t.mNextFocusForwardId == id; 5102 } 5103 }); 5104 } 5105 } 5106 return null; 5107 } 5108 5109 private View findViewInsideOutShouldExist(View root, final int childViewId) { 5110 View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5111 @Override 5112 public boolean apply(View t) { 5113 return t.mID == childViewId; 5114 } 5115 }); 5116 5117 if (result == null) { 5118 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified " 5119 + "by user for id " + childViewId); 5120 } 5121 return result; 5122 } 5123 5124 /** 5125 * Find and return all focusable views that are descendants of this view, 5126 * possibly including this view if it is focusable itself. 5127 * 5128 * @param direction The direction of the focus 5129 * @return A list of focusable views 5130 */ 5131 public ArrayList<View> getFocusables(int direction) { 5132 ArrayList<View> result = new ArrayList<View>(24); 5133 addFocusables(result, direction); 5134 return result; 5135 } 5136 5137 /** 5138 * Add any focusable views that are descendants of this view (possibly 5139 * including this view if it is focusable itself) to views. If we are in touch mode, 5140 * only add views that are also focusable in touch mode. 5141 * 5142 * @param views Focusable views found so far 5143 * @param direction The direction of the focus 5144 */ 5145 public void addFocusables(ArrayList<View> views, int direction) { 5146 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 5147 } 5148 5149 /** 5150 * Adds any focusable views that are descendants of this view (possibly 5151 * including this view if it is focusable itself) to views. This method 5152 * adds all focusable views regardless if we are in touch mode or 5153 * only views focusable in touch mode if we are in touch mode depending on 5154 * the focusable mode paramater. 5155 * 5156 * @param views Focusable views found so far or null if all we are interested is 5157 * the number of focusables. 5158 * @param direction The direction of the focus. 5159 * @param focusableMode The type of focusables to be added. 5160 * 5161 * @see #FOCUSABLES_ALL 5162 * @see #FOCUSABLES_TOUCH_MODE 5163 */ 5164 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 5165 if (!isFocusable()) { 5166 return; 5167 } 5168 5169 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 5170 isInTouchMode() && !isFocusableInTouchMode()) { 5171 return; 5172 } 5173 5174 if (views != null) { 5175 views.add(this); 5176 } 5177 } 5178 5179 /** 5180 * Finds the Views that contain given text. The containment is case insensitive. 5181 * The search is performed by either the text that the View renders or the content 5182 * description that describes the view for accessibility purposes and the view does 5183 * not render or both. Clients can specify how the search is to be performed via 5184 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 5185 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 5186 * 5187 * @param outViews The output list of matching Views. 5188 * @param searched The text to match against. 5189 * 5190 * @see #FIND_VIEWS_WITH_TEXT 5191 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 5192 * @see #setContentDescription(CharSequence) 5193 */ 5194 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 5195 if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 && !TextUtils.isEmpty(searched) 5196 && !TextUtils.isEmpty(mContentDescription)) { 5197 String searchedLowerCase = searched.toString().toLowerCase(); 5198 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 5199 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 5200 outViews.add(this); 5201 } 5202 } 5203 } 5204 5205 /** 5206 * Find and return all touchable views that are descendants of this view, 5207 * possibly including this view if it is touchable itself. 5208 * 5209 * @return A list of touchable views 5210 */ 5211 public ArrayList<View> getTouchables() { 5212 ArrayList<View> result = new ArrayList<View>(); 5213 addTouchables(result); 5214 return result; 5215 } 5216 5217 /** 5218 * Add any touchable views that are descendants of this view (possibly 5219 * including this view if it is touchable itself) to views. 5220 * 5221 * @param views Touchable views found so far 5222 */ 5223 public void addTouchables(ArrayList<View> views) { 5224 final int viewFlags = mViewFlags; 5225 5226 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 5227 && (viewFlags & ENABLED_MASK) == ENABLED) { 5228 views.add(this); 5229 } 5230 } 5231 5232 /** 5233 * Call this to try to give focus to a specific view or to one of its 5234 * descendants. 5235 * 5236 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5237 * false), or if it is focusable and it is not focusable in touch mode 5238 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5239 * 5240 * See also {@link #focusSearch(int)}, which is what you call to say that you 5241 * have focus, and you want your parent to look for the next one. 5242 * 5243 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 5244 * {@link #FOCUS_DOWN} and <code>null</code>. 5245 * 5246 * @return Whether this view or one of its descendants actually took focus. 5247 */ 5248 public final boolean requestFocus() { 5249 return requestFocus(View.FOCUS_DOWN); 5250 } 5251 5252 5253 /** 5254 * Call this to try to give focus to a specific view or to one of its 5255 * descendants and give it a hint about what direction focus is heading. 5256 * 5257 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5258 * false), or if it is focusable and it is not focusable in touch mode 5259 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5260 * 5261 * See also {@link #focusSearch(int)}, which is what you call to say that you 5262 * have focus, and you want your parent to look for the next one. 5263 * 5264 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 5265 * <code>null</code> set for the previously focused rectangle. 5266 * 5267 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5268 * @return Whether this view or one of its descendants actually took focus. 5269 */ 5270 public final boolean requestFocus(int direction) { 5271 return requestFocus(direction, null); 5272 } 5273 5274 /** 5275 * Call this to try to give focus to a specific view or to one of its descendants 5276 * and give it hints about the direction and a specific rectangle that the focus 5277 * is coming from. The rectangle can help give larger views a finer grained hint 5278 * about where focus is coming from, and therefore, where to show selection, or 5279 * forward focus change internally. 5280 * 5281 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5282 * false), or if it is focusable and it is not focusable in touch mode 5283 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5284 * 5285 * A View will not take focus if it is not visible. 5286 * 5287 * A View will not take focus if one of its parents has 5288 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 5289 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 5290 * 5291 * See also {@link #focusSearch(int)}, which is what you call to say that you 5292 * have focus, and you want your parent to look for the next one. 5293 * 5294 * You may wish to override this method if your custom {@link View} has an internal 5295 * {@link View} that it wishes to forward the request to. 5296 * 5297 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5298 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 5299 * to give a finer grained hint about where focus is coming from. May be null 5300 * if there is no hint. 5301 * @return Whether this view or one of its descendants actually took focus. 5302 */ 5303 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 5304 // need to be focusable 5305 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 5306 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5307 return false; 5308 } 5309 5310 // need to be focusable in touch mode if in touch mode 5311 if (isInTouchMode() && 5312 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 5313 return false; 5314 } 5315 5316 // need to not have any parents blocking us 5317 if (hasAncestorThatBlocksDescendantFocus()) { 5318 return false; 5319 } 5320 5321 handleFocusGainInternal(direction, previouslyFocusedRect); 5322 return true; 5323 } 5324 5325 /** Gets the ViewAncestor, or null if not attached. */ 5326 /*package*/ ViewRootImpl getViewRootImpl() { 5327 View root = getRootView(); 5328 return root != null ? (ViewRootImpl)root.getParent() : null; 5329 } 5330 5331 /** 5332 * Call this to try to give focus to a specific view or to one of its descendants. This is a 5333 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 5334 * touch mode to request focus when they are touched. 5335 * 5336 * @return Whether this view or one of its descendants actually took focus. 5337 * 5338 * @see #isInTouchMode() 5339 * 5340 */ 5341 public final boolean requestFocusFromTouch() { 5342 // Leave touch mode if we need to 5343 if (isInTouchMode()) { 5344 ViewRootImpl viewRoot = getViewRootImpl(); 5345 if (viewRoot != null) { 5346 viewRoot.ensureTouchMode(false); 5347 } 5348 } 5349 return requestFocus(View.FOCUS_DOWN); 5350 } 5351 5352 /** 5353 * @return Whether any ancestor of this view blocks descendant focus. 5354 */ 5355 private boolean hasAncestorThatBlocksDescendantFocus() { 5356 ViewParent ancestor = mParent; 5357 while (ancestor instanceof ViewGroup) { 5358 final ViewGroup vgAncestor = (ViewGroup) ancestor; 5359 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 5360 return true; 5361 } else { 5362 ancestor = vgAncestor.getParent(); 5363 } 5364 } 5365 return false; 5366 } 5367 5368 /** 5369 * @hide 5370 */ 5371 public void dispatchStartTemporaryDetach() { 5372 onStartTemporaryDetach(); 5373 } 5374 5375 /** 5376 * This is called when a container is going to temporarily detach a child, with 5377 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 5378 * It will either be followed by {@link #onFinishTemporaryDetach()} or 5379 * {@link #onDetachedFromWindow()} when the container is done. 5380 */ 5381 public void onStartTemporaryDetach() { 5382 removeUnsetPressCallback(); 5383 mPrivateFlags |= CANCEL_NEXT_UP_EVENT; 5384 } 5385 5386 /** 5387 * @hide 5388 */ 5389 public void dispatchFinishTemporaryDetach() { 5390 onFinishTemporaryDetach(); 5391 } 5392 5393 /** 5394 * Called after {@link #onStartTemporaryDetach} when the container is done 5395 * changing the view. 5396 */ 5397 public void onFinishTemporaryDetach() { 5398 } 5399 5400 /** 5401 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 5402 * for this view's window. Returns null if the view is not currently attached 5403 * to the window. Normally you will not need to use this directly, but 5404 * just use the standard high-level event callbacks like 5405 * {@link #onKeyDown(int, KeyEvent)}. 5406 */ 5407 public KeyEvent.DispatcherState getKeyDispatcherState() { 5408 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 5409 } 5410 5411 /** 5412 * Dispatch a key event before it is processed by any input method 5413 * associated with the view hierarchy. This can be used to intercept 5414 * key events in special situations before the IME consumes them; a 5415 * typical example would be handling the BACK key to update the application's 5416 * UI instead of allowing the IME to see it and close itself. 5417 * 5418 * @param event The key event to be dispatched. 5419 * @return True if the event was handled, false otherwise. 5420 */ 5421 public boolean dispatchKeyEventPreIme(KeyEvent event) { 5422 return onKeyPreIme(event.getKeyCode(), event); 5423 } 5424 5425 /** 5426 * Dispatch a key event to the next view on the focus path. This path runs 5427 * from the top of the view tree down to the currently focused view. If this 5428 * view has focus, it will dispatch to itself. Otherwise it will dispatch 5429 * the next node down the focus path. This method also fires any key 5430 * listeners. 5431 * 5432 * @param event The key event to be dispatched. 5433 * @return True if the event was handled, false otherwise. 5434 */ 5435 public boolean dispatchKeyEvent(KeyEvent event) { 5436 if (mInputEventConsistencyVerifier != null) { 5437 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 5438 } 5439 5440 // Give any attached key listener a first crack at the event. 5441 //noinspection SimplifiableIfStatement 5442 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5443 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 5444 return true; 5445 } 5446 5447 if (event.dispatch(this, mAttachInfo != null 5448 ? mAttachInfo.mKeyDispatchState : null, this)) { 5449 return true; 5450 } 5451 5452 if (mInputEventConsistencyVerifier != null) { 5453 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5454 } 5455 return false; 5456 } 5457 5458 /** 5459 * Dispatches a key shortcut event. 5460 * 5461 * @param event The key event to be dispatched. 5462 * @return True if the event was handled by the view, false otherwise. 5463 */ 5464 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 5465 return onKeyShortcut(event.getKeyCode(), event); 5466 } 5467 5468 /** 5469 * Pass the touch screen motion event down to the target view, or this 5470 * view if it is the target. 5471 * 5472 * @param event The motion event to be dispatched. 5473 * @return True if the event was handled by the view, false otherwise. 5474 */ 5475 public boolean dispatchTouchEvent(MotionEvent event) { 5476 if (mInputEventConsistencyVerifier != null) { 5477 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 5478 } 5479 5480 if (onFilterTouchEventForSecurity(event)) { 5481 //noinspection SimplifiableIfStatement 5482 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && 5483 mOnTouchListener.onTouch(this, event)) { 5484 return true; 5485 } 5486 5487 if (onTouchEvent(event)) { 5488 return true; 5489 } 5490 } 5491 5492 if (mInputEventConsistencyVerifier != null) { 5493 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5494 } 5495 return false; 5496 } 5497 5498 /** 5499 * Filter the touch event to apply security policies. 5500 * 5501 * @param event The motion event to be filtered. 5502 * @return True if the event should be dispatched, false if the event should be dropped. 5503 * 5504 * @see #getFilterTouchesWhenObscured 5505 */ 5506 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 5507 //noinspection RedundantIfStatement 5508 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 5509 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 5510 // Window is obscured, drop this touch. 5511 return false; 5512 } 5513 return true; 5514 } 5515 5516 /** 5517 * Pass a trackball motion event down to the focused view. 5518 * 5519 * @param event The motion event to be dispatched. 5520 * @return True if the event was handled by the view, false otherwise. 5521 */ 5522 public boolean dispatchTrackballEvent(MotionEvent event) { 5523 if (mInputEventConsistencyVerifier != null) { 5524 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 5525 } 5526 5527 return onTrackballEvent(event); 5528 } 5529 5530 /** 5531 * Dispatch a generic motion event. 5532 * <p> 5533 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5534 * are delivered to the view under the pointer. All other generic motion events are 5535 * delivered to the focused view. Hover events are handled specially and are delivered 5536 * to {@link #onHoverEvent(MotionEvent)}. 5537 * </p> 5538 * 5539 * @param event The motion event to be dispatched. 5540 * @return True if the event was handled by the view, false otherwise. 5541 */ 5542 public boolean dispatchGenericMotionEvent(MotionEvent event) { 5543 if (mInputEventConsistencyVerifier != null) { 5544 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 5545 } 5546 5547 final int source = event.getSource(); 5548 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5549 final int action = event.getAction(); 5550 if (action == MotionEvent.ACTION_HOVER_ENTER 5551 || action == MotionEvent.ACTION_HOVER_MOVE 5552 || action == MotionEvent.ACTION_HOVER_EXIT) { 5553 if (dispatchHoverEvent(event)) { 5554 return true; 5555 } 5556 } else if (dispatchGenericPointerEvent(event)) { 5557 return true; 5558 } 5559 } else if (dispatchGenericFocusedEvent(event)) { 5560 return true; 5561 } 5562 5563 if (dispatchGenericMotionEventInternal(event)) { 5564 return true; 5565 } 5566 5567 if (mInputEventConsistencyVerifier != null) { 5568 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5569 } 5570 return false; 5571 } 5572 5573 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 5574 //noinspection SimplifiableIfStatement 5575 if (mOnGenericMotionListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5576 && mOnGenericMotionListener.onGenericMotion(this, event)) { 5577 return true; 5578 } 5579 5580 if (onGenericMotionEvent(event)) { 5581 return true; 5582 } 5583 5584 if (mInputEventConsistencyVerifier != null) { 5585 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5586 } 5587 return false; 5588 } 5589 5590 /** 5591 * Dispatch a hover event. 5592 * <p> 5593 * Do not call this method directly. 5594 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5595 * </p> 5596 * 5597 * @param event The motion event to be dispatched. 5598 * @return True if the event was handled by the view, false otherwise. 5599 */ 5600 protected boolean dispatchHoverEvent(MotionEvent event) { 5601 //noinspection SimplifiableIfStatement 5602 if (mOnHoverListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5603 && mOnHoverListener.onHover(this, event)) { 5604 return true; 5605 } 5606 5607 return onHoverEvent(event); 5608 } 5609 5610 /** 5611 * Returns true if the view has a child to which it has recently sent 5612 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 5613 * it does not have a hovered child, then it must be the innermost hovered view. 5614 * @hide 5615 */ 5616 protected boolean hasHoveredChild() { 5617 return false; 5618 } 5619 5620 /** 5621 * Dispatch a generic motion event to the view under the first pointer. 5622 * <p> 5623 * Do not call this method directly. 5624 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5625 * </p> 5626 * 5627 * @param event The motion event to be dispatched. 5628 * @return True if the event was handled by the view, false otherwise. 5629 */ 5630 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 5631 return false; 5632 } 5633 5634 /** 5635 * Dispatch a generic motion event to the currently focused view. 5636 * <p> 5637 * Do not call this method directly. 5638 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5639 * </p> 5640 * 5641 * @param event The motion event to be dispatched. 5642 * @return True if the event was handled by the view, false otherwise. 5643 */ 5644 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 5645 return false; 5646 } 5647 5648 /** 5649 * Dispatch a pointer event. 5650 * <p> 5651 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 5652 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 5653 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 5654 * and should not be expected to handle other pointing device features. 5655 * </p> 5656 * 5657 * @param event The motion event to be dispatched. 5658 * @return True if the event was handled by the view, false otherwise. 5659 * @hide 5660 */ 5661 public final boolean dispatchPointerEvent(MotionEvent event) { 5662 if (event.isTouchEvent()) { 5663 return dispatchTouchEvent(event); 5664 } else { 5665 return dispatchGenericMotionEvent(event); 5666 } 5667 } 5668 5669 /** 5670 * Called when the window containing this view gains or loses window focus. 5671 * ViewGroups should override to route to their children. 5672 * 5673 * @param hasFocus True if the window containing this view now has focus, 5674 * false otherwise. 5675 */ 5676 public void dispatchWindowFocusChanged(boolean hasFocus) { 5677 onWindowFocusChanged(hasFocus); 5678 } 5679 5680 /** 5681 * Called when the window containing this view gains or loses focus. Note 5682 * that this is separate from view focus: to receive key events, both 5683 * your view and its window must have focus. If a window is displayed 5684 * on top of yours that takes input focus, then your own window will lose 5685 * focus but the view focus will remain unchanged. 5686 * 5687 * @param hasWindowFocus True if the window containing this view now has 5688 * focus, false otherwise. 5689 */ 5690 public void onWindowFocusChanged(boolean hasWindowFocus) { 5691 InputMethodManager imm = InputMethodManager.peekInstance(); 5692 if (!hasWindowFocus) { 5693 if (isPressed()) { 5694 setPressed(false); 5695 } 5696 if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5697 imm.focusOut(this); 5698 } 5699 removeLongPressCallback(); 5700 removeTapCallback(); 5701 onFocusLost(); 5702 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5703 imm.focusIn(this); 5704 } 5705 refreshDrawableState(); 5706 } 5707 5708 /** 5709 * Returns true if this view is in a window that currently has window focus. 5710 * Note that this is not the same as the view itself having focus. 5711 * 5712 * @return True if this view is in a window that currently has window focus. 5713 */ 5714 public boolean hasWindowFocus() { 5715 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 5716 } 5717 5718 /** 5719 * Dispatch a view visibility change down the view hierarchy. 5720 * ViewGroups should override to route to their children. 5721 * @param changedView The view whose visibility changed. Could be 'this' or 5722 * an ancestor view. 5723 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5724 * {@link #INVISIBLE} or {@link #GONE}. 5725 */ 5726 protected void dispatchVisibilityChanged(View changedView, int visibility) { 5727 onVisibilityChanged(changedView, visibility); 5728 } 5729 5730 /** 5731 * Called when the visibility of the view or an ancestor of the view is changed. 5732 * @param changedView The view whose visibility changed. Could be 'this' or 5733 * an ancestor view. 5734 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5735 * {@link #INVISIBLE} or {@link #GONE}. 5736 */ 5737 protected void onVisibilityChanged(View changedView, int visibility) { 5738 if (visibility == VISIBLE) { 5739 if (mAttachInfo != null) { 5740 initialAwakenScrollBars(); 5741 } else { 5742 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH; 5743 } 5744 } 5745 } 5746 5747 /** 5748 * Dispatch a hint about whether this view is displayed. For instance, when 5749 * a View moves out of the screen, it might receives a display hint indicating 5750 * the view is not displayed. Applications should not <em>rely</em> on this hint 5751 * as there is no guarantee that they will receive one. 5752 * 5753 * @param hint A hint about whether or not this view is displayed: 5754 * {@link #VISIBLE} or {@link #INVISIBLE}. 5755 */ 5756 public void dispatchDisplayHint(int hint) { 5757 onDisplayHint(hint); 5758 } 5759 5760 /** 5761 * Gives this view a hint about whether is displayed or not. For instance, when 5762 * a View moves out of the screen, it might receives a display hint indicating 5763 * the view is not displayed. Applications should not <em>rely</em> on this hint 5764 * as there is no guarantee that they will receive one. 5765 * 5766 * @param hint A hint about whether or not this view is displayed: 5767 * {@link #VISIBLE} or {@link #INVISIBLE}. 5768 */ 5769 protected void onDisplayHint(int hint) { 5770 } 5771 5772 /** 5773 * Dispatch a window visibility change down the view hierarchy. 5774 * ViewGroups should override to route to their children. 5775 * 5776 * @param visibility The new visibility of the window. 5777 * 5778 * @see #onWindowVisibilityChanged(int) 5779 */ 5780 public void dispatchWindowVisibilityChanged(int visibility) { 5781 onWindowVisibilityChanged(visibility); 5782 } 5783 5784 /** 5785 * Called when the window containing has change its visibility 5786 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 5787 * that this tells you whether or not your window is being made visible 5788 * to the window manager; this does <em>not</em> tell you whether or not 5789 * your window is obscured by other windows on the screen, even if it 5790 * is itself visible. 5791 * 5792 * @param visibility The new visibility of the window. 5793 */ 5794 protected void onWindowVisibilityChanged(int visibility) { 5795 if (visibility == VISIBLE) { 5796 initialAwakenScrollBars(); 5797 } 5798 } 5799 5800 /** 5801 * Returns the current visibility of the window this view is attached to 5802 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 5803 * 5804 * @return Returns the current visibility of the view's window. 5805 */ 5806 public int getWindowVisibility() { 5807 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 5808 } 5809 5810 /** 5811 * Retrieve the overall visible display size in which the window this view is 5812 * attached to has been positioned in. This takes into account screen 5813 * decorations above the window, for both cases where the window itself 5814 * is being position inside of them or the window is being placed under 5815 * then and covered insets are used for the window to position its content 5816 * inside. In effect, this tells you the available area where content can 5817 * be placed and remain visible to users. 5818 * 5819 * <p>This function requires an IPC back to the window manager to retrieve 5820 * the requested information, so should not be used in performance critical 5821 * code like drawing. 5822 * 5823 * @param outRect Filled in with the visible display frame. If the view 5824 * is not attached to a window, this is simply the raw display size. 5825 */ 5826 public void getWindowVisibleDisplayFrame(Rect outRect) { 5827 if (mAttachInfo != null) { 5828 try { 5829 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 5830 } catch (RemoteException e) { 5831 return; 5832 } 5833 // XXX This is really broken, and probably all needs to be done 5834 // in the window manager, and we need to know more about whether 5835 // we want the area behind or in front of the IME. 5836 final Rect insets = mAttachInfo.mVisibleInsets; 5837 outRect.left += insets.left; 5838 outRect.top += insets.top; 5839 outRect.right -= insets.right; 5840 outRect.bottom -= insets.bottom; 5841 return; 5842 } 5843 Display d = WindowManagerImpl.getDefault().getDefaultDisplay(); 5844 d.getRectSize(outRect); 5845 } 5846 5847 /** 5848 * Dispatch a notification about a resource configuration change down 5849 * the view hierarchy. 5850 * ViewGroups should override to route to their children. 5851 * 5852 * @param newConfig The new resource configuration. 5853 * 5854 * @see #onConfigurationChanged(android.content.res.Configuration) 5855 */ 5856 public void dispatchConfigurationChanged(Configuration newConfig) { 5857 onConfigurationChanged(newConfig); 5858 } 5859 5860 /** 5861 * Called when the current configuration of the resources being used 5862 * by the application have changed. You can use this to decide when 5863 * to reload resources that can changed based on orientation and other 5864 * configuration characterstics. You only need to use this if you are 5865 * not relying on the normal {@link android.app.Activity} mechanism of 5866 * recreating the activity instance upon a configuration change. 5867 * 5868 * @param newConfig The new resource configuration. 5869 */ 5870 protected void onConfigurationChanged(Configuration newConfig) { 5871 } 5872 5873 /** 5874 * Private function to aggregate all per-view attributes in to the view 5875 * root. 5876 */ 5877 void dispatchCollectViewAttributes(int visibility) { 5878 performCollectViewAttributes(visibility); 5879 } 5880 5881 void performCollectViewAttributes(int visibility) { 5882 if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) { 5883 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 5884 mAttachInfo.mKeepScreenOn = true; 5885 } 5886 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility; 5887 if (mOnSystemUiVisibilityChangeListener != null) { 5888 mAttachInfo.mHasSystemUiListeners = true; 5889 } 5890 } 5891 } 5892 5893 void needGlobalAttributesUpdate(boolean force) { 5894 final AttachInfo ai = mAttachInfo; 5895 if (ai != null) { 5896 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 5897 || ai.mHasSystemUiListeners) { 5898 ai.mRecomputeGlobalAttributes = true; 5899 } 5900 } 5901 } 5902 5903 /** 5904 * Returns whether the device is currently in touch mode. Touch mode is entered 5905 * once the user begins interacting with the device by touch, and affects various 5906 * things like whether focus is always visible to the user. 5907 * 5908 * @return Whether the device is in touch mode. 5909 */ 5910 @ViewDebug.ExportedProperty 5911 public boolean isInTouchMode() { 5912 if (mAttachInfo != null) { 5913 return mAttachInfo.mInTouchMode; 5914 } else { 5915 return ViewRootImpl.isInTouchMode(); 5916 } 5917 } 5918 5919 /** 5920 * Returns the context the view is running in, through which it can 5921 * access the current theme, resources, etc. 5922 * 5923 * @return The view's Context. 5924 */ 5925 @ViewDebug.CapturedViewProperty 5926 public final Context getContext() { 5927 return mContext; 5928 } 5929 5930 /** 5931 * Handle a key event before it is processed by any input method 5932 * associated with the view hierarchy. This can be used to intercept 5933 * key events in special situations before the IME consumes them; a 5934 * typical example would be handling the BACK key to update the application's 5935 * UI instead of allowing the IME to see it and close itself. 5936 * 5937 * @param keyCode The value in event.getKeyCode(). 5938 * @param event Description of the key event. 5939 * @return If you handled the event, return true. If you want to allow the 5940 * event to be handled by the next receiver, return false. 5941 */ 5942 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 5943 return false; 5944 } 5945 5946 /** 5947 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 5948 * KeyEvent.Callback.onKeyDown()}: perform press of the view 5949 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 5950 * is released, if the view is enabled and clickable. 5951 * 5952 * @param keyCode A key code that represents the button pressed, from 5953 * {@link android.view.KeyEvent}. 5954 * @param event The KeyEvent object that defines the button action. 5955 */ 5956 public boolean onKeyDown(int keyCode, KeyEvent event) { 5957 boolean result = false; 5958 5959 switch (keyCode) { 5960 case KeyEvent.KEYCODE_DPAD_CENTER: 5961 case KeyEvent.KEYCODE_ENTER: { 5962 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5963 return true; 5964 } 5965 // Long clickable items don't necessarily have to be clickable 5966 if (((mViewFlags & CLICKABLE) == CLICKABLE || 5967 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 5968 (event.getRepeatCount() == 0)) { 5969 setPressed(true); 5970 checkForLongClick(0); 5971 return true; 5972 } 5973 break; 5974 } 5975 } 5976 return result; 5977 } 5978 5979 /** 5980 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 5981 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 5982 * the event). 5983 */ 5984 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 5985 return false; 5986 } 5987 5988 /** 5989 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 5990 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 5991 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 5992 * {@link KeyEvent#KEYCODE_ENTER} is released. 5993 * 5994 * @param keyCode A key code that represents the button pressed, from 5995 * {@link android.view.KeyEvent}. 5996 * @param event The KeyEvent object that defines the button action. 5997 */ 5998 public boolean onKeyUp(int keyCode, KeyEvent event) { 5999 boolean result = false; 6000 6001 switch (keyCode) { 6002 case KeyEvent.KEYCODE_DPAD_CENTER: 6003 case KeyEvent.KEYCODE_ENTER: { 6004 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6005 return true; 6006 } 6007 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 6008 setPressed(false); 6009 6010 if (!mHasPerformedLongPress) { 6011 // This is a tap, so remove the longpress check 6012 removeLongPressCallback(); 6013 6014 result = performClick(); 6015 } 6016 } 6017 break; 6018 } 6019 } 6020 return result; 6021 } 6022 6023 /** 6024 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 6025 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 6026 * the event). 6027 * 6028 * @param keyCode A key code that represents the button pressed, from 6029 * {@link android.view.KeyEvent}. 6030 * @param repeatCount The number of times the action was made. 6031 * @param event The KeyEvent object that defines the button action. 6032 */ 6033 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 6034 return false; 6035 } 6036 6037 /** 6038 * Called on the focused view when a key shortcut event is not handled. 6039 * Override this method to implement local key shortcuts for the View. 6040 * Key shortcuts can also be implemented by setting the 6041 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 6042 * 6043 * @param keyCode The value in event.getKeyCode(). 6044 * @param event Description of the key event. 6045 * @return If you handled the event, return true. If you want to allow the 6046 * event to be handled by the next receiver, return false. 6047 */ 6048 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 6049 return false; 6050 } 6051 6052 /** 6053 * Check whether the called view is a text editor, in which case it 6054 * would make sense to automatically display a soft input window for 6055 * it. Subclasses should override this if they implement 6056 * {@link #onCreateInputConnection(EditorInfo)} to return true if 6057 * a call on that method would return a non-null InputConnection, and 6058 * they are really a first-class editor that the user would normally 6059 * start typing on when the go into a window containing your view. 6060 * 6061 * <p>The default implementation always returns false. This does 6062 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 6063 * will not be called or the user can not otherwise perform edits on your 6064 * view; it is just a hint to the system that this is not the primary 6065 * purpose of this view. 6066 * 6067 * @return Returns true if this view is a text editor, else false. 6068 */ 6069 public boolean onCheckIsTextEditor() { 6070 return false; 6071 } 6072 6073 /** 6074 * Create a new InputConnection for an InputMethod to interact 6075 * with the view. The default implementation returns null, since it doesn't 6076 * support input methods. You can override this to implement such support. 6077 * This is only needed for views that take focus and text input. 6078 * 6079 * <p>When implementing this, you probably also want to implement 6080 * {@link #onCheckIsTextEditor()} to indicate you will return a 6081 * non-null InputConnection. 6082 * 6083 * @param outAttrs Fill in with attribute information about the connection. 6084 */ 6085 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 6086 return null; 6087 } 6088 6089 /** 6090 * Called by the {@link android.view.inputmethod.InputMethodManager} 6091 * when a view who is not the current 6092 * input connection target is trying to make a call on the manager. The 6093 * default implementation returns false; you can override this to return 6094 * true for certain views if you are performing InputConnection proxying 6095 * to them. 6096 * @param view The View that is making the InputMethodManager call. 6097 * @return Return true to allow the call, false to reject. 6098 */ 6099 public boolean checkInputConnectionProxy(View view) { 6100 return false; 6101 } 6102 6103 /** 6104 * Show the context menu for this view. It is not safe to hold on to the 6105 * menu after returning from this method. 6106 * 6107 * You should normally not overload this method. Overload 6108 * {@link #onCreateContextMenu(ContextMenu)} or define an 6109 * {@link OnCreateContextMenuListener} to add items to the context menu. 6110 * 6111 * @param menu The context menu to populate 6112 */ 6113 public void createContextMenu(ContextMenu menu) { 6114 ContextMenuInfo menuInfo = getContextMenuInfo(); 6115 6116 // Sets the current menu info so all items added to menu will have 6117 // my extra info set. 6118 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 6119 6120 onCreateContextMenu(menu); 6121 if (mOnCreateContextMenuListener != null) { 6122 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 6123 } 6124 6125 // Clear the extra information so subsequent items that aren't mine don't 6126 // have my extra info. 6127 ((MenuBuilder)menu).setCurrentMenuInfo(null); 6128 6129 if (mParent != null) { 6130 mParent.createContextMenu(menu); 6131 } 6132 } 6133 6134 /** 6135 * Views should implement this if they have extra information to associate 6136 * with the context menu. The return result is supplied as a parameter to 6137 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 6138 * callback. 6139 * 6140 * @return Extra information about the item for which the context menu 6141 * should be shown. This information will vary across different 6142 * subclasses of View. 6143 */ 6144 protected ContextMenuInfo getContextMenuInfo() { 6145 return null; 6146 } 6147 6148 /** 6149 * Views should implement this if the view itself is going to add items to 6150 * the context menu. 6151 * 6152 * @param menu the context menu to populate 6153 */ 6154 protected void onCreateContextMenu(ContextMenu menu) { 6155 } 6156 6157 /** 6158 * Implement this method to handle trackball motion events. The 6159 * <em>relative</em> movement of the trackball since the last event 6160 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 6161 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 6162 * that a movement of 1 corresponds to the user pressing one DPAD key (so 6163 * they will often be fractional values, representing the more fine-grained 6164 * movement information available from a trackball). 6165 * 6166 * @param event The motion event. 6167 * @return True if the event was handled, false otherwise. 6168 */ 6169 public boolean onTrackballEvent(MotionEvent event) { 6170 return false; 6171 } 6172 6173 /** 6174 * Implement this method to handle generic motion events. 6175 * <p> 6176 * Generic motion events describe joystick movements, mouse hovers, track pad 6177 * touches, scroll wheel movements and other input events. The 6178 * {@link MotionEvent#getSource() source} of the motion event specifies 6179 * the class of input that was received. Implementations of this method 6180 * must examine the bits in the source before processing the event. 6181 * The following code example shows how this is done. 6182 * </p><p> 6183 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 6184 * are delivered to the view under the pointer. All other generic motion events are 6185 * delivered to the focused view. 6186 * </p> 6187 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 6188 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 6189 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 6190 * // process the joystick movement... 6191 * return true; 6192 * } 6193 * } 6194 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 6195 * switch (event.getAction()) { 6196 * case MotionEvent.ACTION_HOVER_MOVE: 6197 * // process the mouse hover movement... 6198 * return true; 6199 * case MotionEvent.ACTION_SCROLL: 6200 * // process the scroll wheel movement... 6201 * return true; 6202 * } 6203 * } 6204 * return super.onGenericMotionEvent(event); 6205 * }</pre> 6206 * 6207 * @param event The generic motion event being processed. 6208 * @return True if the event was handled, false otherwise. 6209 */ 6210 public boolean onGenericMotionEvent(MotionEvent event) { 6211 return false; 6212 } 6213 6214 /** 6215 * Implement this method to handle hover events. 6216 * <p> 6217 * This method is called whenever a pointer is hovering into, over, or out of the 6218 * bounds of a view and the view is not currently being touched. 6219 * Hover events are represented as pointer events with action 6220 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 6221 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 6222 * </p> 6223 * <ul> 6224 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 6225 * when the pointer enters the bounds of the view.</li> 6226 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 6227 * when the pointer has already entered the bounds of the view and has moved.</li> 6228 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 6229 * when the pointer has exited the bounds of the view or when the pointer is 6230 * about to go down due to a button click, tap, or similar user action that 6231 * causes the view to be touched.</li> 6232 * </ul> 6233 * <p> 6234 * The view should implement this method to return true to indicate that it is 6235 * handling the hover event, such as by changing its drawable state. 6236 * </p><p> 6237 * The default implementation calls {@link #setHovered} to update the hovered state 6238 * of the view when a hover enter or hover exit event is received, if the view 6239 * is enabled and is clickable. The default implementation also sends hover 6240 * accessibility events. 6241 * </p> 6242 * 6243 * @param event The motion event that describes the hover. 6244 * @return True if the view handled the hover event. 6245 * 6246 * @see #isHovered 6247 * @see #setHovered 6248 * @see #onHoverChanged 6249 */ 6250 public boolean onHoverEvent(MotionEvent event) { 6251 // The root view may receive hover (or touch) events that are outside the bounds of 6252 // the window. This code ensures that we only send accessibility events for 6253 // hovers that are actually within the bounds of the root view. 6254 final int action = event.getAction(); 6255 if (!mSendingHoverAccessibilityEvents) { 6256 if ((action == MotionEvent.ACTION_HOVER_ENTER 6257 || action == MotionEvent.ACTION_HOVER_MOVE) 6258 && !hasHoveredChild() 6259 && pointInView(event.getX(), event.getY())) { 6260 mSendingHoverAccessibilityEvents = true; 6261 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 6262 } 6263 } else { 6264 if (action == MotionEvent.ACTION_HOVER_EXIT 6265 || (action == MotionEvent.ACTION_HOVER_MOVE 6266 && !pointInView(event.getX(), event.getY()))) { 6267 mSendingHoverAccessibilityEvents = false; 6268 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 6269 } 6270 } 6271 6272 if (isHoverable()) { 6273 switch (action) { 6274 case MotionEvent.ACTION_HOVER_ENTER: 6275 setHovered(true); 6276 break; 6277 case MotionEvent.ACTION_HOVER_EXIT: 6278 setHovered(false); 6279 break; 6280 } 6281 6282 // Dispatch the event to onGenericMotionEvent before returning true. 6283 // This is to provide compatibility with existing applications that 6284 // handled HOVER_MOVE events in onGenericMotionEvent and that would 6285 // break because of the new default handling for hoverable views 6286 // in onHoverEvent. 6287 // Note that onGenericMotionEvent will be called by default when 6288 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 6289 dispatchGenericMotionEventInternal(event); 6290 return true; 6291 } 6292 return false; 6293 } 6294 6295 /** 6296 * Returns true if the view should handle {@link #onHoverEvent} 6297 * by calling {@link #setHovered} to change its hovered state. 6298 * 6299 * @return True if the view is hoverable. 6300 */ 6301 private boolean isHoverable() { 6302 final int viewFlags = mViewFlags; 6303 //noinspection SimplifiableIfStatement 6304 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6305 return false; 6306 } 6307 6308 return (viewFlags & CLICKABLE) == CLICKABLE 6309 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6310 } 6311 6312 /** 6313 * Returns true if the view is currently hovered. 6314 * 6315 * @return True if the view is currently hovered. 6316 * 6317 * @see #setHovered 6318 * @see #onHoverChanged 6319 */ 6320 @ViewDebug.ExportedProperty 6321 public boolean isHovered() { 6322 return (mPrivateFlags & HOVERED) != 0; 6323 } 6324 6325 /** 6326 * Sets whether the view is currently hovered. 6327 * <p> 6328 * Calling this method also changes the drawable state of the view. This 6329 * enables the view to react to hover by using different drawable resources 6330 * to change its appearance. 6331 * </p><p> 6332 * The {@link #onHoverChanged} method is called when the hovered state changes. 6333 * </p> 6334 * 6335 * @param hovered True if the view is hovered. 6336 * 6337 * @see #isHovered 6338 * @see #onHoverChanged 6339 */ 6340 public void setHovered(boolean hovered) { 6341 if (hovered) { 6342 if ((mPrivateFlags & HOVERED) == 0) { 6343 mPrivateFlags |= HOVERED; 6344 refreshDrawableState(); 6345 onHoverChanged(true); 6346 } 6347 } else { 6348 if ((mPrivateFlags & HOVERED) != 0) { 6349 mPrivateFlags &= ~HOVERED; 6350 refreshDrawableState(); 6351 onHoverChanged(false); 6352 } 6353 } 6354 } 6355 6356 /** 6357 * Implement this method to handle hover state changes. 6358 * <p> 6359 * This method is called whenever the hover state changes as a result of a 6360 * call to {@link #setHovered}. 6361 * </p> 6362 * 6363 * @param hovered The current hover state, as returned by {@link #isHovered}. 6364 * 6365 * @see #isHovered 6366 * @see #setHovered 6367 */ 6368 public void onHoverChanged(boolean hovered) { 6369 } 6370 6371 /** 6372 * Implement this method to handle touch screen motion events. 6373 * 6374 * @param event The motion event. 6375 * @return True if the event was handled, false otherwise. 6376 */ 6377 public boolean onTouchEvent(MotionEvent event) { 6378 final int viewFlags = mViewFlags; 6379 6380 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6381 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) { 6382 mPrivateFlags &= ~PRESSED; 6383 refreshDrawableState(); 6384 } 6385 // A disabled view that is clickable still consumes the touch 6386 // events, it just doesn't respond to them. 6387 return (((viewFlags & CLICKABLE) == CLICKABLE || 6388 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 6389 } 6390 6391 if (mTouchDelegate != null) { 6392 if (mTouchDelegate.onTouchEvent(event)) { 6393 return true; 6394 } 6395 } 6396 6397 if (((viewFlags & CLICKABLE) == CLICKABLE || 6398 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 6399 switch (event.getAction()) { 6400 case MotionEvent.ACTION_UP: 6401 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; 6402 if ((mPrivateFlags & PRESSED) != 0 || prepressed) { 6403 // take focus if we don't have it already and we should in 6404 // touch mode. 6405 boolean focusTaken = false; 6406 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 6407 focusTaken = requestFocus(); 6408 } 6409 6410 if (prepressed) { 6411 // The button is being released before we actually 6412 // showed it as pressed. Make it show the pressed 6413 // state now (before scheduling the click) to ensure 6414 // the user sees it. 6415 mPrivateFlags |= PRESSED; 6416 refreshDrawableState(); 6417 } 6418 6419 if (!mHasPerformedLongPress) { 6420 // This is a tap, so remove the longpress check 6421 removeLongPressCallback(); 6422 6423 // Only perform take click actions if we were in the pressed state 6424 if (!focusTaken) { 6425 // Use a Runnable and post this rather than calling 6426 // performClick directly. This lets other visual state 6427 // of the view update before click actions start. 6428 if (mPerformClick == null) { 6429 mPerformClick = new PerformClick(); 6430 } 6431 if (!post(mPerformClick)) { 6432 performClick(); 6433 } 6434 } 6435 } 6436 6437 if (mUnsetPressedState == null) { 6438 mUnsetPressedState = new UnsetPressedState(); 6439 } 6440 6441 if (prepressed) { 6442 postDelayed(mUnsetPressedState, 6443 ViewConfiguration.getPressedStateDuration()); 6444 } else if (!post(mUnsetPressedState)) { 6445 // If the post failed, unpress right now 6446 mUnsetPressedState.run(); 6447 } 6448 removeTapCallback(); 6449 } 6450 break; 6451 6452 case MotionEvent.ACTION_DOWN: 6453 mHasPerformedLongPress = false; 6454 6455 if (performButtonActionOnTouchDown(event)) { 6456 break; 6457 } 6458 6459 // Walk up the hierarchy to determine if we're inside a scrolling container. 6460 boolean isInScrollingContainer = isInScrollingContainer(); 6461 6462 // For views inside a scrolling container, delay the pressed feedback for 6463 // a short period in case this is a scroll. 6464 if (isInScrollingContainer) { 6465 mPrivateFlags |= PREPRESSED; 6466 if (mPendingCheckForTap == null) { 6467 mPendingCheckForTap = new CheckForTap(); 6468 } 6469 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 6470 } else { 6471 // Not inside a scrolling container, so show the feedback right away 6472 mPrivateFlags |= PRESSED; 6473 refreshDrawableState(); 6474 checkForLongClick(0); 6475 } 6476 break; 6477 6478 case MotionEvent.ACTION_CANCEL: 6479 mPrivateFlags &= ~PRESSED; 6480 refreshDrawableState(); 6481 removeTapCallback(); 6482 break; 6483 6484 case MotionEvent.ACTION_MOVE: 6485 final int x = (int) event.getX(); 6486 final int y = (int) event.getY(); 6487 6488 // Be lenient about moving outside of buttons 6489 if (!pointInView(x, y, mTouchSlop)) { 6490 // Outside button 6491 removeTapCallback(); 6492 if ((mPrivateFlags & PRESSED) != 0) { 6493 // Remove any future long press/tap checks 6494 removeLongPressCallback(); 6495 6496 // Need to switch from pressed to not pressed 6497 mPrivateFlags &= ~PRESSED; 6498 refreshDrawableState(); 6499 } 6500 } 6501 break; 6502 } 6503 return true; 6504 } 6505 6506 return false; 6507 } 6508 6509 /** 6510 * @hide 6511 */ 6512 public boolean isInScrollingContainer() { 6513 ViewParent p = getParent(); 6514 while (p != null && p instanceof ViewGroup) { 6515 if (((ViewGroup) p).shouldDelayChildPressedState()) { 6516 return true; 6517 } 6518 p = p.getParent(); 6519 } 6520 return false; 6521 } 6522 6523 /** 6524 * Remove the longpress detection timer. 6525 */ 6526 private void removeLongPressCallback() { 6527 if (mPendingCheckForLongPress != null) { 6528 removeCallbacks(mPendingCheckForLongPress); 6529 } 6530 } 6531 6532 /** 6533 * Remove the pending click action 6534 */ 6535 private void removePerformClickCallback() { 6536 if (mPerformClick != null) { 6537 removeCallbacks(mPerformClick); 6538 } 6539 } 6540 6541 /** 6542 * Remove the prepress detection timer. 6543 */ 6544 private void removeUnsetPressCallback() { 6545 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) { 6546 setPressed(false); 6547 removeCallbacks(mUnsetPressedState); 6548 } 6549 } 6550 6551 /** 6552 * Remove the tap detection timer. 6553 */ 6554 private void removeTapCallback() { 6555 if (mPendingCheckForTap != null) { 6556 mPrivateFlags &= ~PREPRESSED; 6557 removeCallbacks(mPendingCheckForTap); 6558 } 6559 } 6560 6561 /** 6562 * Cancels a pending long press. Your subclass can use this if you 6563 * want the context menu to come up if the user presses and holds 6564 * at the same place, but you don't want it to come up if they press 6565 * and then move around enough to cause scrolling. 6566 */ 6567 public void cancelLongPress() { 6568 removeLongPressCallback(); 6569 6570 /* 6571 * The prepressed state handled by the tap callback is a display 6572 * construct, but the tap callback will post a long press callback 6573 * less its own timeout. Remove it here. 6574 */ 6575 removeTapCallback(); 6576 } 6577 6578 /** 6579 * Remove the pending callback for sending a 6580 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 6581 */ 6582 private void removeSendViewScrolledAccessibilityEventCallback() { 6583 if (mSendViewScrolledAccessibilityEvent != null) { 6584 removeCallbacks(mSendViewScrolledAccessibilityEvent); 6585 } 6586 } 6587 6588 /** 6589 * Sets the TouchDelegate for this View. 6590 */ 6591 public void setTouchDelegate(TouchDelegate delegate) { 6592 mTouchDelegate = delegate; 6593 } 6594 6595 /** 6596 * Gets the TouchDelegate for this View. 6597 */ 6598 public TouchDelegate getTouchDelegate() { 6599 return mTouchDelegate; 6600 } 6601 6602 /** 6603 * Set flags controlling behavior of this view. 6604 * 6605 * @param flags Constant indicating the value which should be set 6606 * @param mask Constant indicating the bit range that should be changed 6607 */ 6608 void setFlags(int flags, int mask) { 6609 int old = mViewFlags; 6610 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 6611 6612 int changed = mViewFlags ^ old; 6613 if (changed == 0) { 6614 return; 6615 } 6616 int privateFlags = mPrivateFlags; 6617 6618 /* Check if the FOCUSABLE bit has changed */ 6619 if (((changed & FOCUSABLE_MASK) != 0) && 6620 ((privateFlags & HAS_BOUNDS) !=0)) { 6621 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 6622 && ((privateFlags & FOCUSED) != 0)) { 6623 /* Give up focus if we are no longer focusable */ 6624 clearFocus(); 6625 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 6626 && ((privateFlags & FOCUSED) == 0)) { 6627 /* 6628 * Tell the view system that we are now available to take focus 6629 * if no one else already has it. 6630 */ 6631 if (mParent != null) mParent.focusableViewAvailable(this); 6632 } 6633 } 6634 6635 if ((flags & VISIBILITY_MASK) == VISIBLE) { 6636 if ((changed & VISIBILITY_MASK) != 0) { 6637 /* 6638 * If this view is becoming visible, invalidate it in case it changed while 6639 * it was not visible. Marking it drawn ensures that the invalidation will 6640 * go through. 6641 */ 6642 mPrivateFlags |= DRAWN; 6643 invalidate(true); 6644 6645 needGlobalAttributesUpdate(true); 6646 6647 // a view becoming visible is worth notifying the parent 6648 // about in case nothing has focus. even if this specific view 6649 // isn't focusable, it may contain something that is, so let 6650 // the root view try to give this focus if nothing else does. 6651 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 6652 mParent.focusableViewAvailable(this); 6653 } 6654 } 6655 } 6656 6657 /* Check if the GONE bit has changed */ 6658 if ((changed & GONE) != 0) { 6659 needGlobalAttributesUpdate(false); 6660 requestLayout(); 6661 6662 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 6663 if (hasFocus()) clearFocus(); 6664 destroyDrawingCache(); 6665 if (mParent instanceof View) { 6666 // GONE views noop invalidation, so invalidate the parent 6667 ((View) mParent).invalidate(true); 6668 } 6669 // Mark the view drawn to ensure that it gets invalidated properly the next 6670 // time it is visible and gets invalidated 6671 mPrivateFlags |= DRAWN; 6672 } 6673 if (mAttachInfo != null) { 6674 mAttachInfo.mViewVisibilityChanged = true; 6675 } 6676 } 6677 6678 /* Check if the VISIBLE bit has changed */ 6679 if ((changed & INVISIBLE) != 0) { 6680 needGlobalAttributesUpdate(false); 6681 /* 6682 * If this view is becoming invisible, set the DRAWN flag so that 6683 * the next invalidate() will not be skipped. 6684 */ 6685 mPrivateFlags |= DRAWN; 6686 6687 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 6688 // root view becoming invisible shouldn't clear focus 6689 if (getRootView() != this) { 6690 clearFocus(); 6691 } 6692 } 6693 if (mAttachInfo != null) { 6694 mAttachInfo.mViewVisibilityChanged = true; 6695 } 6696 } 6697 6698 if ((changed & VISIBILITY_MASK) != 0) { 6699 if (mParent instanceof ViewGroup) { 6700 ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6701 ((View) mParent).invalidate(true); 6702 } else if (mParent != null) { 6703 mParent.invalidateChild(this, null); 6704 } 6705 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6706 } 6707 6708 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 6709 destroyDrawingCache(); 6710 } 6711 6712 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 6713 destroyDrawingCache(); 6714 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6715 invalidateParentCaches(); 6716 } 6717 6718 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 6719 destroyDrawingCache(); 6720 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6721 } 6722 6723 if ((changed & DRAW_MASK) != 0) { 6724 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 6725 if (mBGDrawable != null) { 6726 mPrivateFlags &= ~SKIP_DRAW; 6727 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 6728 } else { 6729 mPrivateFlags |= SKIP_DRAW; 6730 } 6731 } else { 6732 mPrivateFlags &= ~SKIP_DRAW; 6733 } 6734 requestLayout(); 6735 invalidate(true); 6736 } 6737 6738 if ((changed & KEEP_SCREEN_ON) != 0) { 6739 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 6740 mParent.recomputeViewAttributes(this); 6741 } 6742 } 6743 6744 if ((changed & LAYOUT_DIRECTION_MASK) != 0) { 6745 requestLayout(); 6746 } 6747 } 6748 6749 /** 6750 * Change the view's z order in the tree, so it's on top of other sibling 6751 * views 6752 */ 6753 public void bringToFront() { 6754 if (mParent != null) { 6755 mParent.bringChildToFront(this); 6756 } 6757 } 6758 6759 /** 6760 * This is called in response to an internal scroll in this view (i.e., the 6761 * view scrolled its own contents). This is typically as a result of 6762 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 6763 * called. 6764 * 6765 * @param l Current horizontal scroll origin. 6766 * @param t Current vertical scroll origin. 6767 * @param oldl Previous horizontal scroll origin. 6768 * @param oldt Previous vertical scroll origin. 6769 */ 6770 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 6771 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6772 postSendViewScrolledAccessibilityEventCallback(); 6773 } 6774 6775 mBackgroundSizeChanged = true; 6776 6777 final AttachInfo ai = mAttachInfo; 6778 if (ai != null) { 6779 ai.mViewScrollChanged = true; 6780 } 6781 } 6782 6783 /** 6784 * Interface definition for a callback to be invoked when the layout bounds of a view 6785 * changes due to layout processing. 6786 */ 6787 public interface OnLayoutChangeListener { 6788 /** 6789 * Called when the focus state of a view has changed. 6790 * 6791 * @param v The view whose state has changed. 6792 * @param left The new value of the view's left property. 6793 * @param top The new value of the view's top property. 6794 * @param right The new value of the view's right property. 6795 * @param bottom The new value of the view's bottom property. 6796 * @param oldLeft The previous value of the view's left property. 6797 * @param oldTop The previous value of the view's top property. 6798 * @param oldRight The previous value of the view's right property. 6799 * @param oldBottom The previous value of the view's bottom property. 6800 */ 6801 void onLayoutChange(View v, int left, int top, int right, int bottom, 6802 int oldLeft, int oldTop, int oldRight, int oldBottom); 6803 } 6804 6805 /** 6806 * This is called during layout when the size of this view has changed. If 6807 * you were just added to the view hierarchy, you're called with the old 6808 * values of 0. 6809 * 6810 * @param w Current width of this view. 6811 * @param h Current height of this view. 6812 * @param oldw Old width of this view. 6813 * @param oldh Old height of this view. 6814 */ 6815 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 6816 } 6817 6818 /** 6819 * Called by draw to draw the child views. This may be overridden 6820 * by derived classes to gain control just before its children are drawn 6821 * (but after its own view has been drawn). 6822 * @param canvas the canvas on which to draw the view 6823 */ 6824 protected void dispatchDraw(Canvas canvas) { 6825 } 6826 6827 /** 6828 * Gets the parent of this view. Note that the parent is a 6829 * ViewParent and not necessarily a View. 6830 * 6831 * @return Parent of this view. 6832 */ 6833 public final ViewParent getParent() { 6834 return mParent; 6835 } 6836 6837 /** 6838 * Set the horizontal scrolled position of your view. This will cause a call to 6839 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6840 * invalidated. 6841 * @param value the x position to scroll to 6842 */ 6843 public void setScrollX(int value) { 6844 scrollTo(value, mScrollY); 6845 } 6846 6847 /** 6848 * Set the vertical scrolled position of your view. This will cause a call to 6849 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6850 * invalidated. 6851 * @param value the y position to scroll to 6852 */ 6853 public void setScrollY(int value) { 6854 scrollTo(mScrollX, value); 6855 } 6856 6857 /** 6858 * Return the scrolled left position of this view. This is the left edge of 6859 * the displayed part of your view. You do not need to draw any pixels 6860 * farther left, since those are outside of the frame of your view on 6861 * screen. 6862 * 6863 * @return The left edge of the displayed part of your view, in pixels. 6864 */ 6865 public final int getScrollX() { 6866 return mScrollX; 6867 } 6868 6869 /** 6870 * Return the scrolled top position of this view. This is the top edge of 6871 * the displayed part of your view. You do not need to draw any pixels above 6872 * it, since those are outside of the frame of your view on screen. 6873 * 6874 * @return The top edge of the displayed part of your view, in pixels. 6875 */ 6876 public final int getScrollY() { 6877 return mScrollY; 6878 } 6879 6880 /** 6881 * Return the width of the your view. 6882 * 6883 * @return The width of your view, in pixels. 6884 */ 6885 @ViewDebug.ExportedProperty(category = "layout") 6886 public final int getWidth() { 6887 return mRight - mLeft; 6888 } 6889 6890 /** 6891 * Return the height of your view. 6892 * 6893 * @return The height of your view, in pixels. 6894 */ 6895 @ViewDebug.ExportedProperty(category = "layout") 6896 public final int getHeight() { 6897 return mBottom - mTop; 6898 } 6899 6900 /** 6901 * Return the visible drawing bounds of your view. Fills in the output 6902 * rectangle with the values from getScrollX(), getScrollY(), 6903 * getWidth(), and getHeight(). 6904 * 6905 * @param outRect The (scrolled) drawing bounds of the view. 6906 */ 6907 public void getDrawingRect(Rect outRect) { 6908 outRect.left = mScrollX; 6909 outRect.top = mScrollY; 6910 outRect.right = mScrollX + (mRight - mLeft); 6911 outRect.bottom = mScrollY + (mBottom - mTop); 6912 } 6913 6914 /** 6915 * Like {@link #getMeasuredWidthAndState()}, but only returns the 6916 * raw width component (that is the result is masked by 6917 * {@link #MEASURED_SIZE_MASK}). 6918 * 6919 * @return The raw measured width of this view. 6920 */ 6921 public final int getMeasuredWidth() { 6922 return mMeasuredWidth & MEASURED_SIZE_MASK; 6923 } 6924 6925 /** 6926 * Return the full width measurement information for this view as computed 6927 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6928 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6929 * This should be used during measurement and layout calculations only. Use 6930 * {@link #getWidth()} to see how wide a view is after layout. 6931 * 6932 * @return The measured width of this view as a bit mask. 6933 */ 6934 public final int getMeasuredWidthAndState() { 6935 return mMeasuredWidth; 6936 } 6937 6938 /** 6939 * Like {@link #getMeasuredHeightAndState()}, but only returns the 6940 * raw width component (that is the result is masked by 6941 * {@link #MEASURED_SIZE_MASK}). 6942 * 6943 * @return The raw measured height of this view. 6944 */ 6945 public final int getMeasuredHeight() { 6946 return mMeasuredHeight & MEASURED_SIZE_MASK; 6947 } 6948 6949 /** 6950 * Return the full height measurement information for this view as computed 6951 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6952 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6953 * This should be used during measurement and layout calculations only. Use 6954 * {@link #getHeight()} to see how wide a view is after layout. 6955 * 6956 * @return The measured width of this view as a bit mask. 6957 */ 6958 public final int getMeasuredHeightAndState() { 6959 return mMeasuredHeight; 6960 } 6961 6962 /** 6963 * Return only the state bits of {@link #getMeasuredWidthAndState()} 6964 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 6965 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 6966 * and the height component is at the shifted bits 6967 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 6968 */ 6969 public final int getMeasuredState() { 6970 return (mMeasuredWidth&MEASURED_STATE_MASK) 6971 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 6972 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 6973 } 6974 6975 /** 6976 * The transform matrix of this view, which is calculated based on the current 6977 * roation, scale, and pivot properties. 6978 * 6979 * @see #getRotation() 6980 * @see #getScaleX() 6981 * @see #getScaleY() 6982 * @see #getPivotX() 6983 * @see #getPivotY() 6984 * @return The current transform matrix for the view 6985 */ 6986 public Matrix getMatrix() { 6987 if (mTransformationInfo != null) { 6988 updateMatrix(); 6989 return mTransformationInfo.mMatrix; 6990 } 6991 return Matrix.IDENTITY_MATRIX; 6992 } 6993 6994 /** 6995 * Utility function to determine if the value is far enough away from zero to be 6996 * considered non-zero. 6997 * @param value A floating point value to check for zero-ness 6998 * @return whether the passed-in value is far enough away from zero to be considered non-zero 6999 */ 7000 private static boolean nonzero(float value) { 7001 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 7002 } 7003 7004 /** 7005 * Returns true if the transform matrix is the identity matrix. 7006 * Recomputes the matrix if necessary. 7007 * 7008 * @return True if the transform matrix is the identity matrix, false otherwise. 7009 */ 7010 final boolean hasIdentityMatrix() { 7011 if (mTransformationInfo != null) { 7012 updateMatrix(); 7013 return mTransformationInfo.mMatrixIsIdentity; 7014 } 7015 return true; 7016 } 7017 7018 void ensureTransformationInfo() { 7019 if (mTransformationInfo == null) { 7020 mTransformationInfo = new TransformationInfo(); 7021 } 7022 } 7023 7024 /** 7025 * Recomputes the transform matrix if necessary. 7026 */ 7027 private void updateMatrix() { 7028 final TransformationInfo info = mTransformationInfo; 7029 if (info == null) { 7030 return; 7031 } 7032 if (info.mMatrixDirty) { 7033 // transform-related properties have changed since the last time someone 7034 // asked for the matrix; recalculate it with the current values 7035 7036 // Figure out if we need to update the pivot point 7037 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7038 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 7039 info.mPrevWidth = mRight - mLeft; 7040 info.mPrevHeight = mBottom - mTop; 7041 info.mPivotX = info.mPrevWidth / 2f; 7042 info.mPivotY = info.mPrevHeight / 2f; 7043 } 7044 } 7045 info.mMatrix.reset(); 7046 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 7047 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 7048 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 7049 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 7050 } else { 7051 if (info.mCamera == null) { 7052 info.mCamera = new Camera(); 7053 info.matrix3D = new Matrix(); 7054 } 7055 info.mCamera.save(); 7056 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 7057 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 7058 info.mCamera.getMatrix(info.matrix3D); 7059 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 7060 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 7061 info.mPivotY + info.mTranslationY); 7062 info.mMatrix.postConcat(info.matrix3D); 7063 info.mCamera.restore(); 7064 } 7065 info.mMatrixDirty = false; 7066 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 7067 info.mInverseMatrixDirty = true; 7068 } 7069 } 7070 7071 /** 7072 * Utility method to retrieve the inverse of the current mMatrix property. 7073 * We cache the matrix to avoid recalculating it when transform properties 7074 * have not changed. 7075 * 7076 * @return The inverse of the current matrix of this view. 7077 */ 7078 final Matrix getInverseMatrix() { 7079 final TransformationInfo info = mTransformationInfo; 7080 if (info != null) { 7081 updateMatrix(); 7082 if (info.mInverseMatrixDirty) { 7083 if (info.mInverseMatrix == null) { 7084 info.mInverseMatrix = new Matrix(); 7085 } 7086 info.mMatrix.invert(info.mInverseMatrix); 7087 info.mInverseMatrixDirty = false; 7088 } 7089 return info.mInverseMatrix; 7090 } 7091 return Matrix.IDENTITY_MATRIX; 7092 } 7093 7094 /** 7095 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 7096 * views are drawn) from the camera to this view. The camera's distance 7097 * affects 3D transformations, for instance rotations around the X and Y 7098 * axis. If the rotationX or rotationY properties are changed and this view is 7099 * large (more than half the size of the screen), it is recommended to always 7100 * use a camera distance that's greater than the height (X axis rotation) or 7101 * the width (Y axis rotation) of this view.</p> 7102 * 7103 * <p>The distance of the camera from the view plane can have an affect on the 7104 * perspective distortion of the view when it is rotated around the x or y axis. 7105 * For example, a large distance will result in a large viewing angle, and there 7106 * will not be much perspective distortion of the view as it rotates. A short 7107 * distance may cause much more perspective distortion upon rotation, and can 7108 * also result in some drawing artifacts if the rotated view ends up partially 7109 * behind the camera (which is why the recommendation is to use a distance at 7110 * least as far as the size of the view, if the view is to be rotated.)</p> 7111 * 7112 * <p>The distance is expressed in "depth pixels." The default distance depends 7113 * on the screen density. For instance, on a medium density display, the 7114 * default distance is 1280. On a high density display, the default distance 7115 * is 1920.</p> 7116 * 7117 * <p>If you want to specify a distance that leads to visually consistent 7118 * results across various densities, use the following formula:</p> 7119 * <pre> 7120 * float scale = context.getResources().getDisplayMetrics().density; 7121 * view.setCameraDistance(distance * scale); 7122 * </pre> 7123 * 7124 * <p>The density scale factor of a high density display is 1.5, 7125 * and 1920 = 1280 * 1.5.</p> 7126 * 7127 * @param distance The distance in "depth pixels", if negative the opposite 7128 * value is used 7129 * 7130 * @see #setRotationX(float) 7131 * @see #setRotationY(float) 7132 */ 7133 public void setCameraDistance(float distance) { 7134 invalidateParentCaches(); 7135 invalidate(false); 7136 7137 ensureTransformationInfo(); 7138 final float dpi = mResources.getDisplayMetrics().densityDpi; 7139 final TransformationInfo info = mTransformationInfo; 7140 if (info.mCamera == null) { 7141 info.mCamera = new Camera(); 7142 info.matrix3D = new Matrix(); 7143 } 7144 7145 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 7146 info.mMatrixDirty = true; 7147 7148 invalidate(false); 7149 } 7150 7151 /** 7152 * The degrees that the view is rotated around the pivot point. 7153 * 7154 * @see #setRotation(float) 7155 * @see #getPivotX() 7156 * @see #getPivotY() 7157 * 7158 * @return The degrees of rotation. 7159 */ 7160 public float getRotation() { 7161 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 7162 } 7163 7164 /** 7165 * Sets the degrees that the view is rotated around the pivot point. Increasing values 7166 * result in clockwise rotation. 7167 * 7168 * @param rotation The degrees of rotation. 7169 * 7170 * @see #getRotation() 7171 * @see #getPivotX() 7172 * @see #getPivotY() 7173 * @see #setRotationX(float) 7174 * @see #setRotationY(float) 7175 * 7176 * @attr ref android.R.styleable#View_rotation 7177 */ 7178 public void setRotation(float rotation) { 7179 ensureTransformationInfo(); 7180 final TransformationInfo info = mTransformationInfo; 7181 if (info.mRotation != rotation) { 7182 invalidateParentCaches(); 7183 // Double-invalidation is necessary to capture view's old and new areas 7184 invalidate(false); 7185 info.mRotation = rotation; 7186 info.mMatrixDirty = true; 7187 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7188 invalidate(false); 7189 } 7190 } 7191 7192 /** 7193 * The degrees that the view is rotated around the vertical axis through the pivot point. 7194 * 7195 * @see #getPivotX() 7196 * @see #getPivotY() 7197 * @see #setRotationY(float) 7198 * 7199 * @return The degrees of Y rotation. 7200 */ 7201 public float getRotationY() { 7202 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 7203 } 7204 7205 /** 7206 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 7207 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 7208 * down the y axis. 7209 * 7210 * When rotating large views, it is recommended to adjust the camera distance 7211 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 7212 * 7213 * @param rotationY The degrees of Y rotation. 7214 * 7215 * @see #getRotationY() 7216 * @see #getPivotX() 7217 * @see #getPivotY() 7218 * @see #setRotation(float) 7219 * @see #setRotationX(float) 7220 * @see #setCameraDistance(float) 7221 * 7222 * @attr ref android.R.styleable#View_rotationY 7223 */ 7224 public void setRotationY(float rotationY) { 7225 ensureTransformationInfo(); 7226 final TransformationInfo info = mTransformationInfo; 7227 if (info.mRotationY != rotationY) { 7228 invalidateParentCaches(); 7229 // Double-invalidation is necessary to capture view's old and new areas 7230 invalidate(false); 7231 info.mRotationY = rotationY; 7232 info.mMatrixDirty = true; 7233 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7234 invalidate(false); 7235 } 7236 } 7237 7238 /** 7239 * The degrees that the view is rotated around the horizontal axis through the pivot point. 7240 * 7241 * @see #getPivotX() 7242 * @see #getPivotY() 7243 * @see #setRotationX(float) 7244 * 7245 * @return The degrees of X rotation. 7246 */ 7247 public float getRotationX() { 7248 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 7249 } 7250 7251 /** 7252 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 7253 * Increasing values result in clockwise rotation from the viewpoint of looking down the 7254 * x axis. 7255 * 7256 * When rotating large views, it is recommended to adjust the camera distance 7257 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 7258 * 7259 * @param rotationX The degrees of X rotation. 7260 * 7261 * @see #getRotationX() 7262 * @see #getPivotX() 7263 * @see #getPivotY() 7264 * @see #setRotation(float) 7265 * @see #setRotationY(float) 7266 * @see #setCameraDistance(float) 7267 * 7268 * @attr ref android.R.styleable#View_rotationX 7269 */ 7270 public void setRotationX(float rotationX) { 7271 ensureTransformationInfo(); 7272 final TransformationInfo info = mTransformationInfo; 7273 if (info.mRotationX != rotationX) { 7274 invalidateParentCaches(); 7275 // Double-invalidation is necessary to capture view's old and new areas 7276 invalidate(false); 7277 info.mRotationX = rotationX; 7278 info.mMatrixDirty = true; 7279 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7280 invalidate(false); 7281 } 7282 } 7283 7284 /** 7285 * The amount that the view is scaled in x around the pivot point, as a proportion of 7286 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 7287 * 7288 * <p>By default, this is 1.0f. 7289 * 7290 * @see #getPivotX() 7291 * @see #getPivotY() 7292 * @return The scaling factor. 7293 */ 7294 public float getScaleX() { 7295 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 7296 } 7297 7298 /** 7299 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 7300 * the view's unscaled width. A value of 1 means that no scaling is applied. 7301 * 7302 * @param scaleX The scaling factor. 7303 * @see #getPivotX() 7304 * @see #getPivotY() 7305 * 7306 * @attr ref android.R.styleable#View_scaleX 7307 */ 7308 public void setScaleX(float scaleX) { 7309 ensureTransformationInfo(); 7310 final TransformationInfo info = mTransformationInfo; 7311 if (info.mScaleX != scaleX) { 7312 invalidateParentCaches(); 7313 // Double-invalidation is necessary to capture view's old and new areas 7314 invalidate(false); 7315 info.mScaleX = scaleX; 7316 info.mMatrixDirty = true; 7317 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7318 invalidate(false); 7319 } 7320 } 7321 7322 /** 7323 * The amount that the view is scaled in y around the pivot point, as a proportion of 7324 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 7325 * 7326 * <p>By default, this is 1.0f. 7327 * 7328 * @see #getPivotX() 7329 * @see #getPivotY() 7330 * @return The scaling factor. 7331 */ 7332 public float getScaleY() { 7333 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 7334 } 7335 7336 /** 7337 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 7338 * the view's unscaled width. A value of 1 means that no scaling is applied. 7339 * 7340 * @param scaleY The scaling factor. 7341 * @see #getPivotX() 7342 * @see #getPivotY() 7343 * 7344 * @attr ref android.R.styleable#View_scaleY 7345 */ 7346 public void setScaleY(float scaleY) { 7347 ensureTransformationInfo(); 7348 final TransformationInfo info = mTransformationInfo; 7349 if (info.mScaleY != scaleY) { 7350 invalidateParentCaches(); 7351 // Double-invalidation is necessary to capture view's old and new areas 7352 invalidate(false); 7353 info.mScaleY = scaleY; 7354 info.mMatrixDirty = true; 7355 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7356 invalidate(false); 7357 } 7358 } 7359 7360 /** 7361 * The x location of the point around which the view is {@link #setRotation(float) rotated} 7362 * and {@link #setScaleX(float) scaled}. 7363 * 7364 * @see #getRotation() 7365 * @see #getScaleX() 7366 * @see #getScaleY() 7367 * @see #getPivotY() 7368 * @return The x location of the pivot point. 7369 */ 7370 public float getPivotX() { 7371 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 7372 } 7373 7374 /** 7375 * Sets the x location of the point around which the view is 7376 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 7377 * By default, the pivot point is centered on the object. 7378 * Setting this property disables this behavior and causes the view to use only the 7379 * explicitly set pivotX and pivotY values. 7380 * 7381 * @param pivotX The x location of the pivot point. 7382 * @see #getRotation() 7383 * @see #getScaleX() 7384 * @see #getScaleY() 7385 * @see #getPivotY() 7386 * 7387 * @attr ref android.R.styleable#View_transformPivotX 7388 */ 7389 public void setPivotX(float pivotX) { 7390 ensureTransformationInfo(); 7391 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7392 final TransformationInfo info = mTransformationInfo; 7393 if (info.mPivotX != pivotX) { 7394 invalidateParentCaches(); 7395 // Double-invalidation is necessary to capture view's old and new areas 7396 invalidate(false); 7397 info.mPivotX = pivotX; 7398 info.mMatrixDirty = true; 7399 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7400 invalidate(false); 7401 } 7402 } 7403 7404 /** 7405 * The y location of the point around which the view is {@link #setRotation(float) rotated} 7406 * and {@link #setScaleY(float) scaled}. 7407 * 7408 * @see #getRotation() 7409 * @see #getScaleX() 7410 * @see #getScaleY() 7411 * @see #getPivotY() 7412 * @return The y location of the pivot point. 7413 */ 7414 public float getPivotY() { 7415 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 7416 } 7417 7418 /** 7419 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 7420 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 7421 * Setting this property disables this behavior and causes the view to use only the 7422 * explicitly set pivotX and pivotY values. 7423 * 7424 * @param pivotY The y location of the pivot point. 7425 * @see #getRotation() 7426 * @see #getScaleX() 7427 * @see #getScaleY() 7428 * @see #getPivotY() 7429 * 7430 * @attr ref android.R.styleable#View_transformPivotY 7431 */ 7432 public void setPivotY(float pivotY) { 7433 ensureTransformationInfo(); 7434 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7435 final TransformationInfo info = mTransformationInfo; 7436 if (info.mPivotY != pivotY) { 7437 invalidateParentCaches(); 7438 // Double-invalidation is necessary to capture view's old and new areas 7439 invalidate(false); 7440 info.mPivotY = pivotY; 7441 info.mMatrixDirty = true; 7442 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7443 invalidate(false); 7444 } 7445 } 7446 7447 /** 7448 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 7449 * completely transparent and 1 means the view is completely opaque. 7450 * 7451 * <p>By default this is 1.0f. 7452 * @return The opacity of the view. 7453 */ 7454 public float getAlpha() { 7455 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 7456 } 7457 7458 /** 7459 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 7460 * completely transparent and 1 means the view is completely opaque.</p> 7461 * 7462 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 7463 * responsible for applying the opacity itself. Otherwise, calling this method is 7464 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 7465 * setting a hardware layer.</p> 7466 * 7467 * @param alpha The opacity of the view. 7468 * 7469 * @see #setLayerType(int, android.graphics.Paint) 7470 * 7471 * @attr ref android.R.styleable#View_alpha 7472 */ 7473 public void setAlpha(float alpha) { 7474 ensureTransformationInfo(); 7475 mTransformationInfo.mAlpha = alpha; 7476 invalidateParentCaches(); 7477 if (onSetAlpha((int) (alpha * 255))) { 7478 mPrivateFlags |= ALPHA_SET; 7479 // subclass is handling alpha - don't optimize rendering cache invalidation 7480 invalidate(true); 7481 } else { 7482 mPrivateFlags &= ~ALPHA_SET; 7483 invalidate(false); 7484 } 7485 } 7486 7487 /** 7488 * Faster version of setAlpha() which performs the same steps except there are 7489 * no calls to invalidate(). The caller of this function should perform proper invalidation 7490 * on the parent and this object. The return value indicates whether the subclass handles 7491 * alpha (the return value for onSetAlpha()). 7492 * 7493 * @param alpha The new value for the alpha property 7494 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) 7495 */ 7496 boolean setAlphaNoInvalidation(float alpha) { 7497 ensureTransformationInfo(); 7498 mTransformationInfo.mAlpha = alpha; 7499 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 7500 if (subclassHandlesAlpha) { 7501 mPrivateFlags |= ALPHA_SET; 7502 } else { 7503 mPrivateFlags &= ~ALPHA_SET; 7504 } 7505 return subclassHandlesAlpha; 7506 } 7507 7508 /** 7509 * Top position of this view relative to its parent. 7510 * 7511 * @return The top of this view, in pixels. 7512 */ 7513 @ViewDebug.CapturedViewProperty 7514 public final int getTop() { 7515 return mTop; 7516 } 7517 7518 /** 7519 * Sets the top position of this view relative to its parent. This method is meant to be called 7520 * by the layout system and should not generally be called otherwise, because the property 7521 * may be changed at any time by the layout. 7522 * 7523 * @param top The top of this view, in pixels. 7524 */ 7525 public final void setTop(int top) { 7526 if (top != mTop) { 7527 updateMatrix(); 7528 final boolean matrixIsIdentity = mTransformationInfo == null 7529 || mTransformationInfo.mMatrixIsIdentity; 7530 if (matrixIsIdentity) { 7531 if (mAttachInfo != null) { 7532 int minTop; 7533 int yLoc; 7534 if (top < mTop) { 7535 minTop = top; 7536 yLoc = top - mTop; 7537 } else { 7538 minTop = mTop; 7539 yLoc = 0; 7540 } 7541 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 7542 } 7543 } else { 7544 // Double-invalidation is necessary to capture view's old and new areas 7545 invalidate(true); 7546 } 7547 7548 int width = mRight - mLeft; 7549 int oldHeight = mBottom - mTop; 7550 7551 mTop = top; 7552 7553 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7554 7555 if (!matrixIsIdentity) { 7556 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7557 // A change in dimension means an auto-centered pivot point changes, too 7558 mTransformationInfo.mMatrixDirty = true; 7559 } 7560 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7561 invalidate(true); 7562 } 7563 mBackgroundSizeChanged = true; 7564 invalidateParentIfNeeded(); 7565 } 7566 } 7567 7568 /** 7569 * Bottom position of this view relative to its parent. 7570 * 7571 * @return The bottom of this view, in pixels. 7572 */ 7573 @ViewDebug.CapturedViewProperty 7574 public final int getBottom() { 7575 return mBottom; 7576 } 7577 7578 /** 7579 * True if this view has changed since the last time being drawn. 7580 * 7581 * @return The dirty state of this view. 7582 */ 7583 public boolean isDirty() { 7584 return (mPrivateFlags & DIRTY_MASK) != 0; 7585 } 7586 7587 /** 7588 * Sets the bottom position of this view relative to its parent. This method is meant to be 7589 * called by the layout system and should not generally be called otherwise, because the 7590 * property may be changed at any time by the layout. 7591 * 7592 * @param bottom The bottom of this view, in pixels. 7593 */ 7594 public final void setBottom(int bottom) { 7595 if (bottom != mBottom) { 7596 updateMatrix(); 7597 final boolean matrixIsIdentity = mTransformationInfo == null 7598 || mTransformationInfo.mMatrixIsIdentity; 7599 if (matrixIsIdentity) { 7600 if (mAttachInfo != null) { 7601 int maxBottom; 7602 if (bottom < mBottom) { 7603 maxBottom = mBottom; 7604 } else { 7605 maxBottom = bottom; 7606 } 7607 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 7608 } 7609 } else { 7610 // Double-invalidation is necessary to capture view's old and new areas 7611 invalidate(true); 7612 } 7613 7614 int width = mRight - mLeft; 7615 int oldHeight = mBottom - mTop; 7616 7617 mBottom = bottom; 7618 7619 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7620 7621 if (!matrixIsIdentity) { 7622 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7623 // A change in dimension means an auto-centered pivot point changes, too 7624 mTransformationInfo.mMatrixDirty = true; 7625 } 7626 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7627 invalidate(true); 7628 } 7629 mBackgroundSizeChanged = true; 7630 invalidateParentIfNeeded(); 7631 } 7632 } 7633 7634 /** 7635 * Left position of this view relative to its parent. 7636 * 7637 * @return The left edge of this view, in pixels. 7638 */ 7639 @ViewDebug.CapturedViewProperty 7640 public final int getLeft() { 7641 return mLeft; 7642 } 7643 7644 /** 7645 * Sets the left position of this view relative to its parent. This method is meant to be called 7646 * by the layout system and should not generally be called otherwise, because the property 7647 * may be changed at any time by the layout. 7648 * 7649 * @param left The bottom of this view, in pixels. 7650 */ 7651 public final void setLeft(int left) { 7652 if (left != mLeft) { 7653 updateMatrix(); 7654 final boolean matrixIsIdentity = mTransformationInfo == null 7655 || mTransformationInfo.mMatrixIsIdentity; 7656 if (matrixIsIdentity) { 7657 if (mAttachInfo != null) { 7658 int minLeft; 7659 int xLoc; 7660 if (left < mLeft) { 7661 minLeft = left; 7662 xLoc = left - mLeft; 7663 } else { 7664 minLeft = mLeft; 7665 xLoc = 0; 7666 } 7667 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 7668 } 7669 } else { 7670 // Double-invalidation is necessary to capture view's old and new areas 7671 invalidate(true); 7672 } 7673 7674 int oldWidth = mRight - mLeft; 7675 int height = mBottom - mTop; 7676 7677 mLeft = left; 7678 7679 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7680 7681 if (!matrixIsIdentity) { 7682 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7683 // A change in dimension means an auto-centered pivot point changes, too 7684 mTransformationInfo.mMatrixDirty = true; 7685 } 7686 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7687 invalidate(true); 7688 } 7689 mBackgroundSizeChanged = true; 7690 invalidateParentIfNeeded(); 7691 } 7692 } 7693 7694 /** 7695 * Right position of this view relative to its parent. 7696 * 7697 * @return The right edge of this view, in pixels. 7698 */ 7699 @ViewDebug.CapturedViewProperty 7700 public final int getRight() { 7701 return mRight; 7702 } 7703 7704 /** 7705 * Sets the right position of this view relative to its parent. This method is meant to be called 7706 * by the layout system and should not generally be called otherwise, because the property 7707 * may be changed at any time by the layout. 7708 * 7709 * @param right The bottom of this view, in pixels. 7710 */ 7711 public final void setRight(int right) { 7712 if (right != mRight) { 7713 updateMatrix(); 7714 final boolean matrixIsIdentity = mTransformationInfo == null 7715 || mTransformationInfo.mMatrixIsIdentity; 7716 if (matrixIsIdentity) { 7717 if (mAttachInfo != null) { 7718 int maxRight; 7719 if (right < mRight) { 7720 maxRight = mRight; 7721 } else { 7722 maxRight = right; 7723 } 7724 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 7725 } 7726 } else { 7727 // Double-invalidation is necessary to capture view's old and new areas 7728 invalidate(true); 7729 } 7730 7731 int oldWidth = mRight - mLeft; 7732 int height = mBottom - mTop; 7733 7734 mRight = right; 7735 7736 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7737 7738 if (!matrixIsIdentity) { 7739 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7740 // A change in dimension means an auto-centered pivot point changes, too 7741 mTransformationInfo.mMatrixDirty = true; 7742 } 7743 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7744 invalidate(true); 7745 } 7746 mBackgroundSizeChanged = true; 7747 invalidateParentIfNeeded(); 7748 } 7749 } 7750 7751 /** 7752 * The visual x position of this view, in pixels. This is equivalent to the 7753 * {@link #setTranslationX(float) translationX} property plus the current 7754 * {@link #getLeft() left} property. 7755 * 7756 * @return The visual x position of this view, in pixels. 7757 */ 7758 public float getX() { 7759 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 7760 } 7761 7762 /** 7763 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 7764 * {@link #setTranslationX(float) translationX} property to be the difference between 7765 * the x value passed in and the current {@link #getLeft() left} property. 7766 * 7767 * @param x The visual x position of this view, in pixels. 7768 */ 7769 public void setX(float x) { 7770 setTranslationX(x - mLeft); 7771 } 7772 7773 /** 7774 * The visual y position of this view, in pixels. This is equivalent to the 7775 * {@link #setTranslationY(float) translationY} property plus the current 7776 * {@link #getTop() top} property. 7777 * 7778 * @return The visual y position of this view, in pixels. 7779 */ 7780 public float getY() { 7781 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 7782 } 7783 7784 /** 7785 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 7786 * {@link #setTranslationY(float) translationY} property to be the difference between 7787 * the y value passed in and the current {@link #getTop() top} property. 7788 * 7789 * @param y The visual y position of this view, in pixels. 7790 */ 7791 public void setY(float y) { 7792 setTranslationY(y - mTop); 7793 } 7794 7795 7796 /** 7797 * The horizontal location of this view relative to its {@link #getLeft() left} position. 7798 * This position is post-layout, in addition to wherever the object's 7799 * layout placed it. 7800 * 7801 * @return The horizontal position of this view relative to its left position, in pixels. 7802 */ 7803 public float getTranslationX() { 7804 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 7805 } 7806 7807 /** 7808 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 7809 * This effectively positions the object post-layout, in addition to wherever the object's 7810 * layout placed it. 7811 * 7812 * @param translationX The horizontal position of this view relative to its left position, 7813 * in pixels. 7814 * 7815 * @attr ref android.R.styleable#View_translationX 7816 */ 7817 public void setTranslationX(float translationX) { 7818 ensureTransformationInfo(); 7819 final TransformationInfo info = mTransformationInfo; 7820 if (info.mTranslationX != translationX) { 7821 invalidateParentCaches(); 7822 // Double-invalidation is necessary to capture view's old and new areas 7823 invalidate(false); 7824 info.mTranslationX = translationX; 7825 info.mMatrixDirty = true; 7826 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7827 invalidate(false); 7828 } 7829 } 7830 7831 /** 7832 * The horizontal location of this view relative to its {@link #getTop() top} position. 7833 * This position is post-layout, in addition to wherever the object's 7834 * layout placed it. 7835 * 7836 * @return The vertical position of this view relative to its top position, 7837 * in pixels. 7838 */ 7839 public float getTranslationY() { 7840 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 7841 } 7842 7843 /** 7844 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 7845 * This effectively positions the object post-layout, in addition to wherever the object's 7846 * layout placed it. 7847 * 7848 * @param translationY The vertical position of this view relative to its top position, 7849 * in pixels. 7850 * 7851 * @attr ref android.R.styleable#View_translationY 7852 */ 7853 public void setTranslationY(float translationY) { 7854 ensureTransformationInfo(); 7855 final TransformationInfo info = mTransformationInfo; 7856 if (info.mTranslationY != translationY) { 7857 invalidateParentCaches(); 7858 // Double-invalidation is necessary to capture view's old and new areas 7859 invalidate(false); 7860 info.mTranslationY = translationY; 7861 info.mMatrixDirty = true; 7862 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7863 invalidate(false); 7864 } 7865 } 7866 7867 /** 7868 * @hide 7869 */ 7870 public void setFastTranslationX(float x) { 7871 ensureTransformationInfo(); 7872 final TransformationInfo info = mTransformationInfo; 7873 info.mTranslationX = x; 7874 info.mMatrixDirty = true; 7875 } 7876 7877 /** 7878 * @hide 7879 */ 7880 public void setFastTranslationY(float y) { 7881 ensureTransformationInfo(); 7882 final TransformationInfo info = mTransformationInfo; 7883 info.mTranslationY = y; 7884 info.mMatrixDirty = true; 7885 } 7886 7887 /** 7888 * @hide 7889 */ 7890 public void setFastX(float x) { 7891 ensureTransformationInfo(); 7892 final TransformationInfo info = mTransformationInfo; 7893 info.mTranslationX = x - mLeft; 7894 info.mMatrixDirty = true; 7895 } 7896 7897 /** 7898 * @hide 7899 */ 7900 public void setFastY(float y) { 7901 ensureTransformationInfo(); 7902 final TransformationInfo info = mTransformationInfo; 7903 info.mTranslationY = y - mTop; 7904 info.mMatrixDirty = true; 7905 } 7906 7907 /** 7908 * @hide 7909 */ 7910 public void setFastScaleX(float x) { 7911 ensureTransformationInfo(); 7912 final TransformationInfo info = mTransformationInfo; 7913 info.mScaleX = x; 7914 info.mMatrixDirty = true; 7915 } 7916 7917 /** 7918 * @hide 7919 */ 7920 public void setFastScaleY(float y) { 7921 ensureTransformationInfo(); 7922 final TransformationInfo info = mTransformationInfo; 7923 info.mScaleY = y; 7924 info.mMatrixDirty = true; 7925 } 7926 7927 /** 7928 * @hide 7929 */ 7930 public void setFastAlpha(float alpha) { 7931 ensureTransformationInfo(); 7932 mTransformationInfo.mAlpha = alpha; 7933 } 7934 7935 /** 7936 * @hide 7937 */ 7938 public void setFastRotationY(float y) { 7939 ensureTransformationInfo(); 7940 final TransformationInfo info = mTransformationInfo; 7941 info.mRotationY = y; 7942 info.mMatrixDirty = true; 7943 } 7944 7945 /** 7946 * Hit rectangle in parent's coordinates 7947 * 7948 * @param outRect The hit rectangle of the view. 7949 */ 7950 public void getHitRect(Rect outRect) { 7951 updateMatrix(); 7952 final TransformationInfo info = mTransformationInfo; 7953 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 7954 outRect.set(mLeft, mTop, mRight, mBottom); 7955 } else { 7956 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 7957 tmpRect.set(-info.mPivotX, -info.mPivotY, 7958 getWidth() - info.mPivotX, getHeight() - info.mPivotY); 7959 info.mMatrix.mapRect(tmpRect); 7960 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 7961 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 7962 } 7963 } 7964 7965 /** 7966 * Determines whether the given point, in local coordinates is inside the view. 7967 */ 7968 /*package*/ final boolean pointInView(float localX, float localY) { 7969 return localX >= 0 && localX < (mRight - mLeft) 7970 && localY >= 0 && localY < (mBottom - mTop); 7971 } 7972 7973 /** 7974 * Utility method to determine whether the given point, in local coordinates, 7975 * is inside the view, where the area of the view is expanded by the slop factor. 7976 * This method is called while processing touch-move events to determine if the event 7977 * is still within the view. 7978 */ 7979 private boolean pointInView(float localX, float localY, float slop) { 7980 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 7981 localY < ((mBottom - mTop) + slop); 7982 } 7983 7984 /** 7985 * When a view has focus and the user navigates away from it, the next view is searched for 7986 * starting from the rectangle filled in by this method. 7987 * 7988 * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)}) 7989 * of the view. However, if your view maintains some idea of internal selection, 7990 * such as a cursor, or a selected row or column, you should override this method and 7991 * fill in a more specific rectangle. 7992 * 7993 * @param r The rectangle to fill in, in this view's coordinates. 7994 */ 7995 public void getFocusedRect(Rect r) { 7996 getDrawingRect(r); 7997 } 7998 7999 /** 8000 * If some part of this view is not clipped by any of its parents, then 8001 * return that area in r in global (root) coordinates. To convert r to local 8002 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x, 8003 * -globalOffset.y)) If the view is completely clipped or translated out, 8004 * return false. 8005 * 8006 * @param r If true is returned, r holds the global coordinates of the 8007 * visible portion of this view. 8008 * @param globalOffset If true is returned, globalOffset holds the dx,dy 8009 * between this view and its root. globalOffet may be null. 8010 * @return true if r is non-empty (i.e. part of the view is visible at the 8011 * root level. 8012 */ 8013 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 8014 int width = mRight - mLeft; 8015 int height = mBottom - mTop; 8016 if (width > 0 && height > 0) { 8017 r.set(0, 0, width, height); 8018 if (globalOffset != null) { 8019 globalOffset.set(-mScrollX, -mScrollY); 8020 } 8021 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 8022 } 8023 return false; 8024 } 8025 8026 public final boolean getGlobalVisibleRect(Rect r) { 8027 return getGlobalVisibleRect(r, null); 8028 } 8029 8030 public final boolean getLocalVisibleRect(Rect r) { 8031 Point offset = new Point(); 8032 if (getGlobalVisibleRect(r, offset)) { 8033 r.offset(-offset.x, -offset.y); // make r local 8034 return true; 8035 } 8036 return false; 8037 } 8038 8039 /** 8040 * Offset this view's vertical location by the specified number of pixels. 8041 * 8042 * @param offset the number of pixels to offset the view by 8043 */ 8044 public void offsetTopAndBottom(int offset) { 8045 if (offset != 0) { 8046 updateMatrix(); 8047 final boolean matrixIsIdentity = mTransformationInfo == null 8048 || mTransformationInfo.mMatrixIsIdentity; 8049 if (matrixIsIdentity) { 8050 final ViewParent p = mParent; 8051 if (p != null && mAttachInfo != null) { 8052 final Rect r = mAttachInfo.mTmpInvalRect; 8053 int minTop; 8054 int maxBottom; 8055 int yLoc; 8056 if (offset < 0) { 8057 minTop = mTop + offset; 8058 maxBottom = mBottom; 8059 yLoc = offset; 8060 } else { 8061 minTop = mTop; 8062 maxBottom = mBottom + offset; 8063 yLoc = 0; 8064 } 8065 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 8066 p.invalidateChild(this, r); 8067 } 8068 } else { 8069 invalidate(false); 8070 } 8071 8072 mTop += offset; 8073 mBottom += offset; 8074 8075 if (!matrixIsIdentity) { 8076 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8077 invalidate(false); 8078 } 8079 invalidateParentIfNeeded(); 8080 } 8081 } 8082 8083 /** 8084 * Offset this view's horizontal location by the specified amount of pixels. 8085 * 8086 * @param offset the numer of pixels to offset the view by 8087 */ 8088 public void offsetLeftAndRight(int offset) { 8089 if (offset != 0) { 8090 updateMatrix(); 8091 final boolean matrixIsIdentity = mTransformationInfo == null 8092 || mTransformationInfo.mMatrixIsIdentity; 8093 if (matrixIsIdentity) { 8094 final ViewParent p = mParent; 8095 if (p != null && mAttachInfo != null) { 8096 final Rect r = mAttachInfo.mTmpInvalRect; 8097 int minLeft; 8098 int maxRight; 8099 if (offset < 0) { 8100 minLeft = mLeft + offset; 8101 maxRight = mRight; 8102 } else { 8103 minLeft = mLeft; 8104 maxRight = mRight + offset; 8105 } 8106 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 8107 p.invalidateChild(this, r); 8108 } 8109 } else { 8110 invalidate(false); 8111 } 8112 8113 mLeft += offset; 8114 mRight += offset; 8115 8116 if (!matrixIsIdentity) { 8117 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8118 invalidate(false); 8119 } 8120 invalidateParentIfNeeded(); 8121 } 8122 } 8123 8124 /** 8125 * Get the LayoutParams associated with this view. All views should have 8126 * layout parameters. These supply parameters to the <i>parent</i> of this 8127 * view specifying how it should be arranged. There are many subclasses of 8128 * ViewGroup.LayoutParams, and these correspond to the different subclasses 8129 * of ViewGroup that are responsible for arranging their children. 8130 * 8131 * This method may return null if this View is not attached to a parent 8132 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 8133 * was not invoked successfully. When a View is attached to a parent 8134 * ViewGroup, this method must not return null. 8135 * 8136 * @return The LayoutParams associated with this view, or null if no 8137 * parameters have been set yet 8138 */ 8139 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 8140 public ViewGroup.LayoutParams getLayoutParams() { 8141 return mLayoutParams; 8142 } 8143 8144 /** 8145 * Set the layout parameters associated with this view. These supply 8146 * parameters to the <i>parent</i> of this view specifying how it should be 8147 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 8148 * correspond to the different subclasses of ViewGroup that are responsible 8149 * for arranging their children. 8150 * 8151 * @param params The layout parameters for this view, cannot be null 8152 */ 8153 public void setLayoutParams(ViewGroup.LayoutParams params) { 8154 if (params == null) { 8155 throw new NullPointerException("Layout parameters cannot be null"); 8156 } 8157 mLayoutParams = params; 8158 requestLayout(); 8159 } 8160 8161 /** 8162 * Set the scrolled position of your view. This will cause a call to 8163 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8164 * invalidated. 8165 * @param x the x position to scroll to 8166 * @param y the y position to scroll to 8167 */ 8168 public void scrollTo(int x, int y) { 8169 if (mScrollX != x || mScrollY != y) { 8170 int oldX = mScrollX; 8171 int oldY = mScrollY; 8172 mScrollX = x; 8173 mScrollY = y; 8174 invalidateParentCaches(); 8175 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 8176 if (!awakenScrollBars()) { 8177 invalidate(true); 8178 } 8179 } 8180 } 8181 8182 /** 8183 * Move the scrolled position of your view. This will cause a call to 8184 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8185 * invalidated. 8186 * @param x the amount of pixels to scroll by horizontally 8187 * @param y the amount of pixels to scroll by vertically 8188 */ 8189 public void scrollBy(int x, int y) { 8190 scrollTo(mScrollX + x, mScrollY + y); 8191 } 8192 8193 /** 8194 * <p>Trigger the scrollbars to draw. When invoked this method starts an 8195 * animation to fade the scrollbars out after a default delay. If a subclass 8196 * provides animated scrolling, the start delay should equal the duration 8197 * of the scrolling animation.</p> 8198 * 8199 * <p>The animation starts only if at least one of the scrollbars is 8200 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 8201 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8202 * this method returns true, and false otherwise. If the animation is 8203 * started, this method calls {@link #invalidate()}; in that case the 8204 * caller should not call {@link #invalidate()}.</p> 8205 * 8206 * <p>This method should be invoked every time a subclass directly updates 8207 * the scroll parameters.</p> 8208 * 8209 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 8210 * and {@link #scrollTo(int, int)}.</p> 8211 * 8212 * @return true if the animation is played, false otherwise 8213 * 8214 * @see #awakenScrollBars(int) 8215 * @see #scrollBy(int, int) 8216 * @see #scrollTo(int, int) 8217 * @see #isHorizontalScrollBarEnabled() 8218 * @see #isVerticalScrollBarEnabled() 8219 * @see #setHorizontalScrollBarEnabled(boolean) 8220 * @see #setVerticalScrollBarEnabled(boolean) 8221 */ 8222 protected boolean awakenScrollBars() { 8223 return mScrollCache != null && 8224 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 8225 } 8226 8227 /** 8228 * Trigger the scrollbars to draw. 8229 * This method differs from awakenScrollBars() only in its default duration. 8230 * initialAwakenScrollBars() will show the scroll bars for longer than 8231 * usual to give the user more of a chance to notice them. 8232 * 8233 * @return true if the animation is played, false otherwise. 8234 */ 8235 private boolean initialAwakenScrollBars() { 8236 return mScrollCache != null && 8237 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 8238 } 8239 8240 /** 8241 * <p> 8242 * Trigger the scrollbars to draw. When invoked this method starts an 8243 * animation to fade the scrollbars out after a fixed delay. If a subclass 8244 * provides animated scrolling, the start delay should equal the duration of 8245 * the scrolling animation. 8246 * </p> 8247 * 8248 * <p> 8249 * The animation starts only if at least one of the scrollbars is enabled, 8250 * as specified by {@link #isHorizontalScrollBarEnabled()} and 8251 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8252 * this method returns true, and false otherwise. If the animation is 8253 * started, this method calls {@link #invalidate()}; in that case the caller 8254 * should not call {@link #invalidate()}. 8255 * </p> 8256 * 8257 * <p> 8258 * This method should be invoked everytime a subclass directly updates the 8259 * scroll parameters. 8260 * </p> 8261 * 8262 * @param startDelay the delay, in milliseconds, after which the animation 8263 * should start; when the delay is 0, the animation starts 8264 * immediately 8265 * @return true if the animation is played, false otherwise 8266 * 8267 * @see #scrollBy(int, int) 8268 * @see #scrollTo(int, int) 8269 * @see #isHorizontalScrollBarEnabled() 8270 * @see #isVerticalScrollBarEnabled() 8271 * @see #setHorizontalScrollBarEnabled(boolean) 8272 * @see #setVerticalScrollBarEnabled(boolean) 8273 */ 8274 protected boolean awakenScrollBars(int startDelay) { 8275 return awakenScrollBars(startDelay, true); 8276 } 8277 8278 /** 8279 * <p> 8280 * Trigger the scrollbars to draw. When invoked this method starts an 8281 * animation to fade the scrollbars out after a fixed delay. If a subclass 8282 * provides animated scrolling, the start delay should equal the duration of 8283 * the scrolling animation. 8284 * </p> 8285 * 8286 * <p> 8287 * The animation starts only if at least one of the scrollbars is enabled, 8288 * as specified by {@link #isHorizontalScrollBarEnabled()} and 8289 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8290 * this method returns true, and false otherwise. If the animation is 8291 * started, this method calls {@link #invalidate()} if the invalidate parameter 8292 * is set to true; in that case the caller 8293 * should not call {@link #invalidate()}. 8294 * </p> 8295 * 8296 * <p> 8297 * This method should be invoked everytime a subclass directly updates the 8298 * scroll parameters. 8299 * </p> 8300 * 8301 * @param startDelay the delay, in milliseconds, after which the animation 8302 * should start; when the delay is 0, the animation starts 8303 * immediately 8304 * 8305 * @param invalidate Wheter this method should call invalidate 8306 * 8307 * @return true if the animation is played, false otherwise 8308 * 8309 * @see #scrollBy(int, int) 8310 * @see #scrollTo(int, int) 8311 * @see #isHorizontalScrollBarEnabled() 8312 * @see #isVerticalScrollBarEnabled() 8313 * @see #setHorizontalScrollBarEnabled(boolean) 8314 * @see #setVerticalScrollBarEnabled(boolean) 8315 */ 8316 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 8317 final ScrollabilityCache scrollCache = mScrollCache; 8318 8319 if (scrollCache == null || !scrollCache.fadeScrollBars) { 8320 return false; 8321 } 8322 8323 if (scrollCache.scrollBar == null) { 8324 scrollCache.scrollBar = new ScrollBarDrawable(); 8325 } 8326 8327 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 8328 8329 if (invalidate) { 8330 // Invalidate to show the scrollbars 8331 invalidate(true); 8332 } 8333 8334 if (scrollCache.state == ScrollabilityCache.OFF) { 8335 // FIXME: this is copied from WindowManagerService. 8336 // We should get this value from the system when it 8337 // is possible to do so. 8338 final int KEY_REPEAT_FIRST_DELAY = 750; 8339 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 8340 } 8341 8342 // Tell mScrollCache when we should start fading. This may 8343 // extend the fade start time if one was already scheduled 8344 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 8345 scrollCache.fadeStartTime = fadeStartTime; 8346 scrollCache.state = ScrollabilityCache.ON; 8347 8348 // Schedule our fader to run, unscheduling any old ones first 8349 if (mAttachInfo != null) { 8350 mAttachInfo.mHandler.removeCallbacks(scrollCache); 8351 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 8352 } 8353 8354 return true; 8355 } 8356 8357 return false; 8358 } 8359 8360 /** 8361 * Do not invalidate views which are not visible and which are not running an animation. They 8362 * will not get drawn and they should not set dirty flags as if they will be drawn 8363 */ 8364 private boolean skipInvalidate() { 8365 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 8366 (!(mParent instanceof ViewGroup) || 8367 !((ViewGroup) mParent).isViewTransitioning(this)); 8368 } 8369 /** 8370 * Mark the area defined by dirty as needing to be drawn. If the view is 8371 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 8372 * in the future. This must be called from a UI thread. To call from a non-UI 8373 * thread, call {@link #postInvalidate()}. 8374 * 8375 * WARNING: This method is destructive to dirty. 8376 * @param dirty the rectangle representing the bounds of the dirty region 8377 */ 8378 public void invalidate(Rect dirty) { 8379 if (ViewDebug.TRACE_HIERARCHY) { 8380 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8381 } 8382 8383 if (skipInvalidate()) { 8384 return; 8385 } 8386 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8387 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8388 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8389 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8390 mPrivateFlags |= INVALIDATED; 8391 mPrivateFlags |= DIRTY; 8392 final ViewParent p = mParent; 8393 final AttachInfo ai = mAttachInfo; 8394 //noinspection PointlessBooleanExpression,ConstantConditions 8395 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8396 if (p != null && ai != null && ai.mHardwareAccelerated) { 8397 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8398 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8399 p.invalidateChild(this, null); 8400 return; 8401 } 8402 } 8403 if (p != null && ai != null) { 8404 final int scrollX = mScrollX; 8405 final int scrollY = mScrollY; 8406 final Rect r = ai.mTmpInvalRect; 8407 r.set(dirty.left - scrollX, dirty.top - scrollY, 8408 dirty.right - scrollX, dirty.bottom - scrollY); 8409 mParent.invalidateChild(this, r); 8410 } 8411 } 8412 } 8413 8414 /** 8415 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 8416 * The coordinates of the dirty rect are relative to the view. 8417 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 8418 * will be called at some point in the future. This must be called from 8419 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 8420 * @param l the left position of the dirty region 8421 * @param t the top position of the dirty region 8422 * @param r the right position of the dirty region 8423 * @param b the bottom position of the dirty region 8424 */ 8425 public void invalidate(int l, int t, int r, int b) { 8426 if (ViewDebug.TRACE_HIERARCHY) { 8427 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8428 } 8429 8430 if (skipInvalidate()) { 8431 return; 8432 } 8433 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8434 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8435 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8436 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8437 mPrivateFlags |= INVALIDATED; 8438 mPrivateFlags |= DIRTY; 8439 final ViewParent p = mParent; 8440 final AttachInfo ai = mAttachInfo; 8441 //noinspection PointlessBooleanExpression,ConstantConditions 8442 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8443 if (p != null && ai != null && ai.mHardwareAccelerated) { 8444 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8445 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8446 p.invalidateChild(this, null); 8447 return; 8448 } 8449 } 8450 if (p != null && ai != null && l < r && t < b) { 8451 final int scrollX = mScrollX; 8452 final int scrollY = mScrollY; 8453 final Rect tmpr = ai.mTmpInvalRect; 8454 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 8455 p.invalidateChild(this, tmpr); 8456 } 8457 } 8458 } 8459 8460 /** 8461 * Invalidate the whole view. If the view is visible, 8462 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 8463 * the future. This must be called from a UI thread. To call from a non-UI thread, 8464 * call {@link #postInvalidate()}. 8465 */ 8466 public void invalidate() { 8467 invalidate(true); 8468 } 8469 8470 /** 8471 * This is where the invalidate() work actually happens. A full invalidate() 8472 * causes the drawing cache to be invalidated, but this function can be called with 8473 * invalidateCache set to false to skip that invalidation step for cases that do not 8474 * need it (for example, a component that remains at the same dimensions with the same 8475 * content). 8476 * 8477 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 8478 * well. This is usually true for a full invalidate, but may be set to false if the 8479 * View's contents or dimensions have not changed. 8480 */ 8481 void invalidate(boolean invalidateCache) { 8482 if (ViewDebug.TRACE_HIERARCHY) { 8483 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8484 } 8485 8486 if (skipInvalidate()) { 8487 return; 8488 } 8489 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8490 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) || 8491 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) { 8492 mLastIsOpaque = isOpaque(); 8493 mPrivateFlags &= ~DRAWN; 8494 mPrivateFlags |= DIRTY; 8495 if (invalidateCache) { 8496 mPrivateFlags |= INVALIDATED; 8497 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8498 } 8499 final AttachInfo ai = mAttachInfo; 8500 final ViewParent p = mParent; 8501 //noinspection PointlessBooleanExpression,ConstantConditions 8502 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8503 if (p != null && ai != null && ai.mHardwareAccelerated) { 8504 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8505 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8506 p.invalidateChild(this, null); 8507 return; 8508 } 8509 } 8510 8511 if (p != null && ai != null) { 8512 final Rect r = ai.mTmpInvalRect; 8513 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8514 // Don't call invalidate -- we don't want to internally scroll 8515 // our own bounds 8516 p.invalidateChild(this, r); 8517 } 8518 } 8519 } 8520 8521 /** 8522 * @hide 8523 */ 8524 public void fastInvalidate() { 8525 if (skipInvalidate()) { 8526 return; 8527 } 8528 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8529 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8530 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8531 if (mParent instanceof View) { 8532 ((View) mParent).mPrivateFlags |= INVALIDATED; 8533 } 8534 mPrivateFlags &= ~DRAWN; 8535 mPrivateFlags |= DIRTY; 8536 mPrivateFlags |= INVALIDATED; 8537 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8538 if (mParent != null && mAttachInfo != null) { 8539 if (mAttachInfo.mHardwareAccelerated) { 8540 mParent.invalidateChild(this, null); 8541 } else { 8542 final Rect r = mAttachInfo.mTmpInvalRect; 8543 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8544 // Don't call invalidate -- we don't want to internally scroll 8545 // our own bounds 8546 mParent.invalidateChild(this, r); 8547 } 8548 } 8549 } 8550 } 8551 8552 /** 8553 * Used to indicate that the parent of this view should clear its caches. This functionality 8554 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8555 * which is necessary when various parent-managed properties of the view change, such as 8556 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 8557 * clears the parent caches and does not causes an invalidate event. 8558 * 8559 * @hide 8560 */ 8561 protected void invalidateParentCaches() { 8562 if (mParent instanceof View) { 8563 ((View) mParent).mPrivateFlags |= INVALIDATED; 8564 } 8565 } 8566 8567 /** 8568 * Used to indicate that the parent of this view should be invalidated. This functionality 8569 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8570 * which is necessary when various parent-managed properties of the view change, such as 8571 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 8572 * an invalidation event to the parent. 8573 * 8574 * @hide 8575 */ 8576 protected void invalidateParentIfNeeded() { 8577 if (isHardwareAccelerated() && mParent instanceof View) { 8578 ((View) mParent).invalidate(true); 8579 } 8580 } 8581 8582 /** 8583 * Indicates whether this View is opaque. An opaque View guarantees that it will 8584 * draw all the pixels overlapping its bounds using a fully opaque color. 8585 * 8586 * Subclasses of View should override this method whenever possible to indicate 8587 * whether an instance is opaque. Opaque Views are treated in a special way by 8588 * the View hierarchy, possibly allowing it to perform optimizations during 8589 * invalidate/draw passes. 8590 * 8591 * @return True if this View is guaranteed to be fully opaque, false otherwise. 8592 */ 8593 @ViewDebug.ExportedProperty(category = "drawing") 8594 public boolean isOpaque() { 8595 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK && 8596 ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1) 8597 >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD); 8598 } 8599 8600 /** 8601 * @hide 8602 */ 8603 protected void computeOpaqueFlags() { 8604 // Opaque if: 8605 // - Has a background 8606 // - Background is opaque 8607 // - Doesn't have scrollbars or scrollbars are inside overlay 8608 8609 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) { 8610 mPrivateFlags |= OPAQUE_BACKGROUND; 8611 } else { 8612 mPrivateFlags &= ~OPAQUE_BACKGROUND; 8613 } 8614 8615 final int flags = mViewFlags; 8616 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 8617 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 8618 mPrivateFlags |= OPAQUE_SCROLLBARS; 8619 } else { 8620 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 8621 } 8622 } 8623 8624 /** 8625 * @hide 8626 */ 8627 protected boolean hasOpaqueScrollbars() { 8628 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 8629 } 8630 8631 /** 8632 * @return A handler associated with the thread running the View. This 8633 * handler can be used to pump events in the UI events queue. 8634 */ 8635 public Handler getHandler() { 8636 if (mAttachInfo != null) { 8637 return mAttachInfo.mHandler; 8638 } 8639 return null; 8640 } 8641 8642 /** 8643 * <p>Causes the Runnable to be added to the message queue. 8644 * The runnable will be run on the user interface thread.</p> 8645 * 8646 * <p>This method can be invoked from outside of the UI thread 8647 * only when this View is attached to a window.</p> 8648 * 8649 * @param action The Runnable that will be executed. 8650 * 8651 * @return Returns true if the Runnable was successfully placed in to the 8652 * message queue. Returns false on failure, usually because the 8653 * looper processing the message queue is exiting. 8654 */ 8655 public boolean post(Runnable action) { 8656 Handler handler; 8657 AttachInfo attachInfo = mAttachInfo; 8658 if (attachInfo != null) { 8659 handler = attachInfo.mHandler; 8660 } else { 8661 // Assume that post will succeed later 8662 ViewRootImpl.getRunQueue().post(action); 8663 return true; 8664 } 8665 8666 return handler.post(action); 8667 } 8668 8669 /** 8670 * <p>Causes the Runnable to be added to the message queue, to be run 8671 * after the specified amount of time elapses. 8672 * The runnable will be run on the user interface thread.</p> 8673 * 8674 * <p>This method can be invoked from outside of the UI thread 8675 * only when this View is attached to a window.</p> 8676 * 8677 * @param action The Runnable that will be executed. 8678 * @param delayMillis The delay (in milliseconds) until the Runnable 8679 * will be executed. 8680 * 8681 * @return true if the Runnable was successfully placed in to the 8682 * message queue. Returns false on failure, usually because the 8683 * looper processing the message queue is exiting. Note that a 8684 * result of true does not mean the Runnable will be processed -- 8685 * if the looper is quit before the delivery time of the message 8686 * occurs then the message will be dropped. 8687 */ 8688 public boolean postDelayed(Runnable action, long delayMillis) { 8689 Handler handler; 8690 AttachInfo attachInfo = mAttachInfo; 8691 if (attachInfo != null) { 8692 handler = attachInfo.mHandler; 8693 } else { 8694 // Assume that post will succeed later 8695 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 8696 return true; 8697 } 8698 8699 return handler.postDelayed(action, delayMillis); 8700 } 8701 8702 /** 8703 * <p>Removes the specified Runnable from the message queue.</p> 8704 * 8705 * <p>This method can be invoked from outside of the UI thread 8706 * only when this View is attached to a window.</p> 8707 * 8708 * @param action The Runnable to remove from the message handling queue 8709 * 8710 * @return true if this view could ask the Handler to remove the Runnable, 8711 * false otherwise. When the returned value is true, the Runnable 8712 * may or may not have been actually removed from the message queue 8713 * (for instance, if the Runnable was not in the queue already.) 8714 */ 8715 public boolean removeCallbacks(Runnable action) { 8716 Handler handler; 8717 AttachInfo attachInfo = mAttachInfo; 8718 if (attachInfo != null) { 8719 handler = attachInfo.mHandler; 8720 } else { 8721 // Assume that post will succeed later 8722 ViewRootImpl.getRunQueue().removeCallbacks(action); 8723 return true; 8724 } 8725 8726 handler.removeCallbacks(action); 8727 return true; 8728 } 8729 8730 /** 8731 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 8732 * Use this to invalidate the View from a non-UI thread.</p> 8733 * 8734 * <p>This method can be invoked from outside of the UI thread 8735 * only when this View is attached to a window.</p> 8736 * 8737 * @see #invalidate() 8738 */ 8739 public void postInvalidate() { 8740 postInvalidateDelayed(0); 8741 } 8742 8743 /** 8744 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 8745 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 8746 * 8747 * <p>This method can be invoked from outside of the UI thread 8748 * only when this View is attached to a window.</p> 8749 * 8750 * @param left The left coordinate of the rectangle to invalidate. 8751 * @param top The top coordinate of the rectangle to invalidate. 8752 * @param right The right coordinate of the rectangle to invalidate. 8753 * @param bottom The bottom coordinate of the rectangle to invalidate. 8754 * 8755 * @see #invalidate(int, int, int, int) 8756 * @see #invalidate(Rect) 8757 */ 8758 public void postInvalidate(int left, int top, int right, int bottom) { 8759 postInvalidateDelayed(0, left, top, right, bottom); 8760 } 8761 8762 /** 8763 * <p>Cause an invalidate to happen on a subsequent cycle through the event 8764 * loop. Waits for the specified amount of time.</p> 8765 * 8766 * <p>This method can be invoked from outside of the UI thread 8767 * only when this View is attached to a window.</p> 8768 * 8769 * @param delayMilliseconds the duration in milliseconds to delay the 8770 * invalidation by 8771 */ 8772 public void postInvalidateDelayed(long delayMilliseconds) { 8773 // We try only with the AttachInfo because there's no point in invalidating 8774 // if we are not attached to our window 8775 AttachInfo attachInfo = mAttachInfo; 8776 if (attachInfo != null) { 8777 Message msg = Message.obtain(); 8778 msg.what = AttachInfo.INVALIDATE_MSG; 8779 msg.obj = this; 8780 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8781 } 8782 } 8783 8784 /** 8785 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 8786 * through the event loop. Waits for the specified amount of time.</p> 8787 * 8788 * <p>This method can be invoked from outside of the UI thread 8789 * only when this View is attached to a window.</p> 8790 * 8791 * @param delayMilliseconds the duration in milliseconds to delay the 8792 * invalidation by 8793 * @param left The left coordinate of the rectangle to invalidate. 8794 * @param top The top coordinate of the rectangle to invalidate. 8795 * @param right The right coordinate of the rectangle to invalidate. 8796 * @param bottom The bottom coordinate of the rectangle to invalidate. 8797 */ 8798 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 8799 int right, int bottom) { 8800 8801 // We try only with the AttachInfo because there's no point in invalidating 8802 // if we are not attached to our window 8803 AttachInfo attachInfo = mAttachInfo; 8804 if (attachInfo != null) { 8805 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 8806 info.target = this; 8807 info.left = left; 8808 info.top = top; 8809 info.right = right; 8810 info.bottom = bottom; 8811 8812 final Message msg = Message.obtain(); 8813 msg.what = AttachInfo.INVALIDATE_RECT_MSG; 8814 msg.obj = info; 8815 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8816 } 8817 } 8818 8819 /** 8820 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 8821 * This event is sent at most once every 8822 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 8823 */ 8824 private void postSendViewScrolledAccessibilityEventCallback() { 8825 if (mSendViewScrolledAccessibilityEvent == null) { 8826 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 8827 } 8828 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 8829 mSendViewScrolledAccessibilityEvent.mIsPending = true; 8830 postDelayed(mSendViewScrolledAccessibilityEvent, 8831 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 8832 } 8833 } 8834 8835 /** 8836 * Called by a parent to request that a child update its values for mScrollX 8837 * and mScrollY if necessary. This will typically be done if the child is 8838 * animating a scroll using a {@link android.widget.Scroller Scroller} 8839 * object. 8840 */ 8841 public void computeScroll() { 8842 } 8843 8844 /** 8845 * <p>Indicate whether the horizontal edges are faded when the view is 8846 * scrolled horizontally.</p> 8847 * 8848 * @return true if the horizontal edges should are faded on scroll, false 8849 * otherwise 8850 * 8851 * @see #setHorizontalFadingEdgeEnabled(boolean) 8852 * @attr ref android.R.styleable#View_requiresFadingEdge 8853 */ 8854 public boolean isHorizontalFadingEdgeEnabled() { 8855 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 8856 } 8857 8858 /** 8859 * <p>Define whether the horizontal edges should be faded when this view 8860 * is scrolled horizontally.</p> 8861 * 8862 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 8863 * be faded when the view is scrolled 8864 * horizontally 8865 * 8866 * @see #isHorizontalFadingEdgeEnabled() 8867 * @attr ref android.R.styleable#View_requiresFadingEdge 8868 */ 8869 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 8870 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 8871 if (horizontalFadingEdgeEnabled) { 8872 initScrollCache(); 8873 } 8874 8875 mViewFlags ^= FADING_EDGE_HORIZONTAL; 8876 } 8877 } 8878 8879 /** 8880 * <p>Indicate whether the vertical edges are faded when the view is 8881 * scrolled horizontally.</p> 8882 * 8883 * @return true if the vertical edges should are faded on scroll, false 8884 * otherwise 8885 * 8886 * @see #setVerticalFadingEdgeEnabled(boolean) 8887 * @attr ref android.R.styleable#View_requiresFadingEdge 8888 */ 8889 public boolean isVerticalFadingEdgeEnabled() { 8890 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 8891 } 8892 8893 /** 8894 * <p>Define whether the vertical edges should be faded when this view 8895 * is scrolled vertically.</p> 8896 * 8897 * @param verticalFadingEdgeEnabled true if the vertical edges should 8898 * be faded when the view is scrolled 8899 * vertically 8900 * 8901 * @see #isVerticalFadingEdgeEnabled() 8902 * @attr ref android.R.styleable#View_requiresFadingEdge 8903 */ 8904 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 8905 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 8906 if (verticalFadingEdgeEnabled) { 8907 initScrollCache(); 8908 } 8909 8910 mViewFlags ^= FADING_EDGE_VERTICAL; 8911 } 8912 } 8913 8914 /** 8915 * Returns the strength, or intensity, of the top faded edge. The strength is 8916 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8917 * returns 0.0 or 1.0 but no value in between. 8918 * 8919 * Subclasses should override this method to provide a smoother fade transition 8920 * when scrolling occurs. 8921 * 8922 * @return the intensity of the top fade as a float between 0.0f and 1.0f 8923 */ 8924 protected float getTopFadingEdgeStrength() { 8925 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 8926 } 8927 8928 /** 8929 * Returns the strength, or intensity, of the bottom faded edge. The strength is 8930 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8931 * returns 0.0 or 1.0 but no value in between. 8932 * 8933 * Subclasses should override this method to provide a smoother fade transition 8934 * when scrolling occurs. 8935 * 8936 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 8937 */ 8938 protected float getBottomFadingEdgeStrength() { 8939 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 8940 computeVerticalScrollRange() ? 1.0f : 0.0f; 8941 } 8942 8943 /** 8944 * Returns the strength, or intensity, of the left faded edge. The strength is 8945 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8946 * returns 0.0 or 1.0 but no value in between. 8947 * 8948 * Subclasses should override this method to provide a smoother fade transition 8949 * when scrolling occurs. 8950 * 8951 * @return the intensity of the left fade as a float between 0.0f and 1.0f 8952 */ 8953 protected float getLeftFadingEdgeStrength() { 8954 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 8955 } 8956 8957 /** 8958 * Returns the strength, or intensity, of the right faded edge. The strength is 8959 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8960 * returns 0.0 or 1.0 but no value in between. 8961 * 8962 * Subclasses should override this method to provide a smoother fade transition 8963 * when scrolling occurs. 8964 * 8965 * @return the intensity of the right fade as a float between 0.0f and 1.0f 8966 */ 8967 protected float getRightFadingEdgeStrength() { 8968 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 8969 computeHorizontalScrollRange() ? 1.0f : 0.0f; 8970 } 8971 8972 /** 8973 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 8974 * scrollbar is not drawn by default.</p> 8975 * 8976 * @return true if the horizontal scrollbar should be painted, false 8977 * otherwise 8978 * 8979 * @see #setHorizontalScrollBarEnabled(boolean) 8980 */ 8981 public boolean isHorizontalScrollBarEnabled() { 8982 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 8983 } 8984 8985 /** 8986 * <p>Define whether the horizontal scrollbar should be drawn or not. The 8987 * scrollbar is not drawn by default.</p> 8988 * 8989 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 8990 * be painted 8991 * 8992 * @see #isHorizontalScrollBarEnabled() 8993 */ 8994 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 8995 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 8996 mViewFlags ^= SCROLLBARS_HORIZONTAL; 8997 computeOpaqueFlags(); 8998 resolvePadding(); 8999 } 9000 } 9001 9002 /** 9003 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 9004 * scrollbar is not drawn by default.</p> 9005 * 9006 * @return true if the vertical scrollbar should be painted, false 9007 * otherwise 9008 * 9009 * @see #setVerticalScrollBarEnabled(boolean) 9010 */ 9011 public boolean isVerticalScrollBarEnabled() { 9012 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 9013 } 9014 9015 /** 9016 * <p>Define whether the vertical scrollbar should be drawn or not. The 9017 * scrollbar is not drawn by default.</p> 9018 * 9019 * @param verticalScrollBarEnabled true if the vertical scrollbar should 9020 * be painted 9021 * 9022 * @see #isVerticalScrollBarEnabled() 9023 */ 9024 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 9025 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 9026 mViewFlags ^= SCROLLBARS_VERTICAL; 9027 computeOpaqueFlags(); 9028 resolvePadding(); 9029 } 9030 } 9031 9032 /** 9033 * @hide 9034 */ 9035 protected void recomputePadding() { 9036 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 9037 } 9038 9039 /** 9040 * Define whether scrollbars will fade when the view is not scrolling. 9041 * 9042 * @param fadeScrollbars wheter to enable fading 9043 * 9044 */ 9045 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 9046 initScrollCache(); 9047 final ScrollabilityCache scrollabilityCache = mScrollCache; 9048 scrollabilityCache.fadeScrollBars = fadeScrollbars; 9049 if (fadeScrollbars) { 9050 scrollabilityCache.state = ScrollabilityCache.OFF; 9051 } else { 9052 scrollabilityCache.state = ScrollabilityCache.ON; 9053 } 9054 } 9055 9056 /** 9057 * 9058 * Returns true if scrollbars will fade when this view is not scrolling 9059 * 9060 * @return true if scrollbar fading is enabled 9061 */ 9062 public boolean isScrollbarFadingEnabled() { 9063 return mScrollCache != null && mScrollCache.fadeScrollBars; 9064 } 9065 9066 /** 9067 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 9068 * inset. When inset, they add to the padding of the view. And the scrollbars 9069 * can be drawn inside the padding area or on the edge of the view. For example, 9070 * if a view has a background drawable and you want to draw the scrollbars 9071 * inside the padding specified by the drawable, you can use 9072 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 9073 * appear at the edge of the view, ignoring the padding, then you can use 9074 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 9075 * @param style the style of the scrollbars. Should be one of 9076 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 9077 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 9078 * @see #SCROLLBARS_INSIDE_OVERLAY 9079 * @see #SCROLLBARS_INSIDE_INSET 9080 * @see #SCROLLBARS_OUTSIDE_OVERLAY 9081 * @see #SCROLLBARS_OUTSIDE_INSET 9082 */ 9083 public void setScrollBarStyle(int style) { 9084 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 9085 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 9086 computeOpaqueFlags(); 9087 resolvePadding(); 9088 } 9089 } 9090 9091 /** 9092 * <p>Returns the current scrollbar style.</p> 9093 * @return the current scrollbar style 9094 * @see #SCROLLBARS_INSIDE_OVERLAY 9095 * @see #SCROLLBARS_INSIDE_INSET 9096 * @see #SCROLLBARS_OUTSIDE_OVERLAY 9097 * @see #SCROLLBARS_OUTSIDE_INSET 9098 */ 9099 @ViewDebug.ExportedProperty(mapping = { 9100 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 9101 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 9102 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 9103 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 9104 }) 9105 public int getScrollBarStyle() { 9106 return mViewFlags & SCROLLBARS_STYLE_MASK; 9107 } 9108 9109 /** 9110 * <p>Compute the horizontal range that the horizontal scrollbar 9111 * represents.</p> 9112 * 9113 * <p>The range is expressed in arbitrary units that must be the same as the 9114 * units used by {@link #computeHorizontalScrollExtent()} and 9115 * {@link #computeHorizontalScrollOffset()}.</p> 9116 * 9117 * <p>The default range is the drawing width of this view.</p> 9118 * 9119 * @return the total horizontal range represented by the horizontal 9120 * scrollbar 9121 * 9122 * @see #computeHorizontalScrollExtent() 9123 * @see #computeHorizontalScrollOffset() 9124 * @see android.widget.ScrollBarDrawable 9125 */ 9126 protected int computeHorizontalScrollRange() { 9127 return getWidth(); 9128 } 9129 9130 /** 9131 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 9132 * within the horizontal range. This value is used to compute the position 9133 * of the thumb within the scrollbar's track.</p> 9134 * 9135 * <p>The range is expressed in arbitrary units that must be the same as the 9136 * units used by {@link #computeHorizontalScrollRange()} and 9137 * {@link #computeHorizontalScrollExtent()}.</p> 9138 * 9139 * <p>The default offset is the scroll offset of this view.</p> 9140 * 9141 * @return the horizontal offset of the scrollbar's thumb 9142 * 9143 * @see #computeHorizontalScrollRange() 9144 * @see #computeHorizontalScrollExtent() 9145 * @see android.widget.ScrollBarDrawable 9146 */ 9147 protected int computeHorizontalScrollOffset() { 9148 return mScrollX; 9149 } 9150 9151 /** 9152 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 9153 * within the horizontal range. This value is used to compute the length 9154 * of the thumb within the scrollbar's track.</p> 9155 * 9156 * <p>The range is expressed in arbitrary units that must be the same as the 9157 * units used by {@link #computeHorizontalScrollRange()} and 9158 * {@link #computeHorizontalScrollOffset()}.</p> 9159 * 9160 * <p>The default extent is the drawing width of this view.</p> 9161 * 9162 * @return the horizontal extent of the scrollbar's thumb 9163 * 9164 * @see #computeHorizontalScrollRange() 9165 * @see #computeHorizontalScrollOffset() 9166 * @see android.widget.ScrollBarDrawable 9167 */ 9168 protected int computeHorizontalScrollExtent() { 9169 return getWidth(); 9170 } 9171 9172 /** 9173 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 9174 * 9175 * <p>The range is expressed in arbitrary units that must be the same as the 9176 * units used by {@link #computeVerticalScrollExtent()} and 9177 * {@link #computeVerticalScrollOffset()}.</p> 9178 * 9179 * @return the total vertical range represented by the vertical scrollbar 9180 * 9181 * <p>The default range is the drawing height of this view.</p> 9182 * 9183 * @see #computeVerticalScrollExtent() 9184 * @see #computeVerticalScrollOffset() 9185 * @see android.widget.ScrollBarDrawable 9186 */ 9187 protected int computeVerticalScrollRange() { 9188 return getHeight(); 9189 } 9190 9191 /** 9192 * <p>Compute the vertical offset of the vertical scrollbar's thumb 9193 * within the horizontal range. This value is used to compute the position 9194 * of the thumb within the scrollbar's track.</p> 9195 * 9196 * <p>The range is expressed in arbitrary units that must be the same as the 9197 * units used by {@link #computeVerticalScrollRange()} and 9198 * {@link #computeVerticalScrollExtent()}.</p> 9199 * 9200 * <p>The default offset is the scroll offset of this view.</p> 9201 * 9202 * @return the vertical offset of the scrollbar's thumb 9203 * 9204 * @see #computeVerticalScrollRange() 9205 * @see #computeVerticalScrollExtent() 9206 * @see android.widget.ScrollBarDrawable 9207 */ 9208 protected int computeVerticalScrollOffset() { 9209 return mScrollY; 9210 } 9211 9212 /** 9213 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 9214 * within the vertical range. This value is used to compute the length 9215 * of the thumb within the scrollbar's track.</p> 9216 * 9217 * <p>The range is expressed in arbitrary units that must be the same as the 9218 * units used by {@link #computeVerticalScrollRange()} and 9219 * {@link #computeVerticalScrollOffset()}.</p> 9220 * 9221 * <p>The default extent is the drawing height of this view.</p> 9222 * 9223 * @return the vertical extent of the scrollbar's thumb 9224 * 9225 * @see #computeVerticalScrollRange() 9226 * @see #computeVerticalScrollOffset() 9227 * @see android.widget.ScrollBarDrawable 9228 */ 9229 protected int computeVerticalScrollExtent() { 9230 return getHeight(); 9231 } 9232 9233 /** 9234 * Check if this view can be scrolled horizontally in a certain direction. 9235 * 9236 * @param direction Negative to check scrolling left, positive to check scrolling right. 9237 * @return true if this view can be scrolled in the specified direction, false otherwise. 9238 */ 9239 public boolean canScrollHorizontally(int direction) { 9240 final int offset = computeHorizontalScrollOffset(); 9241 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 9242 if (range == 0) return false; 9243 if (direction < 0) { 9244 return offset > 0; 9245 } else { 9246 return offset < range - 1; 9247 } 9248 } 9249 9250 /** 9251 * Check if this view can be scrolled vertically in a certain direction. 9252 * 9253 * @param direction Negative to check scrolling up, positive to check scrolling down. 9254 * @return true if this view can be scrolled in the specified direction, false otherwise. 9255 */ 9256 public boolean canScrollVertically(int direction) { 9257 final int offset = computeVerticalScrollOffset(); 9258 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 9259 if (range == 0) return false; 9260 if (direction < 0) { 9261 return offset > 0; 9262 } else { 9263 return offset < range - 1; 9264 } 9265 } 9266 9267 /** 9268 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 9269 * scrollbars are painted only if they have been awakened first.</p> 9270 * 9271 * @param canvas the canvas on which to draw the scrollbars 9272 * 9273 * @see #awakenScrollBars(int) 9274 */ 9275 protected final void onDrawScrollBars(Canvas canvas) { 9276 // scrollbars are drawn only when the animation is running 9277 final ScrollabilityCache cache = mScrollCache; 9278 if (cache != null) { 9279 9280 int state = cache.state; 9281 9282 if (state == ScrollabilityCache.OFF) { 9283 return; 9284 } 9285 9286 boolean invalidate = false; 9287 9288 if (state == ScrollabilityCache.FADING) { 9289 // We're fading -- get our fade interpolation 9290 if (cache.interpolatorValues == null) { 9291 cache.interpolatorValues = new float[1]; 9292 } 9293 9294 float[] values = cache.interpolatorValues; 9295 9296 // Stops the animation if we're done 9297 if (cache.scrollBarInterpolator.timeToValues(values) == 9298 Interpolator.Result.FREEZE_END) { 9299 cache.state = ScrollabilityCache.OFF; 9300 } else { 9301 cache.scrollBar.setAlpha(Math.round(values[0])); 9302 } 9303 9304 // This will make the scroll bars inval themselves after 9305 // drawing. We only want this when we're fading so that 9306 // we prevent excessive redraws 9307 invalidate = true; 9308 } else { 9309 // We're just on -- but we may have been fading before so 9310 // reset alpha 9311 cache.scrollBar.setAlpha(255); 9312 } 9313 9314 9315 final int viewFlags = mViewFlags; 9316 9317 final boolean drawHorizontalScrollBar = 9318 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 9319 final boolean drawVerticalScrollBar = 9320 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 9321 && !isVerticalScrollBarHidden(); 9322 9323 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 9324 final int width = mRight - mLeft; 9325 final int height = mBottom - mTop; 9326 9327 final ScrollBarDrawable scrollBar = cache.scrollBar; 9328 9329 final int scrollX = mScrollX; 9330 final int scrollY = mScrollY; 9331 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 9332 9333 int left, top, right, bottom; 9334 9335 if (drawHorizontalScrollBar) { 9336 int size = scrollBar.getSize(false); 9337 if (size <= 0) { 9338 size = cache.scrollBarSize; 9339 } 9340 9341 scrollBar.setParameters(computeHorizontalScrollRange(), 9342 computeHorizontalScrollOffset(), 9343 computeHorizontalScrollExtent(), false); 9344 final int verticalScrollBarGap = drawVerticalScrollBar ? 9345 getVerticalScrollbarWidth() : 0; 9346 top = scrollY + height - size - (mUserPaddingBottom & inside); 9347 left = scrollX + (mPaddingLeft & inside); 9348 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 9349 bottom = top + size; 9350 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 9351 if (invalidate) { 9352 invalidate(left, top, right, bottom); 9353 } 9354 } 9355 9356 if (drawVerticalScrollBar) { 9357 int size = scrollBar.getSize(true); 9358 if (size <= 0) { 9359 size = cache.scrollBarSize; 9360 } 9361 9362 scrollBar.setParameters(computeVerticalScrollRange(), 9363 computeVerticalScrollOffset(), 9364 computeVerticalScrollExtent(), true); 9365 switch (mVerticalScrollbarPosition) { 9366 default: 9367 case SCROLLBAR_POSITION_DEFAULT: 9368 case SCROLLBAR_POSITION_RIGHT: 9369 left = scrollX + width - size - (mUserPaddingRight & inside); 9370 break; 9371 case SCROLLBAR_POSITION_LEFT: 9372 left = scrollX + (mUserPaddingLeft & inside); 9373 break; 9374 } 9375 top = scrollY + (mPaddingTop & inside); 9376 right = left + size; 9377 bottom = scrollY + height - (mUserPaddingBottom & inside); 9378 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 9379 if (invalidate) { 9380 invalidate(left, top, right, bottom); 9381 } 9382 } 9383 } 9384 } 9385 } 9386 9387 /** 9388 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 9389 * FastScroller is visible. 9390 * @return whether to temporarily hide the vertical scrollbar 9391 * @hide 9392 */ 9393 protected boolean isVerticalScrollBarHidden() { 9394 return false; 9395 } 9396 9397 /** 9398 * <p>Draw the horizontal scrollbar if 9399 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 9400 * 9401 * @param canvas the canvas on which to draw the scrollbar 9402 * @param scrollBar the scrollbar's drawable 9403 * 9404 * @see #isHorizontalScrollBarEnabled() 9405 * @see #computeHorizontalScrollRange() 9406 * @see #computeHorizontalScrollExtent() 9407 * @see #computeHorizontalScrollOffset() 9408 * @see android.widget.ScrollBarDrawable 9409 * @hide 9410 */ 9411 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 9412 int l, int t, int r, int b) { 9413 scrollBar.setBounds(l, t, r, b); 9414 scrollBar.draw(canvas); 9415 } 9416 9417 /** 9418 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 9419 * returns true.</p> 9420 * 9421 * @param canvas the canvas on which to draw the scrollbar 9422 * @param scrollBar the scrollbar's drawable 9423 * 9424 * @see #isVerticalScrollBarEnabled() 9425 * @see #computeVerticalScrollRange() 9426 * @see #computeVerticalScrollExtent() 9427 * @see #computeVerticalScrollOffset() 9428 * @see android.widget.ScrollBarDrawable 9429 * @hide 9430 */ 9431 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 9432 int l, int t, int r, int b) { 9433 scrollBar.setBounds(l, t, r, b); 9434 scrollBar.draw(canvas); 9435 } 9436 9437 /** 9438 * Implement this to do your drawing. 9439 * 9440 * @param canvas the canvas on which the background will be drawn 9441 */ 9442 protected void onDraw(Canvas canvas) { 9443 } 9444 9445 /* 9446 * Caller is responsible for calling requestLayout if necessary. 9447 * (This allows addViewInLayout to not request a new layout.) 9448 */ 9449 void assignParent(ViewParent parent) { 9450 if (mParent == null) { 9451 mParent = parent; 9452 } else if (parent == null) { 9453 mParent = null; 9454 } else { 9455 throw new RuntimeException("view " + this + " being added, but" 9456 + " it already has a parent"); 9457 } 9458 } 9459 9460 /** 9461 * This is called when the view is attached to a window. At this point it 9462 * has a Surface and will start drawing. Note that this function is 9463 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 9464 * however it may be called any time before the first onDraw -- including 9465 * before or after {@link #onMeasure(int, int)}. 9466 * 9467 * @see #onDetachedFromWindow() 9468 */ 9469 protected void onAttachedToWindow() { 9470 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 9471 mParent.requestTransparentRegion(this); 9472 } 9473 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 9474 initialAwakenScrollBars(); 9475 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH; 9476 } 9477 jumpDrawablesToCurrentState(); 9478 // Order is important here: LayoutDirection MUST be resolved before Padding 9479 // and TextDirection 9480 resolveLayoutDirectionIfNeeded(); 9481 resolvePadding(); 9482 resolveTextDirection(); 9483 if (isFocused()) { 9484 InputMethodManager imm = InputMethodManager.peekInstance(); 9485 imm.focusIn(this); 9486 } 9487 } 9488 9489 /** 9490 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 9491 * that the parent directionality can and will be resolved before its children. 9492 */ 9493 private void resolveLayoutDirectionIfNeeded() { 9494 // Do not resolve if it is not needed 9495 if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return; 9496 9497 // Clear any previous layout direction resolution 9498 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL; 9499 9500 // Reset also TextDirection as a change into LayoutDirection may impact the selected 9501 // TextDirectionHeuristic 9502 resetResolvedTextDirection(); 9503 9504 // Set resolved depending on layout direction 9505 switch (getLayoutDirection()) { 9506 case LAYOUT_DIRECTION_INHERIT: 9507 // We cannot do the resolution if there is no parent 9508 if (mParent == null) return; 9509 9510 // If this is root view, no need to look at parent's layout dir. 9511 if (mParent instanceof ViewGroup) { 9512 ViewGroup viewGroup = ((ViewGroup) mParent); 9513 9514 // Check if the parent view group can resolve 9515 if (! viewGroup.canResolveLayoutDirection()) { 9516 return; 9517 } 9518 if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 9519 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9520 } 9521 } 9522 break; 9523 case LAYOUT_DIRECTION_RTL: 9524 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9525 break; 9526 case LAYOUT_DIRECTION_LOCALE: 9527 if(isLayoutDirectionRtl(Locale.getDefault())) { 9528 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9529 } 9530 break; 9531 default: 9532 // Nothing to do, LTR by default 9533 } 9534 9535 // Set to resolved 9536 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED; 9537 } 9538 9539 /** 9540 * @hide 9541 */ 9542 protected void resolvePadding() { 9543 // If the user specified the absolute padding (either with android:padding or 9544 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 9545 // use the default padding or the padding from the background drawable 9546 // (stored at this point in mPadding*) 9547 switch (getResolvedLayoutDirection()) { 9548 case LAYOUT_DIRECTION_RTL: 9549 // Start user padding override Right user padding. Otherwise, if Right user 9550 // padding is not defined, use the default Right padding. If Right user padding 9551 // is defined, just use it. 9552 if (mUserPaddingStart >= 0) { 9553 mUserPaddingRight = mUserPaddingStart; 9554 } else if (mUserPaddingRight < 0) { 9555 mUserPaddingRight = mPaddingRight; 9556 } 9557 if (mUserPaddingEnd >= 0) { 9558 mUserPaddingLeft = mUserPaddingEnd; 9559 } else if (mUserPaddingLeft < 0) { 9560 mUserPaddingLeft = mPaddingLeft; 9561 } 9562 break; 9563 case LAYOUT_DIRECTION_LTR: 9564 default: 9565 // Start user padding override Left user padding. Otherwise, if Left user 9566 // padding is not defined, use the default left padding. If Left user padding 9567 // is defined, just use it. 9568 if (mUserPaddingStart >= 0) { 9569 mUserPaddingLeft = mUserPaddingStart; 9570 } else if (mUserPaddingLeft < 0) { 9571 mUserPaddingLeft = mPaddingLeft; 9572 } 9573 if (mUserPaddingEnd >= 0) { 9574 mUserPaddingRight = mUserPaddingEnd; 9575 } else if (mUserPaddingRight < 0) { 9576 mUserPaddingRight = mPaddingRight; 9577 } 9578 } 9579 9580 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 9581 9582 recomputePadding(); 9583 } 9584 9585 /** 9586 * Return true if layout direction resolution can be done 9587 * 9588 * @hide 9589 */ 9590 protected boolean canResolveLayoutDirection() { 9591 switch (getLayoutDirection()) { 9592 case LAYOUT_DIRECTION_INHERIT: 9593 return (mParent != null); 9594 default: 9595 return true; 9596 } 9597 } 9598 9599 /** 9600 * Reset the resolved layout direction. 9601 * 9602 * Subclasses need to override this method to clear cached information that depends on the 9603 * resolved layout direction, or to inform child views that inherit their layout direction. 9604 * Overrides must also call the superclass implementation at the start of their implementation. 9605 * 9606 * @hide 9607 */ 9608 protected void resetResolvedLayoutDirection() { 9609 // Reset the current View resolution 9610 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED; 9611 } 9612 9613 /** 9614 * Check if a Locale is corresponding to a RTL script. 9615 * 9616 * @param locale Locale to check 9617 * @return true if a Locale is corresponding to a RTL script. 9618 * 9619 * @hide 9620 */ 9621 protected static boolean isLayoutDirectionRtl(Locale locale) { 9622 return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE == 9623 LocaleUtil.getLayoutDirectionFromLocale(locale)); 9624 } 9625 9626 /** 9627 * This is called when the view is detached from a window. At this point it 9628 * no longer has a surface for drawing. 9629 * 9630 * @see #onAttachedToWindow() 9631 */ 9632 protected void onDetachedFromWindow() { 9633 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 9634 9635 removeUnsetPressCallback(); 9636 removeLongPressCallback(); 9637 removePerformClickCallback(); 9638 removeSendViewScrolledAccessibilityEventCallback(); 9639 9640 destroyDrawingCache(); 9641 9642 destroyLayer(); 9643 9644 if (mDisplayList != null) { 9645 mDisplayList.invalidate(); 9646 } 9647 9648 if (mAttachInfo != null) { 9649 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this); 9650 } 9651 9652 mCurrentAnimation = null; 9653 9654 resetResolvedLayoutDirection(); 9655 resetResolvedTextDirection(); 9656 } 9657 9658 /** 9659 * @return The number of times this view has been attached to a window 9660 */ 9661 protected int getWindowAttachCount() { 9662 return mWindowAttachCount; 9663 } 9664 9665 /** 9666 * Retrieve a unique token identifying the window this view is attached to. 9667 * @return Return the window's token for use in 9668 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 9669 */ 9670 public IBinder getWindowToken() { 9671 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 9672 } 9673 9674 /** 9675 * Retrieve a unique token identifying the top-level "real" window of 9676 * the window that this view is attached to. That is, this is like 9677 * {@link #getWindowToken}, except if the window this view in is a panel 9678 * window (attached to another containing window), then the token of 9679 * the containing window is returned instead. 9680 * 9681 * @return Returns the associated window token, either 9682 * {@link #getWindowToken()} or the containing window's token. 9683 */ 9684 public IBinder getApplicationWindowToken() { 9685 AttachInfo ai = mAttachInfo; 9686 if (ai != null) { 9687 IBinder appWindowToken = ai.mPanelParentWindowToken; 9688 if (appWindowToken == null) { 9689 appWindowToken = ai.mWindowToken; 9690 } 9691 return appWindowToken; 9692 } 9693 return null; 9694 } 9695 9696 /** 9697 * Retrieve private session object this view hierarchy is using to 9698 * communicate with the window manager. 9699 * @return the session object to communicate with the window manager 9700 */ 9701 /*package*/ IWindowSession getWindowSession() { 9702 return mAttachInfo != null ? mAttachInfo.mSession : null; 9703 } 9704 9705 /** 9706 * @param info the {@link android.view.View.AttachInfo} to associated with 9707 * this view 9708 */ 9709 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 9710 //System.out.println("Attached! " + this); 9711 mAttachInfo = info; 9712 mWindowAttachCount++; 9713 // We will need to evaluate the drawable state at least once. 9714 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 9715 if (mFloatingTreeObserver != null) { 9716 info.mTreeObserver.merge(mFloatingTreeObserver); 9717 mFloatingTreeObserver = null; 9718 } 9719 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 9720 mAttachInfo.mScrollContainers.add(this); 9721 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 9722 } 9723 performCollectViewAttributes(visibility); 9724 onAttachedToWindow(); 9725 9726 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9727 mOnAttachStateChangeListeners; 9728 if (listeners != null && listeners.size() > 0) { 9729 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9730 // perform the dispatching. The iterator is a safe guard against listeners that 9731 // could mutate the list by calling the various add/remove methods. This prevents 9732 // the array from being modified while we iterate it. 9733 for (OnAttachStateChangeListener listener : listeners) { 9734 listener.onViewAttachedToWindow(this); 9735 } 9736 } 9737 9738 int vis = info.mWindowVisibility; 9739 if (vis != GONE) { 9740 onWindowVisibilityChanged(vis); 9741 } 9742 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 9743 // If nobody has evaluated the drawable state yet, then do it now. 9744 refreshDrawableState(); 9745 } 9746 } 9747 9748 void dispatchDetachedFromWindow() { 9749 AttachInfo info = mAttachInfo; 9750 if (info != null) { 9751 int vis = info.mWindowVisibility; 9752 if (vis != GONE) { 9753 onWindowVisibilityChanged(GONE); 9754 } 9755 } 9756 9757 onDetachedFromWindow(); 9758 9759 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9760 mOnAttachStateChangeListeners; 9761 if (listeners != null && listeners.size() > 0) { 9762 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9763 // perform the dispatching. The iterator is a safe guard against listeners that 9764 // could mutate the list by calling the various add/remove methods. This prevents 9765 // the array from being modified while we iterate it. 9766 for (OnAttachStateChangeListener listener : listeners) { 9767 listener.onViewDetachedFromWindow(this); 9768 } 9769 } 9770 9771 if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) { 9772 mAttachInfo.mScrollContainers.remove(this); 9773 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 9774 } 9775 9776 mAttachInfo = null; 9777 } 9778 9779 /** 9780 * Store this view hierarchy's frozen state into the given container. 9781 * 9782 * @param container The SparseArray in which to save the view's state. 9783 * 9784 * @see #restoreHierarchyState(android.util.SparseArray) 9785 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9786 * @see #onSaveInstanceState() 9787 */ 9788 public void saveHierarchyState(SparseArray<Parcelable> container) { 9789 dispatchSaveInstanceState(container); 9790 } 9791 9792 /** 9793 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 9794 * this view and its children. May be overridden to modify how freezing happens to a 9795 * view's children; for example, some views may want to not store state for their children. 9796 * 9797 * @param container The SparseArray in which to save the view's state. 9798 * 9799 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9800 * @see #saveHierarchyState(android.util.SparseArray) 9801 * @see #onSaveInstanceState() 9802 */ 9803 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 9804 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 9805 mPrivateFlags &= ~SAVE_STATE_CALLED; 9806 Parcelable state = onSaveInstanceState(); 9807 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9808 throw new IllegalStateException( 9809 "Derived class did not call super.onSaveInstanceState()"); 9810 } 9811 if (state != null) { 9812 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 9813 // + ": " + state); 9814 container.put(mID, state); 9815 } 9816 } 9817 } 9818 9819 /** 9820 * Hook allowing a view to generate a representation of its internal state 9821 * that can later be used to create a new instance with that same state. 9822 * This state should only contain information that is not persistent or can 9823 * not be reconstructed later. For example, you will never store your 9824 * current position on screen because that will be computed again when a 9825 * new instance of the view is placed in its view hierarchy. 9826 * <p> 9827 * Some examples of things you may store here: the current cursor position 9828 * in a text view (but usually not the text itself since that is stored in a 9829 * content provider or other persistent storage), the currently selected 9830 * item in a list view. 9831 * 9832 * @return Returns a Parcelable object containing the view's current dynamic 9833 * state, or null if there is nothing interesting to save. The 9834 * default implementation returns null. 9835 * @see #onRestoreInstanceState(android.os.Parcelable) 9836 * @see #saveHierarchyState(android.util.SparseArray) 9837 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9838 * @see #setSaveEnabled(boolean) 9839 */ 9840 protected Parcelable onSaveInstanceState() { 9841 mPrivateFlags |= SAVE_STATE_CALLED; 9842 return BaseSavedState.EMPTY_STATE; 9843 } 9844 9845 /** 9846 * Restore this view hierarchy's frozen state from the given container. 9847 * 9848 * @param container The SparseArray which holds previously frozen states. 9849 * 9850 * @see #saveHierarchyState(android.util.SparseArray) 9851 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9852 * @see #onRestoreInstanceState(android.os.Parcelable) 9853 */ 9854 public void restoreHierarchyState(SparseArray<Parcelable> container) { 9855 dispatchRestoreInstanceState(container); 9856 } 9857 9858 /** 9859 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 9860 * state for this view and its children. May be overridden to modify how restoring 9861 * happens to a view's children; for example, some views may want to not store state 9862 * for their children. 9863 * 9864 * @param container The SparseArray which holds previously saved state. 9865 * 9866 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9867 * @see #restoreHierarchyState(android.util.SparseArray) 9868 * @see #onRestoreInstanceState(android.os.Parcelable) 9869 */ 9870 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 9871 if (mID != NO_ID) { 9872 Parcelable state = container.get(mID); 9873 if (state != null) { 9874 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 9875 // + ": " + state); 9876 mPrivateFlags &= ~SAVE_STATE_CALLED; 9877 onRestoreInstanceState(state); 9878 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9879 throw new IllegalStateException( 9880 "Derived class did not call super.onRestoreInstanceState()"); 9881 } 9882 } 9883 } 9884 } 9885 9886 /** 9887 * Hook allowing a view to re-apply a representation of its internal state that had previously 9888 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 9889 * null state. 9890 * 9891 * @param state The frozen state that had previously been returned by 9892 * {@link #onSaveInstanceState}. 9893 * 9894 * @see #onSaveInstanceState() 9895 * @see #restoreHierarchyState(android.util.SparseArray) 9896 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9897 */ 9898 protected void onRestoreInstanceState(Parcelable state) { 9899 mPrivateFlags |= SAVE_STATE_CALLED; 9900 if (state != BaseSavedState.EMPTY_STATE && state != null) { 9901 throw new IllegalArgumentException("Wrong state class, expecting View State but " 9902 + "received " + state.getClass().toString() + " instead. This usually happens " 9903 + "when two views of different type have the same id in the same hierarchy. " 9904 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 9905 + "other views do not use the same id."); 9906 } 9907 } 9908 9909 /** 9910 * <p>Return the time at which the drawing of the view hierarchy started.</p> 9911 * 9912 * @return the drawing start time in milliseconds 9913 */ 9914 public long getDrawingTime() { 9915 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 9916 } 9917 9918 /** 9919 * <p>Enables or disables the duplication of the parent's state into this view. When 9920 * duplication is enabled, this view gets its drawable state from its parent rather 9921 * than from its own internal properties.</p> 9922 * 9923 * <p>Note: in the current implementation, setting this property to true after the 9924 * view was added to a ViewGroup might have no effect at all. This property should 9925 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 9926 * 9927 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 9928 * property is enabled, an exception will be thrown.</p> 9929 * 9930 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 9931 * parent, these states should not be affected by this method.</p> 9932 * 9933 * @param enabled True to enable duplication of the parent's drawable state, false 9934 * to disable it. 9935 * 9936 * @see #getDrawableState() 9937 * @see #isDuplicateParentStateEnabled() 9938 */ 9939 public void setDuplicateParentStateEnabled(boolean enabled) { 9940 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 9941 } 9942 9943 /** 9944 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 9945 * 9946 * @return True if this view's drawable state is duplicated from the parent, 9947 * false otherwise 9948 * 9949 * @see #getDrawableState() 9950 * @see #setDuplicateParentStateEnabled(boolean) 9951 */ 9952 public boolean isDuplicateParentStateEnabled() { 9953 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 9954 } 9955 9956 /** 9957 * <p>Specifies the type of layer backing this view. The layer can be 9958 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 9959 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 9960 * 9961 * <p>A layer is associated with an optional {@link android.graphics.Paint} 9962 * instance that controls how the layer is composed on screen. The following 9963 * properties of the paint are taken into account when composing the layer:</p> 9964 * <ul> 9965 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 9966 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 9967 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 9968 * </ul> 9969 * 9970 * <p>If this view has an alpha value set to < 1.0 by calling 9971 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 9972 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 9973 * equivalent to setting a hardware layer on this view and providing a paint with 9974 * the desired alpha value.<p> 9975 * 9976 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 9977 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 9978 * for more information on when and how to use layers.</p> 9979 * 9980 * @param layerType The ype of layer to use with this view, must be one of 9981 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 9982 * {@link #LAYER_TYPE_HARDWARE} 9983 * @param paint The paint used to compose the layer. This argument is optional 9984 * and can be null. It is ignored when the layer type is 9985 * {@link #LAYER_TYPE_NONE} 9986 * 9987 * @see #getLayerType() 9988 * @see #LAYER_TYPE_NONE 9989 * @see #LAYER_TYPE_SOFTWARE 9990 * @see #LAYER_TYPE_HARDWARE 9991 * @see #setAlpha(float) 9992 * 9993 * @attr ref android.R.styleable#View_layerType 9994 */ 9995 public void setLayerType(int layerType, Paint paint) { 9996 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 9997 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 9998 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 9999 } 10000 10001 if (layerType == mLayerType) { 10002 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 10003 mLayerPaint = paint == null ? new Paint() : paint; 10004 invalidateParentCaches(); 10005 invalidate(true); 10006 } 10007 return; 10008 } 10009 10010 // Destroy any previous software drawing cache if needed 10011 switch (mLayerType) { 10012 case LAYER_TYPE_HARDWARE: 10013 destroyLayer(); 10014 // fall through - unaccelerated views may use software layer mechanism instead 10015 case LAYER_TYPE_SOFTWARE: 10016 destroyDrawingCache(); 10017 break; 10018 default: 10019 break; 10020 } 10021 10022 mLayerType = layerType; 10023 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 10024 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 10025 mLocalDirtyRect = layerDisabled ? null : new Rect(); 10026 10027 invalidateParentCaches(); 10028 invalidate(true); 10029 } 10030 10031 /** 10032 * Indicates whether this view has a static layer. A view with layer type 10033 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 10034 * dynamic. 10035 */ 10036 boolean hasStaticLayer() { 10037 return mLayerType == LAYER_TYPE_NONE; 10038 } 10039 10040 /** 10041 * Indicates what type of layer is currently associated with this view. By default 10042 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 10043 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 10044 * for more information on the different types of layers. 10045 * 10046 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 10047 * {@link #LAYER_TYPE_HARDWARE} 10048 * 10049 * @see #setLayerType(int, android.graphics.Paint) 10050 * @see #buildLayer() 10051 * @see #LAYER_TYPE_NONE 10052 * @see #LAYER_TYPE_SOFTWARE 10053 * @see #LAYER_TYPE_HARDWARE 10054 */ 10055 public int getLayerType() { 10056 return mLayerType; 10057 } 10058 10059 /** 10060 * Forces this view's layer to be created and this view to be rendered 10061 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 10062 * invoking this method will have no effect. 10063 * 10064 * This method can for instance be used to render a view into its layer before 10065 * starting an animation. If this view is complex, rendering into the layer 10066 * before starting the animation will avoid skipping frames. 10067 * 10068 * @throws IllegalStateException If this view is not attached to a window 10069 * 10070 * @see #setLayerType(int, android.graphics.Paint) 10071 */ 10072 public void buildLayer() { 10073 if (mLayerType == LAYER_TYPE_NONE) return; 10074 10075 if (mAttachInfo == null) { 10076 throw new IllegalStateException("This view must be attached to a window first"); 10077 } 10078 10079 switch (mLayerType) { 10080 case LAYER_TYPE_HARDWARE: 10081 getHardwareLayer(); 10082 break; 10083 case LAYER_TYPE_SOFTWARE: 10084 buildDrawingCache(true); 10085 break; 10086 } 10087 } 10088 10089 /** 10090 * <p>Returns a hardware layer that can be used to draw this view again 10091 * without executing its draw method.</p> 10092 * 10093 * @return A HardwareLayer ready to render, or null if an error occurred. 10094 */ 10095 HardwareLayer getHardwareLayer() { 10096 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 10097 !mAttachInfo.mHardwareRenderer.isEnabled()) { 10098 return null; 10099 } 10100 10101 final int width = mRight - mLeft; 10102 final int height = mBottom - mTop; 10103 10104 if (width == 0 || height == 0) { 10105 return null; 10106 } 10107 10108 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 10109 if (mHardwareLayer == null) { 10110 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 10111 width, height, isOpaque()); 10112 mLocalDirtyRect.setEmpty(); 10113 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 10114 mHardwareLayer.resize(width, height); 10115 mLocalDirtyRect.setEmpty(); 10116 } 10117 10118 // The layer is not valid if the underlying GPU resources cannot be allocated 10119 if (!mHardwareLayer.isValid()) { 10120 return null; 10121 } 10122 10123 HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas; 10124 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas); 10125 10126 // Make sure all the GPU resources have been properly allocated 10127 if (canvas == null) { 10128 mHardwareLayer.end(currentCanvas); 10129 return null; 10130 } 10131 10132 mAttachInfo.mHardwareCanvas = canvas; 10133 try { 10134 canvas.setViewport(width, height); 10135 canvas.onPreDraw(mLocalDirtyRect); 10136 mLocalDirtyRect.setEmpty(); 10137 10138 final int restoreCount = canvas.save(); 10139 10140 computeScroll(); 10141 canvas.translate(-mScrollX, -mScrollY); 10142 10143 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10144 10145 // Fast path for layouts with no backgrounds 10146 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10147 mPrivateFlags &= ~DIRTY_MASK; 10148 dispatchDraw(canvas); 10149 } else { 10150 draw(canvas); 10151 } 10152 10153 canvas.restoreToCount(restoreCount); 10154 } finally { 10155 canvas.onPostDraw(); 10156 mHardwareLayer.end(currentCanvas); 10157 mAttachInfo.mHardwareCanvas = currentCanvas; 10158 } 10159 } 10160 10161 return mHardwareLayer; 10162 } 10163 10164 /** 10165 * Destroys this View's hardware layer if possible. 10166 * 10167 * @return True if the layer was destroyed, false otherwise. 10168 * 10169 * @see #setLayerType(int, android.graphics.Paint) 10170 * @see #LAYER_TYPE_HARDWARE 10171 */ 10172 boolean destroyLayer() { 10173 if (mHardwareLayer != null) { 10174 mHardwareLayer.destroy(); 10175 mHardwareLayer = null; 10176 return true; 10177 } 10178 return false; 10179 } 10180 10181 /** 10182 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 10183 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 10184 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 10185 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 10186 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 10187 * null.</p> 10188 * 10189 * <p>Enabling the drawing cache is similar to 10190 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 10191 * acceleration is turned off. When hardware acceleration is turned on, enabling the 10192 * drawing cache has no effect on rendering because the system uses a different mechanism 10193 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 10194 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 10195 * for information on how to enable software and hardware layers.</p> 10196 * 10197 * <p>This API can be used to manually generate 10198 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 10199 * {@link #getDrawingCache()}.</p> 10200 * 10201 * @param enabled true to enable the drawing cache, false otherwise 10202 * 10203 * @see #isDrawingCacheEnabled() 10204 * @see #getDrawingCache() 10205 * @see #buildDrawingCache() 10206 * @see #setLayerType(int, android.graphics.Paint) 10207 */ 10208 public void setDrawingCacheEnabled(boolean enabled) { 10209 mCachingFailed = false; 10210 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 10211 } 10212 10213 /** 10214 * <p>Indicates whether the drawing cache is enabled for this view.</p> 10215 * 10216 * @return true if the drawing cache is enabled 10217 * 10218 * @see #setDrawingCacheEnabled(boolean) 10219 * @see #getDrawingCache() 10220 */ 10221 @ViewDebug.ExportedProperty(category = "drawing") 10222 public boolean isDrawingCacheEnabled() { 10223 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 10224 } 10225 10226 /** 10227 * Debugging utility which recursively outputs the dirty state of a view and its 10228 * descendants. 10229 * 10230 * @hide 10231 */ 10232 @SuppressWarnings({"UnusedDeclaration"}) 10233 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 10234 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) + 10235 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" + 10236 (mPrivateFlags & View.DRAWING_CACHE_VALID) + 10237 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")"); 10238 if (clear) { 10239 mPrivateFlags &= clearMask; 10240 } 10241 if (this instanceof ViewGroup) { 10242 ViewGroup parent = (ViewGroup) this; 10243 final int count = parent.getChildCount(); 10244 for (int i = 0; i < count; i++) { 10245 final View child = parent.getChildAt(i); 10246 child.outputDirtyFlags(indent + " ", clear, clearMask); 10247 } 10248 } 10249 } 10250 10251 /** 10252 * This method is used by ViewGroup to cause its children to restore or recreate their 10253 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 10254 * to recreate its own display list, which would happen if it went through the normal 10255 * draw/dispatchDraw mechanisms. 10256 * 10257 * @hide 10258 */ 10259 protected void dispatchGetDisplayList() {} 10260 10261 /** 10262 * A view that is not attached or hardware accelerated cannot create a display list. 10263 * This method checks these conditions and returns the appropriate result. 10264 * 10265 * @return true if view has the ability to create a display list, false otherwise. 10266 * 10267 * @hide 10268 */ 10269 public boolean canHaveDisplayList() { 10270 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 10271 } 10272 10273 /** 10274 * <p>Returns a display list that can be used to draw this view again 10275 * without executing its draw method.</p> 10276 * 10277 * @return A DisplayList ready to replay, or null if caching is not enabled. 10278 * 10279 * @hide 10280 */ 10281 public DisplayList getDisplayList() { 10282 if (!canHaveDisplayList()) { 10283 return null; 10284 } 10285 10286 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || 10287 mDisplayList == null || !mDisplayList.isValid() || 10288 mRecreateDisplayList)) { 10289 // Don't need to recreate the display list, just need to tell our 10290 // children to restore/recreate theirs 10291 if (mDisplayList != null && mDisplayList.isValid() && 10292 !mRecreateDisplayList) { 10293 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10294 mPrivateFlags &= ~DIRTY_MASK; 10295 dispatchGetDisplayList(); 10296 10297 return mDisplayList; 10298 } 10299 10300 // If we got here, we're recreating it. Mark it as such to ensure that 10301 // we copy in child display lists into ours in drawChild() 10302 mRecreateDisplayList = true; 10303 if (mDisplayList == null) { 10304 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(); 10305 // If we're creating a new display list, make sure our parent gets invalidated 10306 // since they will need to recreate their display list to account for this 10307 // new child display list. 10308 invalidateParentCaches(); 10309 } 10310 10311 final HardwareCanvas canvas = mDisplayList.start(); 10312 int restoreCount = 0; 10313 try { 10314 int width = mRight - mLeft; 10315 int height = mBottom - mTop; 10316 10317 canvas.setViewport(width, height); 10318 // The dirty rect should always be null for a display list 10319 canvas.onPreDraw(null); 10320 10321 computeScroll(); 10322 10323 restoreCount = canvas.save(); 10324 canvas.translate(-mScrollX, -mScrollY); 10325 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10326 mPrivateFlags &= ~DIRTY_MASK; 10327 10328 // Fast path for layouts with no backgrounds 10329 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10330 dispatchDraw(canvas); 10331 } else { 10332 draw(canvas); 10333 } 10334 } finally { 10335 canvas.restoreToCount(restoreCount); 10336 canvas.onPostDraw(); 10337 10338 mDisplayList.end(); 10339 } 10340 } else { 10341 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10342 mPrivateFlags &= ~DIRTY_MASK; 10343 } 10344 10345 return mDisplayList; 10346 } 10347 10348 /** 10349 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 10350 * 10351 * @return A non-scaled bitmap representing this view or null if cache is disabled. 10352 * 10353 * @see #getDrawingCache(boolean) 10354 */ 10355 public Bitmap getDrawingCache() { 10356 return getDrawingCache(false); 10357 } 10358 10359 /** 10360 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 10361 * is null when caching is disabled. If caching is enabled and the cache is not ready, 10362 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 10363 * draw from the cache when the cache is enabled. To benefit from the cache, you must 10364 * request the drawing cache by calling this method and draw it on screen if the 10365 * returned bitmap is not null.</p> 10366 * 10367 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10368 * this method will create a bitmap of the same size as this view. Because this bitmap 10369 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10370 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10371 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10372 * size than the view. This implies that your application must be able to handle this 10373 * size.</p> 10374 * 10375 * @param autoScale Indicates whether the generated bitmap should be scaled based on 10376 * the current density of the screen when the application is in compatibility 10377 * mode. 10378 * 10379 * @return A bitmap representing this view or null if cache is disabled. 10380 * 10381 * @see #setDrawingCacheEnabled(boolean) 10382 * @see #isDrawingCacheEnabled() 10383 * @see #buildDrawingCache(boolean) 10384 * @see #destroyDrawingCache() 10385 */ 10386 public Bitmap getDrawingCache(boolean autoScale) { 10387 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 10388 return null; 10389 } 10390 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 10391 buildDrawingCache(autoScale); 10392 } 10393 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 10394 } 10395 10396 /** 10397 * <p>Frees the resources used by the drawing cache. If you call 10398 * {@link #buildDrawingCache()} manually without calling 10399 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10400 * should cleanup the cache with this method afterwards.</p> 10401 * 10402 * @see #setDrawingCacheEnabled(boolean) 10403 * @see #buildDrawingCache() 10404 * @see #getDrawingCache() 10405 */ 10406 public void destroyDrawingCache() { 10407 if (mDrawingCache != null) { 10408 mDrawingCache.recycle(); 10409 mDrawingCache = null; 10410 } 10411 if (mUnscaledDrawingCache != null) { 10412 mUnscaledDrawingCache.recycle(); 10413 mUnscaledDrawingCache = null; 10414 } 10415 } 10416 10417 /** 10418 * Setting a solid background color for the drawing cache's bitmaps will improve 10419 * performance and memory usage. Note, though that this should only be used if this 10420 * view will always be drawn on top of a solid color. 10421 * 10422 * @param color The background color to use for the drawing cache's bitmap 10423 * 10424 * @see #setDrawingCacheEnabled(boolean) 10425 * @see #buildDrawingCache() 10426 * @see #getDrawingCache() 10427 */ 10428 public void setDrawingCacheBackgroundColor(int color) { 10429 if (color != mDrawingCacheBackgroundColor) { 10430 mDrawingCacheBackgroundColor = color; 10431 mPrivateFlags &= ~DRAWING_CACHE_VALID; 10432 } 10433 } 10434 10435 /** 10436 * @see #setDrawingCacheBackgroundColor(int) 10437 * 10438 * @return The background color to used for the drawing cache's bitmap 10439 */ 10440 public int getDrawingCacheBackgroundColor() { 10441 return mDrawingCacheBackgroundColor; 10442 } 10443 10444 /** 10445 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 10446 * 10447 * @see #buildDrawingCache(boolean) 10448 */ 10449 public void buildDrawingCache() { 10450 buildDrawingCache(false); 10451 } 10452 10453 /** 10454 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 10455 * 10456 * <p>If you call {@link #buildDrawingCache()} manually without calling 10457 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10458 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 10459 * 10460 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10461 * this method will create a bitmap of the same size as this view. Because this bitmap 10462 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10463 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10464 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10465 * size than the view. This implies that your application must be able to handle this 10466 * size.</p> 10467 * 10468 * <p>You should avoid calling this method when hardware acceleration is enabled. If 10469 * you do not need the drawing cache bitmap, calling this method will increase memory 10470 * usage and cause the view to be rendered in software once, thus negatively impacting 10471 * performance.</p> 10472 * 10473 * @see #getDrawingCache() 10474 * @see #destroyDrawingCache() 10475 */ 10476 public void buildDrawingCache(boolean autoScale) { 10477 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 10478 mDrawingCache == null : mUnscaledDrawingCache == null)) { 10479 mCachingFailed = false; 10480 10481 if (ViewDebug.TRACE_HIERARCHY) { 10482 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 10483 } 10484 10485 int width = mRight - mLeft; 10486 int height = mBottom - mTop; 10487 10488 final AttachInfo attachInfo = mAttachInfo; 10489 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 10490 10491 if (autoScale && scalingRequired) { 10492 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 10493 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 10494 } 10495 10496 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 10497 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 10498 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 10499 10500 if (width <= 0 || height <= 0 || 10501 // Projected bitmap size in bytes 10502 (width * height * (opaque && !use32BitCache ? 2 : 4) > 10503 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 10504 destroyDrawingCache(); 10505 mCachingFailed = true; 10506 return; 10507 } 10508 10509 boolean clear = true; 10510 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 10511 10512 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 10513 Bitmap.Config quality; 10514 if (!opaque) { 10515 // Never pick ARGB_4444 because it looks awful 10516 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 10517 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 10518 case DRAWING_CACHE_QUALITY_AUTO: 10519 quality = Bitmap.Config.ARGB_8888; 10520 break; 10521 case DRAWING_CACHE_QUALITY_LOW: 10522 quality = Bitmap.Config.ARGB_8888; 10523 break; 10524 case DRAWING_CACHE_QUALITY_HIGH: 10525 quality = Bitmap.Config.ARGB_8888; 10526 break; 10527 default: 10528 quality = Bitmap.Config.ARGB_8888; 10529 break; 10530 } 10531 } else { 10532 // Optimization for translucent windows 10533 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 10534 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 10535 } 10536 10537 // Try to cleanup memory 10538 if (bitmap != null) bitmap.recycle(); 10539 10540 try { 10541 bitmap = Bitmap.createBitmap(width, height, quality); 10542 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 10543 if (autoScale) { 10544 mDrawingCache = bitmap; 10545 } else { 10546 mUnscaledDrawingCache = bitmap; 10547 } 10548 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 10549 } catch (OutOfMemoryError e) { 10550 // If there is not enough memory to create the bitmap cache, just 10551 // ignore the issue as bitmap caches are not required to draw the 10552 // view hierarchy 10553 if (autoScale) { 10554 mDrawingCache = null; 10555 } else { 10556 mUnscaledDrawingCache = null; 10557 } 10558 mCachingFailed = true; 10559 return; 10560 } 10561 10562 clear = drawingCacheBackgroundColor != 0; 10563 } 10564 10565 Canvas canvas; 10566 if (attachInfo != null) { 10567 canvas = attachInfo.mCanvas; 10568 if (canvas == null) { 10569 canvas = new Canvas(); 10570 } 10571 canvas.setBitmap(bitmap); 10572 // Temporarily clobber the cached Canvas in case one of our children 10573 // is also using a drawing cache. Without this, the children would 10574 // steal the canvas by attaching their own bitmap to it and bad, bad 10575 // thing would happen (invisible views, corrupted drawings, etc.) 10576 attachInfo.mCanvas = null; 10577 } else { 10578 // This case should hopefully never or seldom happen 10579 canvas = new Canvas(bitmap); 10580 } 10581 10582 if (clear) { 10583 bitmap.eraseColor(drawingCacheBackgroundColor); 10584 } 10585 10586 computeScroll(); 10587 final int restoreCount = canvas.save(); 10588 10589 if (autoScale && scalingRequired) { 10590 final float scale = attachInfo.mApplicationScale; 10591 canvas.scale(scale, scale); 10592 } 10593 10594 canvas.translate(-mScrollX, -mScrollY); 10595 10596 mPrivateFlags |= DRAWN; 10597 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 10598 mLayerType != LAYER_TYPE_NONE) { 10599 mPrivateFlags |= DRAWING_CACHE_VALID; 10600 } 10601 10602 // Fast path for layouts with no backgrounds 10603 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10604 if (ViewDebug.TRACE_HIERARCHY) { 10605 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 10606 } 10607 mPrivateFlags &= ~DIRTY_MASK; 10608 dispatchDraw(canvas); 10609 } else { 10610 draw(canvas); 10611 } 10612 10613 canvas.restoreToCount(restoreCount); 10614 canvas.setBitmap(null); 10615 10616 if (attachInfo != null) { 10617 // Restore the cached Canvas for our siblings 10618 attachInfo.mCanvas = canvas; 10619 } 10620 } 10621 } 10622 10623 /** 10624 * Create a snapshot of the view into a bitmap. We should probably make 10625 * some form of this public, but should think about the API. 10626 */ 10627 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 10628 int width = mRight - mLeft; 10629 int height = mBottom - mTop; 10630 10631 final AttachInfo attachInfo = mAttachInfo; 10632 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 10633 width = (int) ((width * scale) + 0.5f); 10634 height = (int) ((height * scale) + 0.5f); 10635 10636 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 10637 if (bitmap == null) { 10638 throw new OutOfMemoryError(); 10639 } 10640 10641 Resources resources = getResources(); 10642 if (resources != null) { 10643 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 10644 } 10645 10646 Canvas canvas; 10647 if (attachInfo != null) { 10648 canvas = attachInfo.mCanvas; 10649 if (canvas == null) { 10650 canvas = new Canvas(); 10651 } 10652 canvas.setBitmap(bitmap); 10653 // Temporarily clobber the cached Canvas in case one of our children 10654 // is also using a drawing cache. Without this, the children would 10655 // steal the canvas by attaching their own bitmap to it and bad, bad 10656 // things would happen (invisible views, corrupted drawings, etc.) 10657 attachInfo.mCanvas = null; 10658 } else { 10659 // This case should hopefully never or seldom happen 10660 canvas = new Canvas(bitmap); 10661 } 10662 10663 if ((backgroundColor & 0xff000000) != 0) { 10664 bitmap.eraseColor(backgroundColor); 10665 } 10666 10667 computeScroll(); 10668 final int restoreCount = canvas.save(); 10669 canvas.scale(scale, scale); 10670 canvas.translate(-mScrollX, -mScrollY); 10671 10672 // Temporarily remove the dirty mask 10673 int flags = mPrivateFlags; 10674 mPrivateFlags &= ~DIRTY_MASK; 10675 10676 // Fast path for layouts with no backgrounds 10677 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10678 dispatchDraw(canvas); 10679 } else { 10680 draw(canvas); 10681 } 10682 10683 mPrivateFlags = flags; 10684 10685 canvas.restoreToCount(restoreCount); 10686 canvas.setBitmap(null); 10687 10688 if (attachInfo != null) { 10689 // Restore the cached Canvas for our siblings 10690 attachInfo.mCanvas = canvas; 10691 } 10692 10693 return bitmap; 10694 } 10695 10696 /** 10697 * Indicates whether this View is currently in edit mode. A View is usually 10698 * in edit mode when displayed within a developer tool. For instance, if 10699 * this View is being drawn by a visual user interface builder, this method 10700 * should return true. 10701 * 10702 * Subclasses should check the return value of this method to provide 10703 * different behaviors if their normal behavior might interfere with the 10704 * host environment. For instance: the class spawns a thread in its 10705 * constructor, the drawing code relies on device-specific features, etc. 10706 * 10707 * This method is usually checked in the drawing code of custom widgets. 10708 * 10709 * @return True if this View is in edit mode, false otherwise. 10710 */ 10711 public boolean isInEditMode() { 10712 return false; 10713 } 10714 10715 /** 10716 * If the View draws content inside its padding and enables fading edges, 10717 * it needs to support padding offsets. Padding offsets are added to the 10718 * fading edges to extend the length of the fade so that it covers pixels 10719 * drawn inside the padding. 10720 * 10721 * Subclasses of this class should override this method if they need 10722 * to draw content inside the padding. 10723 * 10724 * @return True if padding offset must be applied, false otherwise. 10725 * 10726 * @see #getLeftPaddingOffset() 10727 * @see #getRightPaddingOffset() 10728 * @see #getTopPaddingOffset() 10729 * @see #getBottomPaddingOffset() 10730 * 10731 * @since CURRENT 10732 */ 10733 protected boolean isPaddingOffsetRequired() { 10734 return false; 10735 } 10736 10737 /** 10738 * Amount by which to extend the left fading region. Called only when 10739 * {@link #isPaddingOffsetRequired()} returns true. 10740 * 10741 * @return The left padding offset in pixels. 10742 * 10743 * @see #isPaddingOffsetRequired() 10744 * 10745 * @since CURRENT 10746 */ 10747 protected int getLeftPaddingOffset() { 10748 return 0; 10749 } 10750 10751 /** 10752 * Amount by which to extend the right fading region. Called only when 10753 * {@link #isPaddingOffsetRequired()} returns true. 10754 * 10755 * @return The right padding offset in pixels. 10756 * 10757 * @see #isPaddingOffsetRequired() 10758 * 10759 * @since CURRENT 10760 */ 10761 protected int getRightPaddingOffset() { 10762 return 0; 10763 } 10764 10765 /** 10766 * Amount by which to extend the top fading region. Called only when 10767 * {@link #isPaddingOffsetRequired()} returns true. 10768 * 10769 * @return The top padding offset in pixels. 10770 * 10771 * @see #isPaddingOffsetRequired() 10772 * 10773 * @since CURRENT 10774 */ 10775 protected int getTopPaddingOffset() { 10776 return 0; 10777 } 10778 10779 /** 10780 * Amount by which to extend the bottom fading region. Called only when 10781 * {@link #isPaddingOffsetRequired()} returns true. 10782 * 10783 * @return The bottom padding offset in pixels. 10784 * 10785 * @see #isPaddingOffsetRequired() 10786 * 10787 * @since CURRENT 10788 */ 10789 protected int getBottomPaddingOffset() { 10790 return 0; 10791 } 10792 10793 /** 10794 * @hide 10795 * @param offsetRequired 10796 */ 10797 protected int getFadeTop(boolean offsetRequired) { 10798 int top = mPaddingTop; 10799 if (offsetRequired) top += getTopPaddingOffset(); 10800 return top; 10801 } 10802 10803 /** 10804 * @hide 10805 * @param offsetRequired 10806 */ 10807 protected int getFadeHeight(boolean offsetRequired) { 10808 int padding = mPaddingTop; 10809 if (offsetRequired) padding += getTopPaddingOffset(); 10810 return mBottom - mTop - mPaddingBottom - padding; 10811 } 10812 10813 /** 10814 * <p>Indicates whether this view is attached to an hardware accelerated 10815 * window or not.</p> 10816 * 10817 * <p>Even if this method returns true, it does not mean that every call 10818 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 10819 * accelerated {@link android.graphics.Canvas}. For instance, if this view 10820 * is drawn onto an offscren {@link android.graphics.Bitmap} and its 10821 * window is hardware accelerated, 10822 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 10823 * return false, and this method will return true.</p> 10824 * 10825 * @return True if the view is attached to a window and the window is 10826 * hardware accelerated; false in any other case. 10827 */ 10828 public boolean isHardwareAccelerated() { 10829 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 10830 } 10831 10832 /** 10833 * Manually render this view (and all of its children) to the given Canvas. 10834 * The view must have already done a full layout before this function is 10835 * called. When implementing a view, implement 10836 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 10837 * If you do need to override this method, call the superclass version. 10838 * 10839 * @param canvas The Canvas to which the View is rendered. 10840 */ 10841 public void draw(Canvas canvas) { 10842 if (ViewDebug.TRACE_HIERARCHY) { 10843 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 10844 } 10845 10846 final int privateFlags = mPrivateFlags; 10847 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 10848 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 10849 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 10850 10851 /* 10852 * Draw traversal performs several drawing steps which must be executed 10853 * in the appropriate order: 10854 * 10855 * 1. Draw the background 10856 * 2. If necessary, save the canvas' layers to prepare for fading 10857 * 3. Draw view's content 10858 * 4. Draw children 10859 * 5. If necessary, draw the fading edges and restore layers 10860 * 6. Draw decorations (scrollbars for instance) 10861 */ 10862 10863 // Step 1, draw the background, if needed 10864 int saveCount; 10865 10866 if (!dirtyOpaque) { 10867 final Drawable background = mBGDrawable; 10868 if (background != null) { 10869 final int scrollX = mScrollX; 10870 final int scrollY = mScrollY; 10871 10872 if (mBackgroundSizeChanged) { 10873 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 10874 mBackgroundSizeChanged = false; 10875 } 10876 10877 if ((scrollX | scrollY) == 0) { 10878 background.draw(canvas); 10879 } else { 10880 canvas.translate(scrollX, scrollY); 10881 background.draw(canvas); 10882 canvas.translate(-scrollX, -scrollY); 10883 } 10884 } 10885 } 10886 10887 // skip step 2 & 5 if possible (common case) 10888 final int viewFlags = mViewFlags; 10889 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 10890 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 10891 if (!verticalEdges && !horizontalEdges) { 10892 // Step 3, draw the content 10893 if (!dirtyOpaque) onDraw(canvas); 10894 10895 // Step 4, draw the children 10896 dispatchDraw(canvas); 10897 10898 // Step 6, draw decorations (scrollbars) 10899 onDrawScrollBars(canvas); 10900 10901 // we're done... 10902 return; 10903 } 10904 10905 /* 10906 * Here we do the full fledged routine... 10907 * (this is an uncommon case where speed matters less, 10908 * this is why we repeat some of the tests that have been 10909 * done above) 10910 */ 10911 10912 boolean drawTop = false; 10913 boolean drawBottom = false; 10914 boolean drawLeft = false; 10915 boolean drawRight = false; 10916 10917 float topFadeStrength = 0.0f; 10918 float bottomFadeStrength = 0.0f; 10919 float leftFadeStrength = 0.0f; 10920 float rightFadeStrength = 0.0f; 10921 10922 // Step 2, save the canvas' layers 10923 int paddingLeft = mPaddingLeft; 10924 10925 final boolean offsetRequired = isPaddingOffsetRequired(); 10926 if (offsetRequired) { 10927 paddingLeft += getLeftPaddingOffset(); 10928 } 10929 10930 int left = mScrollX + paddingLeft; 10931 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 10932 int top = mScrollY + getFadeTop(offsetRequired); 10933 int bottom = top + getFadeHeight(offsetRequired); 10934 10935 if (offsetRequired) { 10936 right += getRightPaddingOffset(); 10937 bottom += getBottomPaddingOffset(); 10938 } 10939 10940 final ScrollabilityCache scrollabilityCache = mScrollCache; 10941 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 10942 int length = (int) fadeHeight; 10943 10944 // clip the fade length if top and bottom fades overlap 10945 // overlapping fades produce odd-looking artifacts 10946 if (verticalEdges && (top + length > bottom - length)) { 10947 length = (bottom - top) / 2; 10948 } 10949 10950 // also clip horizontal fades if necessary 10951 if (horizontalEdges && (left + length > right - length)) { 10952 length = (right - left) / 2; 10953 } 10954 10955 if (verticalEdges) { 10956 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 10957 drawTop = topFadeStrength * fadeHeight > 1.0f; 10958 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 10959 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 10960 } 10961 10962 if (horizontalEdges) { 10963 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 10964 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 10965 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 10966 drawRight = rightFadeStrength * fadeHeight > 1.0f; 10967 } 10968 10969 saveCount = canvas.getSaveCount(); 10970 10971 int solidColor = getSolidColor(); 10972 if (solidColor == 0) { 10973 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 10974 10975 if (drawTop) { 10976 canvas.saveLayer(left, top, right, top + length, null, flags); 10977 } 10978 10979 if (drawBottom) { 10980 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 10981 } 10982 10983 if (drawLeft) { 10984 canvas.saveLayer(left, top, left + length, bottom, null, flags); 10985 } 10986 10987 if (drawRight) { 10988 canvas.saveLayer(right - length, top, right, bottom, null, flags); 10989 } 10990 } else { 10991 scrollabilityCache.setFadeColor(solidColor); 10992 } 10993 10994 // Step 3, draw the content 10995 if (!dirtyOpaque) onDraw(canvas); 10996 10997 // Step 4, draw the children 10998 dispatchDraw(canvas); 10999 11000 // Step 5, draw the fade effect and restore layers 11001 final Paint p = scrollabilityCache.paint; 11002 final Matrix matrix = scrollabilityCache.matrix; 11003 final Shader fade = scrollabilityCache.shader; 11004 11005 if (drawTop) { 11006 matrix.setScale(1, fadeHeight * topFadeStrength); 11007 matrix.postTranslate(left, top); 11008 fade.setLocalMatrix(matrix); 11009 canvas.drawRect(left, top, right, top + length, p); 11010 } 11011 11012 if (drawBottom) { 11013 matrix.setScale(1, fadeHeight * bottomFadeStrength); 11014 matrix.postRotate(180); 11015 matrix.postTranslate(left, bottom); 11016 fade.setLocalMatrix(matrix); 11017 canvas.drawRect(left, bottom - length, right, bottom, p); 11018 } 11019 11020 if (drawLeft) { 11021 matrix.setScale(1, fadeHeight * leftFadeStrength); 11022 matrix.postRotate(-90); 11023 matrix.postTranslate(left, top); 11024 fade.setLocalMatrix(matrix); 11025 canvas.drawRect(left, top, left + length, bottom, p); 11026 } 11027 11028 if (drawRight) { 11029 matrix.setScale(1, fadeHeight * rightFadeStrength); 11030 matrix.postRotate(90); 11031 matrix.postTranslate(right, top); 11032 fade.setLocalMatrix(matrix); 11033 canvas.drawRect(right - length, top, right, bottom, p); 11034 } 11035 11036 canvas.restoreToCount(saveCount); 11037 11038 // Step 6, draw decorations (scrollbars) 11039 onDrawScrollBars(canvas); 11040 } 11041 11042 /** 11043 * Override this if your view is known to always be drawn on top of a solid color background, 11044 * and needs to draw fading edges. Returning a non-zero color enables the view system to 11045 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 11046 * should be set to 0xFF. 11047 * 11048 * @see #setVerticalFadingEdgeEnabled(boolean) 11049 * @see #setHorizontalFadingEdgeEnabled(boolean) 11050 * 11051 * @return The known solid color background for this view, or 0 if the color may vary 11052 */ 11053 @ViewDebug.ExportedProperty(category = "drawing") 11054 public int getSolidColor() { 11055 return 0; 11056 } 11057 11058 /** 11059 * Build a human readable string representation of the specified view flags. 11060 * 11061 * @param flags the view flags to convert to a string 11062 * @return a String representing the supplied flags 11063 */ 11064 private static String printFlags(int flags) { 11065 String output = ""; 11066 int numFlags = 0; 11067 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 11068 output += "TAKES_FOCUS"; 11069 numFlags++; 11070 } 11071 11072 switch (flags & VISIBILITY_MASK) { 11073 case INVISIBLE: 11074 if (numFlags > 0) { 11075 output += " "; 11076 } 11077 output += "INVISIBLE"; 11078 // USELESS HERE numFlags++; 11079 break; 11080 case GONE: 11081 if (numFlags > 0) { 11082 output += " "; 11083 } 11084 output += "GONE"; 11085 // USELESS HERE numFlags++; 11086 break; 11087 default: 11088 break; 11089 } 11090 return output; 11091 } 11092 11093 /** 11094 * Build a human readable string representation of the specified private 11095 * view flags. 11096 * 11097 * @param privateFlags the private view flags to convert to a string 11098 * @return a String representing the supplied flags 11099 */ 11100 private static String printPrivateFlags(int privateFlags) { 11101 String output = ""; 11102 int numFlags = 0; 11103 11104 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 11105 output += "WANTS_FOCUS"; 11106 numFlags++; 11107 } 11108 11109 if ((privateFlags & FOCUSED) == FOCUSED) { 11110 if (numFlags > 0) { 11111 output += " "; 11112 } 11113 output += "FOCUSED"; 11114 numFlags++; 11115 } 11116 11117 if ((privateFlags & SELECTED) == SELECTED) { 11118 if (numFlags > 0) { 11119 output += " "; 11120 } 11121 output += "SELECTED"; 11122 numFlags++; 11123 } 11124 11125 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 11126 if (numFlags > 0) { 11127 output += " "; 11128 } 11129 output += "IS_ROOT_NAMESPACE"; 11130 numFlags++; 11131 } 11132 11133 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 11134 if (numFlags > 0) { 11135 output += " "; 11136 } 11137 output += "HAS_BOUNDS"; 11138 numFlags++; 11139 } 11140 11141 if ((privateFlags & DRAWN) == DRAWN) { 11142 if (numFlags > 0) { 11143 output += " "; 11144 } 11145 output += "DRAWN"; 11146 // USELESS HERE numFlags++; 11147 } 11148 return output; 11149 } 11150 11151 /** 11152 * <p>Indicates whether or not this view's layout will be requested during 11153 * the next hierarchy layout pass.</p> 11154 * 11155 * @return true if the layout will be forced during next layout pass 11156 */ 11157 public boolean isLayoutRequested() { 11158 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 11159 } 11160 11161 /** 11162 * Assign a size and position to a view and all of its 11163 * descendants 11164 * 11165 * <p>This is the second phase of the layout mechanism. 11166 * (The first is measuring). In this phase, each parent calls 11167 * layout on all of its children to position them. 11168 * This is typically done using the child measurements 11169 * that were stored in the measure pass().</p> 11170 * 11171 * <p>Derived classes should not override this method. 11172 * Derived classes with children should override 11173 * onLayout. In that method, they should 11174 * call layout on each of their children.</p> 11175 * 11176 * @param l Left position, relative to parent 11177 * @param t Top position, relative to parent 11178 * @param r Right position, relative to parent 11179 * @param b Bottom position, relative to parent 11180 */ 11181 @SuppressWarnings({"unchecked"}) 11182 public void layout(int l, int t, int r, int b) { 11183 int oldL = mLeft; 11184 int oldT = mTop; 11185 int oldB = mBottom; 11186 int oldR = mRight; 11187 boolean changed = setFrame(l, t, r, b); 11188 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 11189 if (ViewDebug.TRACE_HIERARCHY) { 11190 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 11191 } 11192 11193 onLayout(changed, l, t, r, b); 11194 mPrivateFlags &= ~LAYOUT_REQUIRED; 11195 11196 if (mOnLayoutChangeListeners != null) { 11197 ArrayList<OnLayoutChangeListener> listenersCopy = 11198 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone(); 11199 int numListeners = listenersCopy.size(); 11200 for (int i = 0; i < numListeners; ++i) { 11201 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 11202 } 11203 } 11204 } 11205 mPrivateFlags &= ~FORCE_LAYOUT; 11206 } 11207 11208 /** 11209 * Called from layout when this view should 11210 * assign a size and position to each of its children. 11211 * 11212 * Derived classes with children should override 11213 * this method and call layout on each of 11214 * their children. 11215 * @param changed This is a new size or position for this view 11216 * @param left Left position, relative to parent 11217 * @param top Top position, relative to parent 11218 * @param right Right position, relative to parent 11219 * @param bottom Bottom position, relative to parent 11220 */ 11221 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 11222 } 11223 11224 /** 11225 * Assign a size and position to this view. 11226 * 11227 * This is called from layout. 11228 * 11229 * @param left Left position, relative to parent 11230 * @param top Top position, relative to parent 11231 * @param right Right position, relative to parent 11232 * @param bottom Bottom position, relative to parent 11233 * @return true if the new size and position are different than the 11234 * previous ones 11235 * {@hide} 11236 */ 11237 protected boolean setFrame(int left, int top, int right, int bottom) { 11238 boolean changed = false; 11239 11240 if (DBG) { 11241 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 11242 + right + "," + bottom + ")"); 11243 } 11244 11245 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 11246 changed = true; 11247 11248 // Remember our drawn bit 11249 int drawn = mPrivateFlags & DRAWN; 11250 11251 int oldWidth = mRight - mLeft; 11252 int oldHeight = mBottom - mTop; 11253 int newWidth = right - left; 11254 int newHeight = bottom - top; 11255 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 11256 11257 // Invalidate our old position 11258 invalidate(sizeChanged); 11259 11260 mLeft = left; 11261 mTop = top; 11262 mRight = right; 11263 mBottom = bottom; 11264 11265 mPrivateFlags |= HAS_BOUNDS; 11266 11267 11268 if (sizeChanged) { 11269 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 11270 // A change in dimension means an auto-centered pivot point changes, too 11271 if (mTransformationInfo != null) { 11272 mTransformationInfo.mMatrixDirty = true; 11273 } 11274 } 11275 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 11276 } 11277 11278 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 11279 // If we are visible, force the DRAWN bit to on so that 11280 // this invalidate will go through (at least to our parent). 11281 // This is because someone may have invalidated this view 11282 // before this call to setFrame came in, thereby clearing 11283 // the DRAWN bit. 11284 mPrivateFlags |= DRAWN; 11285 invalidate(sizeChanged); 11286 // parent display list may need to be recreated based on a change in the bounds 11287 // of any child 11288 invalidateParentCaches(); 11289 } 11290 11291 // Reset drawn bit to original value (invalidate turns it off) 11292 mPrivateFlags |= drawn; 11293 11294 mBackgroundSizeChanged = true; 11295 } 11296 return changed; 11297 } 11298 11299 /** 11300 * Finalize inflating a view from XML. This is called as the last phase 11301 * of inflation, after all child views have been added. 11302 * 11303 * <p>Even if the subclass overrides onFinishInflate, they should always be 11304 * sure to call the super method, so that we get called. 11305 */ 11306 protected void onFinishInflate() { 11307 } 11308 11309 /** 11310 * Returns the resources associated with this view. 11311 * 11312 * @return Resources object. 11313 */ 11314 public Resources getResources() { 11315 return mResources; 11316 } 11317 11318 /** 11319 * Invalidates the specified Drawable. 11320 * 11321 * @param drawable the drawable to invalidate 11322 */ 11323 public void invalidateDrawable(Drawable drawable) { 11324 if (verifyDrawable(drawable)) { 11325 final Rect dirty = drawable.getBounds(); 11326 final int scrollX = mScrollX; 11327 final int scrollY = mScrollY; 11328 11329 invalidate(dirty.left + scrollX, dirty.top + scrollY, 11330 dirty.right + scrollX, dirty.bottom + scrollY); 11331 } 11332 } 11333 11334 /** 11335 * Schedules an action on a drawable to occur at a specified time. 11336 * 11337 * @param who the recipient of the action 11338 * @param what the action to run on the drawable 11339 * @param when the time at which the action must occur. Uses the 11340 * {@link SystemClock#uptimeMillis} timebase. 11341 */ 11342 public void scheduleDrawable(Drawable who, Runnable what, long when) { 11343 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 11344 mAttachInfo.mHandler.postAtTime(what, who, when); 11345 } 11346 } 11347 11348 /** 11349 * Cancels a scheduled action on a drawable. 11350 * 11351 * @param who the recipient of the action 11352 * @param what the action to cancel 11353 */ 11354 public void unscheduleDrawable(Drawable who, Runnable what) { 11355 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 11356 mAttachInfo.mHandler.removeCallbacks(what, who); 11357 } 11358 } 11359 11360 /** 11361 * Unschedule any events associated with the given Drawable. This can be 11362 * used when selecting a new Drawable into a view, so that the previous 11363 * one is completely unscheduled. 11364 * 11365 * @param who The Drawable to unschedule. 11366 * 11367 * @see #drawableStateChanged 11368 */ 11369 public void unscheduleDrawable(Drawable who) { 11370 if (mAttachInfo != null) { 11371 mAttachInfo.mHandler.removeCallbacksAndMessages(who); 11372 } 11373 } 11374 11375 /** 11376 * Return the layout direction of a given Drawable. 11377 * 11378 * @param who the Drawable to query 11379 * 11380 * @hide 11381 */ 11382 public int getResolvedLayoutDirection(Drawable who) { 11383 return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT; 11384 } 11385 11386 /** 11387 * If your view subclass is displaying its own Drawable objects, it should 11388 * override this function and return true for any Drawable it is 11389 * displaying. This allows animations for those drawables to be 11390 * scheduled. 11391 * 11392 * <p>Be sure to call through to the super class when overriding this 11393 * function. 11394 * 11395 * @param who The Drawable to verify. Return true if it is one you are 11396 * displaying, else return the result of calling through to the 11397 * super class. 11398 * 11399 * @return boolean If true than the Drawable is being displayed in the 11400 * view; else false and it is not allowed to animate. 11401 * 11402 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 11403 * @see #drawableStateChanged() 11404 */ 11405 protected boolean verifyDrawable(Drawable who) { 11406 return who == mBGDrawable; 11407 } 11408 11409 /** 11410 * This function is called whenever the state of the view changes in such 11411 * a way that it impacts the state of drawables being shown. 11412 * 11413 * <p>Be sure to call through to the superclass when overriding this 11414 * function. 11415 * 11416 * @see Drawable#setState(int[]) 11417 */ 11418 protected void drawableStateChanged() { 11419 Drawable d = mBGDrawable; 11420 if (d != null && d.isStateful()) { 11421 d.setState(getDrawableState()); 11422 } 11423 } 11424 11425 /** 11426 * Call this to force a view to update its drawable state. This will cause 11427 * drawableStateChanged to be called on this view. Views that are interested 11428 * in the new state should call getDrawableState. 11429 * 11430 * @see #drawableStateChanged 11431 * @see #getDrawableState 11432 */ 11433 public void refreshDrawableState() { 11434 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 11435 drawableStateChanged(); 11436 11437 ViewParent parent = mParent; 11438 if (parent != null) { 11439 parent.childDrawableStateChanged(this); 11440 } 11441 } 11442 11443 /** 11444 * Return an array of resource IDs of the drawable states representing the 11445 * current state of the view. 11446 * 11447 * @return The current drawable state 11448 * 11449 * @see Drawable#setState(int[]) 11450 * @see #drawableStateChanged() 11451 * @see #onCreateDrawableState(int) 11452 */ 11453 public final int[] getDrawableState() { 11454 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 11455 return mDrawableState; 11456 } else { 11457 mDrawableState = onCreateDrawableState(0); 11458 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 11459 return mDrawableState; 11460 } 11461 } 11462 11463 /** 11464 * Generate the new {@link android.graphics.drawable.Drawable} state for 11465 * this view. This is called by the view 11466 * system when the cached Drawable state is determined to be invalid. To 11467 * retrieve the current state, you should use {@link #getDrawableState}. 11468 * 11469 * @param extraSpace if non-zero, this is the number of extra entries you 11470 * would like in the returned array in which you can place your own 11471 * states. 11472 * 11473 * @return Returns an array holding the current {@link Drawable} state of 11474 * the view. 11475 * 11476 * @see #mergeDrawableStates(int[], int[]) 11477 */ 11478 protected int[] onCreateDrawableState(int extraSpace) { 11479 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 11480 mParent instanceof View) { 11481 return ((View) mParent).onCreateDrawableState(extraSpace); 11482 } 11483 11484 int[] drawableState; 11485 11486 int privateFlags = mPrivateFlags; 11487 11488 int viewStateIndex = 0; 11489 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 11490 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 11491 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 11492 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 11493 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 11494 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 11495 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 11496 HardwareRenderer.isAvailable()) { 11497 // This is set if HW acceleration is requested, even if the current 11498 // process doesn't allow it. This is just to allow app preview 11499 // windows to better match their app. 11500 viewStateIndex |= VIEW_STATE_ACCELERATED; 11501 } 11502 if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 11503 11504 final int privateFlags2 = mPrivateFlags2; 11505 if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 11506 if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 11507 11508 drawableState = VIEW_STATE_SETS[viewStateIndex]; 11509 11510 //noinspection ConstantIfStatement 11511 if (false) { 11512 Log.i("View", "drawableStateIndex=" + viewStateIndex); 11513 Log.i("View", toString() 11514 + " pressed=" + ((privateFlags & PRESSED) != 0) 11515 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 11516 + " fo=" + hasFocus() 11517 + " sl=" + ((privateFlags & SELECTED) != 0) 11518 + " wf=" + hasWindowFocus() 11519 + ": " + Arrays.toString(drawableState)); 11520 } 11521 11522 if (extraSpace == 0) { 11523 return drawableState; 11524 } 11525 11526 final int[] fullState; 11527 if (drawableState != null) { 11528 fullState = new int[drawableState.length + extraSpace]; 11529 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 11530 } else { 11531 fullState = new int[extraSpace]; 11532 } 11533 11534 return fullState; 11535 } 11536 11537 /** 11538 * Merge your own state values in <var>additionalState</var> into the base 11539 * state values <var>baseState</var> that were returned by 11540 * {@link #onCreateDrawableState(int)}. 11541 * 11542 * @param baseState The base state values returned by 11543 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 11544 * own additional state values. 11545 * 11546 * @param additionalState The additional state values you would like 11547 * added to <var>baseState</var>; this array is not modified. 11548 * 11549 * @return As a convenience, the <var>baseState</var> array you originally 11550 * passed into the function is returned. 11551 * 11552 * @see #onCreateDrawableState(int) 11553 */ 11554 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 11555 final int N = baseState.length; 11556 int i = N - 1; 11557 while (i >= 0 && baseState[i] == 0) { 11558 i--; 11559 } 11560 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 11561 return baseState; 11562 } 11563 11564 /** 11565 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 11566 * on all Drawable objects associated with this view. 11567 */ 11568 public void jumpDrawablesToCurrentState() { 11569 if (mBGDrawable != null) { 11570 mBGDrawable.jumpToCurrentState(); 11571 } 11572 } 11573 11574 /** 11575 * Sets the background color for this view. 11576 * @param color the color of the background 11577 */ 11578 @RemotableViewMethod 11579 public void setBackgroundColor(int color) { 11580 if (mBGDrawable instanceof ColorDrawable) { 11581 ((ColorDrawable) mBGDrawable).setColor(color); 11582 } else { 11583 setBackgroundDrawable(new ColorDrawable(color)); 11584 } 11585 } 11586 11587 /** 11588 * Set the background to a given resource. The resource should refer to 11589 * a Drawable object or 0 to remove the background. 11590 * @param resid The identifier of the resource. 11591 * @attr ref android.R.styleable#View_background 11592 */ 11593 @RemotableViewMethod 11594 public void setBackgroundResource(int resid) { 11595 if (resid != 0 && resid == mBackgroundResource) { 11596 return; 11597 } 11598 11599 Drawable d= null; 11600 if (resid != 0) { 11601 d = mResources.getDrawable(resid); 11602 } 11603 setBackgroundDrawable(d); 11604 11605 mBackgroundResource = resid; 11606 } 11607 11608 /** 11609 * Set the background to a given Drawable, or remove the background. If the 11610 * background has padding, this View's padding is set to the background's 11611 * padding. However, when a background is removed, this View's padding isn't 11612 * touched. If setting the padding is desired, please use 11613 * {@link #setPadding(int, int, int, int)}. 11614 * 11615 * @param d The Drawable to use as the background, or null to remove the 11616 * background 11617 */ 11618 public void setBackgroundDrawable(Drawable d) { 11619 if (d == mBGDrawable) { 11620 return; 11621 } 11622 11623 boolean requestLayout = false; 11624 11625 mBackgroundResource = 0; 11626 11627 /* 11628 * Regardless of whether we're setting a new background or not, we want 11629 * to clear the previous drawable. 11630 */ 11631 if (mBGDrawable != null) { 11632 mBGDrawable.setCallback(null); 11633 unscheduleDrawable(mBGDrawable); 11634 } 11635 11636 if (d != null) { 11637 Rect padding = sThreadLocal.get(); 11638 if (padding == null) { 11639 padding = new Rect(); 11640 sThreadLocal.set(padding); 11641 } 11642 if (d.getPadding(padding)) { 11643 switch (d.getResolvedLayoutDirectionSelf()) { 11644 case LAYOUT_DIRECTION_RTL: 11645 setPadding(padding.right, padding.top, padding.left, padding.bottom); 11646 break; 11647 case LAYOUT_DIRECTION_LTR: 11648 default: 11649 setPadding(padding.left, padding.top, padding.right, padding.bottom); 11650 } 11651 } 11652 11653 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 11654 // if it has a different minimum size, we should layout again 11655 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 11656 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 11657 requestLayout = true; 11658 } 11659 11660 d.setCallback(this); 11661 if (d.isStateful()) { 11662 d.setState(getDrawableState()); 11663 } 11664 d.setVisible(getVisibility() == VISIBLE, false); 11665 mBGDrawable = d; 11666 11667 if ((mPrivateFlags & SKIP_DRAW) != 0) { 11668 mPrivateFlags &= ~SKIP_DRAW; 11669 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 11670 requestLayout = true; 11671 } 11672 } else { 11673 /* Remove the background */ 11674 mBGDrawable = null; 11675 11676 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 11677 /* 11678 * This view ONLY drew the background before and we're removing 11679 * the background, so now it won't draw anything 11680 * (hence we SKIP_DRAW) 11681 */ 11682 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 11683 mPrivateFlags |= SKIP_DRAW; 11684 } 11685 11686 /* 11687 * When the background is set, we try to apply its padding to this 11688 * View. When the background is removed, we don't touch this View's 11689 * padding. This is noted in the Javadocs. Hence, we don't need to 11690 * requestLayout(), the invalidate() below is sufficient. 11691 */ 11692 11693 // The old background's minimum size could have affected this 11694 // View's layout, so let's requestLayout 11695 requestLayout = true; 11696 } 11697 11698 computeOpaqueFlags(); 11699 11700 if (requestLayout) { 11701 requestLayout(); 11702 } 11703 11704 mBackgroundSizeChanged = true; 11705 invalidate(true); 11706 } 11707 11708 /** 11709 * Gets the background drawable 11710 * @return The drawable used as the background for this view, if any. 11711 */ 11712 public Drawable getBackground() { 11713 return mBGDrawable; 11714 } 11715 11716 /** 11717 * Sets the padding. The view may add on the space required to display 11718 * the scrollbars, depending on the style and visibility of the scrollbars. 11719 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 11720 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 11721 * from the values set in this call. 11722 * 11723 * @attr ref android.R.styleable#View_padding 11724 * @attr ref android.R.styleable#View_paddingBottom 11725 * @attr ref android.R.styleable#View_paddingLeft 11726 * @attr ref android.R.styleable#View_paddingRight 11727 * @attr ref android.R.styleable#View_paddingTop 11728 * @param left the left padding in pixels 11729 * @param top the top padding in pixels 11730 * @param right the right padding in pixels 11731 * @param bottom the bottom padding in pixels 11732 */ 11733 public void setPadding(int left, int top, int right, int bottom) { 11734 boolean changed = false; 11735 11736 mUserPaddingRelative = false; 11737 11738 mUserPaddingLeft = left; 11739 mUserPaddingRight = right; 11740 mUserPaddingBottom = bottom; 11741 11742 final int viewFlags = mViewFlags; 11743 11744 // Common case is there are no scroll bars. 11745 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 11746 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 11747 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 11748 ? 0 : getVerticalScrollbarWidth(); 11749 switch (mVerticalScrollbarPosition) { 11750 case SCROLLBAR_POSITION_DEFAULT: 11751 if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 11752 left += offset; 11753 } else { 11754 right += offset; 11755 } 11756 break; 11757 case SCROLLBAR_POSITION_RIGHT: 11758 right += offset; 11759 break; 11760 case SCROLLBAR_POSITION_LEFT: 11761 left += offset; 11762 break; 11763 } 11764 } 11765 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 11766 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 11767 ? 0 : getHorizontalScrollbarHeight(); 11768 } 11769 } 11770 11771 if (mPaddingLeft != left) { 11772 changed = true; 11773 mPaddingLeft = left; 11774 } 11775 if (mPaddingTop != top) { 11776 changed = true; 11777 mPaddingTop = top; 11778 } 11779 if (mPaddingRight != right) { 11780 changed = true; 11781 mPaddingRight = right; 11782 } 11783 if (mPaddingBottom != bottom) { 11784 changed = true; 11785 mPaddingBottom = bottom; 11786 } 11787 11788 if (changed) { 11789 requestLayout(); 11790 } 11791 } 11792 11793 /** 11794 * Sets the relative padding. The view may add on the space required to display 11795 * the scrollbars, depending on the style and visibility of the scrollbars. 11796 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 11797 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 11798 * from the values set in this call. 11799 * 11800 * @attr ref android.R.styleable#View_padding 11801 * @attr ref android.R.styleable#View_paddingBottom 11802 * @attr ref android.R.styleable#View_paddingStart 11803 * @attr ref android.R.styleable#View_paddingEnd 11804 * @attr ref android.R.styleable#View_paddingTop 11805 * @param start the start padding in pixels 11806 * @param top the top padding in pixels 11807 * @param end the end padding in pixels 11808 * @param bottom the bottom padding in pixels 11809 * 11810 * @hide 11811 */ 11812 public void setPaddingRelative(int start, int top, int end, int bottom) { 11813 mUserPaddingRelative = true; 11814 11815 mUserPaddingStart = start; 11816 mUserPaddingEnd = end; 11817 11818 switch(getResolvedLayoutDirection()) { 11819 case LAYOUT_DIRECTION_RTL: 11820 setPadding(end, top, start, bottom); 11821 break; 11822 case LAYOUT_DIRECTION_LTR: 11823 default: 11824 setPadding(start, top, end, bottom); 11825 } 11826 } 11827 11828 /** 11829 * Returns the top padding of this view. 11830 * 11831 * @return the top padding in pixels 11832 */ 11833 public int getPaddingTop() { 11834 return mPaddingTop; 11835 } 11836 11837 /** 11838 * Returns the bottom padding of this view. If there are inset and enabled 11839 * scrollbars, this value may include the space required to display the 11840 * scrollbars as well. 11841 * 11842 * @return the bottom padding in pixels 11843 */ 11844 public int getPaddingBottom() { 11845 return mPaddingBottom; 11846 } 11847 11848 /** 11849 * Returns the left padding of this view. If there are inset and enabled 11850 * scrollbars, this value may include the space required to display the 11851 * scrollbars as well. 11852 * 11853 * @return the left padding in pixels 11854 */ 11855 public int getPaddingLeft() { 11856 return mPaddingLeft; 11857 } 11858 11859 /** 11860 * Returns the start padding of this view. If there are inset and enabled 11861 * scrollbars, this value may include the space required to display the 11862 * scrollbars as well. 11863 * 11864 * @return the start padding in pixels 11865 * 11866 * @hide 11867 */ 11868 public int getPaddingStart() { 11869 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 11870 mPaddingRight : mPaddingLeft; 11871 } 11872 11873 /** 11874 * Returns the right padding of this view. If there are inset and enabled 11875 * scrollbars, this value may include the space required to display the 11876 * scrollbars as well. 11877 * 11878 * @return the right padding in pixels 11879 */ 11880 public int getPaddingRight() { 11881 return mPaddingRight; 11882 } 11883 11884 /** 11885 * Returns the end padding of this view. If there are inset and enabled 11886 * scrollbars, this value may include the space required to display the 11887 * scrollbars as well. 11888 * 11889 * @return the end padding in pixels 11890 * 11891 * @hide 11892 */ 11893 public int getPaddingEnd() { 11894 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 11895 mPaddingLeft : mPaddingRight; 11896 } 11897 11898 /** 11899 * Return if the padding as been set thru relative values 11900 * {@link #setPaddingRelative(int, int, int, int)} or thru 11901 * @attr ref android.R.styleable#View_paddingStart or 11902 * @attr ref android.R.styleable#View_paddingEnd 11903 * 11904 * @return true if the padding is relative or false if it is not. 11905 * 11906 * @hide 11907 */ 11908 public boolean isPaddingRelative() { 11909 return mUserPaddingRelative; 11910 } 11911 11912 /** 11913 * Changes the selection state of this view. A view can be selected or not. 11914 * Note that selection is not the same as focus. Views are typically 11915 * selected in the context of an AdapterView like ListView or GridView; 11916 * the selected view is the view that is highlighted. 11917 * 11918 * @param selected true if the view must be selected, false otherwise 11919 */ 11920 public void setSelected(boolean selected) { 11921 if (((mPrivateFlags & SELECTED) != 0) != selected) { 11922 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 11923 if (!selected) resetPressedState(); 11924 invalidate(true); 11925 refreshDrawableState(); 11926 dispatchSetSelected(selected); 11927 } 11928 } 11929 11930 /** 11931 * Dispatch setSelected to all of this View's children. 11932 * 11933 * @see #setSelected(boolean) 11934 * 11935 * @param selected The new selected state 11936 */ 11937 protected void dispatchSetSelected(boolean selected) { 11938 } 11939 11940 /** 11941 * Indicates the selection state of this view. 11942 * 11943 * @return true if the view is selected, false otherwise 11944 */ 11945 @ViewDebug.ExportedProperty 11946 public boolean isSelected() { 11947 return (mPrivateFlags & SELECTED) != 0; 11948 } 11949 11950 /** 11951 * Changes the activated state of this view. A view can be activated or not. 11952 * Note that activation is not the same as selection. Selection is 11953 * a transient property, representing the view (hierarchy) the user is 11954 * currently interacting with. Activation is a longer-term state that the 11955 * user can move views in and out of. For example, in a list view with 11956 * single or multiple selection enabled, the views in the current selection 11957 * set are activated. (Um, yeah, we are deeply sorry about the terminology 11958 * here.) The activated state is propagated down to children of the view it 11959 * is set on. 11960 * 11961 * @param activated true if the view must be activated, false otherwise 11962 */ 11963 public void setActivated(boolean activated) { 11964 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 11965 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 11966 invalidate(true); 11967 refreshDrawableState(); 11968 dispatchSetActivated(activated); 11969 } 11970 } 11971 11972 /** 11973 * Dispatch setActivated to all of this View's children. 11974 * 11975 * @see #setActivated(boolean) 11976 * 11977 * @param activated The new activated state 11978 */ 11979 protected void dispatchSetActivated(boolean activated) { 11980 } 11981 11982 /** 11983 * Indicates the activation state of this view. 11984 * 11985 * @return true if the view is activated, false otherwise 11986 */ 11987 @ViewDebug.ExportedProperty 11988 public boolean isActivated() { 11989 return (mPrivateFlags & ACTIVATED) != 0; 11990 } 11991 11992 /** 11993 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 11994 * observer can be used to get notifications when global events, like 11995 * layout, happen. 11996 * 11997 * The returned ViewTreeObserver observer is not guaranteed to remain 11998 * valid for the lifetime of this View. If the caller of this method keeps 11999 * a long-lived reference to ViewTreeObserver, it should always check for 12000 * the return value of {@link ViewTreeObserver#isAlive()}. 12001 * 12002 * @return The ViewTreeObserver for this view's hierarchy. 12003 */ 12004 public ViewTreeObserver getViewTreeObserver() { 12005 if (mAttachInfo != null) { 12006 return mAttachInfo.mTreeObserver; 12007 } 12008 if (mFloatingTreeObserver == null) { 12009 mFloatingTreeObserver = new ViewTreeObserver(); 12010 } 12011 return mFloatingTreeObserver; 12012 } 12013 12014 /** 12015 * <p>Finds the topmost view in the current view hierarchy.</p> 12016 * 12017 * @return the topmost view containing this view 12018 */ 12019 public View getRootView() { 12020 if (mAttachInfo != null) { 12021 final View v = mAttachInfo.mRootView; 12022 if (v != null) { 12023 return v; 12024 } 12025 } 12026 12027 View parent = this; 12028 12029 while (parent.mParent != null && parent.mParent instanceof View) { 12030 parent = (View) parent.mParent; 12031 } 12032 12033 return parent; 12034 } 12035 12036 /** 12037 * <p>Computes the coordinates of this view on the screen. The argument 12038 * must be an array of two integers. After the method returns, the array 12039 * contains the x and y location in that order.</p> 12040 * 12041 * @param location an array of two integers in which to hold the coordinates 12042 */ 12043 public void getLocationOnScreen(int[] location) { 12044 getLocationInWindow(location); 12045 12046 final AttachInfo info = mAttachInfo; 12047 if (info != null) { 12048 location[0] += info.mWindowLeft; 12049 location[1] += info.mWindowTop; 12050 } 12051 } 12052 12053 /** 12054 * <p>Computes the coordinates of this view in its window. The argument 12055 * must be an array of two integers. After the method returns, the array 12056 * contains the x and y location in that order.</p> 12057 * 12058 * @param location an array of two integers in which to hold the coordinates 12059 */ 12060 public void getLocationInWindow(int[] location) { 12061 if (location == null || location.length < 2) { 12062 throw new IllegalArgumentException("location must be an array of " 12063 + "two integers"); 12064 } 12065 12066 location[0] = mLeft; 12067 location[1] = mTop; 12068 if (mTransformationInfo != null) { 12069 location[0] += (int) (mTransformationInfo.mTranslationX + 0.5f); 12070 location[1] += (int) (mTransformationInfo.mTranslationY + 0.5f); 12071 } 12072 12073 ViewParent viewParent = mParent; 12074 while (viewParent instanceof View) { 12075 final View view = (View)viewParent; 12076 location[0] += view.mLeft - view.mScrollX; 12077 location[1] += view.mTop - view.mScrollY; 12078 if (view.mTransformationInfo != null) { 12079 location[0] += (int) (view.mTransformationInfo.mTranslationX + 0.5f); 12080 location[1] += (int) (view.mTransformationInfo.mTranslationY + 0.5f); 12081 } 12082 viewParent = view.mParent; 12083 } 12084 12085 if (viewParent instanceof ViewRootImpl) { 12086 // *cough* 12087 final ViewRootImpl vr = (ViewRootImpl)viewParent; 12088 location[1] -= vr.mCurScrollY; 12089 } 12090 } 12091 12092 /** 12093 * {@hide} 12094 * @param id the id of the view to be found 12095 * @return the view of the specified id, null if cannot be found 12096 */ 12097 protected View findViewTraversal(int id) { 12098 if (id == mID) { 12099 return this; 12100 } 12101 return null; 12102 } 12103 12104 /** 12105 * {@hide} 12106 * @param tag the tag of the view to be found 12107 * @return the view of specified tag, null if cannot be found 12108 */ 12109 protected View findViewWithTagTraversal(Object tag) { 12110 if (tag != null && tag.equals(mTag)) { 12111 return this; 12112 } 12113 return null; 12114 } 12115 12116 /** 12117 * {@hide} 12118 * @param predicate The predicate to evaluate. 12119 * @param childToSkip If not null, ignores this child during the recursive traversal. 12120 * @return The first view that matches the predicate or null. 12121 */ 12122 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 12123 if (predicate.apply(this)) { 12124 return this; 12125 } 12126 return null; 12127 } 12128 12129 /** 12130 * Look for a child view with the given id. If this view has the given 12131 * id, return this view. 12132 * 12133 * @param id The id to search for. 12134 * @return The view that has the given id in the hierarchy or null 12135 */ 12136 public final View findViewById(int id) { 12137 if (id < 0) { 12138 return null; 12139 } 12140 return findViewTraversal(id); 12141 } 12142 12143 /** 12144 * Finds a view by its unuque and stable accessibility id. 12145 * 12146 * @param accessibilityId The searched accessibility id. 12147 * @return The found view. 12148 */ 12149 final View findViewByAccessibilityId(int accessibilityId) { 12150 if (accessibilityId < 0) { 12151 return null; 12152 } 12153 return findViewByAccessibilityIdTraversal(accessibilityId); 12154 } 12155 12156 /** 12157 * Performs the traversal to find a view by its unuque and stable accessibility id. 12158 * 12159 * <strong>Note:</strong>This method does not stop at the root namespace 12160 * boundary since the user can touch the screen at an arbitrary location 12161 * potentially crossing the root namespace bounday which will send an 12162 * accessibility event to accessibility services and they should be able 12163 * to obtain the event source. Also accessibility ids are guaranteed to be 12164 * unique in the window. 12165 * 12166 * @param accessibilityId The accessibility id. 12167 * @return The found view. 12168 */ 12169 View findViewByAccessibilityIdTraversal(int accessibilityId) { 12170 if (getAccessibilityViewId() == accessibilityId) { 12171 return this; 12172 } 12173 return null; 12174 } 12175 12176 /** 12177 * Look for a child view with the given tag. If this view has the given 12178 * tag, return this view. 12179 * 12180 * @param tag The tag to search for, using "tag.equals(getTag())". 12181 * @return The View that has the given tag in the hierarchy or null 12182 */ 12183 public final View findViewWithTag(Object tag) { 12184 if (tag == null) { 12185 return null; 12186 } 12187 return findViewWithTagTraversal(tag); 12188 } 12189 12190 /** 12191 * {@hide} 12192 * Look for a child view that matches the specified predicate. 12193 * If this view matches the predicate, return this view. 12194 * 12195 * @param predicate The predicate to evaluate. 12196 * @return The first view that matches the predicate or null. 12197 */ 12198 public final View findViewByPredicate(Predicate<View> predicate) { 12199 return findViewByPredicateTraversal(predicate, null); 12200 } 12201 12202 /** 12203 * {@hide} 12204 * Look for a child view that matches the specified predicate, 12205 * starting with the specified view and its descendents and then 12206 * recusively searching the ancestors and siblings of that view 12207 * until this view is reached. 12208 * 12209 * This method is useful in cases where the predicate does not match 12210 * a single unique view (perhaps multiple views use the same id) 12211 * and we are trying to find the view that is "closest" in scope to the 12212 * starting view. 12213 * 12214 * @param start The view to start from. 12215 * @param predicate The predicate to evaluate. 12216 * @return The first view that matches the predicate or null. 12217 */ 12218 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 12219 View childToSkip = null; 12220 for (;;) { 12221 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 12222 if (view != null || start == this) { 12223 return view; 12224 } 12225 12226 ViewParent parent = start.getParent(); 12227 if (parent == null || !(parent instanceof View)) { 12228 return null; 12229 } 12230 12231 childToSkip = start; 12232 start = (View) parent; 12233 } 12234 } 12235 12236 /** 12237 * Sets the identifier for this view. The identifier does not have to be 12238 * unique in this view's hierarchy. The identifier should be a positive 12239 * number. 12240 * 12241 * @see #NO_ID 12242 * @see #getId() 12243 * @see #findViewById(int) 12244 * 12245 * @param id a number used to identify the view 12246 * 12247 * @attr ref android.R.styleable#View_id 12248 */ 12249 public void setId(int id) { 12250 mID = id; 12251 } 12252 12253 /** 12254 * {@hide} 12255 * 12256 * @param isRoot true if the view belongs to the root namespace, false 12257 * otherwise 12258 */ 12259 public void setIsRootNamespace(boolean isRoot) { 12260 if (isRoot) { 12261 mPrivateFlags |= IS_ROOT_NAMESPACE; 12262 } else { 12263 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 12264 } 12265 } 12266 12267 /** 12268 * {@hide} 12269 * 12270 * @return true if the view belongs to the root namespace, false otherwise 12271 */ 12272 public boolean isRootNamespace() { 12273 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 12274 } 12275 12276 /** 12277 * Returns this view's identifier. 12278 * 12279 * @return a positive integer used to identify the view or {@link #NO_ID} 12280 * if the view has no ID 12281 * 12282 * @see #setId(int) 12283 * @see #findViewById(int) 12284 * @attr ref android.R.styleable#View_id 12285 */ 12286 @ViewDebug.CapturedViewProperty 12287 public int getId() { 12288 return mID; 12289 } 12290 12291 /** 12292 * Returns this view's tag. 12293 * 12294 * @return the Object stored in this view as a tag 12295 * 12296 * @see #setTag(Object) 12297 * @see #getTag(int) 12298 */ 12299 @ViewDebug.ExportedProperty 12300 public Object getTag() { 12301 return mTag; 12302 } 12303 12304 /** 12305 * Sets the tag associated with this view. A tag can be used to mark 12306 * a view in its hierarchy and does not have to be unique within the 12307 * hierarchy. Tags can also be used to store data within a view without 12308 * resorting to another data structure. 12309 * 12310 * @param tag an Object to tag the view with 12311 * 12312 * @see #getTag() 12313 * @see #setTag(int, Object) 12314 */ 12315 public void setTag(final Object tag) { 12316 mTag = tag; 12317 } 12318 12319 /** 12320 * Returns the tag associated with this view and the specified key. 12321 * 12322 * @param key The key identifying the tag 12323 * 12324 * @return the Object stored in this view as a tag 12325 * 12326 * @see #setTag(int, Object) 12327 * @see #getTag() 12328 */ 12329 public Object getTag(int key) { 12330 if (mKeyedTags != null) return mKeyedTags.get(key); 12331 return null; 12332 } 12333 12334 /** 12335 * Sets a tag associated with this view and a key. A tag can be used 12336 * to mark a view in its hierarchy and does not have to be unique within 12337 * the hierarchy. Tags can also be used to store data within a view 12338 * without resorting to another data structure. 12339 * 12340 * The specified key should be an id declared in the resources of the 12341 * application to ensure it is unique (see the <a 12342 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 12343 * Keys identified as belonging to 12344 * the Android framework or not associated with any package will cause 12345 * an {@link IllegalArgumentException} to be thrown. 12346 * 12347 * @param key The key identifying the tag 12348 * @param tag An Object to tag the view with 12349 * 12350 * @throws IllegalArgumentException If they specified key is not valid 12351 * 12352 * @see #setTag(Object) 12353 * @see #getTag(int) 12354 */ 12355 public void setTag(int key, final Object tag) { 12356 // If the package id is 0x00 or 0x01, it's either an undefined package 12357 // or a framework id 12358 if ((key >>> 24) < 2) { 12359 throw new IllegalArgumentException("The key must be an application-specific " 12360 + "resource id."); 12361 } 12362 12363 setKeyedTag(key, tag); 12364 } 12365 12366 /** 12367 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 12368 * framework id. 12369 * 12370 * @hide 12371 */ 12372 public void setTagInternal(int key, Object tag) { 12373 if ((key >>> 24) != 0x1) { 12374 throw new IllegalArgumentException("The key must be a framework-specific " 12375 + "resource id."); 12376 } 12377 12378 setKeyedTag(key, tag); 12379 } 12380 12381 private void setKeyedTag(int key, Object tag) { 12382 if (mKeyedTags == null) { 12383 mKeyedTags = new SparseArray<Object>(); 12384 } 12385 12386 mKeyedTags.put(key, tag); 12387 } 12388 12389 /** 12390 * @param consistency The type of consistency. See ViewDebug for more information. 12391 * 12392 * @hide 12393 */ 12394 protected boolean dispatchConsistencyCheck(int consistency) { 12395 return onConsistencyCheck(consistency); 12396 } 12397 12398 /** 12399 * Method that subclasses should implement to check their consistency. The type of 12400 * consistency check is indicated by the bit field passed as a parameter. 12401 * 12402 * @param consistency The type of consistency. See ViewDebug for more information. 12403 * 12404 * @throws IllegalStateException if the view is in an inconsistent state. 12405 * 12406 * @hide 12407 */ 12408 protected boolean onConsistencyCheck(int consistency) { 12409 boolean result = true; 12410 12411 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 12412 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 12413 12414 if (checkLayout) { 12415 if (getParent() == null) { 12416 result = false; 12417 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12418 "View " + this + " does not have a parent."); 12419 } 12420 12421 if (mAttachInfo == null) { 12422 result = false; 12423 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12424 "View " + this + " is not attached to a window."); 12425 } 12426 } 12427 12428 if (checkDrawing) { 12429 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 12430 // from their draw() method 12431 12432 if ((mPrivateFlags & DRAWN) != DRAWN && 12433 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 12434 result = false; 12435 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12436 "View " + this + " was invalidated but its drawing cache is valid."); 12437 } 12438 } 12439 12440 return result; 12441 } 12442 12443 /** 12444 * Prints information about this view in the log output, with the tag 12445 * {@link #VIEW_LOG_TAG}. 12446 * 12447 * @hide 12448 */ 12449 public void debug() { 12450 debug(0); 12451 } 12452 12453 /** 12454 * Prints information about this view in the log output, with the tag 12455 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 12456 * indentation defined by the <code>depth</code>. 12457 * 12458 * @param depth the indentation level 12459 * 12460 * @hide 12461 */ 12462 protected void debug(int depth) { 12463 String output = debugIndent(depth - 1); 12464 12465 output += "+ " + this; 12466 int id = getId(); 12467 if (id != -1) { 12468 output += " (id=" + id + ")"; 12469 } 12470 Object tag = getTag(); 12471 if (tag != null) { 12472 output += " (tag=" + tag + ")"; 12473 } 12474 Log.d(VIEW_LOG_TAG, output); 12475 12476 if ((mPrivateFlags & FOCUSED) != 0) { 12477 output = debugIndent(depth) + " FOCUSED"; 12478 Log.d(VIEW_LOG_TAG, output); 12479 } 12480 12481 output = debugIndent(depth); 12482 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 12483 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 12484 + "} "; 12485 Log.d(VIEW_LOG_TAG, output); 12486 12487 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 12488 || mPaddingBottom != 0) { 12489 output = debugIndent(depth); 12490 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 12491 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 12492 Log.d(VIEW_LOG_TAG, output); 12493 } 12494 12495 output = debugIndent(depth); 12496 output += "mMeasureWidth=" + mMeasuredWidth + 12497 " mMeasureHeight=" + mMeasuredHeight; 12498 Log.d(VIEW_LOG_TAG, output); 12499 12500 output = debugIndent(depth); 12501 if (mLayoutParams == null) { 12502 output += "BAD! no layout params"; 12503 } else { 12504 output = mLayoutParams.debug(output); 12505 } 12506 Log.d(VIEW_LOG_TAG, output); 12507 12508 output = debugIndent(depth); 12509 output += "flags={"; 12510 output += View.printFlags(mViewFlags); 12511 output += "}"; 12512 Log.d(VIEW_LOG_TAG, output); 12513 12514 output = debugIndent(depth); 12515 output += "privateFlags={"; 12516 output += View.printPrivateFlags(mPrivateFlags); 12517 output += "}"; 12518 Log.d(VIEW_LOG_TAG, output); 12519 } 12520 12521 /** 12522 * Creates an string of whitespaces used for indentation. 12523 * 12524 * @param depth the indentation level 12525 * @return a String containing (depth * 2 + 3) * 2 white spaces 12526 * 12527 * @hide 12528 */ 12529 protected static String debugIndent(int depth) { 12530 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 12531 for (int i = 0; i < (depth * 2) + 3; i++) { 12532 spaces.append(' ').append(' '); 12533 } 12534 return spaces.toString(); 12535 } 12536 12537 /** 12538 * <p>Return the offset of the widget's text baseline from the widget's top 12539 * boundary. If this widget does not support baseline alignment, this 12540 * method returns -1. </p> 12541 * 12542 * @return the offset of the baseline within the widget's bounds or -1 12543 * if baseline alignment is not supported 12544 */ 12545 @ViewDebug.ExportedProperty(category = "layout") 12546 public int getBaseline() { 12547 return -1; 12548 } 12549 12550 /** 12551 * Call this when something has changed which has invalidated the 12552 * layout of this view. This will schedule a layout pass of the view 12553 * tree. 12554 */ 12555 public void requestLayout() { 12556 if (ViewDebug.TRACE_HIERARCHY) { 12557 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 12558 } 12559 12560 mPrivateFlags |= FORCE_LAYOUT; 12561 mPrivateFlags |= INVALIDATED; 12562 12563 if (mParent != null) { 12564 if (mLayoutParams != null) { 12565 mLayoutParams.resolveWithDirection(getResolvedLayoutDirection()); 12566 } 12567 if (!mParent.isLayoutRequested()) { 12568 mParent.requestLayout(); 12569 } 12570 } 12571 } 12572 12573 /** 12574 * Forces this view to be laid out during the next layout pass. 12575 * This method does not call requestLayout() or forceLayout() 12576 * on the parent. 12577 */ 12578 public void forceLayout() { 12579 mPrivateFlags |= FORCE_LAYOUT; 12580 mPrivateFlags |= INVALIDATED; 12581 } 12582 12583 /** 12584 * <p> 12585 * This is called to find out how big a view should be. The parent 12586 * supplies constraint information in the width and height parameters. 12587 * </p> 12588 * 12589 * <p> 12590 * The actual mesurement work of a view is performed in 12591 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 12592 * {@link #onMeasure(int, int)} can and must be overriden by subclasses. 12593 * </p> 12594 * 12595 * 12596 * @param widthMeasureSpec Horizontal space requirements as imposed by the 12597 * parent 12598 * @param heightMeasureSpec Vertical space requirements as imposed by the 12599 * parent 12600 * 12601 * @see #onMeasure(int, int) 12602 */ 12603 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 12604 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 12605 widthMeasureSpec != mOldWidthMeasureSpec || 12606 heightMeasureSpec != mOldHeightMeasureSpec) { 12607 12608 // first clears the measured dimension flag 12609 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 12610 12611 if (ViewDebug.TRACE_HIERARCHY) { 12612 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 12613 } 12614 12615 // measure ourselves, this should set the measured dimension flag back 12616 onMeasure(widthMeasureSpec, heightMeasureSpec); 12617 12618 // flag not set, setMeasuredDimension() was not invoked, we raise 12619 // an exception to warn the developer 12620 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 12621 throw new IllegalStateException("onMeasure() did not set the" 12622 + " measured dimension by calling" 12623 + " setMeasuredDimension()"); 12624 } 12625 12626 mPrivateFlags |= LAYOUT_REQUIRED; 12627 } 12628 12629 mOldWidthMeasureSpec = widthMeasureSpec; 12630 mOldHeightMeasureSpec = heightMeasureSpec; 12631 } 12632 12633 /** 12634 * <p> 12635 * Measure the view and its content to determine the measured width and the 12636 * measured height. This method is invoked by {@link #measure(int, int)} and 12637 * should be overriden by subclasses to provide accurate and efficient 12638 * measurement of their contents. 12639 * </p> 12640 * 12641 * <p> 12642 * <strong>CONTRACT:</strong> When overriding this method, you 12643 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 12644 * measured width and height of this view. Failure to do so will trigger an 12645 * <code>IllegalStateException</code>, thrown by 12646 * {@link #measure(int, int)}. Calling the superclass' 12647 * {@link #onMeasure(int, int)} is a valid use. 12648 * </p> 12649 * 12650 * <p> 12651 * The base class implementation of measure defaults to the background size, 12652 * unless a larger size is allowed by the MeasureSpec. Subclasses should 12653 * override {@link #onMeasure(int, int)} to provide better measurements of 12654 * their content. 12655 * </p> 12656 * 12657 * <p> 12658 * If this method is overridden, it is the subclass's responsibility to make 12659 * sure the measured height and width are at least the view's minimum height 12660 * and width ({@link #getSuggestedMinimumHeight()} and 12661 * {@link #getSuggestedMinimumWidth()}). 12662 * </p> 12663 * 12664 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 12665 * The requirements are encoded with 12666 * {@link android.view.View.MeasureSpec}. 12667 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 12668 * The requirements are encoded with 12669 * {@link android.view.View.MeasureSpec}. 12670 * 12671 * @see #getMeasuredWidth() 12672 * @see #getMeasuredHeight() 12673 * @see #setMeasuredDimension(int, int) 12674 * @see #getSuggestedMinimumHeight() 12675 * @see #getSuggestedMinimumWidth() 12676 * @see android.view.View.MeasureSpec#getMode(int) 12677 * @see android.view.View.MeasureSpec#getSize(int) 12678 */ 12679 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 12680 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 12681 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 12682 } 12683 12684 /** 12685 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 12686 * measured width and measured height. Failing to do so will trigger an 12687 * exception at measurement time.</p> 12688 * 12689 * @param measuredWidth The measured width of this view. May be a complex 12690 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 12691 * {@link #MEASURED_STATE_TOO_SMALL}. 12692 * @param measuredHeight The measured height of this view. May be a complex 12693 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 12694 * {@link #MEASURED_STATE_TOO_SMALL}. 12695 */ 12696 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 12697 mMeasuredWidth = measuredWidth; 12698 mMeasuredHeight = measuredHeight; 12699 12700 mPrivateFlags |= MEASURED_DIMENSION_SET; 12701 } 12702 12703 /** 12704 * Merge two states as returned by {@link #getMeasuredState()}. 12705 * @param curState The current state as returned from a view or the result 12706 * of combining multiple views. 12707 * @param newState The new view state to combine. 12708 * @return Returns a new integer reflecting the combination of the two 12709 * states. 12710 */ 12711 public static int combineMeasuredStates(int curState, int newState) { 12712 return curState | newState; 12713 } 12714 12715 /** 12716 * Version of {@link #resolveSizeAndState(int, int, int)} 12717 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 12718 */ 12719 public static int resolveSize(int size, int measureSpec) { 12720 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 12721 } 12722 12723 /** 12724 * Utility to reconcile a desired size and state, with constraints imposed 12725 * by a MeasureSpec. Will take the desired size, unless a different size 12726 * is imposed by the constraints. The returned value is a compound integer, 12727 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 12728 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 12729 * size is smaller than the size the view wants to be. 12730 * 12731 * @param size How big the view wants to be 12732 * @param measureSpec Constraints imposed by the parent 12733 * @return Size information bit mask as defined by 12734 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 12735 */ 12736 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 12737 int result = size; 12738 int specMode = MeasureSpec.getMode(measureSpec); 12739 int specSize = MeasureSpec.getSize(measureSpec); 12740 switch (specMode) { 12741 case MeasureSpec.UNSPECIFIED: 12742 result = size; 12743 break; 12744 case MeasureSpec.AT_MOST: 12745 if (specSize < size) { 12746 result = specSize | MEASURED_STATE_TOO_SMALL; 12747 } else { 12748 result = size; 12749 } 12750 break; 12751 case MeasureSpec.EXACTLY: 12752 result = specSize; 12753 break; 12754 } 12755 return result | (childMeasuredState&MEASURED_STATE_MASK); 12756 } 12757 12758 /** 12759 * Utility to return a default size. Uses the supplied size if the 12760 * MeasureSpec imposed no constraints. Will get larger if allowed 12761 * by the MeasureSpec. 12762 * 12763 * @param size Default size for this view 12764 * @param measureSpec Constraints imposed by the parent 12765 * @return The size this view should be. 12766 */ 12767 public static int getDefaultSize(int size, int measureSpec) { 12768 int result = size; 12769 int specMode = MeasureSpec.getMode(measureSpec); 12770 int specSize = MeasureSpec.getSize(measureSpec); 12771 12772 switch (specMode) { 12773 case MeasureSpec.UNSPECIFIED: 12774 result = size; 12775 break; 12776 case MeasureSpec.AT_MOST: 12777 case MeasureSpec.EXACTLY: 12778 result = specSize; 12779 break; 12780 } 12781 return result; 12782 } 12783 12784 /** 12785 * Returns the suggested minimum height that the view should use. This 12786 * returns the maximum of the view's minimum height 12787 * and the background's minimum height 12788 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 12789 * <p> 12790 * When being used in {@link #onMeasure(int, int)}, the caller should still 12791 * ensure the returned height is within the requirements of the parent. 12792 * 12793 * @return The suggested minimum height of the view. 12794 */ 12795 protected int getSuggestedMinimumHeight() { 12796 int suggestedMinHeight = mMinHeight; 12797 12798 if (mBGDrawable != null) { 12799 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 12800 if (suggestedMinHeight < bgMinHeight) { 12801 suggestedMinHeight = bgMinHeight; 12802 } 12803 } 12804 12805 return suggestedMinHeight; 12806 } 12807 12808 /** 12809 * Returns the suggested minimum width that the view should use. This 12810 * returns the maximum of the view's minimum width) 12811 * and the background's minimum width 12812 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 12813 * <p> 12814 * When being used in {@link #onMeasure(int, int)}, the caller should still 12815 * ensure the returned width is within the requirements of the parent. 12816 * 12817 * @return The suggested minimum width of the view. 12818 */ 12819 protected int getSuggestedMinimumWidth() { 12820 int suggestedMinWidth = mMinWidth; 12821 12822 if (mBGDrawable != null) { 12823 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 12824 if (suggestedMinWidth < bgMinWidth) { 12825 suggestedMinWidth = bgMinWidth; 12826 } 12827 } 12828 12829 return suggestedMinWidth; 12830 } 12831 12832 /** 12833 * Sets the minimum height of the view. It is not guaranteed the view will 12834 * be able to achieve this minimum height (for example, if its parent layout 12835 * constrains it with less available height). 12836 * 12837 * @param minHeight The minimum height the view will try to be. 12838 */ 12839 public void setMinimumHeight(int minHeight) { 12840 mMinHeight = minHeight; 12841 } 12842 12843 /** 12844 * Sets the minimum width of the view. It is not guaranteed the view will 12845 * be able to achieve this minimum width (for example, if its parent layout 12846 * constrains it with less available width). 12847 * 12848 * @param minWidth The minimum width the view will try to be. 12849 */ 12850 public void setMinimumWidth(int minWidth) { 12851 mMinWidth = minWidth; 12852 } 12853 12854 /** 12855 * Get the animation currently associated with this view. 12856 * 12857 * @return The animation that is currently playing or 12858 * scheduled to play for this view. 12859 */ 12860 public Animation getAnimation() { 12861 return mCurrentAnimation; 12862 } 12863 12864 /** 12865 * Start the specified animation now. 12866 * 12867 * @param animation the animation to start now 12868 */ 12869 public void startAnimation(Animation animation) { 12870 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 12871 setAnimation(animation); 12872 invalidateParentCaches(); 12873 invalidate(true); 12874 } 12875 12876 /** 12877 * Cancels any animations for this view. 12878 */ 12879 public void clearAnimation() { 12880 if (mCurrentAnimation != null) { 12881 mCurrentAnimation.detach(); 12882 } 12883 mCurrentAnimation = null; 12884 invalidateParentIfNeeded(); 12885 } 12886 12887 /** 12888 * Sets the next animation to play for this view. 12889 * If you want the animation to play immediately, use 12890 * startAnimation. This method provides allows fine-grained 12891 * control over the start time and invalidation, but you 12892 * must make sure that 1) the animation has a start time set, and 12893 * 2) the view will be invalidated when the animation is supposed to 12894 * start. 12895 * 12896 * @param animation The next animation, or null. 12897 */ 12898 public void setAnimation(Animation animation) { 12899 mCurrentAnimation = animation; 12900 if (animation != null) { 12901 animation.reset(); 12902 } 12903 } 12904 12905 /** 12906 * Invoked by a parent ViewGroup to notify the start of the animation 12907 * currently associated with this view. If you override this method, 12908 * always call super.onAnimationStart(); 12909 * 12910 * @see #setAnimation(android.view.animation.Animation) 12911 * @see #getAnimation() 12912 */ 12913 protected void onAnimationStart() { 12914 mPrivateFlags |= ANIMATION_STARTED; 12915 } 12916 12917 /** 12918 * Invoked by a parent ViewGroup to notify the end of the animation 12919 * currently associated with this view. If you override this method, 12920 * always call super.onAnimationEnd(); 12921 * 12922 * @see #setAnimation(android.view.animation.Animation) 12923 * @see #getAnimation() 12924 */ 12925 protected void onAnimationEnd() { 12926 mPrivateFlags &= ~ANIMATION_STARTED; 12927 } 12928 12929 /** 12930 * Invoked if there is a Transform that involves alpha. Subclass that can 12931 * draw themselves with the specified alpha should return true, and then 12932 * respect that alpha when their onDraw() is called. If this returns false 12933 * then the view may be redirected to draw into an offscreen buffer to 12934 * fulfill the request, which will look fine, but may be slower than if the 12935 * subclass handles it internally. The default implementation returns false. 12936 * 12937 * @param alpha The alpha (0..255) to apply to the view's drawing 12938 * @return true if the view can draw with the specified alpha. 12939 */ 12940 protected boolean onSetAlpha(int alpha) { 12941 return false; 12942 } 12943 12944 /** 12945 * This is used by the RootView to perform an optimization when 12946 * the view hierarchy contains one or several SurfaceView. 12947 * SurfaceView is always considered transparent, but its children are not, 12948 * therefore all View objects remove themselves from the global transparent 12949 * region (passed as a parameter to this function). 12950 * 12951 * @param region The transparent region for this ViewAncestor (window). 12952 * 12953 * @return Returns true if the effective visibility of the view at this 12954 * point is opaque, regardless of the transparent region; returns false 12955 * if it is possible for underlying windows to be seen behind the view. 12956 * 12957 * {@hide} 12958 */ 12959 public boolean gatherTransparentRegion(Region region) { 12960 final AttachInfo attachInfo = mAttachInfo; 12961 if (region != null && attachInfo != null) { 12962 final int pflags = mPrivateFlags; 12963 if ((pflags & SKIP_DRAW) == 0) { 12964 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 12965 // remove it from the transparent region. 12966 final int[] location = attachInfo.mTransparentLocation; 12967 getLocationInWindow(location); 12968 region.op(location[0], location[1], location[0] + mRight - mLeft, 12969 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 12970 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 12971 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 12972 // exists, so we remove the background drawable's non-transparent 12973 // parts from this transparent region. 12974 applyDrawableToTransparentRegion(mBGDrawable, region); 12975 } 12976 } 12977 return true; 12978 } 12979 12980 /** 12981 * Play a sound effect for this view. 12982 * 12983 * <p>The framework will play sound effects for some built in actions, such as 12984 * clicking, but you may wish to play these effects in your widget, 12985 * for instance, for internal navigation. 12986 * 12987 * <p>The sound effect will only be played if sound effects are enabled by the user, and 12988 * {@link #isSoundEffectsEnabled()} is true. 12989 * 12990 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 12991 */ 12992 public void playSoundEffect(int soundConstant) { 12993 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 12994 return; 12995 } 12996 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 12997 } 12998 12999 /** 13000 * BZZZTT!!1! 13001 * 13002 * <p>Provide haptic feedback to the user for this view. 13003 * 13004 * <p>The framework will provide haptic feedback for some built in actions, 13005 * such as long presses, but you may wish to provide feedback for your 13006 * own widget. 13007 * 13008 * <p>The feedback will only be performed if 13009 * {@link #isHapticFeedbackEnabled()} is true. 13010 * 13011 * @param feedbackConstant One of the constants defined in 13012 * {@link HapticFeedbackConstants} 13013 */ 13014 public boolean performHapticFeedback(int feedbackConstant) { 13015 return performHapticFeedback(feedbackConstant, 0); 13016 } 13017 13018 /** 13019 * BZZZTT!!1! 13020 * 13021 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 13022 * 13023 * @param feedbackConstant One of the constants defined in 13024 * {@link HapticFeedbackConstants} 13025 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 13026 */ 13027 public boolean performHapticFeedback(int feedbackConstant, int flags) { 13028 if (mAttachInfo == null) { 13029 return false; 13030 } 13031 //noinspection SimplifiableIfStatement 13032 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 13033 && !isHapticFeedbackEnabled()) { 13034 return false; 13035 } 13036 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 13037 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 13038 } 13039 13040 /** 13041 * Request that the visibility of the status bar be changed. 13042 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 13043 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 13044 */ 13045 public void setSystemUiVisibility(int visibility) { 13046 if (visibility != mSystemUiVisibility) { 13047 mSystemUiVisibility = visibility; 13048 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 13049 mParent.recomputeViewAttributes(this); 13050 } 13051 } 13052 } 13053 13054 /** 13055 * Returns the status bar visibility that this view has requested. 13056 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 13057 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 13058 */ 13059 public int getSystemUiVisibility() { 13060 return mSystemUiVisibility; 13061 } 13062 13063 /** 13064 * Set a listener to receive callbacks when the visibility of the system bar changes. 13065 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 13066 */ 13067 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 13068 mOnSystemUiVisibilityChangeListener = l; 13069 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 13070 mParent.recomputeViewAttributes(this); 13071 } 13072 } 13073 13074 /** 13075 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 13076 * the view hierarchy. 13077 */ 13078 public void dispatchSystemUiVisibilityChanged(int visibility) { 13079 if (mOnSystemUiVisibilityChangeListener != null) { 13080 mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 13081 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 13082 } 13083 } 13084 13085 void updateLocalSystemUiVisibility(int localValue, int localChanges) { 13086 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 13087 if (val != mSystemUiVisibility) { 13088 setSystemUiVisibility(val); 13089 } 13090 } 13091 13092 /** 13093 * Creates an image that the system displays during the drag and drop 13094 * operation. This is called a "drag shadow". The default implementation 13095 * for a DragShadowBuilder based on a View returns an image that has exactly the same 13096 * appearance as the given View. The default also positions the center of the drag shadow 13097 * directly under the touch point. If no View is provided (the constructor with no parameters 13098 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 13099 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 13100 * default is an invisible drag shadow. 13101 * <p> 13102 * You are not required to use the View you provide to the constructor as the basis of the 13103 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 13104 * anything you want as the drag shadow. 13105 * </p> 13106 * <p> 13107 * You pass a DragShadowBuilder object to the system when you start the drag. The system 13108 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 13109 * size and position of the drag shadow. It uses this data to construct a 13110 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 13111 * so that your application can draw the shadow image in the Canvas. 13112 * </p> 13113 * 13114 * <div class="special reference"> 13115 * <h3>Developer Guides</h3> 13116 * <p>For a guide to implementing drag and drop features, read the 13117 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 13118 * </div> 13119 */ 13120 public static class DragShadowBuilder { 13121 private final WeakReference<View> mView; 13122 13123 /** 13124 * Constructs a shadow image builder based on a View. By default, the resulting drag 13125 * shadow will have the same appearance and dimensions as the View, with the touch point 13126 * over the center of the View. 13127 * @param view A View. Any View in scope can be used. 13128 */ 13129 public DragShadowBuilder(View view) { 13130 mView = new WeakReference<View>(view); 13131 } 13132 13133 /** 13134 * Construct a shadow builder object with no associated View. This 13135 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 13136 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 13137 * to supply the drag shadow's dimensions and appearance without 13138 * reference to any View object. If they are not overridden, then the result is an 13139 * invisible drag shadow. 13140 */ 13141 public DragShadowBuilder() { 13142 mView = new WeakReference<View>(null); 13143 } 13144 13145 /** 13146 * Returns the View object that had been passed to the 13147 * {@link #View.DragShadowBuilder(View)} 13148 * constructor. If that View parameter was {@code null} or if the 13149 * {@link #View.DragShadowBuilder()} 13150 * constructor was used to instantiate the builder object, this method will return 13151 * null. 13152 * 13153 * @return The View object associate with this builder object. 13154 */ 13155 @SuppressWarnings({"JavadocReference"}) 13156 final public View getView() { 13157 return mView.get(); 13158 } 13159 13160 /** 13161 * Provides the metrics for the shadow image. These include the dimensions of 13162 * the shadow image, and the point within that shadow that should 13163 * be centered under the touch location while dragging. 13164 * <p> 13165 * The default implementation sets the dimensions of the shadow to be the 13166 * same as the dimensions of the View itself and centers the shadow under 13167 * the touch point. 13168 * </p> 13169 * 13170 * @param shadowSize A {@link android.graphics.Point} containing the width and height 13171 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 13172 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 13173 * image. 13174 * 13175 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 13176 * shadow image that should be underneath the touch point during the drag and drop 13177 * operation. Your application must set {@link android.graphics.Point#x} to the 13178 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 13179 */ 13180 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 13181 final View view = mView.get(); 13182 if (view != null) { 13183 shadowSize.set(view.getWidth(), view.getHeight()); 13184 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 13185 } else { 13186 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 13187 } 13188 } 13189 13190 /** 13191 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 13192 * based on the dimensions it received from the 13193 * {@link #onProvideShadowMetrics(Point, Point)} callback. 13194 * 13195 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 13196 */ 13197 public void onDrawShadow(Canvas canvas) { 13198 final View view = mView.get(); 13199 if (view != null) { 13200 view.draw(canvas); 13201 } else { 13202 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 13203 } 13204 } 13205 } 13206 13207 /** 13208 * Starts a drag and drop operation. When your application calls this method, it passes a 13209 * {@link android.view.View.DragShadowBuilder} object to the system. The 13210 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 13211 * to get metrics for the drag shadow, and then calls the object's 13212 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 13213 * <p> 13214 * Once the system has the drag shadow, it begins the drag and drop operation by sending 13215 * drag events to all the View objects in your application that are currently visible. It does 13216 * this either by calling the View object's drag listener (an implementation of 13217 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 13218 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 13219 * Both are passed a {@link android.view.DragEvent} object that has a 13220 * {@link android.view.DragEvent#getAction()} value of 13221 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 13222 * </p> 13223 * <p> 13224 * Your application can invoke startDrag() on any attached View object. The View object does not 13225 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 13226 * be related to the View the user selected for dragging. 13227 * </p> 13228 * @param data A {@link android.content.ClipData} object pointing to the data to be 13229 * transferred by the drag and drop operation. 13230 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 13231 * drag shadow. 13232 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 13233 * drop operation. This Object is put into every DragEvent object sent by the system during the 13234 * current drag. 13235 * <p> 13236 * myLocalState is a lightweight mechanism for the sending information from the dragged View 13237 * to the target Views. For example, it can contain flags that differentiate between a 13238 * a copy operation and a move operation. 13239 * </p> 13240 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 13241 * so the parameter should be set to 0. 13242 * @return {@code true} if the method completes successfully, or 13243 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 13244 * do a drag, and so no drag operation is in progress. 13245 */ 13246 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 13247 Object myLocalState, int flags) { 13248 if (ViewDebug.DEBUG_DRAG) { 13249 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 13250 } 13251 boolean okay = false; 13252 13253 Point shadowSize = new Point(); 13254 Point shadowTouchPoint = new Point(); 13255 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 13256 13257 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 13258 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 13259 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 13260 } 13261 13262 if (ViewDebug.DEBUG_DRAG) { 13263 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 13264 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 13265 } 13266 Surface surface = new Surface(); 13267 try { 13268 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 13269 flags, shadowSize.x, shadowSize.y, surface); 13270 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 13271 + " surface=" + surface); 13272 if (token != null) { 13273 Canvas canvas = surface.lockCanvas(null); 13274 try { 13275 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 13276 shadowBuilder.onDrawShadow(canvas); 13277 } finally { 13278 surface.unlockCanvasAndPost(canvas); 13279 } 13280 13281 final ViewRootImpl root = getViewRootImpl(); 13282 13283 // Cache the local state object for delivery with DragEvents 13284 root.setLocalDragState(myLocalState); 13285 13286 // repurpose 'shadowSize' for the last touch point 13287 root.getLastTouchPoint(shadowSize); 13288 13289 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 13290 shadowSize.x, shadowSize.y, 13291 shadowTouchPoint.x, shadowTouchPoint.y, data); 13292 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 13293 13294 // Off and running! Release our local surface instance; the drag 13295 // shadow surface is now managed by the system process. 13296 surface.release(); 13297 } 13298 } catch (Exception e) { 13299 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 13300 surface.destroy(); 13301 } 13302 13303 return okay; 13304 } 13305 13306 /** 13307 * Handles drag events sent by the system following a call to 13308 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 13309 *<p> 13310 * When the system calls this method, it passes a 13311 * {@link android.view.DragEvent} object. A call to 13312 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 13313 * in DragEvent. The method uses these to determine what is happening in the drag and drop 13314 * operation. 13315 * @param event The {@link android.view.DragEvent} sent by the system. 13316 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 13317 * in DragEvent, indicating the type of drag event represented by this object. 13318 * @return {@code true} if the method was successful, otherwise {@code false}. 13319 * <p> 13320 * The method should return {@code true} in response to an action type of 13321 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 13322 * operation. 13323 * </p> 13324 * <p> 13325 * The method should also return {@code true} in response to an action type of 13326 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 13327 * {@code false} if it didn't. 13328 * </p> 13329 */ 13330 public boolean onDragEvent(DragEvent event) { 13331 return false; 13332 } 13333 13334 /** 13335 * Detects if this View is enabled and has a drag event listener. 13336 * If both are true, then it calls the drag event listener with the 13337 * {@link android.view.DragEvent} it received. If the drag event listener returns 13338 * {@code true}, then dispatchDragEvent() returns {@code true}. 13339 * <p> 13340 * For all other cases, the method calls the 13341 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 13342 * method and returns its result. 13343 * </p> 13344 * <p> 13345 * This ensures that a drag event is always consumed, even if the View does not have a drag 13346 * event listener. However, if the View has a listener and the listener returns true, then 13347 * onDragEvent() is not called. 13348 * </p> 13349 */ 13350 public boolean dispatchDragEvent(DragEvent event) { 13351 //noinspection SimplifiableIfStatement 13352 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 13353 && mOnDragListener.onDrag(this, event)) { 13354 return true; 13355 } 13356 return onDragEvent(event); 13357 } 13358 13359 boolean canAcceptDrag() { 13360 return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0; 13361 } 13362 13363 /** 13364 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 13365 * it is ever exposed at all. 13366 * @hide 13367 */ 13368 public void onCloseSystemDialogs(String reason) { 13369 } 13370 13371 /** 13372 * Given a Drawable whose bounds have been set to draw into this view, 13373 * update a Region being computed for 13374 * {@link #gatherTransparentRegion(android.graphics.Region)} so 13375 * that any non-transparent parts of the Drawable are removed from the 13376 * given transparent region. 13377 * 13378 * @param dr The Drawable whose transparency is to be applied to the region. 13379 * @param region A Region holding the current transparency information, 13380 * where any parts of the region that are set are considered to be 13381 * transparent. On return, this region will be modified to have the 13382 * transparency information reduced by the corresponding parts of the 13383 * Drawable that are not transparent. 13384 * {@hide} 13385 */ 13386 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 13387 if (DBG) { 13388 Log.i("View", "Getting transparent region for: " + this); 13389 } 13390 final Region r = dr.getTransparentRegion(); 13391 final Rect db = dr.getBounds(); 13392 final AttachInfo attachInfo = mAttachInfo; 13393 if (r != null && attachInfo != null) { 13394 final int w = getRight()-getLeft(); 13395 final int h = getBottom()-getTop(); 13396 if (db.left > 0) { 13397 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 13398 r.op(0, 0, db.left, h, Region.Op.UNION); 13399 } 13400 if (db.right < w) { 13401 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 13402 r.op(db.right, 0, w, h, Region.Op.UNION); 13403 } 13404 if (db.top > 0) { 13405 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 13406 r.op(0, 0, w, db.top, Region.Op.UNION); 13407 } 13408 if (db.bottom < h) { 13409 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 13410 r.op(0, db.bottom, w, h, Region.Op.UNION); 13411 } 13412 final int[] location = attachInfo.mTransparentLocation; 13413 getLocationInWindow(location); 13414 r.translate(location[0], location[1]); 13415 region.op(r, Region.Op.INTERSECT); 13416 } else { 13417 region.op(db, Region.Op.DIFFERENCE); 13418 } 13419 } 13420 13421 private void checkForLongClick(int delayOffset) { 13422 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 13423 mHasPerformedLongPress = false; 13424 13425 if (mPendingCheckForLongPress == null) { 13426 mPendingCheckForLongPress = new CheckForLongPress(); 13427 } 13428 mPendingCheckForLongPress.rememberWindowAttachCount(); 13429 postDelayed(mPendingCheckForLongPress, 13430 ViewConfiguration.getLongPressTimeout() - delayOffset); 13431 } 13432 } 13433 13434 /** 13435 * Inflate a view from an XML resource. This convenience method wraps the {@link 13436 * LayoutInflater} class, which provides a full range of options for view inflation. 13437 * 13438 * @param context The Context object for your activity or application. 13439 * @param resource The resource ID to inflate 13440 * @param root A view group that will be the parent. Used to properly inflate the 13441 * layout_* parameters. 13442 * @see LayoutInflater 13443 */ 13444 public static View inflate(Context context, int resource, ViewGroup root) { 13445 LayoutInflater factory = LayoutInflater.from(context); 13446 return factory.inflate(resource, root); 13447 } 13448 13449 /** 13450 * Scroll the view with standard behavior for scrolling beyond the normal 13451 * content boundaries. Views that call this method should override 13452 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 13453 * results of an over-scroll operation. 13454 * 13455 * Views can use this method to handle any touch or fling-based scrolling. 13456 * 13457 * @param deltaX Change in X in pixels 13458 * @param deltaY Change in Y in pixels 13459 * @param scrollX Current X scroll value in pixels before applying deltaX 13460 * @param scrollY Current Y scroll value in pixels before applying deltaY 13461 * @param scrollRangeX Maximum content scroll range along the X axis 13462 * @param scrollRangeY Maximum content scroll range along the Y axis 13463 * @param maxOverScrollX Number of pixels to overscroll by in either direction 13464 * along the X axis. 13465 * @param maxOverScrollY Number of pixels to overscroll by in either direction 13466 * along the Y axis. 13467 * @param isTouchEvent true if this scroll operation is the result of a touch event. 13468 * @return true if scrolling was clamped to an over-scroll boundary along either 13469 * axis, false otherwise. 13470 */ 13471 @SuppressWarnings({"UnusedParameters"}) 13472 protected boolean overScrollBy(int deltaX, int deltaY, 13473 int scrollX, int scrollY, 13474 int scrollRangeX, int scrollRangeY, 13475 int maxOverScrollX, int maxOverScrollY, 13476 boolean isTouchEvent) { 13477 final int overScrollMode = mOverScrollMode; 13478 final boolean canScrollHorizontal = 13479 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 13480 final boolean canScrollVertical = 13481 computeVerticalScrollRange() > computeVerticalScrollExtent(); 13482 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 13483 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 13484 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 13485 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 13486 13487 int newScrollX = scrollX + deltaX; 13488 if (!overScrollHorizontal) { 13489 maxOverScrollX = 0; 13490 } 13491 13492 int newScrollY = scrollY + deltaY; 13493 if (!overScrollVertical) { 13494 maxOverScrollY = 0; 13495 } 13496 13497 // Clamp values if at the limits and record 13498 final int left = -maxOverScrollX; 13499 final int right = maxOverScrollX + scrollRangeX; 13500 final int top = -maxOverScrollY; 13501 final int bottom = maxOverScrollY + scrollRangeY; 13502 13503 boolean clampedX = false; 13504 if (newScrollX > right) { 13505 newScrollX = right; 13506 clampedX = true; 13507 } else if (newScrollX < left) { 13508 newScrollX = left; 13509 clampedX = true; 13510 } 13511 13512 boolean clampedY = false; 13513 if (newScrollY > bottom) { 13514 newScrollY = bottom; 13515 clampedY = true; 13516 } else if (newScrollY < top) { 13517 newScrollY = top; 13518 clampedY = true; 13519 } 13520 13521 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 13522 13523 return clampedX || clampedY; 13524 } 13525 13526 /** 13527 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 13528 * respond to the results of an over-scroll operation. 13529 * 13530 * @param scrollX New X scroll value in pixels 13531 * @param scrollY New Y scroll value in pixels 13532 * @param clampedX True if scrollX was clamped to an over-scroll boundary 13533 * @param clampedY True if scrollY was clamped to an over-scroll boundary 13534 */ 13535 protected void onOverScrolled(int scrollX, int scrollY, 13536 boolean clampedX, boolean clampedY) { 13537 // Intentionally empty. 13538 } 13539 13540 /** 13541 * Returns the over-scroll mode for this view. The result will be 13542 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 13543 * (allow over-scrolling only if the view content is larger than the container), 13544 * or {@link #OVER_SCROLL_NEVER}. 13545 * 13546 * @return This view's over-scroll mode. 13547 */ 13548 public int getOverScrollMode() { 13549 return mOverScrollMode; 13550 } 13551 13552 /** 13553 * Set the over-scroll mode for this view. Valid over-scroll modes are 13554 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 13555 * (allow over-scrolling only if the view content is larger than the container), 13556 * or {@link #OVER_SCROLL_NEVER}. 13557 * 13558 * Setting the over-scroll mode of a view will have an effect only if the 13559 * view is capable of scrolling. 13560 * 13561 * @param overScrollMode The new over-scroll mode for this view. 13562 */ 13563 public void setOverScrollMode(int overScrollMode) { 13564 if (overScrollMode != OVER_SCROLL_ALWAYS && 13565 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 13566 overScrollMode != OVER_SCROLL_NEVER) { 13567 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 13568 } 13569 mOverScrollMode = overScrollMode; 13570 } 13571 13572 /** 13573 * Gets a scale factor that determines the distance the view should scroll 13574 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 13575 * @return The vertical scroll scale factor. 13576 * @hide 13577 */ 13578 protected float getVerticalScrollFactor() { 13579 if (mVerticalScrollFactor == 0) { 13580 TypedValue outValue = new TypedValue(); 13581 if (!mContext.getTheme().resolveAttribute( 13582 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 13583 throw new IllegalStateException( 13584 "Expected theme to define listPreferredItemHeight."); 13585 } 13586 mVerticalScrollFactor = outValue.getDimension( 13587 mContext.getResources().getDisplayMetrics()); 13588 } 13589 return mVerticalScrollFactor; 13590 } 13591 13592 /** 13593 * Gets a scale factor that determines the distance the view should scroll 13594 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 13595 * @return The horizontal scroll scale factor. 13596 * @hide 13597 */ 13598 protected float getHorizontalScrollFactor() { 13599 // TODO: Should use something else. 13600 return getVerticalScrollFactor(); 13601 } 13602 13603 /** 13604 * Return the value specifying the text direction or policy that was set with 13605 * {@link #setTextDirection(int)}. 13606 * 13607 * @return the defined text direction. It can be one of: 13608 * 13609 * {@link #TEXT_DIRECTION_INHERIT}, 13610 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13611 * {@link #TEXT_DIRECTION_ANY_RTL}, 13612 * {@link #TEXT_DIRECTION_LTR}, 13613 * {@link #TEXT_DIRECTION_RTL}, 13614 * 13615 * @hide 13616 */ 13617 public int getTextDirection() { 13618 return mTextDirection; 13619 } 13620 13621 /** 13622 * Set the text direction. 13623 * 13624 * @param textDirection the direction to set. Should be one of: 13625 * 13626 * {@link #TEXT_DIRECTION_INHERIT}, 13627 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13628 * {@link #TEXT_DIRECTION_ANY_RTL}, 13629 * {@link #TEXT_DIRECTION_LTR}, 13630 * {@link #TEXT_DIRECTION_RTL}, 13631 * 13632 * @hide 13633 */ 13634 public void setTextDirection(int textDirection) { 13635 if (textDirection != mTextDirection) { 13636 mTextDirection = textDirection; 13637 resetResolvedTextDirection(); 13638 requestLayout(); 13639 } 13640 } 13641 13642 /** 13643 * Return the resolved text direction. 13644 * 13645 * @return the resolved text direction. Return one of: 13646 * 13647 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13648 * {@link #TEXT_DIRECTION_ANY_RTL}, 13649 * {@link #TEXT_DIRECTION_LTR}, 13650 * {@link #TEXT_DIRECTION_RTL}, 13651 * 13652 * @hide 13653 */ 13654 public int getResolvedTextDirection() { 13655 if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) { 13656 resolveTextDirection(); 13657 } 13658 return mResolvedTextDirection; 13659 } 13660 13661 /** 13662 * Resolve the text direction. 13663 * 13664 * @hide 13665 */ 13666 protected void resolveTextDirection() { 13667 if (mTextDirection != TEXT_DIRECTION_INHERIT) { 13668 mResolvedTextDirection = mTextDirection; 13669 return; 13670 } 13671 if (mParent != null && mParent instanceof ViewGroup) { 13672 mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection(); 13673 return; 13674 } 13675 mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG; 13676 } 13677 13678 /** 13679 * Reset resolved text direction. Will be resolved during a call to getResolvedTextDirection(). 13680 * 13681 * @hide 13682 */ 13683 protected void resetResolvedTextDirection() { 13684 mResolvedTextDirection = TEXT_DIRECTION_INHERIT; 13685 } 13686 13687 // 13688 // Properties 13689 // 13690 /** 13691 * A Property wrapper around the <code>alpha</code> functionality handled by the 13692 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 13693 */ 13694 public static Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 13695 @Override 13696 public void setValue(View object, float value) { 13697 object.setAlpha(value); 13698 } 13699 13700 @Override 13701 public Float get(View object) { 13702 return object.getAlpha(); 13703 } 13704 }; 13705 13706 /** 13707 * A Property wrapper around the <code>translationX</code> functionality handled by the 13708 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 13709 */ 13710 public static Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 13711 @Override 13712 public void setValue(View object, float value) { 13713 object.setTranslationX(value); 13714 } 13715 13716 @Override 13717 public Float get(View object) { 13718 return object.getTranslationX(); 13719 } 13720 }; 13721 13722 /** 13723 * A Property wrapper around the <code>translationY</code> functionality handled by the 13724 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 13725 */ 13726 public static Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 13727 @Override 13728 public void setValue(View object, float value) { 13729 object.setTranslationY(value); 13730 } 13731 13732 @Override 13733 public Float get(View object) { 13734 return object.getTranslationY(); 13735 } 13736 }; 13737 13738 /** 13739 * A Property wrapper around the <code>x</code> functionality handled by the 13740 * {@link View#setX(float)} and {@link View#getX()} methods. 13741 */ 13742 public static Property<View, Float> X = new FloatProperty<View>("x") { 13743 @Override 13744 public void setValue(View object, float value) { 13745 object.setX(value); 13746 } 13747 13748 @Override 13749 public Float get(View object) { 13750 return object.getX(); 13751 } 13752 }; 13753 13754 /** 13755 * A Property wrapper around the <code>y</code> functionality handled by the 13756 * {@link View#setY(float)} and {@link View#getY()} methods. 13757 */ 13758 public static Property<View, Float> Y = new FloatProperty<View>("y") { 13759 @Override 13760 public void setValue(View object, float value) { 13761 object.setY(value); 13762 } 13763 13764 @Override 13765 public Float get(View object) { 13766 return object.getY(); 13767 } 13768 }; 13769 13770 /** 13771 * A Property wrapper around the <code>rotation</code> functionality handled by the 13772 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 13773 */ 13774 public static Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 13775 @Override 13776 public void setValue(View object, float value) { 13777 object.setRotation(value); 13778 } 13779 13780 @Override 13781 public Float get(View object) { 13782 return object.getRotation(); 13783 } 13784 }; 13785 13786 /** 13787 * A Property wrapper around the <code>rotationX</code> functionality handled by the 13788 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 13789 */ 13790 public static Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 13791 @Override 13792 public void setValue(View object, float value) { 13793 object.setRotationX(value); 13794 } 13795 13796 @Override 13797 public Float get(View object) { 13798 return object.getRotationX(); 13799 } 13800 }; 13801 13802 /** 13803 * A Property wrapper around the <code>rotationY</code> functionality handled by the 13804 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 13805 */ 13806 public static Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 13807 @Override 13808 public void setValue(View object, float value) { 13809 object.setRotationY(value); 13810 } 13811 13812 @Override 13813 public Float get(View object) { 13814 return object.getRotationY(); 13815 } 13816 }; 13817 13818 /** 13819 * A Property wrapper around the <code>scaleX</code> functionality handled by the 13820 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 13821 */ 13822 public static Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 13823 @Override 13824 public void setValue(View object, float value) { 13825 object.setScaleX(value); 13826 } 13827 13828 @Override 13829 public Float get(View object) { 13830 return object.getScaleX(); 13831 } 13832 }; 13833 13834 /** 13835 * A Property wrapper around the <code>scaleY</code> functionality handled by the 13836 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 13837 */ 13838 public static Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 13839 @Override 13840 public void setValue(View object, float value) { 13841 object.setScaleY(value); 13842 } 13843 13844 @Override 13845 public Float get(View object) { 13846 return object.getScaleY(); 13847 } 13848 }; 13849 13850 /** 13851 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 13852 * Each MeasureSpec represents a requirement for either the width or the height. 13853 * A MeasureSpec is comprised of a size and a mode. There are three possible 13854 * modes: 13855 * <dl> 13856 * <dt>UNSPECIFIED</dt> 13857 * <dd> 13858 * The parent has not imposed any constraint on the child. It can be whatever size 13859 * it wants. 13860 * </dd> 13861 * 13862 * <dt>EXACTLY</dt> 13863 * <dd> 13864 * The parent has determined an exact size for the child. The child is going to be 13865 * given those bounds regardless of how big it wants to be. 13866 * </dd> 13867 * 13868 * <dt>AT_MOST</dt> 13869 * <dd> 13870 * The child can be as large as it wants up to the specified size. 13871 * </dd> 13872 * </dl> 13873 * 13874 * MeasureSpecs are implemented as ints to reduce object allocation. This class 13875 * is provided to pack and unpack the <size, mode> tuple into the int. 13876 */ 13877 public static class MeasureSpec { 13878 private static final int MODE_SHIFT = 30; 13879 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 13880 13881 /** 13882 * Measure specification mode: The parent has not imposed any constraint 13883 * on the child. It can be whatever size it wants. 13884 */ 13885 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 13886 13887 /** 13888 * Measure specification mode: The parent has determined an exact size 13889 * for the child. The child is going to be given those bounds regardless 13890 * of how big it wants to be. 13891 */ 13892 public static final int EXACTLY = 1 << MODE_SHIFT; 13893 13894 /** 13895 * Measure specification mode: The child can be as large as it wants up 13896 * to the specified size. 13897 */ 13898 public static final int AT_MOST = 2 << MODE_SHIFT; 13899 13900 /** 13901 * Creates a measure specification based on the supplied size and mode. 13902 * 13903 * The mode must always be one of the following: 13904 * <ul> 13905 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 13906 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 13907 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 13908 * </ul> 13909 * 13910 * @param size the size of the measure specification 13911 * @param mode the mode of the measure specification 13912 * @return the measure specification based on size and mode 13913 */ 13914 public static int makeMeasureSpec(int size, int mode) { 13915 return size + mode; 13916 } 13917 13918 /** 13919 * Extracts the mode from the supplied measure specification. 13920 * 13921 * @param measureSpec the measure specification to extract the mode from 13922 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 13923 * {@link android.view.View.MeasureSpec#AT_MOST} or 13924 * {@link android.view.View.MeasureSpec#EXACTLY} 13925 */ 13926 public static int getMode(int measureSpec) { 13927 return (measureSpec & MODE_MASK); 13928 } 13929 13930 /** 13931 * Extracts the size from the supplied measure specification. 13932 * 13933 * @param measureSpec the measure specification to extract the size from 13934 * @return the size in pixels defined in the supplied measure specification 13935 */ 13936 public static int getSize(int measureSpec) { 13937 return (measureSpec & ~MODE_MASK); 13938 } 13939 13940 /** 13941 * Returns a String representation of the specified measure 13942 * specification. 13943 * 13944 * @param measureSpec the measure specification to convert to a String 13945 * @return a String with the following format: "MeasureSpec: MODE SIZE" 13946 */ 13947 public static String toString(int measureSpec) { 13948 int mode = getMode(measureSpec); 13949 int size = getSize(measureSpec); 13950 13951 StringBuilder sb = new StringBuilder("MeasureSpec: "); 13952 13953 if (mode == UNSPECIFIED) 13954 sb.append("UNSPECIFIED "); 13955 else if (mode == EXACTLY) 13956 sb.append("EXACTLY "); 13957 else if (mode == AT_MOST) 13958 sb.append("AT_MOST "); 13959 else 13960 sb.append(mode).append(" "); 13961 13962 sb.append(size); 13963 return sb.toString(); 13964 } 13965 } 13966 13967 class CheckForLongPress implements Runnable { 13968 13969 private int mOriginalWindowAttachCount; 13970 13971 public void run() { 13972 if (isPressed() && (mParent != null) 13973 && mOriginalWindowAttachCount == mWindowAttachCount) { 13974 if (performLongClick()) { 13975 mHasPerformedLongPress = true; 13976 } 13977 } 13978 } 13979 13980 public void rememberWindowAttachCount() { 13981 mOriginalWindowAttachCount = mWindowAttachCount; 13982 } 13983 } 13984 13985 private final class CheckForTap implements Runnable { 13986 public void run() { 13987 mPrivateFlags &= ~PREPRESSED; 13988 mPrivateFlags |= PRESSED; 13989 refreshDrawableState(); 13990 checkForLongClick(ViewConfiguration.getTapTimeout()); 13991 } 13992 } 13993 13994 private final class PerformClick implements Runnable { 13995 public void run() { 13996 performClick(); 13997 } 13998 } 13999 14000 /** @hide */ 14001 public void hackTurnOffWindowResizeAnim(boolean off) { 14002 mAttachInfo.mTurnOffWindowResizeAnim = off; 14003 } 14004 14005 /** 14006 * This method returns a ViewPropertyAnimator object, which can be used to animate 14007 * specific properties on this View. 14008 * 14009 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 14010 */ 14011 public ViewPropertyAnimator animate() { 14012 if (mAnimator == null) { 14013 mAnimator = new ViewPropertyAnimator(this); 14014 } 14015 return mAnimator; 14016 } 14017 14018 /** 14019 * Interface definition for a callback to be invoked when a key event is 14020 * dispatched to this view. The callback will be invoked before the key 14021 * event is given to the view. 14022 */ 14023 public interface OnKeyListener { 14024 /** 14025 * Called when a key is dispatched to a view. This allows listeners to 14026 * get a chance to respond before the target view. 14027 * 14028 * @param v The view the key has been dispatched to. 14029 * @param keyCode The code for the physical key that was pressed 14030 * @param event The KeyEvent object containing full information about 14031 * the event. 14032 * @return True if the listener has consumed the event, false otherwise. 14033 */ 14034 boolean onKey(View v, int keyCode, KeyEvent event); 14035 } 14036 14037 /** 14038 * Interface definition for a callback to be invoked when a touch event is 14039 * dispatched to this view. The callback will be invoked before the touch 14040 * event is given to the view. 14041 */ 14042 public interface OnTouchListener { 14043 /** 14044 * Called when a touch event is dispatched to a view. This allows listeners to 14045 * get a chance to respond before the target view. 14046 * 14047 * @param v The view the touch event has been dispatched to. 14048 * @param event The MotionEvent object containing full information about 14049 * the event. 14050 * @return True if the listener has consumed the event, false otherwise. 14051 */ 14052 boolean onTouch(View v, MotionEvent event); 14053 } 14054 14055 /** 14056 * Interface definition for a callback to be invoked when a hover event is 14057 * dispatched to this view. The callback will be invoked before the hover 14058 * event is given to the view. 14059 */ 14060 public interface OnHoverListener { 14061 /** 14062 * Called when a hover event is dispatched to a view. This allows listeners to 14063 * get a chance to respond before the target view. 14064 * 14065 * @param v The view the hover event has been dispatched to. 14066 * @param event The MotionEvent object containing full information about 14067 * the event. 14068 * @return True if the listener has consumed the event, false otherwise. 14069 */ 14070 boolean onHover(View v, MotionEvent event); 14071 } 14072 14073 /** 14074 * Interface definition for a callback to be invoked when a generic motion event is 14075 * dispatched to this view. The callback will be invoked before the generic motion 14076 * event is given to the view. 14077 */ 14078 public interface OnGenericMotionListener { 14079 /** 14080 * Called when a generic motion event is dispatched to a view. This allows listeners to 14081 * get a chance to respond before the target view. 14082 * 14083 * @param v The view the generic motion event has been dispatched to. 14084 * @param event The MotionEvent object containing full information about 14085 * the event. 14086 * @return True if the listener has consumed the event, false otherwise. 14087 */ 14088 boolean onGenericMotion(View v, MotionEvent event); 14089 } 14090 14091 /** 14092 * Interface definition for a callback to be invoked when a view has been clicked and held. 14093 */ 14094 public interface OnLongClickListener { 14095 /** 14096 * Called when a view has been clicked and held. 14097 * 14098 * @param v The view that was clicked and held. 14099 * 14100 * @return true if the callback consumed the long click, false otherwise. 14101 */ 14102 boolean onLongClick(View v); 14103 } 14104 14105 /** 14106 * Interface definition for a callback to be invoked when a drag is being dispatched 14107 * to this view. The callback will be invoked before the hosting view's own 14108 * onDrag(event) method. If the listener wants to fall back to the hosting view's 14109 * onDrag(event) behavior, it should return 'false' from this callback. 14110 * 14111 * <div class="special reference"> 14112 * <h3>Developer Guides</h3> 14113 * <p>For a guide to implementing drag and drop features, read the 14114 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 14115 * </div> 14116 */ 14117 public interface OnDragListener { 14118 /** 14119 * Called when a drag event is dispatched to a view. This allows listeners 14120 * to get a chance to override base View behavior. 14121 * 14122 * @param v The View that received the drag event. 14123 * @param event The {@link android.view.DragEvent} object for the drag event. 14124 * @return {@code true} if the drag event was handled successfully, or {@code false} 14125 * if the drag event was not handled. Note that {@code false} will trigger the View 14126 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 14127 */ 14128 boolean onDrag(View v, DragEvent event); 14129 } 14130 14131 /** 14132 * Interface definition for a callback to be invoked when the focus state of 14133 * a view changed. 14134 */ 14135 public interface OnFocusChangeListener { 14136 /** 14137 * Called when the focus state of a view has changed. 14138 * 14139 * @param v The view whose state has changed. 14140 * @param hasFocus The new focus state of v. 14141 */ 14142 void onFocusChange(View v, boolean hasFocus); 14143 } 14144 14145 /** 14146 * Interface definition for a callback to be invoked when a view is clicked. 14147 */ 14148 public interface OnClickListener { 14149 /** 14150 * Called when a view has been clicked. 14151 * 14152 * @param v The view that was clicked. 14153 */ 14154 void onClick(View v); 14155 } 14156 14157 /** 14158 * Interface definition for a callback to be invoked when the context menu 14159 * for this view is being built. 14160 */ 14161 public interface OnCreateContextMenuListener { 14162 /** 14163 * Called when the context menu for this view is being built. It is not 14164 * safe to hold onto the menu after this method returns. 14165 * 14166 * @param menu The context menu that is being built 14167 * @param v The view for which the context menu is being built 14168 * @param menuInfo Extra information about the item for which the 14169 * context menu should be shown. This information will vary 14170 * depending on the class of v. 14171 */ 14172 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 14173 } 14174 14175 /** 14176 * Interface definition for a callback to be invoked when the status bar changes 14177 * visibility. This reports <strong>global</strong> changes to the system UI 14178 * state, not just what the application is requesting. 14179 * 14180 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 14181 */ 14182 public interface OnSystemUiVisibilityChangeListener { 14183 /** 14184 * Called when the status bar changes visibility because of a call to 14185 * {@link View#setSystemUiVisibility(int)}. 14186 * 14187 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 14188 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. This tells you the 14189 * <strong>global</strong> state of the UI visibility flags, not what your 14190 * app is currently applying. 14191 */ 14192 public void onSystemUiVisibilityChange(int visibility); 14193 } 14194 14195 /** 14196 * Interface definition for a callback to be invoked when this view is attached 14197 * or detached from its window. 14198 */ 14199 public interface OnAttachStateChangeListener { 14200 /** 14201 * Called when the view is attached to a window. 14202 * @param v The view that was attached 14203 */ 14204 public void onViewAttachedToWindow(View v); 14205 /** 14206 * Called when the view is detached from a window. 14207 * @param v The view that was detached 14208 */ 14209 public void onViewDetachedFromWindow(View v); 14210 } 14211 14212 private final class UnsetPressedState implements Runnable { 14213 public void run() { 14214 setPressed(false); 14215 } 14216 } 14217 14218 /** 14219 * Base class for derived classes that want to save and restore their own 14220 * state in {@link android.view.View#onSaveInstanceState()}. 14221 */ 14222 public static class BaseSavedState extends AbsSavedState { 14223 /** 14224 * Constructor used when reading from a parcel. Reads the state of the superclass. 14225 * 14226 * @param source 14227 */ 14228 public BaseSavedState(Parcel source) { 14229 super(source); 14230 } 14231 14232 /** 14233 * Constructor called by derived classes when creating their SavedState objects 14234 * 14235 * @param superState The state of the superclass of this view 14236 */ 14237 public BaseSavedState(Parcelable superState) { 14238 super(superState); 14239 } 14240 14241 public static final Parcelable.Creator<BaseSavedState> CREATOR = 14242 new Parcelable.Creator<BaseSavedState>() { 14243 public BaseSavedState createFromParcel(Parcel in) { 14244 return new BaseSavedState(in); 14245 } 14246 14247 public BaseSavedState[] newArray(int size) { 14248 return new BaseSavedState[size]; 14249 } 14250 }; 14251 } 14252 14253 /** 14254 * A set of information given to a view when it is attached to its parent 14255 * window. 14256 */ 14257 static class AttachInfo { 14258 interface Callbacks { 14259 void playSoundEffect(int effectId); 14260 boolean performHapticFeedback(int effectId, boolean always); 14261 } 14262 14263 /** 14264 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 14265 * to a Handler. This class contains the target (View) to invalidate and 14266 * the coordinates of the dirty rectangle. 14267 * 14268 * For performance purposes, this class also implements a pool of up to 14269 * POOL_LIMIT objects that get reused. This reduces memory allocations 14270 * whenever possible. 14271 */ 14272 static class InvalidateInfo implements Poolable<InvalidateInfo> { 14273 private static final int POOL_LIMIT = 10; 14274 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 14275 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 14276 public InvalidateInfo newInstance() { 14277 return new InvalidateInfo(); 14278 } 14279 14280 public void onAcquired(InvalidateInfo element) { 14281 } 14282 14283 public void onReleased(InvalidateInfo element) { 14284 element.target = null; 14285 } 14286 }, POOL_LIMIT) 14287 ); 14288 14289 private InvalidateInfo mNext; 14290 private boolean mIsPooled; 14291 14292 View target; 14293 14294 int left; 14295 int top; 14296 int right; 14297 int bottom; 14298 14299 public void setNextPoolable(InvalidateInfo element) { 14300 mNext = element; 14301 } 14302 14303 public InvalidateInfo getNextPoolable() { 14304 return mNext; 14305 } 14306 14307 static InvalidateInfo acquire() { 14308 return sPool.acquire(); 14309 } 14310 14311 void release() { 14312 sPool.release(this); 14313 } 14314 14315 public boolean isPooled() { 14316 return mIsPooled; 14317 } 14318 14319 public void setPooled(boolean isPooled) { 14320 mIsPooled = isPooled; 14321 } 14322 } 14323 14324 final IWindowSession mSession; 14325 14326 final IWindow mWindow; 14327 14328 final IBinder mWindowToken; 14329 14330 final Callbacks mRootCallbacks; 14331 14332 HardwareCanvas mHardwareCanvas; 14333 14334 /** 14335 * The top view of the hierarchy. 14336 */ 14337 View mRootView; 14338 14339 IBinder mPanelParentWindowToken; 14340 Surface mSurface; 14341 14342 boolean mHardwareAccelerated; 14343 boolean mHardwareAccelerationRequested; 14344 HardwareRenderer mHardwareRenderer; 14345 14346 /** 14347 * Scale factor used by the compatibility mode 14348 */ 14349 float mApplicationScale; 14350 14351 /** 14352 * Indicates whether the application is in compatibility mode 14353 */ 14354 boolean mScalingRequired; 14355 14356 /** 14357 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 14358 */ 14359 boolean mTurnOffWindowResizeAnim; 14360 14361 /** 14362 * Left position of this view's window 14363 */ 14364 int mWindowLeft; 14365 14366 /** 14367 * Top position of this view's window 14368 */ 14369 int mWindowTop; 14370 14371 /** 14372 * Indicates whether views need to use 32-bit drawing caches 14373 */ 14374 boolean mUse32BitDrawingCache; 14375 14376 /** 14377 * For windows that are full-screen but using insets to layout inside 14378 * of the screen decorations, these are the current insets for the 14379 * content of the window. 14380 */ 14381 final Rect mContentInsets = new Rect(); 14382 14383 /** 14384 * For windows that are full-screen but using insets to layout inside 14385 * of the screen decorations, these are the current insets for the 14386 * actual visible parts of the window. 14387 */ 14388 final Rect mVisibleInsets = new Rect(); 14389 14390 /** 14391 * The internal insets given by this window. This value is 14392 * supplied by the client (through 14393 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 14394 * be given to the window manager when changed to be used in laying 14395 * out windows behind it. 14396 */ 14397 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 14398 = new ViewTreeObserver.InternalInsetsInfo(); 14399 14400 /** 14401 * All views in the window's hierarchy that serve as scroll containers, 14402 * used to determine if the window can be resized or must be panned 14403 * to adjust for a soft input area. 14404 */ 14405 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 14406 14407 final KeyEvent.DispatcherState mKeyDispatchState 14408 = new KeyEvent.DispatcherState(); 14409 14410 /** 14411 * Indicates whether the view's window currently has the focus. 14412 */ 14413 boolean mHasWindowFocus; 14414 14415 /** 14416 * The current visibility of the window. 14417 */ 14418 int mWindowVisibility; 14419 14420 /** 14421 * Indicates the time at which drawing started to occur. 14422 */ 14423 long mDrawingTime; 14424 14425 /** 14426 * Indicates whether or not ignoring the DIRTY_MASK flags. 14427 */ 14428 boolean mIgnoreDirtyState; 14429 14430 /** 14431 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 14432 * to avoid clearing that flag prematurely. 14433 */ 14434 boolean mSetIgnoreDirtyState = false; 14435 14436 /** 14437 * Indicates whether the view's window is currently in touch mode. 14438 */ 14439 boolean mInTouchMode; 14440 14441 /** 14442 * Indicates that ViewAncestor should trigger a global layout change 14443 * the next time it performs a traversal 14444 */ 14445 boolean mRecomputeGlobalAttributes; 14446 14447 /** 14448 * Always report new attributes at next traversal. 14449 */ 14450 boolean mForceReportNewAttributes; 14451 14452 /** 14453 * Set during a traveral if any views want to keep the screen on. 14454 */ 14455 boolean mKeepScreenOn; 14456 14457 /** 14458 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 14459 */ 14460 int mSystemUiVisibility; 14461 14462 /** 14463 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 14464 * attached. 14465 */ 14466 boolean mHasSystemUiListeners; 14467 14468 /** 14469 * Set if the visibility of any views has changed. 14470 */ 14471 boolean mViewVisibilityChanged; 14472 14473 /** 14474 * Set to true if a view has been scrolled. 14475 */ 14476 boolean mViewScrollChanged; 14477 14478 /** 14479 * Global to the view hierarchy used as a temporary for dealing with 14480 * x/y points in the transparent region computations. 14481 */ 14482 final int[] mTransparentLocation = new int[2]; 14483 14484 /** 14485 * Global to the view hierarchy used as a temporary for dealing with 14486 * x/y points in the ViewGroup.invalidateChild implementation. 14487 */ 14488 final int[] mInvalidateChildLocation = new int[2]; 14489 14490 14491 /** 14492 * Global to the view hierarchy used as a temporary for dealing with 14493 * x/y location when view is transformed. 14494 */ 14495 final float[] mTmpTransformLocation = new float[2]; 14496 14497 /** 14498 * The view tree observer used to dispatch global events like 14499 * layout, pre-draw, touch mode change, etc. 14500 */ 14501 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 14502 14503 /** 14504 * A Canvas used by the view hierarchy to perform bitmap caching. 14505 */ 14506 Canvas mCanvas; 14507 14508 /** 14509 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 14510 * handler can be used to pump events in the UI events queue. 14511 */ 14512 final Handler mHandler; 14513 14514 /** 14515 * Identifier for messages requesting the view to be invalidated. 14516 * Such messages should be sent to {@link #mHandler}. 14517 */ 14518 static final int INVALIDATE_MSG = 0x1; 14519 14520 /** 14521 * Identifier for messages requesting the view to invalidate a region. 14522 * Such messages should be sent to {@link #mHandler}. 14523 */ 14524 static final int INVALIDATE_RECT_MSG = 0x2; 14525 14526 /** 14527 * Temporary for use in computing invalidate rectangles while 14528 * calling up the hierarchy. 14529 */ 14530 final Rect mTmpInvalRect = new Rect(); 14531 14532 /** 14533 * Temporary for use in computing hit areas with transformed views 14534 */ 14535 final RectF mTmpTransformRect = new RectF(); 14536 14537 /** 14538 * Temporary list for use in collecting focusable descendents of a view. 14539 */ 14540 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 14541 14542 /** 14543 * The id of the window for accessibility purposes. 14544 */ 14545 int mAccessibilityWindowId = View.NO_ID; 14546 14547 /** 14548 * Creates a new set of attachment information with the specified 14549 * events handler and thread. 14550 * 14551 * @param handler the events handler the view must use 14552 */ 14553 AttachInfo(IWindowSession session, IWindow window, 14554 Handler handler, Callbacks effectPlayer) { 14555 mSession = session; 14556 mWindow = window; 14557 mWindowToken = window.asBinder(); 14558 mHandler = handler; 14559 mRootCallbacks = effectPlayer; 14560 } 14561 } 14562 14563 /** 14564 * <p>ScrollabilityCache holds various fields used by a View when scrolling 14565 * is supported. This avoids keeping too many unused fields in most 14566 * instances of View.</p> 14567 */ 14568 private static class ScrollabilityCache implements Runnable { 14569 14570 /** 14571 * Scrollbars are not visible 14572 */ 14573 public static final int OFF = 0; 14574 14575 /** 14576 * Scrollbars are visible 14577 */ 14578 public static final int ON = 1; 14579 14580 /** 14581 * Scrollbars are fading away 14582 */ 14583 public static final int FADING = 2; 14584 14585 public boolean fadeScrollBars; 14586 14587 public int fadingEdgeLength; 14588 public int scrollBarDefaultDelayBeforeFade; 14589 public int scrollBarFadeDuration; 14590 14591 public int scrollBarSize; 14592 public ScrollBarDrawable scrollBar; 14593 public float[] interpolatorValues; 14594 public View host; 14595 14596 public final Paint paint; 14597 public final Matrix matrix; 14598 public Shader shader; 14599 14600 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 14601 14602 private static final float[] OPAQUE = { 255 }; 14603 private static final float[] TRANSPARENT = { 0.0f }; 14604 14605 /** 14606 * When fading should start. This time moves into the future every time 14607 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 14608 */ 14609 public long fadeStartTime; 14610 14611 14612 /** 14613 * The current state of the scrollbars: ON, OFF, or FADING 14614 */ 14615 public int state = OFF; 14616 14617 private int mLastColor; 14618 14619 public ScrollabilityCache(ViewConfiguration configuration, View host) { 14620 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 14621 scrollBarSize = configuration.getScaledScrollBarSize(); 14622 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 14623 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 14624 14625 paint = new Paint(); 14626 matrix = new Matrix(); 14627 // use use a height of 1, and then wack the matrix each time we 14628 // actually use it. 14629 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 14630 14631 paint.setShader(shader); 14632 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 14633 this.host = host; 14634 } 14635 14636 public void setFadeColor(int color) { 14637 if (color != 0 && color != mLastColor) { 14638 mLastColor = color; 14639 color |= 0xFF000000; 14640 14641 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 14642 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 14643 14644 paint.setShader(shader); 14645 // Restore the default transfer mode (src_over) 14646 paint.setXfermode(null); 14647 } 14648 } 14649 14650 public void run() { 14651 long now = AnimationUtils.currentAnimationTimeMillis(); 14652 if (now >= fadeStartTime) { 14653 14654 // the animation fades the scrollbars out by changing 14655 // the opacity (alpha) from fully opaque to fully 14656 // transparent 14657 int nextFrame = (int) now; 14658 int framesCount = 0; 14659 14660 Interpolator interpolator = scrollBarInterpolator; 14661 14662 // Start opaque 14663 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 14664 14665 // End transparent 14666 nextFrame += scrollBarFadeDuration; 14667 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 14668 14669 state = FADING; 14670 14671 // Kick off the fade animation 14672 host.invalidate(true); 14673 } 14674 } 14675 } 14676 14677 /** 14678 * Resuable callback for sending 14679 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 14680 */ 14681 private class SendViewScrolledAccessibilityEvent implements Runnable { 14682 public volatile boolean mIsPending; 14683 14684 public void run() { 14685 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 14686 mIsPending = false; 14687 } 14688 } 14689 14690 /** 14691 * <p> 14692 * This class represents a delegate that can be registered in a {@link View} 14693 * to enhance accessibility support via composition rather via inheritance. 14694 * It is specifically targeted to widget developers that extend basic View 14695 * classes i.e. classes in package android.view, that would like their 14696 * applications to be backwards compatible. 14697 * </p> 14698 * <p> 14699 * A scenario in which a developer would like to use an accessibility delegate 14700 * is overriding a method introduced in a later API version then the minimal API 14701 * version supported by the application. For example, the method 14702 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 14703 * in API version 4 when the accessibility APIs were first introduced. If a 14704 * developer would like his application to run on API version 4 devices (assuming 14705 * all other APIs used by the application are version 4 or lower) and take advantage 14706 * of this method, instead of overriding the method which would break the application's 14707 * backwards compatibility, he can override the corresponding method in this 14708 * delegate and register the delegate in the target View if the API version of 14709 * the system is high enough i.e. the API version is same or higher to the API 14710 * version that introduced 14711 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 14712 * </p> 14713 * <p> 14714 * Here is an example implementation: 14715 * </p> 14716 * <code><pre><p> 14717 * if (Build.VERSION.SDK_INT >= 14) { 14718 * // If the API version is equal of higher than the version in 14719 * // which onInitializeAccessibilityNodeInfo was introduced we 14720 * // register a delegate with a customized implementation. 14721 * View view = findViewById(R.id.view_id); 14722 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 14723 * public void onInitializeAccessibilityNodeInfo(View host, 14724 * AccessibilityNodeInfo info) { 14725 * // Let the default implementation populate the info. 14726 * super.onInitializeAccessibilityNodeInfo(host, info); 14727 * // Set some other information. 14728 * info.setEnabled(host.isEnabled()); 14729 * } 14730 * }); 14731 * } 14732 * </code></pre></p> 14733 * <p> 14734 * This delegate contains methods that correspond to the accessibility methods 14735 * in View. If a delegate has been specified the implementation in View hands 14736 * off handling to the corresponding method in this delegate. The default 14737 * implementation the delegate methods behaves exactly as the corresponding 14738 * method in View for the case of no accessibility delegate been set. Hence, 14739 * to customize the behavior of a View method, clients can override only the 14740 * corresponding delegate method without altering the behavior of the rest 14741 * accessibility related methods of the host view. 14742 * </p> 14743 */ 14744 public static class AccessibilityDelegate { 14745 14746 /** 14747 * Sends an accessibility event of the given type. If accessibility is not 14748 * enabled this method has no effect. 14749 * <p> 14750 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 14751 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 14752 * been set. 14753 * </p> 14754 * 14755 * @param host The View hosting the delegate. 14756 * @param eventType The type of the event to send. 14757 * 14758 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 14759 */ 14760 public void sendAccessibilityEvent(View host, int eventType) { 14761 host.sendAccessibilityEventInternal(eventType); 14762 } 14763 14764 /** 14765 * Sends an accessibility event. This method behaves exactly as 14766 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 14767 * empty {@link AccessibilityEvent} and does not perform a check whether 14768 * accessibility is enabled. 14769 * <p> 14770 * The default implementation behaves as 14771 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 14772 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 14773 * the case of no accessibility delegate been set. 14774 * </p> 14775 * 14776 * @param host The View hosting the delegate. 14777 * @param event The event to send. 14778 * 14779 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 14780 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 14781 */ 14782 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 14783 host.sendAccessibilityEventUncheckedInternal(event); 14784 } 14785 14786 /** 14787 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 14788 * to its children for adding their text content to the event. 14789 * <p> 14790 * The default implementation behaves as 14791 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 14792 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 14793 * the case of no accessibility delegate been set. 14794 * </p> 14795 * 14796 * @param host The View hosting the delegate. 14797 * @param event The event. 14798 * @return True if the event population was completed. 14799 * 14800 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 14801 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 14802 */ 14803 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 14804 return host.dispatchPopulateAccessibilityEventInternal(event); 14805 } 14806 14807 /** 14808 * Gives a chance to the host View to populate the accessibility event with its 14809 * text content. 14810 * <p> 14811 * The default implementation behaves as 14812 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 14813 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 14814 * the case of no accessibility delegate been set. 14815 * </p> 14816 * 14817 * @param host The View hosting the delegate. 14818 * @param event The accessibility event which to populate. 14819 * 14820 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 14821 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 14822 */ 14823 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 14824 host.onPopulateAccessibilityEventInternal(event); 14825 } 14826 14827 /** 14828 * Initializes an {@link AccessibilityEvent} with information about the 14829 * the host View which is the event source. 14830 * <p> 14831 * The default implementation behaves as 14832 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 14833 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 14834 * the case of no accessibility delegate been set. 14835 * </p> 14836 * 14837 * @param host The View hosting the delegate. 14838 * @param event The event to initialize. 14839 * 14840 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 14841 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 14842 */ 14843 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 14844 host.onInitializeAccessibilityEventInternal(event); 14845 } 14846 14847 /** 14848 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 14849 * <p> 14850 * The default implementation behaves as 14851 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 14852 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 14853 * the case of no accessibility delegate been set. 14854 * </p> 14855 * 14856 * @param host The View hosting the delegate. 14857 * @param info The instance to initialize. 14858 * 14859 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 14860 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 14861 */ 14862 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 14863 host.onInitializeAccessibilityNodeInfoInternal(info); 14864 } 14865 14866 /** 14867 * Called when a child of the host View has requested sending an 14868 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 14869 * to augment the event. 14870 * <p> 14871 * The default implementation behaves as 14872 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 14873 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 14874 * the case of no accessibility delegate been set. 14875 * </p> 14876 * 14877 * @param host The View hosting the delegate. 14878 * @param child The child which requests sending the event. 14879 * @param event The event to be sent. 14880 * @return True if the event should be sent 14881 * 14882 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 14883 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 14884 */ 14885 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 14886 AccessibilityEvent event) { 14887 return host.onRequestSendAccessibilityEventInternal(child, event); 14888 } 14889 } 14890} 14891