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