View.java revision db8c9a6a4d9bf8c39f834b25611926caf21380f6
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.Parcel; 44import android.os.Parcelable; 45import android.os.RemoteException; 46import android.os.SystemClock; 47import android.text.TextUtils; 48import android.util.AttributeSet; 49import android.util.FloatProperty; 50import android.util.LocaleUtil; 51import android.util.Log; 52import android.util.Pool; 53import android.util.Poolable; 54import android.util.PoolableManager; 55import android.util.Pools; 56import android.util.Property; 57import android.util.SparseArray; 58import android.util.TypedValue; 59import android.view.ContextMenu.ContextMenuInfo; 60import android.view.accessibility.AccessibilityEvent; 61import android.view.accessibility.AccessibilityEventSource; 62import android.view.accessibility.AccessibilityManager; 63import android.view.accessibility.AccessibilityNodeInfo; 64import android.view.accessibility.AccessibilityNodeProvider; 65import android.view.animation.Animation; 66import android.view.animation.AnimationUtils; 67import android.view.animation.Transformation; 68import android.view.inputmethod.EditorInfo; 69import android.view.inputmethod.InputConnection; 70import android.view.inputmethod.InputMethodManager; 71import android.widget.ScrollBarDrawable; 72 73import static android.os.Build.VERSION_CODES.*; 74 75import com.android.internal.R; 76import com.android.internal.util.Predicate; 77import com.android.internal.view.menu.MenuBuilder; 78 79import java.lang.ref.WeakReference; 80import java.lang.reflect.InvocationTargetException; 81import java.lang.reflect.Method; 82import java.util.ArrayList; 83import java.util.Arrays; 84import java.util.Locale; 85import java.util.concurrent.CopyOnWriteArrayList; 86 87/** 88 * <p> 89 * This class represents the basic building block for user interface components. A View 90 * occupies a rectangular area on the screen and is responsible for drawing and 91 * event handling. View is the base class for <em>widgets</em>, which are 92 * used to create interactive UI components (buttons, text fields, etc.). The 93 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 94 * are invisible containers that hold other Views (or other ViewGroups) and define 95 * their layout properties. 96 * </p> 97 * 98 * <div class="special reference"> 99 * <h3>Developer Guides</h3> 100 * <p>For information about using this class to develop your application's user interface, 101 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 102 * </div> 103 * 104 * <a name="Using"></a> 105 * <h3>Using Views</h3> 106 * <p> 107 * All of the views in a window are arranged in a single tree. You can add views 108 * either from code or by specifying a tree of views in one or more XML layout 109 * files. There are many specialized subclasses of views that act as controls or 110 * are capable of displaying text, images, or other content. 111 * </p> 112 * <p> 113 * Once you have created a tree of views, there are typically a few types of 114 * common operations you may wish to perform: 115 * <ul> 116 * <li><strong>Set properties:</strong> for example setting the text of a 117 * {@link android.widget.TextView}. The available properties and the methods 118 * that set them will vary among the different subclasses of views. Note that 119 * properties that are known at build time can be set in the XML layout 120 * files.</li> 121 * <li><strong>Set focus:</strong> The framework will handled moving focus in 122 * response to user input. To force focus to a specific view, call 123 * {@link #requestFocus}.</li> 124 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 125 * that will be notified when something interesting happens to the view. For 126 * example, all views will let you set a listener to be notified when the view 127 * gains or loses focus. You can register such a listener using 128 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 129 * Other view subclasses offer more specialized listeners. For example, a Button 130 * exposes a listener to notify clients when the button is clicked.</li> 131 * <li><strong>Set visibility:</strong> You can hide or show views using 132 * {@link #setVisibility(int)}.</li> 133 * </ul> 134 * </p> 135 * <p><em> 136 * Note: The Android framework is responsible for measuring, laying out and 137 * drawing views. You should not call methods that perform these actions on 138 * views yourself unless you are actually implementing a 139 * {@link android.view.ViewGroup}. 140 * </em></p> 141 * 142 * <a name="Lifecycle"></a> 143 * <h3>Implementing a Custom View</h3> 144 * 145 * <p> 146 * To implement a custom view, you will usually begin by providing overrides for 147 * some of the standard methods that the framework calls on all views. You do 148 * not need to override all of these methods. In fact, you can start by just 149 * overriding {@link #onDraw(android.graphics.Canvas)}. 150 * <table border="2" width="85%" align="center" cellpadding="5"> 151 * <thead> 152 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 153 * </thead> 154 * 155 * <tbody> 156 * <tr> 157 * <td rowspan="2">Creation</td> 158 * <td>Constructors</td> 159 * <td>There is a form of the constructor that are called when the view 160 * is created from code and a form that is called when the view is 161 * inflated from a layout file. The second form should parse and apply 162 * any attributes defined in the layout file. 163 * </td> 164 * </tr> 165 * <tr> 166 * <td><code>{@link #onFinishInflate()}</code></td> 167 * <td>Called after a view and all of its children has been inflated 168 * from XML.</td> 169 * </tr> 170 * 171 * <tr> 172 * <td rowspan="3">Layout</td> 173 * <td><code>{@link #onMeasure(int, int)}</code></td> 174 * <td>Called to determine the size requirements for this view and all 175 * of its children. 176 * </td> 177 * </tr> 178 * <tr> 179 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 180 * <td>Called when this view should assign a size and position to all 181 * of its children. 182 * </td> 183 * </tr> 184 * <tr> 185 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 186 * <td>Called when the size of this view has changed. 187 * </td> 188 * </tr> 189 * 190 * <tr> 191 * <td>Drawing</td> 192 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 193 * <td>Called when the view should render its content. 194 * </td> 195 * </tr> 196 * 197 * <tr> 198 * <td rowspan="4">Event processing</td> 199 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 200 * <td>Called when a new key event occurs. 201 * </td> 202 * </tr> 203 * <tr> 204 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 205 * <td>Called when a key up event occurs. 206 * </td> 207 * </tr> 208 * <tr> 209 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 210 * <td>Called when a trackball motion event occurs. 211 * </td> 212 * </tr> 213 * <tr> 214 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 215 * <td>Called when a touch screen motion event occurs. 216 * </td> 217 * </tr> 218 * 219 * <tr> 220 * <td rowspan="2">Focus</td> 221 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 222 * <td>Called when the view gains or loses focus. 223 * </td> 224 * </tr> 225 * 226 * <tr> 227 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 228 * <td>Called when the window containing the view gains or loses focus. 229 * </td> 230 * </tr> 231 * 232 * <tr> 233 * <td rowspan="3">Attaching</td> 234 * <td><code>{@link #onAttachedToWindow()}</code></td> 235 * <td>Called when the view is attached to a window. 236 * </td> 237 * </tr> 238 * 239 * <tr> 240 * <td><code>{@link #onDetachedFromWindow}</code></td> 241 * <td>Called when the view is detached from its window. 242 * </td> 243 * </tr> 244 * 245 * <tr> 246 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 247 * <td>Called when the visibility of the window containing the view 248 * has changed. 249 * </td> 250 * </tr> 251 * </tbody> 252 * 253 * </table> 254 * </p> 255 * 256 * <a name="IDs"></a> 257 * <h3>IDs</h3> 258 * Views may have an integer id associated with them. These ids are typically 259 * assigned in the layout XML files, and are used to find specific views within 260 * the view tree. A common pattern is to: 261 * <ul> 262 * <li>Define a Button in the layout file and assign it a unique ID. 263 * <pre> 264 * <Button 265 * android:id="@+id/my_button" 266 * android:layout_width="wrap_content" 267 * android:layout_height="wrap_content" 268 * android:text="@string/my_button_text"/> 269 * </pre></li> 270 * <li>From the onCreate method of an Activity, find the Button 271 * <pre class="prettyprint"> 272 * Button myButton = (Button) findViewById(R.id.my_button); 273 * </pre></li> 274 * </ul> 275 * <p> 276 * View IDs need not be unique throughout the tree, but it is good practice to 277 * ensure that they are at least unique within the part of the tree you are 278 * searching. 279 * </p> 280 * 281 * <a name="Position"></a> 282 * <h3>Position</h3> 283 * <p> 284 * The geometry of a view is that of a rectangle. A view has a location, 285 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 286 * two dimensions, expressed as a width and a height. The unit for location 287 * and dimensions is the pixel. 288 * </p> 289 * 290 * <p> 291 * It is possible to retrieve the location of a view by invoking the methods 292 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 293 * coordinate of the rectangle representing the view. The latter returns the 294 * top, or Y, coordinate of the rectangle representing the view. These methods 295 * both return the location of the view relative to its parent. For instance, 296 * when getLeft() returns 20, that means the view is located 20 pixels to the 297 * right of the left edge of its direct parent. 298 * </p> 299 * 300 * <p> 301 * In addition, several convenience methods are offered to avoid unnecessary 302 * computations, namely {@link #getRight()} and {@link #getBottom()}. 303 * These methods return the coordinates of the right and bottom edges of the 304 * rectangle representing the view. For instance, calling {@link #getRight()} 305 * is similar to the following computation: <code>getLeft() + getWidth()</code> 306 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 307 * </p> 308 * 309 * <a name="SizePaddingMargins"></a> 310 * <h3>Size, padding and margins</h3> 311 * <p> 312 * The size of a view is expressed with a width and a height. A view actually 313 * possess two pairs of width and height values. 314 * </p> 315 * 316 * <p> 317 * The first pair is known as <em>measured width</em> and 318 * <em>measured height</em>. These dimensions define how big a view wants to be 319 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 320 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 321 * and {@link #getMeasuredHeight()}. 322 * </p> 323 * 324 * <p> 325 * The second pair is simply known as <em>width</em> and <em>height</em>, or 326 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 327 * dimensions define the actual size of the view on screen, at drawing time and 328 * after layout. These values may, but do not have to, be different from the 329 * measured width and height. The width and height can be obtained by calling 330 * {@link #getWidth()} and {@link #getHeight()}. 331 * </p> 332 * 333 * <p> 334 * To measure its dimensions, a view takes into account its padding. The padding 335 * is expressed in pixels for the left, top, right and bottom parts of the view. 336 * Padding can be used to offset the content of the view by a specific amount of 337 * pixels. For instance, a left padding of 2 will push the view's content by 338 * 2 pixels to the right of the left edge. Padding can be set using the 339 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 340 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 341 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 342 * {@link #getPaddingEnd()}. 343 * </p> 344 * 345 * <p> 346 * Even though a view can define a padding, it does not provide any support for 347 * margins. However, view groups provide such a support. Refer to 348 * {@link android.view.ViewGroup} and 349 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 350 * </p> 351 * 352 * <a name="Layout"></a> 353 * <h3>Layout</h3> 354 * <p> 355 * Layout is a two pass process: a measure pass and a layout pass. The measuring 356 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 357 * of the view tree. Each view pushes dimension specifications down the tree 358 * during the recursion. At the end of the measure pass, every view has stored 359 * its measurements. The second pass happens in 360 * {@link #layout(int,int,int,int)} and is also top-down. During 361 * this pass each parent is responsible for positioning all of its children 362 * using the sizes computed in the measure pass. 363 * </p> 364 * 365 * <p> 366 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 367 * {@link #getMeasuredHeight()} values must be set, along with those for all of 368 * that view's descendants. A view's measured width and measured height values 369 * must respect the constraints imposed by the view's parents. This guarantees 370 * that at the end of the measure pass, all parents accept all of their 371 * children's measurements. A parent view may call measure() more than once on 372 * its children. For example, the parent may measure each child once with 373 * unspecified dimensions to find out how big they want to be, then call 374 * measure() on them again with actual numbers if the sum of all the children's 375 * unconstrained sizes is too big or too small. 376 * </p> 377 * 378 * <p> 379 * The measure pass uses two classes to communicate dimensions. The 380 * {@link MeasureSpec} class is used by views to tell their parents how they 381 * want to be measured and positioned. The base LayoutParams class just 382 * describes how big the view wants to be for both width and height. For each 383 * dimension, it can specify one of: 384 * <ul> 385 * <li> an exact number 386 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 387 * (minus padding) 388 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 389 * enclose its content (plus padding). 390 * </ul> 391 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 392 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 393 * an X and Y value. 394 * </p> 395 * 396 * <p> 397 * MeasureSpecs are used to push requirements down the tree from parent to 398 * child. A MeasureSpec can be in one of three modes: 399 * <ul> 400 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 401 * of a child view. For example, a LinearLayout may call measure() on its child 402 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 403 * tall the child view wants to be given a width of 240 pixels. 404 * <li>EXACTLY: This is used by the parent to impose an exact size on the 405 * child. The child must use this size, and guarantee that all of its 406 * descendants will fit within this size. 407 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 408 * child. The child must gurantee that it and all of its descendants will fit 409 * within this size. 410 * </ul> 411 * </p> 412 * 413 * <p> 414 * To intiate a layout, call {@link #requestLayout}. This method is typically 415 * called by a view on itself when it believes that is can no longer fit within 416 * its current bounds. 417 * </p> 418 * 419 * <a name="Drawing"></a> 420 * <h3>Drawing</h3> 421 * <p> 422 * Drawing is handled by walking the tree and rendering each view that 423 * intersects the invalid region. Because the tree is traversed in-order, 424 * this means that parents will draw before (i.e., behind) their children, with 425 * siblings drawn in the order they appear in the tree. 426 * If you set a background drawable for a View, then the View will draw it for you 427 * before calling back to its <code>onDraw()</code> method. 428 * </p> 429 * 430 * <p> 431 * Note that the framework will not draw views that are not in the invalid region. 432 * </p> 433 * 434 * <p> 435 * To force a view to draw, call {@link #invalidate()}. 436 * </p> 437 * 438 * <a name="EventHandlingThreading"></a> 439 * <h3>Event Handling and Threading</h3> 440 * <p> 441 * The basic cycle of a view is as follows: 442 * <ol> 443 * <li>An event comes in and is dispatched to the appropriate view. The view 444 * handles the event and notifies any listeners.</li> 445 * <li>If in the course of processing the event, the view's bounds may need 446 * to be changed, the view will call {@link #requestLayout()}.</li> 447 * <li>Similarly, if in the course of processing the event the view's appearance 448 * may need to be changed, the view will call {@link #invalidate()}.</li> 449 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 450 * the framework will take care of measuring, laying out, and drawing the tree 451 * as appropriate.</li> 452 * </ol> 453 * </p> 454 * 455 * <p><em>Note: The entire view tree is single threaded. You must always be on 456 * the UI thread when calling any method on any view.</em> 457 * If you are doing work on other threads and want to update the state of a view 458 * from that thread, you should use a {@link Handler}. 459 * </p> 460 * 461 * <a name="FocusHandling"></a> 462 * <h3>Focus Handling</h3> 463 * <p> 464 * The framework will handle routine focus movement in response to user input. 465 * This includes changing the focus as views are removed or hidden, or as new 466 * views become available. Views indicate their willingness to take focus 467 * through the {@link #isFocusable} method. To change whether a view can take 468 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 469 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 470 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 471 * </p> 472 * <p> 473 * Focus movement is based on an algorithm which finds the nearest neighbor in a 474 * given direction. In rare cases, the default algorithm may not match the 475 * intended behavior of the developer. In these situations, you can provide 476 * explicit overrides by using these XML attributes in the layout file: 477 * <pre> 478 * nextFocusDown 479 * nextFocusLeft 480 * nextFocusRight 481 * nextFocusUp 482 * </pre> 483 * </p> 484 * 485 * 486 * <p> 487 * To get a particular view to take focus, call {@link #requestFocus()}. 488 * </p> 489 * 490 * <a name="TouchMode"></a> 491 * <h3>Touch Mode</h3> 492 * <p> 493 * When a user is navigating a user interface via directional keys such as a D-pad, it is 494 * necessary to give focus to actionable items such as buttons so the user can see 495 * what will take input. If the device has touch capabilities, however, and the user 496 * begins interacting with the interface by touching it, it is no longer necessary to 497 * always highlight, or give focus to, a particular view. This motivates a mode 498 * for interaction named 'touch mode'. 499 * </p> 500 * <p> 501 * For a touch capable device, once the user touches the screen, the device 502 * will enter touch mode. From this point onward, only views for which 503 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 504 * Other views that are touchable, like buttons, will not take focus when touched; they will 505 * only fire the on click listeners. 506 * </p> 507 * <p> 508 * Any time a user hits a directional key, such as a D-pad direction, the view device will 509 * exit touch mode, and find a view to take focus, so that the user may resume interacting 510 * with the user interface without touching the screen again. 511 * </p> 512 * <p> 513 * The touch mode state is maintained across {@link android.app.Activity}s. Call 514 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 515 * </p> 516 * 517 * <a name="Scrolling"></a> 518 * <h3>Scrolling</h3> 519 * <p> 520 * The framework provides basic support for views that wish to internally 521 * scroll their content. This includes keeping track of the X and Y scroll 522 * offset as well as mechanisms for drawing scrollbars. See 523 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 524 * {@link #awakenScrollBars()} for more details. 525 * </p> 526 * 527 * <a name="Tags"></a> 528 * <h3>Tags</h3> 529 * <p> 530 * Unlike IDs, tags are not used to identify views. Tags are essentially an 531 * extra piece of information that can be associated with a view. They are most 532 * often used as a convenience to store data related to views in the views 533 * themselves rather than by putting them in a separate structure. 534 * </p> 535 * 536 * <a name="Animation"></a> 537 * <h3>Animation</h3> 538 * <p> 539 * You can attach an {@link Animation} object to a view using 540 * {@link #setAnimation(Animation)} or 541 * {@link #startAnimation(Animation)}. The animation can alter the scale, 542 * rotation, translation and alpha of a view over time. If the animation is 543 * attached to a view that has children, the animation will affect the entire 544 * subtree rooted by that node. When an animation is started, the framework will 545 * take care of redrawing the appropriate views until the animation completes. 546 * </p> 547 * <p> 548 * Starting with Android 3.0, the preferred way of animating views is to use the 549 * {@link android.animation} package APIs. 550 * </p> 551 * 552 * <a name="Security"></a> 553 * <h3>Security</h3> 554 * <p> 555 * Sometimes it is essential that an application be able to verify that an action 556 * is being performed with the full knowledge and consent of the user, such as 557 * granting a permission request, making a purchase or clicking on an advertisement. 558 * Unfortunately, a malicious application could try to spoof the user into 559 * performing these actions, unaware, by concealing the intended purpose of the view. 560 * As a remedy, the framework offers a touch filtering mechanism that can be used to 561 * improve the security of views that provide access to sensitive functionality. 562 * </p><p> 563 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 564 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 565 * will discard touches that are received whenever the view's window is obscured by 566 * another visible window. As a result, the view will not receive touches whenever a 567 * toast, dialog or other window appears above the view's window. 568 * </p><p> 569 * For more fine-grained control over security, consider overriding the 570 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 571 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 572 * </p> 573 * 574 * @attr ref android.R.styleable#View_alpha 575 * @attr ref android.R.styleable#View_background 576 * @attr ref android.R.styleable#View_clickable 577 * @attr ref android.R.styleable#View_contentDescription 578 * @attr ref android.R.styleable#View_drawingCacheQuality 579 * @attr ref android.R.styleable#View_duplicateParentState 580 * @attr ref android.R.styleable#View_id 581 * @attr ref android.R.styleable#View_requiresFadingEdge 582 * @attr ref android.R.styleable#View_fadingEdgeLength 583 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 584 * @attr ref android.R.styleable#View_fitsSystemWindows 585 * @attr ref android.R.styleable#View_isScrollContainer 586 * @attr ref android.R.styleable#View_focusable 587 * @attr ref android.R.styleable#View_focusableInTouchMode 588 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 589 * @attr ref android.R.styleable#View_keepScreenOn 590 * @attr ref android.R.styleable#View_layerType 591 * @attr ref android.R.styleable#View_longClickable 592 * @attr ref android.R.styleable#View_minHeight 593 * @attr ref android.R.styleable#View_minWidth 594 * @attr ref android.R.styleable#View_nextFocusDown 595 * @attr ref android.R.styleable#View_nextFocusLeft 596 * @attr ref android.R.styleable#View_nextFocusRight 597 * @attr ref android.R.styleable#View_nextFocusUp 598 * @attr ref android.R.styleable#View_onClick 599 * @attr ref android.R.styleable#View_padding 600 * @attr ref android.R.styleable#View_paddingBottom 601 * @attr ref android.R.styleable#View_paddingLeft 602 * @attr ref android.R.styleable#View_paddingRight 603 * @attr ref android.R.styleable#View_paddingTop 604 * @attr ref android.R.styleable#View_paddingStart 605 * @attr ref android.R.styleable#View_paddingEnd 606 * @attr ref android.R.styleable#View_saveEnabled 607 * @attr ref android.R.styleable#View_rotation 608 * @attr ref android.R.styleable#View_rotationX 609 * @attr ref android.R.styleable#View_rotationY 610 * @attr ref android.R.styleable#View_scaleX 611 * @attr ref android.R.styleable#View_scaleY 612 * @attr ref android.R.styleable#View_scrollX 613 * @attr ref android.R.styleable#View_scrollY 614 * @attr ref android.R.styleable#View_scrollbarSize 615 * @attr ref android.R.styleable#View_scrollbarStyle 616 * @attr ref android.R.styleable#View_scrollbars 617 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 618 * @attr ref android.R.styleable#View_scrollbarFadeDuration 619 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 620 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 621 * @attr ref android.R.styleable#View_scrollbarThumbVertical 622 * @attr ref android.R.styleable#View_scrollbarTrackVertical 623 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 624 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 625 * @attr ref android.R.styleable#View_soundEffectsEnabled 626 * @attr ref android.R.styleable#View_tag 627 * @attr ref android.R.styleable#View_transformPivotX 628 * @attr ref android.R.styleable#View_transformPivotY 629 * @attr ref android.R.styleable#View_translationX 630 * @attr ref android.R.styleable#View_translationY 631 * @attr ref android.R.styleable#View_visibility 632 * 633 * @see android.view.ViewGroup 634 */ 635public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback, 636 AccessibilityEventSource { 637 private static final boolean DBG = false; 638 639 /** 640 * The logging tag used by this class with android.util.Log. 641 */ 642 protected static final String VIEW_LOG_TAG = "View"; 643 644 /** 645 * Used to mark a View that has no ID. 646 */ 647 public static final int NO_ID = -1; 648 649 /** 650 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 651 * calling setFlags. 652 */ 653 private static final int NOT_FOCUSABLE = 0x00000000; 654 655 /** 656 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 657 * setFlags. 658 */ 659 private static final int FOCUSABLE = 0x00000001; 660 661 /** 662 * Mask for use with setFlags indicating bits used for focus. 663 */ 664 private static final int FOCUSABLE_MASK = 0x00000001; 665 666 /** 667 * This view will adjust its padding to fit sytem windows (e.g. status bar) 668 */ 669 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 670 671 /** 672 * This view is visible. 673 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 674 * android:visibility}. 675 */ 676 public static final int VISIBLE = 0x00000000; 677 678 /** 679 * This view is invisible, but it still takes up space for layout purposes. 680 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 681 * android:visibility}. 682 */ 683 public static final int INVISIBLE = 0x00000004; 684 685 /** 686 * This view is invisible, and it doesn't take any space for layout 687 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 688 * android:visibility}. 689 */ 690 public static final int GONE = 0x00000008; 691 692 /** 693 * Mask for use with setFlags indicating bits used for visibility. 694 * {@hide} 695 */ 696 static final int VISIBILITY_MASK = 0x0000000C; 697 698 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 699 700 /** 701 * This view is enabled. Interpretation varies by subclass. 702 * Use with ENABLED_MASK when calling setFlags. 703 * {@hide} 704 */ 705 static final int ENABLED = 0x00000000; 706 707 /** 708 * This view is disabled. Interpretation varies by subclass. 709 * Use with ENABLED_MASK when calling setFlags. 710 * {@hide} 711 */ 712 static final int DISABLED = 0x00000020; 713 714 /** 715 * Mask for use with setFlags indicating bits used for indicating whether 716 * this view is enabled 717 * {@hide} 718 */ 719 static final int ENABLED_MASK = 0x00000020; 720 721 /** 722 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 723 * called and further optimizations will be performed. It is okay to have 724 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 725 * {@hide} 726 */ 727 static final int WILL_NOT_DRAW = 0x00000080; 728 729 /** 730 * Mask for use with setFlags indicating bits used for indicating whether 731 * this view is will draw 732 * {@hide} 733 */ 734 static final int DRAW_MASK = 0x00000080; 735 736 /** 737 * <p>This view doesn't show scrollbars.</p> 738 * {@hide} 739 */ 740 static final int SCROLLBARS_NONE = 0x00000000; 741 742 /** 743 * <p>This view shows horizontal scrollbars.</p> 744 * {@hide} 745 */ 746 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 747 748 /** 749 * <p>This view shows vertical scrollbars.</p> 750 * {@hide} 751 */ 752 static final int SCROLLBARS_VERTICAL = 0x00000200; 753 754 /** 755 * <p>Mask for use with setFlags indicating bits used for indicating which 756 * scrollbars are enabled.</p> 757 * {@hide} 758 */ 759 static final int SCROLLBARS_MASK = 0x00000300; 760 761 /** 762 * Indicates that the view should filter touches when its window is obscured. 763 * Refer to the class comments for more information about this security feature. 764 * {@hide} 765 */ 766 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 767 768 /** 769 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 770 * that they are optional and should be skipped if the window has 771 * requested system UI flags that ignore those insets for layout. 772 */ 773 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 774 775 /** 776 * <p>This view doesn't show fading edges.</p> 777 * {@hide} 778 */ 779 static final int FADING_EDGE_NONE = 0x00000000; 780 781 /** 782 * <p>This view shows horizontal fading edges.</p> 783 * {@hide} 784 */ 785 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 786 787 /** 788 * <p>This view shows vertical fading edges.</p> 789 * {@hide} 790 */ 791 static final int FADING_EDGE_VERTICAL = 0x00002000; 792 793 /** 794 * <p>Mask for use with setFlags indicating bits used for indicating which 795 * fading edges are enabled.</p> 796 * {@hide} 797 */ 798 static final int FADING_EDGE_MASK = 0x00003000; 799 800 /** 801 * <p>Indicates this view can be clicked. When clickable, a View reacts 802 * to clicks by notifying the OnClickListener.<p> 803 * {@hide} 804 */ 805 static final int CLICKABLE = 0x00004000; 806 807 /** 808 * <p>Indicates this view is caching its drawing into a bitmap.</p> 809 * {@hide} 810 */ 811 static final int DRAWING_CACHE_ENABLED = 0x00008000; 812 813 /** 814 * <p>Indicates that no icicle should be saved for this view.<p> 815 * {@hide} 816 */ 817 static final int SAVE_DISABLED = 0x000010000; 818 819 /** 820 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 821 * property.</p> 822 * {@hide} 823 */ 824 static final int SAVE_DISABLED_MASK = 0x000010000; 825 826 /** 827 * <p>Indicates that no drawing cache should ever be created for this view.<p> 828 * {@hide} 829 */ 830 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 831 832 /** 833 * <p>Indicates this view can take / keep focus when int touch mode.</p> 834 * {@hide} 835 */ 836 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 837 838 /** 839 * <p>Enables low quality mode for the drawing cache.</p> 840 */ 841 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 842 843 /** 844 * <p>Enables high quality mode for the drawing cache.</p> 845 */ 846 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 847 848 /** 849 * <p>Enables automatic quality mode for the drawing cache.</p> 850 */ 851 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 852 853 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 854 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 855 }; 856 857 /** 858 * <p>Mask for use with setFlags indicating bits used for the cache 859 * quality property.</p> 860 * {@hide} 861 */ 862 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 863 864 /** 865 * <p> 866 * Indicates this view can be long clicked. When long clickable, a View 867 * reacts to long clicks by notifying the OnLongClickListener or showing a 868 * context menu. 869 * </p> 870 * {@hide} 871 */ 872 static final int LONG_CLICKABLE = 0x00200000; 873 874 /** 875 * <p>Indicates that this view gets its drawable states from its direct parent 876 * and ignores its original internal states.</p> 877 * 878 * @hide 879 */ 880 static final int DUPLICATE_PARENT_STATE = 0x00400000; 881 882 /** 883 * The scrollbar style to display the scrollbars inside the content area, 884 * without increasing the padding. The scrollbars will be overlaid with 885 * translucency on the view's content. 886 */ 887 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 888 889 /** 890 * The scrollbar style to display the scrollbars inside the padded area, 891 * increasing the padding of the view. The scrollbars will not overlap the 892 * content area of the view. 893 */ 894 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 895 896 /** 897 * The scrollbar style to display the scrollbars at the edge of the view, 898 * without increasing the padding. The scrollbars will be overlaid with 899 * translucency. 900 */ 901 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 902 903 /** 904 * The scrollbar style to display the scrollbars at the edge of the view, 905 * increasing the padding of the view. The scrollbars will only overlap the 906 * background, if any. 907 */ 908 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 909 910 /** 911 * Mask to check if the scrollbar style is overlay or inset. 912 * {@hide} 913 */ 914 static final int SCROLLBARS_INSET_MASK = 0x01000000; 915 916 /** 917 * Mask to check if the scrollbar style is inside or outside. 918 * {@hide} 919 */ 920 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 921 922 /** 923 * Mask for scrollbar style. 924 * {@hide} 925 */ 926 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 927 928 /** 929 * View flag indicating that the screen should remain on while the 930 * window containing this view is visible to the user. This effectively 931 * takes care of automatically setting the WindowManager's 932 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 933 */ 934 public static final int KEEP_SCREEN_ON = 0x04000000; 935 936 /** 937 * View flag indicating whether this view should have sound effects enabled 938 * for events such as clicking and touching. 939 */ 940 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 941 942 /** 943 * View flag indicating whether this view should have haptic feedback 944 * enabled for events such as long presses. 945 */ 946 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 947 948 /** 949 * <p>Indicates that the view hierarchy should stop saving state when 950 * it reaches this view. If state saving is initiated immediately at 951 * the view, it will be allowed. 952 * {@hide} 953 */ 954 static final int PARENT_SAVE_DISABLED = 0x20000000; 955 956 /** 957 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 958 * {@hide} 959 */ 960 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 961 962 /** 963 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 964 * should add all focusable Views regardless if they are focusable in touch mode. 965 */ 966 public static final int FOCUSABLES_ALL = 0x00000000; 967 968 /** 969 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 970 * should add only Views focusable in touch mode. 971 */ 972 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 973 974 /** 975 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 976 * item. 977 */ 978 public static final int FOCUS_BACKWARD = 0x00000001; 979 980 /** 981 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 982 * item. 983 */ 984 public static final int FOCUS_FORWARD = 0x00000002; 985 986 /** 987 * Use with {@link #focusSearch(int)}. Move focus to the left. 988 */ 989 public static final int FOCUS_LEFT = 0x00000011; 990 991 /** 992 * Use with {@link #focusSearch(int)}. Move focus up. 993 */ 994 public static final int FOCUS_UP = 0x00000021; 995 996 /** 997 * Use with {@link #focusSearch(int)}. Move focus to the right. 998 */ 999 public static final int FOCUS_RIGHT = 0x00000042; 1000 1001 /** 1002 * Use with {@link #focusSearch(int)}. Move focus down. 1003 */ 1004 public static final int FOCUS_DOWN = 0x00000082; 1005 1006 /** 1007 * Bits of {@link #getMeasuredWidthAndState()} and 1008 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1009 */ 1010 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1011 1012 /** 1013 * Bits of {@link #getMeasuredWidthAndState()} and 1014 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1015 */ 1016 public static final int MEASURED_STATE_MASK = 0xff000000; 1017 1018 /** 1019 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1020 * for functions that combine both width and height into a single int, 1021 * such as {@link #getMeasuredState()} and the childState argument of 1022 * {@link #resolveSizeAndState(int, int, int)}. 1023 */ 1024 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1025 1026 /** 1027 * Bit of {@link #getMeasuredWidthAndState()} and 1028 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1029 * is smaller that the space the view would like to have. 1030 */ 1031 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1032 1033 /** 1034 * Base View state sets 1035 */ 1036 // Singles 1037 /** 1038 * Indicates the view has no states set. States are used with 1039 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1040 * view depending on its state. 1041 * 1042 * @see android.graphics.drawable.Drawable 1043 * @see #getDrawableState() 1044 */ 1045 protected static final int[] EMPTY_STATE_SET; 1046 /** 1047 * Indicates the view is enabled. States are used with 1048 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1049 * view depending on its state. 1050 * 1051 * @see android.graphics.drawable.Drawable 1052 * @see #getDrawableState() 1053 */ 1054 protected static final int[] ENABLED_STATE_SET; 1055 /** 1056 * Indicates the view is focused. States are used with 1057 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1058 * view depending on its state. 1059 * 1060 * @see android.graphics.drawable.Drawable 1061 * @see #getDrawableState() 1062 */ 1063 protected static final int[] FOCUSED_STATE_SET; 1064 /** 1065 * Indicates the view is selected. States are used with 1066 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1067 * view depending on its state. 1068 * 1069 * @see android.graphics.drawable.Drawable 1070 * @see #getDrawableState() 1071 */ 1072 protected static final int[] SELECTED_STATE_SET; 1073 /** 1074 * Indicates the view is pressed. States are used with 1075 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1076 * view depending on its state. 1077 * 1078 * @see android.graphics.drawable.Drawable 1079 * @see #getDrawableState() 1080 * @hide 1081 */ 1082 protected static final int[] PRESSED_STATE_SET; 1083 /** 1084 * Indicates the view's window has focus. States are used with 1085 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1086 * view depending on its state. 1087 * 1088 * @see android.graphics.drawable.Drawable 1089 * @see #getDrawableState() 1090 */ 1091 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1092 // Doubles 1093 /** 1094 * Indicates the view is enabled and has the focus. 1095 * 1096 * @see #ENABLED_STATE_SET 1097 * @see #FOCUSED_STATE_SET 1098 */ 1099 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1100 /** 1101 * Indicates the view is enabled and selected. 1102 * 1103 * @see #ENABLED_STATE_SET 1104 * @see #SELECTED_STATE_SET 1105 */ 1106 protected static final int[] ENABLED_SELECTED_STATE_SET; 1107 /** 1108 * Indicates the view is enabled and that its window has focus. 1109 * 1110 * @see #ENABLED_STATE_SET 1111 * @see #WINDOW_FOCUSED_STATE_SET 1112 */ 1113 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1114 /** 1115 * Indicates the view is focused and selected. 1116 * 1117 * @see #FOCUSED_STATE_SET 1118 * @see #SELECTED_STATE_SET 1119 */ 1120 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1121 /** 1122 * Indicates the view has the focus and that its window has the focus. 1123 * 1124 * @see #FOCUSED_STATE_SET 1125 * @see #WINDOW_FOCUSED_STATE_SET 1126 */ 1127 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1128 /** 1129 * Indicates the view is selected and that its window has the focus. 1130 * 1131 * @see #SELECTED_STATE_SET 1132 * @see #WINDOW_FOCUSED_STATE_SET 1133 */ 1134 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1135 // Triples 1136 /** 1137 * Indicates the view is enabled, focused and selected. 1138 * 1139 * @see #ENABLED_STATE_SET 1140 * @see #FOCUSED_STATE_SET 1141 * @see #SELECTED_STATE_SET 1142 */ 1143 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1144 /** 1145 * Indicates the view is enabled, focused and its window has the focus. 1146 * 1147 * @see #ENABLED_STATE_SET 1148 * @see #FOCUSED_STATE_SET 1149 * @see #WINDOW_FOCUSED_STATE_SET 1150 */ 1151 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1152 /** 1153 * Indicates the view is enabled, selected and its window has the focus. 1154 * 1155 * @see #ENABLED_STATE_SET 1156 * @see #SELECTED_STATE_SET 1157 * @see #WINDOW_FOCUSED_STATE_SET 1158 */ 1159 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1160 /** 1161 * Indicates the view is focused, selected and its window has the focus. 1162 * 1163 * @see #FOCUSED_STATE_SET 1164 * @see #SELECTED_STATE_SET 1165 * @see #WINDOW_FOCUSED_STATE_SET 1166 */ 1167 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1168 /** 1169 * Indicates the view is enabled, focused, selected and its window 1170 * has the focus. 1171 * 1172 * @see #ENABLED_STATE_SET 1173 * @see #FOCUSED_STATE_SET 1174 * @see #SELECTED_STATE_SET 1175 * @see #WINDOW_FOCUSED_STATE_SET 1176 */ 1177 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1178 /** 1179 * Indicates the view is pressed and its window has the focus. 1180 * 1181 * @see #PRESSED_STATE_SET 1182 * @see #WINDOW_FOCUSED_STATE_SET 1183 */ 1184 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1185 /** 1186 * Indicates the view is pressed and selected. 1187 * 1188 * @see #PRESSED_STATE_SET 1189 * @see #SELECTED_STATE_SET 1190 */ 1191 protected static final int[] PRESSED_SELECTED_STATE_SET; 1192 /** 1193 * Indicates the view is pressed, selected and its window has the focus. 1194 * 1195 * @see #PRESSED_STATE_SET 1196 * @see #SELECTED_STATE_SET 1197 * @see #WINDOW_FOCUSED_STATE_SET 1198 */ 1199 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1200 /** 1201 * Indicates the view is pressed and focused. 1202 * 1203 * @see #PRESSED_STATE_SET 1204 * @see #FOCUSED_STATE_SET 1205 */ 1206 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1207 /** 1208 * Indicates the view is pressed, focused and its window has the focus. 1209 * 1210 * @see #PRESSED_STATE_SET 1211 * @see #FOCUSED_STATE_SET 1212 * @see #WINDOW_FOCUSED_STATE_SET 1213 */ 1214 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1215 /** 1216 * Indicates the view is pressed, focused and selected. 1217 * 1218 * @see #PRESSED_STATE_SET 1219 * @see #SELECTED_STATE_SET 1220 * @see #FOCUSED_STATE_SET 1221 */ 1222 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1223 /** 1224 * Indicates the view is pressed, focused, selected and its window has the focus. 1225 * 1226 * @see #PRESSED_STATE_SET 1227 * @see #FOCUSED_STATE_SET 1228 * @see #SELECTED_STATE_SET 1229 * @see #WINDOW_FOCUSED_STATE_SET 1230 */ 1231 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1232 /** 1233 * Indicates the view is pressed and enabled. 1234 * 1235 * @see #PRESSED_STATE_SET 1236 * @see #ENABLED_STATE_SET 1237 */ 1238 protected static final int[] PRESSED_ENABLED_STATE_SET; 1239 /** 1240 * Indicates the view is pressed, enabled and its window has the focus. 1241 * 1242 * @see #PRESSED_STATE_SET 1243 * @see #ENABLED_STATE_SET 1244 * @see #WINDOW_FOCUSED_STATE_SET 1245 */ 1246 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1247 /** 1248 * Indicates the view is pressed, enabled and selected. 1249 * 1250 * @see #PRESSED_STATE_SET 1251 * @see #ENABLED_STATE_SET 1252 * @see #SELECTED_STATE_SET 1253 */ 1254 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1255 /** 1256 * Indicates the view is pressed, enabled, selected and its window has the 1257 * focus. 1258 * 1259 * @see #PRESSED_STATE_SET 1260 * @see #ENABLED_STATE_SET 1261 * @see #SELECTED_STATE_SET 1262 * @see #WINDOW_FOCUSED_STATE_SET 1263 */ 1264 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1265 /** 1266 * Indicates the view is pressed, enabled and focused. 1267 * 1268 * @see #PRESSED_STATE_SET 1269 * @see #ENABLED_STATE_SET 1270 * @see #FOCUSED_STATE_SET 1271 */ 1272 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1273 /** 1274 * Indicates the view is pressed, enabled, focused and its window has the 1275 * focus. 1276 * 1277 * @see #PRESSED_STATE_SET 1278 * @see #ENABLED_STATE_SET 1279 * @see #FOCUSED_STATE_SET 1280 * @see #WINDOW_FOCUSED_STATE_SET 1281 */ 1282 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1283 /** 1284 * Indicates the view is pressed, enabled, focused and selected. 1285 * 1286 * @see #PRESSED_STATE_SET 1287 * @see #ENABLED_STATE_SET 1288 * @see #SELECTED_STATE_SET 1289 * @see #FOCUSED_STATE_SET 1290 */ 1291 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1292 /** 1293 * Indicates the view is pressed, enabled, focused, selected and its window 1294 * has the focus. 1295 * 1296 * @see #PRESSED_STATE_SET 1297 * @see #ENABLED_STATE_SET 1298 * @see #SELECTED_STATE_SET 1299 * @see #FOCUSED_STATE_SET 1300 * @see #WINDOW_FOCUSED_STATE_SET 1301 */ 1302 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1303 1304 /** 1305 * The order here is very important to {@link #getDrawableState()} 1306 */ 1307 private static final int[][] VIEW_STATE_SETS; 1308 1309 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1310 static final int VIEW_STATE_SELECTED = 1 << 1; 1311 static final int VIEW_STATE_FOCUSED = 1 << 2; 1312 static final int VIEW_STATE_ENABLED = 1 << 3; 1313 static final int VIEW_STATE_PRESSED = 1 << 4; 1314 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1315 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1316 static final int VIEW_STATE_HOVERED = 1 << 7; 1317 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1318 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1319 1320 static final int[] VIEW_STATE_IDS = new int[] { 1321 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1322 R.attr.state_selected, VIEW_STATE_SELECTED, 1323 R.attr.state_focused, VIEW_STATE_FOCUSED, 1324 R.attr.state_enabled, VIEW_STATE_ENABLED, 1325 R.attr.state_pressed, VIEW_STATE_PRESSED, 1326 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1327 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1328 R.attr.state_hovered, VIEW_STATE_HOVERED, 1329 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1330 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED, 1331 }; 1332 1333 static { 1334 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1335 throw new IllegalStateException( 1336 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1337 } 1338 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1339 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1340 int viewState = R.styleable.ViewDrawableStates[i]; 1341 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1342 if (VIEW_STATE_IDS[j] == viewState) { 1343 orderedIds[i * 2] = viewState; 1344 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1345 } 1346 } 1347 } 1348 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1349 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1350 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1351 int numBits = Integer.bitCount(i); 1352 int[] set = new int[numBits]; 1353 int pos = 0; 1354 for (int j = 0; j < orderedIds.length; j += 2) { 1355 if ((i & orderedIds[j+1]) != 0) { 1356 set[pos++] = orderedIds[j]; 1357 } 1358 } 1359 VIEW_STATE_SETS[i] = set; 1360 } 1361 1362 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1363 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1364 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1365 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1366 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1367 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1368 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1369 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1370 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1371 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1372 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1373 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1374 | VIEW_STATE_FOCUSED]; 1375 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1376 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1377 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1378 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1379 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1380 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1381 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1382 | VIEW_STATE_ENABLED]; 1383 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1384 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1385 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1386 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1387 | VIEW_STATE_ENABLED]; 1388 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1389 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1390 | VIEW_STATE_ENABLED]; 1391 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1392 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1393 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1394 1395 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1396 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1397 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1398 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1399 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1400 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1401 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1402 | VIEW_STATE_PRESSED]; 1403 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1404 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1405 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1406 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1407 | VIEW_STATE_PRESSED]; 1408 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1409 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1410 | VIEW_STATE_PRESSED]; 1411 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1412 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1413 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1414 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1415 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1416 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1417 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1418 | VIEW_STATE_PRESSED]; 1419 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1420 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1421 | VIEW_STATE_PRESSED]; 1422 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1423 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1424 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1425 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1426 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1427 | VIEW_STATE_PRESSED]; 1428 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1429 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1430 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1431 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1432 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1433 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1434 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1435 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1436 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1437 | VIEW_STATE_PRESSED]; 1438 } 1439 1440 /** 1441 * Accessibility event types that are dispatched for text population. 1442 */ 1443 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1444 AccessibilityEvent.TYPE_VIEW_CLICKED 1445 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1446 | AccessibilityEvent.TYPE_VIEW_SELECTED 1447 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1448 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1449 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1450 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1451 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1452 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED; 1453 1454 /** 1455 * Temporary Rect currently for use in setBackground(). This will probably 1456 * be extended in the future to hold our own class with more than just 1457 * a Rect. :) 1458 */ 1459 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1460 1461 /** 1462 * Temporary flag, used to enable processing of View properties in the native DisplayList 1463 * object instead of during draw(). Soon to be enabled by default for hardware-accelerated 1464 * apps. 1465 * @hide 1466 */ 1467 public static final boolean USE_DISPLAY_LIST_PROPERTIES = true; 1468 1469 /** 1470 * Map used to store views' tags. 1471 */ 1472 private SparseArray<Object> mKeyedTags; 1473 1474 /** 1475 * The next available accessiiblity id. 1476 */ 1477 private static int sNextAccessibilityViewId; 1478 1479 /** 1480 * The animation currently associated with this view. 1481 * @hide 1482 */ 1483 protected Animation mCurrentAnimation = null; 1484 1485 /** 1486 * Width as measured during measure pass. 1487 * {@hide} 1488 */ 1489 @ViewDebug.ExportedProperty(category = "measurement") 1490 int mMeasuredWidth; 1491 1492 /** 1493 * Height as measured during measure pass. 1494 * {@hide} 1495 */ 1496 @ViewDebug.ExportedProperty(category = "measurement") 1497 int mMeasuredHeight; 1498 1499 /** 1500 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1501 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1502 * its display list. This flag, used only when hw accelerated, allows us to clear the 1503 * flag while retaining this information until it's needed (at getDisplayList() time and 1504 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1505 * 1506 * {@hide} 1507 */ 1508 boolean mRecreateDisplayList = false; 1509 1510 /** 1511 * The view's identifier. 1512 * {@hide} 1513 * 1514 * @see #setId(int) 1515 * @see #getId() 1516 */ 1517 @ViewDebug.ExportedProperty(resolveId = true) 1518 int mID = NO_ID; 1519 1520 /** 1521 * The stable ID of this view for accessibility purposes. 1522 */ 1523 int mAccessibilityViewId = NO_ID; 1524 1525 /** 1526 * The view's tag. 1527 * {@hide} 1528 * 1529 * @see #setTag(Object) 1530 * @see #getTag() 1531 */ 1532 protected Object mTag; 1533 1534 // for mPrivateFlags: 1535 /** {@hide} */ 1536 static final int WANTS_FOCUS = 0x00000001; 1537 /** {@hide} */ 1538 static final int FOCUSED = 0x00000002; 1539 /** {@hide} */ 1540 static final int SELECTED = 0x00000004; 1541 /** {@hide} */ 1542 static final int IS_ROOT_NAMESPACE = 0x00000008; 1543 /** {@hide} */ 1544 static final int HAS_BOUNDS = 0x00000010; 1545 /** {@hide} */ 1546 static final int DRAWN = 0x00000020; 1547 /** 1548 * When this flag is set, this view is running an animation on behalf of its 1549 * children and should therefore not cancel invalidate requests, even if they 1550 * lie outside of this view's bounds. 1551 * 1552 * {@hide} 1553 */ 1554 static final int DRAW_ANIMATION = 0x00000040; 1555 /** {@hide} */ 1556 static final int SKIP_DRAW = 0x00000080; 1557 /** {@hide} */ 1558 static final int ONLY_DRAWS_BACKGROUND = 0x00000100; 1559 /** {@hide} */ 1560 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1561 /** {@hide} */ 1562 static final int DRAWABLE_STATE_DIRTY = 0x00000400; 1563 /** {@hide} */ 1564 static final int MEASURED_DIMENSION_SET = 0x00000800; 1565 /** {@hide} */ 1566 static final int FORCE_LAYOUT = 0x00001000; 1567 /** {@hide} */ 1568 static final int LAYOUT_REQUIRED = 0x00002000; 1569 1570 private static final int PRESSED = 0x00004000; 1571 1572 /** {@hide} */ 1573 static final int DRAWING_CACHE_VALID = 0x00008000; 1574 /** 1575 * Flag used to indicate that this view should be drawn once more (and only once 1576 * more) after its animation has completed. 1577 * {@hide} 1578 */ 1579 static final int ANIMATION_STARTED = 0x00010000; 1580 1581 private static final int SAVE_STATE_CALLED = 0x00020000; 1582 1583 /** 1584 * Indicates that the View returned true when onSetAlpha() was called and that 1585 * the alpha must be restored. 1586 * {@hide} 1587 */ 1588 static final int ALPHA_SET = 0x00040000; 1589 1590 /** 1591 * Set by {@link #setScrollContainer(boolean)}. 1592 */ 1593 static final int SCROLL_CONTAINER = 0x00080000; 1594 1595 /** 1596 * Set by {@link #setScrollContainer(boolean)}. 1597 */ 1598 static final int SCROLL_CONTAINER_ADDED = 0x00100000; 1599 1600 /** 1601 * View flag indicating whether this view was invalidated (fully or partially.) 1602 * 1603 * @hide 1604 */ 1605 static final int DIRTY = 0x00200000; 1606 1607 /** 1608 * View flag indicating whether this view was invalidated by an opaque 1609 * invalidate request. 1610 * 1611 * @hide 1612 */ 1613 static final int DIRTY_OPAQUE = 0x00400000; 1614 1615 /** 1616 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}. 1617 * 1618 * @hide 1619 */ 1620 static final int DIRTY_MASK = 0x00600000; 1621 1622 /** 1623 * Indicates whether the background is opaque. 1624 * 1625 * @hide 1626 */ 1627 static final int OPAQUE_BACKGROUND = 0x00800000; 1628 1629 /** 1630 * Indicates whether the scrollbars are opaque. 1631 * 1632 * @hide 1633 */ 1634 static final int OPAQUE_SCROLLBARS = 0x01000000; 1635 1636 /** 1637 * Indicates whether the view is opaque. 1638 * 1639 * @hide 1640 */ 1641 static final int OPAQUE_MASK = 0x01800000; 1642 1643 /** 1644 * Indicates a prepressed state; 1645 * the short time between ACTION_DOWN and recognizing 1646 * a 'real' press. Prepressed is used to recognize quick taps 1647 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1648 * 1649 * @hide 1650 */ 1651 private static final int PREPRESSED = 0x02000000; 1652 1653 /** 1654 * Indicates whether the view is temporarily detached. 1655 * 1656 * @hide 1657 */ 1658 static final int CANCEL_NEXT_UP_EVENT = 0x04000000; 1659 1660 /** 1661 * Indicates that we should awaken scroll bars once attached 1662 * 1663 * @hide 1664 */ 1665 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1666 1667 /** 1668 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1669 * @hide 1670 */ 1671 private static final int HOVERED = 0x10000000; 1672 1673 /** 1674 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1675 * for transform operations 1676 * 1677 * @hide 1678 */ 1679 private static final int PIVOT_EXPLICITLY_SET = 0x20000000; 1680 1681 /** {@hide} */ 1682 static final int ACTIVATED = 0x40000000; 1683 1684 /** 1685 * Indicates that this view was specifically invalidated, not just dirtied because some 1686 * child view was invalidated. The flag is used to determine when we need to recreate 1687 * a view's display list (as opposed to just returning a reference to its existing 1688 * display list). 1689 * 1690 * @hide 1691 */ 1692 static final int INVALIDATED = 0x80000000; 1693 1694 /* Masks for mPrivateFlags2 */ 1695 1696 /** 1697 * Indicates that this view has reported that it can accept the current drag's content. 1698 * Cleared when the drag operation concludes. 1699 * @hide 1700 */ 1701 static final int DRAG_CAN_ACCEPT = 0x00000001; 1702 1703 /** 1704 * Indicates that this view is currently directly under the drag location in a 1705 * drag-and-drop operation involving content that it can accept. Cleared when 1706 * the drag exits the view, or when the drag operation concludes. 1707 * @hide 1708 */ 1709 static final int DRAG_HOVERED = 0x00000002; 1710 1711 /** 1712 * Horizontal layout direction of this view is from Left to Right. 1713 * Use with {@link #setLayoutDirection}. 1714 */ 1715 public static final int LAYOUT_DIRECTION_LTR = 0; 1716 1717 /** 1718 * Horizontal layout direction of this view is from Right to Left. 1719 * Use with {@link #setLayoutDirection}. 1720 */ 1721 public static final int LAYOUT_DIRECTION_RTL = 1; 1722 1723 /** 1724 * Horizontal layout direction of this view is inherited from its parent. 1725 * Use with {@link #setLayoutDirection}. 1726 */ 1727 public static final int LAYOUT_DIRECTION_INHERIT = 2; 1728 1729 /** 1730 * Horizontal layout direction of this view is from deduced from the default language 1731 * script for the locale. Use with {@link #setLayoutDirection}. 1732 */ 1733 public static final int LAYOUT_DIRECTION_LOCALE = 3; 1734 1735 /** 1736 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1737 * @hide 1738 */ 1739 static final int LAYOUT_DIRECTION_MASK_SHIFT = 2; 1740 1741 /** 1742 * Mask for use with private flags indicating bits used for horizontal layout direction. 1743 * @hide 1744 */ 1745 static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT; 1746 1747 /** 1748 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1749 * right-to-left direction. 1750 * @hide 1751 */ 1752 static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT; 1753 1754 /** 1755 * Indicates whether the view horizontal layout direction has been resolved. 1756 * @hide 1757 */ 1758 static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT; 1759 1760 /** 1761 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1762 * @hide 1763 */ 1764 static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT; 1765 1766 /* 1767 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1768 * flag value. 1769 * @hide 1770 */ 1771 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1772 LAYOUT_DIRECTION_LTR, 1773 LAYOUT_DIRECTION_RTL, 1774 LAYOUT_DIRECTION_INHERIT, 1775 LAYOUT_DIRECTION_LOCALE 1776 }; 1777 1778 /** 1779 * Default horizontal layout direction. 1780 * @hide 1781 */ 1782 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1783 1784 1785 /** 1786 * Indicates that the view is tracking some sort of transient state 1787 * that the app should not need to be aware of, but that the framework 1788 * should take special care to preserve. 1789 * 1790 * @hide 1791 */ 1792 static final int HAS_TRANSIENT_STATE = 0x00000100; 1793 1794 1795 /** 1796 * Text direction is inherited thru {@link ViewGroup} 1797 */ 1798 public static final int TEXT_DIRECTION_INHERIT = 0; 1799 1800 /** 1801 * Text direction is using "first strong algorithm". The first strong directional character 1802 * determines the paragraph direction. If there is no strong directional character, the 1803 * paragraph direction is the view's resolved layout direction. 1804 */ 1805 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1806 1807 /** 1808 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1809 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1810 * If there are neither, the paragraph direction is the view's resolved layout direction. 1811 */ 1812 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1813 1814 /** 1815 * Text direction is forced to LTR. 1816 */ 1817 public static final int TEXT_DIRECTION_LTR = 3; 1818 1819 /** 1820 * Text direction is forced to RTL. 1821 */ 1822 public static final int TEXT_DIRECTION_RTL = 4; 1823 1824 /** 1825 * Text direction is coming from the system Locale. 1826 */ 1827 public static final int TEXT_DIRECTION_LOCALE = 5; 1828 1829 /** 1830 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 1831 * @hide 1832 */ 1833 static final int TEXT_DIRECTION_MASK_SHIFT = 6; 1834 1835 /** 1836 * Default text direction is inherited 1837 */ 1838 protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 1839 1840 /** 1841 * Mask for use with private flags indicating bits used for text direction. 1842 * @hide 1843 */ 1844 static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT; 1845 1846 /** 1847 * Array of text direction flags for mapping attribute "textDirection" to correct 1848 * flag value. 1849 * @hide 1850 */ 1851 private static final int[] TEXT_DIRECTION_FLAGS = { 1852 TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT, 1853 TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT, 1854 TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT, 1855 TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT, 1856 TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT, 1857 TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT 1858 }; 1859 1860 /** 1861 * Indicates whether the view text direction has been resolved. 1862 * @hide 1863 */ 1864 static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT; 1865 1866 /** 1867 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1868 * @hide 1869 */ 1870 static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 1871 1872 /** 1873 * Mask for use with private flags indicating bits used for resolved text direction. 1874 * @hide 1875 */ 1876 static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1877 1878 /** 1879 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 1880 * @hide 1881 */ 1882 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = 1883 TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1884 1885 1886 /* End of masks for mPrivateFlags2 */ 1887 1888 static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED; 1889 1890 /** 1891 * Always allow a user to over-scroll this view, provided it is a 1892 * view that can scroll. 1893 * 1894 * @see #getOverScrollMode() 1895 * @see #setOverScrollMode(int) 1896 */ 1897 public static final int OVER_SCROLL_ALWAYS = 0; 1898 1899 /** 1900 * Allow a user to over-scroll this view only if the content is large 1901 * enough to meaningfully scroll, provided it is a view that can scroll. 1902 * 1903 * @see #getOverScrollMode() 1904 * @see #setOverScrollMode(int) 1905 */ 1906 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 1907 1908 /** 1909 * Never allow a user to over-scroll this view. 1910 * 1911 * @see #getOverScrollMode() 1912 * @see #setOverScrollMode(int) 1913 */ 1914 public static final int OVER_SCROLL_NEVER = 2; 1915 1916 /** 1917 * Special constant for {@link #setSystemUiVisibility(int)}: View has 1918 * requested the system UI (status bar) to be visible (the default). 1919 * 1920 * @see #setSystemUiVisibility(int) 1921 */ 1922 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 1923 1924 /** 1925 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 1926 * system UI to enter an unobtrusive "low profile" mode. 1927 * 1928 * <p>This is for use in games, book readers, video players, or any other 1929 * "immersive" application where the usual system chrome is deemed too distracting. 1930 * 1931 * <p>In low profile mode, the status bar and/or navigation icons may dim. 1932 * 1933 * @see #setSystemUiVisibility(int) 1934 */ 1935 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 1936 1937 /** 1938 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 1939 * system navigation be temporarily hidden. 1940 * 1941 * <p>This is an even less obtrusive state than that called for by 1942 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 1943 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 1944 * those to disappear. This is useful (in conjunction with the 1945 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 1946 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 1947 * window flags) for displaying content using every last pixel on the display. 1948 * 1949 * <p>There is a limitation: because navigation controls are so important, the least user 1950 * interaction will cause them to reappear immediately. When this happens, both 1951 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 1952 * so that both elements reappear at the same time. 1953 * 1954 * @see #setSystemUiVisibility(int) 1955 */ 1956 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 1957 1958 /** 1959 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 1960 * into the normal fullscreen mode so that its content can take over the screen 1961 * while still allowing the user to interact with the application. 1962 * 1963 * <p>This has the same visual effect as 1964 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 1965 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 1966 * meaning that non-critical screen decorations (such as the status bar) will be 1967 * hidden while the user is in the View's window, focusing the experience on 1968 * that content. Unlike the window flag, if you are using ActionBar in 1969 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 1970 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 1971 * hide the action bar. 1972 * 1973 * <p>This approach to going fullscreen is best used over the window flag when 1974 * it is a transient state -- that is, the application does this at certain 1975 * points in its user interaction where it wants to allow the user to focus 1976 * on content, but not as a continuous state. For situations where the application 1977 * would like to simply stay full screen the entire time (such as a game that 1978 * wants to take over the screen), the 1979 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 1980 * is usually a better approach. The state set here will be removed by the system 1981 * in various situations (such as the user moving to another application) like 1982 * the other system UI states. 1983 * 1984 * <p>When using this flag, the application should provide some easy facility 1985 * for the user to go out of it. A common example would be in an e-book 1986 * reader, where tapping on the screen brings back whatever screen and UI 1987 * decorations that had been hidden while the user was immersed in reading 1988 * the book. 1989 * 1990 * @see #setSystemUiVisibility(int) 1991 */ 1992 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 1993 1994 /** 1995 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 1996 * flags, we would like a stable view of the content insets given to 1997 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 1998 * will always represent the worst case that the application can expect 1999 * as a continue state. In practice this means with any of system bar, 2000 * nav bar, and status bar shown, but not the space that would be needed 2001 * for an input method. 2002 * 2003 * <p>If you are using ActionBar in 2004 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2005 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2006 * insets it adds to those given to the application. 2007 */ 2008 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2009 2010 /** 2011 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2012 * to be layed out as if it has requested 2013 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2014 * allows it to avoid artifacts when switching in and out of that mode, at 2015 * the expense that some of its user interface may be covered by screen 2016 * decorations when they are shown. You can perform layout of your inner 2017 * UI elements to account for the navagation system UI through the 2018 * {@link #fitSystemWindows(Rect)} method. 2019 */ 2020 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2021 2022 /** 2023 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2024 * to be layed out as if it has requested 2025 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2026 * allows it to avoid artifacts when switching in and out of that mode, at 2027 * the expense that some of its user interface may be covered by screen 2028 * decorations when they are shown. You can perform layout of your inner 2029 * UI elements to account for non-fullscreen system UI through the 2030 * {@link #fitSystemWindows(Rect)} method. 2031 */ 2032 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2033 2034 /** 2035 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2036 */ 2037 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2038 2039 /** 2040 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2041 */ 2042 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2043 2044 /** 2045 * @hide 2046 * 2047 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2048 * out of the public fields to keep the undefined bits out of the developer's way. 2049 * 2050 * Flag to make the status bar not expandable. Unless you also 2051 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2052 */ 2053 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2054 2055 /** 2056 * @hide 2057 * 2058 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2059 * out of the public fields to keep the undefined bits out of the developer's way. 2060 * 2061 * Flag to hide notification icons and scrolling ticker text. 2062 */ 2063 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2064 2065 /** 2066 * @hide 2067 * 2068 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2069 * out of the public fields to keep the undefined bits out of the developer's way. 2070 * 2071 * Flag to disable incoming notification alerts. This will not block 2072 * icons, but it will block sound, vibrating and other visual or aural notifications. 2073 */ 2074 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2075 2076 /** 2077 * @hide 2078 * 2079 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2080 * out of the public fields to keep the undefined bits out of the developer's way. 2081 * 2082 * Flag to hide only the scrolling ticker. Note that 2083 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2084 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2085 */ 2086 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2087 2088 /** 2089 * @hide 2090 * 2091 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2092 * out of the public fields to keep the undefined bits out of the developer's way. 2093 * 2094 * Flag to hide the center system info area. 2095 */ 2096 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2097 2098 /** 2099 * @hide 2100 * 2101 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2102 * out of the public fields to keep the undefined bits out of the developer's way. 2103 * 2104 * Flag to hide only the home button. Don't use this 2105 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2106 */ 2107 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2108 2109 /** 2110 * @hide 2111 * 2112 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2113 * out of the public fields to keep the undefined bits out of the developer's way. 2114 * 2115 * Flag to hide only the back button. Don't use this 2116 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2117 */ 2118 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2119 2120 /** 2121 * @hide 2122 * 2123 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2124 * out of the public fields to keep the undefined bits out of the developer's way. 2125 * 2126 * Flag to hide only the clock. You might use this if your activity has 2127 * its own clock making the status bar's clock redundant. 2128 */ 2129 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2130 2131 /** 2132 * @hide 2133 * 2134 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2135 * out of the public fields to keep the undefined bits out of the developer's way. 2136 * 2137 * Flag to hide only the recent apps button. Don't use this 2138 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2139 */ 2140 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2141 2142 /** 2143 * @hide 2144 */ 2145 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2146 2147 /** 2148 * These are the system UI flags that can be cleared by events outside 2149 * of an application. Currently this is just the ability to tap on the 2150 * screen while hiding the navigation bar to have it return. 2151 * @hide 2152 */ 2153 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2154 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2155 | SYSTEM_UI_FLAG_FULLSCREEN; 2156 2157 /** 2158 * Flags that can impact the layout in relation to system UI. 2159 */ 2160 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2161 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2162 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2163 2164 /** 2165 * Find views that render the specified text. 2166 * 2167 * @see #findViewsWithText(ArrayList, CharSequence, int) 2168 */ 2169 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2170 2171 /** 2172 * Find find views that contain the specified content description. 2173 * 2174 * @see #findViewsWithText(ArrayList, CharSequence, int) 2175 */ 2176 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2177 2178 /** 2179 * Find views that contain {@link AccessibilityNodeProvider}. Such 2180 * a View is a root of virtual view hierarchy and may contain the searched 2181 * text. If this flag is set Views with providers are automatically 2182 * added and it is a responsibility of the client to call the APIs of 2183 * the provider to determine whether the virtual tree rooted at this View 2184 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2185 * represeting the virtual views with this text. 2186 * 2187 * @see #findViewsWithText(ArrayList, CharSequence, int) 2188 * 2189 * @hide 2190 */ 2191 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2192 2193 /** 2194 * Indicates that the screen has changed state and is now off. 2195 * 2196 * @see #onScreenStateChanged(int) 2197 */ 2198 public static final int SCREEN_STATE_OFF = 0x0; 2199 2200 /** 2201 * Indicates that the screen has changed state and is now on. 2202 * 2203 * @see #onScreenStateChanged(int) 2204 */ 2205 public static final int SCREEN_STATE_ON = 0x1; 2206 2207 /** 2208 * Controls the over-scroll mode for this view. 2209 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2210 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2211 * and {@link #OVER_SCROLL_NEVER}. 2212 */ 2213 private int mOverScrollMode; 2214 2215 /** 2216 * The parent this view is attached to. 2217 * {@hide} 2218 * 2219 * @see #getParent() 2220 */ 2221 protected ViewParent mParent; 2222 2223 /** 2224 * {@hide} 2225 */ 2226 AttachInfo mAttachInfo; 2227 2228 /** 2229 * {@hide} 2230 */ 2231 @ViewDebug.ExportedProperty(flagMapping = { 2232 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT, 2233 name = "FORCE_LAYOUT"), 2234 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED, 2235 name = "LAYOUT_REQUIRED"), 2236 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID, 2237 name = "DRAWING_CACHE_INVALID", outputIf = false), 2238 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true), 2239 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false), 2240 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2241 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY") 2242 }) 2243 int mPrivateFlags; 2244 int mPrivateFlags2; 2245 2246 /** 2247 * This view's request for the visibility of the status bar. 2248 * @hide 2249 */ 2250 @ViewDebug.ExportedProperty(flagMapping = { 2251 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2252 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2253 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2254 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2255 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2256 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2257 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2258 equals = SYSTEM_UI_FLAG_VISIBLE, 2259 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2260 }) 2261 int mSystemUiVisibility; 2262 2263 /** 2264 * Count of how many windows this view has been attached to. 2265 */ 2266 int mWindowAttachCount; 2267 2268 /** 2269 * The layout parameters associated with this view and used by the parent 2270 * {@link android.view.ViewGroup} to determine how this view should be 2271 * laid out. 2272 * {@hide} 2273 */ 2274 protected ViewGroup.LayoutParams mLayoutParams; 2275 2276 /** 2277 * The view flags hold various views states. 2278 * {@hide} 2279 */ 2280 @ViewDebug.ExportedProperty 2281 int mViewFlags; 2282 2283 static class TransformationInfo { 2284 /** 2285 * The transform matrix for the View. This transform is calculated internally 2286 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2287 * is used by default. Do *not* use this variable directly; instead call 2288 * getMatrix(), which will automatically recalculate the matrix if necessary 2289 * to get the correct matrix based on the latest rotation and scale properties. 2290 */ 2291 private final Matrix mMatrix = new Matrix(); 2292 2293 /** 2294 * The transform matrix for the View. This transform is calculated internally 2295 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2296 * is used by default. Do *not* use this variable directly; instead call 2297 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2298 * to get the correct matrix based on the latest rotation and scale properties. 2299 */ 2300 private Matrix mInverseMatrix; 2301 2302 /** 2303 * An internal variable that tracks whether we need to recalculate the 2304 * transform matrix, based on whether the rotation or scaleX/Y properties 2305 * have changed since the matrix was last calculated. 2306 */ 2307 boolean mMatrixDirty = false; 2308 2309 /** 2310 * An internal variable that tracks whether we need to recalculate the 2311 * transform matrix, based on whether the rotation or scaleX/Y properties 2312 * have changed since the matrix was last calculated. 2313 */ 2314 private boolean mInverseMatrixDirty = true; 2315 2316 /** 2317 * A variable that tracks whether we need to recalculate the 2318 * transform matrix, based on whether the rotation or scaleX/Y properties 2319 * have changed since the matrix was last calculated. This variable 2320 * is only valid after a call to updateMatrix() or to a function that 2321 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2322 */ 2323 private boolean mMatrixIsIdentity = true; 2324 2325 /** 2326 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2327 */ 2328 private Camera mCamera = null; 2329 2330 /** 2331 * This matrix is used when computing the matrix for 3D rotations. 2332 */ 2333 private Matrix matrix3D = null; 2334 2335 /** 2336 * These prev values are used to recalculate a centered pivot point when necessary. The 2337 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2338 * set), so thes values are only used then as well. 2339 */ 2340 private int mPrevWidth = -1; 2341 private int mPrevHeight = -1; 2342 2343 /** 2344 * The degrees rotation around the vertical axis through the pivot point. 2345 */ 2346 @ViewDebug.ExportedProperty 2347 float mRotationY = 0f; 2348 2349 /** 2350 * The degrees rotation around the horizontal axis through the pivot point. 2351 */ 2352 @ViewDebug.ExportedProperty 2353 float mRotationX = 0f; 2354 2355 /** 2356 * The degrees rotation around the pivot point. 2357 */ 2358 @ViewDebug.ExportedProperty 2359 float mRotation = 0f; 2360 2361 /** 2362 * The amount of translation of the object away from its left property (post-layout). 2363 */ 2364 @ViewDebug.ExportedProperty 2365 float mTranslationX = 0f; 2366 2367 /** 2368 * The amount of translation of the object away from its top property (post-layout). 2369 */ 2370 @ViewDebug.ExportedProperty 2371 float mTranslationY = 0f; 2372 2373 /** 2374 * The amount of scale in the x direction around the pivot point. A 2375 * value of 1 means no scaling is applied. 2376 */ 2377 @ViewDebug.ExportedProperty 2378 float mScaleX = 1f; 2379 2380 /** 2381 * The amount of scale in the y direction around the pivot point. A 2382 * value of 1 means no scaling is applied. 2383 */ 2384 @ViewDebug.ExportedProperty 2385 float mScaleY = 1f; 2386 2387 /** 2388 * The x location of the point around which the view is rotated and scaled. 2389 */ 2390 @ViewDebug.ExportedProperty 2391 float mPivotX = 0f; 2392 2393 /** 2394 * The y location of the point around which the view is rotated and scaled. 2395 */ 2396 @ViewDebug.ExportedProperty 2397 float mPivotY = 0f; 2398 2399 /** 2400 * The opacity of the View. This is a value from 0 to 1, where 0 means 2401 * completely transparent and 1 means completely opaque. 2402 */ 2403 @ViewDebug.ExportedProperty 2404 float mAlpha = 1f; 2405 } 2406 2407 TransformationInfo mTransformationInfo; 2408 2409 private boolean mLastIsOpaque; 2410 2411 /** 2412 * Convenience value to check for float values that are close enough to zero to be considered 2413 * zero. 2414 */ 2415 private static final float NONZERO_EPSILON = .001f; 2416 2417 /** 2418 * The distance in pixels from the left edge of this view's parent 2419 * to the left edge of this view. 2420 * {@hide} 2421 */ 2422 @ViewDebug.ExportedProperty(category = "layout") 2423 protected int mLeft; 2424 /** 2425 * The distance in pixels from the left edge of this view's parent 2426 * to the right edge of this view. 2427 * {@hide} 2428 */ 2429 @ViewDebug.ExportedProperty(category = "layout") 2430 protected int mRight; 2431 /** 2432 * The distance in pixels from the top edge of this view's parent 2433 * to the top edge of this view. 2434 * {@hide} 2435 */ 2436 @ViewDebug.ExportedProperty(category = "layout") 2437 protected int mTop; 2438 /** 2439 * The distance in pixels from the top edge of this view's parent 2440 * to the bottom edge of this view. 2441 * {@hide} 2442 */ 2443 @ViewDebug.ExportedProperty(category = "layout") 2444 protected int mBottom; 2445 2446 /** 2447 * The offset, in pixels, by which the content of this view is scrolled 2448 * horizontally. 2449 * {@hide} 2450 */ 2451 @ViewDebug.ExportedProperty(category = "scrolling") 2452 protected int mScrollX; 2453 /** 2454 * The offset, in pixels, by which the content of this view is scrolled 2455 * vertically. 2456 * {@hide} 2457 */ 2458 @ViewDebug.ExportedProperty(category = "scrolling") 2459 protected int mScrollY; 2460 2461 /** 2462 * The left padding in pixels, that is the distance in pixels between the 2463 * left edge of this view and the left edge of its content. 2464 * {@hide} 2465 */ 2466 @ViewDebug.ExportedProperty(category = "padding") 2467 protected int mPaddingLeft; 2468 /** 2469 * The right padding in pixels, that is the distance in pixels between the 2470 * right edge of this view and the right edge of its content. 2471 * {@hide} 2472 */ 2473 @ViewDebug.ExportedProperty(category = "padding") 2474 protected int mPaddingRight; 2475 /** 2476 * The top padding in pixels, that is the distance in pixels between the 2477 * top edge of this view and the top edge of its content. 2478 * {@hide} 2479 */ 2480 @ViewDebug.ExportedProperty(category = "padding") 2481 protected int mPaddingTop; 2482 /** 2483 * The bottom padding in pixels, that is the distance in pixels between the 2484 * bottom edge of this view and the bottom edge of its content. 2485 * {@hide} 2486 */ 2487 @ViewDebug.ExportedProperty(category = "padding") 2488 protected int mPaddingBottom; 2489 2490 /** 2491 * Briefly describes the view and is primarily used for accessibility support. 2492 */ 2493 private CharSequence mContentDescription; 2494 2495 /** 2496 * Cache the paddingRight set by the user to append to the scrollbar's size. 2497 * 2498 * @hide 2499 */ 2500 @ViewDebug.ExportedProperty(category = "padding") 2501 protected int mUserPaddingRight; 2502 2503 /** 2504 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2505 * 2506 * @hide 2507 */ 2508 @ViewDebug.ExportedProperty(category = "padding") 2509 protected int mUserPaddingBottom; 2510 2511 /** 2512 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2513 * 2514 * @hide 2515 */ 2516 @ViewDebug.ExportedProperty(category = "padding") 2517 protected int mUserPaddingLeft; 2518 2519 /** 2520 * Cache if the user padding is relative. 2521 * 2522 */ 2523 @ViewDebug.ExportedProperty(category = "padding") 2524 boolean mUserPaddingRelative; 2525 2526 /** 2527 * Cache the paddingStart set by the user to append to the scrollbar's size. 2528 * 2529 */ 2530 @ViewDebug.ExportedProperty(category = "padding") 2531 int mUserPaddingStart; 2532 2533 /** 2534 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2535 * 2536 */ 2537 @ViewDebug.ExportedProperty(category = "padding") 2538 int mUserPaddingEnd; 2539 2540 /** 2541 * @hide 2542 */ 2543 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2544 /** 2545 * @hide 2546 */ 2547 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2548 2549 private Drawable mBGDrawable; 2550 2551 private int mBackgroundResource; 2552 private boolean mBackgroundSizeChanged; 2553 2554 static class ListenerInfo { 2555 /** 2556 * Listener used to dispatch focus change events. 2557 * This field should be made private, so it is hidden from the SDK. 2558 * {@hide} 2559 */ 2560 protected OnFocusChangeListener mOnFocusChangeListener; 2561 2562 /** 2563 * Listeners for layout change events. 2564 */ 2565 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2566 2567 /** 2568 * Listeners for attach events. 2569 */ 2570 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2571 2572 /** 2573 * Listener used to dispatch click events. 2574 * This field should be made private, so it is hidden from the SDK. 2575 * {@hide} 2576 */ 2577 public OnClickListener mOnClickListener; 2578 2579 /** 2580 * Listener used to dispatch long click events. 2581 * This field should be made private, so it is hidden from the SDK. 2582 * {@hide} 2583 */ 2584 protected OnLongClickListener mOnLongClickListener; 2585 2586 /** 2587 * Listener used to build the context menu. 2588 * This field should be made private, so it is hidden from the SDK. 2589 * {@hide} 2590 */ 2591 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2592 2593 private OnKeyListener mOnKeyListener; 2594 2595 private OnTouchListener mOnTouchListener; 2596 2597 private OnHoverListener mOnHoverListener; 2598 2599 private OnGenericMotionListener mOnGenericMotionListener; 2600 2601 private OnDragListener mOnDragListener; 2602 2603 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2604 } 2605 2606 ListenerInfo mListenerInfo; 2607 2608 /** 2609 * The application environment this view lives in. 2610 * This field should be made private, so it is hidden from the SDK. 2611 * {@hide} 2612 */ 2613 protected Context mContext; 2614 2615 private final Resources mResources; 2616 2617 private ScrollabilityCache mScrollCache; 2618 2619 private int[] mDrawableState = null; 2620 2621 /** 2622 * Set to true when drawing cache is enabled and cannot be created. 2623 * 2624 * @hide 2625 */ 2626 public boolean mCachingFailed; 2627 2628 private Bitmap mDrawingCache; 2629 private Bitmap mUnscaledDrawingCache; 2630 private HardwareLayer mHardwareLayer; 2631 DisplayList mDisplayList; 2632 2633 /** 2634 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2635 * the user may specify which view to go to next. 2636 */ 2637 private int mNextFocusLeftId = View.NO_ID; 2638 2639 /** 2640 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2641 * the user may specify which view to go to next. 2642 */ 2643 private int mNextFocusRightId = View.NO_ID; 2644 2645 /** 2646 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2647 * the user may specify which view to go to next. 2648 */ 2649 private int mNextFocusUpId = View.NO_ID; 2650 2651 /** 2652 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2653 * the user may specify which view to go to next. 2654 */ 2655 private int mNextFocusDownId = View.NO_ID; 2656 2657 /** 2658 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 2659 * the user may specify which view to go to next. 2660 */ 2661 int mNextFocusForwardId = View.NO_ID; 2662 2663 private CheckForLongPress mPendingCheckForLongPress; 2664 private CheckForTap mPendingCheckForTap = null; 2665 private PerformClick mPerformClick; 2666 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 2667 2668 private UnsetPressedState mUnsetPressedState; 2669 2670 /** 2671 * Whether the long press's action has been invoked. The tap's action is invoked on the 2672 * up event while a long press is invoked as soon as the long press duration is reached, so 2673 * a long press could be performed before the tap is checked, in which case the tap's action 2674 * should not be invoked. 2675 */ 2676 private boolean mHasPerformedLongPress; 2677 2678 /** 2679 * The minimum height of the view. We'll try our best to have the height 2680 * of this view to at least this amount. 2681 */ 2682 @ViewDebug.ExportedProperty(category = "measurement") 2683 private int mMinHeight; 2684 2685 /** 2686 * The minimum width of the view. We'll try our best to have the width 2687 * of this view to at least this amount. 2688 */ 2689 @ViewDebug.ExportedProperty(category = "measurement") 2690 private int mMinWidth; 2691 2692 /** 2693 * The delegate to handle touch events that are physically in this view 2694 * but should be handled by another view. 2695 */ 2696 private TouchDelegate mTouchDelegate = null; 2697 2698 /** 2699 * Solid color to use as a background when creating the drawing cache. Enables 2700 * the cache to use 16 bit bitmaps instead of 32 bit. 2701 */ 2702 private int mDrawingCacheBackgroundColor = 0; 2703 2704 /** 2705 * Special tree observer used when mAttachInfo is null. 2706 */ 2707 private ViewTreeObserver mFloatingTreeObserver; 2708 2709 /** 2710 * Cache the touch slop from the context that created the view. 2711 */ 2712 private int mTouchSlop; 2713 2714 /** 2715 * Object that handles automatic animation of view properties. 2716 */ 2717 private ViewPropertyAnimator mAnimator = null; 2718 2719 /** 2720 * Flag indicating that a drag can cross window boundaries. When 2721 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 2722 * with this flag set, all visible applications will be able to participate 2723 * in the drag operation and receive the dragged content. 2724 * 2725 * @hide 2726 */ 2727 public static final int DRAG_FLAG_GLOBAL = 1; 2728 2729 /** 2730 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 2731 */ 2732 private float mVerticalScrollFactor; 2733 2734 /** 2735 * Position of the vertical scroll bar. 2736 */ 2737 private int mVerticalScrollbarPosition; 2738 2739 /** 2740 * Position the scroll bar at the default position as determined by the system. 2741 */ 2742 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 2743 2744 /** 2745 * Position the scroll bar along the left edge. 2746 */ 2747 public static final int SCROLLBAR_POSITION_LEFT = 1; 2748 2749 /** 2750 * Position the scroll bar along the right edge. 2751 */ 2752 public static final int SCROLLBAR_POSITION_RIGHT = 2; 2753 2754 /** 2755 * Indicates that the view does not have a layer. 2756 * 2757 * @see #getLayerType() 2758 * @see #setLayerType(int, android.graphics.Paint) 2759 * @see #LAYER_TYPE_SOFTWARE 2760 * @see #LAYER_TYPE_HARDWARE 2761 */ 2762 public static final int LAYER_TYPE_NONE = 0; 2763 2764 /** 2765 * <p>Indicates that the view has a software layer. A software layer is backed 2766 * by a bitmap and causes the view to be rendered using Android's software 2767 * rendering pipeline, even if hardware acceleration is enabled.</p> 2768 * 2769 * <p>Software layers have various usages:</p> 2770 * <p>When the application is not using hardware acceleration, a software layer 2771 * is useful to apply a specific color filter and/or blending mode and/or 2772 * translucency to a view and all its children.</p> 2773 * <p>When the application is using hardware acceleration, a software layer 2774 * is useful to render drawing primitives not supported by the hardware 2775 * accelerated pipeline. It can also be used to cache a complex view tree 2776 * into a texture and reduce the complexity of drawing operations. For instance, 2777 * when animating a complex view tree with a translation, a software layer can 2778 * be used to render the view tree only once.</p> 2779 * <p>Software layers should be avoided when the affected view tree updates 2780 * often. Every update will require to re-render the software layer, which can 2781 * potentially be slow (particularly when hardware acceleration is turned on 2782 * since the layer will have to be uploaded into a hardware texture after every 2783 * update.)</p> 2784 * 2785 * @see #getLayerType() 2786 * @see #setLayerType(int, android.graphics.Paint) 2787 * @see #LAYER_TYPE_NONE 2788 * @see #LAYER_TYPE_HARDWARE 2789 */ 2790 public static final int LAYER_TYPE_SOFTWARE = 1; 2791 2792 /** 2793 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 2794 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 2795 * OpenGL hardware) and causes the view to be rendered using Android's hardware 2796 * rendering pipeline, but only if hardware acceleration is turned on for the 2797 * view hierarchy. When hardware acceleration is turned off, hardware layers 2798 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 2799 * 2800 * <p>A hardware layer is useful to apply a specific color filter and/or 2801 * blending mode and/or translucency to a view and all its children.</p> 2802 * <p>A hardware layer can be used to cache a complex view tree into a 2803 * texture and reduce the complexity of drawing operations. For instance, 2804 * when animating a complex view tree with a translation, a hardware layer can 2805 * be used to render the view tree only once.</p> 2806 * <p>A hardware layer can also be used to increase the rendering quality when 2807 * rotation transformations are applied on a view. It can also be used to 2808 * prevent potential clipping issues when applying 3D transforms on a view.</p> 2809 * 2810 * @see #getLayerType() 2811 * @see #setLayerType(int, android.graphics.Paint) 2812 * @see #LAYER_TYPE_NONE 2813 * @see #LAYER_TYPE_SOFTWARE 2814 */ 2815 public static final int LAYER_TYPE_HARDWARE = 2; 2816 2817 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 2818 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 2819 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 2820 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 2821 }) 2822 int mLayerType = LAYER_TYPE_NONE; 2823 Paint mLayerPaint; 2824 Rect mLocalDirtyRect; 2825 2826 /** 2827 * Set to true when the view is sending hover accessibility events because it 2828 * is the innermost hovered view. 2829 */ 2830 private boolean mSendingHoverAccessibilityEvents; 2831 2832 /** 2833 * Simple constructor to use when creating a view from code. 2834 * 2835 * @param context The Context the view is running in, through which it can 2836 * access the current theme, resources, etc. 2837 */ 2838 public View(Context context) { 2839 mContext = context; 2840 mResources = context != null ? context.getResources() : null; 2841 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 2842 // Set layout and text direction defaults 2843 mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) | 2844 (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT); 2845 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 2846 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 2847 mUserPaddingStart = -1; 2848 mUserPaddingEnd = -1; 2849 mUserPaddingRelative = false; 2850 } 2851 2852 /** 2853 * Delegate for injecting accessiblity functionality. 2854 */ 2855 AccessibilityDelegate mAccessibilityDelegate; 2856 2857 /** 2858 * Consistency verifier for debugging purposes. 2859 * @hide 2860 */ 2861 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 2862 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 2863 new InputEventConsistencyVerifier(this, 0) : null; 2864 2865 /** 2866 * Constructor that is called when inflating a view from XML. This is called 2867 * when a view is being constructed from an XML file, supplying attributes 2868 * that were specified in the XML file. This version uses a default style of 2869 * 0, so the only attribute values applied are those in the Context's Theme 2870 * and the given AttributeSet. 2871 * 2872 * <p> 2873 * The method onFinishInflate() will be called after all children have been 2874 * added. 2875 * 2876 * @param context The Context the view is running in, through which it can 2877 * access the current theme, resources, etc. 2878 * @param attrs The attributes of the XML tag that is inflating the view. 2879 * @see #View(Context, AttributeSet, int) 2880 */ 2881 public View(Context context, AttributeSet attrs) { 2882 this(context, attrs, 0); 2883 } 2884 2885 /** 2886 * Perform inflation from XML and apply a class-specific base style. This 2887 * constructor of View allows subclasses to use their own base style when 2888 * they are inflating. For example, a Button class's constructor would call 2889 * this version of the super class constructor and supply 2890 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 2891 * the theme's button style to modify all of the base view attributes (in 2892 * particular its background) as well as the Button class's attributes. 2893 * 2894 * @param context The Context the view is running in, through which it can 2895 * access the current theme, resources, etc. 2896 * @param attrs The attributes of the XML tag that is inflating the view. 2897 * @param defStyle The default style to apply to this view. If 0, no style 2898 * will be applied (beyond what is included in the theme). This may 2899 * either be an attribute resource, whose value will be retrieved 2900 * from the current theme, or an explicit style resource. 2901 * @see #View(Context, AttributeSet) 2902 */ 2903 public View(Context context, AttributeSet attrs, int defStyle) { 2904 this(context); 2905 2906 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 2907 defStyle, 0); 2908 2909 Drawable background = null; 2910 2911 int leftPadding = -1; 2912 int topPadding = -1; 2913 int rightPadding = -1; 2914 int bottomPadding = -1; 2915 int startPadding = -1; 2916 int endPadding = -1; 2917 2918 int padding = -1; 2919 2920 int viewFlagValues = 0; 2921 int viewFlagMasks = 0; 2922 2923 boolean setScrollContainer = false; 2924 2925 int x = 0; 2926 int y = 0; 2927 2928 float tx = 0; 2929 float ty = 0; 2930 float rotation = 0; 2931 float rotationX = 0; 2932 float rotationY = 0; 2933 float sx = 1f; 2934 float sy = 1f; 2935 boolean transformSet = false; 2936 2937 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 2938 2939 int overScrollMode = mOverScrollMode; 2940 final int N = a.getIndexCount(); 2941 for (int i = 0; i < N; i++) { 2942 int attr = a.getIndex(i); 2943 switch (attr) { 2944 case com.android.internal.R.styleable.View_background: 2945 background = a.getDrawable(attr); 2946 break; 2947 case com.android.internal.R.styleable.View_padding: 2948 padding = a.getDimensionPixelSize(attr, -1); 2949 break; 2950 case com.android.internal.R.styleable.View_paddingLeft: 2951 leftPadding = a.getDimensionPixelSize(attr, -1); 2952 break; 2953 case com.android.internal.R.styleable.View_paddingTop: 2954 topPadding = a.getDimensionPixelSize(attr, -1); 2955 break; 2956 case com.android.internal.R.styleable.View_paddingRight: 2957 rightPadding = a.getDimensionPixelSize(attr, -1); 2958 break; 2959 case com.android.internal.R.styleable.View_paddingBottom: 2960 bottomPadding = a.getDimensionPixelSize(attr, -1); 2961 break; 2962 case com.android.internal.R.styleable.View_paddingStart: 2963 startPadding = a.getDimensionPixelSize(attr, -1); 2964 break; 2965 case com.android.internal.R.styleable.View_paddingEnd: 2966 endPadding = a.getDimensionPixelSize(attr, -1); 2967 break; 2968 case com.android.internal.R.styleable.View_scrollX: 2969 x = a.getDimensionPixelOffset(attr, 0); 2970 break; 2971 case com.android.internal.R.styleable.View_scrollY: 2972 y = a.getDimensionPixelOffset(attr, 0); 2973 break; 2974 case com.android.internal.R.styleable.View_alpha: 2975 setAlpha(a.getFloat(attr, 1f)); 2976 break; 2977 case com.android.internal.R.styleable.View_transformPivotX: 2978 setPivotX(a.getDimensionPixelOffset(attr, 0)); 2979 break; 2980 case com.android.internal.R.styleable.View_transformPivotY: 2981 setPivotY(a.getDimensionPixelOffset(attr, 0)); 2982 break; 2983 case com.android.internal.R.styleable.View_translationX: 2984 tx = a.getDimensionPixelOffset(attr, 0); 2985 transformSet = true; 2986 break; 2987 case com.android.internal.R.styleable.View_translationY: 2988 ty = a.getDimensionPixelOffset(attr, 0); 2989 transformSet = true; 2990 break; 2991 case com.android.internal.R.styleable.View_rotation: 2992 rotation = a.getFloat(attr, 0); 2993 transformSet = true; 2994 break; 2995 case com.android.internal.R.styleable.View_rotationX: 2996 rotationX = a.getFloat(attr, 0); 2997 transformSet = true; 2998 break; 2999 case com.android.internal.R.styleable.View_rotationY: 3000 rotationY = a.getFloat(attr, 0); 3001 transformSet = true; 3002 break; 3003 case com.android.internal.R.styleable.View_scaleX: 3004 sx = a.getFloat(attr, 1f); 3005 transformSet = true; 3006 break; 3007 case com.android.internal.R.styleable.View_scaleY: 3008 sy = a.getFloat(attr, 1f); 3009 transformSet = true; 3010 break; 3011 case com.android.internal.R.styleable.View_id: 3012 mID = a.getResourceId(attr, NO_ID); 3013 break; 3014 case com.android.internal.R.styleable.View_tag: 3015 mTag = a.getText(attr); 3016 break; 3017 case com.android.internal.R.styleable.View_fitsSystemWindows: 3018 if (a.getBoolean(attr, false)) { 3019 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3020 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3021 } 3022 break; 3023 case com.android.internal.R.styleable.View_focusable: 3024 if (a.getBoolean(attr, false)) { 3025 viewFlagValues |= FOCUSABLE; 3026 viewFlagMasks |= FOCUSABLE_MASK; 3027 } 3028 break; 3029 case com.android.internal.R.styleable.View_focusableInTouchMode: 3030 if (a.getBoolean(attr, false)) { 3031 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3032 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3033 } 3034 break; 3035 case com.android.internal.R.styleable.View_clickable: 3036 if (a.getBoolean(attr, false)) { 3037 viewFlagValues |= CLICKABLE; 3038 viewFlagMasks |= CLICKABLE; 3039 } 3040 break; 3041 case com.android.internal.R.styleable.View_longClickable: 3042 if (a.getBoolean(attr, false)) { 3043 viewFlagValues |= LONG_CLICKABLE; 3044 viewFlagMasks |= LONG_CLICKABLE; 3045 } 3046 break; 3047 case com.android.internal.R.styleable.View_saveEnabled: 3048 if (!a.getBoolean(attr, true)) { 3049 viewFlagValues |= SAVE_DISABLED; 3050 viewFlagMasks |= SAVE_DISABLED_MASK; 3051 } 3052 break; 3053 case com.android.internal.R.styleable.View_duplicateParentState: 3054 if (a.getBoolean(attr, false)) { 3055 viewFlagValues |= DUPLICATE_PARENT_STATE; 3056 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3057 } 3058 break; 3059 case com.android.internal.R.styleable.View_visibility: 3060 final int visibility = a.getInt(attr, 0); 3061 if (visibility != 0) { 3062 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3063 viewFlagMasks |= VISIBILITY_MASK; 3064 } 3065 break; 3066 case com.android.internal.R.styleable.View_layoutDirection: 3067 // Clear any layout direction flags (included resolved bits) already set 3068 mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK); 3069 // Set the layout direction flags depending on the value of the attribute 3070 final int layoutDirection = a.getInt(attr, -1); 3071 final int value = (layoutDirection != -1) ? 3072 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3073 mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT); 3074 break; 3075 case com.android.internal.R.styleable.View_drawingCacheQuality: 3076 final int cacheQuality = a.getInt(attr, 0); 3077 if (cacheQuality != 0) { 3078 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3079 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3080 } 3081 break; 3082 case com.android.internal.R.styleable.View_contentDescription: 3083 mContentDescription = a.getString(attr); 3084 break; 3085 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3086 if (!a.getBoolean(attr, true)) { 3087 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3088 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3089 } 3090 break; 3091 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3092 if (!a.getBoolean(attr, true)) { 3093 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3094 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3095 } 3096 break; 3097 case R.styleable.View_scrollbars: 3098 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3099 if (scrollbars != SCROLLBARS_NONE) { 3100 viewFlagValues |= scrollbars; 3101 viewFlagMasks |= SCROLLBARS_MASK; 3102 initializeScrollbars(a); 3103 } 3104 break; 3105 //noinspection deprecation 3106 case R.styleable.View_fadingEdge: 3107 if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) { 3108 // Ignore the attribute starting with ICS 3109 break; 3110 } 3111 // With builds < ICS, fall through and apply fading edges 3112 case R.styleable.View_requiresFadingEdge: 3113 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3114 if (fadingEdge != FADING_EDGE_NONE) { 3115 viewFlagValues |= fadingEdge; 3116 viewFlagMasks |= FADING_EDGE_MASK; 3117 initializeFadingEdge(a); 3118 } 3119 break; 3120 case R.styleable.View_scrollbarStyle: 3121 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3122 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3123 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3124 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3125 } 3126 break; 3127 case R.styleable.View_isScrollContainer: 3128 setScrollContainer = true; 3129 if (a.getBoolean(attr, false)) { 3130 setScrollContainer(true); 3131 } 3132 break; 3133 case com.android.internal.R.styleable.View_keepScreenOn: 3134 if (a.getBoolean(attr, false)) { 3135 viewFlagValues |= KEEP_SCREEN_ON; 3136 viewFlagMasks |= KEEP_SCREEN_ON; 3137 } 3138 break; 3139 case R.styleable.View_filterTouchesWhenObscured: 3140 if (a.getBoolean(attr, false)) { 3141 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3142 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3143 } 3144 break; 3145 case R.styleable.View_nextFocusLeft: 3146 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3147 break; 3148 case R.styleable.View_nextFocusRight: 3149 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3150 break; 3151 case R.styleable.View_nextFocusUp: 3152 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3153 break; 3154 case R.styleable.View_nextFocusDown: 3155 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3156 break; 3157 case R.styleable.View_nextFocusForward: 3158 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3159 break; 3160 case R.styleable.View_minWidth: 3161 mMinWidth = a.getDimensionPixelSize(attr, 0); 3162 break; 3163 case R.styleable.View_minHeight: 3164 mMinHeight = a.getDimensionPixelSize(attr, 0); 3165 break; 3166 case R.styleable.View_onClick: 3167 if (context.isRestricted()) { 3168 throw new IllegalStateException("The android:onClick attribute cannot " 3169 + "be used within a restricted context"); 3170 } 3171 3172 final String handlerName = a.getString(attr); 3173 if (handlerName != null) { 3174 setOnClickListener(new OnClickListener() { 3175 private Method mHandler; 3176 3177 public void onClick(View v) { 3178 if (mHandler == null) { 3179 try { 3180 mHandler = getContext().getClass().getMethod(handlerName, 3181 View.class); 3182 } catch (NoSuchMethodException e) { 3183 int id = getId(); 3184 String idText = id == NO_ID ? "" : " with id '" 3185 + getContext().getResources().getResourceEntryName( 3186 id) + "'"; 3187 throw new IllegalStateException("Could not find a method " + 3188 handlerName + "(View) in the activity " 3189 + getContext().getClass() + " for onClick handler" 3190 + " on view " + View.this.getClass() + idText, e); 3191 } 3192 } 3193 3194 try { 3195 mHandler.invoke(getContext(), View.this); 3196 } catch (IllegalAccessException e) { 3197 throw new IllegalStateException("Could not execute non " 3198 + "public method of the activity", e); 3199 } catch (InvocationTargetException e) { 3200 throw new IllegalStateException("Could not execute " 3201 + "method of the activity", e); 3202 } 3203 } 3204 }); 3205 } 3206 break; 3207 case R.styleable.View_overScrollMode: 3208 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3209 break; 3210 case R.styleable.View_verticalScrollbarPosition: 3211 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3212 break; 3213 case R.styleable.View_layerType: 3214 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3215 break; 3216 case R.styleable.View_textDirection: 3217 // Clear any text direction flag already set 3218 mPrivateFlags2 &= ~TEXT_DIRECTION_MASK; 3219 // Set the text direction flags depending on the value of the attribute 3220 final int textDirection = a.getInt(attr, -1); 3221 if (textDirection != -1) { 3222 mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection]; 3223 } 3224 break; 3225 } 3226 } 3227 3228 a.recycle(); 3229 3230 setOverScrollMode(overScrollMode); 3231 3232 if (background != null) { 3233 setBackgroundDrawable(background); 3234 } 3235 3236 // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved 3237 // layout direction). Those cached values will be used later during padding resolution. 3238 mUserPaddingStart = startPadding; 3239 mUserPaddingEnd = endPadding; 3240 3241 updateUserPaddingRelative(); 3242 3243 if (padding >= 0) { 3244 leftPadding = padding; 3245 topPadding = padding; 3246 rightPadding = padding; 3247 bottomPadding = padding; 3248 } 3249 3250 // If the user specified the padding (either with android:padding or 3251 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 3252 // use the default padding or the padding from the background drawable 3253 // (stored at this point in mPadding*) 3254 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft, 3255 topPadding >= 0 ? topPadding : mPaddingTop, 3256 rightPadding >= 0 ? rightPadding : mPaddingRight, 3257 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3258 3259 if (viewFlagMasks != 0) { 3260 setFlags(viewFlagValues, viewFlagMasks); 3261 } 3262 3263 // Needs to be called after mViewFlags is set 3264 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3265 recomputePadding(); 3266 } 3267 3268 if (x != 0 || y != 0) { 3269 scrollTo(x, y); 3270 } 3271 3272 if (transformSet) { 3273 setTranslationX(tx); 3274 setTranslationY(ty); 3275 setRotation(rotation); 3276 setRotationX(rotationX); 3277 setRotationY(rotationY); 3278 setScaleX(sx); 3279 setScaleY(sy); 3280 } 3281 3282 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3283 setScrollContainer(true); 3284 } 3285 3286 computeOpaqueFlags(); 3287 } 3288 3289 private void updateUserPaddingRelative() { 3290 mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0); 3291 } 3292 3293 /** 3294 * Non-public constructor for use in testing 3295 */ 3296 View() { 3297 mResources = null; 3298 } 3299 3300 /** 3301 * <p> 3302 * Initializes the fading edges from a given set of styled attributes. This 3303 * method should be called by subclasses that need fading edges and when an 3304 * instance of these subclasses is created programmatically rather than 3305 * being inflated from XML. This method is automatically called when the XML 3306 * is inflated. 3307 * </p> 3308 * 3309 * @param a the styled attributes set to initialize the fading edges from 3310 */ 3311 protected void initializeFadingEdge(TypedArray a) { 3312 initScrollCache(); 3313 3314 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3315 R.styleable.View_fadingEdgeLength, 3316 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3317 } 3318 3319 /** 3320 * Returns the size of the vertical faded edges used to indicate that more 3321 * content in this view is visible. 3322 * 3323 * @return The size in pixels of the vertical faded edge or 0 if vertical 3324 * faded edges are not enabled for this view. 3325 * @attr ref android.R.styleable#View_fadingEdgeLength 3326 */ 3327 public int getVerticalFadingEdgeLength() { 3328 if (isVerticalFadingEdgeEnabled()) { 3329 ScrollabilityCache cache = mScrollCache; 3330 if (cache != null) { 3331 return cache.fadingEdgeLength; 3332 } 3333 } 3334 return 0; 3335 } 3336 3337 /** 3338 * Set the size of the faded edge used to indicate that more content in this 3339 * view is available. Will not change whether the fading edge is enabled; use 3340 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3341 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3342 * for the vertical or horizontal fading edges. 3343 * 3344 * @param length The size in pixels of the faded edge used to indicate that more 3345 * content in this view is visible. 3346 */ 3347 public void setFadingEdgeLength(int length) { 3348 initScrollCache(); 3349 mScrollCache.fadingEdgeLength = length; 3350 } 3351 3352 /** 3353 * Returns the size of the horizontal faded edges used to indicate that more 3354 * content in this view is visible. 3355 * 3356 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3357 * faded edges are not enabled for this view. 3358 * @attr ref android.R.styleable#View_fadingEdgeLength 3359 */ 3360 public int getHorizontalFadingEdgeLength() { 3361 if (isHorizontalFadingEdgeEnabled()) { 3362 ScrollabilityCache cache = mScrollCache; 3363 if (cache != null) { 3364 return cache.fadingEdgeLength; 3365 } 3366 } 3367 return 0; 3368 } 3369 3370 /** 3371 * Returns the width of the vertical scrollbar. 3372 * 3373 * @return The width in pixels of the vertical scrollbar or 0 if there 3374 * is no vertical scrollbar. 3375 */ 3376 public int getVerticalScrollbarWidth() { 3377 ScrollabilityCache cache = mScrollCache; 3378 if (cache != null) { 3379 ScrollBarDrawable scrollBar = cache.scrollBar; 3380 if (scrollBar != null) { 3381 int size = scrollBar.getSize(true); 3382 if (size <= 0) { 3383 size = cache.scrollBarSize; 3384 } 3385 return size; 3386 } 3387 return 0; 3388 } 3389 return 0; 3390 } 3391 3392 /** 3393 * Returns the height of the horizontal scrollbar. 3394 * 3395 * @return The height in pixels of the horizontal scrollbar or 0 if 3396 * there is no horizontal scrollbar. 3397 */ 3398 protected int getHorizontalScrollbarHeight() { 3399 ScrollabilityCache cache = mScrollCache; 3400 if (cache != null) { 3401 ScrollBarDrawable scrollBar = cache.scrollBar; 3402 if (scrollBar != null) { 3403 int size = scrollBar.getSize(false); 3404 if (size <= 0) { 3405 size = cache.scrollBarSize; 3406 } 3407 return size; 3408 } 3409 return 0; 3410 } 3411 return 0; 3412 } 3413 3414 /** 3415 * <p> 3416 * Initializes the scrollbars from a given set of styled attributes. This 3417 * method should be called by subclasses that need scrollbars and when an 3418 * instance of these subclasses is created programmatically rather than 3419 * being inflated from XML. This method is automatically called when the XML 3420 * is inflated. 3421 * </p> 3422 * 3423 * @param a the styled attributes set to initialize the scrollbars from 3424 */ 3425 protected void initializeScrollbars(TypedArray a) { 3426 initScrollCache(); 3427 3428 final ScrollabilityCache scrollabilityCache = mScrollCache; 3429 3430 if (scrollabilityCache.scrollBar == null) { 3431 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 3432 } 3433 3434 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 3435 3436 if (!fadeScrollbars) { 3437 scrollabilityCache.state = ScrollabilityCache.ON; 3438 } 3439 scrollabilityCache.fadeScrollBars = fadeScrollbars; 3440 3441 3442 scrollabilityCache.scrollBarFadeDuration = a.getInt( 3443 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 3444 .getScrollBarFadeDuration()); 3445 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 3446 R.styleable.View_scrollbarDefaultDelayBeforeFade, 3447 ViewConfiguration.getScrollDefaultDelay()); 3448 3449 3450 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 3451 com.android.internal.R.styleable.View_scrollbarSize, 3452 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3453 3454 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3455 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3456 3457 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3458 if (thumb != null) { 3459 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3460 } 3461 3462 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3463 false); 3464 if (alwaysDraw) { 3465 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3466 } 3467 3468 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3469 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3470 3471 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3472 if (thumb != null) { 3473 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3474 } 3475 3476 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3477 false); 3478 if (alwaysDraw) { 3479 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3480 } 3481 3482 // Re-apply user/background padding so that scrollbar(s) get added 3483 resolvePadding(); 3484 } 3485 3486 /** 3487 * <p> 3488 * Initalizes the scrollability cache if necessary. 3489 * </p> 3490 */ 3491 private void initScrollCache() { 3492 if (mScrollCache == null) { 3493 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 3494 } 3495 } 3496 3497 /** 3498 * Set the position of the vertical scroll bar. Should be one of 3499 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 3500 * {@link #SCROLLBAR_POSITION_RIGHT}. 3501 * 3502 * @param position Where the vertical scroll bar should be positioned. 3503 */ 3504 public void setVerticalScrollbarPosition(int position) { 3505 if (mVerticalScrollbarPosition != position) { 3506 mVerticalScrollbarPosition = position; 3507 computeOpaqueFlags(); 3508 resolvePadding(); 3509 } 3510 } 3511 3512 /** 3513 * @return The position where the vertical scroll bar will show, if applicable. 3514 * @see #setVerticalScrollbarPosition(int) 3515 */ 3516 public int getVerticalScrollbarPosition() { 3517 return mVerticalScrollbarPosition; 3518 } 3519 3520 ListenerInfo getListenerInfo() { 3521 if (mListenerInfo != null) { 3522 return mListenerInfo; 3523 } 3524 mListenerInfo = new ListenerInfo(); 3525 return mListenerInfo; 3526 } 3527 3528 /** 3529 * Register a callback to be invoked when focus of this view changed. 3530 * 3531 * @param l The callback that will run. 3532 */ 3533 public void setOnFocusChangeListener(OnFocusChangeListener l) { 3534 getListenerInfo().mOnFocusChangeListener = l; 3535 } 3536 3537 /** 3538 * Add a listener that will be called when the bounds of the view change due to 3539 * layout processing. 3540 * 3541 * @param listener The listener that will be called when layout bounds change. 3542 */ 3543 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 3544 ListenerInfo li = getListenerInfo(); 3545 if (li.mOnLayoutChangeListeners == null) { 3546 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 3547 } 3548 if (!li.mOnLayoutChangeListeners.contains(listener)) { 3549 li.mOnLayoutChangeListeners.add(listener); 3550 } 3551 } 3552 3553 /** 3554 * Remove a listener for layout changes. 3555 * 3556 * @param listener The listener for layout bounds change. 3557 */ 3558 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 3559 ListenerInfo li = mListenerInfo; 3560 if (li == null || li.mOnLayoutChangeListeners == null) { 3561 return; 3562 } 3563 li.mOnLayoutChangeListeners.remove(listener); 3564 } 3565 3566 /** 3567 * Add a listener for attach state changes. 3568 * 3569 * This listener will be called whenever this view is attached or detached 3570 * from a window. Remove the listener using 3571 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 3572 * 3573 * @param listener Listener to attach 3574 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 3575 */ 3576 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3577 ListenerInfo li = getListenerInfo(); 3578 if (li.mOnAttachStateChangeListeners == null) { 3579 li.mOnAttachStateChangeListeners 3580 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 3581 } 3582 li.mOnAttachStateChangeListeners.add(listener); 3583 } 3584 3585 /** 3586 * Remove a listener for attach state changes. The listener will receive no further 3587 * notification of window attach/detach events. 3588 * 3589 * @param listener Listener to remove 3590 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 3591 */ 3592 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3593 ListenerInfo li = mListenerInfo; 3594 if (li == null || li.mOnAttachStateChangeListeners == null) { 3595 return; 3596 } 3597 li.mOnAttachStateChangeListeners.remove(listener); 3598 } 3599 3600 /** 3601 * Returns the focus-change callback registered for this view. 3602 * 3603 * @return The callback, or null if one is not registered. 3604 */ 3605 public OnFocusChangeListener getOnFocusChangeListener() { 3606 ListenerInfo li = mListenerInfo; 3607 return li != null ? li.mOnFocusChangeListener : null; 3608 } 3609 3610 /** 3611 * Register a callback to be invoked when this view is clicked. If this view is not 3612 * clickable, it becomes clickable. 3613 * 3614 * @param l The callback that will run 3615 * 3616 * @see #setClickable(boolean) 3617 */ 3618 public void setOnClickListener(OnClickListener l) { 3619 if (!isClickable()) { 3620 setClickable(true); 3621 } 3622 getListenerInfo().mOnClickListener = l; 3623 } 3624 3625 /** 3626 * Return whether this view has an attached OnClickListener. Returns 3627 * true if there is a listener, false if there is none. 3628 */ 3629 public boolean hasOnClickListeners() { 3630 ListenerInfo li = mListenerInfo; 3631 return (li != null && li.mOnClickListener != null); 3632 } 3633 3634 /** 3635 * Register a callback to be invoked when this view is clicked and held. If this view is not 3636 * long clickable, it becomes long clickable. 3637 * 3638 * @param l The callback that will run 3639 * 3640 * @see #setLongClickable(boolean) 3641 */ 3642 public void setOnLongClickListener(OnLongClickListener l) { 3643 if (!isLongClickable()) { 3644 setLongClickable(true); 3645 } 3646 getListenerInfo().mOnLongClickListener = l; 3647 } 3648 3649 /** 3650 * Register a callback to be invoked when the context menu for this view is 3651 * being built. If this view is not long clickable, it becomes long clickable. 3652 * 3653 * @param l The callback that will run 3654 * 3655 */ 3656 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 3657 if (!isLongClickable()) { 3658 setLongClickable(true); 3659 } 3660 getListenerInfo().mOnCreateContextMenuListener = l; 3661 } 3662 3663 /** 3664 * Call this view's OnClickListener, if it is defined. Performs all normal 3665 * actions associated with clicking: reporting accessibility event, playing 3666 * a sound, etc. 3667 * 3668 * @return True there was an assigned OnClickListener that was called, false 3669 * otherwise is returned. 3670 */ 3671 public boolean performClick() { 3672 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 3673 3674 ListenerInfo li = mListenerInfo; 3675 if (li != null && li.mOnClickListener != null) { 3676 playSoundEffect(SoundEffectConstants.CLICK); 3677 li.mOnClickListener.onClick(this); 3678 return true; 3679 } 3680 3681 return false; 3682 } 3683 3684 /** 3685 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 3686 * this only calls the listener, and does not do any associated clicking 3687 * actions like reporting an accessibility event. 3688 * 3689 * @return True there was an assigned OnClickListener that was called, false 3690 * otherwise is returned. 3691 */ 3692 public boolean callOnClick() { 3693 ListenerInfo li = mListenerInfo; 3694 if (li != null && li.mOnClickListener != null) { 3695 li.mOnClickListener.onClick(this); 3696 return true; 3697 } 3698 return false; 3699 } 3700 3701 /** 3702 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 3703 * OnLongClickListener did not consume the event. 3704 * 3705 * @return True if one of the above receivers consumed the event, false otherwise. 3706 */ 3707 public boolean performLongClick() { 3708 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 3709 3710 boolean handled = false; 3711 ListenerInfo li = mListenerInfo; 3712 if (li != null && li.mOnLongClickListener != null) { 3713 handled = li.mOnLongClickListener.onLongClick(View.this); 3714 } 3715 if (!handled) { 3716 handled = showContextMenu(); 3717 } 3718 if (handled) { 3719 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 3720 } 3721 return handled; 3722 } 3723 3724 /** 3725 * Performs button-related actions during a touch down event. 3726 * 3727 * @param event The event. 3728 * @return True if the down was consumed. 3729 * 3730 * @hide 3731 */ 3732 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 3733 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 3734 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 3735 return true; 3736 } 3737 } 3738 return false; 3739 } 3740 3741 /** 3742 * Bring up the context menu for this view. 3743 * 3744 * @return Whether a context menu was displayed. 3745 */ 3746 public boolean showContextMenu() { 3747 return getParent().showContextMenuForChild(this); 3748 } 3749 3750 /** 3751 * Bring up the context menu for this view, referring to the item under the specified point. 3752 * 3753 * @param x The referenced x coordinate. 3754 * @param y The referenced y coordinate. 3755 * @param metaState The keyboard modifiers that were pressed. 3756 * @return Whether a context menu was displayed. 3757 * 3758 * @hide 3759 */ 3760 public boolean showContextMenu(float x, float y, int metaState) { 3761 return showContextMenu(); 3762 } 3763 3764 /** 3765 * Start an action mode. 3766 * 3767 * @param callback Callback that will control the lifecycle of the action mode 3768 * @return The new action mode if it is started, null otherwise 3769 * 3770 * @see ActionMode 3771 */ 3772 public ActionMode startActionMode(ActionMode.Callback callback) { 3773 ViewParent parent = getParent(); 3774 if (parent == null) return null; 3775 return parent.startActionModeForChild(this, callback); 3776 } 3777 3778 /** 3779 * Register a callback to be invoked when a key is pressed in this view. 3780 * @param l the key listener to attach to this view 3781 */ 3782 public void setOnKeyListener(OnKeyListener l) { 3783 getListenerInfo().mOnKeyListener = l; 3784 } 3785 3786 /** 3787 * Register a callback to be invoked when a touch event is sent to this view. 3788 * @param l the touch listener to attach to this view 3789 */ 3790 public void setOnTouchListener(OnTouchListener l) { 3791 getListenerInfo().mOnTouchListener = l; 3792 } 3793 3794 /** 3795 * Register a callback to be invoked when a generic motion event is sent to this view. 3796 * @param l the generic motion listener to attach to this view 3797 */ 3798 public void setOnGenericMotionListener(OnGenericMotionListener l) { 3799 getListenerInfo().mOnGenericMotionListener = l; 3800 } 3801 3802 /** 3803 * Register a callback to be invoked when a hover event is sent to this view. 3804 * @param l the hover listener to attach to this view 3805 */ 3806 public void setOnHoverListener(OnHoverListener l) { 3807 getListenerInfo().mOnHoverListener = l; 3808 } 3809 3810 /** 3811 * Register a drag event listener callback object for this View. The parameter is 3812 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 3813 * View, the system calls the 3814 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 3815 * @param l An implementation of {@link android.view.View.OnDragListener}. 3816 */ 3817 public void setOnDragListener(OnDragListener l) { 3818 getListenerInfo().mOnDragListener = l; 3819 } 3820 3821 /** 3822 * Give this view focus. This will cause 3823 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3824 * 3825 * Note: this does not check whether this {@link View} should get focus, it just 3826 * gives it focus no matter what. It should only be called internally by framework 3827 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 3828 * 3829 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 3830 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 3831 * focus moved when requestFocus() is called. It may not always 3832 * apply, in which case use the default View.FOCUS_DOWN. 3833 * @param previouslyFocusedRect The rectangle of the view that had focus 3834 * prior in this View's coordinate system. 3835 */ 3836 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 3837 if (DBG) { 3838 System.out.println(this + " requestFocus()"); 3839 } 3840 3841 if ((mPrivateFlags & FOCUSED) == 0) { 3842 mPrivateFlags |= FOCUSED; 3843 3844 if (mParent != null) { 3845 mParent.requestChildFocus(this, this); 3846 } 3847 3848 onFocusChanged(true, direction, previouslyFocusedRect); 3849 refreshDrawableState(); 3850 } 3851 } 3852 3853 /** 3854 * Request that a rectangle of this view be visible on the screen, 3855 * scrolling if necessary just enough. 3856 * 3857 * <p>A View should call this if it maintains some notion of which part 3858 * of its content is interesting. For example, a text editing view 3859 * should call this when its cursor moves. 3860 * 3861 * @param rectangle The rectangle. 3862 * @return Whether any parent scrolled. 3863 */ 3864 public boolean requestRectangleOnScreen(Rect rectangle) { 3865 return requestRectangleOnScreen(rectangle, false); 3866 } 3867 3868 /** 3869 * Request that a rectangle of this view be visible on the screen, 3870 * scrolling if necessary just enough. 3871 * 3872 * <p>A View should call this if it maintains some notion of which part 3873 * of its content is interesting. For example, a text editing view 3874 * should call this when its cursor moves. 3875 * 3876 * <p>When <code>immediate</code> is set to true, scrolling will not be 3877 * animated. 3878 * 3879 * @param rectangle The rectangle. 3880 * @param immediate True to forbid animated scrolling, false otherwise 3881 * @return Whether any parent scrolled. 3882 */ 3883 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 3884 View child = this; 3885 ViewParent parent = mParent; 3886 boolean scrolled = false; 3887 while (parent != null) { 3888 scrolled |= parent.requestChildRectangleOnScreen(child, 3889 rectangle, immediate); 3890 3891 // offset rect so next call has the rectangle in the 3892 // coordinate system of its direct child. 3893 rectangle.offset(child.getLeft(), child.getTop()); 3894 rectangle.offset(-child.getScrollX(), -child.getScrollY()); 3895 3896 if (!(parent instanceof View)) { 3897 break; 3898 } 3899 3900 child = (View) parent; 3901 parent = child.getParent(); 3902 } 3903 return scrolled; 3904 } 3905 3906 /** 3907 * Called when this view wants to give up focus. If focus is cleared 3908 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 3909 * <p> 3910 * <strong>Note:</strong> When a View clears focus the framework is trying 3911 * to give focus to the first focusable View from the top. Hence, if this 3912 * View is the first from the top that can take focus, then its focus will 3913 * not be cleared nor will the focus change callback be invoked. 3914 * </p> 3915 */ 3916 public void clearFocus() { 3917 if (DBG) { 3918 System.out.println(this + " clearFocus()"); 3919 } 3920 3921 if ((mPrivateFlags & FOCUSED) != 0) { 3922 mPrivateFlags &= ~FOCUSED; 3923 3924 if (mParent != null) { 3925 mParent.clearChildFocus(this); 3926 } 3927 3928 onFocusChanged(false, 0, null); 3929 refreshDrawableState(); 3930 } 3931 } 3932 3933 /** 3934 * Called to clear the focus of a view that is about to be removed. 3935 * Doesn't call clearChildFocus, which prevents this view from taking 3936 * focus again before it has been removed from the parent 3937 */ 3938 void clearFocusForRemoval() { 3939 if ((mPrivateFlags & FOCUSED) != 0) { 3940 mPrivateFlags &= ~FOCUSED; 3941 3942 onFocusChanged(false, 0, null); 3943 refreshDrawableState(); 3944 3945 // The view cleared focus and invoked the callbacks, so now is the 3946 // time to give focus to the the first focusable from the top to 3947 // ensure that the gain focus is announced after clear focus. 3948 getRootView().requestFocus(FOCUS_FORWARD); 3949 } 3950 } 3951 3952 /** 3953 * Called internally by the view system when a new view is getting focus. 3954 * This is what clears the old focus. 3955 */ 3956 void unFocus() { 3957 if (DBG) { 3958 System.out.println(this + " unFocus()"); 3959 } 3960 3961 if ((mPrivateFlags & FOCUSED) != 0) { 3962 mPrivateFlags &= ~FOCUSED; 3963 3964 onFocusChanged(false, 0, null); 3965 refreshDrawableState(); 3966 } 3967 } 3968 3969 /** 3970 * Returns true if this view has focus iteself, or is the ancestor of the 3971 * view that has focus. 3972 * 3973 * @return True if this view has or contains focus, false otherwise. 3974 */ 3975 @ViewDebug.ExportedProperty(category = "focus") 3976 public boolean hasFocus() { 3977 return (mPrivateFlags & FOCUSED) != 0; 3978 } 3979 3980 /** 3981 * Returns true if this view is focusable or if it contains a reachable View 3982 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 3983 * is a View whose parents do not block descendants focus. 3984 * 3985 * Only {@link #VISIBLE} views are considered focusable. 3986 * 3987 * @return True if the view is focusable or if the view contains a focusable 3988 * View, false otherwise. 3989 * 3990 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 3991 */ 3992 public boolean hasFocusable() { 3993 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 3994 } 3995 3996 /** 3997 * Called by the view system when the focus state of this view changes. 3998 * When the focus change event is caused by directional navigation, direction 3999 * and previouslyFocusedRect provide insight into where the focus is coming from. 4000 * When overriding, be sure to call up through to the super class so that 4001 * the standard focus handling will occur. 4002 * 4003 * @param gainFocus True if the View has focus; false otherwise. 4004 * @param direction The direction focus has moved when requestFocus() 4005 * is called to give this view focus. Values are 4006 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4007 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4008 * It may not always apply, in which case use the default. 4009 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4010 * system, of the previously focused view. If applicable, this will be 4011 * passed in as finer grained information about where the focus is coming 4012 * from (in addition to direction). Will be <code>null</code> otherwise. 4013 */ 4014 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 4015 if (gainFocus) { 4016 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 4017 } 4018 4019 InputMethodManager imm = InputMethodManager.peekInstance(); 4020 if (!gainFocus) { 4021 if (isPressed()) { 4022 setPressed(false); 4023 } 4024 if (imm != null && mAttachInfo != null 4025 && mAttachInfo.mHasWindowFocus) { 4026 imm.focusOut(this); 4027 } 4028 onFocusLost(); 4029 } else if (imm != null && mAttachInfo != null 4030 && mAttachInfo.mHasWindowFocus) { 4031 imm.focusIn(this); 4032 } 4033 4034 invalidate(true); 4035 ListenerInfo li = mListenerInfo; 4036 if (li != null && li.mOnFocusChangeListener != null) { 4037 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 4038 } 4039 4040 if (mAttachInfo != null) { 4041 mAttachInfo.mKeyDispatchState.reset(this); 4042 } 4043 } 4044 4045 /** 4046 * Sends an accessibility event of the given type. If accessiiblity is 4047 * not enabled this method has no effect. The default implementation calls 4048 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 4049 * to populate information about the event source (this View), then calls 4050 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 4051 * populate the text content of the event source including its descendants, 4052 * and last calls 4053 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 4054 * on its parent to resuest sending of the event to interested parties. 4055 * <p> 4056 * If an {@link AccessibilityDelegate} has been specified via calling 4057 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4058 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 4059 * responsible for handling this call. 4060 * </p> 4061 * 4062 * @param eventType The type of the event to send, as defined by several types from 4063 * {@link android.view.accessibility.AccessibilityEvent}, such as 4064 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 4065 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 4066 * 4067 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4068 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4069 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 4070 * @see AccessibilityDelegate 4071 */ 4072 public void sendAccessibilityEvent(int eventType) { 4073 if (mAccessibilityDelegate != null) { 4074 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 4075 } else { 4076 sendAccessibilityEventInternal(eventType); 4077 } 4078 } 4079 4080 /** 4081 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 4082 * {@link AccessibilityEvent} to make an announcement which is related to some 4083 * sort of a context change for which none of the events representing UI transitions 4084 * is a good fit. For example, announcing a new page in a book. If accessibility 4085 * is not enabled this method does nothing. 4086 * 4087 * @param text The announcement text. 4088 */ 4089 public void announceForAccessibility(CharSequence text) { 4090 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4091 AccessibilityEvent event = AccessibilityEvent.obtain( 4092 AccessibilityEvent.TYPE_ANNOUNCEMENT); 4093 event.getText().add(text); 4094 sendAccessibilityEventUnchecked(event); 4095 } 4096 } 4097 4098 /** 4099 * @see #sendAccessibilityEvent(int) 4100 * 4101 * Note: Called from the default {@link AccessibilityDelegate}. 4102 */ 4103 void sendAccessibilityEventInternal(int eventType) { 4104 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4105 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 4106 } 4107 } 4108 4109 /** 4110 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 4111 * takes as an argument an empty {@link AccessibilityEvent} and does not 4112 * perform a check whether accessibility is enabled. 4113 * <p> 4114 * If an {@link AccessibilityDelegate} has been specified via calling 4115 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4116 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 4117 * is responsible for handling this call. 4118 * </p> 4119 * 4120 * @param event The event to send. 4121 * 4122 * @see #sendAccessibilityEvent(int) 4123 */ 4124 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 4125 if (mAccessibilityDelegate != null) { 4126 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 4127 } else { 4128 sendAccessibilityEventUncheckedInternal(event); 4129 } 4130 } 4131 4132 /** 4133 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 4134 * 4135 * Note: Called from the default {@link AccessibilityDelegate}. 4136 */ 4137 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 4138 if (!isShown()) { 4139 return; 4140 } 4141 onInitializeAccessibilityEvent(event); 4142 // Only a subset of accessibility events populates text content. 4143 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 4144 dispatchPopulateAccessibilityEvent(event); 4145 } 4146 // In the beginning we called #isShown(), so we know that getParent() is not null. 4147 getParent().requestSendAccessibilityEvent(this, event); 4148 } 4149 4150 /** 4151 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 4152 * to its children for adding their text content to the event. Note that the 4153 * event text is populated in a separate dispatch path since we add to the 4154 * event not only the text of the source but also the text of all its descendants. 4155 * A typical implementation will call 4156 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 4157 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4158 * on each child. Override this method if custom population of the event text 4159 * content is required. 4160 * <p> 4161 * If an {@link AccessibilityDelegate} has been specified via calling 4162 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4163 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 4164 * is responsible for handling this call. 4165 * </p> 4166 * <p> 4167 * <em>Note:</em> Accessibility events of certain types are not dispatched for 4168 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 4169 * </p> 4170 * 4171 * @param event The event. 4172 * 4173 * @return True if the event population was completed. 4174 */ 4175 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 4176 if (mAccessibilityDelegate != null) { 4177 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 4178 } else { 4179 return dispatchPopulateAccessibilityEventInternal(event); 4180 } 4181 } 4182 4183 /** 4184 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4185 * 4186 * Note: Called from the default {@link AccessibilityDelegate}. 4187 */ 4188 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4189 onPopulateAccessibilityEvent(event); 4190 return false; 4191 } 4192 4193 /** 4194 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4195 * giving a chance to this View to populate the accessibility event with its 4196 * text content. While this method is free to modify event 4197 * attributes other than text content, doing so should normally be performed in 4198 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 4199 * <p> 4200 * Example: Adding formatted date string to an accessibility event in addition 4201 * to the text added by the super implementation: 4202 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4203 * super.onPopulateAccessibilityEvent(event); 4204 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 4205 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 4206 * mCurrentDate.getTimeInMillis(), flags); 4207 * event.getText().add(selectedDateUtterance); 4208 * }</pre> 4209 * <p> 4210 * If an {@link AccessibilityDelegate} has been specified via calling 4211 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4212 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 4213 * is responsible for handling this call. 4214 * </p> 4215 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4216 * information to the event, in case the default implementation has basic information to add. 4217 * </p> 4218 * 4219 * @param event The accessibility event which to populate. 4220 * 4221 * @see #sendAccessibilityEvent(int) 4222 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4223 */ 4224 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4225 if (mAccessibilityDelegate != null) { 4226 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 4227 } else { 4228 onPopulateAccessibilityEventInternal(event); 4229 } 4230 } 4231 4232 /** 4233 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 4234 * 4235 * Note: Called from the default {@link AccessibilityDelegate}. 4236 */ 4237 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4238 4239 } 4240 4241 /** 4242 * Initializes an {@link AccessibilityEvent} with information about 4243 * this View which is the event source. In other words, the source of 4244 * an accessibility event is the view whose state change triggered firing 4245 * the event. 4246 * <p> 4247 * Example: Setting the password property of an event in addition 4248 * to properties set by the super implementation: 4249 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4250 * super.onInitializeAccessibilityEvent(event); 4251 * event.setPassword(true); 4252 * }</pre> 4253 * <p> 4254 * If an {@link AccessibilityDelegate} has been specified via calling 4255 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4256 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 4257 * is responsible for handling this call. 4258 * </p> 4259 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4260 * information to the event, in case the default implementation has basic information to add. 4261 * </p> 4262 * @param event The event to initialize. 4263 * 4264 * @see #sendAccessibilityEvent(int) 4265 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4266 */ 4267 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4268 if (mAccessibilityDelegate != null) { 4269 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 4270 } else { 4271 onInitializeAccessibilityEventInternal(event); 4272 } 4273 } 4274 4275 /** 4276 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4277 * 4278 * Note: Called from the default {@link AccessibilityDelegate}. 4279 */ 4280 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 4281 event.setSource(this); 4282 event.setClassName(View.class.getName()); 4283 event.setPackageName(getContext().getPackageName()); 4284 event.setEnabled(isEnabled()); 4285 event.setContentDescription(mContentDescription); 4286 4287 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) { 4288 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList; 4289 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, 4290 FOCUSABLES_ALL); 4291 event.setItemCount(focusablesTempList.size()); 4292 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 4293 focusablesTempList.clear(); 4294 } 4295 } 4296 4297 /** 4298 * Returns an {@link AccessibilityNodeInfo} representing this view from the 4299 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 4300 * This method is responsible for obtaining an accessibility node info from a 4301 * pool of reusable instances and calling 4302 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 4303 * initialize the former. 4304 * <p> 4305 * Note: The client is responsible for recycling the obtained instance by calling 4306 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 4307 * </p> 4308 * 4309 * @return A populated {@link AccessibilityNodeInfo}. 4310 * 4311 * @see AccessibilityNodeInfo 4312 */ 4313 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 4314 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 4315 if (provider != null) { 4316 return provider.createAccessibilityNodeInfo(View.NO_ID); 4317 } else { 4318 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 4319 onInitializeAccessibilityNodeInfo(info); 4320 return info; 4321 } 4322 } 4323 4324 /** 4325 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 4326 * The base implementation sets: 4327 * <ul> 4328 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 4329 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 4330 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 4331 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 4332 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 4333 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 4334 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 4335 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 4336 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 4337 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 4338 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 4339 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 4340 * </ul> 4341 * <p> 4342 * Subclasses should override this method, call the super implementation, 4343 * and set additional attributes. 4344 * </p> 4345 * <p> 4346 * If an {@link AccessibilityDelegate} has been specified via calling 4347 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4348 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 4349 * is responsible for handling this call. 4350 * </p> 4351 * 4352 * @param info The instance to initialize. 4353 */ 4354 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 4355 if (mAccessibilityDelegate != null) { 4356 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 4357 } else { 4358 onInitializeAccessibilityNodeInfoInternal(info); 4359 } 4360 } 4361 4362 /** 4363 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 4364 * 4365 * Note: Called from the default {@link AccessibilityDelegate}. 4366 */ 4367 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 4368 Rect bounds = mAttachInfo.mTmpInvalRect; 4369 getDrawingRect(bounds); 4370 info.setBoundsInParent(bounds); 4371 4372 int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation; 4373 getLocationOnScreen(locationOnScreen); 4374 bounds.offsetTo(0, 0); 4375 bounds.offset(locationOnScreen[0], locationOnScreen[1]); 4376 info.setBoundsInScreen(bounds); 4377 4378 if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { 4379 ViewParent parent = getParent(); 4380 if (parent instanceof View) { 4381 View parentView = (View) parent; 4382 info.setParent(parentView); 4383 } 4384 } 4385 4386 info.setPackageName(mContext.getPackageName()); 4387 info.setClassName(View.class.getName()); 4388 info.setContentDescription(getContentDescription()); 4389 4390 info.setEnabled(isEnabled()); 4391 info.setClickable(isClickable()); 4392 info.setFocusable(isFocusable()); 4393 info.setFocused(isFocused()); 4394 info.setSelected(isSelected()); 4395 info.setLongClickable(isLongClickable()); 4396 4397 // TODO: These make sense only if we are in an AdapterView but all 4398 // views can be selected. Maybe from accessiiblity perspective 4399 // we should report as selectable view in an AdapterView. 4400 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 4401 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 4402 4403 if (isFocusable()) { 4404 if (isFocused()) { 4405 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 4406 } else { 4407 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 4408 } 4409 } 4410 } 4411 4412 /** 4413 * Sets a delegate for implementing accessibility support via compositon as 4414 * opposed to inheritance. The delegate's primary use is for implementing 4415 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 4416 * 4417 * @param delegate The delegate instance. 4418 * 4419 * @see AccessibilityDelegate 4420 */ 4421 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 4422 mAccessibilityDelegate = delegate; 4423 } 4424 4425 /** 4426 * Gets the provider for managing a virtual view hierarchy rooted at this View 4427 * and reported to {@link android.accessibilityservice.AccessibilityService}s 4428 * that explore the window content. 4429 * <p> 4430 * If this method returns an instance, this instance is responsible for managing 4431 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 4432 * View including the one representing the View itself. Similarly the returned 4433 * instance is responsible for performing accessibility actions on any virtual 4434 * view or the root view itself. 4435 * </p> 4436 * <p> 4437 * If an {@link AccessibilityDelegate} has been specified via calling 4438 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4439 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 4440 * is responsible for handling this call. 4441 * </p> 4442 * 4443 * @return The provider. 4444 * 4445 * @see AccessibilityNodeProvider 4446 */ 4447 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 4448 if (mAccessibilityDelegate != null) { 4449 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 4450 } else { 4451 return null; 4452 } 4453 } 4454 4455 /** 4456 * Gets the unique identifier of this view on the screen for accessibility purposes. 4457 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 4458 * 4459 * @return The view accessibility id. 4460 * 4461 * @hide 4462 */ 4463 public int getAccessibilityViewId() { 4464 if (mAccessibilityViewId == NO_ID) { 4465 mAccessibilityViewId = sNextAccessibilityViewId++; 4466 } 4467 return mAccessibilityViewId; 4468 } 4469 4470 /** 4471 * Gets the unique identifier of the window in which this View reseides. 4472 * 4473 * @return The window accessibility id. 4474 * 4475 * @hide 4476 */ 4477 public int getAccessibilityWindowId() { 4478 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 4479 } 4480 4481 /** 4482 * Gets the {@link View} description. It briefly describes the view and is 4483 * primarily used for accessibility support. Set this property to enable 4484 * better accessibility support for your application. This is especially 4485 * true for views that do not have textual representation (For example, 4486 * ImageButton). 4487 * 4488 * @return The content descriptiopn. 4489 * 4490 * @attr ref android.R.styleable#View_contentDescription 4491 */ 4492 public CharSequence getContentDescription() { 4493 return mContentDescription; 4494 } 4495 4496 /** 4497 * Sets the {@link View} description. It briefly describes the view and is 4498 * primarily used for accessibility support. Set this property to enable 4499 * better accessibility support for your application. This is especially 4500 * true for views that do not have textual representation (For example, 4501 * ImageButton). 4502 * 4503 * @param contentDescription The content description. 4504 * 4505 * @attr ref android.R.styleable#View_contentDescription 4506 */ 4507 @RemotableViewMethod 4508 public void setContentDescription(CharSequence contentDescription) { 4509 mContentDescription = contentDescription; 4510 } 4511 4512 /** 4513 * Invoked whenever this view loses focus, either by losing window focus or by losing 4514 * focus within its window. This method can be used to clear any state tied to the 4515 * focus. For instance, if a button is held pressed with the trackball and the window 4516 * loses focus, this method can be used to cancel the press. 4517 * 4518 * Subclasses of View overriding this method should always call super.onFocusLost(). 4519 * 4520 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 4521 * @see #onWindowFocusChanged(boolean) 4522 * 4523 * @hide pending API council approval 4524 */ 4525 protected void onFocusLost() { 4526 resetPressedState(); 4527 } 4528 4529 private void resetPressedState() { 4530 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 4531 return; 4532 } 4533 4534 if (isPressed()) { 4535 setPressed(false); 4536 4537 if (!mHasPerformedLongPress) { 4538 removeLongPressCallback(); 4539 } 4540 } 4541 } 4542 4543 /** 4544 * Returns true if this view has focus 4545 * 4546 * @return True if this view has focus, false otherwise. 4547 */ 4548 @ViewDebug.ExportedProperty(category = "focus") 4549 public boolean isFocused() { 4550 return (mPrivateFlags & FOCUSED) != 0; 4551 } 4552 4553 /** 4554 * Find the view in the hierarchy rooted at this view that currently has 4555 * focus. 4556 * 4557 * @return The view that currently has focus, or null if no focused view can 4558 * be found. 4559 */ 4560 public View findFocus() { 4561 return (mPrivateFlags & FOCUSED) != 0 ? this : null; 4562 } 4563 4564 /** 4565 * Change whether this view is one of the set of scrollable containers in 4566 * its window. This will be used to determine whether the window can 4567 * resize or must pan when a soft input area is open -- scrollable 4568 * containers allow the window to use resize mode since the container 4569 * will appropriately shrink. 4570 */ 4571 public void setScrollContainer(boolean isScrollContainer) { 4572 if (isScrollContainer) { 4573 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) { 4574 mAttachInfo.mScrollContainers.add(this); 4575 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 4576 } 4577 mPrivateFlags |= SCROLL_CONTAINER; 4578 } else { 4579 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 4580 mAttachInfo.mScrollContainers.remove(this); 4581 } 4582 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED); 4583 } 4584 } 4585 4586 /** 4587 * Returns the quality of the drawing cache. 4588 * 4589 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4590 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4591 * 4592 * @see #setDrawingCacheQuality(int) 4593 * @see #setDrawingCacheEnabled(boolean) 4594 * @see #isDrawingCacheEnabled() 4595 * 4596 * @attr ref android.R.styleable#View_drawingCacheQuality 4597 */ 4598 public int getDrawingCacheQuality() { 4599 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 4600 } 4601 4602 /** 4603 * Set the drawing cache quality of this view. This value is used only when the 4604 * drawing cache is enabled 4605 * 4606 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4607 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4608 * 4609 * @see #getDrawingCacheQuality() 4610 * @see #setDrawingCacheEnabled(boolean) 4611 * @see #isDrawingCacheEnabled() 4612 * 4613 * @attr ref android.R.styleable#View_drawingCacheQuality 4614 */ 4615 public void setDrawingCacheQuality(int quality) { 4616 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 4617 } 4618 4619 /** 4620 * Returns whether the screen should remain on, corresponding to the current 4621 * value of {@link #KEEP_SCREEN_ON}. 4622 * 4623 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 4624 * 4625 * @see #setKeepScreenOn(boolean) 4626 * 4627 * @attr ref android.R.styleable#View_keepScreenOn 4628 */ 4629 public boolean getKeepScreenOn() { 4630 return (mViewFlags & KEEP_SCREEN_ON) != 0; 4631 } 4632 4633 /** 4634 * Controls whether the screen should remain on, modifying the 4635 * value of {@link #KEEP_SCREEN_ON}. 4636 * 4637 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 4638 * 4639 * @see #getKeepScreenOn() 4640 * 4641 * @attr ref android.R.styleable#View_keepScreenOn 4642 */ 4643 public void setKeepScreenOn(boolean keepScreenOn) { 4644 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 4645 } 4646 4647 /** 4648 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4649 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4650 * 4651 * @attr ref android.R.styleable#View_nextFocusLeft 4652 */ 4653 public int getNextFocusLeftId() { 4654 return mNextFocusLeftId; 4655 } 4656 4657 /** 4658 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4659 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 4660 * decide automatically. 4661 * 4662 * @attr ref android.R.styleable#View_nextFocusLeft 4663 */ 4664 public void setNextFocusLeftId(int nextFocusLeftId) { 4665 mNextFocusLeftId = nextFocusLeftId; 4666 } 4667 4668 /** 4669 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4670 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4671 * 4672 * @attr ref android.R.styleable#View_nextFocusRight 4673 */ 4674 public int getNextFocusRightId() { 4675 return mNextFocusRightId; 4676 } 4677 4678 /** 4679 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4680 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 4681 * decide automatically. 4682 * 4683 * @attr ref android.R.styleable#View_nextFocusRight 4684 */ 4685 public void setNextFocusRightId(int nextFocusRightId) { 4686 mNextFocusRightId = nextFocusRightId; 4687 } 4688 4689 /** 4690 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4691 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4692 * 4693 * @attr ref android.R.styleable#View_nextFocusUp 4694 */ 4695 public int getNextFocusUpId() { 4696 return mNextFocusUpId; 4697 } 4698 4699 /** 4700 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4701 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 4702 * decide automatically. 4703 * 4704 * @attr ref android.R.styleable#View_nextFocusUp 4705 */ 4706 public void setNextFocusUpId(int nextFocusUpId) { 4707 mNextFocusUpId = nextFocusUpId; 4708 } 4709 4710 /** 4711 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4712 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4713 * 4714 * @attr ref android.R.styleable#View_nextFocusDown 4715 */ 4716 public int getNextFocusDownId() { 4717 return mNextFocusDownId; 4718 } 4719 4720 /** 4721 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4722 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 4723 * decide automatically. 4724 * 4725 * @attr ref android.R.styleable#View_nextFocusDown 4726 */ 4727 public void setNextFocusDownId(int nextFocusDownId) { 4728 mNextFocusDownId = nextFocusDownId; 4729 } 4730 4731 /** 4732 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4733 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4734 * 4735 * @attr ref android.R.styleable#View_nextFocusForward 4736 */ 4737 public int getNextFocusForwardId() { 4738 return mNextFocusForwardId; 4739 } 4740 4741 /** 4742 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4743 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 4744 * decide automatically. 4745 * 4746 * @attr ref android.R.styleable#View_nextFocusForward 4747 */ 4748 public void setNextFocusForwardId(int nextFocusForwardId) { 4749 mNextFocusForwardId = nextFocusForwardId; 4750 } 4751 4752 /** 4753 * Returns the visibility of this view and all of its ancestors 4754 * 4755 * @return True if this view and all of its ancestors are {@link #VISIBLE} 4756 */ 4757 public boolean isShown() { 4758 View current = this; 4759 //noinspection ConstantConditions 4760 do { 4761 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 4762 return false; 4763 } 4764 ViewParent parent = current.mParent; 4765 if (parent == null) { 4766 return false; // We are not attached to the view root 4767 } 4768 if (!(parent instanceof View)) { 4769 return true; 4770 } 4771 current = (View) parent; 4772 } while (current != null); 4773 4774 return false; 4775 } 4776 4777 /** 4778 * Called by the view hierarchy when the content insets for a window have 4779 * changed, to allow it to adjust its content to fit within those windows. 4780 * The content insets tell you the space that the status bar, input method, 4781 * and other system windows infringe on the application's window. 4782 * 4783 * <p>You do not normally need to deal with this function, since the default 4784 * window decoration given to applications takes care of applying it to the 4785 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 4786 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 4787 * and your content can be placed under those system elements. You can then 4788 * use this method within your view hierarchy if you have parts of your UI 4789 * which you would like to ensure are not being covered. 4790 * 4791 * <p>The default implementation of this method simply applies the content 4792 * inset's to the view's padding. This can be enabled through 4793 * {@link #setFitsSystemWindows(boolean)}. Alternatively, you can override 4794 * the method and handle the insets however you would like. Note that the 4795 * insets provided by the framework are always relative to the far edges 4796 * of the window, not accounting for the location of the called view within 4797 * that window. (In fact when this method is called you do not yet know 4798 * where the layout will place the view, as it is done before layout happens.) 4799 * 4800 * <p>Note: unlike many View methods, there is no dispatch phase to this 4801 * call. If you are overriding it in a ViewGroup and want to allow the 4802 * call to continue to your children, you must be sure to call the super 4803 * implementation. 4804 * 4805 * @param insets Current content insets of the window. Prior to 4806 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 4807 * the insets or else you and Android will be unhappy. 4808 * 4809 * @return Return true if this view applied the insets and it should not 4810 * continue propagating further down the hierarchy, false otherwise. 4811 */ 4812 protected boolean fitSystemWindows(Rect insets) { 4813 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 4814 mUserPaddingStart = -1; 4815 mUserPaddingEnd = -1; 4816 mUserPaddingRelative = false; 4817 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 4818 || mAttachInfo == null 4819 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 4820 internalSetPadding(insets.left, insets.top, insets.right, insets.bottom); 4821 return true; 4822 } else { 4823 internalSetPadding(0, 0, 0, 0); 4824 return false; 4825 } 4826 } 4827 return false; 4828 } 4829 4830 /** 4831 * Set whether or not this view should account for system screen decorations 4832 * such as the status bar and inset its content. This allows this view to be 4833 * positioned in absolute screen coordinates and remain visible to the user. 4834 * 4835 * <p>This should only be used by top-level window decor views. 4836 * 4837 * @param fitSystemWindows true to inset content for system screen decorations, false for 4838 * default behavior. 4839 * 4840 * @attr ref android.R.styleable#View_fitsSystemWindows 4841 */ 4842 public void setFitsSystemWindows(boolean fitSystemWindows) { 4843 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 4844 } 4845 4846 /** 4847 * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view 4848 * will account for system screen decorations such as the status bar and inset its 4849 * content. This allows the view to be positioned in absolute screen coordinates 4850 * and remain visible to the user. 4851 * 4852 * @return true if this view will adjust its content bounds for system screen decorations. 4853 * 4854 * @attr ref android.R.styleable#View_fitsSystemWindows 4855 */ 4856 public boolean fitsSystemWindows() { 4857 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 4858 } 4859 4860 /** 4861 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 4862 */ 4863 public void requestFitSystemWindows() { 4864 if (mParent != null) { 4865 mParent.requestFitSystemWindows(); 4866 } 4867 } 4868 4869 /** 4870 * For use by PhoneWindow to make its own system window fitting optional. 4871 * @hide 4872 */ 4873 public void makeOptionalFitsSystemWindows() { 4874 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 4875 } 4876 4877 /** 4878 * Returns the visibility status for this view. 4879 * 4880 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4881 * @attr ref android.R.styleable#View_visibility 4882 */ 4883 @ViewDebug.ExportedProperty(mapping = { 4884 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 4885 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 4886 @ViewDebug.IntToString(from = GONE, to = "GONE") 4887 }) 4888 public int getVisibility() { 4889 return mViewFlags & VISIBILITY_MASK; 4890 } 4891 4892 /** 4893 * Set the enabled state of this view. 4894 * 4895 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4896 * @attr ref android.R.styleable#View_visibility 4897 */ 4898 @RemotableViewMethod 4899 public void setVisibility(int visibility) { 4900 setFlags(visibility, VISIBILITY_MASK); 4901 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); 4902 } 4903 4904 /** 4905 * Returns the enabled status for this view. The interpretation of the 4906 * enabled state varies by subclass. 4907 * 4908 * @return True if this view is enabled, false otherwise. 4909 */ 4910 @ViewDebug.ExportedProperty 4911 public boolean isEnabled() { 4912 return (mViewFlags & ENABLED_MASK) == ENABLED; 4913 } 4914 4915 /** 4916 * Set the enabled state of this view. The interpretation of the enabled 4917 * state varies by subclass. 4918 * 4919 * @param enabled True if this view is enabled, false otherwise. 4920 */ 4921 @RemotableViewMethod 4922 public void setEnabled(boolean enabled) { 4923 if (enabled == isEnabled()) return; 4924 4925 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 4926 4927 /* 4928 * The View most likely has to change its appearance, so refresh 4929 * the drawable state. 4930 */ 4931 refreshDrawableState(); 4932 4933 // Invalidate too, since the default behavior for views is to be 4934 // be drawn at 50% alpha rather than to change the drawable. 4935 invalidate(true); 4936 } 4937 4938 /** 4939 * Set whether this view can receive the focus. 4940 * 4941 * Setting this to false will also ensure that this view is not focusable 4942 * in touch mode. 4943 * 4944 * @param focusable If true, this view can receive the focus. 4945 * 4946 * @see #setFocusableInTouchMode(boolean) 4947 * @attr ref android.R.styleable#View_focusable 4948 */ 4949 public void setFocusable(boolean focusable) { 4950 if (!focusable) { 4951 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 4952 } 4953 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 4954 } 4955 4956 /** 4957 * Set whether this view can receive focus while in touch mode. 4958 * 4959 * Setting this to true will also ensure that this view is focusable. 4960 * 4961 * @param focusableInTouchMode If true, this view can receive the focus while 4962 * in touch mode. 4963 * 4964 * @see #setFocusable(boolean) 4965 * @attr ref android.R.styleable#View_focusableInTouchMode 4966 */ 4967 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 4968 // Focusable in touch mode should always be set before the focusable flag 4969 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 4970 // which, in touch mode, will not successfully request focus on this view 4971 // because the focusable in touch mode flag is not set 4972 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 4973 if (focusableInTouchMode) { 4974 setFlags(FOCUSABLE, FOCUSABLE_MASK); 4975 } 4976 } 4977 4978 /** 4979 * Set whether this view should have sound effects enabled for events such as 4980 * clicking and touching. 4981 * 4982 * <p>You may wish to disable sound effects for a view if you already play sounds, 4983 * for instance, a dial key that plays dtmf tones. 4984 * 4985 * @param soundEffectsEnabled whether sound effects are enabled for this view. 4986 * @see #isSoundEffectsEnabled() 4987 * @see #playSoundEffect(int) 4988 * @attr ref android.R.styleable#View_soundEffectsEnabled 4989 */ 4990 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 4991 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 4992 } 4993 4994 /** 4995 * @return whether this view should have sound effects enabled for events such as 4996 * clicking and touching. 4997 * 4998 * @see #setSoundEffectsEnabled(boolean) 4999 * @see #playSoundEffect(int) 5000 * @attr ref android.R.styleable#View_soundEffectsEnabled 5001 */ 5002 @ViewDebug.ExportedProperty 5003 public boolean isSoundEffectsEnabled() { 5004 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 5005 } 5006 5007 /** 5008 * Set whether this view should have haptic feedback for events such as 5009 * long presses. 5010 * 5011 * <p>You may wish to disable haptic feedback if your view already controls 5012 * its own haptic feedback. 5013 * 5014 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 5015 * @see #isHapticFeedbackEnabled() 5016 * @see #performHapticFeedback(int) 5017 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 5018 */ 5019 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 5020 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 5021 } 5022 5023 /** 5024 * @return whether this view should have haptic feedback enabled for events 5025 * long presses. 5026 * 5027 * @see #setHapticFeedbackEnabled(boolean) 5028 * @see #performHapticFeedback(int) 5029 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 5030 */ 5031 @ViewDebug.ExportedProperty 5032 public boolean isHapticFeedbackEnabled() { 5033 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 5034 } 5035 5036 /** 5037 * Returns the layout direction for this view. 5038 * 5039 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 5040 * {@link #LAYOUT_DIRECTION_RTL}, 5041 * {@link #LAYOUT_DIRECTION_INHERIT} or 5042 * {@link #LAYOUT_DIRECTION_LOCALE}. 5043 * @attr ref android.R.styleable#View_layoutDirection 5044 */ 5045 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5046 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 5047 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 5048 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 5049 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 5050 }) 5051 public int getLayoutDirection() { 5052 return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT; 5053 } 5054 5055 /** 5056 * Set the layout direction for this view. This will propagate a reset of layout direction 5057 * resolution to the view's children and resolve layout direction for this view. 5058 * 5059 * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR}, 5060 * {@link #LAYOUT_DIRECTION_RTL}, 5061 * {@link #LAYOUT_DIRECTION_INHERIT} or 5062 * {@link #LAYOUT_DIRECTION_LOCALE}. 5063 * 5064 * @attr ref android.R.styleable#View_layoutDirection 5065 */ 5066 @RemotableViewMethod 5067 public void setLayoutDirection(int layoutDirection) { 5068 if (getLayoutDirection() != layoutDirection) { 5069 // Reset the current layout direction and the resolved one 5070 mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK; 5071 resetResolvedLayoutDirection(); 5072 // Set the new layout direction (filtered) and ask for a layout pass 5073 mPrivateFlags2 |= 5074 ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK); 5075 requestLayout(); 5076 } 5077 } 5078 5079 /** 5080 * Returns the resolved layout direction for this view. 5081 * 5082 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 5083 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 5084 */ 5085 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5086 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 5087 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 5088 }) 5089 public int getResolvedLayoutDirection() { 5090 // The layout diretion will be resolved only if needed 5091 if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) { 5092 resolveLayoutDirection(); 5093 } 5094 return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ? 5095 LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 5096 } 5097 5098 /** 5099 * Indicates whether or not this view's layout is right-to-left. This is resolved from 5100 * layout attribute and/or the inherited value from the parent 5101 * 5102 * @return true if the layout is right-to-left. 5103 */ 5104 @ViewDebug.ExportedProperty(category = "layout") 5105 public boolean isLayoutRtl() { 5106 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 5107 } 5108 5109 /** 5110 * Indicates whether the view is currently tracking transient state that the 5111 * app should not need to concern itself with saving and restoring, but that 5112 * the framework should take special note to preserve when possible. 5113 * 5114 * @return true if the view has transient state 5115 */ 5116 @ViewDebug.ExportedProperty(category = "layout") 5117 public boolean hasTransientState() { 5118 return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE; 5119 } 5120 5121 /** 5122 * Set whether this view is currently tracking transient state that the 5123 * framework should attempt to preserve when possible. 5124 * 5125 * @param hasTransientState true if this view has transient state 5126 */ 5127 public void setHasTransientState(boolean hasTransientState) { 5128 if (hasTransientState() == hasTransientState) return; 5129 5130 mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) | 5131 (hasTransientState ? HAS_TRANSIENT_STATE : 0); 5132 if (mParent != null) { 5133 try { 5134 mParent.childHasTransientStateChanged(this, hasTransientState); 5135 } catch (AbstractMethodError e) { 5136 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 5137 " does not fully implement ViewParent", e); 5138 } 5139 } 5140 } 5141 5142 /** 5143 * If this view doesn't do any drawing on its own, set this flag to 5144 * allow further optimizations. By default, this flag is not set on 5145 * View, but could be set on some View subclasses such as ViewGroup. 5146 * 5147 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 5148 * you should clear this flag. 5149 * 5150 * @param willNotDraw whether or not this View draw on its own 5151 */ 5152 public void setWillNotDraw(boolean willNotDraw) { 5153 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 5154 } 5155 5156 /** 5157 * Returns whether or not this View draws on its own. 5158 * 5159 * @return true if this view has nothing to draw, false otherwise 5160 */ 5161 @ViewDebug.ExportedProperty(category = "drawing") 5162 public boolean willNotDraw() { 5163 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 5164 } 5165 5166 /** 5167 * When a View's drawing cache is enabled, drawing is redirected to an 5168 * offscreen bitmap. Some views, like an ImageView, must be able to 5169 * bypass this mechanism if they already draw a single bitmap, to avoid 5170 * unnecessary usage of the memory. 5171 * 5172 * @param willNotCacheDrawing true if this view does not cache its 5173 * drawing, false otherwise 5174 */ 5175 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 5176 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 5177 } 5178 5179 /** 5180 * Returns whether or not this View can cache its drawing or not. 5181 * 5182 * @return true if this view does not cache its drawing, false otherwise 5183 */ 5184 @ViewDebug.ExportedProperty(category = "drawing") 5185 public boolean willNotCacheDrawing() { 5186 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 5187 } 5188 5189 /** 5190 * Indicates whether this view reacts to click events or not. 5191 * 5192 * @return true if the view is clickable, false otherwise 5193 * 5194 * @see #setClickable(boolean) 5195 * @attr ref android.R.styleable#View_clickable 5196 */ 5197 @ViewDebug.ExportedProperty 5198 public boolean isClickable() { 5199 return (mViewFlags & CLICKABLE) == CLICKABLE; 5200 } 5201 5202 /** 5203 * Enables or disables click events for this view. When a view 5204 * is clickable it will change its state to "pressed" on every click. 5205 * Subclasses should set the view clickable to visually react to 5206 * user's clicks. 5207 * 5208 * @param clickable true to make the view clickable, false otherwise 5209 * 5210 * @see #isClickable() 5211 * @attr ref android.R.styleable#View_clickable 5212 */ 5213 public void setClickable(boolean clickable) { 5214 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 5215 } 5216 5217 /** 5218 * Indicates whether this view reacts to long click events or not. 5219 * 5220 * @return true if the view is long clickable, false otherwise 5221 * 5222 * @see #setLongClickable(boolean) 5223 * @attr ref android.R.styleable#View_longClickable 5224 */ 5225 public boolean isLongClickable() { 5226 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 5227 } 5228 5229 /** 5230 * Enables or disables long click events for this view. When a view is long 5231 * clickable it reacts to the user holding down the button for a longer 5232 * duration than a tap. This event can either launch the listener or a 5233 * context menu. 5234 * 5235 * @param longClickable true to make the view long clickable, false otherwise 5236 * @see #isLongClickable() 5237 * @attr ref android.R.styleable#View_longClickable 5238 */ 5239 public void setLongClickable(boolean longClickable) { 5240 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 5241 } 5242 5243 /** 5244 * Sets the pressed state for this view. 5245 * 5246 * @see #isClickable() 5247 * @see #setClickable(boolean) 5248 * 5249 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 5250 * the View's internal state from a previously set "pressed" state. 5251 */ 5252 public void setPressed(boolean pressed) { 5253 final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED); 5254 5255 if (pressed) { 5256 mPrivateFlags |= PRESSED; 5257 } else { 5258 mPrivateFlags &= ~PRESSED; 5259 } 5260 5261 if (needsRefresh) { 5262 refreshDrawableState(); 5263 } 5264 dispatchSetPressed(pressed); 5265 } 5266 5267 /** 5268 * Dispatch setPressed to all of this View's children. 5269 * 5270 * @see #setPressed(boolean) 5271 * 5272 * @param pressed The new pressed state 5273 */ 5274 protected void dispatchSetPressed(boolean pressed) { 5275 } 5276 5277 /** 5278 * Indicates whether the view is currently in pressed state. Unless 5279 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 5280 * the pressed state. 5281 * 5282 * @see #setPressed(boolean) 5283 * @see #isClickable() 5284 * @see #setClickable(boolean) 5285 * 5286 * @return true if the view is currently pressed, false otherwise 5287 */ 5288 public boolean isPressed() { 5289 return (mPrivateFlags & PRESSED) == PRESSED; 5290 } 5291 5292 /** 5293 * Indicates whether this view will save its state (that is, 5294 * whether its {@link #onSaveInstanceState} method will be called). 5295 * 5296 * @return Returns true if the view state saving is enabled, else false. 5297 * 5298 * @see #setSaveEnabled(boolean) 5299 * @attr ref android.R.styleable#View_saveEnabled 5300 */ 5301 public boolean isSaveEnabled() { 5302 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 5303 } 5304 5305 /** 5306 * Controls whether the saving of this view's state is 5307 * enabled (that is, whether its {@link #onSaveInstanceState} method 5308 * will be called). Note that even if freezing is enabled, the 5309 * view still must have an id assigned to it (via {@link #setId(int)}) 5310 * for its state to be saved. This flag can only disable the 5311 * saving of this view; any child views may still have their state saved. 5312 * 5313 * @param enabled Set to false to <em>disable</em> state saving, or true 5314 * (the default) to allow it. 5315 * 5316 * @see #isSaveEnabled() 5317 * @see #setId(int) 5318 * @see #onSaveInstanceState() 5319 * @attr ref android.R.styleable#View_saveEnabled 5320 */ 5321 public void setSaveEnabled(boolean enabled) { 5322 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 5323 } 5324 5325 /** 5326 * Gets whether the framework should discard touches when the view's 5327 * window is obscured by another visible window. 5328 * Refer to the {@link View} security documentation for more details. 5329 * 5330 * @return True if touch filtering is enabled. 5331 * 5332 * @see #setFilterTouchesWhenObscured(boolean) 5333 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 5334 */ 5335 @ViewDebug.ExportedProperty 5336 public boolean getFilterTouchesWhenObscured() { 5337 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 5338 } 5339 5340 /** 5341 * Sets whether the framework should discard touches when the view's 5342 * window is obscured by another visible window. 5343 * Refer to the {@link View} security documentation for more details. 5344 * 5345 * @param enabled True if touch filtering should be enabled. 5346 * 5347 * @see #getFilterTouchesWhenObscured 5348 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 5349 */ 5350 public void setFilterTouchesWhenObscured(boolean enabled) { 5351 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 5352 FILTER_TOUCHES_WHEN_OBSCURED); 5353 } 5354 5355 /** 5356 * Indicates whether the entire hierarchy under this view will save its 5357 * state when a state saving traversal occurs from its parent. The default 5358 * is true; if false, these views will not be saved unless 5359 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 5360 * 5361 * @return Returns true if the view state saving from parent is enabled, else false. 5362 * 5363 * @see #setSaveFromParentEnabled(boolean) 5364 */ 5365 public boolean isSaveFromParentEnabled() { 5366 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 5367 } 5368 5369 /** 5370 * Controls whether the entire hierarchy under this view will save its 5371 * state when a state saving traversal occurs from its parent. The default 5372 * is true; if false, these views will not be saved unless 5373 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 5374 * 5375 * @param enabled Set to false to <em>disable</em> state saving, or true 5376 * (the default) to allow it. 5377 * 5378 * @see #isSaveFromParentEnabled() 5379 * @see #setId(int) 5380 * @see #onSaveInstanceState() 5381 */ 5382 public void setSaveFromParentEnabled(boolean enabled) { 5383 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 5384 } 5385 5386 5387 /** 5388 * Returns whether this View is able to take focus. 5389 * 5390 * @return True if this view can take focus, or false otherwise. 5391 * @attr ref android.R.styleable#View_focusable 5392 */ 5393 @ViewDebug.ExportedProperty(category = "focus") 5394 public final boolean isFocusable() { 5395 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 5396 } 5397 5398 /** 5399 * When a view is focusable, it may not want to take focus when in touch mode. 5400 * For example, a button would like focus when the user is navigating via a D-pad 5401 * so that the user can click on it, but once the user starts touching the screen, 5402 * the button shouldn't take focus 5403 * @return Whether the view is focusable in touch mode. 5404 * @attr ref android.R.styleable#View_focusableInTouchMode 5405 */ 5406 @ViewDebug.ExportedProperty 5407 public final boolean isFocusableInTouchMode() { 5408 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 5409 } 5410 5411 /** 5412 * Find the nearest view in the specified direction that can take focus. 5413 * This does not actually give focus to that view. 5414 * 5415 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5416 * 5417 * @return The nearest focusable in the specified direction, or null if none 5418 * can be found. 5419 */ 5420 public View focusSearch(int direction) { 5421 if (mParent != null) { 5422 return mParent.focusSearch(this, direction); 5423 } else { 5424 return null; 5425 } 5426 } 5427 5428 /** 5429 * This method is the last chance for the focused view and its ancestors to 5430 * respond to an arrow key. This is called when the focused view did not 5431 * consume the key internally, nor could the view system find a new view in 5432 * the requested direction to give focus to. 5433 * 5434 * @param focused The currently focused view. 5435 * @param direction The direction focus wants to move. One of FOCUS_UP, 5436 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 5437 * @return True if the this view consumed this unhandled move. 5438 */ 5439 public boolean dispatchUnhandledMove(View focused, int direction) { 5440 return false; 5441 } 5442 5443 /** 5444 * If a user manually specified the next view id for a particular direction, 5445 * use the root to look up the view. 5446 * @param root The root view of the hierarchy containing this view. 5447 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 5448 * or FOCUS_BACKWARD. 5449 * @return The user specified next view, or null if there is none. 5450 */ 5451 View findUserSetNextFocus(View root, int direction) { 5452 switch (direction) { 5453 case FOCUS_LEFT: 5454 if (mNextFocusLeftId == View.NO_ID) return null; 5455 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 5456 case FOCUS_RIGHT: 5457 if (mNextFocusRightId == View.NO_ID) return null; 5458 return findViewInsideOutShouldExist(root, mNextFocusRightId); 5459 case FOCUS_UP: 5460 if (mNextFocusUpId == View.NO_ID) return null; 5461 return findViewInsideOutShouldExist(root, mNextFocusUpId); 5462 case FOCUS_DOWN: 5463 if (mNextFocusDownId == View.NO_ID) return null; 5464 return findViewInsideOutShouldExist(root, mNextFocusDownId); 5465 case FOCUS_FORWARD: 5466 if (mNextFocusForwardId == View.NO_ID) return null; 5467 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 5468 case FOCUS_BACKWARD: { 5469 if (mID == View.NO_ID) return null; 5470 final int id = mID; 5471 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5472 @Override 5473 public boolean apply(View t) { 5474 return t.mNextFocusForwardId == id; 5475 } 5476 }); 5477 } 5478 } 5479 return null; 5480 } 5481 5482 private View findViewInsideOutShouldExist(View root, final int childViewId) { 5483 View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5484 @Override 5485 public boolean apply(View t) { 5486 return t.mID == childViewId; 5487 } 5488 }); 5489 5490 if (result == null) { 5491 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified " 5492 + "by user for id " + childViewId); 5493 } 5494 return result; 5495 } 5496 5497 /** 5498 * Find and return all focusable views that are descendants of this view, 5499 * possibly including this view if it is focusable itself. 5500 * 5501 * @param direction The direction of the focus 5502 * @return A list of focusable views 5503 */ 5504 public ArrayList<View> getFocusables(int direction) { 5505 ArrayList<View> result = new ArrayList<View>(24); 5506 addFocusables(result, direction); 5507 return result; 5508 } 5509 5510 /** 5511 * Add any focusable views that are descendants of this view (possibly 5512 * including this view if it is focusable itself) to views. If we are in touch mode, 5513 * only add views that are also focusable in touch mode. 5514 * 5515 * @param views Focusable views found so far 5516 * @param direction The direction of the focus 5517 */ 5518 public void addFocusables(ArrayList<View> views, int direction) { 5519 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 5520 } 5521 5522 /** 5523 * Adds any focusable views that are descendants of this view (possibly 5524 * including this view if it is focusable itself) to views. This method 5525 * adds all focusable views regardless if we are in touch mode or 5526 * only views focusable in touch mode if we are in touch mode depending on 5527 * the focusable mode paramater. 5528 * 5529 * @param views Focusable views found so far or null if all we are interested is 5530 * the number of focusables. 5531 * @param direction The direction of the focus. 5532 * @param focusableMode The type of focusables to be added. 5533 * 5534 * @see #FOCUSABLES_ALL 5535 * @see #FOCUSABLES_TOUCH_MODE 5536 */ 5537 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 5538 if (!isFocusable()) { 5539 return; 5540 } 5541 5542 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 5543 isInTouchMode() && !isFocusableInTouchMode()) { 5544 return; 5545 } 5546 5547 if (views != null) { 5548 views.add(this); 5549 } 5550 } 5551 5552 /** 5553 * Finds the Views that contain given text. The containment is case insensitive. 5554 * The search is performed by either the text that the View renders or the content 5555 * description that describes the view for accessibility purposes and the view does 5556 * not render or both. Clients can specify how the search is to be performed via 5557 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 5558 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 5559 * 5560 * @param outViews The output list of matching Views. 5561 * @param searched The text to match against. 5562 * 5563 * @see #FIND_VIEWS_WITH_TEXT 5564 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 5565 * @see #setContentDescription(CharSequence) 5566 */ 5567 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 5568 if (getAccessibilityNodeProvider() != null) { 5569 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 5570 outViews.add(this); 5571 } 5572 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 5573 && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) { 5574 String searchedLowerCase = searched.toString().toLowerCase(); 5575 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 5576 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 5577 outViews.add(this); 5578 } 5579 } 5580 } 5581 5582 /** 5583 * Find and return all touchable views that are descendants of this view, 5584 * possibly including this view if it is touchable itself. 5585 * 5586 * @return A list of touchable views 5587 */ 5588 public ArrayList<View> getTouchables() { 5589 ArrayList<View> result = new ArrayList<View>(); 5590 addTouchables(result); 5591 return result; 5592 } 5593 5594 /** 5595 * Add any touchable views that are descendants of this view (possibly 5596 * including this view if it is touchable itself) to views. 5597 * 5598 * @param views Touchable views found so far 5599 */ 5600 public void addTouchables(ArrayList<View> views) { 5601 final int viewFlags = mViewFlags; 5602 5603 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 5604 && (viewFlags & ENABLED_MASK) == ENABLED) { 5605 views.add(this); 5606 } 5607 } 5608 5609 /** 5610 * Call this to try to give focus to a specific view or to one of its 5611 * descendants. 5612 * 5613 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5614 * false), or if it is focusable and it is not focusable in touch mode 5615 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5616 * 5617 * See also {@link #focusSearch(int)}, which is what you call to say that you 5618 * have focus, and you want your parent to look for the next one. 5619 * 5620 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 5621 * {@link #FOCUS_DOWN} and <code>null</code>. 5622 * 5623 * @return Whether this view or one of its descendants actually took focus. 5624 */ 5625 public final boolean requestFocus() { 5626 return requestFocus(View.FOCUS_DOWN); 5627 } 5628 5629 5630 /** 5631 * Call this to try to give focus to a specific view or to one of its 5632 * descendants and give it a hint about what direction focus is heading. 5633 * 5634 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5635 * false), or if it is focusable and it is not focusable in touch mode 5636 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5637 * 5638 * See also {@link #focusSearch(int)}, which is what you call to say that you 5639 * have focus, and you want your parent to look for the next one. 5640 * 5641 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 5642 * <code>null</code> set for the previously focused rectangle. 5643 * 5644 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5645 * @return Whether this view or one of its descendants actually took focus. 5646 */ 5647 public final boolean requestFocus(int direction) { 5648 return requestFocus(direction, null); 5649 } 5650 5651 /** 5652 * Call this to try to give focus to a specific view or to one of its descendants 5653 * and give it hints about the direction and a specific rectangle that the focus 5654 * is coming from. The rectangle can help give larger views a finer grained hint 5655 * about where focus is coming from, and therefore, where to show selection, or 5656 * forward focus change internally. 5657 * 5658 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5659 * false), or if it is focusable and it is not focusable in touch mode 5660 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5661 * 5662 * A View will not take focus if it is not visible. 5663 * 5664 * A View will not take focus if one of its parents has 5665 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 5666 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 5667 * 5668 * See also {@link #focusSearch(int)}, which is what you call to say that you 5669 * have focus, and you want your parent to look for the next one. 5670 * 5671 * You may wish to override this method if your custom {@link View} has an internal 5672 * {@link View} that it wishes to forward the request to. 5673 * 5674 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5675 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 5676 * to give a finer grained hint about where focus is coming from. May be null 5677 * if there is no hint. 5678 * @return Whether this view or one of its descendants actually took focus. 5679 */ 5680 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 5681 // need to be focusable 5682 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 5683 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5684 return false; 5685 } 5686 5687 // need to be focusable in touch mode if in touch mode 5688 if (isInTouchMode() && 5689 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 5690 return false; 5691 } 5692 5693 // need to not have any parents blocking us 5694 if (hasAncestorThatBlocksDescendantFocus()) { 5695 return false; 5696 } 5697 5698 handleFocusGainInternal(direction, previouslyFocusedRect); 5699 return true; 5700 } 5701 5702 /** 5703 * Call this to try to give focus to a specific view or to one of its descendants. This is a 5704 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 5705 * touch mode to request focus when they are touched. 5706 * 5707 * @return Whether this view or one of its descendants actually took focus. 5708 * 5709 * @see #isInTouchMode() 5710 * 5711 */ 5712 public final boolean requestFocusFromTouch() { 5713 // Leave touch mode if we need to 5714 if (isInTouchMode()) { 5715 ViewRootImpl viewRoot = getViewRootImpl(); 5716 if (viewRoot != null) { 5717 viewRoot.ensureTouchMode(false); 5718 } 5719 } 5720 return requestFocus(View.FOCUS_DOWN); 5721 } 5722 5723 /** 5724 * @return Whether any ancestor of this view blocks descendant focus. 5725 */ 5726 private boolean hasAncestorThatBlocksDescendantFocus() { 5727 ViewParent ancestor = mParent; 5728 while (ancestor instanceof ViewGroup) { 5729 final ViewGroup vgAncestor = (ViewGroup) ancestor; 5730 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 5731 return true; 5732 } else { 5733 ancestor = vgAncestor.getParent(); 5734 } 5735 } 5736 return false; 5737 } 5738 5739 /** 5740 * @hide 5741 */ 5742 public void dispatchStartTemporaryDetach() { 5743 onStartTemporaryDetach(); 5744 } 5745 5746 /** 5747 * This is called when a container is going to temporarily detach a child, with 5748 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 5749 * It will either be followed by {@link #onFinishTemporaryDetach()} or 5750 * {@link #onDetachedFromWindow()} when the container is done. 5751 */ 5752 public void onStartTemporaryDetach() { 5753 removeUnsetPressCallback(); 5754 mPrivateFlags |= CANCEL_NEXT_UP_EVENT; 5755 } 5756 5757 /** 5758 * @hide 5759 */ 5760 public void dispatchFinishTemporaryDetach() { 5761 onFinishTemporaryDetach(); 5762 } 5763 5764 /** 5765 * Called after {@link #onStartTemporaryDetach} when the container is done 5766 * changing the view. 5767 */ 5768 public void onFinishTemporaryDetach() { 5769 } 5770 5771 /** 5772 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 5773 * for this view's window. Returns null if the view is not currently attached 5774 * to the window. Normally you will not need to use this directly, but 5775 * just use the standard high-level event callbacks like 5776 * {@link #onKeyDown(int, KeyEvent)}. 5777 */ 5778 public KeyEvent.DispatcherState getKeyDispatcherState() { 5779 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 5780 } 5781 5782 /** 5783 * Dispatch a key event before it is processed by any input method 5784 * associated with the view hierarchy. This can be used to intercept 5785 * key events in special situations before the IME consumes them; a 5786 * typical example would be handling the BACK key to update the application's 5787 * UI instead of allowing the IME to see it and close itself. 5788 * 5789 * @param event The key event to be dispatched. 5790 * @return True if the event was handled, false otherwise. 5791 */ 5792 public boolean dispatchKeyEventPreIme(KeyEvent event) { 5793 return onKeyPreIme(event.getKeyCode(), event); 5794 } 5795 5796 /** 5797 * Dispatch a key event to the next view on the focus path. This path runs 5798 * from the top of the view tree down to the currently focused view. If this 5799 * view has focus, it will dispatch to itself. Otherwise it will dispatch 5800 * the next node down the focus path. This method also fires any key 5801 * listeners. 5802 * 5803 * @param event The key event to be dispatched. 5804 * @return True if the event was handled, false otherwise. 5805 */ 5806 public boolean dispatchKeyEvent(KeyEvent event) { 5807 if (mInputEventConsistencyVerifier != null) { 5808 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 5809 } 5810 5811 // Give any attached key listener a first crack at the event. 5812 //noinspection SimplifiableIfStatement 5813 ListenerInfo li = mListenerInfo; 5814 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5815 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 5816 return true; 5817 } 5818 5819 if (event.dispatch(this, mAttachInfo != null 5820 ? mAttachInfo.mKeyDispatchState : null, this)) { 5821 return true; 5822 } 5823 5824 if (mInputEventConsistencyVerifier != null) { 5825 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5826 } 5827 return false; 5828 } 5829 5830 /** 5831 * Dispatches a key shortcut event. 5832 * 5833 * @param event The key event to be dispatched. 5834 * @return True if the event was handled by the view, false otherwise. 5835 */ 5836 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 5837 return onKeyShortcut(event.getKeyCode(), event); 5838 } 5839 5840 /** 5841 * Pass the touch screen motion event down to the target view, or this 5842 * view if it is the target. 5843 * 5844 * @param event The motion event to be dispatched. 5845 * @return True if the event was handled by the view, false otherwise. 5846 */ 5847 public boolean dispatchTouchEvent(MotionEvent event) { 5848 if (mInputEventConsistencyVerifier != null) { 5849 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 5850 } 5851 5852 if (onFilterTouchEventForSecurity(event)) { 5853 //noinspection SimplifiableIfStatement 5854 ListenerInfo li = mListenerInfo; 5855 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5856 && li.mOnTouchListener.onTouch(this, event)) { 5857 return true; 5858 } 5859 5860 if (onTouchEvent(event)) { 5861 return true; 5862 } 5863 } 5864 5865 if (mInputEventConsistencyVerifier != null) { 5866 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5867 } 5868 return false; 5869 } 5870 5871 /** 5872 * Filter the touch event to apply security policies. 5873 * 5874 * @param event The motion event to be filtered. 5875 * @return True if the event should be dispatched, false if the event should be dropped. 5876 * 5877 * @see #getFilterTouchesWhenObscured 5878 */ 5879 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 5880 //noinspection RedundantIfStatement 5881 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 5882 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 5883 // Window is obscured, drop this touch. 5884 return false; 5885 } 5886 return true; 5887 } 5888 5889 /** 5890 * Pass a trackball motion event down to the focused view. 5891 * 5892 * @param event The motion event to be dispatched. 5893 * @return True if the event was handled by the view, false otherwise. 5894 */ 5895 public boolean dispatchTrackballEvent(MotionEvent event) { 5896 if (mInputEventConsistencyVerifier != null) { 5897 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 5898 } 5899 5900 return onTrackballEvent(event); 5901 } 5902 5903 /** 5904 * Dispatch a generic motion event. 5905 * <p> 5906 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5907 * are delivered to the view under the pointer. All other generic motion events are 5908 * delivered to the focused view. Hover events are handled specially and are delivered 5909 * to {@link #onHoverEvent(MotionEvent)}. 5910 * </p> 5911 * 5912 * @param event The motion event to be dispatched. 5913 * @return True if the event was handled by the view, false otherwise. 5914 */ 5915 public boolean dispatchGenericMotionEvent(MotionEvent event) { 5916 if (mInputEventConsistencyVerifier != null) { 5917 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 5918 } 5919 5920 final int source = event.getSource(); 5921 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5922 final int action = event.getAction(); 5923 if (action == MotionEvent.ACTION_HOVER_ENTER 5924 || action == MotionEvent.ACTION_HOVER_MOVE 5925 || action == MotionEvent.ACTION_HOVER_EXIT) { 5926 if (dispatchHoverEvent(event)) { 5927 return true; 5928 } 5929 } else if (dispatchGenericPointerEvent(event)) { 5930 return true; 5931 } 5932 } else if (dispatchGenericFocusedEvent(event)) { 5933 return true; 5934 } 5935 5936 if (dispatchGenericMotionEventInternal(event)) { 5937 return true; 5938 } 5939 5940 if (mInputEventConsistencyVerifier != null) { 5941 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5942 } 5943 return false; 5944 } 5945 5946 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 5947 //noinspection SimplifiableIfStatement 5948 ListenerInfo li = mListenerInfo; 5949 if (li != null && li.mOnGenericMotionListener != null 5950 && (mViewFlags & ENABLED_MASK) == ENABLED 5951 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 5952 return true; 5953 } 5954 5955 if (onGenericMotionEvent(event)) { 5956 return true; 5957 } 5958 5959 if (mInputEventConsistencyVerifier != null) { 5960 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5961 } 5962 return false; 5963 } 5964 5965 /** 5966 * Dispatch a hover event. 5967 * <p> 5968 * Do not call this method directly. 5969 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5970 * </p> 5971 * 5972 * @param event The motion event to be dispatched. 5973 * @return True if the event was handled by the view, false otherwise. 5974 */ 5975 protected boolean dispatchHoverEvent(MotionEvent event) { 5976 //noinspection SimplifiableIfStatement 5977 ListenerInfo li = mListenerInfo; 5978 if (li != null && li.mOnHoverListener != null 5979 && (mViewFlags & ENABLED_MASK) == ENABLED 5980 && li.mOnHoverListener.onHover(this, event)) { 5981 return true; 5982 } 5983 5984 return onHoverEvent(event); 5985 } 5986 5987 /** 5988 * Returns true if the view has a child to which it has recently sent 5989 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 5990 * it does not have a hovered child, then it must be the innermost hovered view. 5991 * @hide 5992 */ 5993 protected boolean hasHoveredChild() { 5994 return false; 5995 } 5996 5997 /** 5998 * Dispatch a generic motion event to the view under the first pointer. 5999 * <p> 6000 * Do not call this method directly. 6001 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 6002 * </p> 6003 * 6004 * @param event The motion event to be dispatched. 6005 * @return True if the event was handled by the view, false otherwise. 6006 */ 6007 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 6008 return false; 6009 } 6010 6011 /** 6012 * Dispatch a generic motion event to the currently focused view. 6013 * <p> 6014 * Do not call this method directly. 6015 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 6016 * </p> 6017 * 6018 * @param event The motion event to be dispatched. 6019 * @return True if the event was handled by the view, false otherwise. 6020 */ 6021 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 6022 return false; 6023 } 6024 6025 /** 6026 * Dispatch a pointer event. 6027 * <p> 6028 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 6029 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 6030 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 6031 * and should not be expected to handle other pointing device features. 6032 * </p> 6033 * 6034 * @param event The motion event to be dispatched. 6035 * @return True if the event was handled by the view, false otherwise. 6036 * @hide 6037 */ 6038 public final boolean dispatchPointerEvent(MotionEvent event) { 6039 if (event.isTouchEvent()) { 6040 return dispatchTouchEvent(event); 6041 } else { 6042 return dispatchGenericMotionEvent(event); 6043 } 6044 } 6045 6046 /** 6047 * Called when the window containing this view gains or loses window focus. 6048 * ViewGroups should override to route to their children. 6049 * 6050 * @param hasFocus True if the window containing this view now has focus, 6051 * false otherwise. 6052 */ 6053 public void dispatchWindowFocusChanged(boolean hasFocus) { 6054 onWindowFocusChanged(hasFocus); 6055 } 6056 6057 /** 6058 * Called when the window containing this view gains or loses focus. Note 6059 * that this is separate from view focus: to receive key events, both 6060 * your view and its window must have focus. If a window is displayed 6061 * on top of yours that takes input focus, then your own window will lose 6062 * focus but the view focus will remain unchanged. 6063 * 6064 * @param hasWindowFocus True if the window containing this view now has 6065 * focus, false otherwise. 6066 */ 6067 public void onWindowFocusChanged(boolean hasWindowFocus) { 6068 InputMethodManager imm = InputMethodManager.peekInstance(); 6069 if (!hasWindowFocus) { 6070 if (isPressed()) { 6071 setPressed(false); 6072 } 6073 if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 6074 imm.focusOut(this); 6075 } 6076 removeLongPressCallback(); 6077 removeTapCallback(); 6078 onFocusLost(); 6079 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 6080 imm.focusIn(this); 6081 } 6082 refreshDrawableState(); 6083 } 6084 6085 /** 6086 * Returns true if this view is in a window that currently has window focus. 6087 * Note that this is not the same as the view itself having focus. 6088 * 6089 * @return True if this view is in a window that currently has window focus. 6090 */ 6091 public boolean hasWindowFocus() { 6092 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 6093 } 6094 6095 /** 6096 * Dispatch a view visibility change down the view hierarchy. 6097 * ViewGroups should override to route to their children. 6098 * @param changedView The view whose visibility changed. Could be 'this' or 6099 * an ancestor view. 6100 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 6101 * {@link #INVISIBLE} or {@link #GONE}. 6102 */ 6103 protected void dispatchVisibilityChanged(View changedView, int visibility) { 6104 onVisibilityChanged(changedView, visibility); 6105 } 6106 6107 /** 6108 * Called when the visibility of the view or an ancestor of the view is changed. 6109 * @param changedView The view whose visibility changed. Could be 'this' or 6110 * an ancestor view. 6111 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 6112 * {@link #INVISIBLE} or {@link #GONE}. 6113 */ 6114 protected void onVisibilityChanged(View changedView, int visibility) { 6115 if (visibility == VISIBLE) { 6116 if (mAttachInfo != null) { 6117 initialAwakenScrollBars(); 6118 } else { 6119 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH; 6120 } 6121 } 6122 } 6123 6124 /** 6125 * Dispatch a hint about whether this view is displayed. For instance, when 6126 * a View moves out of the screen, it might receives a display hint indicating 6127 * the view is not displayed. Applications should not <em>rely</em> on this hint 6128 * as there is no guarantee that they will receive one. 6129 * 6130 * @param hint A hint about whether or not this view is displayed: 6131 * {@link #VISIBLE} or {@link #INVISIBLE}. 6132 */ 6133 public void dispatchDisplayHint(int hint) { 6134 onDisplayHint(hint); 6135 } 6136 6137 /** 6138 * Gives this view a hint about whether is displayed or not. For instance, when 6139 * a View moves out of the screen, it might receives a display hint indicating 6140 * the view is not displayed. Applications should not <em>rely</em> on this hint 6141 * as there is no guarantee that they will receive one. 6142 * 6143 * @param hint A hint about whether or not this view is displayed: 6144 * {@link #VISIBLE} or {@link #INVISIBLE}. 6145 */ 6146 protected void onDisplayHint(int hint) { 6147 } 6148 6149 /** 6150 * Dispatch a window visibility change down the view hierarchy. 6151 * ViewGroups should override to route to their children. 6152 * 6153 * @param visibility The new visibility of the window. 6154 * 6155 * @see #onWindowVisibilityChanged(int) 6156 */ 6157 public void dispatchWindowVisibilityChanged(int visibility) { 6158 onWindowVisibilityChanged(visibility); 6159 } 6160 6161 /** 6162 * Called when the window containing has change its visibility 6163 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 6164 * that this tells you whether or not your window is being made visible 6165 * to the window manager; this does <em>not</em> tell you whether or not 6166 * your window is obscured by other windows on the screen, even if it 6167 * is itself visible. 6168 * 6169 * @param visibility The new visibility of the window. 6170 */ 6171 protected void onWindowVisibilityChanged(int visibility) { 6172 if (visibility == VISIBLE) { 6173 initialAwakenScrollBars(); 6174 } 6175 } 6176 6177 /** 6178 * Returns the current visibility of the window this view is attached to 6179 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 6180 * 6181 * @return Returns the current visibility of the view's window. 6182 */ 6183 public int getWindowVisibility() { 6184 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 6185 } 6186 6187 /** 6188 * Retrieve the overall visible display size in which the window this view is 6189 * attached to has been positioned in. This takes into account screen 6190 * decorations above the window, for both cases where the window itself 6191 * is being position inside of them or the window is being placed under 6192 * then and covered insets are used for the window to position its content 6193 * inside. In effect, this tells you the available area where content can 6194 * be placed and remain visible to users. 6195 * 6196 * <p>This function requires an IPC back to the window manager to retrieve 6197 * the requested information, so should not be used in performance critical 6198 * code like drawing. 6199 * 6200 * @param outRect Filled in with the visible display frame. If the view 6201 * is not attached to a window, this is simply the raw display size. 6202 */ 6203 public void getWindowVisibleDisplayFrame(Rect outRect) { 6204 if (mAttachInfo != null) { 6205 try { 6206 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 6207 } catch (RemoteException e) { 6208 return; 6209 } 6210 // XXX This is really broken, and probably all needs to be done 6211 // in the window manager, and we need to know more about whether 6212 // we want the area behind or in front of the IME. 6213 final Rect insets = mAttachInfo.mVisibleInsets; 6214 outRect.left += insets.left; 6215 outRect.top += insets.top; 6216 outRect.right -= insets.right; 6217 outRect.bottom -= insets.bottom; 6218 return; 6219 } 6220 Display d = WindowManagerImpl.getDefault().getDefaultDisplay(); 6221 d.getRectSize(outRect); 6222 } 6223 6224 /** 6225 * Dispatch a notification about a resource configuration change down 6226 * the view hierarchy. 6227 * ViewGroups should override to route to their children. 6228 * 6229 * @param newConfig The new resource configuration. 6230 * 6231 * @see #onConfigurationChanged(android.content.res.Configuration) 6232 */ 6233 public void dispatchConfigurationChanged(Configuration newConfig) { 6234 onConfigurationChanged(newConfig); 6235 } 6236 6237 /** 6238 * Called when the current configuration of the resources being used 6239 * by the application have changed. You can use this to decide when 6240 * to reload resources that can changed based on orientation and other 6241 * configuration characterstics. You only need to use this if you are 6242 * not relying on the normal {@link android.app.Activity} mechanism of 6243 * recreating the activity instance upon a configuration change. 6244 * 6245 * @param newConfig The new resource configuration. 6246 */ 6247 protected void onConfigurationChanged(Configuration newConfig) { 6248 } 6249 6250 /** 6251 * Private function to aggregate all per-view attributes in to the view 6252 * root. 6253 */ 6254 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 6255 performCollectViewAttributes(attachInfo, visibility); 6256 } 6257 6258 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 6259 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 6260 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 6261 attachInfo.mKeepScreenOn = true; 6262 } 6263 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 6264 ListenerInfo li = mListenerInfo; 6265 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 6266 attachInfo.mHasSystemUiListeners = true; 6267 } 6268 } 6269 } 6270 6271 void needGlobalAttributesUpdate(boolean force) { 6272 final AttachInfo ai = mAttachInfo; 6273 if (ai != null) { 6274 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 6275 || ai.mHasSystemUiListeners) { 6276 ai.mRecomputeGlobalAttributes = true; 6277 } 6278 } 6279 } 6280 6281 /** 6282 * Returns whether the device is currently in touch mode. Touch mode is entered 6283 * once the user begins interacting with the device by touch, and affects various 6284 * things like whether focus is always visible to the user. 6285 * 6286 * @return Whether the device is in touch mode. 6287 */ 6288 @ViewDebug.ExportedProperty 6289 public boolean isInTouchMode() { 6290 if (mAttachInfo != null) { 6291 return mAttachInfo.mInTouchMode; 6292 } else { 6293 return ViewRootImpl.isInTouchMode(); 6294 } 6295 } 6296 6297 /** 6298 * Returns the context the view is running in, through which it can 6299 * access the current theme, resources, etc. 6300 * 6301 * @return The view's Context. 6302 */ 6303 @ViewDebug.CapturedViewProperty 6304 public final Context getContext() { 6305 return mContext; 6306 } 6307 6308 /** 6309 * Handle a key event before it is processed by any input method 6310 * associated with the view hierarchy. This can be used to intercept 6311 * key events in special situations before the IME consumes them; a 6312 * typical example would be handling the BACK key to update the application's 6313 * UI instead of allowing the IME to see it and close itself. 6314 * 6315 * @param keyCode The value in event.getKeyCode(). 6316 * @param event Description of the key event. 6317 * @return If you handled the event, return true. If you want to allow the 6318 * event to be handled by the next receiver, return false. 6319 */ 6320 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 6321 return false; 6322 } 6323 6324 /** 6325 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 6326 * KeyEvent.Callback.onKeyDown()}: perform press of the view 6327 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 6328 * is released, if the view is enabled and clickable. 6329 * 6330 * @param keyCode A key code that represents the button pressed, from 6331 * {@link android.view.KeyEvent}. 6332 * @param event The KeyEvent object that defines the button action. 6333 */ 6334 public boolean onKeyDown(int keyCode, KeyEvent event) { 6335 boolean result = false; 6336 6337 switch (keyCode) { 6338 case KeyEvent.KEYCODE_DPAD_CENTER: 6339 case KeyEvent.KEYCODE_ENTER: { 6340 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6341 return true; 6342 } 6343 // Long clickable items don't necessarily have to be clickable 6344 if (((mViewFlags & CLICKABLE) == CLICKABLE || 6345 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 6346 (event.getRepeatCount() == 0)) { 6347 setPressed(true); 6348 checkForLongClick(0); 6349 return true; 6350 } 6351 break; 6352 } 6353 } 6354 return result; 6355 } 6356 6357 /** 6358 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 6359 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 6360 * the event). 6361 */ 6362 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 6363 return false; 6364 } 6365 6366 /** 6367 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 6368 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 6369 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 6370 * {@link KeyEvent#KEYCODE_ENTER} is released. 6371 * 6372 * @param keyCode A key code that represents the button pressed, from 6373 * {@link android.view.KeyEvent}. 6374 * @param event The KeyEvent object that defines the button action. 6375 */ 6376 public boolean onKeyUp(int keyCode, KeyEvent event) { 6377 boolean result = false; 6378 6379 switch (keyCode) { 6380 case KeyEvent.KEYCODE_DPAD_CENTER: 6381 case KeyEvent.KEYCODE_ENTER: { 6382 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6383 return true; 6384 } 6385 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 6386 setPressed(false); 6387 6388 if (!mHasPerformedLongPress) { 6389 // This is a tap, so remove the longpress check 6390 removeLongPressCallback(); 6391 6392 result = performClick(); 6393 } 6394 } 6395 break; 6396 } 6397 } 6398 return result; 6399 } 6400 6401 /** 6402 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 6403 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 6404 * the event). 6405 * 6406 * @param keyCode A key code that represents the button pressed, from 6407 * {@link android.view.KeyEvent}. 6408 * @param repeatCount The number of times the action was made. 6409 * @param event The KeyEvent object that defines the button action. 6410 */ 6411 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 6412 return false; 6413 } 6414 6415 /** 6416 * Called on the focused view when a key shortcut event is not handled. 6417 * Override this method to implement local key shortcuts for the View. 6418 * Key shortcuts can also be implemented by setting the 6419 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 6420 * 6421 * @param keyCode The value in event.getKeyCode(). 6422 * @param event Description of the key event. 6423 * @return If you handled the event, return true. If you want to allow the 6424 * event to be handled by the next receiver, return false. 6425 */ 6426 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 6427 return false; 6428 } 6429 6430 /** 6431 * Check whether the called view is a text editor, in which case it 6432 * would make sense to automatically display a soft input window for 6433 * it. Subclasses should override this if they implement 6434 * {@link #onCreateInputConnection(EditorInfo)} to return true if 6435 * a call on that method would return a non-null InputConnection, and 6436 * they are really a first-class editor that the user would normally 6437 * start typing on when the go into a window containing your view. 6438 * 6439 * <p>The default implementation always returns false. This does 6440 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 6441 * will not be called or the user can not otherwise perform edits on your 6442 * view; it is just a hint to the system that this is not the primary 6443 * purpose of this view. 6444 * 6445 * @return Returns true if this view is a text editor, else false. 6446 */ 6447 public boolean onCheckIsTextEditor() { 6448 return false; 6449 } 6450 6451 /** 6452 * Create a new InputConnection for an InputMethod to interact 6453 * with the view. The default implementation returns null, since it doesn't 6454 * support input methods. You can override this to implement such support. 6455 * This is only needed for views that take focus and text input. 6456 * 6457 * <p>When implementing this, you probably also want to implement 6458 * {@link #onCheckIsTextEditor()} to indicate you will return a 6459 * non-null InputConnection. 6460 * 6461 * @param outAttrs Fill in with attribute information about the connection. 6462 */ 6463 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 6464 return null; 6465 } 6466 6467 /** 6468 * Called by the {@link android.view.inputmethod.InputMethodManager} 6469 * when a view who is not the current 6470 * input connection target is trying to make a call on the manager. The 6471 * default implementation returns false; you can override this to return 6472 * true for certain views if you are performing InputConnection proxying 6473 * to them. 6474 * @param view The View that is making the InputMethodManager call. 6475 * @return Return true to allow the call, false to reject. 6476 */ 6477 public boolean checkInputConnectionProxy(View view) { 6478 return false; 6479 } 6480 6481 /** 6482 * Show the context menu for this view. It is not safe to hold on to the 6483 * menu after returning from this method. 6484 * 6485 * You should normally not overload this method. Overload 6486 * {@link #onCreateContextMenu(ContextMenu)} or define an 6487 * {@link OnCreateContextMenuListener} to add items to the context menu. 6488 * 6489 * @param menu The context menu to populate 6490 */ 6491 public void createContextMenu(ContextMenu menu) { 6492 ContextMenuInfo menuInfo = getContextMenuInfo(); 6493 6494 // Sets the current menu info so all items added to menu will have 6495 // my extra info set. 6496 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 6497 6498 onCreateContextMenu(menu); 6499 ListenerInfo li = mListenerInfo; 6500 if (li != null && li.mOnCreateContextMenuListener != null) { 6501 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 6502 } 6503 6504 // Clear the extra information so subsequent items that aren't mine don't 6505 // have my extra info. 6506 ((MenuBuilder)menu).setCurrentMenuInfo(null); 6507 6508 if (mParent != null) { 6509 mParent.createContextMenu(menu); 6510 } 6511 } 6512 6513 /** 6514 * Views should implement this if they have extra information to associate 6515 * with the context menu. The return result is supplied as a parameter to 6516 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 6517 * callback. 6518 * 6519 * @return Extra information about the item for which the context menu 6520 * should be shown. This information will vary across different 6521 * subclasses of View. 6522 */ 6523 protected ContextMenuInfo getContextMenuInfo() { 6524 return null; 6525 } 6526 6527 /** 6528 * Views should implement this if the view itself is going to add items to 6529 * the context menu. 6530 * 6531 * @param menu the context menu to populate 6532 */ 6533 protected void onCreateContextMenu(ContextMenu menu) { 6534 } 6535 6536 /** 6537 * Implement this method to handle trackball motion events. The 6538 * <em>relative</em> movement of the trackball since the last event 6539 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 6540 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 6541 * that a movement of 1 corresponds to the user pressing one DPAD key (so 6542 * they will often be fractional values, representing the more fine-grained 6543 * movement information available from a trackball). 6544 * 6545 * @param event The motion event. 6546 * @return True if the event was handled, false otherwise. 6547 */ 6548 public boolean onTrackballEvent(MotionEvent event) { 6549 return false; 6550 } 6551 6552 /** 6553 * Implement this method to handle generic motion events. 6554 * <p> 6555 * Generic motion events describe joystick movements, mouse hovers, track pad 6556 * touches, scroll wheel movements and other input events. The 6557 * {@link MotionEvent#getSource() source} of the motion event specifies 6558 * the class of input that was received. Implementations of this method 6559 * must examine the bits in the source before processing the event. 6560 * The following code example shows how this is done. 6561 * </p><p> 6562 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 6563 * are delivered to the view under the pointer. All other generic motion events are 6564 * delivered to the focused view. 6565 * </p> 6566 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 6567 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 6568 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 6569 * // process the joystick movement... 6570 * return true; 6571 * } 6572 * } 6573 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 6574 * switch (event.getAction()) { 6575 * case MotionEvent.ACTION_HOVER_MOVE: 6576 * // process the mouse hover movement... 6577 * return true; 6578 * case MotionEvent.ACTION_SCROLL: 6579 * // process the scroll wheel movement... 6580 * return true; 6581 * } 6582 * } 6583 * return super.onGenericMotionEvent(event); 6584 * }</pre> 6585 * 6586 * @param event The generic motion event being processed. 6587 * @return True if the event was handled, false otherwise. 6588 */ 6589 public boolean onGenericMotionEvent(MotionEvent event) { 6590 return false; 6591 } 6592 6593 /** 6594 * Implement this method to handle hover events. 6595 * <p> 6596 * This method is called whenever a pointer is hovering into, over, or out of the 6597 * bounds of a view and the view is not currently being touched. 6598 * Hover events are represented as pointer events with action 6599 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 6600 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 6601 * </p> 6602 * <ul> 6603 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 6604 * when the pointer enters the bounds of the view.</li> 6605 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 6606 * when the pointer has already entered the bounds of the view and has moved.</li> 6607 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 6608 * when the pointer has exited the bounds of the view or when the pointer is 6609 * about to go down due to a button click, tap, or similar user action that 6610 * causes the view to be touched.</li> 6611 * </ul> 6612 * <p> 6613 * The view should implement this method to return true to indicate that it is 6614 * handling the hover event, such as by changing its drawable state. 6615 * </p><p> 6616 * The default implementation calls {@link #setHovered} to update the hovered state 6617 * of the view when a hover enter or hover exit event is received, if the view 6618 * is enabled and is clickable. The default implementation also sends hover 6619 * accessibility events. 6620 * </p> 6621 * 6622 * @param event The motion event that describes the hover. 6623 * @return True if the view handled the hover event. 6624 * 6625 * @see #isHovered 6626 * @see #setHovered 6627 * @see #onHoverChanged 6628 */ 6629 public boolean onHoverEvent(MotionEvent event) { 6630 // The root view may receive hover (or touch) events that are outside the bounds of 6631 // the window. This code ensures that we only send accessibility events for 6632 // hovers that are actually within the bounds of the root view. 6633 final int action = event.getAction(); 6634 if (!mSendingHoverAccessibilityEvents) { 6635 if ((action == MotionEvent.ACTION_HOVER_ENTER 6636 || action == MotionEvent.ACTION_HOVER_MOVE) 6637 && !hasHoveredChild() 6638 && pointInView(event.getX(), event.getY())) { 6639 mSendingHoverAccessibilityEvents = true; 6640 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 6641 } 6642 } else { 6643 if (action == MotionEvent.ACTION_HOVER_EXIT 6644 || (action == MotionEvent.ACTION_HOVER_MOVE 6645 && !pointInView(event.getX(), event.getY()))) { 6646 mSendingHoverAccessibilityEvents = false; 6647 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 6648 } 6649 } 6650 6651 if (isHoverable()) { 6652 switch (action) { 6653 case MotionEvent.ACTION_HOVER_ENTER: 6654 setHovered(true); 6655 break; 6656 case MotionEvent.ACTION_HOVER_EXIT: 6657 setHovered(false); 6658 break; 6659 } 6660 6661 // Dispatch the event to onGenericMotionEvent before returning true. 6662 // This is to provide compatibility with existing applications that 6663 // handled HOVER_MOVE events in onGenericMotionEvent and that would 6664 // break because of the new default handling for hoverable views 6665 // in onHoverEvent. 6666 // Note that onGenericMotionEvent will be called by default when 6667 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 6668 dispatchGenericMotionEventInternal(event); 6669 return true; 6670 } 6671 return false; 6672 } 6673 6674 /** 6675 * Returns true if the view should handle {@link #onHoverEvent} 6676 * by calling {@link #setHovered} to change its hovered state. 6677 * 6678 * @return True if the view is hoverable. 6679 */ 6680 private boolean isHoverable() { 6681 final int viewFlags = mViewFlags; 6682 //noinspection SimplifiableIfStatement 6683 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6684 return false; 6685 } 6686 6687 return (viewFlags & CLICKABLE) == CLICKABLE 6688 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6689 } 6690 6691 /** 6692 * Returns true if the view is currently hovered. 6693 * 6694 * @return True if the view is currently hovered. 6695 * 6696 * @see #setHovered 6697 * @see #onHoverChanged 6698 */ 6699 @ViewDebug.ExportedProperty 6700 public boolean isHovered() { 6701 return (mPrivateFlags & HOVERED) != 0; 6702 } 6703 6704 /** 6705 * Sets whether the view is currently hovered. 6706 * <p> 6707 * Calling this method also changes the drawable state of the view. This 6708 * enables the view to react to hover by using different drawable resources 6709 * to change its appearance. 6710 * </p><p> 6711 * The {@link #onHoverChanged} method is called when the hovered state changes. 6712 * </p> 6713 * 6714 * @param hovered True if the view is hovered. 6715 * 6716 * @see #isHovered 6717 * @see #onHoverChanged 6718 */ 6719 public void setHovered(boolean hovered) { 6720 if (hovered) { 6721 if ((mPrivateFlags & HOVERED) == 0) { 6722 mPrivateFlags |= HOVERED; 6723 refreshDrawableState(); 6724 onHoverChanged(true); 6725 } 6726 } else { 6727 if ((mPrivateFlags & HOVERED) != 0) { 6728 mPrivateFlags &= ~HOVERED; 6729 refreshDrawableState(); 6730 onHoverChanged(false); 6731 } 6732 } 6733 } 6734 6735 /** 6736 * Implement this method to handle hover state changes. 6737 * <p> 6738 * This method is called whenever the hover state changes as a result of a 6739 * call to {@link #setHovered}. 6740 * </p> 6741 * 6742 * @param hovered The current hover state, as returned by {@link #isHovered}. 6743 * 6744 * @see #isHovered 6745 * @see #setHovered 6746 */ 6747 public void onHoverChanged(boolean hovered) { 6748 } 6749 6750 /** 6751 * Implement this method to handle touch screen motion events. 6752 * 6753 * @param event The motion event. 6754 * @return True if the event was handled, false otherwise. 6755 */ 6756 public boolean onTouchEvent(MotionEvent event) { 6757 final int viewFlags = mViewFlags; 6758 6759 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6760 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) { 6761 setPressed(false); 6762 } 6763 // A disabled view that is clickable still consumes the touch 6764 // events, it just doesn't respond to them. 6765 return (((viewFlags & CLICKABLE) == CLICKABLE || 6766 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 6767 } 6768 6769 if (mTouchDelegate != null) { 6770 if (mTouchDelegate.onTouchEvent(event)) { 6771 return true; 6772 } 6773 } 6774 6775 if (((viewFlags & CLICKABLE) == CLICKABLE || 6776 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 6777 switch (event.getAction()) { 6778 case MotionEvent.ACTION_UP: 6779 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; 6780 if ((mPrivateFlags & PRESSED) != 0 || prepressed) { 6781 // take focus if we don't have it already and we should in 6782 // touch mode. 6783 boolean focusTaken = false; 6784 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 6785 focusTaken = requestFocus(); 6786 } 6787 6788 if (prepressed) { 6789 // The button is being released before we actually 6790 // showed it as pressed. Make it show the pressed 6791 // state now (before scheduling the click) to ensure 6792 // the user sees it. 6793 setPressed(true); 6794 } 6795 6796 if (!mHasPerformedLongPress) { 6797 // This is a tap, so remove the longpress check 6798 removeLongPressCallback(); 6799 6800 // Only perform take click actions if we were in the pressed state 6801 if (!focusTaken) { 6802 // Use a Runnable and post this rather than calling 6803 // performClick directly. This lets other visual state 6804 // of the view update before click actions start. 6805 if (mPerformClick == null) { 6806 mPerformClick = new PerformClick(); 6807 } 6808 if (!post(mPerformClick)) { 6809 performClick(); 6810 } 6811 } 6812 } 6813 6814 if (mUnsetPressedState == null) { 6815 mUnsetPressedState = new UnsetPressedState(); 6816 } 6817 6818 if (prepressed) { 6819 postDelayed(mUnsetPressedState, 6820 ViewConfiguration.getPressedStateDuration()); 6821 } else if (!post(mUnsetPressedState)) { 6822 // If the post failed, unpress right now 6823 mUnsetPressedState.run(); 6824 } 6825 removeTapCallback(); 6826 } 6827 break; 6828 6829 case MotionEvent.ACTION_DOWN: 6830 mHasPerformedLongPress = false; 6831 6832 if (performButtonActionOnTouchDown(event)) { 6833 break; 6834 } 6835 6836 // Walk up the hierarchy to determine if we're inside a scrolling container. 6837 boolean isInScrollingContainer = isInScrollingContainer(); 6838 6839 // For views inside a scrolling container, delay the pressed feedback for 6840 // a short period in case this is a scroll. 6841 if (isInScrollingContainer) { 6842 mPrivateFlags |= PREPRESSED; 6843 if (mPendingCheckForTap == null) { 6844 mPendingCheckForTap = new CheckForTap(); 6845 } 6846 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 6847 } else { 6848 // Not inside a scrolling container, so show the feedback right away 6849 setPressed(true); 6850 checkForLongClick(0); 6851 } 6852 break; 6853 6854 case MotionEvent.ACTION_CANCEL: 6855 setPressed(false); 6856 removeTapCallback(); 6857 break; 6858 6859 case MotionEvent.ACTION_MOVE: 6860 final int x = (int) event.getX(); 6861 final int y = (int) event.getY(); 6862 6863 // Be lenient about moving outside of buttons 6864 if (!pointInView(x, y, mTouchSlop)) { 6865 // Outside button 6866 removeTapCallback(); 6867 if ((mPrivateFlags & PRESSED) != 0) { 6868 // Remove any future long press/tap checks 6869 removeLongPressCallback(); 6870 6871 setPressed(false); 6872 } 6873 } 6874 break; 6875 } 6876 return true; 6877 } 6878 6879 return false; 6880 } 6881 6882 /** 6883 * @hide 6884 */ 6885 public boolean isInScrollingContainer() { 6886 ViewParent p = getParent(); 6887 while (p != null && p instanceof ViewGroup) { 6888 if (((ViewGroup) p).shouldDelayChildPressedState()) { 6889 return true; 6890 } 6891 p = p.getParent(); 6892 } 6893 return false; 6894 } 6895 6896 /** 6897 * Remove the longpress detection timer. 6898 */ 6899 private void removeLongPressCallback() { 6900 if (mPendingCheckForLongPress != null) { 6901 removeCallbacks(mPendingCheckForLongPress); 6902 } 6903 } 6904 6905 /** 6906 * Remove the pending click action 6907 */ 6908 private void removePerformClickCallback() { 6909 if (mPerformClick != null) { 6910 removeCallbacks(mPerformClick); 6911 } 6912 } 6913 6914 /** 6915 * Remove the prepress detection timer. 6916 */ 6917 private void removeUnsetPressCallback() { 6918 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) { 6919 setPressed(false); 6920 removeCallbacks(mUnsetPressedState); 6921 } 6922 } 6923 6924 /** 6925 * Remove the tap detection timer. 6926 */ 6927 private void removeTapCallback() { 6928 if (mPendingCheckForTap != null) { 6929 mPrivateFlags &= ~PREPRESSED; 6930 removeCallbacks(mPendingCheckForTap); 6931 } 6932 } 6933 6934 /** 6935 * Cancels a pending long press. Your subclass can use this if you 6936 * want the context menu to come up if the user presses and holds 6937 * at the same place, but you don't want it to come up if they press 6938 * and then move around enough to cause scrolling. 6939 */ 6940 public void cancelLongPress() { 6941 removeLongPressCallback(); 6942 6943 /* 6944 * The prepressed state handled by the tap callback is a display 6945 * construct, but the tap callback will post a long press callback 6946 * less its own timeout. Remove it here. 6947 */ 6948 removeTapCallback(); 6949 } 6950 6951 /** 6952 * Remove the pending callback for sending a 6953 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 6954 */ 6955 private void removeSendViewScrolledAccessibilityEventCallback() { 6956 if (mSendViewScrolledAccessibilityEvent != null) { 6957 removeCallbacks(mSendViewScrolledAccessibilityEvent); 6958 } 6959 } 6960 6961 /** 6962 * Sets the TouchDelegate for this View. 6963 */ 6964 public void setTouchDelegate(TouchDelegate delegate) { 6965 mTouchDelegate = delegate; 6966 } 6967 6968 /** 6969 * Gets the TouchDelegate for this View. 6970 */ 6971 public TouchDelegate getTouchDelegate() { 6972 return mTouchDelegate; 6973 } 6974 6975 /** 6976 * Set flags controlling behavior of this view. 6977 * 6978 * @param flags Constant indicating the value which should be set 6979 * @param mask Constant indicating the bit range that should be changed 6980 */ 6981 void setFlags(int flags, int mask) { 6982 int old = mViewFlags; 6983 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 6984 6985 int changed = mViewFlags ^ old; 6986 if (changed == 0) { 6987 return; 6988 } 6989 int privateFlags = mPrivateFlags; 6990 6991 /* Check if the FOCUSABLE bit has changed */ 6992 if (((changed & FOCUSABLE_MASK) != 0) && 6993 ((privateFlags & HAS_BOUNDS) !=0)) { 6994 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 6995 && ((privateFlags & FOCUSED) != 0)) { 6996 /* Give up focus if we are no longer focusable */ 6997 clearFocus(); 6998 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 6999 && ((privateFlags & FOCUSED) == 0)) { 7000 /* 7001 * Tell the view system that we are now available to take focus 7002 * if no one else already has it. 7003 */ 7004 if (mParent != null) mParent.focusableViewAvailable(this); 7005 } 7006 } 7007 7008 if ((flags & VISIBILITY_MASK) == VISIBLE) { 7009 if ((changed & VISIBILITY_MASK) != 0) { 7010 /* 7011 * If this view is becoming visible, invalidate it in case it changed while 7012 * it was not visible. Marking it drawn ensures that the invalidation will 7013 * go through. 7014 */ 7015 mPrivateFlags |= DRAWN; 7016 invalidate(true); 7017 7018 needGlobalAttributesUpdate(true); 7019 7020 // a view becoming visible is worth notifying the parent 7021 // about in case nothing has focus. even if this specific view 7022 // isn't focusable, it may contain something that is, so let 7023 // the root view try to give this focus if nothing else does. 7024 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 7025 mParent.focusableViewAvailable(this); 7026 } 7027 } 7028 } 7029 7030 /* Check if the GONE bit has changed */ 7031 if ((changed & GONE) != 0) { 7032 needGlobalAttributesUpdate(false); 7033 requestLayout(); 7034 7035 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 7036 if (hasFocus()) clearFocus(); 7037 destroyDrawingCache(); 7038 if (mParent instanceof View) { 7039 // GONE views noop invalidation, so invalidate the parent 7040 ((View) mParent).invalidate(true); 7041 } 7042 // Mark the view drawn to ensure that it gets invalidated properly the next 7043 // time it is visible and gets invalidated 7044 mPrivateFlags |= DRAWN; 7045 } 7046 if (mAttachInfo != null) { 7047 mAttachInfo.mViewVisibilityChanged = true; 7048 } 7049 } 7050 7051 /* Check if the VISIBLE bit has changed */ 7052 if ((changed & INVISIBLE) != 0) { 7053 needGlobalAttributesUpdate(false); 7054 /* 7055 * If this view is becoming invisible, set the DRAWN flag so that 7056 * the next invalidate() will not be skipped. 7057 */ 7058 mPrivateFlags |= DRAWN; 7059 7060 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 7061 // root view becoming invisible shouldn't clear focus 7062 if (getRootView() != this) { 7063 clearFocus(); 7064 } 7065 } 7066 if (mAttachInfo != null) { 7067 mAttachInfo.mViewVisibilityChanged = true; 7068 } 7069 } 7070 7071 if ((changed & VISIBILITY_MASK) != 0) { 7072 if (mParent instanceof ViewGroup) { 7073 ((ViewGroup) mParent).onChildVisibilityChanged(this, 7074 (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK)); 7075 ((View) mParent).invalidate(true); 7076 } else if (mParent != null) { 7077 mParent.invalidateChild(this, null); 7078 } 7079 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 7080 } 7081 7082 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 7083 destroyDrawingCache(); 7084 } 7085 7086 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 7087 destroyDrawingCache(); 7088 mPrivateFlags &= ~DRAWING_CACHE_VALID; 7089 invalidateParentCaches(); 7090 } 7091 7092 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 7093 destroyDrawingCache(); 7094 mPrivateFlags &= ~DRAWING_CACHE_VALID; 7095 } 7096 7097 if ((changed & DRAW_MASK) != 0) { 7098 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 7099 if (mBGDrawable != null) { 7100 mPrivateFlags &= ~SKIP_DRAW; 7101 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 7102 } else { 7103 mPrivateFlags |= SKIP_DRAW; 7104 } 7105 } else { 7106 mPrivateFlags &= ~SKIP_DRAW; 7107 } 7108 requestLayout(); 7109 invalidate(true); 7110 } 7111 7112 if ((changed & KEEP_SCREEN_ON) != 0) { 7113 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 7114 mParent.recomputeViewAttributes(this); 7115 } 7116 } 7117 } 7118 7119 /** 7120 * Change the view's z order in the tree, so it's on top of other sibling 7121 * views 7122 */ 7123 public void bringToFront() { 7124 if (mParent != null) { 7125 mParent.bringChildToFront(this); 7126 } 7127 } 7128 7129 /** 7130 * This is called in response to an internal scroll in this view (i.e., the 7131 * view scrolled its own contents). This is typically as a result of 7132 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 7133 * called. 7134 * 7135 * @param l Current horizontal scroll origin. 7136 * @param t Current vertical scroll origin. 7137 * @param oldl Previous horizontal scroll origin. 7138 * @param oldt Previous vertical scroll origin. 7139 */ 7140 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 7141 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 7142 postSendViewScrolledAccessibilityEventCallback(); 7143 } 7144 7145 mBackgroundSizeChanged = true; 7146 7147 final AttachInfo ai = mAttachInfo; 7148 if (ai != null) { 7149 ai.mViewScrollChanged = true; 7150 } 7151 } 7152 7153 /** 7154 * Interface definition for a callback to be invoked when the layout bounds of a view 7155 * changes due to layout processing. 7156 */ 7157 public interface OnLayoutChangeListener { 7158 /** 7159 * Called when the focus state of a view has changed. 7160 * 7161 * @param v The view whose state has changed. 7162 * @param left The new value of the view's left property. 7163 * @param top The new value of the view's top property. 7164 * @param right The new value of the view's right property. 7165 * @param bottom The new value of the view's bottom property. 7166 * @param oldLeft The previous value of the view's left property. 7167 * @param oldTop The previous value of the view's top property. 7168 * @param oldRight The previous value of the view's right property. 7169 * @param oldBottom The previous value of the view's bottom property. 7170 */ 7171 void onLayoutChange(View v, int left, int top, int right, int bottom, 7172 int oldLeft, int oldTop, int oldRight, int oldBottom); 7173 } 7174 7175 /** 7176 * This is called during layout when the size of this view has changed. If 7177 * you were just added to the view hierarchy, you're called with the old 7178 * values of 0. 7179 * 7180 * @param w Current width of this view. 7181 * @param h Current height of this view. 7182 * @param oldw Old width of this view. 7183 * @param oldh Old height of this view. 7184 */ 7185 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 7186 } 7187 7188 /** 7189 * Called by draw to draw the child views. This may be overridden 7190 * by derived classes to gain control just before its children are drawn 7191 * (but after its own view has been drawn). 7192 * @param canvas the canvas on which to draw the view 7193 */ 7194 protected void dispatchDraw(Canvas canvas) { 7195 } 7196 7197 /** 7198 * Gets the parent of this view. Note that the parent is a 7199 * ViewParent and not necessarily a View. 7200 * 7201 * @return Parent of this view. 7202 */ 7203 public final ViewParent getParent() { 7204 return mParent; 7205 } 7206 7207 /** 7208 * Set the horizontal scrolled position of your view. This will cause a call to 7209 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7210 * invalidated. 7211 * @param value the x position to scroll to 7212 */ 7213 public void setScrollX(int value) { 7214 scrollTo(value, mScrollY); 7215 } 7216 7217 /** 7218 * Set the vertical scrolled position of your view. This will cause a call to 7219 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7220 * invalidated. 7221 * @param value the y position to scroll to 7222 */ 7223 public void setScrollY(int value) { 7224 scrollTo(mScrollX, value); 7225 } 7226 7227 /** 7228 * Return the scrolled left position of this view. This is the left edge of 7229 * the displayed part of your view. You do not need to draw any pixels 7230 * farther left, since those are outside of the frame of your view on 7231 * screen. 7232 * 7233 * @return The left edge of the displayed part of your view, in pixels. 7234 */ 7235 public final int getScrollX() { 7236 return mScrollX; 7237 } 7238 7239 /** 7240 * Return the scrolled top position of this view. This is the top edge of 7241 * the displayed part of your view. You do not need to draw any pixels above 7242 * it, since those are outside of the frame of your view on screen. 7243 * 7244 * @return The top edge of the displayed part of your view, in pixels. 7245 */ 7246 public final int getScrollY() { 7247 return mScrollY; 7248 } 7249 7250 /** 7251 * Return the width of the your view. 7252 * 7253 * @return The width of your view, in pixels. 7254 */ 7255 @ViewDebug.ExportedProperty(category = "layout") 7256 public final int getWidth() { 7257 return mRight - mLeft; 7258 } 7259 7260 /** 7261 * Return the height of your view. 7262 * 7263 * @return The height of your view, in pixels. 7264 */ 7265 @ViewDebug.ExportedProperty(category = "layout") 7266 public final int getHeight() { 7267 return mBottom - mTop; 7268 } 7269 7270 /** 7271 * Return the visible drawing bounds of your view. Fills in the output 7272 * rectangle with the values from getScrollX(), getScrollY(), 7273 * getWidth(), and getHeight(). 7274 * 7275 * @param outRect The (scrolled) drawing bounds of the view. 7276 */ 7277 public void getDrawingRect(Rect outRect) { 7278 outRect.left = mScrollX; 7279 outRect.top = mScrollY; 7280 outRect.right = mScrollX + (mRight - mLeft); 7281 outRect.bottom = mScrollY + (mBottom - mTop); 7282 } 7283 7284 /** 7285 * Like {@link #getMeasuredWidthAndState()}, but only returns the 7286 * raw width component (that is the result is masked by 7287 * {@link #MEASURED_SIZE_MASK}). 7288 * 7289 * @return The raw measured width of this view. 7290 */ 7291 public final int getMeasuredWidth() { 7292 return mMeasuredWidth & MEASURED_SIZE_MASK; 7293 } 7294 7295 /** 7296 * Return the full width measurement information for this view as computed 7297 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 7298 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 7299 * This should be used during measurement and layout calculations only. Use 7300 * {@link #getWidth()} to see how wide a view is after layout. 7301 * 7302 * @return The measured width of this view as a bit mask. 7303 */ 7304 public final int getMeasuredWidthAndState() { 7305 return mMeasuredWidth; 7306 } 7307 7308 /** 7309 * Like {@link #getMeasuredHeightAndState()}, but only returns the 7310 * raw width component (that is the result is masked by 7311 * {@link #MEASURED_SIZE_MASK}). 7312 * 7313 * @return The raw measured height of this view. 7314 */ 7315 public final int getMeasuredHeight() { 7316 return mMeasuredHeight & MEASURED_SIZE_MASK; 7317 } 7318 7319 /** 7320 * Return the full height measurement information for this view as computed 7321 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 7322 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 7323 * This should be used during measurement and layout calculations only. Use 7324 * {@link #getHeight()} to see how wide a view is after layout. 7325 * 7326 * @return The measured width of this view as a bit mask. 7327 */ 7328 public final int getMeasuredHeightAndState() { 7329 return mMeasuredHeight; 7330 } 7331 7332 /** 7333 * Return only the state bits of {@link #getMeasuredWidthAndState()} 7334 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 7335 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 7336 * and the height component is at the shifted bits 7337 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 7338 */ 7339 public final int getMeasuredState() { 7340 return (mMeasuredWidth&MEASURED_STATE_MASK) 7341 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 7342 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 7343 } 7344 7345 /** 7346 * The transform matrix of this view, which is calculated based on the current 7347 * roation, scale, and pivot properties. 7348 * 7349 * @see #getRotation() 7350 * @see #getScaleX() 7351 * @see #getScaleY() 7352 * @see #getPivotX() 7353 * @see #getPivotY() 7354 * @return The current transform matrix for the view 7355 */ 7356 public Matrix getMatrix() { 7357 if (mTransformationInfo != null) { 7358 updateMatrix(); 7359 return mTransformationInfo.mMatrix; 7360 } 7361 return Matrix.IDENTITY_MATRIX; 7362 } 7363 7364 /** 7365 * Utility function to determine if the value is far enough away from zero to be 7366 * considered non-zero. 7367 * @param value A floating point value to check for zero-ness 7368 * @return whether the passed-in value is far enough away from zero to be considered non-zero 7369 */ 7370 private static boolean nonzero(float value) { 7371 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 7372 } 7373 7374 /** 7375 * Returns true if the transform matrix is the identity matrix. 7376 * Recomputes the matrix if necessary. 7377 * 7378 * @return True if the transform matrix is the identity matrix, false otherwise. 7379 */ 7380 final boolean hasIdentityMatrix() { 7381 if (mTransformationInfo != null) { 7382 updateMatrix(); 7383 return mTransformationInfo.mMatrixIsIdentity; 7384 } 7385 return true; 7386 } 7387 7388 void ensureTransformationInfo() { 7389 if (mTransformationInfo == null) { 7390 mTransformationInfo = new TransformationInfo(); 7391 } 7392 } 7393 7394 /** 7395 * Recomputes the transform matrix if necessary. 7396 */ 7397 private void updateMatrix() { 7398 final TransformationInfo info = mTransformationInfo; 7399 if (info == null) { 7400 return; 7401 } 7402 if (info.mMatrixDirty) { 7403 // transform-related properties have changed since the last time someone 7404 // asked for the matrix; recalculate it with the current values 7405 7406 // Figure out if we need to update the pivot point 7407 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7408 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 7409 info.mPrevWidth = mRight - mLeft; 7410 info.mPrevHeight = mBottom - mTop; 7411 info.mPivotX = info.mPrevWidth / 2f; 7412 info.mPivotY = info.mPrevHeight / 2f; 7413 } 7414 } 7415 info.mMatrix.reset(); 7416 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 7417 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 7418 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 7419 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 7420 } else { 7421 if (info.mCamera == null) { 7422 info.mCamera = new Camera(); 7423 info.matrix3D = new Matrix(); 7424 } 7425 info.mCamera.save(); 7426 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 7427 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 7428 info.mCamera.getMatrix(info.matrix3D); 7429 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 7430 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 7431 info.mPivotY + info.mTranslationY); 7432 info.mMatrix.postConcat(info.matrix3D); 7433 info.mCamera.restore(); 7434 } 7435 info.mMatrixDirty = false; 7436 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 7437 info.mInverseMatrixDirty = true; 7438 } 7439 } 7440 7441 /** 7442 * Utility method to retrieve the inverse of the current mMatrix property. 7443 * We cache the matrix to avoid recalculating it when transform properties 7444 * have not changed. 7445 * 7446 * @return The inverse of the current matrix of this view. 7447 */ 7448 final Matrix getInverseMatrix() { 7449 final TransformationInfo info = mTransformationInfo; 7450 if (info != null) { 7451 updateMatrix(); 7452 if (info.mInverseMatrixDirty) { 7453 if (info.mInverseMatrix == null) { 7454 info.mInverseMatrix = new Matrix(); 7455 } 7456 info.mMatrix.invert(info.mInverseMatrix); 7457 info.mInverseMatrixDirty = false; 7458 } 7459 return info.mInverseMatrix; 7460 } 7461 return Matrix.IDENTITY_MATRIX; 7462 } 7463 7464 /** 7465 * Gets the distance along the Z axis from the camera to this view. 7466 * 7467 * @see #setCameraDistance(float) 7468 * 7469 * @return The distance along the Z axis. 7470 */ 7471 public float getCameraDistance() { 7472 ensureTransformationInfo(); 7473 final float dpi = mResources.getDisplayMetrics().densityDpi; 7474 final TransformationInfo info = mTransformationInfo; 7475 if (info.mCamera == null) { 7476 info.mCamera = new Camera(); 7477 info.matrix3D = new Matrix(); 7478 } 7479 return -(info.mCamera.getLocationZ() * dpi); 7480 } 7481 7482 /** 7483 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 7484 * views are drawn) from the camera to this view. The camera's distance 7485 * affects 3D transformations, for instance rotations around the X and Y 7486 * axis. If the rotationX or rotationY properties are changed and this view is 7487 * large (more than half the size of the screen), it is recommended to always 7488 * use a camera distance that's greater than the height (X axis rotation) or 7489 * the width (Y axis rotation) of this view.</p> 7490 * 7491 * <p>The distance of the camera from the view plane can have an affect on the 7492 * perspective distortion of the view when it is rotated around the x or y axis. 7493 * For example, a large distance will result in a large viewing angle, and there 7494 * will not be much perspective distortion of the view as it rotates. A short 7495 * distance may cause much more perspective distortion upon rotation, and can 7496 * also result in some drawing artifacts if the rotated view ends up partially 7497 * behind the camera (which is why the recommendation is to use a distance at 7498 * least as far as the size of the view, if the view is to be rotated.)</p> 7499 * 7500 * <p>The distance is expressed in "depth pixels." The default distance depends 7501 * on the screen density. For instance, on a medium density display, the 7502 * default distance is 1280. On a high density display, the default distance 7503 * is 1920.</p> 7504 * 7505 * <p>If you want to specify a distance that leads to visually consistent 7506 * results across various densities, use the following formula:</p> 7507 * <pre> 7508 * float scale = context.getResources().getDisplayMetrics().density; 7509 * view.setCameraDistance(distance * scale); 7510 * </pre> 7511 * 7512 * <p>The density scale factor of a high density display is 1.5, 7513 * and 1920 = 1280 * 1.5.</p> 7514 * 7515 * @param distance The distance in "depth pixels", if negative the opposite 7516 * value is used 7517 * 7518 * @see #setRotationX(float) 7519 * @see #setRotationY(float) 7520 */ 7521 public void setCameraDistance(float distance) { 7522 invalidateViewProperty(true, false); 7523 7524 ensureTransformationInfo(); 7525 final float dpi = mResources.getDisplayMetrics().densityDpi; 7526 final TransformationInfo info = mTransformationInfo; 7527 if (info.mCamera == null) { 7528 info.mCamera = new Camera(); 7529 info.matrix3D = new Matrix(); 7530 } 7531 7532 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 7533 info.mMatrixDirty = true; 7534 7535 invalidateViewProperty(false, false); 7536 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7537 mDisplayList.setCameraDistance(-Math.abs(distance) / dpi); 7538 } 7539 } 7540 7541 /** 7542 * The degrees that the view is rotated around the pivot point. 7543 * 7544 * @see #setRotation(float) 7545 * @see #getPivotX() 7546 * @see #getPivotY() 7547 * 7548 * @return The degrees of rotation. 7549 */ 7550 @ViewDebug.ExportedProperty(category = "drawing") 7551 public float getRotation() { 7552 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 7553 } 7554 7555 /** 7556 * Sets the degrees that the view is rotated around the pivot point. Increasing values 7557 * result in clockwise rotation. 7558 * 7559 * @param rotation The degrees of rotation. 7560 * 7561 * @see #getRotation() 7562 * @see #getPivotX() 7563 * @see #getPivotY() 7564 * @see #setRotationX(float) 7565 * @see #setRotationY(float) 7566 * 7567 * @attr ref android.R.styleable#View_rotation 7568 */ 7569 public void setRotation(float rotation) { 7570 ensureTransformationInfo(); 7571 final TransformationInfo info = mTransformationInfo; 7572 if (info.mRotation != rotation) { 7573 // Double-invalidation is necessary to capture view's old and new areas 7574 invalidateViewProperty(true, false); 7575 info.mRotation = rotation; 7576 info.mMatrixDirty = true; 7577 invalidateViewProperty(false, true); 7578 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7579 mDisplayList.setRotation(rotation); 7580 } 7581 } 7582 } 7583 7584 /** 7585 * The degrees that the view is rotated around the vertical axis through the pivot point. 7586 * 7587 * @see #getPivotX() 7588 * @see #getPivotY() 7589 * @see #setRotationY(float) 7590 * 7591 * @return The degrees of Y rotation. 7592 */ 7593 @ViewDebug.ExportedProperty(category = "drawing") 7594 public float getRotationY() { 7595 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 7596 } 7597 7598 /** 7599 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 7600 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 7601 * down the y axis. 7602 * 7603 * When rotating large views, it is recommended to adjust the camera distance 7604 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 7605 * 7606 * @param rotationY The degrees of Y rotation. 7607 * 7608 * @see #getRotationY() 7609 * @see #getPivotX() 7610 * @see #getPivotY() 7611 * @see #setRotation(float) 7612 * @see #setRotationX(float) 7613 * @see #setCameraDistance(float) 7614 * 7615 * @attr ref android.R.styleable#View_rotationY 7616 */ 7617 public void setRotationY(float rotationY) { 7618 ensureTransformationInfo(); 7619 final TransformationInfo info = mTransformationInfo; 7620 if (info.mRotationY != rotationY) { 7621 invalidateViewProperty(true, false); 7622 info.mRotationY = rotationY; 7623 info.mMatrixDirty = true; 7624 invalidateViewProperty(false, true); 7625 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7626 mDisplayList.setRotationY(rotationY); 7627 } 7628 } 7629 } 7630 7631 /** 7632 * The degrees that the view is rotated around the horizontal axis through the pivot point. 7633 * 7634 * @see #getPivotX() 7635 * @see #getPivotY() 7636 * @see #setRotationX(float) 7637 * 7638 * @return The degrees of X rotation. 7639 */ 7640 @ViewDebug.ExportedProperty(category = "drawing") 7641 public float getRotationX() { 7642 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 7643 } 7644 7645 /** 7646 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 7647 * Increasing values result in clockwise rotation from the viewpoint of looking down the 7648 * x axis. 7649 * 7650 * When rotating large views, it is recommended to adjust the camera distance 7651 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 7652 * 7653 * @param rotationX The degrees of X rotation. 7654 * 7655 * @see #getRotationX() 7656 * @see #getPivotX() 7657 * @see #getPivotY() 7658 * @see #setRotation(float) 7659 * @see #setRotationY(float) 7660 * @see #setCameraDistance(float) 7661 * 7662 * @attr ref android.R.styleable#View_rotationX 7663 */ 7664 public void setRotationX(float rotationX) { 7665 ensureTransformationInfo(); 7666 final TransformationInfo info = mTransformationInfo; 7667 if (info.mRotationX != rotationX) { 7668 invalidateViewProperty(true, false); 7669 info.mRotationX = rotationX; 7670 info.mMatrixDirty = true; 7671 invalidateViewProperty(false, true); 7672 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7673 mDisplayList.setRotationX(rotationX); 7674 } 7675 } 7676 } 7677 7678 /** 7679 * The amount that the view is scaled in x around the pivot point, as a proportion of 7680 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 7681 * 7682 * <p>By default, this is 1.0f. 7683 * 7684 * @see #getPivotX() 7685 * @see #getPivotY() 7686 * @return The scaling factor. 7687 */ 7688 @ViewDebug.ExportedProperty(category = "drawing") 7689 public float getScaleX() { 7690 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 7691 } 7692 7693 /** 7694 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 7695 * the view's unscaled width. A value of 1 means that no scaling is applied. 7696 * 7697 * @param scaleX The scaling factor. 7698 * @see #getPivotX() 7699 * @see #getPivotY() 7700 * 7701 * @attr ref android.R.styleable#View_scaleX 7702 */ 7703 public void setScaleX(float scaleX) { 7704 ensureTransformationInfo(); 7705 final TransformationInfo info = mTransformationInfo; 7706 if (info.mScaleX != scaleX) { 7707 invalidateViewProperty(true, false); 7708 info.mScaleX = scaleX; 7709 info.mMatrixDirty = true; 7710 invalidateViewProperty(false, true); 7711 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7712 mDisplayList.setScaleX(scaleX); 7713 } 7714 } 7715 } 7716 7717 /** 7718 * The amount that the view is scaled in y around the pivot point, as a proportion of 7719 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 7720 * 7721 * <p>By default, this is 1.0f. 7722 * 7723 * @see #getPivotX() 7724 * @see #getPivotY() 7725 * @return The scaling factor. 7726 */ 7727 @ViewDebug.ExportedProperty(category = "drawing") 7728 public float getScaleY() { 7729 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 7730 } 7731 7732 /** 7733 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 7734 * the view's unscaled width. A value of 1 means that no scaling is applied. 7735 * 7736 * @param scaleY The scaling factor. 7737 * @see #getPivotX() 7738 * @see #getPivotY() 7739 * 7740 * @attr ref android.R.styleable#View_scaleY 7741 */ 7742 public void setScaleY(float scaleY) { 7743 ensureTransformationInfo(); 7744 final TransformationInfo info = mTransformationInfo; 7745 if (info.mScaleY != scaleY) { 7746 invalidateViewProperty(true, false); 7747 info.mScaleY = scaleY; 7748 info.mMatrixDirty = true; 7749 invalidateViewProperty(false, true); 7750 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7751 mDisplayList.setScaleY(scaleY); 7752 } 7753 } 7754 } 7755 7756 /** 7757 * The x location of the point around which the view is {@link #setRotation(float) rotated} 7758 * and {@link #setScaleX(float) scaled}. 7759 * 7760 * @see #getRotation() 7761 * @see #getScaleX() 7762 * @see #getScaleY() 7763 * @see #getPivotY() 7764 * @return The x location of the pivot point. 7765 */ 7766 @ViewDebug.ExportedProperty(category = "drawing") 7767 public float getPivotX() { 7768 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 7769 } 7770 7771 /** 7772 * Sets the x location of the point around which the view is 7773 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 7774 * By default, the pivot point is centered on the object. 7775 * Setting this property disables this behavior and causes the view to use only the 7776 * explicitly set pivotX and pivotY values. 7777 * 7778 * @param pivotX The x location of the pivot point. 7779 * @see #getRotation() 7780 * @see #getScaleX() 7781 * @see #getScaleY() 7782 * @see #getPivotY() 7783 * 7784 * @attr ref android.R.styleable#View_transformPivotX 7785 */ 7786 public void setPivotX(float pivotX) { 7787 ensureTransformationInfo(); 7788 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7789 final TransformationInfo info = mTransformationInfo; 7790 if (info.mPivotX != pivotX) { 7791 invalidateViewProperty(true, false); 7792 info.mPivotX = pivotX; 7793 info.mMatrixDirty = true; 7794 invalidateViewProperty(false, true); 7795 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7796 mDisplayList.setPivotX(pivotX); 7797 } 7798 } 7799 } 7800 7801 /** 7802 * The y location of the point around which the view is {@link #setRotation(float) rotated} 7803 * and {@link #setScaleY(float) scaled}. 7804 * 7805 * @see #getRotation() 7806 * @see #getScaleX() 7807 * @see #getScaleY() 7808 * @see #getPivotY() 7809 * @return The y location of the pivot point. 7810 */ 7811 @ViewDebug.ExportedProperty(category = "drawing") 7812 public float getPivotY() { 7813 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 7814 } 7815 7816 /** 7817 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 7818 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 7819 * Setting this property disables this behavior and causes the view to use only the 7820 * explicitly set pivotX and pivotY values. 7821 * 7822 * @param pivotY The y location of the pivot point. 7823 * @see #getRotation() 7824 * @see #getScaleX() 7825 * @see #getScaleY() 7826 * @see #getPivotY() 7827 * 7828 * @attr ref android.R.styleable#View_transformPivotY 7829 */ 7830 public void setPivotY(float pivotY) { 7831 ensureTransformationInfo(); 7832 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7833 final TransformationInfo info = mTransformationInfo; 7834 if (info.mPivotY != pivotY) { 7835 invalidateViewProperty(true, false); 7836 info.mPivotY = pivotY; 7837 info.mMatrixDirty = true; 7838 invalidateViewProperty(false, true); 7839 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7840 mDisplayList.setPivotY(pivotY); 7841 } 7842 } 7843 } 7844 7845 /** 7846 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 7847 * completely transparent and 1 means the view is completely opaque. 7848 * 7849 * <p>By default this is 1.0f. 7850 * @return The opacity of the view. 7851 */ 7852 @ViewDebug.ExportedProperty(category = "drawing") 7853 public float getAlpha() { 7854 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 7855 } 7856 7857 /** 7858 * Returns whether this View has content which overlaps. This function, intended to be 7859 * overridden by specific View types, is an optimization when alpha is set on a view. If 7860 * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer 7861 * and then composited it into place, which can be expensive. If the view has no overlapping 7862 * rendering, the view can draw each primitive with the appropriate alpha value directly. 7863 * An example of overlapping rendering is a TextView with a background image, such as a 7864 * Button. An example of non-overlapping rendering is a TextView with no background, or 7865 * an ImageView with only the foreground image. The default implementation returns true; 7866 * subclasses should override if they have cases which can be optimized. 7867 * 7868 * @return true if the content in this view might overlap, false otherwise. 7869 */ 7870 public boolean hasOverlappingRendering() { 7871 return true; 7872 } 7873 7874 /** 7875 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 7876 * completely transparent and 1 means the view is completely opaque.</p> 7877 * 7878 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 7879 * responsible for applying the opacity itself. Otherwise, calling this method is 7880 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 7881 * setting a hardware layer.</p> 7882 * 7883 * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have 7884 * performance implications. It is generally best to use the alpha property sparingly and 7885 * transiently, as in the case of fading animations.</p> 7886 * 7887 * @param alpha The opacity of the view. 7888 * 7889 * @see #setLayerType(int, android.graphics.Paint) 7890 * 7891 * @attr ref android.R.styleable#View_alpha 7892 */ 7893 public void setAlpha(float alpha) { 7894 ensureTransformationInfo(); 7895 if (mTransformationInfo.mAlpha != alpha) { 7896 mTransformationInfo.mAlpha = alpha; 7897 if (onSetAlpha((int) (alpha * 255))) { 7898 mPrivateFlags |= ALPHA_SET; 7899 // subclass is handling alpha - don't optimize rendering cache invalidation 7900 invalidateParentCaches(); 7901 invalidate(true); 7902 } else { 7903 mPrivateFlags &= ~ALPHA_SET; 7904 invalidateViewProperty(true, false); 7905 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7906 mDisplayList.setAlpha(alpha); 7907 } 7908 } 7909 } 7910 } 7911 7912 /** 7913 * Faster version of setAlpha() which performs the same steps except there are 7914 * no calls to invalidate(). The caller of this function should perform proper invalidation 7915 * on the parent and this object. The return value indicates whether the subclass handles 7916 * alpha (the return value for onSetAlpha()). 7917 * 7918 * @param alpha The new value for the alpha property 7919 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 7920 * the new value for the alpha property is different from the old value 7921 */ 7922 boolean setAlphaNoInvalidation(float alpha) { 7923 ensureTransformationInfo(); 7924 if (mTransformationInfo.mAlpha != alpha) { 7925 mTransformationInfo.mAlpha = alpha; 7926 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 7927 if (subclassHandlesAlpha) { 7928 mPrivateFlags |= ALPHA_SET; 7929 return true; 7930 } else { 7931 mPrivateFlags &= ~ALPHA_SET; 7932 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7933 mDisplayList.setAlpha(alpha); 7934 } 7935 } 7936 } 7937 return false; 7938 } 7939 7940 /** 7941 * Top position of this view relative to its parent. 7942 * 7943 * @return The top of this view, in pixels. 7944 */ 7945 @ViewDebug.CapturedViewProperty 7946 public final int getTop() { 7947 return mTop; 7948 } 7949 7950 /** 7951 * Sets the top position of this view relative to its parent. This method is meant to be called 7952 * by the layout system and should not generally be called otherwise, because the property 7953 * may be changed at any time by the layout. 7954 * 7955 * @param top The top of this view, in pixels. 7956 */ 7957 public final void setTop(int top) { 7958 if (top != mTop) { 7959 updateMatrix(); 7960 final boolean matrixIsIdentity = mTransformationInfo == null 7961 || mTransformationInfo.mMatrixIsIdentity; 7962 if (matrixIsIdentity) { 7963 if (mAttachInfo != null) { 7964 int minTop; 7965 int yLoc; 7966 if (top < mTop) { 7967 minTop = top; 7968 yLoc = top - mTop; 7969 } else { 7970 minTop = mTop; 7971 yLoc = 0; 7972 } 7973 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 7974 } 7975 } else { 7976 // Double-invalidation is necessary to capture view's old and new areas 7977 invalidate(true); 7978 } 7979 7980 int width = mRight - mLeft; 7981 int oldHeight = mBottom - mTop; 7982 7983 mTop = top; 7984 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7985 mDisplayList.setTop(mTop); 7986 } 7987 7988 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7989 7990 if (!matrixIsIdentity) { 7991 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7992 // A change in dimension means an auto-centered pivot point changes, too 7993 mTransformationInfo.mMatrixDirty = true; 7994 } 7995 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7996 invalidate(true); 7997 } 7998 mBackgroundSizeChanged = true; 7999 invalidateParentIfNeeded(); 8000 } 8001 } 8002 8003 /** 8004 * Bottom position of this view relative to its parent. 8005 * 8006 * @return The bottom of this view, in pixels. 8007 */ 8008 @ViewDebug.CapturedViewProperty 8009 public final int getBottom() { 8010 return mBottom; 8011 } 8012 8013 /** 8014 * True if this view has changed since the last time being drawn. 8015 * 8016 * @return The dirty state of this view. 8017 */ 8018 public boolean isDirty() { 8019 return (mPrivateFlags & DIRTY_MASK) != 0; 8020 } 8021 8022 /** 8023 * Sets the bottom position of this view relative to its parent. This method is meant to be 8024 * called by the layout system and should not generally be called otherwise, because the 8025 * property may be changed at any time by the layout. 8026 * 8027 * @param bottom The bottom of this view, in pixels. 8028 */ 8029 public final void setBottom(int bottom) { 8030 if (bottom != mBottom) { 8031 updateMatrix(); 8032 final boolean matrixIsIdentity = mTransformationInfo == null 8033 || mTransformationInfo.mMatrixIsIdentity; 8034 if (matrixIsIdentity) { 8035 if (mAttachInfo != null) { 8036 int maxBottom; 8037 if (bottom < mBottom) { 8038 maxBottom = mBottom; 8039 } else { 8040 maxBottom = bottom; 8041 } 8042 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 8043 } 8044 } else { 8045 // Double-invalidation is necessary to capture view's old and new areas 8046 invalidate(true); 8047 } 8048 8049 int width = mRight - mLeft; 8050 int oldHeight = mBottom - mTop; 8051 8052 mBottom = bottom; 8053 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 8054 mDisplayList.setBottom(mBottom); 8055 } 8056 8057 onSizeChanged(width, mBottom - mTop, width, oldHeight); 8058 8059 if (!matrixIsIdentity) { 8060 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 8061 // A change in dimension means an auto-centered pivot point changes, too 8062 mTransformationInfo.mMatrixDirty = true; 8063 } 8064 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8065 invalidate(true); 8066 } 8067 mBackgroundSizeChanged = true; 8068 invalidateParentIfNeeded(); 8069 } 8070 } 8071 8072 /** 8073 * Left position of this view relative to its parent. 8074 * 8075 * @return The left edge of this view, in pixels. 8076 */ 8077 @ViewDebug.CapturedViewProperty 8078 public final int getLeft() { 8079 return mLeft; 8080 } 8081 8082 /** 8083 * Sets the left position of this view relative to its parent. This method is meant to be called 8084 * by the layout system and should not generally be called otherwise, because the property 8085 * may be changed at any time by the layout. 8086 * 8087 * @param left The bottom of this view, in pixels. 8088 */ 8089 public final void setLeft(int left) { 8090 if (left != mLeft) { 8091 updateMatrix(); 8092 final boolean matrixIsIdentity = mTransformationInfo == null 8093 || mTransformationInfo.mMatrixIsIdentity; 8094 if (matrixIsIdentity) { 8095 if (mAttachInfo != null) { 8096 int minLeft; 8097 int xLoc; 8098 if (left < mLeft) { 8099 minLeft = left; 8100 xLoc = left - mLeft; 8101 } else { 8102 minLeft = mLeft; 8103 xLoc = 0; 8104 } 8105 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 8106 } 8107 } else { 8108 // Double-invalidation is necessary to capture view's old and new areas 8109 invalidate(true); 8110 } 8111 8112 int oldWidth = mRight - mLeft; 8113 int height = mBottom - mTop; 8114 8115 mLeft = left; 8116 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 8117 mDisplayList.setLeft(left); 8118 } 8119 8120 onSizeChanged(mRight - mLeft, height, oldWidth, height); 8121 8122 if (!matrixIsIdentity) { 8123 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 8124 // A change in dimension means an auto-centered pivot point changes, too 8125 mTransformationInfo.mMatrixDirty = true; 8126 } 8127 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8128 invalidate(true); 8129 } 8130 mBackgroundSizeChanged = true; 8131 invalidateParentIfNeeded(); 8132 if (USE_DISPLAY_LIST_PROPERTIES) { 8133 8134 } 8135 } 8136 } 8137 8138 /** 8139 * Right position of this view relative to its parent. 8140 * 8141 * @return The right edge of this view, in pixels. 8142 */ 8143 @ViewDebug.CapturedViewProperty 8144 public final int getRight() { 8145 return mRight; 8146 } 8147 8148 /** 8149 * Sets the right position of this view relative to its parent. This method is meant to be called 8150 * by the layout system and should not generally be called otherwise, because the property 8151 * may be changed at any time by the layout. 8152 * 8153 * @param right The bottom of this view, in pixels. 8154 */ 8155 public final void setRight(int right) { 8156 if (right != mRight) { 8157 updateMatrix(); 8158 final boolean matrixIsIdentity = mTransformationInfo == null 8159 || mTransformationInfo.mMatrixIsIdentity; 8160 if (matrixIsIdentity) { 8161 if (mAttachInfo != null) { 8162 int maxRight; 8163 if (right < mRight) { 8164 maxRight = mRight; 8165 } else { 8166 maxRight = right; 8167 } 8168 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 8169 } 8170 } else { 8171 // Double-invalidation is necessary to capture view's old and new areas 8172 invalidate(true); 8173 } 8174 8175 int oldWidth = mRight - mLeft; 8176 int height = mBottom - mTop; 8177 8178 mRight = right; 8179 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 8180 mDisplayList.setRight(mRight); 8181 } 8182 8183 onSizeChanged(mRight - mLeft, height, oldWidth, height); 8184 8185 if (!matrixIsIdentity) { 8186 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 8187 // A change in dimension means an auto-centered pivot point changes, too 8188 mTransformationInfo.mMatrixDirty = true; 8189 } 8190 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8191 invalidate(true); 8192 } 8193 mBackgroundSizeChanged = true; 8194 invalidateParentIfNeeded(); 8195 } 8196 } 8197 8198 /** 8199 * The visual x position of this view, in pixels. This is equivalent to the 8200 * {@link #setTranslationX(float) translationX} property plus the current 8201 * {@link #getLeft() left} property. 8202 * 8203 * @return The visual x position of this view, in pixels. 8204 */ 8205 @ViewDebug.ExportedProperty(category = "drawing") 8206 public float getX() { 8207 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 8208 } 8209 8210 /** 8211 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 8212 * {@link #setTranslationX(float) translationX} property to be the difference between 8213 * the x value passed in and the current {@link #getLeft() left} property. 8214 * 8215 * @param x The visual x position of this view, in pixels. 8216 */ 8217 public void setX(float x) { 8218 setTranslationX(x - mLeft); 8219 } 8220 8221 /** 8222 * The visual y position of this view, in pixels. This is equivalent to the 8223 * {@link #setTranslationY(float) translationY} property plus the current 8224 * {@link #getTop() top} property. 8225 * 8226 * @return The visual y position of this view, in pixels. 8227 */ 8228 @ViewDebug.ExportedProperty(category = "drawing") 8229 public float getY() { 8230 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 8231 } 8232 8233 /** 8234 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 8235 * {@link #setTranslationY(float) translationY} property to be the difference between 8236 * the y value passed in and the current {@link #getTop() top} property. 8237 * 8238 * @param y The visual y position of this view, in pixels. 8239 */ 8240 public void setY(float y) { 8241 setTranslationY(y - mTop); 8242 } 8243 8244 8245 /** 8246 * The horizontal location of this view relative to its {@link #getLeft() left} position. 8247 * This position is post-layout, in addition to wherever the object's 8248 * layout placed it. 8249 * 8250 * @return The horizontal position of this view relative to its left position, in pixels. 8251 */ 8252 @ViewDebug.ExportedProperty(category = "drawing") 8253 public float getTranslationX() { 8254 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 8255 } 8256 8257 /** 8258 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 8259 * This effectively positions the object post-layout, in addition to wherever the object's 8260 * layout placed it. 8261 * 8262 * @param translationX The horizontal position of this view relative to its left position, 8263 * in pixels. 8264 * 8265 * @attr ref android.R.styleable#View_translationX 8266 */ 8267 public void setTranslationX(float translationX) { 8268 ensureTransformationInfo(); 8269 final TransformationInfo info = mTransformationInfo; 8270 if (info.mTranslationX != translationX) { 8271 // Double-invalidation is necessary to capture view's old and new areas 8272 invalidateViewProperty(true, false); 8273 info.mTranslationX = translationX; 8274 info.mMatrixDirty = true; 8275 invalidateViewProperty(false, true); 8276 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 8277 mDisplayList.setTranslationX(translationX); 8278 } 8279 } 8280 } 8281 8282 /** 8283 * The horizontal location of this view relative to its {@link #getTop() top} position. 8284 * This position is post-layout, in addition to wherever the object's 8285 * layout placed it. 8286 * 8287 * @return The vertical position of this view relative to its top position, 8288 * in pixels. 8289 */ 8290 @ViewDebug.ExportedProperty(category = "drawing") 8291 public float getTranslationY() { 8292 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 8293 } 8294 8295 /** 8296 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 8297 * This effectively positions the object post-layout, in addition to wherever the object's 8298 * layout placed it. 8299 * 8300 * @param translationY The vertical position of this view relative to its top position, 8301 * in pixels. 8302 * 8303 * @attr ref android.R.styleable#View_translationY 8304 */ 8305 public void setTranslationY(float translationY) { 8306 ensureTransformationInfo(); 8307 final TransformationInfo info = mTransformationInfo; 8308 if (info.mTranslationY != translationY) { 8309 invalidateViewProperty(true, false); 8310 info.mTranslationY = translationY; 8311 info.mMatrixDirty = true; 8312 invalidateViewProperty(false, true); 8313 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 8314 mDisplayList.setTranslationY(translationY); 8315 } 8316 } 8317 } 8318 8319 /** 8320 * Hit rectangle in parent's coordinates 8321 * 8322 * @param outRect The hit rectangle of the view. 8323 */ 8324 public void getHitRect(Rect outRect) { 8325 updateMatrix(); 8326 final TransformationInfo info = mTransformationInfo; 8327 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 8328 outRect.set(mLeft, mTop, mRight, mBottom); 8329 } else { 8330 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 8331 tmpRect.set(-info.mPivotX, -info.mPivotY, 8332 getWidth() - info.mPivotX, getHeight() - info.mPivotY); 8333 info.mMatrix.mapRect(tmpRect); 8334 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 8335 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 8336 } 8337 } 8338 8339 /** 8340 * Determines whether the given point, in local coordinates is inside the view. 8341 */ 8342 /*package*/ final boolean pointInView(float localX, float localY) { 8343 return localX >= 0 && localX < (mRight - mLeft) 8344 && localY >= 0 && localY < (mBottom - mTop); 8345 } 8346 8347 /** 8348 * Utility method to determine whether the given point, in local coordinates, 8349 * is inside the view, where the area of the view is expanded by the slop factor. 8350 * This method is called while processing touch-move events to determine if the event 8351 * is still within the view. 8352 */ 8353 private boolean pointInView(float localX, float localY, float slop) { 8354 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 8355 localY < ((mBottom - mTop) + slop); 8356 } 8357 8358 /** 8359 * When a view has focus and the user navigates away from it, the next view is searched for 8360 * starting from the rectangle filled in by this method. 8361 * 8362 * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)}) 8363 * of the view. However, if your view maintains some idea of internal selection, 8364 * such as a cursor, or a selected row or column, you should override this method and 8365 * fill in a more specific rectangle. 8366 * 8367 * @param r The rectangle to fill in, in this view's coordinates. 8368 */ 8369 public void getFocusedRect(Rect r) { 8370 getDrawingRect(r); 8371 } 8372 8373 /** 8374 * If some part of this view is not clipped by any of its parents, then 8375 * return that area in r in global (root) coordinates. To convert r to local 8376 * coordinates (without taking possible View rotations into account), offset 8377 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 8378 * If the view is completely clipped or translated out, return false. 8379 * 8380 * @param r If true is returned, r holds the global coordinates of the 8381 * visible portion of this view. 8382 * @param globalOffset If true is returned, globalOffset holds the dx,dy 8383 * between this view and its root. globalOffet may be null. 8384 * @return true if r is non-empty (i.e. part of the view is visible at the 8385 * root level. 8386 */ 8387 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 8388 int width = mRight - mLeft; 8389 int height = mBottom - mTop; 8390 if (width > 0 && height > 0) { 8391 r.set(0, 0, width, height); 8392 if (globalOffset != null) { 8393 globalOffset.set(-mScrollX, -mScrollY); 8394 } 8395 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 8396 } 8397 return false; 8398 } 8399 8400 public final boolean getGlobalVisibleRect(Rect r) { 8401 return getGlobalVisibleRect(r, null); 8402 } 8403 8404 public final boolean getLocalVisibleRect(Rect r) { 8405 Point offset = new Point(); 8406 if (getGlobalVisibleRect(r, offset)) { 8407 r.offset(-offset.x, -offset.y); // make r local 8408 return true; 8409 } 8410 return false; 8411 } 8412 8413 /** 8414 * Offset this view's vertical location by the specified number of pixels. 8415 * 8416 * @param offset the number of pixels to offset the view by 8417 */ 8418 public void offsetTopAndBottom(int offset) { 8419 if (offset != 0) { 8420 updateMatrix(); 8421 final boolean matrixIsIdentity = mTransformationInfo == null 8422 || mTransformationInfo.mMatrixIsIdentity; 8423 if (matrixIsIdentity) { 8424 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 8425 invalidateViewProperty(false, false); 8426 } else { 8427 final ViewParent p = mParent; 8428 if (p != null && mAttachInfo != null) { 8429 final Rect r = mAttachInfo.mTmpInvalRect; 8430 int minTop; 8431 int maxBottom; 8432 int yLoc; 8433 if (offset < 0) { 8434 minTop = mTop + offset; 8435 maxBottom = mBottom; 8436 yLoc = offset; 8437 } else { 8438 minTop = mTop; 8439 maxBottom = mBottom + offset; 8440 yLoc = 0; 8441 } 8442 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 8443 p.invalidateChild(this, r); 8444 } 8445 } 8446 } else { 8447 invalidateViewProperty(false, false); 8448 } 8449 8450 mTop += offset; 8451 mBottom += offset; 8452 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 8453 mDisplayList.offsetTopBottom(offset); 8454 invalidateViewProperty(false, false); 8455 } else { 8456 if (!matrixIsIdentity) { 8457 invalidateViewProperty(false, true); 8458 } 8459 invalidateParentIfNeeded(); 8460 } 8461 } 8462 } 8463 8464 /** 8465 * Offset this view's horizontal location by the specified amount of pixels. 8466 * 8467 * @param offset the numer of pixels to offset the view by 8468 */ 8469 public void offsetLeftAndRight(int offset) { 8470 if (offset != 0) { 8471 updateMatrix(); 8472 final boolean matrixIsIdentity = mTransformationInfo == null 8473 || mTransformationInfo.mMatrixIsIdentity; 8474 if (matrixIsIdentity) { 8475 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 8476 invalidateViewProperty(false, false); 8477 } else { 8478 final ViewParent p = mParent; 8479 if (p != null && mAttachInfo != null) { 8480 final Rect r = mAttachInfo.mTmpInvalRect; 8481 int minLeft; 8482 int maxRight; 8483 if (offset < 0) { 8484 minLeft = mLeft + offset; 8485 maxRight = mRight; 8486 } else { 8487 minLeft = mLeft; 8488 maxRight = mRight + offset; 8489 } 8490 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 8491 p.invalidateChild(this, r); 8492 } 8493 } 8494 } else { 8495 invalidateViewProperty(false, false); 8496 } 8497 8498 mLeft += offset; 8499 mRight += offset; 8500 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 8501 mDisplayList.offsetLeftRight(offset); 8502 invalidateViewProperty(false, false); 8503 } else { 8504 if (!matrixIsIdentity) { 8505 invalidateViewProperty(false, true); 8506 } 8507 invalidateParentIfNeeded(); 8508 } 8509 } 8510 } 8511 8512 /** 8513 * Get the LayoutParams associated with this view. All views should have 8514 * layout parameters. These supply parameters to the <i>parent</i> of this 8515 * view specifying how it should be arranged. There are many subclasses of 8516 * ViewGroup.LayoutParams, and these correspond to the different subclasses 8517 * of ViewGroup that are responsible for arranging their children. 8518 * 8519 * This method may return null if this View is not attached to a parent 8520 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 8521 * was not invoked successfully. When a View is attached to a parent 8522 * ViewGroup, this method must not return null. 8523 * 8524 * @return The LayoutParams associated with this view, or null if no 8525 * parameters have been set yet 8526 */ 8527 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 8528 public ViewGroup.LayoutParams getLayoutParams() { 8529 return mLayoutParams; 8530 } 8531 8532 /** 8533 * Set the layout parameters associated with this view. These supply 8534 * parameters to the <i>parent</i> of this view specifying how it should be 8535 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 8536 * correspond to the different subclasses of ViewGroup that are responsible 8537 * for arranging their children. 8538 * 8539 * @param params The layout parameters for this view, cannot be null 8540 */ 8541 public void setLayoutParams(ViewGroup.LayoutParams params) { 8542 if (params == null) { 8543 throw new NullPointerException("Layout parameters cannot be null"); 8544 } 8545 mLayoutParams = params; 8546 if (mParent instanceof ViewGroup) { 8547 ((ViewGroup) mParent).onSetLayoutParams(this, params); 8548 } 8549 requestLayout(); 8550 } 8551 8552 /** 8553 * Set the scrolled position of your view. This will cause a call to 8554 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8555 * invalidated. 8556 * @param x the x position to scroll to 8557 * @param y the y position to scroll to 8558 */ 8559 public void scrollTo(int x, int y) { 8560 if (mScrollX != x || mScrollY != y) { 8561 int oldX = mScrollX; 8562 int oldY = mScrollY; 8563 mScrollX = x; 8564 mScrollY = y; 8565 invalidateParentCaches(); 8566 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 8567 if (!awakenScrollBars()) { 8568 invalidate(true); 8569 } 8570 } 8571 } 8572 8573 /** 8574 * Move the scrolled position of your view. This will cause a call to 8575 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8576 * invalidated. 8577 * @param x the amount of pixels to scroll by horizontally 8578 * @param y the amount of pixels to scroll by vertically 8579 */ 8580 public void scrollBy(int x, int y) { 8581 scrollTo(mScrollX + x, mScrollY + y); 8582 } 8583 8584 /** 8585 * <p>Trigger the scrollbars to draw. When invoked this method starts an 8586 * animation to fade the scrollbars out after a default delay. If a subclass 8587 * provides animated scrolling, the start delay should equal the duration 8588 * of the scrolling animation.</p> 8589 * 8590 * <p>The animation starts only if at least one of the scrollbars is 8591 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 8592 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8593 * this method returns true, and false otherwise. If the animation is 8594 * started, this method calls {@link #invalidate()}; in that case the 8595 * caller should not call {@link #invalidate()}.</p> 8596 * 8597 * <p>This method should be invoked every time a subclass directly updates 8598 * the scroll parameters.</p> 8599 * 8600 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 8601 * and {@link #scrollTo(int, int)}.</p> 8602 * 8603 * @return true if the animation is played, false otherwise 8604 * 8605 * @see #awakenScrollBars(int) 8606 * @see #scrollBy(int, int) 8607 * @see #scrollTo(int, int) 8608 * @see #isHorizontalScrollBarEnabled() 8609 * @see #isVerticalScrollBarEnabled() 8610 * @see #setHorizontalScrollBarEnabled(boolean) 8611 * @see #setVerticalScrollBarEnabled(boolean) 8612 */ 8613 protected boolean awakenScrollBars() { 8614 return mScrollCache != null && 8615 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 8616 } 8617 8618 /** 8619 * Trigger the scrollbars to draw. 8620 * This method differs from awakenScrollBars() only in its default duration. 8621 * initialAwakenScrollBars() will show the scroll bars for longer than 8622 * usual to give the user more of a chance to notice them. 8623 * 8624 * @return true if the animation is played, false otherwise. 8625 */ 8626 private boolean initialAwakenScrollBars() { 8627 return mScrollCache != null && 8628 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 8629 } 8630 8631 /** 8632 * <p> 8633 * Trigger the scrollbars to draw. When invoked this method starts an 8634 * animation to fade the scrollbars out after a fixed delay. If a subclass 8635 * provides animated scrolling, the start delay should equal the duration of 8636 * the scrolling animation. 8637 * </p> 8638 * 8639 * <p> 8640 * The animation starts only if at least one of the scrollbars is enabled, 8641 * as specified by {@link #isHorizontalScrollBarEnabled()} and 8642 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8643 * this method returns true, and false otherwise. If the animation is 8644 * started, this method calls {@link #invalidate()}; in that case the caller 8645 * should not call {@link #invalidate()}. 8646 * </p> 8647 * 8648 * <p> 8649 * This method should be invoked everytime a subclass directly updates the 8650 * scroll parameters. 8651 * </p> 8652 * 8653 * @param startDelay the delay, in milliseconds, after which the animation 8654 * should start; when the delay is 0, the animation starts 8655 * immediately 8656 * @return true if the animation is played, false otherwise 8657 * 8658 * @see #scrollBy(int, int) 8659 * @see #scrollTo(int, int) 8660 * @see #isHorizontalScrollBarEnabled() 8661 * @see #isVerticalScrollBarEnabled() 8662 * @see #setHorizontalScrollBarEnabled(boolean) 8663 * @see #setVerticalScrollBarEnabled(boolean) 8664 */ 8665 protected boolean awakenScrollBars(int startDelay) { 8666 return awakenScrollBars(startDelay, true); 8667 } 8668 8669 /** 8670 * <p> 8671 * Trigger the scrollbars to draw. When invoked this method starts an 8672 * animation to fade the scrollbars out after a fixed delay. If a subclass 8673 * provides animated scrolling, the start delay should equal the duration of 8674 * the scrolling animation. 8675 * </p> 8676 * 8677 * <p> 8678 * The animation starts only if at least one of the scrollbars is enabled, 8679 * as specified by {@link #isHorizontalScrollBarEnabled()} and 8680 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8681 * this method returns true, and false otherwise. If the animation is 8682 * started, this method calls {@link #invalidate()} if the invalidate parameter 8683 * is set to true; in that case the caller 8684 * should not call {@link #invalidate()}. 8685 * </p> 8686 * 8687 * <p> 8688 * This method should be invoked everytime a subclass directly updates the 8689 * scroll parameters. 8690 * </p> 8691 * 8692 * @param startDelay the delay, in milliseconds, after which the animation 8693 * should start; when the delay is 0, the animation starts 8694 * immediately 8695 * 8696 * @param invalidate Wheter this method should call invalidate 8697 * 8698 * @return true if the animation is played, false otherwise 8699 * 8700 * @see #scrollBy(int, int) 8701 * @see #scrollTo(int, int) 8702 * @see #isHorizontalScrollBarEnabled() 8703 * @see #isVerticalScrollBarEnabled() 8704 * @see #setHorizontalScrollBarEnabled(boolean) 8705 * @see #setVerticalScrollBarEnabled(boolean) 8706 */ 8707 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 8708 final ScrollabilityCache scrollCache = mScrollCache; 8709 8710 if (scrollCache == null || !scrollCache.fadeScrollBars) { 8711 return false; 8712 } 8713 8714 if (scrollCache.scrollBar == null) { 8715 scrollCache.scrollBar = new ScrollBarDrawable(); 8716 } 8717 8718 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 8719 8720 if (invalidate) { 8721 // Invalidate to show the scrollbars 8722 invalidate(true); 8723 } 8724 8725 if (scrollCache.state == ScrollabilityCache.OFF) { 8726 // FIXME: this is copied from WindowManagerService. 8727 // We should get this value from the system when it 8728 // is possible to do so. 8729 final int KEY_REPEAT_FIRST_DELAY = 750; 8730 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 8731 } 8732 8733 // Tell mScrollCache when we should start fading. This may 8734 // extend the fade start time if one was already scheduled 8735 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 8736 scrollCache.fadeStartTime = fadeStartTime; 8737 scrollCache.state = ScrollabilityCache.ON; 8738 8739 // Schedule our fader to run, unscheduling any old ones first 8740 if (mAttachInfo != null) { 8741 mAttachInfo.mHandler.removeCallbacks(scrollCache); 8742 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 8743 } 8744 8745 return true; 8746 } 8747 8748 return false; 8749 } 8750 8751 /** 8752 * Do not invalidate views which are not visible and which are not running an animation. They 8753 * will not get drawn and they should not set dirty flags as if they will be drawn 8754 */ 8755 private boolean skipInvalidate() { 8756 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 8757 (!(mParent instanceof ViewGroup) || 8758 !((ViewGroup) mParent).isViewTransitioning(this)); 8759 } 8760 /** 8761 * Mark the area defined by dirty as needing to be drawn. If the view is 8762 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 8763 * in the future. This must be called from a UI thread. To call from a non-UI 8764 * thread, call {@link #postInvalidate()}. 8765 * 8766 * WARNING: This method is destructive to dirty. 8767 * @param dirty the rectangle representing the bounds of the dirty region 8768 */ 8769 public void invalidate(Rect dirty) { 8770 if (ViewDebug.TRACE_HIERARCHY) { 8771 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8772 } 8773 8774 if (skipInvalidate()) { 8775 return; 8776 } 8777 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8778 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8779 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8780 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8781 mPrivateFlags |= INVALIDATED; 8782 mPrivateFlags |= DIRTY; 8783 final ViewParent p = mParent; 8784 final AttachInfo ai = mAttachInfo; 8785 //noinspection PointlessBooleanExpression,ConstantConditions 8786 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8787 if (p != null && ai != null && ai.mHardwareAccelerated) { 8788 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8789 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8790 p.invalidateChild(this, null); 8791 return; 8792 } 8793 } 8794 if (p != null && ai != null) { 8795 final int scrollX = mScrollX; 8796 final int scrollY = mScrollY; 8797 final Rect r = ai.mTmpInvalRect; 8798 r.set(dirty.left - scrollX, dirty.top - scrollY, 8799 dirty.right - scrollX, dirty.bottom - scrollY); 8800 mParent.invalidateChild(this, r); 8801 } 8802 } 8803 } 8804 8805 /** 8806 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 8807 * The coordinates of the dirty rect are relative to the view. 8808 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 8809 * will be called at some point in the future. This must be called from 8810 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 8811 * @param l the left position of the dirty region 8812 * @param t the top position of the dirty region 8813 * @param r the right position of the dirty region 8814 * @param b the bottom position of the dirty region 8815 */ 8816 public void invalidate(int l, int t, int r, int b) { 8817 if (ViewDebug.TRACE_HIERARCHY) { 8818 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8819 } 8820 8821 if (skipInvalidate()) { 8822 return; 8823 } 8824 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8825 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8826 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8827 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8828 mPrivateFlags |= INVALIDATED; 8829 mPrivateFlags |= DIRTY; 8830 final ViewParent p = mParent; 8831 final AttachInfo ai = mAttachInfo; 8832 //noinspection PointlessBooleanExpression,ConstantConditions 8833 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8834 if (p != null && ai != null && ai.mHardwareAccelerated) { 8835 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8836 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8837 p.invalidateChild(this, null); 8838 return; 8839 } 8840 } 8841 if (p != null && ai != null && l < r && t < b) { 8842 final int scrollX = mScrollX; 8843 final int scrollY = mScrollY; 8844 final Rect tmpr = ai.mTmpInvalRect; 8845 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 8846 p.invalidateChild(this, tmpr); 8847 } 8848 } 8849 } 8850 8851 /** 8852 * Invalidate the whole view. If the view is visible, 8853 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 8854 * the future. This must be called from a UI thread. To call from a non-UI thread, 8855 * call {@link #postInvalidate()}. 8856 */ 8857 public void invalidate() { 8858 invalidate(true); 8859 } 8860 8861 /** 8862 * This is where the invalidate() work actually happens. A full invalidate() 8863 * causes the drawing cache to be invalidated, but this function can be called with 8864 * invalidateCache set to false to skip that invalidation step for cases that do not 8865 * need it (for example, a component that remains at the same dimensions with the same 8866 * content). 8867 * 8868 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 8869 * well. This is usually true for a full invalidate, but may be set to false if the 8870 * View's contents or dimensions have not changed. 8871 */ 8872 void invalidate(boolean invalidateCache) { 8873 if (ViewDebug.TRACE_HIERARCHY) { 8874 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8875 } 8876 8877 if (skipInvalidate()) { 8878 return; 8879 } 8880 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8881 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) || 8882 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) { 8883 mLastIsOpaque = isOpaque(); 8884 mPrivateFlags &= ~DRAWN; 8885 mPrivateFlags |= DIRTY; 8886 if (invalidateCache) { 8887 mPrivateFlags |= INVALIDATED; 8888 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8889 } 8890 final AttachInfo ai = mAttachInfo; 8891 final ViewParent p = mParent; 8892 //noinspection PointlessBooleanExpression,ConstantConditions 8893 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8894 if (p != null && ai != null && ai.mHardwareAccelerated) { 8895 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8896 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8897 p.invalidateChild(this, null); 8898 return; 8899 } 8900 } 8901 8902 if (p != null && ai != null) { 8903 final Rect r = ai.mTmpInvalRect; 8904 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8905 // Don't call invalidate -- we don't want to internally scroll 8906 // our own bounds 8907 p.invalidateChild(this, r); 8908 } 8909 } 8910 } 8911 8912 /** 8913 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 8914 * set any flags or handle all of the cases handled by the default invalidation methods. 8915 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 8916 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 8917 * walk up the hierarchy, transforming the dirty rect as necessary. 8918 * 8919 * The method also handles normal invalidation logic if display list properties are not 8920 * being used in this view. The invalidateParent and forceRedraw flags are used by that 8921 * backup approach, to handle these cases used in the various property-setting methods. 8922 * 8923 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 8924 * are not being used in this view 8925 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 8926 * list properties are not being used in this view 8927 */ 8928 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 8929 if (!USE_DISPLAY_LIST_PROPERTIES || mDisplayList == null || 8930 (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) { 8931 if (invalidateParent) { 8932 invalidateParentCaches(); 8933 } 8934 if (forceRedraw) { 8935 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8936 } 8937 invalidate(false); 8938 } else { 8939 final AttachInfo ai = mAttachInfo; 8940 final ViewParent p = mParent; 8941 if (p != null && ai != null) { 8942 final Rect r = ai.mTmpInvalRect; 8943 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8944 if (mParent instanceof ViewGroup) { 8945 ((ViewGroup) mParent).invalidateChildFast(this, r); 8946 } else { 8947 mParent.invalidateChild(this, r); 8948 } 8949 } 8950 } 8951 } 8952 8953 /** 8954 * Utility method to transform a given Rect by the current matrix of this view. 8955 */ 8956 void transformRect(final Rect rect) { 8957 if (!getMatrix().isIdentity()) { 8958 RectF boundingRect = mAttachInfo.mTmpTransformRect; 8959 boundingRect.set(rect); 8960 getMatrix().mapRect(boundingRect); 8961 rect.set((int) (boundingRect.left - 0.5f), 8962 (int) (boundingRect.top - 0.5f), 8963 (int) (boundingRect.right + 0.5f), 8964 (int) (boundingRect.bottom + 0.5f)); 8965 } 8966 } 8967 8968 /** 8969 * Used to indicate that the parent of this view should clear its caches. This functionality 8970 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8971 * which is necessary when various parent-managed properties of the view change, such as 8972 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 8973 * clears the parent caches and does not causes an invalidate event. 8974 * 8975 * @hide 8976 */ 8977 protected void invalidateParentCaches() { 8978 if (mParent instanceof View) { 8979 ((View) mParent).mPrivateFlags |= INVALIDATED; 8980 } 8981 } 8982 8983 /** 8984 * Used to indicate that the parent of this view should be invalidated. This functionality 8985 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8986 * which is necessary when various parent-managed properties of the view change, such as 8987 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 8988 * an invalidation event to the parent. 8989 * 8990 * @hide 8991 */ 8992 protected void invalidateParentIfNeeded() { 8993 if (isHardwareAccelerated() && mParent instanceof View) { 8994 ((View) mParent).invalidate(true); 8995 } 8996 } 8997 8998 /** 8999 * Indicates whether this View is opaque. An opaque View guarantees that it will 9000 * draw all the pixels overlapping its bounds using a fully opaque color. 9001 * 9002 * Subclasses of View should override this method whenever possible to indicate 9003 * whether an instance is opaque. Opaque Views are treated in a special way by 9004 * the View hierarchy, possibly allowing it to perform optimizations during 9005 * invalidate/draw passes. 9006 * 9007 * @return True if this View is guaranteed to be fully opaque, false otherwise. 9008 */ 9009 @ViewDebug.ExportedProperty(category = "drawing") 9010 public boolean isOpaque() { 9011 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK && 9012 ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1) 9013 >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD); 9014 } 9015 9016 /** 9017 * @hide 9018 */ 9019 protected void computeOpaqueFlags() { 9020 // Opaque if: 9021 // - Has a background 9022 // - Background is opaque 9023 // - Doesn't have scrollbars or scrollbars are inside overlay 9024 9025 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) { 9026 mPrivateFlags |= OPAQUE_BACKGROUND; 9027 } else { 9028 mPrivateFlags &= ~OPAQUE_BACKGROUND; 9029 } 9030 9031 final int flags = mViewFlags; 9032 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 9033 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 9034 mPrivateFlags |= OPAQUE_SCROLLBARS; 9035 } else { 9036 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 9037 } 9038 } 9039 9040 /** 9041 * @hide 9042 */ 9043 protected boolean hasOpaqueScrollbars() { 9044 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 9045 } 9046 9047 /** 9048 * @return A handler associated with the thread running the View. This 9049 * handler can be used to pump events in the UI events queue. 9050 */ 9051 public Handler getHandler() { 9052 if (mAttachInfo != null) { 9053 return mAttachInfo.mHandler; 9054 } 9055 return null; 9056 } 9057 9058 /** 9059 * Gets the view root associated with the View. 9060 * @return The view root, or null if none. 9061 * @hide 9062 */ 9063 public ViewRootImpl getViewRootImpl() { 9064 if (mAttachInfo != null) { 9065 return mAttachInfo.mViewRootImpl; 9066 } 9067 return null; 9068 } 9069 9070 /** 9071 * <p>Causes the Runnable to be added to the message queue. 9072 * The runnable will be run on the user interface thread.</p> 9073 * 9074 * <p>This method can be invoked from outside of the UI thread 9075 * only when this View is attached to a window.</p> 9076 * 9077 * @param action The Runnable that will be executed. 9078 * 9079 * @return Returns true if the Runnable was successfully placed in to the 9080 * message queue. Returns false on failure, usually because the 9081 * looper processing the message queue is exiting. 9082 */ 9083 public boolean post(Runnable action) { 9084 final AttachInfo attachInfo = mAttachInfo; 9085 if (attachInfo != null) { 9086 return attachInfo.mHandler.post(action); 9087 } 9088 // Assume that post will succeed later 9089 ViewRootImpl.getRunQueue().post(action); 9090 return true; 9091 } 9092 9093 /** 9094 * <p>Causes the Runnable to be added to the message queue, to be run 9095 * after the specified amount of time elapses. 9096 * The runnable will be run on the user interface thread.</p> 9097 * 9098 * <p>This method can be invoked from outside of the UI thread 9099 * only when this View is attached to a window.</p> 9100 * 9101 * @param action The Runnable that will be executed. 9102 * @param delayMillis The delay (in milliseconds) until the Runnable 9103 * will be executed. 9104 * 9105 * @return true if the Runnable was successfully placed in to the 9106 * message queue. Returns false on failure, usually because the 9107 * looper processing the message queue is exiting. Note that a 9108 * result of true does not mean the Runnable will be processed -- 9109 * if the looper is quit before the delivery time of the message 9110 * occurs then the message will be dropped. 9111 */ 9112 public boolean postDelayed(Runnable action, long delayMillis) { 9113 final AttachInfo attachInfo = mAttachInfo; 9114 if (attachInfo != null) { 9115 return attachInfo.mHandler.postDelayed(action, delayMillis); 9116 } 9117 // Assume that post will succeed later 9118 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 9119 return true; 9120 } 9121 9122 /** 9123 * <p>Causes the Runnable to execute on the next animation time step. 9124 * The runnable will be run on the user interface thread.</p> 9125 * 9126 * <p>This method can be invoked from outside of the UI thread 9127 * only when this View is attached to a window.</p> 9128 * 9129 * @param action The Runnable that will be executed. 9130 * 9131 * @hide 9132 */ 9133 public void postOnAnimation(Runnable action) { 9134 final AttachInfo attachInfo = mAttachInfo; 9135 if (attachInfo != null) { 9136 attachInfo.mViewRootImpl.mChoreographer.postCallback( 9137 Choreographer.CALLBACK_ANIMATION, action, null); 9138 } else { 9139 // Assume that post will succeed later 9140 ViewRootImpl.getRunQueue().post(action); 9141 } 9142 } 9143 9144 /** 9145 * <p>Causes the Runnable to execute on the next animation time step, 9146 * after the specified amount of time elapses. 9147 * The runnable will be run on the user interface thread.</p> 9148 * 9149 * <p>This method can be invoked from outside of the UI thread 9150 * only when this View is attached to a window.</p> 9151 * 9152 * @param action The Runnable that will be executed. 9153 * @param delayMillis The delay (in milliseconds) until the Runnable 9154 * will be executed. 9155 * 9156 * @hide 9157 */ 9158 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 9159 final AttachInfo attachInfo = mAttachInfo; 9160 if (attachInfo != null) { 9161 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 9162 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 9163 } else { 9164 // Assume that post will succeed later 9165 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 9166 } 9167 } 9168 9169 /** 9170 * <p>Removes the specified Runnable from the message queue.</p> 9171 * 9172 * <p>This method can be invoked from outside of the UI thread 9173 * only when this View is attached to a window.</p> 9174 * 9175 * @param action The Runnable to remove from the message handling queue 9176 * 9177 * @return true if this view could ask the Handler to remove the Runnable, 9178 * false otherwise. When the returned value is true, the Runnable 9179 * may or may not have been actually removed from the message queue 9180 * (for instance, if the Runnable was not in the queue already.) 9181 */ 9182 public boolean removeCallbacks(Runnable action) { 9183 if (action != null) { 9184 final AttachInfo attachInfo = mAttachInfo; 9185 if (attachInfo != null) { 9186 attachInfo.mHandler.removeCallbacks(action); 9187 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 9188 Choreographer.CALLBACK_ANIMATION, action, null); 9189 } else { 9190 // Assume that post will succeed later 9191 ViewRootImpl.getRunQueue().removeCallbacks(action); 9192 } 9193 } 9194 return true; 9195 } 9196 9197 /** 9198 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 9199 * Use this to invalidate the View from a non-UI thread.</p> 9200 * 9201 * <p>This method can be invoked from outside of the UI thread 9202 * only when this View is attached to a window.</p> 9203 * 9204 * @see #invalidate() 9205 */ 9206 public void postInvalidate() { 9207 postInvalidateDelayed(0); 9208 } 9209 9210 /** 9211 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 9212 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 9213 * 9214 * <p>This method can be invoked from outside of the UI thread 9215 * only when this View is attached to a window.</p> 9216 * 9217 * @param left The left coordinate of the rectangle to invalidate. 9218 * @param top The top coordinate of the rectangle to invalidate. 9219 * @param right The right coordinate of the rectangle to invalidate. 9220 * @param bottom The bottom coordinate of the rectangle to invalidate. 9221 * 9222 * @see #invalidate(int, int, int, int) 9223 * @see #invalidate(Rect) 9224 */ 9225 public void postInvalidate(int left, int top, int right, int bottom) { 9226 postInvalidateDelayed(0, left, top, right, bottom); 9227 } 9228 9229 /** 9230 * <p>Cause an invalidate to happen on a subsequent cycle through the event 9231 * loop. Waits for the specified amount of time.</p> 9232 * 9233 * <p>This method can be invoked from outside of the UI thread 9234 * only when this View is attached to a window.</p> 9235 * 9236 * @param delayMilliseconds the duration in milliseconds to delay the 9237 * invalidation by 9238 */ 9239 public void postInvalidateDelayed(long delayMilliseconds) { 9240 // We try only with the AttachInfo because there's no point in invalidating 9241 // if we are not attached to our window 9242 final AttachInfo attachInfo = mAttachInfo; 9243 if (attachInfo != null) { 9244 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 9245 } 9246 } 9247 9248 /** 9249 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 9250 * through the event loop. Waits for the specified amount of time.</p> 9251 * 9252 * <p>This method can be invoked from outside of the UI thread 9253 * only when this View is attached to a window.</p> 9254 * 9255 * @param delayMilliseconds the duration in milliseconds to delay the 9256 * invalidation by 9257 * @param left The left coordinate of the rectangle to invalidate. 9258 * @param top The top coordinate of the rectangle to invalidate. 9259 * @param right The right coordinate of the rectangle to invalidate. 9260 * @param bottom The bottom coordinate of the rectangle to invalidate. 9261 */ 9262 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 9263 int right, int bottom) { 9264 9265 // We try only with the AttachInfo because there's no point in invalidating 9266 // if we are not attached to our window 9267 final AttachInfo attachInfo = mAttachInfo; 9268 if (attachInfo != null) { 9269 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 9270 info.target = this; 9271 info.left = left; 9272 info.top = top; 9273 info.right = right; 9274 info.bottom = bottom; 9275 9276 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 9277 } 9278 } 9279 9280 /** 9281 * <p>Cause an invalidate to happen on the next animation time step, typically the 9282 * next display frame.</p> 9283 * 9284 * <p>This method can be invoked from outside of the UI thread 9285 * only when this View is attached to a window.</p> 9286 * 9287 * @hide 9288 */ 9289 public void postInvalidateOnAnimation() { 9290 // We try only with the AttachInfo because there's no point in invalidating 9291 // if we are not attached to our window 9292 final AttachInfo attachInfo = mAttachInfo; 9293 if (attachInfo != null) { 9294 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 9295 } 9296 } 9297 9298 /** 9299 * <p>Cause an invalidate of the specified area to happen on the next animation 9300 * time step, typically the next display frame.</p> 9301 * 9302 * <p>This method can be invoked from outside of the UI thread 9303 * only when this View is attached to a window.</p> 9304 * 9305 * @param left The left coordinate of the rectangle to invalidate. 9306 * @param top The top coordinate of the rectangle to invalidate. 9307 * @param right The right coordinate of the rectangle to invalidate. 9308 * @param bottom The bottom coordinate of the rectangle to invalidate. 9309 * 9310 * @hide 9311 */ 9312 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 9313 // We try only with the AttachInfo because there's no point in invalidating 9314 // if we are not attached to our window 9315 final AttachInfo attachInfo = mAttachInfo; 9316 if (attachInfo != null) { 9317 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 9318 info.target = this; 9319 info.left = left; 9320 info.top = top; 9321 info.right = right; 9322 info.bottom = bottom; 9323 9324 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 9325 } 9326 } 9327 9328 /** 9329 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 9330 * This event is sent at most once every 9331 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 9332 */ 9333 private void postSendViewScrolledAccessibilityEventCallback() { 9334 if (mSendViewScrolledAccessibilityEvent == null) { 9335 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 9336 } 9337 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 9338 mSendViewScrolledAccessibilityEvent.mIsPending = true; 9339 postDelayed(mSendViewScrolledAccessibilityEvent, 9340 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 9341 } 9342 } 9343 9344 /** 9345 * Called by a parent to request that a child update its values for mScrollX 9346 * and mScrollY if necessary. This will typically be done if the child is 9347 * animating a scroll using a {@link android.widget.Scroller Scroller} 9348 * object. 9349 */ 9350 public void computeScroll() { 9351 } 9352 9353 /** 9354 * <p>Indicate whether the horizontal edges are faded when the view is 9355 * scrolled horizontally.</p> 9356 * 9357 * @return true if the horizontal edges should are faded on scroll, false 9358 * otherwise 9359 * 9360 * @see #setHorizontalFadingEdgeEnabled(boolean) 9361 * @attr ref android.R.styleable#View_requiresFadingEdge 9362 */ 9363 public boolean isHorizontalFadingEdgeEnabled() { 9364 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 9365 } 9366 9367 /** 9368 * <p>Define whether the horizontal edges should be faded when this view 9369 * is scrolled horizontally.</p> 9370 * 9371 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 9372 * be faded when the view is scrolled 9373 * horizontally 9374 * 9375 * @see #isHorizontalFadingEdgeEnabled() 9376 * @attr ref android.R.styleable#View_requiresFadingEdge 9377 */ 9378 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 9379 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 9380 if (horizontalFadingEdgeEnabled) { 9381 initScrollCache(); 9382 } 9383 9384 mViewFlags ^= FADING_EDGE_HORIZONTAL; 9385 } 9386 } 9387 9388 /** 9389 * <p>Indicate whether the vertical edges are faded when the view is 9390 * scrolled horizontally.</p> 9391 * 9392 * @return true if the vertical edges should are faded on scroll, false 9393 * otherwise 9394 * 9395 * @see #setVerticalFadingEdgeEnabled(boolean) 9396 * @attr ref android.R.styleable#View_requiresFadingEdge 9397 */ 9398 public boolean isVerticalFadingEdgeEnabled() { 9399 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 9400 } 9401 9402 /** 9403 * <p>Define whether the vertical edges should be faded when this view 9404 * is scrolled vertically.</p> 9405 * 9406 * @param verticalFadingEdgeEnabled true if the vertical edges should 9407 * be faded when the view is scrolled 9408 * vertically 9409 * 9410 * @see #isVerticalFadingEdgeEnabled() 9411 * @attr ref android.R.styleable#View_requiresFadingEdge 9412 */ 9413 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 9414 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 9415 if (verticalFadingEdgeEnabled) { 9416 initScrollCache(); 9417 } 9418 9419 mViewFlags ^= FADING_EDGE_VERTICAL; 9420 } 9421 } 9422 9423 /** 9424 * Returns the strength, or intensity, of the top faded edge. The strength is 9425 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 9426 * returns 0.0 or 1.0 but no value in between. 9427 * 9428 * Subclasses should override this method to provide a smoother fade transition 9429 * when scrolling occurs. 9430 * 9431 * @return the intensity of the top fade as a float between 0.0f and 1.0f 9432 */ 9433 protected float getTopFadingEdgeStrength() { 9434 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 9435 } 9436 9437 /** 9438 * Returns the strength, or intensity, of the bottom faded edge. The strength is 9439 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 9440 * returns 0.0 or 1.0 but no value in between. 9441 * 9442 * Subclasses should override this method to provide a smoother fade transition 9443 * when scrolling occurs. 9444 * 9445 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 9446 */ 9447 protected float getBottomFadingEdgeStrength() { 9448 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 9449 computeVerticalScrollRange() ? 1.0f : 0.0f; 9450 } 9451 9452 /** 9453 * Returns the strength, or intensity, of the left faded edge. The strength is 9454 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 9455 * returns 0.0 or 1.0 but no value in between. 9456 * 9457 * Subclasses should override this method to provide a smoother fade transition 9458 * when scrolling occurs. 9459 * 9460 * @return the intensity of the left fade as a float between 0.0f and 1.0f 9461 */ 9462 protected float getLeftFadingEdgeStrength() { 9463 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 9464 } 9465 9466 /** 9467 * Returns the strength, or intensity, of the right faded edge. The strength is 9468 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 9469 * returns 0.0 or 1.0 but no value in between. 9470 * 9471 * Subclasses should override this method to provide a smoother fade transition 9472 * when scrolling occurs. 9473 * 9474 * @return the intensity of the right fade as a float between 0.0f and 1.0f 9475 */ 9476 protected float getRightFadingEdgeStrength() { 9477 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 9478 computeHorizontalScrollRange() ? 1.0f : 0.0f; 9479 } 9480 9481 /** 9482 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 9483 * scrollbar is not drawn by default.</p> 9484 * 9485 * @return true if the horizontal scrollbar should be painted, false 9486 * otherwise 9487 * 9488 * @see #setHorizontalScrollBarEnabled(boolean) 9489 */ 9490 public boolean isHorizontalScrollBarEnabled() { 9491 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 9492 } 9493 9494 /** 9495 * <p>Define whether the horizontal scrollbar should be drawn or not. The 9496 * scrollbar is not drawn by default.</p> 9497 * 9498 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 9499 * be painted 9500 * 9501 * @see #isHorizontalScrollBarEnabled() 9502 */ 9503 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 9504 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 9505 mViewFlags ^= SCROLLBARS_HORIZONTAL; 9506 computeOpaqueFlags(); 9507 resolvePadding(); 9508 } 9509 } 9510 9511 /** 9512 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 9513 * scrollbar is not drawn by default.</p> 9514 * 9515 * @return true if the vertical scrollbar should be painted, false 9516 * otherwise 9517 * 9518 * @see #setVerticalScrollBarEnabled(boolean) 9519 */ 9520 public boolean isVerticalScrollBarEnabled() { 9521 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 9522 } 9523 9524 /** 9525 * <p>Define whether the vertical scrollbar should be drawn or not. The 9526 * scrollbar is not drawn by default.</p> 9527 * 9528 * @param verticalScrollBarEnabled true if the vertical scrollbar should 9529 * be painted 9530 * 9531 * @see #isVerticalScrollBarEnabled() 9532 */ 9533 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 9534 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 9535 mViewFlags ^= SCROLLBARS_VERTICAL; 9536 computeOpaqueFlags(); 9537 resolvePadding(); 9538 } 9539 } 9540 9541 /** 9542 * @hide 9543 */ 9544 protected void recomputePadding() { 9545 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 9546 } 9547 9548 /** 9549 * Define whether scrollbars will fade when the view is not scrolling. 9550 * 9551 * @param fadeScrollbars wheter to enable fading 9552 * 9553 */ 9554 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 9555 initScrollCache(); 9556 final ScrollabilityCache scrollabilityCache = mScrollCache; 9557 scrollabilityCache.fadeScrollBars = fadeScrollbars; 9558 if (fadeScrollbars) { 9559 scrollabilityCache.state = ScrollabilityCache.OFF; 9560 } else { 9561 scrollabilityCache.state = ScrollabilityCache.ON; 9562 } 9563 } 9564 9565 /** 9566 * 9567 * Returns true if scrollbars will fade when this view is not scrolling 9568 * 9569 * @return true if scrollbar fading is enabled 9570 */ 9571 public boolean isScrollbarFadingEnabled() { 9572 return mScrollCache != null && mScrollCache.fadeScrollBars; 9573 } 9574 9575 /** 9576 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 9577 * inset. When inset, they add to the padding of the view. And the scrollbars 9578 * can be drawn inside the padding area or on the edge of the view. For example, 9579 * if a view has a background drawable and you want to draw the scrollbars 9580 * inside the padding specified by the drawable, you can use 9581 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 9582 * appear at the edge of the view, ignoring the padding, then you can use 9583 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 9584 * @param style the style of the scrollbars. Should be one of 9585 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 9586 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 9587 * @see #SCROLLBARS_INSIDE_OVERLAY 9588 * @see #SCROLLBARS_INSIDE_INSET 9589 * @see #SCROLLBARS_OUTSIDE_OVERLAY 9590 * @see #SCROLLBARS_OUTSIDE_INSET 9591 */ 9592 public void setScrollBarStyle(int style) { 9593 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 9594 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 9595 computeOpaqueFlags(); 9596 resolvePadding(); 9597 } 9598 } 9599 9600 /** 9601 * <p>Returns the current scrollbar style.</p> 9602 * @return the current scrollbar style 9603 * @see #SCROLLBARS_INSIDE_OVERLAY 9604 * @see #SCROLLBARS_INSIDE_INSET 9605 * @see #SCROLLBARS_OUTSIDE_OVERLAY 9606 * @see #SCROLLBARS_OUTSIDE_INSET 9607 */ 9608 @ViewDebug.ExportedProperty(mapping = { 9609 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 9610 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 9611 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 9612 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 9613 }) 9614 public int getScrollBarStyle() { 9615 return mViewFlags & SCROLLBARS_STYLE_MASK; 9616 } 9617 9618 /** 9619 * <p>Compute the horizontal range that the horizontal scrollbar 9620 * represents.</p> 9621 * 9622 * <p>The range is expressed in arbitrary units that must be the same as the 9623 * units used by {@link #computeHorizontalScrollExtent()} and 9624 * {@link #computeHorizontalScrollOffset()}.</p> 9625 * 9626 * <p>The default range is the drawing width of this view.</p> 9627 * 9628 * @return the total horizontal range represented by the horizontal 9629 * scrollbar 9630 * 9631 * @see #computeHorizontalScrollExtent() 9632 * @see #computeHorizontalScrollOffset() 9633 * @see android.widget.ScrollBarDrawable 9634 */ 9635 protected int computeHorizontalScrollRange() { 9636 return getWidth(); 9637 } 9638 9639 /** 9640 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 9641 * within the horizontal range. This value is used to compute the position 9642 * of the thumb within the scrollbar's track.</p> 9643 * 9644 * <p>The range is expressed in arbitrary units that must be the same as the 9645 * units used by {@link #computeHorizontalScrollRange()} and 9646 * {@link #computeHorizontalScrollExtent()}.</p> 9647 * 9648 * <p>The default offset is the scroll offset of this view.</p> 9649 * 9650 * @return the horizontal offset of the scrollbar's thumb 9651 * 9652 * @see #computeHorizontalScrollRange() 9653 * @see #computeHorizontalScrollExtent() 9654 * @see android.widget.ScrollBarDrawable 9655 */ 9656 protected int computeHorizontalScrollOffset() { 9657 return mScrollX; 9658 } 9659 9660 /** 9661 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 9662 * within the horizontal range. This value is used to compute the length 9663 * of the thumb within the scrollbar's track.</p> 9664 * 9665 * <p>The range is expressed in arbitrary units that must be the same as the 9666 * units used by {@link #computeHorizontalScrollRange()} and 9667 * {@link #computeHorizontalScrollOffset()}.</p> 9668 * 9669 * <p>The default extent is the drawing width of this view.</p> 9670 * 9671 * @return the horizontal extent of the scrollbar's thumb 9672 * 9673 * @see #computeHorizontalScrollRange() 9674 * @see #computeHorizontalScrollOffset() 9675 * @see android.widget.ScrollBarDrawable 9676 */ 9677 protected int computeHorizontalScrollExtent() { 9678 return getWidth(); 9679 } 9680 9681 /** 9682 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 9683 * 9684 * <p>The range is expressed in arbitrary units that must be the same as the 9685 * units used by {@link #computeVerticalScrollExtent()} and 9686 * {@link #computeVerticalScrollOffset()}.</p> 9687 * 9688 * @return the total vertical range represented by the vertical scrollbar 9689 * 9690 * <p>The default range is the drawing height of this view.</p> 9691 * 9692 * @see #computeVerticalScrollExtent() 9693 * @see #computeVerticalScrollOffset() 9694 * @see android.widget.ScrollBarDrawable 9695 */ 9696 protected int computeVerticalScrollRange() { 9697 return getHeight(); 9698 } 9699 9700 /** 9701 * <p>Compute the vertical offset of the vertical scrollbar's thumb 9702 * within the horizontal range. This value is used to compute the position 9703 * of the thumb within the scrollbar's track.</p> 9704 * 9705 * <p>The range is expressed in arbitrary units that must be the same as the 9706 * units used by {@link #computeVerticalScrollRange()} and 9707 * {@link #computeVerticalScrollExtent()}.</p> 9708 * 9709 * <p>The default offset is the scroll offset of this view.</p> 9710 * 9711 * @return the vertical offset of the scrollbar's thumb 9712 * 9713 * @see #computeVerticalScrollRange() 9714 * @see #computeVerticalScrollExtent() 9715 * @see android.widget.ScrollBarDrawable 9716 */ 9717 protected int computeVerticalScrollOffset() { 9718 return mScrollY; 9719 } 9720 9721 /** 9722 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 9723 * within the vertical range. This value is used to compute the length 9724 * of the thumb within the scrollbar's track.</p> 9725 * 9726 * <p>The range is expressed in arbitrary units that must be the same as the 9727 * units used by {@link #computeVerticalScrollRange()} and 9728 * {@link #computeVerticalScrollOffset()}.</p> 9729 * 9730 * <p>The default extent is the drawing height of this view.</p> 9731 * 9732 * @return the vertical extent of the scrollbar's thumb 9733 * 9734 * @see #computeVerticalScrollRange() 9735 * @see #computeVerticalScrollOffset() 9736 * @see android.widget.ScrollBarDrawable 9737 */ 9738 protected int computeVerticalScrollExtent() { 9739 return getHeight(); 9740 } 9741 9742 /** 9743 * Check if this view can be scrolled horizontally in a certain direction. 9744 * 9745 * @param direction Negative to check scrolling left, positive to check scrolling right. 9746 * @return true if this view can be scrolled in the specified direction, false otherwise. 9747 */ 9748 public boolean canScrollHorizontally(int direction) { 9749 final int offset = computeHorizontalScrollOffset(); 9750 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 9751 if (range == 0) return false; 9752 if (direction < 0) { 9753 return offset > 0; 9754 } else { 9755 return offset < range - 1; 9756 } 9757 } 9758 9759 /** 9760 * Check if this view can be scrolled vertically in a certain direction. 9761 * 9762 * @param direction Negative to check scrolling up, positive to check scrolling down. 9763 * @return true if this view can be scrolled in the specified direction, false otherwise. 9764 */ 9765 public boolean canScrollVertically(int direction) { 9766 final int offset = computeVerticalScrollOffset(); 9767 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 9768 if (range == 0) return false; 9769 if (direction < 0) { 9770 return offset > 0; 9771 } else { 9772 return offset < range - 1; 9773 } 9774 } 9775 9776 /** 9777 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 9778 * scrollbars are painted only if they have been awakened first.</p> 9779 * 9780 * @param canvas the canvas on which to draw the scrollbars 9781 * 9782 * @see #awakenScrollBars(int) 9783 */ 9784 protected final void onDrawScrollBars(Canvas canvas) { 9785 // scrollbars are drawn only when the animation is running 9786 final ScrollabilityCache cache = mScrollCache; 9787 if (cache != null) { 9788 9789 int state = cache.state; 9790 9791 if (state == ScrollabilityCache.OFF) { 9792 return; 9793 } 9794 9795 boolean invalidate = false; 9796 9797 if (state == ScrollabilityCache.FADING) { 9798 // We're fading -- get our fade interpolation 9799 if (cache.interpolatorValues == null) { 9800 cache.interpolatorValues = new float[1]; 9801 } 9802 9803 float[] values = cache.interpolatorValues; 9804 9805 // Stops the animation if we're done 9806 if (cache.scrollBarInterpolator.timeToValues(values) == 9807 Interpolator.Result.FREEZE_END) { 9808 cache.state = ScrollabilityCache.OFF; 9809 } else { 9810 cache.scrollBar.setAlpha(Math.round(values[0])); 9811 } 9812 9813 // This will make the scroll bars inval themselves after 9814 // drawing. We only want this when we're fading so that 9815 // we prevent excessive redraws 9816 invalidate = true; 9817 } else { 9818 // We're just on -- but we may have been fading before so 9819 // reset alpha 9820 cache.scrollBar.setAlpha(255); 9821 } 9822 9823 9824 final int viewFlags = mViewFlags; 9825 9826 final boolean drawHorizontalScrollBar = 9827 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 9828 final boolean drawVerticalScrollBar = 9829 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 9830 && !isVerticalScrollBarHidden(); 9831 9832 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 9833 final int width = mRight - mLeft; 9834 final int height = mBottom - mTop; 9835 9836 final ScrollBarDrawable scrollBar = cache.scrollBar; 9837 9838 final int scrollX = mScrollX; 9839 final int scrollY = mScrollY; 9840 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 9841 9842 int left, top, right, bottom; 9843 9844 if (drawHorizontalScrollBar) { 9845 int size = scrollBar.getSize(false); 9846 if (size <= 0) { 9847 size = cache.scrollBarSize; 9848 } 9849 9850 scrollBar.setParameters(computeHorizontalScrollRange(), 9851 computeHorizontalScrollOffset(), 9852 computeHorizontalScrollExtent(), false); 9853 final int verticalScrollBarGap = drawVerticalScrollBar ? 9854 getVerticalScrollbarWidth() : 0; 9855 top = scrollY + height - size - (mUserPaddingBottom & inside); 9856 left = scrollX + (mPaddingLeft & inside); 9857 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 9858 bottom = top + size; 9859 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 9860 if (invalidate) { 9861 invalidate(left, top, right, bottom); 9862 } 9863 } 9864 9865 if (drawVerticalScrollBar) { 9866 int size = scrollBar.getSize(true); 9867 if (size <= 0) { 9868 size = cache.scrollBarSize; 9869 } 9870 9871 scrollBar.setParameters(computeVerticalScrollRange(), 9872 computeVerticalScrollOffset(), 9873 computeVerticalScrollExtent(), true); 9874 switch (mVerticalScrollbarPosition) { 9875 default: 9876 case SCROLLBAR_POSITION_DEFAULT: 9877 case SCROLLBAR_POSITION_RIGHT: 9878 left = scrollX + width - size - (mUserPaddingRight & inside); 9879 break; 9880 case SCROLLBAR_POSITION_LEFT: 9881 left = scrollX + (mUserPaddingLeft & inside); 9882 break; 9883 } 9884 top = scrollY + (mPaddingTop & inside); 9885 right = left + size; 9886 bottom = scrollY + height - (mUserPaddingBottom & inside); 9887 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 9888 if (invalidate) { 9889 invalidate(left, top, right, bottom); 9890 } 9891 } 9892 } 9893 } 9894 } 9895 9896 /** 9897 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 9898 * FastScroller is visible. 9899 * @return whether to temporarily hide the vertical scrollbar 9900 * @hide 9901 */ 9902 protected boolean isVerticalScrollBarHidden() { 9903 return false; 9904 } 9905 9906 /** 9907 * <p>Draw the horizontal scrollbar if 9908 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 9909 * 9910 * @param canvas the canvas on which to draw the scrollbar 9911 * @param scrollBar the scrollbar's drawable 9912 * 9913 * @see #isHorizontalScrollBarEnabled() 9914 * @see #computeHorizontalScrollRange() 9915 * @see #computeHorizontalScrollExtent() 9916 * @see #computeHorizontalScrollOffset() 9917 * @see android.widget.ScrollBarDrawable 9918 * @hide 9919 */ 9920 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 9921 int l, int t, int r, int b) { 9922 scrollBar.setBounds(l, t, r, b); 9923 scrollBar.draw(canvas); 9924 } 9925 9926 /** 9927 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 9928 * returns true.</p> 9929 * 9930 * @param canvas the canvas on which to draw the scrollbar 9931 * @param scrollBar the scrollbar's drawable 9932 * 9933 * @see #isVerticalScrollBarEnabled() 9934 * @see #computeVerticalScrollRange() 9935 * @see #computeVerticalScrollExtent() 9936 * @see #computeVerticalScrollOffset() 9937 * @see android.widget.ScrollBarDrawable 9938 * @hide 9939 */ 9940 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 9941 int l, int t, int r, int b) { 9942 scrollBar.setBounds(l, t, r, b); 9943 scrollBar.draw(canvas); 9944 } 9945 9946 /** 9947 * Implement this to do your drawing. 9948 * 9949 * @param canvas the canvas on which the background will be drawn 9950 */ 9951 protected void onDraw(Canvas canvas) { 9952 } 9953 9954 /* 9955 * Caller is responsible for calling requestLayout if necessary. 9956 * (This allows addViewInLayout to not request a new layout.) 9957 */ 9958 void assignParent(ViewParent parent) { 9959 if (mParent == null) { 9960 mParent = parent; 9961 } else if (parent == null) { 9962 mParent = null; 9963 } else { 9964 throw new RuntimeException("view " + this + " being added, but" 9965 + " it already has a parent"); 9966 } 9967 } 9968 9969 /** 9970 * This is called when the view is attached to a window. At this point it 9971 * has a Surface and will start drawing. Note that this function is 9972 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 9973 * however it may be called any time before the first onDraw -- including 9974 * before or after {@link #onMeasure(int, int)}. 9975 * 9976 * @see #onDetachedFromWindow() 9977 */ 9978 protected void onAttachedToWindow() { 9979 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 9980 mParent.requestTransparentRegion(this); 9981 } 9982 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 9983 initialAwakenScrollBars(); 9984 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH; 9985 } 9986 jumpDrawablesToCurrentState(); 9987 // Order is important here: LayoutDirection MUST be resolved before Padding 9988 // and TextDirection 9989 resolveLayoutDirection(); 9990 resolvePadding(); 9991 resolveTextDirection(); 9992 if (isFocused()) { 9993 InputMethodManager imm = InputMethodManager.peekInstance(); 9994 imm.focusIn(this); 9995 } 9996 } 9997 9998 /** 9999 * @see #onScreenStateChanged(int) 10000 */ 10001 void dispatchScreenStateChanged(int screenState) { 10002 onScreenStateChanged(screenState); 10003 } 10004 10005 /** 10006 * This method is called whenever the state of the screen this view is 10007 * attached to changes. A state change will usually occurs when the screen 10008 * turns on or off (whether it happens automatically or the user does it 10009 * manually.) 10010 * 10011 * @param screenState The new state of the screen. Can be either 10012 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 10013 */ 10014 public void onScreenStateChanged(int screenState) { 10015 } 10016 10017 /** 10018 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 10019 * that the parent directionality can and will be resolved before its children. 10020 * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done. 10021 */ 10022 public void resolveLayoutDirection() { 10023 // Clear any previous layout direction resolution 10024 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK; 10025 10026 // Set resolved depending on layout direction 10027 switch (getLayoutDirection()) { 10028 case LAYOUT_DIRECTION_INHERIT: 10029 // If this is root view, no need to look at parent's layout dir. 10030 if (canResolveLayoutDirection()) { 10031 ViewGroup viewGroup = ((ViewGroup) mParent); 10032 10033 if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 10034 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 10035 } 10036 } else { 10037 // Nothing to do, LTR by default 10038 } 10039 break; 10040 case LAYOUT_DIRECTION_RTL: 10041 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 10042 break; 10043 case LAYOUT_DIRECTION_LOCALE: 10044 if(isLayoutDirectionRtl(Locale.getDefault())) { 10045 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 10046 } 10047 break; 10048 default: 10049 // Nothing to do, LTR by default 10050 } 10051 10052 // Set to resolved 10053 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED; 10054 onResolvedLayoutDirectionChanged(); 10055 // Resolve padding 10056 resolvePadding(); 10057 } 10058 10059 /** 10060 * Called when layout direction has been resolved. 10061 * 10062 * The default implementation does nothing. 10063 */ 10064 public void onResolvedLayoutDirectionChanged() { 10065 } 10066 10067 /** 10068 * Resolve padding depending on layout direction. 10069 */ 10070 public void resolvePadding() { 10071 // If the user specified the absolute padding (either with android:padding or 10072 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 10073 // use the default padding or the padding from the background drawable 10074 // (stored at this point in mPadding*) 10075 int resolvedLayoutDirection = getResolvedLayoutDirection(); 10076 switch (resolvedLayoutDirection) { 10077 case LAYOUT_DIRECTION_RTL: 10078 // Start user padding override Right user padding. Otherwise, if Right user 10079 // padding is not defined, use the default Right padding. If Right user padding 10080 // is defined, just use it. 10081 if (mUserPaddingStart >= 0) { 10082 mUserPaddingRight = mUserPaddingStart; 10083 } else if (mUserPaddingRight < 0) { 10084 mUserPaddingRight = mPaddingRight; 10085 } 10086 if (mUserPaddingEnd >= 0) { 10087 mUserPaddingLeft = mUserPaddingEnd; 10088 } else if (mUserPaddingLeft < 0) { 10089 mUserPaddingLeft = mPaddingLeft; 10090 } 10091 break; 10092 case LAYOUT_DIRECTION_LTR: 10093 default: 10094 // Start user padding override Left user padding. Otherwise, if Left user 10095 // padding is not defined, use the default left padding. If Left user padding 10096 // is defined, just use it. 10097 if (mUserPaddingStart >= 0) { 10098 mUserPaddingLeft = mUserPaddingStart; 10099 } else if (mUserPaddingLeft < 0) { 10100 mUserPaddingLeft = mPaddingLeft; 10101 } 10102 if (mUserPaddingEnd >= 0) { 10103 mUserPaddingRight = mUserPaddingEnd; 10104 } else if (mUserPaddingRight < 0) { 10105 mUserPaddingRight = mPaddingRight; 10106 } 10107 } 10108 10109 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 10110 10111 if(isPaddingRelative()) { 10112 setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom); 10113 } else { 10114 recomputePadding(); 10115 } 10116 onPaddingChanged(resolvedLayoutDirection); 10117 } 10118 10119 /** 10120 * Resolve padding depending on the layout direction. Subclasses that care about 10121 * padding resolution should override this method. The default implementation does 10122 * nothing. 10123 * 10124 * @param layoutDirection the direction of the layout 10125 * 10126 * @see {@link #LAYOUT_DIRECTION_LTR} 10127 * @see {@link #LAYOUT_DIRECTION_RTL} 10128 */ 10129 public void onPaddingChanged(int layoutDirection) { 10130 } 10131 10132 /** 10133 * Check if layout direction resolution can be done. 10134 * 10135 * @return true if layout direction resolution can be done otherwise return false. 10136 */ 10137 public boolean canResolveLayoutDirection() { 10138 switch (getLayoutDirection()) { 10139 case LAYOUT_DIRECTION_INHERIT: 10140 return (mParent != null) && (mParent instanceof ViewGroup); 10141 default: 10142 return true; 10143 } 10144 } 10145 10146 /** 10147 * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset} 10148 * when reset is done. 10149 */ 10150 public void resetResolvedLayoutDirection() { 10151 // Reset the current resolved bits 10152 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK; 10153 onResolvedLayoutDirectionReset(); 10154 // Reset also the text direction 10155 resetResolvedTextDirection(); 10156 } 10157 10158 /** 10159 * Called during reset of resolved layout direction. 10160 * 10161 * Subclasses need to override this method to clear cached information that depends on the 10162 * resolved layout direction, or to inform child views that inherit their layout direction. 10163 * 10164 * The default implementation does nothing. 10165 */ 10166 public void onResolvedLayoutDirectionReset() { 10167 } 10168 10169 /** 10170 * Check if a Locale uses an RTL script. 10171 * 10172 * @param locale Locale to check 10173 * @return true if the Locale uses an RTL script. 10174 */ 10175 protected static boolean isLayoutDirectionRtl(Locale locale) { 10176 return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale)); 10177 } 10178 10179 /** 10180 * This is called when the view is detached from a window. At this point it 10181 * no longer has a surface for drawing. 10182 * 10183 * @see #onAttachedToWindow() 10184 */ 10185 protected void onDetachedFromWindow() { 10186 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 10187 10188 removeUnsetPressCallback(); 10189 removeLongPressCallback(); 10190 removePerformClickCallback(); 10191 removeSendViewScrolledAccessibilityEventCallback(); 10192 10193 destroyDrawingCache(); 10194 10195 destroyLayer(false); 10196 10197 if (mAttachInfo != null) { 10198 if (mDisplayList != null) { 10199 mAttachInfo.mViewRootImpl.invalidateDisplayList(mDisplayList); 10200 } 10201 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 10202 } else { 10203 if (mDisplayList != null) { 10204 // Should never happen 10205 mDisplayList.invalidate(); 10206 } 10207 } 10208 10209 mCurrentAnimation = null; 10210 10211 resetResolvedLayoutDirection(); 10212 } 10213 10214 /** 10215 * @return The number of times this view has been attached to a window 10216 */ 10217 protected int getWindowAttachCount() { 10218 return mWindowAttachCount; 10219 } 10220 10221 /** 10222 * Retrieve a unique token identifying the window this view is attached to. 10223 * @return Return the window's token for use in 10224 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 10225 */ 10226 public IBinder getWindowToken() { 10227 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 10228 } 10229 10230 /** 10231 * Retrieve a unique token identifying the top-level "real" window of 10232 * the window that this view is attached to. That is, this is like 10233 * {@link #getWindowToken}, except if the window this view in is a panel 10234 * window (attached to another containing window), then the token of 10235 * the containing window is returned instead. 10236 * 10237 * @return Returns the associated window token, either 10238 * {@link #getWindowToken()} or the containing window's token. 10239 */ 10240 public IBinder getApplicationWindowToken() { 10241 AttachInfo ai = mAttachInfo; 10242 if (ai != null) { 10243 IBinder appWindowToken = ai.mPanelParentWindowToken; 10244 if (appWindowToken == null) { 10245 appWindowToken = ai.mWindowToken; 10246 } 10247 return appWindowToken; 10248 } 10249 return null; 10250 } 10251 10252 /** 10253 * Retrieve private session object this view hierarchy is using to 10254 * communicate with the window manager. 10255 * @return the session object to communicate with the window manager 10256 */ 10257 /*package*/ IWindowSession getWindowSession() { 10258 return mAttachInfo != null ? mAttachInfo.mSession : null; 10259 } 10260 10261 /** 10262 * @param info the {@link android.view.View.AttachInfo} to associated with 10263 * this view 10264 */ 10265 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 10266 //System.out.println("Attached! " + this); 10267 mAttachInfo = info; 10268 mWindowAttachCount++; 10269 // We will need to evaluate the drawable state at least once. 10270 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 10271 if (mFloatingTreeObserver != null) { 10272 info.mTreeObserver.merge(mFloatingTreeObserver); 10273 mFloatingTreeObserver = null; 10274 } 10275 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 10276 mAttachInfo.mScrollContainers.add(this); 10277 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 10278 } 10279 performCollectViewAttributes(mAttachInfo, visibility); 10280 onAttachedToWindow(); 10281 10282 ListenerInfo li = mListenerInfo; 10283 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 10284 li != null ? li.mOnAttachStateChangeListeners : null; 10285 if (listeners != null && listeners.size() > 0) { 10286 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 10287 // perform the dispatching. The iterator is a safe guard against listeners that 10288 // could mutate the list by calling the various add/remove methods. This prevents 10289 // the array from being modified while we iterate it. 10290 for (OnAttachStateChangeListener listener : listeners) { 10291 listener.onViewAttachedToWindow(this); 10292 } 10293 } 10294 10295 int vis = info.mWindowVisibility; 10296 if (vis != GONE) { 10297 onWindowVisibilityChanged(vis); 10298 } 10299 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 10300 // If nobody has evaluated the drawable state yet, then do it now. 10301 refreshDrawableState(); 10302 } 10303 } 10304 10305 void dispatchDetachedFromWindow() { 10306 AttachInfo info = mAttachInfo; 10307 if (info != null) { 10308 int vis = info.mWindowVisibility; 10309 if (vis != GONE) { 10310 onWindowVisibilityChanged(GONE); 10311 } 10312 } 10313 10314 onDetachedFromWindow(); 10315 10316 ListenerInfo li = mListenerInfo; 10317 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 10318 li != null ? li.mOnAttachStateChangeListeners : null; 10319 if (listeners != null && listeners.size() > 0) { 10320 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 10321 // perform the dispatching. The iterator is a safe guard against listeners that 10322 // could mutate the list by calling the various add/remove methods. This prevents 10323 // the array from being modified while we iterate it. 10324 for (OnAttachStateChangeListener listener : listeners) { 10325 listener.onViewDetachedFromWindow(this); 10326 } 10327 } 10328 10329 if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) { 10330 mAttachInfo.mScrollContainers.remove(this); 10331 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 10332 } 10333 10334 mAttachInfo = null; 10335 } 10336 10337 /** 10338 * Store this view hierarchy's frozen state into the given container. 10339 * 10340 * @param container The SparseArray in which to save the view's state. 10341 * 10342 * @see #restoreHierarchyState(android.util.SparseArray) 10343 * @see #dispatchSaveInstanceState(android.util.SparseArray) 10344 * @see #onSaveInstanceState() 10345 */ 10346 public void saveHierarchyState(SparseArray<Parcelable> container) { 10347 dispatchSaveInstanceState(container); 10348 } 10349 10350 /** 10351 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 10352 * this view and its children. May be overridden to modify how freezing happens to a 10353 * view's children; for example, some views may want to not store state for their children. 10354 * 10355 * @param container The SparseArray in which to save the view's state. 10356 * 10357 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 10358 * @see #saveHierarchyState(android.util.SparseArray) 10359 * @see #onSaveInstanceState() 10360 */ 10361 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 10362 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 10363 mPrivateFlags &= ~SAVE_STATE_CALLED; 10364 Parcelable state = onSaveInstanceState(); 10365 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 10366 throw new IllegalStateException( 10367 "Derived class did not call super.onSaveInstanceState()"); 10368 } 10369 if (state != null) { 10370 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 10371 // + ": " + state); 10372 container.put(mID, state); 10373 } 10374 } 10375 } 10376 10377 /** 10378 * Hook allowing a view to generate a representation of its internal state 10379 * that can later be used to create a new instance with that same state. 10380 * This state should only contain information that is not persistent or can 10381 * not be reconstructed later. For example, you will never store your 10382 * current position on screen because that will be computed again when a 10383 * new instance of the view is placed in its view hierarchy. 10384 * <p> 10385 * Some examples of things you may store here: the current cursor position 10386 * in a text view (but usually not the text itself since that is stored in a 10387 * content provider or other persistent storage), the currently selected 10388 * item in a list view. 10389 * 10390 * @return Returns a Parcelable object containing the view's current dynamic 10391 * state, or null if there is nothing interesting to save. The 10392 * default implementation returns null. 10393 * @see #onRestoreInstanceState(android.os.Parcelable) 10394 * @see #saveHierarchyState(android.util.SparseArray) 10395 * @see #dispatchSaveInstanceState(android.util.SparseArray) 10396 * @see #setSaveEnabled(boolean) 10397 */ 10398 protected Parcelable onSaveInstanceState() { 10399 mPrivateFlags |= SAVE_STATE_CALLED; 10400 return BaseSavedState.EMPTY_STATE; 10401 } 10402 10403 /** 10404 * Restore this view hierarchy's frozen state from the given container. 10405 * 10406 * @param container The SparseArray which holds previously frozen states. 10407 * 10408 * @see #saveHierarchyState(android.util.SparseArray) 10409 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 10410 * @see #onRestoreInstanceState(android.os.Parcelable) 10411 */ 10412 public void restoreHierarchyState(SparseArray<Parcelable> container) { 10413 dispatchRestoreInstanceState(container); 10414 } 10415 10416 /** 10417 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 10418 * state for this view and its children. May be overridden to modify how restoring 10419 * happens to a view's children; for example, some views may want to not store state 10420 * for their children. 10421 * 10422 * @param container The SparseArray which holds previously saved state. 10423 * 10424 * @see #dispatchSaveInstanceState(android.util.SparseArray) 10425 * @see #restoreHierarchyState(android.util.SparseArray) 10426 * @see #onRestoreInstanceState(android.os.Parcelable) 10427 */ 10428 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 10429 if (mID != NO_ID) { 10430 Parcelable state = container.get(mID); 10431 if (state != null) { 10432 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 10433 // + ": " + state); 10434 mPrivateFlags &= ~SAVE_STATE_CALLED; 10435 onRestoreInstanceState(state); 10436 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 10437 throw new IllegalStateException( 10438 "Derived class did not call super.onRestoreInstanceState()"); 10439 } 10440 } 10441 } 10442 } 10443 10444 /** 10445 * Hook allowing a view to re-apply a representation of its internal state that had previously 10446 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 10447 * null state. 10448 * 10449 * @param state The frozen state that had previously been returned by 10450 * {@link #onSaveInstanceState}. 10451 * 10452 * @see #onSaveInstanceState() 10453 * @see #restoreHierarchyState(android.util.SparseArray) 10454 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 10455 */ 10456 protected void onRestoreInstanceState(Parcelable state) { 10457 mPrivateFlags |= SAVE_STATE_CALLED; 10458 if (state != BaseSavedState.EMPTY_STATE && state != null) { 10459 throw new IllegalArgumentException("Wrong state class, expecting View State but " 10460 + "received " + state.getClass().toString() + " instead. This usually happens " 10461 + "when two views of different type have the same id in the same hierarchy. " 10462 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 10463 + "other views do not use the same id."); 10464 } 10465 } 10466 10467 /** 10468 * <p>Return the time at which the drawing of the view hierarchy started.</p> 10469 * 10470 * @return the drawing start time in milliseconds 10471 */ 10472 public long getDrawingTime() { 10473 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 10474 } 10475 10476 /** 10477 * <p>Enables or disables the duplication of the parent's state into this view. When 10478 * duplication is enabled, this view gets its drawable state from its parent rather 10479 * than from its own internal properties.</p> 10480 * 10481 * <p>Note: in the current implementation, setting this property to true after the 10482 * view was added to a ViewGroup might have no effect at all. This property should 10483 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 10484 * 10485 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 10486 * property is enabled, an exception will be thrown.</p> 10487 * 10488 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 10489 * parent, these states should not be affected by this method.</p> 10490 * 10491 * @param enabled True to enable duplication of the parent's drawable state, false 10492 * to disable it. 10493 * 10494 * @see #getDrawableState() 10495 * @see #isDuplicateParentStateEnabled() 10496 */ 10497 public void setDuplicateParentStateEnabled(boolean enabled) { 10498 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 10499 } 10500 10501 /** 10502 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 10503 * 10504 * @return True if this view's drawable state is duplicated from the parent, 10505 * false otherwise 10506 * 10507 * @see #getDrawableState() 10508 * @see #setDuplicateParentStateEnabled(boolean) 10509 */ 10510 public boolean isDuplicateParentStateEnabled() { 10511 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 10512 } 10513 10514 /** 10515 * <p>Specifies the type of layer backing this view. The layer can be 10516 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 10517 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 10518 * 10519 * <p>A layer is associated with an optional {@link android.graphics.Paint} 10520 * instance that controls how the layer is composed on screen. The following 10521 * properties of the paint are taken into account when composing the layer:</p> 10522 * <ul> 10523 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 10524 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 10525 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 10526 * </ul> 10527 * 10528 * <p>If this view has an alpha value set to < 1.0 by calling 10529 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 10530 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 10531 * equivalent to setting a hardware layer on this view and providing a paint with 10532 * the desired alpha value.<p> 10533 * 10534 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 10535 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 10536 * for more information on when and how to use layers.</p> 10537 * 10538 * @param layerType The ype of layer to use with this view, must be one of 10539 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 10540 * {@link #LAYER_TYPE_HARDWARE} 10541 * @param paint The paint used to compose the layer. This argument is optional 10542 * and can be null. It is ignored when the layer type is 10543 * {@link #LAYER_TYPE_NONE} 10544 * 10545 * @see #getLayerType() 10546 * @see #LAYER_TYPE_NONE 10547 * @see #LAYER_TYPE_SOFTWARE 10548 * @see #LAYER_TYPE_HARDWARE 10549 * @see #setAlpha(float) 10550 * 10551 * @attr ref android.R.styleable#View_layerType 10552 */ 10553 public void setLayerType(int layerType, Paint paint) { 10554 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 10555 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 10556 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 10557 } 10558 10559 if (layerType == mLayerType) { 10560 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 10561 mLayerPaint = paint == null ? new Paint() : paint; 10562 invalidateParentCaches(); 10563 invalidate(true); 10564 } 10565 return; 10566 } 10567 10568 // Destroy any previous software drawing cache if needed 10569 switch (mLayerType) { 10570 case LAYER_TYPE_HARDWARE: 10571 destroyLayer(false); 10572 // fall through - non-accelerated views may use software layer mechanism instead 10573 case LAYER_TYPE_SOFTWARE: 10574 destroyDrawingCache(); 10575 break; 10576 default: 10577 break; 10578 } 10579 10580 mLayerType = layerType; 10581 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 10582 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 10583 mLocalDirtyRect = layerDisabled ? null : new Rect(); 10584 10585 invalidateParentCaches(); 10586 invalidate(true); 10587 } 10588 10589 /** 10590 * Indicates whether this view has a static layer. A view with layer type 10591 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 10592 * dynamic. 10593 */ 10594 boolean hasStaticLayer() { 10595 return true; 10596 } 10597 10598 /** 10599 * Indicates what type of layer is currently associated with this view. By default 10600 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 10601 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 10602 * for more information on the different types of layers. 10603 * 10604 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 10605 * {@link #LAYER_TYPE_HARDWARE} 10606 * 10607 * @see #setLayerType(int, android.graphics.Paint) 10608 * @see #buildLayer() 10609 * @see #LAYER_TYPE_NONE 10610 * @see #LAYER_TYPE_SOFTWARE 10611 * @see #LAYER_TYPE_HARDWARE 10612 */ 10613 public int getLayerType() { 10614 return mLayerType; 10615 } 10616 10617 /** 10618 * Forces this view's layer to be created and this view to be rendered 10619 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 10620 * invoking this method will have no effect. 10621 * 10622 * This method can for instance be used to render a view into its layer before 10623 * starting an animation. If this view is complex, rendering into the layer 10624 * before starting the animation will avoid skipping frames. 10625 * 10626 * @throws IllegalStateException If this view is not attached to a window 10627 * 10628 * @see #setLayerType(int, android.graphics.Paint) 10629 */ 10630 public void buildLayer() { 10631 if (mLayerType == LAYER_TYPE_NONE) return; 10632 10633 if (mAttachInfo == null) { 10634 throw new IllegalStateException("This view must be attached to a window first"); 10635 } 10636 10637 switch (mLayerType) { 10638 case LAYER_TYPE_HARDWARE: 10639 if (mAttachInfo.mHardwareRenderer != null && 10640 mAttachInfo.mHardwareRenderer.isEnabled() && 10641 mAttachInfo.mHardwareRenderer.validate()) { 10642 getHardwareLayer(); 10643 } 10644 break; 10645 case LAYER_TYPE_SOFTWARE: 10646 buildDrawingCache(true); 10647 break; 10648 } 10649 } 10650 10651 // Make sure the HardwareRenderer.validate() was invoked before calling this method 10652 void flushLayer() { 10653 if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) { 10654 mHardwareLayer.flush(); 10655 } 10656 } 10657 10658 /** 10659 * <p>Returns a hardware layer that can be used to draw this view again 10660 * without executing its draw method.</p> 10661 * 10662 * @return A HardwareLayer ready to render, or null if an error occurred. 10663 */ 10664 HardwareLayer getHardwareLayer() { 10665 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 10666 !mAttachInfo.mHardwareRenderer.isEnabled()) { 10667 return null; 10668 } 10669 10670 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 10671 10672 final int width = mRight - mLeft; 10673 final int height = mBottom - mTop; 10674 10675 if (width == 0 || height == 0) { 10676 return null; 10677 } 10678 10679 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 10680 if (mHardwareLayer == null) { 10681 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 10682 width, height, isOpaque()); 10683 mLocalDirtyRect.set(0, 0, width, height); 10684 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 10685 mHardwareLayer.resize(width, height); 10686 mLocalDirtyRect.set(0, 0, width, height); 10687 } 10688 10689 // The layer is not valid if the underlying GPU resources cannot be allocated 10690 if (!mHardwareLayer.isValid()) { 10691 return null; 10692 } 10693 10694 mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect); 10695 mLocalDirtyRect.setEmpty(); 10696 } 10697 10698 return mHardwareLayer; 10699 } 10700 10701 /** 10702 * Destroys this View's hardware layer if possible. 10703 * 10704 * @return True if the layer was destroyed, false otherwise. 10705 * 10706 * @see #setLayerType(int, android.graphics.Paint) 10707 * @see #LAYER_TYPE_HARDWARE 10708 */ 10709 boolean destroyLayer(boolean valid) { 10710 if (mHardwareLayer != null) { 10711 AttachInfo info = mAttachInfo; 10712 if (info != null && info.mHardwareRenderer != null && 10713 info.mHardwareRenderer.isEnabled() && 10714 (valid || info.mHardwareRenderer.validate())) { 10715 mHardwareLayer.destroy(); 10716 mHardwareLayer = null; 10717 10718 invalidate(true); 10719 invalidateParentCaches(); 10720 } 10721 return true; 10722 } 10723 return false; 10724 } 10725 10726 /** 10727 * Destroys all hardware rendering resources. This method is invoked 10728 * when the system needs to reclaim resources. Upon execution of this 10729 * method, you should free any OpenGL resources created by the view. 10730 * 10731 * Note: you <strong>must</strong> call 10732 * <code>super.destroyHardwareResources()</code> when overriding 10733 * this method. 10734 * 10735 * @hide 10736 */ 10737 protected void destroyHardwareResources() { 10738 destroyLayer(true); 10739 } 10740 10741 /** 10742 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 10743 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 10744 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 10745 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 10746 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 10747 * null.</p> 10748 * 10749 * <p>Enabling the drawing cache is similar to 10750 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 10751 * acceleration is turned off. When hardware acceleration is turned on, enabling the 10752 * drawing cache has no effect on rendering because the system uses a different mechanism 10753 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 10754 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 10755 * for information on how to enable software and hardware layers.</p> 10756 * 10757 * <p>This API can be used to manually generate 10758 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 10759 * {@link #getDrawingCache()}.</p> 10760 * 10761 * @param enabled true to enable the drawing cache, false otherwise 10762 * 10763 * @see #isDrawingCacheEnabled() 10764 * @see #getDrawingCache() 10765 * @see #buildDrawingCache() 10766 * @see #setLayerType(int, android.graphics.Paint) 10767 */ 10768 public void setDrawingCacheEnabled(boolean enabled) { 10769 mCachingFailed = false; 10770 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 10771 } 10772 10773 /** 10774 * <p>Indicates whether the drawing cache is enabled for this view.</p> 10775 * 10776 * @return true if the drawing cache is enabled 10777 * 10778 * @see #setDrawingCacheEnabled(boolean) 10779 * @see #getDrawingCache() 10780 */ 10781 @ViewDebug.ExportedProperty(category = "drawing") 10782 public boolean isDrawingCacheEnabled() { 10783 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 10784 } 10785 10786 /** 10787 * Debugging utility which recursively outputs the dirty state of a view and its 10788 * descendants. 10789 * 10790 * @hide 10791 */ 10792 @SuppressWarnings({"UnusedDeclaration"}) 10793 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 10794 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) + 10795 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" + 10796 (mPrivateFlags & View.DRAWING_CACHE_VALID) + 10797 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")"); 10798 if (clear) { 10799 mPrivateFlags &= clearMask; 10800 } 10801 if (this instanceof ViewGroup) { 10802 ViewGroup parent = (ViewGroup) this; 10803 final int count = parent.getChildCount(); 10804 for (int i = 0; i < count; i++) { 10805 final View child = parent.getChildAt(i); 10806 child.outputDirtyFlags(indent + " ", clear, clearMask); 10807 } 10808 } 10809 } 10810 10811 /** 10812 * This method is used by ViewGroup to cause its children to restore or recreate their 10813 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 10814 * to recreate its own display list, which would happen if it went through the normal 10815 * draw/dispatchDraw mechanisms. 10816 * 10817 * @hide 10818 */ 10819 protected void dispatchGetDisplayList() {} 10820 10821 /** 10822 * A view that is not attached or hardware accelerated cannot create a display list. 10823 * This method checks these conditions and returns the appropriate result. 10824 * 10825 * @return true if view has the ability to create a display list, false otherwise. 10826 * 10827 * @hide 10828 */ 10829 public boolean canHaveDisplayList() { 10830 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 10831 } 10832 10833 /** 10834 * @return The HardwareRenderer associated with that view or null if hardware rendering 10835 * is not supported or this this has not been attached to a window. 10836 * 10837 * @hide 10838 */ 10839 public HardwareRenderer getHardwareRenderer() { 10840 if (mAttachInfo != null) { 10841 return mAttachInfo.mHardwareRenderer; 10842 } 10843 return null; 10844 } 10845 10846 /** 10847 * Returns a DisplayList. If the incoming displayList is null, one will be created. 10848 * Otherwise, the same display list will be returned (after having been rendered into 10849 * along the way, depending on the invalidation state of the view). 10850 * 10851 * @param displayList The previous version of this displayList, could be null. 10852 * @param isLayer Whether the requester of the display list is a layer. If so, 10853 * the view will avoid creating a layer inside the resulting display list. 10854 * @return A new or reused DisplayList object. 10855 */ 10856 private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) { 10857 if (!canHaveDisplayList()) { 10858 return null; 10859 } 10860 10861 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || 10862 displayList == null || !displayList.isValid() || 10863 (!isLayer && mRecreateDisplayList))) { 10864 // Don't need to recreate the display list, just need to tell our 10865 // children to restore/recreate theirs 10866 if (displayList != null && displayList.isValid() && 10867 !isLayer && !mRecreateDisplayList) { 10868 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10869 mPrivateFlags &= ~DIRTY_MASK; 10870 dispatchGetDisplayList(); 10871 10872 return displayList; 10873 } 10874 10875 if (!isLayer) { 10876 // If we got here, we're recreating it. Mark it as such to ensure that 10877 // we copy in child display lists into ours in drawChild() 10878 mRecreateDisplayList = true; 10879 } 10880 if (displayList == null) { 10881 final String name = getClass().getSimpleName(); 10882 displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name); 10883 // If we're creating a new display list, make sure our parent gets invalidated 10884 // since they will need to recreate their display list to account for this 10885 // new child display list. 10886 invalidateParentCaches(); 10887 } 10888 10889 boolean caching = false; 10890 final HardwareCanvas canvas = displayList.start(); 10891 int restoreCount = 0; 10892 int width = mRight - mLeft; 10893 int height = mBottom - mTop; 10894 10895 try { 10896 canvas.setViewport(width, height); 10897 // The dirty rect should always be null for a display list 10898 canvas.onPreDraw(null); 10899 int layerType = ( 10900 !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ? 10901 getLayerType() : LAYER_TYPE_NONE; 10902 if (!isLayer && layerType != LAYER_TYPE_NONE && USE_DISPLAY_LIST_PROPERTIES) { 10903 if (layerType == LAYER_TYPE_HARDWARE) { 10904 final HardwareLayer layer = getHardwareLayer(); 10905 if (layer != null && layer.isValid()) { 10906 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 10907 } else { 10908 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 10909 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 10910 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 10911 } 10912 caching = true; 10913 } else { 10914 buildDrawingCache(true); 10915 Bitmap cache = getDrawingCache(true); 10916 if (cache != null) { 10917 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 10918 caching = true; 10919 } 10920 } 10921 } else { 10922 10923 computeScroll(); 10924 10925 if (!USE_DISPLAY_LIST_PROPERTIES) { 10926 restoreCount = canvas.save(); 10927 } 10928 canvas.translate(-mScrollX, -mScrollY); 10929 if (!isLayer) { 10930 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10931 mPrivateFlags &= ~DIRTY_MASK; 10932 } 10933 10934 // Fast path for layouts with no backgrounds 10935 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10936 dispatchDraw(canvas); 10937 } else { 10938 draw(canvas); 10939 } 10940 } 10941 } finally { 10942 if (USE_DISPLAY_LIST_PROPERTIES) { 10943 canvas.restoreToCount(restoreCount); 10944 } 10945 canvas.onPostDraw(); 10946 10947 displayList.end(); 10948 if (USE_DISPLAY_LIST_PROPERTIES) { 10949 displayList.setCaching(caching); 10950 } 10951 if (isLayer && USE_DISPLAY_LIST_PROPERTIES) { 10952 displayList.setLeftTopRightBottom(0, 0, width, height); 10953 } else { 10954 setDisplayListProperties(displayList); 10955 } 10956 } 10957 } else if (!isLayer) { 10958 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10959 mPrivateFlags &= ~DIRTY_MASK; 10960 } 10961 10962 return displayList; 10963 } 10964 10965 /** 10966 * Get the DisplayList for the HardwareLayer 10967 * 10968 * @param layer The HardwareLayer whose DisplayList we want 10969 * @return A DisplayList fopr the specified HardwareLayer 10970 */ 10971 private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) { 10972 DisplayList displayList = getDisplayList(layer.getDisplayList(), true); 10973 layer.setDisplayList(displayList); 10974 return displayList; 10975 } 10976 10977 10978 /** 10979 * <p>Returns a display list that can be used to draw this view again 10980 * without executing its draw method.</p> 10981 * 10982 * @return A DisplayList ready to replay, or null if caching is not enabled. 10983 * 10984 * @hide 10985 */ 10986 public DisplayList getDisplayList() { 10987 mDisplayList = getDisplayList(mDisplayList, false); 10988 return mDisplayList; 10989 } 10990 10991 /** 10992 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 10993 * 10994 * @return A non-scaled bitmap representing this view or null if cache is disabled. 10995 * 10996 * @see #getDrawingCache(boolean) 10997 */ 10998 public Bitmap getDrawingCache() { 10999 return getDrawingCache(false); 11000 } 11001 11002 /** 11003 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 11004 * is null when caching is disabled. If caching is enabled and the cache is not ready, 11005 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 11006 * draw from the cache when the cache is enabled. To benefit from the cache, you must 11007 * request the drawing cache by calling this method and draw it on screen if the 11008 * returned bitmap is not null.</p> 11009 * 11010 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 11011 * this method will create a bitmap of the same size as this view. Because this bitmap 11012 * will be drawn scaled by the parent ViewGroup, the result on screen might show 11013 * scaling artifacts. To avoid such artifacts, you should call this method by setting 11014 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 11015 * size than the view. This implies that your application must be able to handle this 11016 * size.</p> 11017 * 11018 * @param autoScale Indicates whether the generated bitmap should be scaled based on 11019 * the current density of the screen when the application is in compatibility 11020 * mode. 11021 * 11022 * @return A bitmap representing this view or null if cache is disabled. 11023 * 11024 * @see #setDrawingCacheEnabled(boolean) 11025 * @see #isDrawingCacheEnabled() 11026 * @see #buildDrawingCache(boolean) 11027 * @see #destroyDrawingCache() 11028 */ 11029 public Bitmap getDrawingCache(boolean autoScale) { 11030 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 11031 return null; 11032 } 11033 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 11034 buildDrawingCache(autoScale); 11035 } 11036 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 11037 } 11038 11039 /** 11040 * <p>Frees the resources used by the drawing cache. If you call 11041 * {@link #buildDrawingCache()} manually without calling 11042 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 11043 * should cleanup the cache with this method afterwards.</p> 11044 * 11045 * @see #setDrawingCacheEnabled(boolean) 11046 * @see #buildDrawingCache() 11047 * @see #getDrawingCache() 11048 */ 11049 public void destroyDrawingCache() { 11050 if (mDrawingCache != null) { 11051 mDrawingCache.recycle(); 11052 mDrawingCache = null; 11053 } 11054 if (mUnscaledDrawingCache != null) { 11055 mUnscaledDrawingCache.recycle(); 11056 mUnscaledDrawingCache = null; 11057 } 11058 } 11059 11060 /** 11061 * Setting a solid background color for the drawing cache's bitmaps will improve 11062 * performance and memory usage. Note, though that this should only be used if this 11063 * view will always be drawn on top of a solid color. 11064 * 11065 * @param color The background color to use for the drawing cache's bitmap 11066 * 11067 * @see #setDrawingCacheEnabled(boolean) 11068 * @see #buildDrawingCache() 11069 * @see #getDrawingCache() 11070 */ 11071 public void setDrawingCacheBackgroundColor(int color) { 11072 if (color != mDrawingCacheBackgroundColor) { 11073 mDrawingCacheBackgroundColor = color; 11074 mPrivateFlags &= ~DRAWING_CACHE_VALID; 11075 } 11076 } 11077 11078 /** 11079 * @see #setDrawingCacheBackgroundColor(int) 11080 * 11081 * @return The background color to used for the drawing cache's bitmap 11082 */ 11083 public int getDrawingCacheBackgroundColor() { 11084 return mDrawingCacheBackgroundColor; 11085 } 11086 11087 /** 11088 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 11089 * 11090 * @see #buildDrawingCache(boolean) 11091 */ 11092 public void buildDrawingCache() { 11093 buildDrawingCache(false); 11094 } 11095 11096 /** 11097 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 11098 * 11099 * <p>If you call {@link #buildDrawingCache()} manually without calling 11100 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 11101 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 11102 * 11103 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 11104 * this method will create a bitmap of the same size as this view. Because this bitmap 11105 * will be drawn scaled by the parent ViewGroup, the result on screen might show 11106 * scaling artifacts. To avoid such artifacts, you should call this method by setting 11107 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 11108 * size than the view. This implies that your application must be able to handle this 11109 * size.</p> 11110 * 11111 * <p>You should avoid calling this method when hardware acceleration is enabled. If 11112 * you do not need the drawing cache bitmap, calling this method will increase memory 11113 * usage and cause the view to be rendered in software once, thus negatively impacting 11114 * performance.</p> 11115 * 11116 * @see #getDrawingCache() 11117 * @see #destroyDrawingCache() 11118 */ 11119 public void buildDrawingCache(boolean autoScale) { 11120 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 11121 mDrawingCache == null : mUnscaledDrawingCache == null)) { 11122 mCachingFailed = false; 11123 11124 if (ViewDebug.TRACE_HIERARCHY) { 11125 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 11126 } 11127 11128 int width = mRight - mLeft; 11129 int height = mBottom - mTop; 11130 11131 final AttachInfo attachInfo = mAttachInfo; 11132 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 11133 11134 if (autoScale && scalingRequired) { 11135 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 11136 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 11137 } 11138 11139 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 11140 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 11141 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 11142 11143 if (width <= 0 || height <= 0 || 11144 // Projected bitmap size in bytes 11145 (width * height * (opaque && !use32BitCache ? 2 : 4) > 11146 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 11147 destroyDrawingCache(); 11148 mCachingFailed = true; 11149 return; 11150 } 11151 11152 boolean clear = true; 11153 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 11154 11155 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 11156 Bitmap.Config quality; 11157 if (!opaque) { 11158 // Never pick ARGB_4444 because it looks awful 11159 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 11160 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 11161 case DRAWING_CACHE_QUALITY_AUTO: 11162 quality = Bitmap.Config.ARGB_8888; 11163 break; 11164 case DRAWING_CACHE_QUALITY_LOW: 11165 quality = Bitmap.Config.ARGB_8888; 11166 break; 11167 case DRAWING_CACHE_QUALITY_HIGH: 11168 quality = Bitmap.Config.ARGB_8888; 11169 break; 11170 default: 11171 quality = Bitmap.Config.ARGB_8888; 11172 break; 11173 } 11174 } else { 11175 // Optimization for translucent windows 11176 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 11177 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 11178 } 11179 11180 // Try to cleanup memory 11181 if (bitmap != null) bitmap.recycle(); 11182 11183 try { 11184 bitmap = Bitmap.createBitmap(width, height, quality); 11185 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 11186 if (autoScale) { 11187 mDrawingCache = bitmap; 11188 } else { 11189 mUnscaledDrawingCache = bitmap; 11190 } 11191 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 11192 } catch (OutOfMemoryError e) { 11193 // If there is not enough memory to create the bitmap cache, just 11194 // ignore the issue as bitmap caches are not required to draw the 11195 // view hierarchy 11196 if (autoScale) { 11197 mDrawingCache = null; 11198 } else { 11199 mUnscaledDrawingCache = null; 11200 } 11201 mCachingFailed = true; 11202 return; 11203 } 11204 11205 clear = drawingCacheBackgroundColor != 0; 11206 } 11207 11208 Canvas canvas; 11209 if (attachInfo != null) { 11210 canvas = attachInfo.mCanvas; 11211 if (canvas == null) { 11212 canvas = new Canvas(); 11213 } 11214 canvas.setBitmap(bitmap); 11215 // Temporarily clobber the cached Canvas in case one of our children 11216 // is also using a drawing cache. Without this, the children would 11217 // steal the canvas by attaching their own bitmap to it and bad, bad 11218 // thing would happen (invisible views, corrupted drawings, etc.) 11219 attachInfo.mCanvas = null; 11220 } else { 11221 // This case should hopefully never or seldom happen 11222 canvas = new Canvas(bitmap); 11223 } 11224 11225 if (clear) { 11226 bitmap.eraseColor(drawingCacheBackgroundColor); 11227 } 11228 11229 computeScroll(); 11230 final int restoreCount = canvas.save(); 11231 11232 if (autoScale && scalingRequired) { 11233 final float scale = attachInfo.mApplicationScale; 11234 canvas.scale(scale, scale); 11235 } 11236 11237 canvas.translate(-mScrollX, -mScrollY); 11238 11239 mPrivateFlags |= DRAWN; 11240 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 11241 mLayerType != LAYER_TYPE_NONE) { 11242 mPrivateFlags |= DRAWING_CACHE_VALID; 11243 } 11244 11245 // Fast path for layouts with no backgrounds 11246 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 11247 if (ViewDebug.TRACE_HIERARCHY) { 11248 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 11249 } 11250 mPrivateFlags &= ~DIRTY_MASK; 11251 dispatchDraw(canvas); 11252 } else { 11253 draw(canvas); 11254 } 11255 11256 canvas.restoreToCount(restoreCount); 11257 canvas.setBitmap(null); 11258 11259 if (attachInfo != null) { 11260 // Restore the cached Canvas for our siblings 11261 attachInfo.mCanvas = canvas; 11262 } 11263 } 11264 } 11265 11266 /** 11267 * Create a snapshot of the view into a bitmap. We should probably make 11268 * some form of this public, but should think about the API. 11269 */ 11270 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 11271 int width = mRight - mLeft; 11272 int height = mBottom - mTop; 11273 11274 final AttachInfo attachInfo = mAttachInfo; 11275 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 11276 width = (int) ((width * scale) + 0.5f); 11277 height = (int) ((height * scale) + 0.5f); 11278 11279 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 11280 if (bitmap == null) { 11281 throw new OutOfMemoryError(); 11282 } 11283 11284 Resources resources = getResources(); 11285 if (resources != null) { 11286 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 11287 } 11288 11289 Canvas canvas; 11290 if (attachInfo != null) { 11291 canvas = attachInfo.mCanvas; 11292 if (canvas == null) { 11293 canvas = new Canvas(); 11294 } 11295 canvas.setBitmap(bitmap); 11296 // Temporarily clobber the cached Canvas in case one of our children 11297 // is also using a drawing cache. Without this, the children would 11298 // steal the canvas by attaching their own bitmap to it and bad, bad 11299 // things would happen (invisible views, corrupted drawings, etc.) 11300 attachInfo.mCanvas = null; 11301 } else { 11302 // This case should hopefully never or seldom happen 11303 canvas = new Canvas(bitmap); 11304 } 11305 11306 if ((backgroundColor & 0xff000000) != 0) { 11307 bitmap.eraseColor(backgroundColor); 11308 } 11309 11310 computeScroll(); 11311 final int restoreCount = canvas.save(); 11312 canvas.scale(scale, scale); 11313 canvas.translate(-mScrollX, -mScrollY); 11314 11315 // Temporarily remove the dirty mask 11316 int flags = mPrivateFlags; 11317 mPrivateFlags &= ~DIRTY_MASK; 11318 11319 // Fast path for layouts with no backgrounds 11320 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 11321 dispatchDraw(canvas); 11322 } else { 11323 draw(canvas); 11324 } 11325 11326 mPrivateFlags = flags; 11327 11328 canvas.restoreToCount(restoreCount); 11329 canvas.setBitmap(null); 11330 11331 if (attachInfo != null) { 11332 // Restore the cached Canvas for our siblings 11333 attachInfo.mCanvas = canvas; 11334 } 11335 11336 return bitmap; 11337 } 11338 11339 /** 11340 * Indicates whether this View is currently in edit mode. A View is usually 11341 * in edit mode when displayed within a developer tool. For instance, if 11342 * this View is being drawn by a visual user interface builder, this method 11343 * should return true. 11344 * 11345 * Subclasses should check the return value of this method to provide 11346 * different behaviors if their normal behavior might interfere with the 11347 * host environment. For instance: the class spawns a thread in its 11348 * constructor, the drawing code relies on device-specific features, etc. 11349 * 11350 * This method is usually checked in the drawing code of custom widgets. 11351 * 11352 * @return True if this View is in edit mode, false otherwise. 11353 */ 11354 public boolean isInEditMode() { 11355 return false; 11356 } 11357 11358 /** 11359 * If the View draws content inside its padding and enables fading edges, 11360 * it needs to support padding offsets. Padding offsets are added to the 11361 * fading edges to extend the length of the fade so that it covers pixels 11362 * drawn inside the padding. 11363 * 11364 * Subclasses of this class should override this method if they need 11365 * to draw content inside the padding. 11366 * 11367 * @return True if padding offset must be applied, false otherwise. 11368 * 11369 * @see #getLeftPaddingOffset() 11370 * @see #getRightPaddingOffset() 11371 * @see #getTopPaddingOffset() 11372 * @see #getBottomPaddingOffset() 11373 * 11374 * @since CURRENT 11375 */ 11376 protected boolean isPaddingOffsetRequired() { 11377 return false; 11378 } 11379 11380 /** 11381 * Amount by which to extend the left fading region. Called only when 11382 * {@link #isPaddingOffsetRequired()} returns true. 11383 * 11384 * @return The left padding offset in pixels. 11385 * 11386 * @see #isPaddingOffsetRequired() 11387 * 11388 * @since CURRENT 11389 */ 11390 protected int getLeftPaddingOffset() { 11391 return 0; 11392 } 11393 11394 /** 11395 * Amount by which to extend the right fading region. Called only when 11396 * {@link #isPaddingOffsetRequired()} returns true. 11397 * 11398 * @return The right padding offset in pixels. 11399 * 11400 * @see #isPaddingOffsetRequired() 11401 * 11402 * @since CURRENT 11403 */ 11404 protected int getRightPaddingOffset() { 11405 return 0; 11406 } 11407 11408 /** 11409 * Amount by which to extend the top fading region. Called only when 11410 * {@link #isPaddingOffsetRequired()} returns true. 11411 * 11412 * @return The top padding offset in pixels. 11413 * 11414 * @see #isPaddingOffsetRequired() 11415 * 11416 * @since CURRENT 11417 */ 11418 protected int getTopPaddingOffset() { 11419 return 0; 11420 } 11421 11422 /** 11423 * Amount by which to extend the bottom fading region. Called only when 11424 * {@link #isPaddingOffsetRequired()} returns true. 11425 * 11426 * @return The bottom padding offset in pixels. 11427 * 11428 * @see #isPaddingOffsetRequired() 11429 * 11430 * @since CURRENT 11431 */ 11432 protected int getBottomPaddingOffset() { 11433 return 0; 11434 } 11435 11436 /** 11437 * @hide 11438 * @param offsetRequired 11439 */ 11440 protected int getFadeTop(boolean offsetRequired) { 11441 int top = mPaddingTop; 11442 if (offsetRequired) top += getTopPaddingOffset(); 11443 return top; 11444 } 11445 11446 /** 11447 * @hide 11448 * @param offsetRequired 11449 */ 11450 protected int getFadeHeight(boolean offsetRequired) { 11451 int padding = mPaddingTop; 11452 if (offsetRequired) padding += getTopPaddingOffset(); 11453 return mBottom - mTop - mPaddingBottom - padding; 11454 } 11455 11456 /** 11457 * <p>Indicates whether this view is attached to a hardware accelerated 11458 * window or not.</p> 11459 * 11460 * <p>Even if this method returns true, it does not mean that every call 11461 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 11462 * accelerated {@link android.graphics.Canvas}. For instance, if this view 11463 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 11464 * window is hardware accelerated, 11465 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 11466 * return false, and this method will return true.</p> 11467 * 11468 * @return True if the view is attached to a window and the window is 11469 * hardware accelerated; false in any other case. 11470 */ 11471 public boolean isHardwareAccelerated() { 11472 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 11473 } 11474 11475 /** 11476 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 11477 * case of an active Animation being run on the view. 11478 */ 11479 private boolean drawAnimation(ViewGroup parent, long drawingTime, 11480 Animation a, boolean scalingRequired) { 11481 Transformation invalidationTransform; 11482 final int flags = parent.mGroupFlags; 11483 final boolean initialized = a.isInitialized(); 11484 if (!initialized) { 11485 a.initialize(mRight - mLeft, mBottom - mTop, getWidth(), getHeight()); 11486 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 11487 onAnimationStart(); 11488 } 11489 11490 boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f); 11491 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 11492 if (parent.mInvalidationTransformation == null) { 11493 parent.mInvalidationTransformation = new Transformation(); 11494 } 11495 invalidationTransform = parent.mInvalidationTransformation; 11496 a.getTransformation(drawingTime, invalidationTransform, 1f); 11497 } else { 11498 invalidationTransform = parent.mChildTransformation; 11499 } 11500 if (more) { 11501 if (!a.willChangeBounds()) { 11502 if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) == 11503 parent.FLAG_OPTIMIZE_INVALIDATE) { 11504 parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED; 11505 } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) { 11506 // The child need to draw an animation, potentially offscreen, so 11507 // make sure we do not cancel invalidate requests 11508 parent.mPrivateFlags |= DRAW_ANIMATION; 11509 parent.invalidate(mLeft, mTop, mRight, mBottom); 11510 } 11511 } else { 11512 if (parent.mInvalidateRegion == null) { 11513 parent.mInvalidateRegion = new RectF(); 11514 } 11515 final RectF region = parent.mInvalidateRegion; 11516 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 11517 invalidationTransform); 11518 11519 // The child need to draw an animation, potentially offscreen, so 11520 // make sure we do not cancel invalidate requests 11521 parent.mPrivateFlags |= DRAW_ANIMATION; 11522 11523 final int left = mLeft + (int) region.left; 11524 final int top = mTop + (int) region.top; 11525 parent.invalidate(left, top, left + (int) (region.width() + .5f), 11526 top + (int) (region.height() + .5f)); 11527 } 11528 } 11529 return more; 11530 } 11531 11532 void setDisplayListProperties() { 11533 setDisplayListProperties(mDisplayList); 11534 } 11535 11536 /** 11537 * This method is called by getDisplayList() when a display list is created or re-rendered. 11538 * It sets or resets the current value of all properties on that display list (resetting is 11539 * necessary when a display list is being re-created, because we need to make sure that 11540 * previously-set transform values 11541 */ 11542 void setDisplayListProperties(DisplayList displayList) { 11543 if (USE_DISPLAY_LIST_PROPERTIES && displayList != null) { 11544 displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 11545 displayList.setHasOverlappingRendering(hasOverlappingRendering()); 11546 if (mParent instanceof ViewGroup) { 11547 displayList.setClipChildren( 11548 (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 11549 } 11550 float alpha = 1; 11551 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 11552 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 11553 ViewGroup parentVG = (ViewGroup) mParent; 11554 final boolean hasTransform = 11555 parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation); 11556 if (hasTransform) { 11557 Transformation transform = parentVG.mChildTransformation; 11558 final int transformType = parentVG.mChildTransformation.getTransformationType(); 11559 if (transformType != Transformation.TYPE_IDENTITY) { 11560 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 11561 alpha = transform.getAlpha(); 11562 } 11563 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 11564 displayList.setStaticMatrix(transform.getMatrix()); 11565 } 11566 } 11567 } 11568 } 11569 if (mTransformationInfo != null) { 11570 alpha *= mTransformationInfo.mAlpha; 11571 if (alpha < 1) { 11572 final int multipliedAlpha = (int) (255 * alpha); 11573 if (onSetAlpha(multipliedAlpha)) { 11574 alpha = 1; 11575 } 11576 } 11577 displayList.setTransformationInfo(alpha, 11578 mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY, 11579 mTransformationInfo.mRotation, mTransformationInfo.mRotationX, 11580 mTransformationInfo.mRotationY, mTransformationInfo.mScaleX, 11581 mTransformationInfo.mScaleY); 11582 if (mTransformationInfo.mCamera == null) { 11583 mTransformationInfo.mCamera = new Camera(); 11584 mTransformationInfo.matrix3D = new Matrix(); 11585 } 11586 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ()); 11587 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) { 11588 displayList.setPivotX(getPivotX()); 11589 displayList.setPivotY(getPivotY()); 11590 } 11591 } else if (alpha < 1) { 11592 displayList.setAlpha(alpha); 11593 } 11594 } 11595 } 11596 11597 /** 11598 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 11599 * This draw() method is an implementation detail and is not intended to be overridden or 11600 * to be called from anywhere else other than ViewGroup.drawChild(). 11601 */ 11602 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 11603 boolean useDisplayListProperties = USE_DISPLAY_LIST_PROPERTIES && mAttachInfo != null && 11604 mAttachInfo.mHardwareAccelerated; 11605 boolean more = false; 11606 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 11607 final int flags = parent.mGroupFlags; 11608 11609 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 11610 parent.mChildTransformation.clear(); 11611 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 11612 } 11613 11614 Transformation transformToApply = null; 11615 boolean concatMatrix = false; 11616 11617 boolean scalingRequired = false; 11618 boolean caching; 11619 int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE; 11620 11621 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 11622 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 11623 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 11624 caching = true; 11625 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 11626 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 11627 } else { 11628 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 11629 } 11630 11631 final Animation a = getAnimation(); 11632 if (a != null) { 11633 more = drawAnimation(parent, drawingTime, a, scalingRequired); 11634 concatMatrix = a.willChangeTransformationMatrix(); 11635 transformToApply = parent.mChildTransformation; 11636 } else if (!useDisplayListProperties && 11637 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 11638 final boolean hasTransform = 11639 parent.getChildStaticTransformation(this, parent.mChildTransformation); 11640 if (hasTransform) { 11641 final int transformType = parent.mChildTransformation.getTransformationType(); 11642 transformToApply = transformType != Transformation.TYPE_IDENTITY ? 11643 parent.mChildTransformation : null; 11644 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 11645 } 11646 } 11647 11648 concatMatrix |= !childHasIdentityMatrix; 11649 11650 // Sets the flag as early as possible to allow draw() implementations 11651 // to call invalidate() successfully when doing animations 11652 mPrivateFlags |= DRAWN; 11653 11654 if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 11655 (mPrivateFlags & DRAW_ANIMATION) == 0) { 11656 return more; 11657 } 11658 11659 if (hardwareAccelerated) { 11660 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 11661 // retain the flag's value temporarily in the mRecreateDisplayList flag 11662 mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED; 11663 mPrivateFlags &= ~INVALIDATED; 11664 } 11665 11666 computeScroll(); 11667 11668 final int sx = mScrollX; 11669 final int sy = mScrollY; 11670 11671 DisplayList displayList = null; 11672 Bitmap cache = null; 11673 boolean hasDisplayList = false; 11674 if (caching) { 11675 if (!hardwareAccelerated) { 11676 if (layerType != LAYER_TYPE_NONE) { 11677 layerType = LAYER_TYPE_SOFTWARE; 11678 buildDrawingCache(true); 11679 } 11680 cache = getDrawingCache(true); 11681 } else { 11682 switch (layerType) { 11683 case LAYER_TYPE_SOFTWARE: 11684 if (useDisplayListProperties) { 11685 hasDisplayList = canHaveDisplayList(); 11686 } else { 11687 buildDrawingCache(true); 11688 cache = getDrawingCache(true); 11689 } 11690 break; 11691 case LAYER_TYPE_HARDWARE: 11692 if (useDisplayListProperties) { 11693 hasDisplayList = canHaveDisplayList(); 11694 } 11695 break; 11696 case LAYER_TYPE_NONE: 11697 // Delay getting the display list until animation-driven alpha values are 11698 // set up and possibly passed on to the view 11699 hasDisplayList = canHaveDisplayList(); 11700 break; 11701 } 11702 } 11703 } 11704 useDisplayListProperties &= hasDisplayList; 11705 if (useDisplayListProperties) { 11706 displayList = getDisplayList(); 11707 if (!displayList.isValid()) { 11708 // Uncommon, but possible. If a view is removed from the hierarchy during the call 11709 // to getDisplayList(), the display list will be marked invalid and we should not 11710 // try to use it again. 11711 displayList = null; 11712 hasDisplayList = false; 11713 useDisplayListProperties = false; 11714 } 11715 } 11716 11717 final boolean hasNoCache = cache == null || hasDisplayList; 11718 final boolean offsetForScroll = cache == null && !hasDisplayList && 11719 layerType != LAYER_TYPE_HARDWARE; 11720 11721 int restoreTo = -1; 11722 if (!useDisplayListProperties || transformToApply != null) { 11723 restoreTo = canvas.save(); 11724 } 11725 if (offsetForScroll) { 11726 canvas.translate(mLeft - sx, mTop - sy); 11727 } else { 11728 if (!useDisplayListProperties) { 11729 canvas.translate(mLeft, mTop); 11730 } 11731 if (scalingRequired) { 11732 if (useDisplayListProperties) { 11733 // TODO: Might not need this if we put everything inside the DL 11734 restoreTo = canvas.save(); 11735 } 11736 // mAttachInfo cannot be null, otherwise scalingRequired == false 11737 final float scale = 1.0f / mAttachInfo.mApplicationScale; 11738 canvas.scale(scale, scale); 11739 } 11740 } 11741 11742 float alpha = useDisplayListProperties ? 1 : getAlpha(); 11743 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) { 11744 if (transformToApply != null || !childHasIdentityMatrix) { 11745 int transX = 0; 11746 int transY = 0; 11747 11748 if (offsetForScroll) { 11749 transX = -sx; 11750 transY = -sy; 11751 } 11752 11753 if (transformToApply != null) { 11754 if (concatMatrix) { 11755 if (useDisplayListProperties) { 11756 displayList.setAnimationMatrix(transformToApply.getMatrix()); 11757 } else { 11758 // Undo the scroll translation, apply the transformation matrix, 11759 // then redo the scroll translate to get the correct result. 11760 canvas.translate(-transX, -transY); 11761 canvas.concat(transformToApply.getMatrix()); 11762 canvas.translate(transX, transY); 11763 } 11764 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 11765 } 11766 11767 float transformAlpha = transformToApply.getAlpha(); 11768 if (transformAlpha < 1) { 11769 alpha *= transformToApply.getAlpha(); 11770 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 11771 } 11772 } 11773 11774 if (!childHasIdentityMatrix && !useDisplayListProperties) { 11775 canvas.translate(-transX, -transY); 11776 canvas.concat(getMatrix()); 11777 canvas.translate(transX, transY); 11778 } 11779 } 11780 11781 if (alpha < 1) { 11782 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 11783 if (hasNoCache) { 11784 final int multipliedAlpha = (int) (255 * alpha); 11785 if (!onSetAlpha(multipliedAlpha)) { 11786 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 11787 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 11788 layerType != LAYER_TYPE_NONE) { 11789 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 11790 } 11791 if (useDisplayListProperties) { 11792 displayList.setAlpha(alpha * getAlpha()); 11793 } else if (layerType == LAYER_TYPE_NONE) { 11794 final int scrollX = hasDisplayList ? 0 : sx; 11795 final int scrollY = hasDisplayList ? 0 : sy; 11796 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 11797 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 11798 } 11799 } else { 11800 // Alpha is handled by the child directly, clobber the layer's alpha 11801 mPrivateFlags |= ALPHA_SET; 11802 } 11803 } 11804 } 11805 } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) { 11806 onSetAlpha(255); 11807 mPrivateFlags &= ~ALPHA_SET; 11808 } 11809 11810 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 11811 !useDisplayListProperties) { 11812 if (offsetForScroll) { 11813 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 11814 } else { 11815 if (!scalingRequired || cache == null) { 11816 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 11817 } else { 11818 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 11819 } 11820 } 11821 } 11822 11823 if (!useDisplayListProperties && hasDisplayList) { 11824 displayList = getDisplayList(); 11825 if (!displayList.isValid()) { 11826 // Uncommon, but possible. If a view is removed from the hierarchy during the call 11827 // to getDisplayList(), the display list will be marked invalid and we should not 11828 // try to use it again. 11829 displayList = null; 11830 hasDisplayList = false; 11831 } 11832 } 11833 11834 if (hasNoCache) { 11835 boolean layerRendered = false; 11836 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 11837 final HardwareLayer layer = getHardwareLayer(); 11838 if (layer != null && layer.isValid()) { 11839 mLayerPaint.setAlpha((int) (alpha * 255)); 11840 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 11841 layerRendered = true; 11842 } else { 11843 final int scrollX = hasDisplayList ? 0 : sx; 11844 final int scrollY = hasDisplayList ? 0 : sy; 11845 canvas.saveLayer(scrollX, scrollY, 11846 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 11847 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 11848 } 11849 } 11850 11851 if (!layerRendered) { 11852 if (!hasDisplayList) { 11853 // Fast path for layouts with no backgrounds 11854 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 11855 if (ViewDebug.TRACE_HIERARCHY) { 11856 ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW); 11857 } 11858 mPrivateFlags &= ~DIRTY_MASK; 11859 dispatchDraw(canvas); 11860 } else { 11861 draw(canvas); 11862 } 11863 } else { 11864 mPrivateFlags &= ~DIRTY_MASK; 11865 ((HardwareCanvas) canvas).drawDisplayList(displayList, 11866 mRight - mLeft, mBottom - mTop, null, flags); 11867 } 11868 } 11869 } else if (cache != null) { 11870 mPrivateFlags &= ~DIRTY_MASK; 11871 Paint cachePaint; 11872 11873 if (layerType == LAYER_TYPE_NONE) { 11874 cachePaint = parent.mCachePaint; 11875 if (cachePaint == null) { 11876 cachePaint = new Paint(); 11877 cachePaint.setDither(false); 11878 parent.mCachePaint = cachePaint; 11879 } 11880 if (alpha < 1) { 11881 cachePaint.setAlpha((int) (alpha * 255)); 11882 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 11883 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 11884 cachePaint.setAlpha(255); 11885 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 11886 } 11887 } else { 11888 cachePaint = mLayerPaint; 11889 cachePaint.setAlpha((int) (alpha * 255)); 11890 } 11891 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 11892 } 11893 11894 if (restoreTo >= 0) { 11895 canvas.restoreToCount(restoreTo); 11896 } 11897 11898 if (a != null && !more) { 11899 if (!hardwareAccelerated && !a.getFillAfter()) { 11900 onSetAlpha(255); 11901 } 11902 parent.finishAnimatingView(this, a); 11903 } 11904 11905 if (more && hardwareAccelerated) { 11906 // invalidation is the trigger to recreate display lists, so if we're using 11907 // display lists to render, force an invalidate to allow the animation to 11908 // continue drawing another frame 11909 parent.invalidate(true); 11910 if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) { 11911 // alpha animations should cause the child to recreate its display list 11912 invalidate(true); 11913 } 11914 } 11915 11916 mRecreateDisplayList = false; 11917 11918 return more; 11919 } 11920 11921 /** 11922 * Manually render this view (and all of its children) to the given Canvas. 11923 * The view must have already done a full layout before this function is 11924 * called. When implementing a view, implement 11925 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 11926 * If you do need to override this method, call the superclass version. 11927 * 11928 * @param canvas The Canvas to which the View is rendered. 11929 */ 11930 public void draw(Canvas canvas) { 11931 if (ViewDebug.TRACE_HIERARCHY) { 11932 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 11933 } 11934 11935 final int privateFlags = mPrivateFlags; 11936 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 11937 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 11938 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 11939 11940 /* 11941 * Draw traversal performs several drawing steps which must be executed 11942 * in the appropriate order: 11943 * 11944 * 1. Draw the background 11945 * 2. If necessary, save the canvas' layers to prepare for fading 11946 * 3. Draw view's content 11947 * 4. Draw children 11948 * 5. If necessary, draw the fading edges and restore layers 11949 * 6. Draw decorations (scrollbars for instance) 11950 */ 11951 11952 // Step 1, draw the background, if needed 11953 int saveCount; 11954 11955 if (!dirtyOpaque) { 11956 final Drawable background = mBGDrawable; 11957 if (background != null) { 11958 final int scrollX = mScrollX; 11959 final int scrollY = mScrollY; 11960 11961 if (mBackgroundSizeChanged) { 11962 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 11963 mBackgroundSizeChanged = false; 11964 } 11965 11966 if ((scrollX | scrollY) == 0) { 11967 background.draw(canvas); 11968 } else { 11969 canvas.translate(scrollX, scrollY); 11970 background.draw(canvas); 11971 canvas.translate(-scrollX, -scrollY); 11972 } 11973 } 11974 } 11975 11976 // skip step 2 & 5 if possible (common case) 11977 final int viewFlags = mViewFlags; 11978 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 11979 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 11980 if (!verticalEdges && !horizontalEdges) { 11981 // Step 3, draw the content 11982 if (!dirtyOpaque) onDraw(canvas); 11983 11984 // Step 4, draw the children 11985 dispatchDraw(canvas); 11986 11987 // Step 6, draw decorations (scrollbars) 11988 onDrawScrollBars(canvas); 11989 11990 // we're done... 11991 return; 11992 } 11993 11994 /* 11995 * Here we do the full fledged routine... 11996 * (this is an uncommon case where speed matters less, 11997 * this is why we repeat some of the tests that have been 11998 * done above) 11999 */ 12000 12001 boolean drawTop = false; 12002 boolean drawBottom = false; 12003 boolean drawLeft = false; 12004 boolean drawRight = false; 12005 12006 float topFadeStrength = 0.0f; 12007 float bottomFadeStrength = 0.0f; 12008 float leftFadeStrength = 0.0f; 12009 float rightFadeStrength = 0.0f; 12010 12011 // Step 2, save the canvas' layers 12012 int paddingLeft = mPaddingLeft; 12013 12014 final boolean offsetRequired = isPaddingOffsetRequired(); 12015 if (offsetRequired) { 12016 paddingLeft += getLeftPaddingOffset(); 12017 } 12018 12019 int left = mScrollX + paddingLeft; 12020 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 12021 int top = mScrollY + getFadeTop(offsetRequired); 12022 int bottom = top + getFadeHeight(offsetRequired); 12023 12024 if (offsetRequired) { 12025 right += getRightPaddingOffset(); 12026 bottom += getBottomPaddingOffset(); 12027 } 12028 12029 final ScrollabilityCache scrollabilityCache = mScrollCache; 12030 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 12031 int length = (int) fadeHeight; 12032 12033 // clip the fade length if top and bottom fades overlap 12034 // overlapping fades produce odd-looking artifacts 12035 if (verticalEdges && (top + length > bottom - length)) { 12036 length = (bottom - top) / 2; 12037 } 12038 12039 // also clip horizontal fades if necessary 12040 if (horizontalEdges && (left + length > right - length)) { 12041 length = (right - left) / 2; 12042 } 12043 12044 if (verticalEdges) { 12045 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 12046 drawTop = topFadeStrength * fadeHeight > 1.0f; 12047 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 12048 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 12049 } 12050 12051 if (horizontalEdges) { 12052 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 12053 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 12054 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 12055 drawRight = rightFadeStrength * fadeHeight > 1.0f; 12056 } 12057 12058 saveCount = canvas.getSaveCount(); 12059 12060 int solidColor = getSolidColor(); 12061 if (solidColor == 0) { 12062 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 12063 12064 if (drawTop) { 12065 canvas.saveLayer(left, top, right, top + length, null, flags); 12066 } 12067 12068 if (drawBottom) { 12069 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 12070 } 12071 12072 if (drawLeft) { 12073 canvas.saveLayer(left, top, left + length, bottom, null, flags); 12074 } 12075 12076 if (drawRight) { 12077 canvas.saveLayer(right - length, top, right, bottom, null, flags); 12078 } 12079 } else { 12080 scrollabilityCache.setFadeColor(solidColor); 12081 } 12082 12083 // Step 3, draw the content 12084 if (!dirtyOpaque) onDraw(canvas); 12085 12086 // Step 4, draw the children 12087 dispatchDraw(canvas); 12088 12089 // Step 5, draw the fade effect and restore layers 12090 final Paint p = scrollabilityCache.paint; 12091 final Matrix matrix = scrollabilityCache.matrix; 12092 final Shader fade = scrollabilityCache.shader; 12093 12094 if (drawTop) { 12095 matrix.setScale(1, fadeHeight * topFadeStrength); 12096 matrix.postTranslate(left, top); 12097 fade.setLocalMatrix(matrix); 12098 canvas.drawRect(left, top, right, top + length, p); 12099 } 12100 12101 if (drawBottom) { 12102 matrix.setScale(1, fadeHeight * bottomFadeStrength); 12103 matrix.postRotate(180); 12104 matrix.postTranslate(left, bottom); 12105 fade.setLocalMatrix(matrix); 12106 canvas.drawRect(left, bottom - length, right, bottom, p); 12107 } 12108 12109 if (drawLeft) { 12110 matrix.setScale(1, fadeHeight * leftFadeStrength); 12111 matrix.postRotate(-90); 12112 matrix.postTranslate(left, top); 12113 fade.setLocalMatrix(matrix); 12114 canvas.drawRect(left, top, left + length, bottom, p); 12115 } 12116 12117 if (drawRight) { 12118 matrix.setScale(1, fadeHeight * rightFadeStrength); 12119 matrix.postRotate(90); 12120 matrix.postTranslate(right, top); 12121 fade.setLocalMatrix(matrix); 12122 canvas.drawRect(right - length, top, right, bottom, p); 12123 } 12124 12125 canvas.restoreToCount(saveCount); 12126 12127 // Step 6, draw decorations (scrollbars) 12128 onDrawScrollBars(canvas); 12129 } 12130 12131 /** 12132 * Override this if your view is known to always be drawn on top of a solid color background, 12133 * and needs to draw fading edges. Returning a non-zero color enables the view system to 12134 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 12135 * should be set to 0xFF. 12136 * 12137 * @see #setVerticalFadingEdgeEnabled(boolean) 12138 * @see #setHorizontalFadingEdgeEnabled(boolean) 12139 * 12140 * @return The known solid color background for this view, or 0 if the color may vary 12141 */ 12142 @ViewDebug.ExportedProperty(category = "drawing") 12143 public int getSolidColor() { 12144 return 0; 12145 } 12146 12147 /** 12148 * Build a human readable string representation of the specified view flags. 12149 * 12150 * @param flags the view flags to convert to a string 12151 * @return a String representing the supplied flags 12152 */ 12153 private static String printFlags(int flags) { 12154 String output = ""; 12155 int numFlags = 0; 12156 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 12157 output += "TAKES_FOCUS"; 12158 numFlags++; 12159 } 12160 12161 switch (flags & VISIBILITY_MASK) { 12162 case INVISIBLE: 12163 if (numFlags > 0) { 12164 output += " "; 12165 } 12166 output += "INVISIBLE"; 12167 // USELESS HERE numFlags++; 12168 break; 12169 case GONE: 12170 if (numFlags > 0) { 12171 output += " "; 12172 } 12173 output += "GONE"; 12174 // USELESS HERE numFlags++; 12175 break; 12176 default: 12177 break; 12178 } 12179 return output; 12180 } 12181 12182 /** 12183 * Build a human readable string representation of the specified private 12184 * view flags. 12185 * 12186 * @param privateFlags the private view flags to convert to a string 12187 * @return a String representing the supplied flags 12188 */ 12189 private static String printPrivateFlags(int privateFlags) { 12190 String output = ""; 12191 int numFlags = 0; 12192 12193 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 12194 output += "WANTS_FOCUS"; 12195 numFlags++; 12196 } 12197 12198 if ((privateFlags & FOCUSED) == FOCUSED) { 12199 if (numFlags > 0) { 12200 output += " "; 12201 } 12202 output += "FOCUSED"; 12203 numFlags++; 12204 } 12205 12206 if ((privateFlags & SELECTED) == SELECTED) { 12207 if (numFlags > 0) { 12208 output += " "; 12209 } 12210 output += "SELECTED"; 12211 numFlags++; 12212 } 12213 12214 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 12215 if (numFlags > 0) { 12216 output += " "; 12217 } 12218 output += "IS_ROOT_NAMESPACE"; 12219 numFlags++; 12220 } 12221 12222 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 12223 if (numFlags > 0) { 12224 output += " "; 12225 } 12226 output += "HAS_BOUNDS"; 12227 numFlags++; 12228 } 12229 12230 if ((privateFlags & DRAWN) == DRAWN) { 12231 if (numFlags > 0) { 12232 output += " "; 12233 } 12234 output += "DRAWN"; 12235 // USELESS HERE numFlags++; 12236 } 12237 return output; 12238 } 12239 12240 /** 12241 * <p>Indicates whether or not this view's layout will be requested during 12242 * the next hierarchy layout pass.</p> 12243 * 12244 * @return true if the layout will be forced during next layout pass 12245 */ 12246 public boolean isLayoutRequested() { 12247 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 12248 } 12249 12250 /** 12251 * Assign a size and position to a view and all of its 12252 * descendants 12253 * 12254 * <p>This is the second phase of the layout mechanism. 12255 * (The first is measuring). In this phase, each parent calls 12256 * layout on all of its children to position them. 12257 * This is typically done using the child measurements 12258 * that were stored in the measure pass().</p> 12259 * 12260 * <p>Derived classes should not override this method. 12261 * Derived classes with children should override 12262 * onLayout. In that method, they should 12263 * call layout on each of their children.</p> 12264 * 12265 * @param l Left position, relative to parent 12266 * @param t Top position, relative to parent 12267 * @param r Right position, relative to parent 12268 * @param b Bottom position, relative to parent 12269 */ 12270 @SuppressWarnings({"unchecked"}) 12271 public void layout(int l, int t, int r, int b) { 12272 int oldL = mLeft; 12273 int oldT = mTop; 12274 int oldB = mBottom; 12275 int oldR = mRight; 12276 boolean changed = setFrame(l, t, r, b); 12277 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 12278 if (ViewDebug.TRACE_HIERARCHY) { 12279 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 12280 } 12281 12282 onLayout(changed, l, t, r, b); 12283 mPrivateFlags &= ~LAYOUT_REQUIRED; 12284 12285 ListenerInfo li = mListenerInfo; 12286 if (li != null && li.mOnLayoutChangeListeners != null) { 12287 ArrayList<OnLayoutChangeListener> listenersCopy = 12288 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 12289 int numListeners = listenersCopy.size(); 12290 for (int i = 0; i < numListeners; ++i) { 12291 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 12292 } 12293 } 12294 } 12295 mPrivateFlags &= ~FORCE_LAYOUT; 12296 } 12297 12298 /** 12299 * Called from layout when this view should 12300 * assign a size and position to each of its children. 12301 * 12302 * Derived classes with children should override 12303 * this method and call layout on each of 12304 * their children. 12305 * @param changed This is a new size or position for this view 12306 * @param left Left position, relative to parent 12307 * @param top Top position, relative to parent 12308 * @param right Right position, relative to parent 12309 * @param bottom Bottom position, relative to parent 12310 */ 12311 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 12312 } 12313 12314 /** 12315 * Assign a size and position to this view. 12316 * 12317 * This is called from layout. 12318 * 12319 * @param left Left position, relative to parent 12320 * @param top Top position, relative to parent 12321 * @param right Right position, relative to parent 12322 * @param bottom Bottom position, relative to parent 12323 * @return true if the new size and position are different than the 12324 * previous ones 12325 * {@hide} 12326 */ 12327 protected boolean setFrame(int left, int top, int right, int bottom) { 12328 boolean changed = false; 12329 12330 if (DBG) { 12331 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 12332 + right + "," + bottom + ")"); 12333 } 12334 12335 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 12336 changed = true; 12337 12338 // Remember our drawn bit 12339 int drawn = mPrivateFlags & DRAWN; 12340 12341 int oldWidth = mRight - mLeft; 12342 int oldHeight = mBottom - mTop; 12343 int newWidth = right - left; 12344 int newHeight = bottom - top; 12345 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 12346 12347 // Invalidate our old position 12348 invalidate(sizeChanged); 12349 12350 mLeft = left; 12351 mTop = top; 12352 mRight = right; 12353 mBottom = bottom; 12354 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 12355 mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 12356 } 12357 12358 mPrivateFlags |= HAS_BOUNDS; 12359 12360 12361 if (sizeChanged) { 12362 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 12363 // A change in dimension means an auto-centered pivot point changes, too 12364 if (mTransformationInfo != null) { 12365 mTransformationInfo.mMatrixDirty = true; 12366 } 12367 } 12368 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 12369 } 12370 12371 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 12372 // If we are visible, force the DRAWN bit to on so that 12373 // this invalidate will go through (at least to our parent). 12374 // This is because someone may have invalidated this view 12375 // before this call to setFrame came in, thereby clearing 12376 // the DRAWN bit. 12377 mPrivateFlags |= DRAWN; 12378 invalidate(sizeChanged); 12379 // parent display list may need to be recreated based on a change in the bounds 12380 // of any child 12381 invalidateParentCaches(); 12382 } 12383 12384 // Reset drawn bit to original value (invalidate turns it off) 12385 mPrivateFlags |= drawn; 12386 12387 mBackgroundSizeChanged = true; 12388 } 12389 return changed; 12390 } 12391 12392 /** 12393 * Finalize inflating a view from XML. This is called as the last phase 12394 * of inflation, after all child views have been added. 12395 * 12396 * <p>Even if the subclass overrides onFinishInflate, they should always be 12397 * sure to call the super method, so that we get called. 12398 */ 12399 protected void onFinishInflate() { 12400 } 12401 12402 /** 12403 * Returns the resources associated with this view. 12404 * 12405 * @return Resources object. 12406 */ 12407 public Resources getResources() { 12408 return mResources; 12409 } 12410 12411 /** 12412 * Invalidates the specified Drawable. 12413 * 12414 * @param drawable the drawable to invalidate 12415 */ 12416 public void invalidateDrawable(Drawable drawable) { 12417 if (verifyDrawable(drawable)) { 12418 final Rect dirty = drawable.getBounds(); 12419 final int scrollX = mScrollX; 12420 final int scrollY = mScrollY; 12421 12422 invalidate(dirty.left + scrollX, dirty.top + scrollY, 12423 dirty.right + scrollX, dirty.bottom + scrollY); 12424 } 12425 } 12426 12427 /** 12428 * Schedules an action on a drawable to occur at a specified time. 12429 * 12430 * @param who the recipient of the action 12431 * @param what the action to run on the drawable 12432 * @param when the time at which the action must occur. Uses the 12433 * {@link SystemClock#uptimeMillis} timebase. 12434 */ 12435 public void scheduleDrawable(Drawable who, Runnable what, long when) { 12436 if (verifyDrawable(who) && what != null) { 12437 final long delay = when - SystemClock.uptimeMillis(); 12438 if (mAttachInfo != null) { 12439 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 12440 Choreographer.CALLBACK_ANIMATION, what, who, 12441 Choreographer.subtractFrameDelay(delay)); 12442 } else { 12443 ViewRootImpl.getRunQueue().postDelayed(what, delay); 12444 } 12445 } 12446 } 12447 12448 /** 12449 * Cancels a scheduled action on a drawable. 12450 * 12451 * @param who the recipient of the action 12452 * @param what the action to cancel 12453 */ 12454 public void unscheduleDrawable(Drawable who, Runnable what) { 12455 if (verifyDrawable(who) && what != null) { 12456 if (mAttachInfo != null) { 12457 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 12458 Choreographer.CALLBACK_ANIMATION, what, who); 12459 } else { 12460 ViewRootImpl.getRunQueue().removeCallbacks(what); 12461 } 12462 } 12463 } 12464 12465 /** 12466 * Unschedule any events associated with the given Drawable. This can be 12467 * used when selecting a new Drawable into a view, so that the previous 12468 * one is completely unscheduled. 12469 * 12470 * @param who The Drawable to unschedule. 12471 * 12472 * @see #drawableStateChanged 12473 */ 12474 public void unscheduleDrawable(Drawable who) { 12475 if (mAttachInfo != null && who != null) { 12476 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 12477 Choreographer.CALLBACK_ANIMATION, null, who); 12478 } 12479 } 12480 12481 /** 12482 * Return the layout direction of a given Drawable. 12483 * 12484 * @param who the Drawable to query 12485 */ 12486 public int getResolvedLayoutDirection(Drawable who) { 12487 return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT; 12488 } 12489 12490 /** 12491 * If your view subclass is displaying its own Drawable objects, it should 12492 * override this function and return true for any Drawable it is 12493 * displaying. This allows animations for those drawables to be 12494 * scheduled. 12495 * 12496 * <p>Be sure to call through to the super class when overriding this 12497 * function. 12498 * 12499 * @param who The Drawable to verify. Return true if it is one you are 12500 * displaying, else return the result of calling through to the 12501 * super class. 12502 * 12503 * @return boolean If true than the Drawable is being displayed in the 12504 * view; else false and it is not allowed to animate. 12505 * 12506 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 12507 * @see #drawableStateChanged() 12508 */ 12509 protected boolean verifyDrawable(Drawable who) { 12510 return who == mBGDrawable; 12511 } 12512 12513 /** 12514 * This function is called whenever the state of the view changes in such 12515 * a way that it impacts the state of drawables being shown. 12516 * 12517 * <p>Be sure to call through to the superclass when overriding this 12518 * function. 12519 * 12520 * @see Drawable#setState(int[]) 12521 */ 12522 protected void drawableStateChanged() { 12523 Drawable d = mBGDrawable; 12524 if (d != null && d.isStateful()) { 12525 d.setState(getDrawableState()); 12526 } 12527 } 12528 12529 /** 12530 * Call this to force a view to update its drawable state. This will cause 12531 * drawableStateChanged to be called on this view. Views that are interested 12532 * in the new state should call getDrawableState. 12533 * 12534 * @see #drawableStateChanged 12535 * @see #getDrawableState 12536 */ 12537 public void refreshDrawableState() { 12538 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 12539 drawableStateChanged(); 12540 12541 ViewParent parent = mParent; 12542 if (parent != null) { 12543 parent.childDrawableStateChanged(this); 12544 } 12545 } 12546 12547 /** 12548 * Return an array of resource IDs of the drawable states representing the 12549 * current state of the view. 12550 * 12551 * @return The current drawable state 12552 * 12553 * @see Drawable#setState(int[]) 12554 * @see #drawableStateChanged() 12555 * @see #onCreateDrawableState(int) 12556 */ 12557 public final int[] getDrawableState() { 12558 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 12559 return mDrawableState; 12560 } else { 12561 mDrawableState = onCreateDrawableState(0); 12562 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 12563 return mDrawableState; 12564 } 12565 } 12566 12567 /** 12568 * Generate the new {@link android.graphics.drawable.Drawable} state for 12569 * this view. This is called by the view 12570 * system when the cached Drawable state is determined to be invalid. To 12571 * retrieve the current state, you should use {@link #getDrawableState}. 12572 * 12573 * @param extraSpace if non-zero, this is the number of extra entries you 12574 * would like in the returned array in which you can place your own 12575 * states. 12576 * 12577 * @return Returns an array holding the current {@link Drawable} state of 12578 * the view. 12579 * 12580 * @see #mergeDrawableStates(int[], int[]) 12581 */ 12582 protected int[] onCreateDrawableState(int extraSpace) { 12583 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 12584 mParent instanceof View) { 12585 return ((View) mParent).onCreateDrawableState(extraSpace); 12586 } 12587 12588 int[] drawableState; 12589 12590 int privateFlags = mPrivateFlags; 12591 12592 int viewStateIndex = 0; 12593 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 12594 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 12595 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 12596 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 12597 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 12598 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 12599 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 12600 HardwareRenderer.isAvailable()) { 12601 // This is set if HW acceleration is requested, even if the current 12602 // process doesn't allow it. This is just to allow app preview 12603 // windows to better match their app. 12604 viewStateIndex |= VIEW_STATE_ACCELERATED; 12605 } 12606 if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 12607 12608 final int privateFlags2 = mPrivateFlags2; 12609 if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 12610 if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 12611 12612 drawableState = VIEW_STATE_SETS[viewStateIndex]; 12613 12614 //noinspection ConstantIfStatement 12615 if (false) { 12616 Log.i("View", "drawableStateIndex=" + viewStateIndex); 12617 Log.i("View", toString() 12618 + " pressed=" + ((privateFlags & PRESSED) != 0) 12619 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 12620 + " fo=" + hasFocus() 12621 + " sl=" + ((privateFlags & SELECTED) != 0) 12622 + " wf=" + hasWindowFocus() 12623 + ": " + Arrays.toString(drawableState)); 12624 } 12625 12626 if (extraSpace == 0) { 12627 return drawableState; 12628 } 12629 12630 final int[] fullState; 12631 if (drawableState != null) { 12632 fullState = new int[drawableState.length + extraSpace]; 12633 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 12634 } else { 12635 fullState = new int[extraSpace]; 12636 } 12637 12638 return fullState; 12639 } 12640 12641 /** 12642 * Merge your own state values in <var>additionalState</var> into the base 12643 * state values <var>baseState</var> that were returned by 12644 * {@link #onCreateDrawableState(int)}. 12645 * 12646 * @param baseState The base state values returned by 12647 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 12648 * own additional state values. 12649 * 12650 * @param additionalState The additional state values you would like 12651 * added to <var>baseState</var>; this array is not modified. 12652 * 12653 * @return As a convenience, the <var>baseState</var> array you originally 12654 * passed into the function is returned. 12655 * 12656 * @see #onCreateDrawableState(int) 12657 */ 12658 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 12659 final int N = baseState.length; 12660 int i = N - 1; 12661 while (i >= 0 && baseState[i] == 0) { 12662 i--; 12663 } 12664 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 12665 return baseState; 12666 } 12667 12668 /** 12669 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 12670 * on all Drawable objects associated with this view. 12671 */ 12672 public void jumpDrawablesToCurrentState() { 12673 if (mBGDrawable != null) { 12674 mBGDrawable.jumpToCurrentState(); 12675 } 12676 } 12677 12678 /** 12679 * Sets the background color for this view. 12680 * @param color the color of the background 12681 */ 12682 @RemotableViewMethod 12683 public void setBackgroundColor(int color) { 12684 if (mBGDrawable instanceof ColorDrawable) { 12685 ((ColorDrawable) mBGDrawable).setColor(color); 12686 } else { 12687 setBackgroundDrawable(new ColorDrawable(color)); 12688 } 12689 } 12690 12691 /** 12692 * Set the background to a given resource. The resource should refer to 12693 * a Drawable object or 0 to remove the background. 12694 * @param resid The identifier of the resource. 12695 * @attr ref android.R.styleable#View_background 12696 */ 12697 @RemotableViewMethod 12698 public void setBackgroundResource(int resid) { 12699 if (resid != 0 && resid == mBackgroundResource) { 12700 return; 12701 } 12702 12703 Drawable d= null; 12704 if (resid != 0) { 12705 d = mResources.getDrawable(resid); 12706 } 12707 setBackgroundDrawable(d); 12708 12709 mBackgroundResource = resid; 12710 } 12711 12712 /** 12713 * Set the background to a given Drawable, or remove the background. If the 12714 * background has padding, this View's padding is set to the background's 12715 * padding. However, when a background is removed, this View's padding isn't 12716 * touched. If setting the padding is desired, please use 12717 * {@link #setPadding(int, int, int, int)}. 12718 * 12719 * @param d The Drawable to use as the background, or null to remove the 12720 * background 12721 */ 12722 public void setBackgroundDrawable(Drawable d) { 12723 if (d == mBGDrawable) { 12724 return; 12725 } 12726 12727 boolean requestLayout = false; 12728 12729 mBackgroundResource = 0; 12730 12731 /* 12732 * Regardless of whether we're setting a new background or not, we want 12733 * to clear the previous drawable. 12734 */ 12735 if (mBGDrawable != null) { 12736 mBGDrawable.setCallback(null); 12737 unscheduleDrawable(mBGDrawable); 12738 } 12739 12740 if (d != null) { 12741 Rect padding = sThreadLocal.get(); 12742 if (padding == null) { 12743 padding = new Rect(); 12744 sThreadLocal.set(padding); 12745 } 12746 if (d.getPadding(padding)) { 12747 switch (d.getResolvedLayoutDirectionSelf()) { 12748 case LAYOUT_DIRECTION_RTL: 12749 setPadding(padding.right, padding.top, padding.left, padding.bottom); 12750 break; 12751 case LAYOUT_DIRECTION_LTR: 12752 default: 12753 setPadding(padding.left, padding.top, padding.right, padding.bottom); 12754 } 12755 } 12756 12757 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 12758 // if it has a different minimum size, we should layout again 12759 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 12760 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 12761 requestLayout = true; 12762 } 12763 12764 d.setCallback(this); 12765 if (d.isStateful()) { 12766 d.setState(getDrawableState()); 12767 } 12768 d.setVisible(getVisibility() == VISIBLE, false); 12769 mBGDrawable = d; 12770 12771 if ((mPrivateFlags & SKIP_DRAW) != 0) { 12772 mPrivateFlags &= ~SKIP_DRAW; 12773 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 12774 requestLayout = true; 12775 } 12776 } else { 12777 /* Remove the background */ 12778 mBGDrawable = null; 12779 12780 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 12781 /* 12782 * This view ONLY drew the background before and we're removing 12783 * the background, so now it won't draw anything 12784 * (hence we SKIP_DRAW) 12785 */ 12786 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 12787 mPrivateFlags |= SKIP_DRAW; 12788 } 12789 12790 /* 12791 * When the background is set, we try to apply its padding to this 12792 * View. When the background is removed, we don't touch this View's 12793 * padding. This is noted in the Javadocs. Hence, we don't need to 12794 * requestLayout(), the invalidate() below is sufficient. 12795 */ 12796 12797 // The old background's minimum size could have affected this 12798 // View's layout, so let's requestLayout 12799 requestLayout = true; 12800 } 12801 12802 computeOpaqueFlags(); 12803 12804 if (requestLayout) { 12805 requestLayout(); 12806 } 12807 12808 mBackgroundSizeChanged = true; 12809 invalidate(true); 12810 } 12811 12812 /** 12813 * Gets the background drawable 12814 * @return The drawable used as the background for this view, if any. 12815 */ 12816 public Drawable getBackground() { 12817 return mBGDrawable; 12818 } 12819 12820 /** 12821 * Sets the padding. The view may add on the space required to display 12822 * the scrollbars, depending on the style and visibility of the scrollbars. 12823 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 12824 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 12825 * from the values set in this call. 12826 * 12827 * @attr ref android.R.styleable#View_padding 12828 * @attr ref android.R.styleable#View_paddingBottom 12829 * @attr ref android.R.styleable#View_paddingLeft 12830 * @attr ref android.R.styleable#View_paddingRight 12831 * @attr ref android.R.styleable#View_paddingTop 12832 * @param left the left padding in pixels 12833 * @param top the top padding in pixels 12834 * @param right the right padding in pixels 12835 * @param bottom the bottom padding in pixels 12836 */ 12837 public void setPadding(int left, int top, int right, int bottom) { 12838 mUserPaddingStart = -1; 12839 mUserPaddingEnd = -1; 12840 mUserPaddingRelative = false; 12841 12842 internalSetPadding(left, top, right, bottom); 12843 } 12844 12845 private void internalSetPadding(int left, int top, int right, int bottom) { 12846 mUserPaddingLeft = left; 12847 mUserPaddingRight = right; 12848 mUserPaddingBottom = bottom; 12849 12850 final int viewFlags = mViewFlags; 12851 boolean changed = false; 12852 12853 // Common case is there are no scroll bars. 12854 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 12855 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 12856 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 12857 ? 0 : getVerticalScrollbarWidth(); 12858 switch (mVerticalScrollbarPosition) { 12859 case SCROLLBAR_POSITION_DEFAULT: 12860 if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12861 left += offset; 12862 } else { 12863 right += offset; 12864 } 12865 break; 12866 case SCROLLBAR_POSITION_RIGHT: 12867 right += offset; 12868 break; 12869 case SCROLLBAR_POSITION_LEFT: 12870 left += offset; 12871 break; 12872 } 12873 } 12874 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 12875 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 12876 ? 0 : getHorizontalScrollbarHeight(); 12877 } 12878 } 12879 12880 if (mPaddingLeft != left) { 12881 changed = true; 12882 mPaddingLeft = left; 12883 } 12884 if (mPaddingTop != top) { 12885 changed = true; 12886 mPaddingTop = top; 12887 } 12888 if (mPaddingRight != right) { 12889 changed = true; 12890 mPaddingRight = right; 12891 } 12892 if (mPaddingBottom != bottom) { 12893 changed = true; 12894 mPaddingBottom = bottom; 12895 } 12896 12897 if (changed) { 12898 requestLayout(); 12899 } 12900 } 12901 12902 /** 12903 * Sets the relative padding. The view may add on the space required to display 12904 * the scrollbars, depending on the style and visibility of the scrollbars. 12905 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 12906 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 12907 * from the values set in this call. 12908 * 12909 * @attr ref android.R.styleable#View_padding 12910 * @attr ref android.R.styleable#View_paddingBottom 12911 * @attr ref android.R.styleable#View_paddingStart 12912 * @attr ref android.R.styleable#View_paddingEnd 12913 * @attr ref android.R.styleable#View_paddingTop 12914 * @param start the start padding in pixels 12915 * @param top the top padding in pixels 12916 * @param end the end padding in pixels 12917 * @param bottom the bottom padding in pixels 12918 */ 12919 public void setPaddingRelative(int start, int top, int end, int bottom) { 12920 mUserPaddingStart = start; 12921 mUserPaddingEnd = end; 12922 mUserPaddingRelative = true; 12923 12924 switch(getResolvedLayoutDirection()) { 12925 case LAYOUT_DIRECTION_RTL: 12926 internalSetPadding(end, top, start, bottom); 12927 break; 12928 case LAYOUT_DIRECTION_LTR: 12929 default: 12930 internalSetPadding(start, top, end, bottom); 12931 } 12932 } 12933 12934 /** 12935 * Returns the top padding of this view. 12936 * 12937 * @return the top padding in pixels 12938 */ 12939 public int getPaddingTop() { 12940 return mPaddingTop; 12941 } 12942 12943 /** 12944 * Returns the bottom padding of this view. If there are inset and enabled 12945 * scrollbars, this value may include the space required to display the 12946 * scrollbars as well. 12947 * 12948 * @return the bottom padding in pixels 12949 */ 12950 public int getPaddingBottom() { 12951 return mPaddingBottom; 12952 } 12953 12954 /** 12955 * Returns the left padding of this view. If there are inset and enabled 12956 * scrollbars, this value may include the space required to display the 12957 * scrollbars as well. 12958 * 12959 * @return the left padding in pixels 12960 */ 12961 public int getPaddingLeft() { 12962 return mPaddingLeft; 12963 } 12964 12965 /** 12966 * Returns the start padding of this view depending on its resolved layout direction. 12967 * If there are inset and enabled scrollbars, this value may include the space 12968 * required to display the scrollbars as well. 12969 * 12970 * @return the start padding in pixels 12971 */ 12972 public int getPaddingStart() { 12973 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 12974 mPaddingRight : mPaddingLeft; 12975 } 12976 12977 /** 12978 * Returns the right padding of this view. If there are inset and enabled 12979 * scrollbars, this value may include the space required to display the 12980 * scrollbars as well. 12981 * 12982 * @return the right padding in pixels 12983 */ 12984 public int getPaddingRight() { 12985 return mPaddingRight; 12986 } 12987 12988 /** 12989 * Returns the end padding of this view depending on its resolved layout direction. 12990 * If there are inset and enabled scrollbars, this value may include the space 12991 * required to display the scrollbars as well. 12992 * 12993 * @return the end padding in pixels 12994 */ 12995 public int getPaddingEnd() { 12996 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 12997 mPaddingLeft : mPaddingRight; 12998 } 12999 13000 /** 13001 * Return if the padding as been set thru relative values 13002 * {@link #setPaddingRelative(int, int, int, int)} or thru 13003 * @attr ref android.R.styleable#View_paddingStart or 13004 * @attr ref android.R.styleable#View_paddingEnd 13005 * 13006 * @return true if the padding is relative or false if it is not. 13007 */ 13008 public boolean isPaddingRelative() { 13009 return mUserPaddingRelative; 13010 } 13011 13012 /** 13013 * Changes the selection state of this view. A view can be selected or not. 13014 * Note that selection is not the same as focus. Views are typically 13015 * selected in the context of an AdapterView like ListView or GridView; 13016 * the selected view is the view that is highlighted. 13017 * 13018 * @param selected true if the view must be selected, false otherwise 13019 */ 13020 public void setSelected(boolean selected) { 13021 if (((mPrivateFlags & SELECTED) != 0) != selected) { 13022 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 13023 if (!selected) resetPressedState(); 13024 invalidate(true); 13025 refreshDrawableState(); 13026 dispatchSetSelected(selected); 13027 } 13028 } 13029 13030 /** 13031 * Dispatch setSelected to all of this View's children. 13032 * 13033 * @see #setSelected(boolean) 13034 * 13035 * @param selected The new selected state 13036 */ 13037 protected void dispatchSetSelected(boolean selected) { 13038 } 13039 13040 /** 13041 * Indicates the selection state of this view. 13042 * 13043 * @return true if the view is selected, false otherwise 13044 */ 13045 @ViewDebug.ExportedProperty 13046 public boolean isSelected() { 13047 return (mPrivateFlags & SELECTED) != 0; 13048 } 13049 13050 /** 13051 * Changes the activated state of this view. A view can be activated or not. 13052 * Note that activation is not the same as selection. Selection is 13053 * a transient property, representing the view (hierarchy) the user is 13054 * currently interacting with. Activation is a longer-term state that the 13055 * user can move views in and out of. For example, in a list view with 13056 * single or multiple selection enabled, the views in the current selection 13057 * set are activated. (Um, yeah, we are deeply sorry about the terminology 13058 * here.) The activated state is propagated down to children of the view it 13059 * is set on. 13060 * 13061 * @param activated true if the view must be activated, false otherwise 13062 */ 13063 public void setActivated(boolean activated) { 13064 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 13065 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 13066 invalidate(true); 13067 refreshDrawableState(); 13068 dispatchSetActivated(activated); 13069 } 13070 } 13071 13072 /** 13073 * Dispatch setActivated to all of this View's children. 13074 * 13075 * @see #setActivated(boolean) 13076 * 13077 * @param activated The new activated state 13078 */ 13079 protected void dispatchSetActivated(boolean activated) { 13080 } 13081 13082 /** 13083 * Indicates the activation state of this view. 13084 * 13085 * @return true if the view is activated, false otherwise 13086 */ 13087 @ViewDebug.ExportedProperty 13088 public boolean isActivated() { 13089 return (mPrivateFlags & ACTIVATED) != 0; 13090 } 13091 13092 /** 13093 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 13094 * observer can be used to get notifications when global events, like 13095 * layout, happen. 13096 * 13097 * The returned ViewTreeObserver observer is not guaranteed to remain 13098 * valid for the lifetime of this View. If the caller of this method keeps 13099 * a long-lived reference to ViewTreeObserver, it should always check for 13100 * the return value of {@link ViewTreeObserver#isAlive()}. 13101 * 13102 * @return The ViewTreeObserver for this view's hierarchy. 13103 */ 13104 public ViewTreeObserver getViewTreeObserver() { 13105 if (mAttachInfo != null) { 13106 return mAttachInfo.mTreeObserver; 13107 } 13108 if (mFloatingTreeObserver == null) { 13109 mFloatingTreeObserver = new ViewTreeObserver(); 13110 } 13111 return mFloatingTreeObserver; 13112 } 13113 13114 /** 13115 * <p>Finds the topmost view in the current view hierarchy.</p> 13116 * 13117 * @return the topmost view containing this view 13118 */ 13119 public View getRootView() { 13120 if (mAttachInfo != null) { 13121 final View v = mAttachInfo.mRootView; 13122 if (v != null) { 13123 return v; 13124 } 13125 } 13126 13127 View parent = this; 13128 13129 while (parent.mParent != null && parent.mParent instanceof View) { 13130 parent = (View) parent.mParent; 13131 } 13132 13133 return parent; 13134 } 13135 13136 /** 13137 * <p>Computes the coordinates of this view on the screen. The argument 13138 * must be an array of two integers. After the method returns, the array 13139 * contains the x and y location in that order.</p> 13140 * 13141 * @param location an array of two integers in which to hold the coordinates 13142 */ 13143 public void getLocationOnScreen(int[] location) { 13144 getLocationInWindow(location); 13145 13146 final AttachInfo info = mAttachInfo; 13147 if (info != null) { 13148 location[0] += info.mWindowLeft; 13149 location[1] += info.mWindowTop; 13150 } 13151 } 13152 13153 /** 13154 * <p>Computes the coordinates of this view in its window. The argument 13155 * must be an array of two integers. After the method returns, the array 13156 * contains the x and y location in that order.</p> 13157 * 13158 * @param location an array of two integers in which to hold the coordinates 13159 */ 13160 public void getLocationInWindow(int[] location) { 13161 if (location == null || location.length < 2) { 13162 throw new IllegalArgumentException("location must be an array of two integers"); 13163 } 13164 13165 if (mAttachInfo == null) { 13166 // When the view is not attached to a window, this method does not make sense 13167 location[0] = location[1] = 0; 13168 return; 13169 } 13170 13171 float[] position = mAttachInfo.mTmpTransformLocation; 13172 position[0] = position[1] = 0.0f; 13173 13174 if (!hasIdentityMatrix()) { 13175 getMatrix().mapPoints(position); 13176 } 13177 13178 position[0] += mLeft; 13179 position[1] += mTop; 13180 13181 ViewParent viewParent = mParent; 13182 while (viewParent instanceof View) { 13183 final View view = (View) viewParent; 13184 13185 position[0] -= view.mScrollX; 13186 position[1] -= view.mScrollY; 13187 13188 if (!view.hasIdentityMatrix()) { 13189 view.getMatrix().mapPoints(position); 13190 } 13191 13192 position[0] += view.mLeft; 13193 position[1] += view.mTop; 13194 13195 viewParent = view.mParent; 13196 } 13197 13198 if (viewParent instanceof ViewRootImpl) { 13199 // *cough* 13200 final ViewRootImpl vr = (ViewRootImpl) viewParent; 13201 position[1] -= vr.mCurScrollY; 13202 } 13203 13204 location[0] = (int) (position[0] + 0.5f); 13205 location[1] = (int) (position[1] + 0.5f); 13206 } 13207 13208 /** 13209 * {@hide} 13210 * @param id the id of the view to be found 13211 * @return the view of the specified id, null if cannot be found 13212 */ 13213 protected View findViewTraversal(int id) { 13214 if (id == mID) { 13215 return this; 13216 } 13217 return null; 13218 } 13219 13220 /** 13221 * {@hide} 13222 * @param tag the tag of the view to be found 13223 * @return the view of specified tag, null if cannot be found 13224 */ 13225 protected View findViewWithTagTraversal(Object tag) { 13226 if (tag != null && tag.equals(mTag)) { 13227 return this; 13228 } 13229 return null; 13230 } 13231 13232 /** 13233 * {@hide} 13234 * @param predicate The predicate to evaluate. 13235 * @param childToSkip If not null, ignores this child during the recursive traversal. 13236 * @return The first view that matches the predicate or null. 13237 */ 13238 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 13239 if (predicate.apply(this)) { 13240 return this; 13241 } 13242 return null; 13243 } 13244 13245 /** 13246 * Look for a child view with the given id. If this view has the given 13247 * id, return this view. 13248 * 13249 * @param id The id to search for. 13250 * @return The view that has the given id in the hierarchy or null 13251 */ 13252 public final View findViewById(int id) { 13253 if (id < 0) { 13254 return null; 13255 } 13256 return findViewTraversal(id); 13257 } 13258 13259 /** 13260 * Finds a view by its unuque and stable accessibility id. 13261 * 13262 * @param accessibilityId The searched accessibility id. 13263 * @return The found view. 13264 */ 13265 final View findViewByAccessibilityId(int accessibilityId) { 13266 if (accessibilityId < 0) { 13267 return null; 13268 } 13269 return findViewByAccessibilityIdTraversal(accessibilityId); 13270 } 13271 13272 /** 13273 * Performs the traversal to find a view by its unuque and stable accessibility id. 13274 * 13275 * <strong>Note:</strong>This method does not stop at the root namespace 13276 * boundary since the user can touch the screen at an arbitrary location 13277 * potentially crossing the root namespace bounday which will send an 13278 * accessibility event to accessibility services and they should be able 13279 * to obtain the event source. Also accessibility ids are guaranteed to be 13280 * unique in the window. 13281 * 13282 * @param accessibilityId The accessibility id. 13283 * @return The found view. 13284 */ 13285 View findViewByAccessibilityIdTraversal(int accessibilityId) { 13286 if (getAccessibilityViewId() == accessibilityId) { 13287 return this; 13288 } 13289 return null; 13290 } 13291 13292 /** 13293 * Look for a child view with the given tag. If this view has the given 13294 * tag, return this view. 13295 * 13296 * @param tag The tag to search for, using "tag.equals(getTag())". 13297 * @return The View that has the given tag in the hierarchy or null 13298 */ 13299 public final View findViewWithTag(Object tag) { 13300 if (tag == null) { 13301 return null; 13302 } 13303 return findViewWithTagTraversal(tag); 13304 } 13305 13306 /** 13307 * {@hide} 13308 * Look for a child view that matches the specified predicate. 13309 * If this view matches the predicate, return this view. 13310 * 13311 * @param predicate The predicate to evaluate. 13312 * @return The first view that matches the predicate or null. 13313 */ 13314 public final View findViewByPredicate(Predicate<View> predicate) { 13315 return findViewByPredicateTraversal(predicate, null); 13316 } 13317 13318 /** 13319 * {@hide} 13320 * Look for a child view that matches the specified predicate, 13321 * starting with the specified view and its descendents and then 13322 * recusively searching the ancestors and siblings of that view 13323 * until this view is reached. 13324 * 13325 * This method is useful in cases where the predicate does not match 13326 * a single unique view (perhaps multiple views use the same id) 13327 * and we are trying to find the view that is "closest" in scope to the 13328 * starting view. 13329 * 13330 * @param start The view to start from. 13331 * @param predicate The predicate to evaluate. 13332 * @return The first view that matches the predicate or null. 13333 */ 13334 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 13335 View childToSkip = null; 13336 for (;;) { 13337 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 13338 if (view != null || start == this) { 13339 return view; 13340 } 13341 13342 ViewParent parent = start.getParent(); 13343 if (parent == null || !(parent instanceof View)) { 13344 return null; 13345 } 13346 13347 childToSkip = start; 13348 start = (View) parent; 13349 } 13350 } 13351 13352 /** 13353 * Sets the identifier for this view. The identifier does not have to be 13354 * unique in this view's hierarchy. The identifier should be a positive 13355 * number. 13356 * 13357 * @see #NO_ID 13358 * @see #getId() 13359 * @see #findViewById(int) 13360 * 13361 * @param id a number used to identify the view 13362 * 13363 * @attr ref android.R.styleable#View_id 13364 */ 13365 public void setId(int id) { 13366 mID = id; 13367 } 13368 13369 /** 13370 * {@hide} 13371 * 13372 * @param isRoot true if the view belongs to the root namespace, false 13373 * otherwise 13374 */ 13375 public void setIsRootNamespace(boolean isRoot) { 13376 if (isRoot) { 13377 mPrivateFlags |= IS_ROOT_NAMESPACE; 13378 } else { 13379 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 13380 } 13381 } 13382 13383 /** 13384 * {@hide} 13385 * 13386 * @return true if the view belongs to the root namespace, false otherwise 13387 */ 13388 public boolean isRootNamespace() { 13389 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 13390 } 13391 13392 /** 13393 * Returns this view's identifier. 13394 * 13395 * @return a positive integer used to identify the view or {@link #NO_ID} 13396 * if the view has no ID 13397 * 13398 * @see #setId(int) 13399 * @see #findViewById(int) 13400 * @attr ref android.R.styleable#View_id 13401 */ 13402 @ViewDebug.CapturedViewProperty 13403 public int getId() { 13404 return mID; 13405 } 13406 13407 /** 13408 * Returns this view's tag. 13409 * 13410 * @return the Object stored in this view as a tag 13411 * 13412 * @see #setTag(Object) 13413 * @see #getTag(int) 13414 */ 13415 @ViewDebug.ExportedProperty 13416 public Object getTag() { 13417 return mTag; 13418 } 13419 13420 /** 13421 * Sets the tag associated with this view. A tag can be used to mark 13422 * a view in its hierarchy and does not have to be unique within the 13423 * hierarchy. Tags can also be used to store data within a view without 13424 * resorting to another data structure. 13425 * 13426 * @param tag an Object to tag the view with 13427 * 13428 * @see #getTag() 13429 * @see #setTag(int, Object) 13430 */ 13431 public void setTag(final Object tag) { 13432 mTag = tag; 13433 } 13434 13435 /** 13436 * Returns the tag associated with this view and the specified key. 13437 * 13438 * @param key The key identifying the tag 13439 * 13440 * @return the Object stored in this view as a tag 13441 * 13442 * @see #setTag(int, Object) 13443 * @see #getTag() 13444 */ 13445 public Object getTag(int key) { 13446 if (mKeyedTags != null) return mKeyedTags.get(key); 13447 return null; 13448 } 13449 13450 /** 13451 * Sets a tag associated with this view and a key. A tag can be used 13452 * to mark a view in its hierarchy and does not have to be unique within 13453 * the hierarchy. Tags can also be used to store data within a view 13454 * without resorting to another data structure. 13455 * 13456 * The specified key should be an id declared in the resources of the 13457 * application to ensure it is unique (see the <a 13458 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 13459 * Keys identified as belonging to 13460 * the Android framework or not associated with any package will cause 13461 * an {@link IllegalArgumentException} to be thrown. 13462 * 13463 * @param key The key identifying the tag 13464 * @param tag An Object to tag the view with 13465 * 13466 * @throws IllegalArgumentException If they specified key is not valid 13467 * 13468 * @see #setTag(Object) 13469 * @see #getTag(int) 13470 */ 13471 public void setTag(int key, final Object tag) { 13472 // If the package id is 0x00 or 0x01, it's either an undefined package 13473 // or a framework id 13474 if ((key >>> 24) < 2) { 13475 throw new IllegalArgumentException("The key must be an application-specific " 13476 + "resource id."); 13477 } 13478 13479 setKeyedTag(key, tag); 13480 } 13481 13482 /** 13483 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 13484 * framework id. 13485 * 13486 * @hide 13487 */ 13488 public void setTagInternal(int key, Object tag) { 13489 if ((key >>> 24) != 0x1) { 13490 throw new IllegalArgumentException("The key must be a framework-specific " 13491 + "resource id."); 13492 } 13493 13494 setKeyedTag(key, tag); 13495 } 13496 13497 private void setKeyedTag(int key, Object tag) { 13498 if (mKeyedTags == null) { 13499 mKeyedTags = new SparseArray<Object>(); 13500 } 13501 13502 mKeyedTags.put(key, tag); 13503 } 13504 13505 /** 13506 * @param consistency The type of consistency. See ViewDebug for more information. 13507 * 13508 * @hide 13509 */ 13510 protected boolean dispatchConsistencyCheck(int consistency) { 13511 return onConsistencyCheck(consistency); 13512 } 13513 13514 /** 13515 * Method that subclasses should implement to check their consistency. The type of 13516 * consistency check is indicated by the bit field passed as a parameter. 13517 * 13518 * @param consistency The type of consistency. See ViewDebug for more information. 13519 * 13520 * @throws IllegalStateException if the view is in an inconsistent state. 13521 * 13522 * @hide 13523 */ 13524 protected boolean onConsistencyCheck(int consistency) { 13525 boolean result = true; 13526 13527 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 13528 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 13529 13530 if (checkLayout) { 13531 if (getParent() == null) { 13532 result = false; 13533 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 13534 "View " + this + " does not have a parent."); 13535 } 13536 13537 if (mAttachInfo == null) { 13538 result = false; 13539 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 13540 "View " + this + " is not attached to a window."); 13541 } 13542 } 13543 13544 if (checkDrawing) { 13545 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 13546 // from their draw() method 13547 13548 if ((mPrivateFlags & DRAWN) != DRAWN && 13549 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 13550 result = false; 13551 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 13552 "View " + this + " was invalidated but its drawing cache is valid."); 13553 } 13554 } 13555 13556 return result; 13557 } 13558 13559 /** 13560 * Prints information about this view in the log output, with the tag 13561 * {@link #VIEW_LOG_TAG}. 13562 * 13563 * @hide 13564 */ 13565 public void debug() { 13566 debug(0); 13567 } 13568 13569 /** 13570 * Prints information about this view in the log output, with the tag 13571 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 13572 * indentation defined by the <code>depth</code>. 13573 * 13574 * @param depth the indentation level 13575 * 13576 * @hide 13577 */ 13578 protected void debug(int depth) { 13579 String output = debugIndent(depth - 1); 13580 13581 output += "+ " + this; 13582 int id = getId(); 13583 if (id != -1) { 13584 output += " (id=" + id + ")"; 13585 } 13586 Object tag = getTag(); 13587 if (tag != null) { 13588 output += " (tag=" + tag + ")"; 13589 } 13590 Log.d(VIEW_LOG_TAG, output); 13591 13592 if ((mPrivateFlags & FOCUSED) != 0) { 13593 output = debugIndent(depth) + " FOCUSED"; 13594 Log.d(VIEW_LOG_TAG, output); 13595 } 13596 13597 output = debugIndent(depth); 13598 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 13599 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 13600 + "} "; 13601 Log.d(VIEW_LOG_TAG, output); 13602 13603 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 13604 || mPaddingBottom != 0) { 13605 output = debugIndent(depth); 13606 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 13607 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 13608 Log.d(VIEW_LOG_TAG, output); 13609 } 13610 13611 output = debugIndent(depth); 13612 output += "mMeasureWidth=" + mMeasuredWidth + 13613 " mMeasureHeight=" + mMeasuredHeight; 13614 Log.d(VIEW_LOG_TAG, output); 13615 13616 output = debugIndent(depth); 13617 if (mLayoutParams == null) { 13618 output += "BAD! no layout params"; 13619 } else { 13620 output = mLayoutParams.debug(output); 13621 } 13622 Log.d(VIEW_LOG_TAG, output); 13623 13624 output = debugIndent(depth); 13625 output += "flags={"; 13626 output += View.printFlags(mViewFlags); 13627 output += "}"; 13628 Log.d(VIEW_LOG_TAG, output); 13629 13630 output = debugIndent(depth); 13631 output += "privateFlags={"; 13632 output += View.printPrivateFlags(mPrivateFlags); 13633 output += "}"; 13634 Log.d(VIEW_LOG_TAG, output); 13635 } 13636 13637 /** 13638 * Creates a string of whitespaces used for indentation. 13639 * 13640 * @param depth the indentation level 13641 * @return a String containing (depth * 2 + 3) * 2 white spaces 13642 * 13643 * @hide 13644 */ 13645 protected static String debugIndent(int depth) { 13646 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 13647 for (int i = 0; i < (depth * 2) + 3; i++) { 13648 spaces.append(' ').append(' '); 13649 } 13650 return spaces.toString(); 13651 } 13652 13653 /** 13654 * <p>Return the offset of the widget's text baseline from the widget's top 13655 * boundary. If this widget does not support baseline alignment, this 13656 * method returns -1. </p> 13657 * 13658 * @return the offset of the baseline within the widget's bounds or -1 13659 * if baseline alignment is not supported 13660 */ 13661 @ViewDebug.ExportedProperty(category = "layout") 13662 public int getBaseline() { 13663 return -1; 13664 } 13665 13666 /** 13667 * Call this when something has changed which has invalidated the 13668 * layout of this view. This will schedule a layout pass of the view 13669 * tree. 13670 */ 13671 public void requestLayout() { 13672 if (ViewDebug.TRACE_HIERARCHY) { 13673 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 13674 } 13675 13676 mPrivateFlags |= FORCE_LAYOUT; 13677 mPrivateFlags |= INVALIDATED; 13678 13679 if (mLayoutParams != null) { 13680 mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection()); 13681 } 13682 13683 if (mParent != null && !mParent.isLayoutRequested()) { 13684 mParent.requestLayout(); 13685 } 13686 } 13687 13688 /** 13689 * Forces this view to be laid out during the next layout pass. 13690 * This method does not call requestLayout() or forceLayout() 13691 * on the parent. 13692 */ 13693 public void forceLayout() { 13694 mPrivateFlags |= FORCE_LAYOUT; 13695 mPrivateFlags |= INVALIDATED; 13696 } 13697 13698 /** 13699 * <p> 13700 * This is called to find out how big a view should be. The parent 13701 * supplies constraint information in the width and height parameters. 13702 * </p> 13703 * 13704 * <p> 13705 * The actual measurement work of a view is performed in 13706 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 13707 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 13708 * </p> 13709 * 13710 * 13711 * @param widthMeasureSpec Horizontal space requirements as imposed by the 13712 * parent 13713 * @param heightMeasureSpec Vertical space requirements as imposed by the 13714 * parent 13715 * 13716 * @see #onMeasure(int, int) 13717 */ 13718 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 13719 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 13720 widthMeasureSpec != mOldWidthMeasureSpec || 13721 heightMeasureSpec != mOldHeightMeasureSpec) { 13722 13723 // first clears the measured dimension flag 13724 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 13725 13726 if (ViewDebug.TRACE_HIERARCHY) { 13727 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 13728 } 13729 13730 // measure ourselves, this should set the measured dimension flag back 13731 onMeasure(widthMeasureSpec, heightMeasureSpec); 13732 13733 // flag not set, setMeasuredDimension() was not invoked, we raise 13734 // an exception to warn the developer 13735 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 13736 throw new IllegalStateException("onMeasure() did not set the" 13737 + " measured dimension by calling" 13738 + " setMeasuredDimension()"); 13739 } 13740 13741 mPrivateFlags |= LAYOUT_REQUIRED; 13742 } 13743 13744 mOldWidthMeasureSpec = widthMeasureSpec; 13745 mOldHeightMeasureSpec = heightMeasureSpec; 13746 } 13747 13748 /** 13749 * <p> 13750 * Measure the view and its content to determine the measured width and the 13751 * measured height. This method is invoked by {@link #measure(int, int)} and 13752 * should be overriden by subclasses to provide accurate and efficient 13753 * measurement of their contents. 13754 * </p> 13755 * 13756 * <p> 13757 * <strong>CONTRACT:</strong> When overriding this method, you 13758 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 13759 * measured width and height of this view. Failure to do so will trigger an 13760 * <code>IllegalStateException</code>, thrown by 13761 * {@link #measure(int, int)}. Calling the superclass' 13762 * {@link #onMeasure(int, int)} is a valid use. 13763 * </p> 13764 * 13765 * <p> 13766 * The base class implementation of measure defaults to the background size, 13767 * unless a larger size is allowed by the MeasureSpec. Subclasses should 13768 * override {@link #onMeasure(int, int)} to provide better measurements of 13769 * their content. 13770 * </p> 13771 * 13772 * <p> 13773 * If this method is overridden, it is the subclass's responsibility to make 13774 * sure the measured height and width are at least the view's minimum height 13775 * and width ({@link #getSuggestedMinimumHeight()} and 13776 * {@link #getSuggestedMinimumWidth()}). 13777 * </p> 13778 * 13779 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 13780 * The requirements are encoded with 13781 * {@link android.view.View.MeasureSpec}. 13782 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 13783 * The requirements are encoded with 13784 * {@link android.view.View.MeasureSpec}. 13785 * 13786 * @see #getMeasuredWidth() 13787 * @see #getMeasuredHeight() 13788 * @see #setMeasuredDimension(int, int) 13789 * @see #getSuggestedMinimumHeight() 13790 * @see #getSuggestedMinimumWidth() 13791 * @see android.view.View.MeasureSpec#getMode(int) 13792 * @see android.view.View.MeasureSpec#getSize(int) 13793 */ 13794 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 13795 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 13796 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 13797 } 13798 13799 /** 13800 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 13801 * measured width and measured height. Failing to do so will trigger an 13802 * exception at measurement time.</p> 13803 * 13804 * @param measuredWidth The measured width of this view. May be a complex 13805 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 13806 * {@link #MEASURED_STATE_TOO_SMALL}. 13807 * @param measuredHeight The measured height of this view. May be a complex 13808 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 13809 * {@link #MEASURED_STATE_TOO_SMALL}. 13810 */ 13811 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 13812 mMeasuredWidth = measuredWidth; 13813 mMeasuredHeight = measuredHeight; 13814 13815 mPrivateFlags |= MEASURED_DIMENSION_SET; 13816 } 13817 13818 /** 13819 * Merge two states as returned by {@link #getMeasuredState()}. 13820 * @param curState The current state as returned from a view or the result 13821 * of combining multiple views. 13822 * @param newState The new view state to combine. 13823 * @return Returns a new integer reflecting the combination of the two 13824 * states. 13825 */ 13826 public static int combineMeasuredStates(int curState, int newState) { 13827 return curState | newState; 13828 } 13829 13830 /** 13831 * Version of {@link #resolveSizeAndState(int, int, int)} 13832 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 13833 */ 13834 public static int resolveSize(int size, int measureSpec) { 13835 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 13836 } 13837 13838 /** 13839 * Utility to reconcile a desired size and state, with constraints imposed 13840 * by a MeasureSpec. Will take the desired size, unless a different size 13841 * is imposed by the constraints. The returned value is a compound integer, 13842 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 13843 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 13844 * size is smaller than the size the view wants to be. 13845 * 13846 * @param size How big the view wants to be 13847 * @param measureSpec Constraints imposed by the parent 13848 * @return Size information bit mask as defined by 13849 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 13850 */ 13851 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 13852 int result = size; 13853 int specMode = MeasureSpec.getMode(measureSpec); 13854 int specSize = MeasureSpec.getSize(measureSpec); 13855 switch (specMode) { 13856 case MeasureSpec.UNSPECIFIED: 13857 result = size; 13858 break; 13859 case MeasureSpec.AT_MOST: 13860 if (specSize < size) { 13861 result = specSize | MEASURED_STATE_TOO_SMALL; 13862 } else { 13863 result = size; 13864 } 13865 break; 13866 case MeasureSpec.EXACTLY: 13867 result = specSize; 13868 break; 13869 } 13870 return result | (childMeasuredState&MEASURED_STATE_MASK); 13871 } 13872 13873 /** 13874 * Utility to return a default size. Uses the supplied size if the 13875 * MeasureSpec imposed no constraints. Will get larger if allowed 13876 * by the MeasureSpec. 13877 * 13878 * @param size Default size for this view 13879 * @param measureSpec Constraints imposed by the parent 13880 * @return The size this view should be. 13881 */ 13882 public static int getDefaultSize(int size, int measureSpec) { 13883 int result = size; 13884 int specMode = MeasureSpec.getMode(measureSpec); 13885 int specSize = MeasureSpec.getSize(measureSpec); 13886 13887 switch (specMode) { 13888 case MeasureSpec.UNSPECIFIED: 13889 result = size; 13890 break; 13891 case MeasureSpec.AT_MOST: 13892 case MeasureSpec.EXACTLY: 13893 result = specSize; 13894 break; 13895 } 13896 return result; 13897 } 13898 13899 /** 13900 * Returns the suggested minimum height that the view should use. This 13901 * returns the maximum of the view's minimum height 13902 * and the background's minimum height 13903 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 13904 * <p> 13905 * When being used in {@link #onMeasure(int, int)}, the caller should still 13906 * ensure the returned height is within the requirements of the parent. 13907 * 13908 * @return The suggested minimum height of the view. 13909 */ 13910 protected int getSuggestedMinimumHeight() { 13911 int suggestedMinHeight = mMinHeight; 13912 13913 if (mBGDrawable != null) { 13914 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 13915 if (suggestedMinHeight < bgMinHeight) { 13916 suggestedMinHeight = bgMinHeight; 13917 } 13918 } 13919 13920 return suggestedMinHeight; 13921 } 13922 13923 /** 13924 * Returns the suggested minimum width that the view should use. This 13925 * returns the maximum of the view's minimum width) 13926 * and the background's minimum width 13927 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 13928 * <p> 13929 * When being used in {@link #onMeasure(int, int)}, the caller should still 13930 * ensure the returned width is within the requirements of the parent. 13931 * 13932 * @return The suggested minimum width of the view. 13933 */ 13934 protected int getSuggestedMinimumWidth() { 13935 int suggestedMinWidth = mMinWidth; 13936 13937 if (mBGDrawable != null) { 13938 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 13939 if (suggestedMinWidth < bgMinWidth) { 13940 suggestedMinWidth = bgMinWidth; 13941 } 13942 } 13943 13944 return suggestedMinWidth; 13945 } 13946 13947 /** 13948 * Sets the minimum height of the view. It is not guaranteed the view will 13949 * be able to achieve this minimum height (for example, if its parent layout 13950 * constrains it with less available height). 13951 * 13952 * @param minHeight The minimum height the view will try to be. 13953 */ 13954 public void setMinimumHeight(int minHeight) { 13955 mMinHeight = minHeight; 13956 } 13957 13958 /** 13959 * Sets the minimum width of the view. It is not guaranteed the view will 13960 * be able to achieve this minimum width (for example, if its parent layout 13961 * constrains it with less available width). 13962 * 13963 * @param minWidth The minimum width the view will try to be. 13964 */ 13965 public void setMinimumWidth(int minWidth) { 13966 mMinWidth = minWidth; 13967 } 13968 13969 /** 13970 * Get the animation currently associated with this view. 13971 * 13972 * @return The animation that is currently playing or 13973 * scheduled to play for this view. 13974 */ 13975 public Animation getAnimation() { 13976 return mCurrentAnimation; 13977 } 13978 13979 /** 13980 * Start the specified animation now. 13981 * 13982 * @param animation the animation to start now 13983 */ 13984 public void startAnimation(Animation animation) { 13985 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 13986 setAnimation(animation); 13987 invalidateParentCaches(); 13988 invalidate(true); 13989 } 13990 13991 /** 13992 * Cancels any animations for this view. 13993 */ 13994 public void clearAnimation() { 13995 if (mCurrentAnimation != null) { 13996 mCurrentAnimation.detach(); 13997 } 13998 mCurrentAnimation = null; 13999 invalidateParentIfNeeded(); 14000 } 14001 14002 /** 14003 * Sets the next animation to play for this view. 14004 * If you want the animation to play immediately, use 14005 * startAnimation. This method provides allows fine-grained 14006 * control over the start time and invalidation, but you 14007 * must make sure that 1) the animation has a start time set, and 14008 * 2) the view will be invalidated when the animation is supposed to 14009 * start. 14010 * 14011 * @param animation The next animation, or null. 14012 */ 14013 public void setAnimation(Animation animation) { 14014 mCurrentAnimation = animation; 14015 if (animation != null) { 14016 animation.reset(); 14017 } 14018 } 14019 14020 /** 14021 * Invoked by a parent ViewGroup to notify the start of the animation 14022 * currently associated with this view. If you override this method, 14023 * always call super.onAnimationStart(); 14024 * 14025 * @see #setAnimation(android.view.animation.Animation) 14026 * @see #getAnimation() 14027 */ 14028 protected void onAnimationStart() { 14029 mPrivateFlags |= ANIMATION_STARTED; 14030 } 14031 14032 /** 14033 * Invoked by a parent ViewGroup to notify the end of the animation 14034 * currently associated with this view. If you override this method, 14035 * always call super.onAnimationEnd(); 14036 * 14037 * @see #setAnimation(android.view.animation.Animation) 14038 * @see #getAnimation() 14039 */ 14040 protected void onAnimationEnd() { 14041 mPrivateFlags &= ~ANIMATION_STARTED; 14042 } 14043 14044 /** 14045 * Invoked if there is a Transform that involves alpha. Subclass that can 14046 * draw themselves with the specified alpha should return true, and then 14047 * respect that alpha when their onDraw() is called. If this returns false 14048 * then the view may be redirected to draw into an offscreen buffer to 14049 * fulfill the request, which will look fine, but may be slower than if the 14050 * subclass handles it internally. The default implementation returns false. 14051 * 14052 * @param alpha The alpha (0..255) to apply to the view's drawing 14053 * @return true if the view can draw with the specified alpha. 14054 */ 14055 protected boolean onSetAlpha(int alpha) { 14056 return false; 14057 } 14058 14059 /** 14060 * This is used by the RootView to perform an optimization when 14061 * the view hierarchy contains one or several SurfaceView. 14062 * SurfaceView is always considered transparent, but its children are not, 14063 * therefore all View objects remove themselves from the global transparent 14064 * region (passed as a parameter to this function). 14065 * 14066 * @param region The transparent region for this ViewAncestor (window). 14067 * 14068 * @return Returns true if the effective visibility of the view at this 14069 * point is opaque, regardless of the transparent region; returns false 14070 * if it is possible for underlying windows to be seen behind the view. 14071 * 14072 * {@hide} 14073 */ 14074 public boolean gatherTransparentRegion(Region region) { 14075 final AttachInfo attachInfo = mAttachInfo; 14076 if (region != null && attachInfo != null) { 14077 final int pflags = mPrivateFlags; 14078 if ((pflags & SKIP_DRAW) == 0) { 14079 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 14080 // remove it from the transparent region. 14081 final int[] location = attachInfo.mTransparentLocation; 14082 getLocationInWindow(location); 14083 region.op(location[0], location[1], location[0] + mRight - mLeft, 14084 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 14085 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 14086 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 14087 // exists, so we remove the background drawable's non-transparent 14088 // parts from this transparent region. 14089 applyDrawableToTransparentRegion(mBGDrawable, region); 14090 } 14091 } 14092 return true; 14093 } 14094 14095 /** 14096 * Play a sound effect for this view. 14097 * 14098 * <p>The framework will play sound effects for some built in actions, such as 14099 * clicking, but you may wish to play these effects in your widget, 14100 * for instance, for internal navigation. 14101 * 14102 * <p>The sound effect will only be played if sound effects are enabled by the user, and 14103 * {@link #isSoundEffectsEnabled()} is true. 14104 * 14105 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 14106 */ 14107 public void playSoundEffect(int soundConstant) { 14108 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 14109 return; 14110 } 14111 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 14112 } 14113 14114 /** 14115 * BZZZTT!!1! 14116 * 14117 * <p>Provide haptic feedback to the user for this view. 14118 * 14119 * <p>The framework will provide haptic feedback for some built in actions, 14120 * such as long presses, but you may wish to provide feedback for your 14121 * own widget. 14122 * 14123 * <p>The feedback will only be performed if 14124 * {@link #isHapticFeedbackEnabled()} is true. 14125 * 14126 * @param feedbackConstant One of the constants defined in 14127 * {@link HapticFeedbackConstants} 14128 */ 14129 public boolean performHapticFeedback(int feedbackConstant) { 14130 return performHapticFeedback(feedbackConstant, 0); 14131 } 14132 14133 /** 14134 * BZZZTT!!1! 14135 * 14136 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 14137 * 14138 * @param feedbackConstant One of the constants defined in 14139 * {@link HapticFeedbackConstants} 14140 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 14141 */ 14142 public boolean performHapticFeedback(int feedbackConstant, int flags) { 14143 if (mAttachInfo == null) { 14144 return false; 14145 } 14146 //noinspection SimplifiableIfStatement 14147 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 14148 && !isHapticFeedbackEnabled()) { 14149 return false; 14150 } 14151 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 14152 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 14153 } 14154 14155 /** 14156 * Request that the visibility of the status bar be changed. 14157 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 14158 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 14159 */ 14160 public void setSystemUiVisibility(int visibility) { 14161 if (visibility != mSystemUiVisibility) { 14162 mSystemUiVisibility = visibility; 14163 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 14164 mParent.recomputeViewAttributes(this); 14165 } 14166 } 14167 } 14168 14169 /** 14170 * Returns the status bar visibility that this view has requested. 14171 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 14172 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 14173 */ 14174 public int getSystemUiVisibility() { 14175 return mSystemUiVisibility; 14176 } 14177 14178 /** 14179 * Returns the current system UI visibility that is currently set for 14180 * the entire window. This is the combination of the 14181 * {@link #setSystemUiVisibility(int)} values supplied by all of the 14182 * views in the window. 14183 */ 14184 public int getWindowSystemUiVisibility() { 14185 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 14186 } 14187 14188 /** 14189 * Override to find out when the window's requested system UI visibility 14190 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 14191 * This is different from the callbacks recieved through 14192 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 14193 * in that this is only telling you about the local request of the window, 14194 * not the actual values applied by the system. 14195 */ 14196 public void onWindowSystemUiVisibilityChanged(int visible) { 14197 } 14198 14199 /** 14200 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 14201 * the view hierarchy. 14202 */ 14203 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 14204 onWindowSystemUiVisibilityChanged(visible); 14205 } 14206 14207 /** 14208 * Set a listener to receive callbacks when the visibility of the system bar changes. 14209 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 14210 */ 14211 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 14212 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 14213 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 14214 mParent.recomputeViewAttributes(this); 14215 } 14216 } 14217 14218 /** 14219 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 14220 * the view hierarchy. 14221 */ 14222 public void dispatchSystemUiVisibilityChanged(int visibility) { 14223 ListenerInfo li = mListenerInfo; 14224 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 14225 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 14226 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 14227 } 14228 } 14229 14230 void updateLocalSystemUiVisibility(int localValue, int localChanges) { 14231 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 14232 if (val != mSystemUiVisibility) { 14233 setSystemUiVisibility(val); 14234 } 14235 } 14236 14237 /** 14238 * Creates an image that the system displays during the drag and drop 14239 * operation. This is called a "drag shadow". The default implementation 14240 * for a DragShadowBuilder based on a View returns an image that has exactly the same 14241 * appearance as the given View. The default also positions the center of the drag shadow 14242 * directly under the touch point. If no View is provided (the constructor with no parameters 14243 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 14244 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 14245 * default is an invisible drag shadow. 14246 * <p> 14247 * You are not required to use the View you provide to the constructor as the basis of the 14248 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 14249 * anything you want as the drag shadow. 14250 * </p> 14251 * <p> 14252 * You pass a DragShadowBuilder object to the system when you start the drag. The system 14253 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 14254 * size and position of the drag shadow. It uses this data to construct a 14255 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 14256 * so that your application can draw the shadow image in the Canvas. 14257 * </p> 14258 * 14259 * <div class="special reference"> 14260 * <h3>Developer Guides</h3> 14261 * <p>For a guide to implementing drag and drop features, read the 14262 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 14263 * </div> 14264 */ 14265 public static class DragShadowBuilder { 14266 private final WeakReference<View> mView; 14267 14268 /** 14269 * Constructs a shadow image builder based on a View. By default, the resulting drag 14270 * shadow will have the same appearance and dimensions as the View, with the touch point 14271 * over the center of the View. 14272 * @param view A View. Any View in scope can be used. 14273 */ 14274 public DragShadowBuilder(View view) { 14275 mView = new WeakReference<View>(view); 14276 } 14277 14278 /** 14279 * Construct a shadow builder object with no associated View. This 14280 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 14281 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 14282 * to supply the drag shadow's dimensions and appearance without 14283 * reference to any View object. If they are not overridden, then the result is an 14284 * invisible drag shadow. 14285 */ 14286 public DragShadowBuilder() { 14287 mView = new WeakReference<View>(null); 14288 } 14289 14290 /** 14291 * Returns the View object that had been passed to the 14292 * {@link #View.DragShadowBuilder(View)} 14293 * constructor. If that View parameter was {@code null} or if the 14294 * {@link #View.DragShadowBuilder()} 14295 * constructor was used to instantiate the builder object, this method will return 14296 * null. 14297 * 14298 * @return The View object associate with this builder object. 14299 */ 14300 @SuppressWarnings({"JavadocReference"}) 14301 final public View getView() { 14302 return mView.get(); 14303 } 14304 14305 /** 14306 * Provides the metrics for the shadow image. These include the dimensions of 14307 * the shadow image, and the point within that shadow that should 14308 * be centered under the touch location while dragging. 14309 * <p> 14310 * The default implementation sets the dimensions of the shadow to be the 14311 * same as the dimensions of the View itself and centers the shadow under 14312 * the touch point. 14313 * </p> 14314 * 14315 * @param shadowSize A {@link android.graphics.Point} containing the width and height 14316 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 14317 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 14318 * image. 14319 * 14320 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 14321 * shadow image that should be underneath the touch point during the drag and drop 14322 * operation. Your application must set {@link android.graphics.Point#x} to the 14323 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 14324 */ 14325 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 14326 final View view = mView.get(); 14327 if (view != null) { 14328 shadowSize.set(view.getWidth(), view.getHeight()); 14329 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 14330 } else { 14331 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 14332 } 14333 } 14334 14335 /** 14336 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 14337 * based on the dimensions it received from the 14338 * {@link #onProvideShadowMetrics(Point, Point)} callback. 14339 * 14340 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 14341 */ 14342 public void onDrawShadow(Canvas canvas) { 14343 final View view = mView.get(); 14344 if (view != null) { 14345 view.draw(canvas); 14346 } else { 14347 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 14348 } 14349 } 14350 } 14351 14352 /** 14353 * Starts a drag and drop operation. When your application calls this method, it passes a 14354 * {@link android.view.View.DragShadowBuilder} object to the system. The 14355 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 14356 * to get metrics for the drag shadow, and then calls the object's 14357 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 14358 * <p> 14359 * Once the system has the drag shadow, it begins the drag and drop operation by sending 14360 * drag events to all the View objects in your application that are currently visible. It does 14361 * this either by calling the View object's drag listener (an implementation of 14362 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 14363 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 14364 * Both are passed a {@link android.view.DragEvent} object that has a 14365 * {@link android.view.DragEvent#getAction()} value of 14366 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 14367 * </p> 14368 * <p> 14369 * Your application can invoke startDrag() on any attached View object. The View object does not 14370 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 14371 * be related to the View the user selected for dragging. 14372 * </p> 14373 * @param data A {@link android.content.ClipData} object pointing to the data to be 14374 * transferred by the drag and drop operation. 14375 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 14376 * drag shadow. 14377 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 14378 * drop operation. This Object is put into every DragEvent object sent by the system during the 14379 * current drag. 14380 * <p> 14381 * myLocalState is a lightweight mechanism for the sending information from the dragged View 14382 * to the target Views. For example, it can contain flags that differentiate between a 14383 * a copy operation and a move operation. 14384 * </p> 14385 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 14386 * so the parameter should be set to 0. 14387 * @return {@code true} if the method completes successfully, or 14388 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 14389 * do a drag, and so no drag operation is in progress. 14390 */ 14391 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 14392 Object myLocalState, int flags) { 14393 if (ViewDebug.DEBUG_DRAG) { 14394 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 14395 } 14396 boolean okay = false; 14397 14398 Point shadowSize = new Point(); 14399 Point shadowTouchPoint = new Point(); 14400 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 14401 14402 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 14403 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 14404 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 14405 } 14406 14407 if (ViewDebug.DEBUG_DRAG) { 14408 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 14409 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 14410 } 14411 Surface surface = new Surface(); 14412 try { 14413 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 14414 flags, shadowSize.x, shadowSize.y, surface); 14415 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 14416 + " surface=" + surface); 14417 if (token != null) { 14418 Canvas canvas = surface.lockCanvas(null); 14419 try { 14420 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 14421 shadowBuilder.onDrawShadow(canvas); 14422 } finally { 14423 surface.unlockCanvasAndPost(canvas); 14424 } 14425 14426 final ViewRootImpl root = getViewRootImpl(); 14427 14428 // Cache the local state object for delivery with DragEvents 14429 root.setLocalDragState(myLocalState); 14430 14431 // repurpose 'shadowSize' for the last touch point 14432 root.getLastTouchPoint(shadowSize); 14433 14434 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 14435 shadowSize.x, shadowSize.y, 14436 shadowTouchPoint.x, shadowTouchPoint.y, data); 14437 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 14438 14439 // Off and running! Release our local surface instance; the drag 14440 // shadow surface is now managed by the system process. 14441 surface.release(); 14442 } 14443 } catch (Exception e) { 14444 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 14445 surface.destroy(); 14446 } 14447 14448 return okay; 14449 } 14450 14451 /** 14452 * Handles drag events sent by the system following a call to 14453 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 14454 *<p> 14455 * When the system calls this method, it passes a 14456 * {@link android.view.DragEvent} object. A call to 14457 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 14458 * in DragEvent. The method uses these to determine what is happening in the drag and drop 14459 * operation. 14460 * @param event The {@link android.view.DragEvent} sent by the system. 14461 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 14462 * in DragEvent, indicating the type of drag event represented by this object. 14463 * @return {@code true} if the method was successful, otherwise {@code false}. 14464 * <p> 14465 * The method should return {@code true} in response to an action type of 14466 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 14467 * operation. 14468 * </p> 14469 * <p> 14470 * The method should also return {@code true} in response to an action type of 14471 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 14472 * {@code false} if it didn't. 14473 * </p> 14474 */ 14475 public boolean onDragEvent(DragEvent event) { 14476 return false; 14477 } 14478 14479 /** 14480 * Detects if this View is enabled and has a drag event listener. 14481 * If both are true, then it calls the drag event listener with the 14482 * {@link android.view.DragEvent} it received. If the drag event listener returns 14483 * {@code true}, then dispatchDragEvent() returns {@code true}. 14484 * <p> 14485 * For all other cases, the method calls the 14486 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 14487 * method and returns its result. 14488 * </p> 14489 * <p> 14490 * This ensures that a drag event is always consumed, even if the View does not have a drag 14491 * event listener. However, if the View has a listener and the listener returns true, then 14492 * onDragEvent() is not called. 14493 * </p> 14494 */ 14495 public boolean dispatchDragEvent(DragEvent event) { 14496 //noinspection SimplifiableIfStatement 14497 ListenerInfo li = mListenerInfo; 14498 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 14499 && li.mOnDragListener.onDrag(this, event)) { 14500 return true; 14501 } 14502 return onDragEvent(event); 14503 } 14504 14505 boolean canAcceptDrag() { 14506 return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0; 14507 } 14508 14509 /** 14510 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 14511 * it is ever exposed at all. 14512 * @hide 14513 */ 14514 public void onCloseSystemDialogs(String reason) { 14515 } 14516 14517 /** 14518 * Given a Drawable whose bounds have been set to draw into this view, 14519 * update a Region being computed for 14520 * {@link #gatherTransparentRegion(android.graphics.Region)} so 14521 * that any non-transparent parts of the Drawable are removed from the 14522 * given transparent region. 14523 * 14524 * @param dr The Drawable whose transparency is to be applied to the region. 14525 * @param region A Region holding the current transparency information, 14526 * where any parts of the region that are set are considered to be 14527 * transparent. On return, this region will be modified to have the 14528 * transparency information reduced by the corresponding parts of the 14529 * Drawable that are not transparent. 14530 * {@hide} 14531 */ 14532 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 14533 if (DBG) { 14534 Log.i("View", "Getting transparent region for: " + this); 14535 } 14536 final Region r = dr.getTransparentRegion(); 14537 final Rect db = dr.getBounds(); 14538 final AttachInfo attachInfo = mAttachInfo; 14539 if (r != null && attachInfo != null) { 14540 final int w = getRight()-getLeft(); 14541 final int h = getBottom()-getTop(); 14542 if (db.left > 0) { 14543 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 14544 r.op(0, 0, db.left, h, Region.Op.UNION); 14545 } 14546 if (db.right < w) { 14547 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 14548 r.op(db.right, 0, w, h, Region.Op.UNION); 14549 } 14550 if (db.top > 0) { 14551 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 14552 r.op(0, 0, w, db.top, Region.Op.UNION); 14553 } 14554 if (db.bottom < h) { 14555 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 14556 r.op(0, db.bottom, w, h, Region.Op.UNION); 14557 } 14558 final int[] location = attachInfo.mTransparentLocation; 14559 getLocationInWindow(location); 14560 r.translate(location[0], location[1]); 14561 region.op(r, Region.Op.INTERSECT); 14562 } else { 14563 region.op(db, Region.Op.DIFFERENCE); 14564 } 14565 } 14566 14567 private void checkForLongClick(int delayOffset) { 14568 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 14569 mHasPerformedLongPress = false; 14570 14571 if (mPendingCheckForLongPress == null) { 14572 mPendingCheckForLongPress = new CheckForLongPress(); 14573 } 14574 mPendingCheckForLongPress.rememberWindowAttachCount(); 14575 postDelayed(mPendingCheckForLongPress, 14576 ViewConfiguration.getLongPressTimeout() - delayOffset); 14577 } 14578 } 14579 14580 /** 14581 * Inflate a view from an XML resource. This convenience method wraps the {@link 14582 * LayoutInflater} class, which provides a full range of options for view inflation. 14583 * 14584 * @param context The Context object for your activity or application. 14585 * @param resource The resource ID to inflate 14586 * @param root A view group that will be the parent. Used to properly inflate the 14587 * layout_* parameters. 14588 * @see LayoutInflater 14589 */ 14590 public static View inflate(Context context, int resource, ViewGroup root) { 14591 LayoutInflater factory = LayoutInflater.from(context); 14592 return factory.inflate(resource, root); 14593 } 14594 14595 /** 14596 * Scroll the view with standard behavior for scrolling beyond the normal 14597 * content boundaries. Views that call this method should override 14598 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 14599 * results of an over-scroll operation. 14600 * 14601 * Views can use this method to handle any touch or fling-based scrolling. 14602 * 14603 * @param deltaX Change in X in pixels 14604 * @param deltaY Change in Y in pixels 14605 * @param scrollX Current X scroll value in pixels before applying deltaX 14606 * @param scrollY Current Y scroll value in pixels before applying deltaY 14607 * @param scrollRangeX Maximum content scroll range along the X axis 14608 * @param scrollRangeY Maximum content scroll range along the Y axis 14609 * @param maxOverScrollX Number of pixels to overscroll by in either direction 14610 * along the X axis. 14611 * @param maxOverScrollY Number of pixels to overscroll by in either direction 14612 * along the Y axis. 14613 * @param isTouchEvent true if this scroll operation is the result of a touch event. 14614 * @return true if scrolling was clamped to an over-scroll boundary along either 14615 * axis, false otherwise. 14616 */ 14617 @SuppressWarnings({"UnusedParameters"}) 14618 protected boolean overScrollBy(int deltaX, int deltaY, 14619 int scrollX, int scrollY, 14620 int scrollRangeX, int scrollRangeY, 14621 int maxOverScrollX, int maxOverScrollY, 14622 boolean isTouchEvent) { 14623 final int overScrollMode = mOverScrollMode; 14624 final boolean canScrollHorizontal = 14625 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 14626 final boolean canScrollVertical = 14627 computeVerticalScrollRange() > computeVerticalScrollExtent(); 14628 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 14629 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 14630 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 14631 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 14632 14633 int newScrollX = scrollX + deltaX; 14634 if (!overScrollHorizontal) { 14635 maxOverScrollX = 0; 14636 } 14637 14638 int newScrollY = scrollY + deltaY; 14639 if (!overScrollVertical) { 14640 maxOverScrollY = 0; 14641 } 14642 14643 // Clamp values if at the limits and record 14644 final int left = -maxOverScrollX; 14645 final int right = maxOverScrollX + scrollRangeX; 14646 final int top = -maxOverScrollY; 14647 final int bottom = maxOverScrollY + scrollRangeY; 14648 14649 boolean clampedX = false; 14650 if (newScrollX > right) { 14651 newScrollX = right; 14652 clampedX = true; 14653 } else if (newScrollX < left) { 14654 newScrollX = left; 14655 clampedX = true; 14656 } 14657 14658 boolean clampedY = false; 14659 if (newScrollY > bottom) { 14660 newScrollY = bottom; 14661 clampedY = true; 14662 } else if (newScrollY < top) { 14663 newScrollY = top; 14664 clampedY = true; 14665 } 14666 14667 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 14668 14669 return clampedX || clampedY; 14670 } 14671 14672 /** 14673 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 14674 * respond to the results of an over-scroll operation. 14675 * 14676 * @param scrollX New X scroll value in pixels 14677 * @param scrollY New Y scroll value in pixels 14678 * @param clampedX True if scrollX was clamped to an over-scroll boundary 14679 * @param clampedY True if scrollY was clamped to an over-scroll boundary 14680 */ 14681 protected void onOverScrolled(int scrollX, int scrollY, 14682 boolean clampedX, boolean clampedY) { 14683 // Intentionally empty. 14684 } 14685 14686 /** 14687 * Returns the over-scroll mode for this view. The result will be 14688 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 14689 * (allow over-scrolling only if the view content is larger than the container), 14690 * or {@link #OVER_SCROLL_NEVER}. 14691 * 14692 * @return This view's over-scroll mode. 14693 */ 14694 public int getOverScrollMode() { 14695 return mOverScrollMode; 14696 } 14697 14698 /** 14699 * Set the over-scroll mode for this view. Valid over-scroll modes are 14700 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 14701 * (allow over-scrolling only if the view content is larger than the container), 14702 * or {@link #OVER_SCROLL_NEVER}. 14703 * 14704 * Setting the over-scroll mode of a view will have an effect only if the 14705 * view is capable of scrolling. 14706 * 14707 * @param overScrollMode The new over-scroll mode for this view. 14708 */ 14709 public void setOverScrollMode(int overScrollMode) { 14710 if (overScrollMode != OVER_SCROLL_ALWAYS && 14711 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 14712 overScrollMode != OVER_SCROLL_NEVER) { 14713 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 14714 } 14715 mOverScrollMode = overScrollMode; 14716 } 14717 14718 /** 14719 * Gets a scale factor that determines the distance the view should scroll 14720 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 14721 * @return The vertical scroll scale factor. 14722 * @hide 14723 */ 14724 protected float getVerticalScrollFactor() { 14725 if (mVerticalScrollFactor == 0) { 14726 TypedValue outValue = new TypedValue(); 14727 if (!mContext.getTheme().resolveAttribute( 14728 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 14729 throw new IllegalStateException( 14730 "Expected theme to define listPreferredItemHeight."); 14731 } 14732 mVerticalScrollFactor = outValue.getDimension( 14733 mContext.getResources().getDisplayMetrics()); 14734 } 14735 return mVerticalScrollFactor; 14736 } 14737 14738 /** 14739 * Gets a scale factor that determines the distance the view should scroll 14740 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 14741 * @return The horizontal scroll scale factor. 14742 * @hide 14743 */ 14744 protected float getHorizontalScrollFactor() { 14745 // TODO: Should use something else. 14746 return getVerticalScrollFactor(); 14747 } 14748 14749 /** 14750 * Return the value specifying the text direction or policy that was set with 14751 * {@link #setTextDirection(int)}. 14752 * 14753 * @return the defined text direction. It can be one of: 14754 * 14755 * {@link #TEXT_DIRECTION_INHERIT}, 14756 * {@link #TEXT_DIRECTION_FIRST_STRONG} 14757 * {@link #TEXT_DIRECTION_ANY_RTL}, 14758 * {@link #TEXT_DIRECTION_LTR}, 14759 * {@link #TEXT_DIRECTION_RTL}, 14760 * {@link #TEXT_DIRECTION_LOCALE}, 14761 */ 14762 @ViewDebug.ExportedProperty(category = "text", mapping = { 14763 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 14764 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 14765 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 14766 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 14767 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 14768 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 14769 }) 14770 public int getTextDirection() { 14771 return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT; 14772 } 14773 14774 /** 14775 * Set the text direction. 14776 * 14777 * @param textDirection the direction to set. Should be one of: 14778 * 14779 * {@link #TEXT_DIRECTION_INHERIT}, 14780 * {@link #TEXT_DIRECTION_FIRST_STRONG} 14781 * {@link #TEXT_DIRECTION_ANY_RTL}, 14782 * {@link #TEXT_DIRECTION_LTR}, 14783 * {@link #TEXT_DIRECTION_RTL}, 14784 * {@link #TEXT_DIRECTION_LOCALE}, 14785 */ 14786 public void setTextDirection(int textDirection) { 14787 if (getTextDirection() != textDirection) { 14788 // Reset the current text direction and the resolved one 14789 mPrivateFlags2 &= ~TEXT_DIRECTION_MASK; 14790 resetResolvedTextDirection(); 14791 // Set the new text direction 14792 mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK); 14793 requestLayout(); 14794 invalidate(true); 14795 } 14796 } 14797 14798 /** 14799 * Return the resolved text direction. 14800 * 14801 * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches 14802 * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds 14803 * up the parent chain of the view. if there is no parent, then it will return the default 14804 * {@link #TEXT_DIRECTION_FIRST_STRONG}. 14805 * 14806 * @return the resolved text direction. Returns one of: 14807 * 14808 * {@link #TEXT_DIRECTION_FIRST_STRONG} 14809 * {@link #TEXT_DIRECTION_ANY_RTL}, 14810 * {@link #TEXT_DIRECTION_LTR}, 14811 * {@link #TEXT_DIRECTION_RTL}, 14812 * {@link #TEXT_DIRECTION_LOCALE}, 14813 */ 14814 public int getResolvedTextDirection() { 14815 // The text direction will be resolved only if needed 14816 if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) { 14817 resolveTextDirection(); 14818 } 14819 return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 14820 } 14821 14822 /** 14823 * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when 14824 * resolution is done. 14825 */ 14826 public void resolveTextDirection() { 14827 // Reset any previous text direction resolution 14828 mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK); 14829 14830 // Set resolved text direction flag depending on text direction flag 14831 final int textDirection = getTextDirection(); 14832 switch(textDirection) { 14833 case TEXT_DIRECTION_INHERIT: 14834 if (canResolveTextDirection()) { 14835 ViewGroup viewGroup = ((ViewGroup) mParent); 14836 14837 // Set current resolved direction to the same value as the parent's one 14838 final int parentResolvedDirection = viewGroup.getResolvedTextDirection(); 14839 switch (parentResolvedDirection) { 14840 case TEXT_DIRECTION_FIRST_STRONG: 14841 case TEXT_DIRECTION_ANY_RTL: 14842 case TEXT_DIRECTION_LTR: 14843 case TEXT_DIRECTION_RTL: 14844 case TEXT_DIRECTION_LOCALE: 14845 mPrivateFlags2 |= 14846 (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 14847 break; 14848 default: 14849 // Default resolved direction is "first strong" heuristic 14850 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT; 14851 } 14852 } else { 14853 // We cannot do the resolution if there is no parent, so use the default one 14854 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT; 14855 } 14856 break; 14857 case TEXT_DIRECTION_FIRST_STRONG: 14858 case TEXT_DIRECTION_ANY_RTL: 14859 case TEXT_DIRECTION_LTR: 14860 case TEXT_DIRECTION_RTL: 14861 case TEXT_DIRECTION_LOCALE: 14862 // Resolved direction is the same as text direction 14863 mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 14864 break; 14865 default: 14866 // Default resolved direction is "first strong" heuristic 14867 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT; 14868 } 14869 14870 // Set to resolved 14871 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED; 14872 onResolvedTextDirectionChanged(); 14873 } 14874 14875 /** 14876 * Called when text direction has been resolved. Subclasses that care about text direction 14877 * resolution should override this method. 14878 * 14879 * The default implementation does nothing. 14880 */ 14881 public void onResolvedTextDirectionChanged() { 14882 } 14883 14884 /** 14885 * Check if text direction resolution can be done. 14886 * 14887 * @return true if text direction resolution can be done otherwise return false. 14888 */ 14889 public boolean canResolveTextDirection() { 14890 switch (getTextDirection()) { 14891 case TEXT_DIRECTION_INHERIT: 14892 return (mParent != null) && (mParent instanceof ViewGroup); 14893 default: 14894 return true; 14895 } 14896 } 14897 14898 /** 14899 * Reset resolved text direction. Text direction can be resolved with a call to 14900 * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when 14901 * reset is done. 14902 */ 14903 public void resetResolvedTextDirection() { 14904 mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK); 14905 onResolvedTextDirectionReset(); 14906 } 14907 14908 /** 14909 * Called when text direction is reset. Subclasses that care about text direction reset should 14910 * override this method and do a reset of the text direction of their children. The default 14911 * implementation does nothing. 14912 */ 14913 public void onResolvedTextDirectionReset() { 14914 } 14915 14916 // 14917 // Properties 14918 // 14919 /** 14920 * A Property wrapper around the <code>alpha</code> functionality handled by the 14921 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 14922 */ 14923 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 14924 @Override 14925 public void setValue(View object, float value) { 14926 object.setAlpha(value); 14927 } 14928 14929 @Override 14930 public Float get(View object) { 14931 return object.getAlpha(); 14932 } 14933 }; 14934 14935 /** 14936 * A Property wrapper around the <code>translationX</code> functionality handled by the 14937 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 14938 */ 14939 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 14940 @Override 14941 public void setValue(View object, float value) { 14942 object.setTranslationX(value); 14943 } 14944 14945 @Override 14946 public Float get(View object) { 14947 return object.getTranslationX(); 14948 } 14949 }; 14950 14951 /** 14952 * A Property wrapper around the <code>translationY</code> functionality handled by the 14953 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 14954 */ 14955 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 14956 @Override 14957 public void setValue(View object, float value) { 14958 object.setTranslationY(value); 14959 } 14960 14961 @Override 14962 public Float get(View object) { 14963 return object.getTranslationY(); 14964 } 14965 }; 14966 14967 /** 14968 * A Property wrapper around the <code>x</code> functionality handled by the 14969 * {@link View#setX(float)} and {@link View#getX()} methods. 14970 */ 14971 public static final Property<View, Float> X = new FloatProperty<View>("x") { 14972 @Override 14973 public void setValue(View object, float value) { 14974 object.setX(value); 14975 } 14976 14977 @Override 14978 public Float get(View object) { 14979 return object.getX(); 14980 } 14981 }; 14982 14983 /** 14984 * A Property wrapper around the <code>y</code> functionality handled by the 14985 * {@link View#setY(float)} and {@link View#getY()} methods. 14986 */ 14987 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 14988 @Override 14989 public void setValue(View object, float value) { 14990 object.setY(value); 14991 } 14992 14993 @Override 14994 public Float get(View object) { 14995 return object.getY(); 14996 } 14997 }; 14998 14999 /** 15000 * A Property wrapper around the <code>rotation</code> functionality handled by the 15001 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 15002 */ 15003 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 15004 @Override 15005 public void setValue(View object, float value) { 15006 object.setRotation(value); 15007 } 15008 15009 @Override 15010 public Float get(View object) { 15011 return object.getRotation(); 15012 } 15013 }; 15014 15015 /** 15016 * A Property wrapper around the <code>rotationX</code> functionality handled by the 15017 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 15018 */ 15019 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 15020 @Override 15021 public void setValue(View object, float value) { 15022 object.setRotationX(value); 15023 } 15024 15025 @Override 15026 public Float get(View object) { 15027 return object.getRotationX(); 15028 } 15029 }; 15030 15031 /** 15032 * A Property wrapper around the <code>rotationY</code> functionality handled by the 15033 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 15034 */ 15035 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 15036 @Override 15037 public void setValue(View object, float value) { 15038 object.setRotationY(value); 15039 } 15040 15041 @Override 15042 public Float get(View object) { 15043 return object.getRotationY(); 15044 } 15045 }; 15046 15047 /** 15048 * A Property wrapper around the <code>scaleX</code> functionality handled by the 15049 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 15050 */ 15051 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 15052 @Override 15053 public void setValue(View object, float value) { 15054 object.setScaleX(value); 15055 } 15056 15057 @Override 15058 public Float get(View object) { 15059 return object.getScaleX(); 15060 } 15061 }; 15062 15063 /** 15064 * A Property wrapper around the <code>scaleY</code> functionality handled by the 15065 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 15066 */ 15067 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 15068 @Override 15069 public void setValue(View object, float value) { 15070 object.setScaleY(value); 15071 } 15072 15073 @Override 15074 public Float get(View object) { 15075 return object.getScaleY(); 15076 } 15077 }; 15078 15079 /** 15080 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 15081 * Each MeasureSpec represents a requirement for either the width or the height. 15082 * A MeasureSpec is comprised of a size and a mode. There are three possible 15083 * modes: 15084 * <dl> 15085 * <dt>UNSPECIFIED</dt> 15086 * <dd> 15087 * The parent has not imposed any constraint on the child. It can be whatever size 15088 * it wants. 15089 * </dd> 15090 * 15091 * <dt>EXACTLY</dt> 15092 * <dd> 15093 * The parent has determined an exact size for the child. The child is going to be 15094 * given those bounds regardless of how big it wants to be. 15095 * </dd> 15096 * 15097 * <dt>AT_MOST</dt> 15098 * <dd> 15099 * The child can be as large as it wants up to the specified size. 15100 * </dd> 15101 * </dl> 15102 * 15103 * MeasureSpecs are implemented as ints to reduce object allocation. This class 15104 * is provided to pack and unpack the <size, mode> tuple into the int. 15105 */ 15106 public static class MeasureSpec { 15107 private static final int MODE_SHIFT = 30; 15108 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 15109 15110 /** 15111 * Measure specification mode: The parent has not imposed any constraint 15112 * on the child. It can be whatever size it wants. 15113 */ 15114 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 15115 15116 /** 15117 * Measure specification mode: The parent has determined an exact size 15118 * for the child. The child is going to be given those bounds regardless 15119 * of how big it wants to be. 15120 */ 15121 public static final int EXACTLY = 1 << MODE_SHIFT; 15122 15123 /** 15124 * Measure specification mode: The child can be as large as it wants up 15125 * to the specified size. 15126 */ 15127 public static final int AT_MOST = 2 << MODE_SHIFT; 15128 15129 /** 15130 * Creates a measure specification based on the supplied size and mode. 15131 * 15132 * The mode must always be one of the following: 15133 * <ul> 15134 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 15135 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 15136 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 15137 * </ul> 15138 * 15139 * @param size the size of the measure specification 15140 * @param mode the mode of the measure specification 15141 * @return the measure specification based on size and mode 15142 */ 15143 public static int makeMeasureSpec(int size, int mode) { 15144 return size + mode; 15145 } 15146 15147 /** 15148 * Extracts the mode from the supplied measure specification. 15149 * 15150 * @param measureSpec the measure specification to extract the mode from 15151 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 15152 * {@link android.view.View.MeasureSpec#AT_MOST} or 15153 * {@link android.view.View.MeasureSpec#EXACTLY} 15154 */ 15155 public static int getMode(int measureSpec) { 15156 return (measureSpec & MODE_MASK); 15157 } 15158 15159 /** 15160 * Extracts the size from the supplied measure specification. 15161 * 15162 * @param measureSpec the measure specification to extract the size from 15163 * @return the size in pixels defined in the supplied measure specification 15164 */ 15165 public static int getSize(int measureSpec) { 15166 return (measureSpec & ~MODE_MASK); 15167 } 15168 15169 /** 15170 * Returns a String representation of the specified measure 15171 * specification. 15172 * 15173 * @param measureSpec the measure specification to convert to a String 15174 * @return a String with the following format: "MeasureSpec: MODE SIZE" 15175 */ 15176 public static String toString(int measureSpec) { 15177 int mode = getMode(measureSpec); 15178 int size = getSize(measureSpec); 15179 15180 StringBuilder sb = new StringBuilder("MeasureSpec: "); 15181 15182 if (mode == UNSPECIFIED) 15183 sb.append("UNSPECIFIED "); 15184 else if (mode == EXACTLY) 15185 sb.append("EXACTLY "); 15186 else if (mode == AT_MOST) 15187 sb.append("AT_MOST "); 15188 else 15189 sb.append(mode).append(" "); 15190 15191 sb.append(size); 15192 return sb.toString(); 15193 } 15194 } 15195 15196 class CheckForLongPress implements Runnable { 15197 15198 private int mOriginalWindowAttachCount; 15199 15200 public void run() { 15201 if (isPressed() && (mParent != null) 15202 && mOriginalWindowAttachCount == mWindowAttachCount) { 15203 if (performLongClick()) { 15204 mHasPerformedLongPress = true; 15205 } 15206 } 15207 } 15208 15209 public void rememberWindowAttachCount() { 15210 mOriginalWindowAttachCount = mWindowAttachCount; 15211 } 15212 } 15213 15214 private final class CheckForTap implements Runnable { 15215 public void run() { 15216 mPrivateFlags &= ~PREPRESSED; 15217 setPressed(true); 15218 checkForLongClick(ViewConfiguration.getTapTimeout()); 15219 } 15220 } 15221 15222 private final class PerformClick implements Runnable { 15223 public void run() { 15224 performClick(); 15225 } 15226 } 15227 15228 /** @hide */ 15229 public void hackTurnOffWindowResizeAnim(boolean off) { 15230 mAttachInfo.mTurnOffWindowResizeAnim = off; 15231 } 15232 15233 /** 15234 * This method returns a ViewPropertyAnimator object, which can be used to animate 15235 * specific properties on this View. 15236 * 15237 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 15238 */ 15239 public ViewPropertyAnimator animate() { 15240 if (mAnimator == null) { 15241 mAnimator = new ViewPropertyAnimator(this); 15242 } 15243 return mAnimator; 15244 } 15245 15246 /** 15247 * Interface definition for a callback to be invoked when a key event is 15248 * dispatched to this view. The callback will be invoked before the key 15249 * event is given to the view. 15250 */ 15251 public interface OnKeyListener { 15252 /** 15253 * Called when a key is dispatched to a view. This allows listeners to 15254 * get a chance to respond before the target view. 15255 * 15256 * @param v The view the key has been dispatched to. 15257 * @param keyCode The code for the physical key that was pressed 15258 * @param event The KeyEvent object containing full information about 15259 * the event. 15260 * @return True if the listener has consumed the event, false otherwise. 15261 */ 15262 boolean onKey(View v, int keyCode, KeyEvent event); 15263 } 15264 15265 /** 15266 * Interface definition for a callback to be invoked when a touch event is 15267 * dispatched to this view. The callback will be invoked before the touch 15268 * event is given to the view. 15269 */ 15270 public interface OnTouchListener { 15271 /** 15272 * Called when a touch event is dispatched to a view. This allows listeners to 15273 * get a chance to respond before the target view. 15274 * 15275 * @param v The view the touch event has been dispatched to. 15276 * @param event The MotionEvent object containing full information about 15277 * the event. 15278 * @return True if the listener has consumed the event, false otherwise. 15279 */ 15280 boolean onTouch(View v, MotionEvent event); 15281 } 15282 15283 /** 15284 * Interface definition for a callback to be invoked when a hover event is 15285 * dispatched to this view. The callback will be invoked before the hover 15286 * event is given to the view. 15287 */ 15288 public interface OnHoverListener { 15289 /** 15290 * Called when a hover event is dispatched to a view. This allows listeners to 15291 * get a chance to respond before the target view. 15292 * 15293 * @param v The view the hover event has been dispatched to. 15294 * @param event The MotionEvent object containing full information about 15295 * the event. 15296 * @return True if the listener has consumed the event, false otherwise. 15297 */ 15298 boolean onHover(View v, MotionEvent event); 15299 } 15300 15301 /** 15302 * Interface definition for a callback to be invoked when a generic motion event is 15303 * dispatched to this view. The callback will be invoked before the generic motion 15304 * event is given to the view. 15305 */ 15306 public interface OnGenericMotionListener { 15307 /** 15308 * Called when a generic motion event is dispatched to a view. This allows listeners to 15309 * get a chance to respond before the target view. 15310 * 15311 * @param v The view the generic motion event has been dispatched to. 15312 * @param event The MotionEvent object containing full information about 15313 * the event. 15314 * @return True if the listener has consumed the event, false otherwise. 15315 */ 15316 boolean onGenericMotion(View v, MotionEvent event); 15317 } 15318 15319 /** 15320 * Interface definition for a callback to be invoked when a view has been clicked and held. 15321 */ 15322 public interface OnLongClickListener { 15323 /** 15324 * Called when a view has been clicked and held. 15325 * 15326 * @param v The view that was clicked and held. 15327 * 15328 * @return true if the callback consumed the long click, false otherwise. 15329 */ 15330 boolean onLongClick(View v); 15331 } 15332 15333 /** 15334 * Interface definition for a callback to be invoked when a drag is being dispatched 15335 * to this view. The callback will be invoked before the hosting view's own 15336 * onDrag(event) method. If the listener wants to fall back to the hosting view's 15337 * onDrag(event) behavior, it should return 'false' from this callback. 15338 * 15339 * <div class="special reference"> 15340 * <h3>Developer Guides</h3> 15341 * <p>For a guide to implementing drag and drop features, read the 15342 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 15343 * </div> 15344 */ 15345 public interface OnDragListener { 15346 /** 15347 * Called when a drag event is dispatched to a view. This allows listeners 15348 * to get a chance to override base View behavior. 15349 * 15350 * @param v The View that received the drag event. 15351 * @param event The {@link android.view.DragEvent} object for the drag event. 15352 * @return {@code true} if the drag event was handled successfully, or {@code false} 15353 * if the drag event was not handled. Note that {@code false} will trigger the View 15354 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 15355 */ 15356 boolean onDrag(View v, DragEvent event); 15357 } 15358 15359 /** 15360 * Interface definition for a callback to be invoked when the focus state of 15361 * a view changed. 15362 */ 15363 public interface OnFocusChangeListener { 15364 /** 15365 * Called when the focus state of a view has changed. 15366 * 15367 * @param v The view whose state has changed. 15368 * @param hasFocus The new focus state of v. 15369 */ 15370 void onFocusChange(View v, boolean hasFocus); 15371 } 15372 15373 /** 15374 * Interface definition for a callback to be invoked when a view is clicked. 15375 */ 15376 public interface OnClickListener { 15377 /** 15378 * Called when a view has been clicked. 15379 * 15380 * @param v The view that was clicked. 15381 */ 15382 void onClick(View v); 15383 } 15384 15385 /** 15386 * Interface definition for a callback to be invoked when the context menu 15387 * for this view is being built. 15388 */ 15389 public interface OnCreateContextMenuListener { 15390 /** 15391 * Called when the context menu for this view is being built. It is not 15392 * safe to hold onto the menu after this method returns. 15393 * 15394 * @param menu The context menu that is being built 15395 * @param v The view for which the context menu is being built 15396 * @param menuInfo Extra information about the item for which the 15397 * context menu should be shown. This information will vary 15398 * depending on the class of v. 15399 */ 15400 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 15401 } 15402 15403 /** 15404 * Interface definition for a callback to be invoked when the status bar changes 15405 * visibility. This reports <strong>global</strong> changes to the system UI 15406 * state, not just what the application is requesting. 15407 * 15408 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 15409 */ 15410 public interface OnSystemUiVisibilityChangeListener { 15411 /** 15412 * Called when the status bar changes visibility because of a call to 15413 * {@link View#setSystemUiVisibility(int)}. 15414 * 15415 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 15416 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. This tells you the 15417 * <strong>global</strong> state of the UI visibility flags, not what your 15418 * app is currently applying. 15419 */ 15420 public void onSystemUiVisibilityChange(int visibility); 15421 } 15422 15423 /** 15424 * Interface definition for a callback to be invoked when this view is attached 15425 * or detached from its window. 15426 */ 15427 public interface OnAttachStateChangeListener { 15428 /** 15429 * Called when the view is attached to a window. 15430 * @param v The view that was attached 15431 */ 15432 public void onViewAttachedToWindow(View v); 15433 /** 15434 * Called when the view is detached from a window. 15435 * @param v The view that was detached 15436 */ 15437 public void onViewDetachedFromWindow(View v); 15438 } 15439 15440 private final class UnsetPressedState implements Runnable { 15441 public void run() { 15442 setPressed(false); 15443 } 15444 } 15445 15446 /** 15447 * Base class for derived classes that want to save and restore their own 15448 * state in {@link android.view.View#onSaveInstanceState()}. 15449 */ 15450 public static class BaseSavedState extends AbsSavedState { 15451 /** 15452 * Constructor used when reading from a parcel. Reads the state of the superclass. 15453 * 15454 * @param source 15455 */ 15456 public BaseSavedState(Parcel source) { 15457 super(source); 15458 } 15459 15460 /** 15461 * Constructor called by derived classes when creating their SavedState objects 15462 * 15463 * @param superState The state of the superclass of this view 15464 */ 15465 public BaseSavedState(Parcelable superState) { 15466 super(superState); 15467 } 15468 15469 public static final Parcelable.Creator<BaseSavedState> CREATOR = 15470 new Parcelable.Creator<BaseSavedState>() { 15471 public BaseSavedState createFromParcel(Parcel in) { 15472 return new BaseSavedState(in); 15473 } 15474 15475 public BaseSavedState[] newArray(int size) { 15476 return new BaseSavedState[size]; 15477 } 15478 }; 15479 } 15480 15481 /** 15482 * A set of information given to a view when it is attached to its parent 15483 * window. 15484 */ 15485 static class AttachInfo { 15486 interface Callbacks { 15487 void playSoundEffect(int effectId); 15488 boolean performHapticFeedback(int effectId, boolean always); 15489 } 15490 15491 /** 15492 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 15493 * to a Handler. This class contains the target (View) to invalidate and 15494 * the coordinates of the dirty rectangle. 15495 * 15496 * For performance purposes, this class also implements a pool of up to 15497 * POOL_LIMIT objects that get reused. This reduces memory allocations 15498 * whenever possible. 15499 */ 15500 static class InvalidateInfo implements Poolable<InvalidateInfo> { 15501 private static final int POOL_LIMIT = 10; 15502 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 15503 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 15504 public InvalidateInfo newInstance() { 15505 return new InvalidateInfo(); 15506 } 15507 15508 public void onAcquired(InvalidateInfo element) { 15509 } 15510 15511 public void onReleased(InvalidateInfo element) { 15512 element.target = null; 15513 } 15514 }, POOL_LIMIT) 15515 ); 15516 15517 private InvalidateInfo mNext; 15518 private boolean mIsPooled; 15519 15520 View target; 15521 15522 int left; 15523 int top; 15524 int right; 15525 int bottom; 15526 15527 public void setNextPoolable(InvalidateInfo element) { 15528 mNext = element; 15529 } 15530 15531 public InvalidateInfo getNextPoolable() { 15532 return mNext; 15533 } 15534 15535 static InvalidateInfo acquire() { 15536 return sPool.acquire(); 15537 } 15538 15539 void release() { 15540 sPool.release(this); 15541 } 15542 15543 public boolean isPooled() { 15544 return mIsPooled; 15545 } 15546 15547 public void setPooled(boolean isPooled) { 15548 mIsPooled = isPooled; 15549 } 15550 } 15551 15552 final IWindowSession mSession; 15553 15554 final IWindow mWindow; 15555 15556 final IBinder mWindowToken; 15557 15558 final Callbacks mRootCallbacks; 15559 15560 HardwareCanvas mHardwareCanvas; 15561 15562 /** 15563 * The top view of the hierarchy. 15564 */ 15565 View mRootView; 15566 15567 IBinder mPanelParentWindowToken; 15568 Surface mSurface; 15569 15570 boolean mHardwareAccelerated; 15571 boolean mHardwareAccelerationRequested; 15572 HardwareRenderer mHardwareRenderer; 15573 15574 boolean mScreenOn; 15575 15576 /** 15577 * Scale factor used by the compatibility mode 15578 */ 15579 float mApplicationScale; 15580 15581 /** 15582 * Indicates whether the application is in compatibility mode 15583 */ 15584 boolean mScalingRequired; 15585 15586 /** 15587 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 15588 */ 15589 boolean mTurnOffWindowResizeAnim; 15590 15591 /** 15592 * Left position of this view's window 15593 */ 15594 int mWindowLeft; 15595 15596 /** 15597 * Top position of this view's window 15598 */ 15599 int mWindowTop; 15600 15601 /** 15602 * Indicates whether views need to use 32-bit drawing caches 15603 */ 15604 boolean mUse32BitDrawingCache; 15605 15606 /** 15607 * For windows that are full-screen but using insets to layout inside 15608 * of the screen decorations, these are the current insets for the 15609 * content of the window. 15610 */ 15611 final Rect mContentInsets = new Rect(); 15612 15613 /** 15614 * For windows that are full-screen but using insets to layout inside 15615 * of the screen decorations, these are the current insets for the 15616 * actual visible parts of the window. 15617 */ 15618 final Rect mVisibleInsets = new Rect(); 15619 15620 /** 15621 * The internal insets given by this window. This value is 15622 * supplied by the client (through 15623 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 15624 * be given to the window manager when changed to be used in laying 15625 * out windows behind it. 15626 */ 15627 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 15628 = new ViewTreeObserver.InternalInsetsInfo(); 15629 15630 /** 15631 * All views in the window's hierarchy that serve as scroll containers, 15632 * used to determine if the window can be resized or must be panned 15633 * to adjust for a soft input area. 15634 */ 15635 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 15636 15637 final KeyEvent.DispatcherState mKeyDispatchState 15638 = new KeyEvent.DispatcherState(); 15639 15640 /** 15641 * Indicates whether the view's window currently has the focus. 15642 */ 15643 boolean mHasWindowFocus; 15644 15645 /** 15646 * The current visibility of the window. 15647 */ 15648 int mWindowVisibility; 15649 15650 /** 15651 * Indicates the time at which drawing started to occur. 15652 */ 15653 long mDrawingTime; 15654 15655 /** 15656 * Indicates whether or not ignoring the DIRTY_MASK flags. 15657 */ 15658 boolean mIgnoreDirtyState; 15659 15660 /** 15661 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 15662 * to avoid clearing that flag prematurely. 15663 */ 15664 boolean mSetIgnoreDirtyState = false; 15665 15666 /** 15667 * Indicates whether the view's window is currently in touch mode. 15668 */ 15669 boolean mInTouchMode; 15670 15671 /** 15672 * Indicates that ViewAncestor should trigger a global layout change 15673 * the next time it performs a traversal 15674 */ 15675 boolean mRecomputeGlobalAttributes; 15676 15677 /** 15678 * Always report new attributes at next traversal. 15679 */ 15680 boolean mForceReportNewAttributes; 15681 15682 /** 15683 * Set during a traveral if any views want to keep the screen on. 15684 */ 15685 boolean mKeepScreenOn; 15686 15687 /** 15688 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 15689 */ 15690 int mSystemUiVisibility; 15691 15692 /** 15693 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 15694 * attached. 15695 */ 15696 boolean mHasSystemUiListeners; 15697 15698 /** 15699 * Set if the visibility of any views has changed. 15700 */ 15701 boolean mViewVisibilityChanged; 15702 15703 /** 15704 * Set to true if a view has been scrolled. 15705 */ 15706 boolean mViewScrollChanged; 15707 15708 /** 15709 * Global to the view hierarchy used as a temporary for dealing with 15710 * x/y points in the transparent region computations. 15711 */ 15712 final int[] mTransparentLocation = new int[2]; 15713 15714 /** 15715 * Global to the view hierarchy used as a temporary for dealing with 15716 * x/y points in the ViewGroup.invalidateChild implementation. 15717 */ 15718 final int[] mInvalidateChildLocation = new int[2]; 15719 15720 15721 /** 15722 * Global to the view hierarchy used as a temporary for dealing with 15723 * x/y location when view is transformed. 15724 */ 15725 final float[] mTmpTransformLocation = new float[2]; 15726 15727 /** 15728 * The view tree observer used to dispatch global events like 15729 * layout, pre-draw, touch mode change, etc. 15730 */ 15731 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 15732 15733 /** 15734 * A Canvas used by the view hierarchy to perform bitmap caching. 15735 */ 15736 Canvas mCanvas; 15737 15738 /** 15739 * The view root impl. 15740 */ 15741 final ViewRootImpl mViewRootImpl; 15742 15743 /** 15744 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 15745 * handler can be used to pump events in the UI events queue. 15746 */ 15747 final Handler mHandler; 15748 15749 /** 15750 * Temporary for use in computing invalidate rectangles while 15751 * calling up the hierarchy. 15752 */ 15753 final Rect mTmpInvalRect = new Rect(); 15754 15755 /** 15756 * Temporary for use in computing hit areas with transformed views 15757 */ 15758 final RectF mTmpTransformRect = new RectF(); 15759 15760 /** 15761 * Temporary list for use in collecting focusable descendents of a view. 15762 */ 15763 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 15764 15765 /** 15766 * The id of the window for accessibility purposes. 15767 */ 15768 int mAccessibilityWindowId = View.NO_ID; 15769 15770 /** 15771 * Creates a new set of attachment information with the specified 15772 * events handler and thread. 15773 * 15774 * @param handler the events handler the view must use 15775 */ 15776 AttachInfo(IWindowSession session, IWindow window, 15777 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 15778 mSession = session; 15779 mWindow = window; 15780 mWindowToken = window.asBinder(); 15781 mViewRootImpl = viewRootImpl; 15782 mHandler = handler; 15783 mRootCallbacks = effectPlayer; 15784 } 15785 } 15786 15787 /** 15788 * <p>ScrollabilityCache holds various fields used by a View when scrolling 15789 * is supported. This avoids keeping too many unused fields in most 15790 * instances of View.</p> 15791 */ 15792 private static class ScrollabilityCache implements Runnable { 15793 15794 /** 15795 * Scrollbars are not visible 15796 */ 15797 public static final int OFF = 0; 15798 15799 /** 15800 * Scrollbars are visible 15801 */ 15802 public static final int ON = 1; 15803 15804 /** 15805 * Scrollbars are fading away 15806 */ 15807 public static final int FADING = 2; 15808 15809 public boolean fadeScrollBars; 15810 15811 public int fadingEdgeLength; 15812 public int scrollBarDefaultDelayBeforeFade; 15813 public int scrollBarFadeDuration; 15814 15815 public int scrollBarSize; 15816 public ScrollBarDrawable scrollBar; 15817 public float[] interpolatorValues; 15818 public View host; 15819 15820 public final Paint paint; 15821 public final Matrix matrix; 15822 public Shader shader; 15823 15824 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 15825 15826 private static final float[] OPAQUE = { 255 }; 15827 private static final float[] TRANSPARENT = { 0.0f }; 15828 15829 /** 15830 * When fading should start. This time moves into the future every time 15831 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 15832 */ 15833 public long fadeStartTime; 15834 15835 15836 /** 15837 * The current state of the scrollbars: ON, OFF, or FADING 15838 */ 15839 public int state = OFF; 15840 15841 private int mLastColor; 15842 15843 public ScrollabilityCache(ViewConfiguration configuration, View host) { 15844 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 15845 scrollBarSize = configuration.getScaledScrollBarSize(); 15846 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 15847 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 15848 15849 paint = new Paint(); 15850 matrix = new Matrix(); 15851 // use use a height of 1, and then wack the matrix each time we 15852 // actually use it. 15853 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 15854 15855 paint.setShader(shader); 15856 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 15857 this.host = host; 15858 } 15859 15860 public void setFadeColor(int color) { 15861 if (color != 0 && color != mLastColor) { 15862 mLastColor = color; 15863 color |= 0xFF000000; 15864 15865 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 15866 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 15867 15868 paint.setShader(shader); 15869 // Restore the default transfer mode (src_over) 15870 paint.setXfermode(null); 15871 } 15872 } 15873 15874 public void run() { 15875 long now = AnimationUtils.currentAnimationTimeMillis(); 15876 if (now >= fadeStartTime) { 15877 15878 // the animation fades the scrollbars out by changing 15879 // the opacity (alpha) from fully opaque to fully 15880 // transparent 15881 int nextFrame = (int) now; 15882 int framesCount = 0; 15883 15884 Interpolator interpolator = scrollBarInterpolator; 15885 15886 // Start opaque 15887 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 15888 15889 // End transparent 15890 nextFrame += scrollBarFadeDuration; 15891 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 15892 15893 state = FADING; 15894 15895 // Kick off the fade animation 15896 host.invalidate(true); 15897 } 15898 } 15899 } 15900 15901 /** 15902 * Resuable callback for sending 15903 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 15904 */ 15905 private class SendViewScrolledAccessibilityEvent implements Runnable { 15906 public volatile boolean mIsPending; 15907 15908 public void run() { 15909 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 15910 mIsPending = false; 15911 } 15912 } 15913 15914 /** 15915 * <p> 15916 * This class represents a delegate that can be registered in a {@link View} 15917 * to enhance accessibility support via composition rather via inheritance. 15918 * It is specifically targeted to widget developers that extend basic View 15919 * classes i.e. classes in package android.view, that would like their 15920 * applications to be backwards compatible. 15921 * </p> 15922 * <div class="special reference"> 15923 * <h3>Developer Guides</h3> 15924 * <p>For more information about making applications accessible, read the 15925 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 15926 * developer guide.</p> 15927 * </div> 15928 * <p> 15929 * A scenario in which a developer would like to use an accessibility delegate 15930 * is overriding a method introduced in a later API version then the minimal API 15931 * version supported by the application. For example, the method 15932 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 15933 * in API version 4 when the accessibility APIs were first introduced. If a 15934 * developer would like his application to run on API version 4 devices (assuming 15935 * all other APIs used by the application are version 4 or lower) and take advantage 15936 * of this method, instead of overriding the method which would break the application's 15937 * backwards compatibility, he can override the corresponding method in this 15938 * delegate and register the delegate in the target View if the API version of 15939 * the system is high enough i.e. the API version is same or higher to the API 15940 * version that introduced 15941 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 15942 * </p> 15943 * <p> 15944 * Here is an example implementation: 15945 * </p> 15946 * <code><pre><p> 15947 * if (Build.VERSION.SDK_INT >= 14) { 15948 * // If the API version is equal of higher than the version in 15949 * // which onInitializeAccessibilityNodeInfo was introduced we 15950 * // register a delegate with a customized implementation. 15951 * View view = findViewById(R.id.view_id); 15952 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 15953 * public void onInitializeAccessibilityNodeInfo(View host, 15954 * AccessibilityNodeInfo info) { 15955 * // Let the default implementation populate the info. 15956 * super.onInitializeAccessibilityNodeInfo(host, info); 15957 * // Set some other information. 15958 * info.setEnabled(host.isEnabled()); 15959 * } 15960 * }); 15961 * } 15962 * </code></pre></p> 15963 * <p> 15964 * This delegate contains methods that correspond to the accessibility methods 15965 * in View. If a delegate has been specified the implementation in View hands 15966 * off handling to the corresponding method in this delegate. The default 15967 * implementation the delegate methods behaves exactly as the corresponding 15968 * method in View for the case of no accessibility delegate been set. Hence, 15969 * to customize the behavior of a View method, clients can override only the 15970 * corresponding delegate method without altering the behavior of the rest 15971 * accessibility related methods of the host view. 15972 * </p> 15973 */ 15974 public static class AccessibilityDelegate { 15975 15976 /** 15977 * Sends an accessibility event of the given type. If accessibility is not 15978 * enabled this method has no effect. 15979 * <p> 15980 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 15981 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 15982 * been set. 15983 * </p> 15984 * 15985 * @param host The View hosting the delegate. 15986 * @param eventType The type of the event to send. 15987 * 15988 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 15989 */ 15990 public void sendAccessibilityEvent(View host, int eventType) { 15991 host.sendAccessibilityEventInternal(eventType); 15992 } 15993 15994 /** 15995 * Sends an accessibility event. This method behaves exactly as 15996 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 15997 * empty {@link AccessibilityEvent} and does not perform a check whether 15998 * accessibility is enabled. 15999 * <p> 16000 * The default implementation behaves as 16001 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 16002 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 16003 * the case of no accessibility delegate been set. 16004 * </p> 16005 * 16006 * @param host The View hosting the delegate. 16007 * @param event The event to send. 16008 * 16009 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 16010 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 16011 */ 16012 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 16013 host.sendAccessibilityEventUncheckedInternal(event); 16014 } 16015 16016 /** 16017 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 16018 * to its children for adding their text content to the event. 16019 * <p> 16020 * The default implementation behaves as 16021 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 16022 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 16023 * the case of no accessibility delegate been set. 16024 * </p> 16025 * 16026 * @param host The View hosting the delegate. 16027 * @param event The event. 16028 * @return True if the event population was completed. 16029 * 16030 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 16031 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 16032 */ 16033 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 16034 return host.dispatchPopulateAccessibilityEventInternal(event); 16035 } 16036 16037 /** 16038 * Gives a chance to the host View to populate the accessibility event with its 16039 * text content. 16040 * <p> 16041 * The default implementation behaves as 16042 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 16043 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 16044 * the case of no accessibility delegate been set. 16045 * </p> 16046 * 16047 * @param host The View hosting the delegate. 16048 * @param event The accessibility event which to populate. 16049 * 16050 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 16051 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 16052 */ 16053 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 16054 host.onPopulateAccessibilityEventInternal(event); 16055 } 16056 16057 /** 16058 * Initializes an {@link AccessibilityEvent} with information about the 16059 * the host View which is the event source. 16060 * <p> 16061 * The default implementation behaves as 16062 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 16063 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 16064 * the case of no accessibility delegate been set. 16065 * </p> 16066 * 16067 * @param host The View hosting the delegate. 16068 * @param event The event to initialize. 16069 * 16070 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 16071 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 16072 */ 16073 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 16074 host.onInitializeAccessibilityEventInternal(event); 16075 } 16076 16077 /** 16078 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 16079 * <p> 16080 * The default implementation behaves as 16081 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 16082 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 16083 * the case of no accessibility delegate been set. 16084 * </p> 16085 * 16086 * @param host The View hosting the delegate. 16087 * @param info The instance to initialize. 16088 * 16089 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 16090 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 16091 */ 16092 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 16093 host.onInitializeAccessibilityNodeInfoInternal(info); 16094 } 16095 16096 /** 16097 * Called when a child of the host View has requested sending an 16098 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 16099 * to augment the event. 16100 * <p> 16101 * The default implementation behaves as 16102 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 16103 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 16104 * the case of no accessibility delegate been set. 16105 * </p> 16106 * 16107 * @param host The View hosting the delegate. 16108 * @param child The child which requests sending the event. 16109 * @param event The event to be sent. 16110 * @return True if the event should be sent 16111 * 16112 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 16113 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 16114 */ 16115 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 16116 AccessibilityEvent event) { 16117 return host.onRequestSendAccessibilityEventInternal(child, event); 16118 } 16119 16120 /** 16121 * Gets the provider for managing a virtual view hierarchy rooted at this View 16122 * and reported to {@link android.accessibilityservice.AccessibilityService}s 16123 * that explore the window content. 16124 * <p> 16125 * The default implementation behaves as 16126 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 16127 * the case of no accessibility delegate been set. 16128 * </p> 16129 * 16130 * @return The provider. 16131 * 16132 * @see AccessibilityNodeProvider 16133 */ 16134 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 16135 return null; 16136 } 16137 } 16138} 16139