View.java revision edc1e59b34c7f813ad197545b1d846e3a99a6831
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)} method and queried by calling 340 * {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 341 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}. 342 * </p> 343 * 344 * <p> 345 * Even though a view can define a padding, it does not provide any support for 346 * margins. However, view groups provide such a support. Refer to 347 * {@link android.view.ViewGroup} and 348 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 349 * </p> 350 * 351 * <a name="Layout"></a> 352 * <h3>Layout</h3> 353 * <p> 354 * Layout is a two pass process: a measure pass and a layout pass. The measuring 355 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 356 * of the view tree. Each view pushes dimension specifications down the tree 357 * during the recursion. At the end of the measure pass, every view has stored 358 * its measurements. The second pass happens in 359 * {@link #layout(int,int,int,int)} and is also top-down. During 360 * this pass each parent is responsible for positioning all of its children 361 * using the sizes computed in the measure pass. 362 * </p> 363 * 364 * <p> 365 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 366 * {@link #getMeasuredHeight()} values must be set, along with those for all of 367 * that view's descendants. A view's measured width and measured height values 368 * must respect the constraints imposed by the view's parents. This guarantees 369 * that at the end of the measure pass, all parents accept all of their 370 * children's measurements. A parent view may call measure() more than once on 371 * its children. For example, the parent may measure each child once with 372 * unspecified dimensions to find out how big they want to be, then call 373 * measure() on them again with actual numbers if the sum of all the children's 374 * unconstrained sizes is too big or too small. 375 * </p> 376 * 377 * <p> 378 * The measure pass uses two classes to communicate dimensions. The 379 * {@link MeasureSpec} class is used by views to tell their parents how they 380 * want to be measured and positioned. The base LayoutParams class just 381 * describes how big the view wants to be for both width and height. For each 382 * dimension, it can specify one of: 383 * <ul> 384 * <li> an exact number 385 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 386 * (minus padding) 387 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 388 * enclose its content (plus padding). 389 * </ul> 390 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 391 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 392 * an X and Y value. 393 * </p> 394 * 395 * <p> 396 * MeasureSpecs are used to push requirements down the tree from parent to 397 * child. A MeasureSpec can be in one of three modes: 398 * <ul> 399 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 400 * of a child view. For example, a LinearLayout may call measure() on its child 401 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 402 * tall the child view wants to be given a width of 240 pixels. 403 * <li>EXACTLY: This is used by the parent to impose an exact size on the 404 * child. The child must use this size, and guarantee that all of its 405 * descendants will fit within this size. 406 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 407 * child. The child must gurantee that it and all of its descendants will fit 408 * within this size. 409 * </ul> 410 * </p> 411 * 412 * <p> 413 * To intiate a layout, call {@link #requestLayout}. This method is typically 414 * called by a view on itself when it believes that is can no longer fit within 415 * its current bounds. 416 * </p> 417 * 418 * <a name="Drawing"></a> 419 * <h3>Drawing</h3> 420 * <p> 421 * Drawing is handled by walking the tree and rendering each view that 422 * intersects the invalid region. Because the tree is traversed in-order, 423 * this means that parents will draw before (i.e., behind) their children, with 424 * siblings drawn in the order they appear in the tree. 425 * If you set a background drawable for a View, then the View will draw it for you 426 * before calling back to its <code>onDraw()</code> method. 427 * </p> 428 * 429 * <p> 430 * Note that the framework will not draw views that are not in the invalid region. 431 * </p> 432 * 433 * <p> 434 * To force a view to draw, call {@link #invalidate()}. 435 * </p> 436 * 437 * <a name="EventHandlingThreading"></a> 438 * <h3>Event Handling and Threading</h3> 439 * <p> 440 * The basic cycle of a view is as follows: 441 * <ol> 442 * <li>An event comes in and is dispatched to the appropriate view. The view 443 * handles the event and notifies any listeners.</li> 444 * <li>If in the course of processing the event, the view's bounds may need 445 * to be changed, the view will call {@link #requestLayout()}.</li> 446 * <li>Similarly, if in the course of processing the event the view's appearance 447 * may need to be changed, the view will call {@link #invalidate()}.</li> 448 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 449 * the framework will take care of measuring, laying out, and drawing the tree 450 * as appropriate.</li> 451 * </ol> 452 * </p> 453 * 454 * <p><em>Note: The entire view tree is single threaded. You must always be on 455 * the UI thread when calling any method on any view.</em> 456 * If you are doing work on other threads and want to update the state of a view 457 * from that thread, you should use a {@link Handler}. 458 * </p> 459 * 460 * <a name="FocusHandling"></a> 461 * <h3>Focus Handling</h3> 462 * <p> 463 * The framework will handle routine focus movement in response to user input. 464 * This includes changing the focus as views are removed or hidden, or as new 465 * views become available. Views indicate their willingness to take focus 466 * through the {@link #isFocusable} method. To change whether a view can take 467 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 468 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 469 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 470 * </p> 471 * <p> 472 * Focus movement is based on an algorithm which finds the nearest neighbor in a 473 * given direction. In rare cases, the default algorithm may not match the 474 * intended behavior of the developer. In these situations, you can provide 475 * explicit overrides by using these XML attributes in the layout file: 476 * <pre> 477 * nextFocusDown 478 * nextFocusLeft 479 * nextFocusRight 480 * nextFocusUp 481 * </pre> 482 * </p> 483 * 484 * 485 * <p> 486 * To get a particular view to take focus, call {@link #requestFocus()}. 487 * </p> 488 * 489 * <a name="TouchMode"></a> 490 * <h3>Touch Mode</h3> 491 * <p> 492 * When a user is navigating a user interface via directional keys such as a D-pad, it is 493 * necessary to give focus to actionable items such as buttons so the user can see 494 * what will take input. If the device has touch capabilities, however, and the user 495 * begins interacting with the interface by touching it, it is no longer necessary to 496 * always highlight, or give focus to, a particular view. This motivates a mode 497 * for interaction named 'touch mode'. 498 * </p> 499 * <p> 500 * For a touch capable device, once the user touches the screen, the device 501 * will enter touch mode. From this point onward, only views for which 502 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 503 * Other views that are touchable, like buttons, will not take focus when touched; they will 504 * only fire the on click listeners. 505 * </p> 506 * <p> 507 * Any time a user hits a directional key, such as a D-pad direction, the view device will 508 * exit touch mode, and find a view to take focus, so that the user may resume interacting 509 * with the user interface without touching the screen again. 510 * </p> 511 * <p> 512 * The touch mode state is maintained across {@link android.app.Activity}s. Call 513 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 514 * </p> 515 * 516 * <a name="Scrolling"></a> 517 * <h3>Scrolling</h3> 518 * <p> 519 * The framework provides basic support for views that wish to internally 520 * scroll their content. This includes keeping track of the X and Y scroll 521 * offset as well as mechanisms for drawing scrollbars. See 522 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 523 * {@link #awakenScrollBars()} for more details. 524 * </p> 525 * 526 * <a name="Tags"></a> 527 * <h3>Tags</h3> 528 * <p> 529 * Unlike IDs, tags are not used to identify views. Tags are essentially an 530 * extra piece of information that can be associated with a view. They are most 531 * often used as a convenience to store data related to views in the views 532 * themselves rather than by putting them in a separate structure. 533 * </p> 534 * 535 * <a name="Animation"></a> 536 * <h3>Animation</h3> 537 * <p> 538 * You can attach an {@link Animation} object to a view using 539 * {@link #setAnimation(Animation)} or 540 * {@link #startAnimation(Animation)}. The animation can alter the scale, 541 * rotation, translation and alpha of a view over time. If the animation is 542 * attached to a view that has children, the animation will affect the entire 543 * subtree rooted by that node. When an animation is started, the framework will 544 * take care of redrawing the appropriate views until the animation completes. 545 * </p> 546 * <p> 547 * Starting with Android 3.0, the preferred way of animating views is to use the 548 * {@link android.animation} package APIs. 549 * </p> 550 * 551 * <a name="Security"></a> 552 * <h3>Security</h3> 553 * <p> 554 * Sometimes it is essential that an application be able to verify that an action 555 * is being performed with the full knowledge and consent of the user, such as 556 * granting a permission request, making a purchase or clicking on an advertisement. 557 * Unfortunately, a malicious application could try to spoof the user into 558 * performing these actions, unaware, by concealing the intended purpose of the view. 559 * As a remedy, the framework offers a touch filtering mechanism that can be used to 560 * improve the security of views that provide access to sensitive functionality. 561 * </p><p> 562 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 563 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 564 * will discard touches that are received whenever the view's window is obscured by 565 * another visible window. As a result, the view will not receive touches whenever a 566 * toast, dialog or other window appears above the view's window. 567 * </p><p> 568 * For more fine-grained control over security, consider overriding the 569 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 570 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 571 * </p> 572 * 573 * @attr ref android.R.styleable#View_alpha 574 * @attr ref android.R.styleable#View_background 575 * @attr ref android.R.styleable#View_clickable 576 * @attr ref android.R.styleable#View_contentDescription 577 * @attr ref android.R.styleable#View_drawingCacheQuality 578 * @attr ref android.R.styleable#View_duplicateParentState 579 * @attr ref android.R.styleable#View_id 580 * @attr ref android.R.styleable#View_requiresFadingEdge 581 * @attr ref android.R.styleable#View_fadingEdgeLength 582 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 583 * @attr ref android.R.styleable#View_fitsSystemWindows 584 * @attr ref android.R.styleable#View_isScrollContainer 585 * @attr ref android.R.styleable#View_focusable 586 * @attr ref android.R.styleable#View_focusableInTouchMode 587 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 588 * @attr ref android.R.styleable#View_keepScreenOn 589 * @attr ref android.R.styleable#View_layerType 590 * @attr ref android.R.styleable#View_longClickable 591 * @attr ref android.R.styleable#View_minHeight 592 * @attr ref android.R.styleable#View_minWidth 593 * @attr ref android.R.styleable#View_nextFocusDown 594 * @attr ref android.R.styleable#View_nextFocusLeft 595 * @attr ref android.R.styleable#View_nextFocusRight 596 * @attr ref android.R.styleable#View_nextFocusUp 597 * @attr ref android.R.styleable#View_onClick 598 * @attr ref android.R.styleable#View_padding 599 * @attr ref android.R.styleable#View_paddingBottom 600 * @attr ref android.R.styleable#View_paddingLeft 601 * @attr ref android.R.styleable#View_paddingRight 602 * @attr ref android.R.styleable#View_paddingTop 603 * @attr ref android.R.styleable#View_paddingStart 604 * @attr ref android.R.styleable#View_paddingEnd 605 * @attr ref android.R.styleable#View_saveEnabled 606 * @attr ref android.R.styleable#View_rotation 607 * @attr ref android.R.styleable#View_rotationX 608 * @attr ref android.R.styleable#View_rotationY 609 * @attr ref android.R.styleable#View_scaleX 610 * @attr ref android.R.styleable#View_scaleY 611 * @attr ref android.R.styleable#View_scrollX 612 * @attr ref android.R.styleable#View_scrollY 613 * @attr ref android.R.styleable#View_scrollbarSize 614 * @attr ref android.R.styleable#View_scrollbarStyle 615 * @attr ref android.R.styleable#View_scrollbars 616 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 617 * @attr ref android.R.styleable#View_scrollbarFadeDuration 618 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 619 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 620 * @attr ref android.R.styleable#View_scrollbarThumbVertical 621 * @attr ref android.R.styleable#View_scrollbarTrackVertical 622 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 623 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 624 * @attr ref android.R.styleable#View_soundEffectsEnabled 625 * @attr ref android.R.styleable#View_tag 626 * @attr ref android.R.styleable#View_transformPivotX 627 * @attr ref android.R.styleable#View_transformPivotY 628 * @attr ref android.R.styleable#View_translationX 629 * @attr ref android.R.styleable#View_translationY 630 * @attr ref android.R.styleable#View_visibility 631 * 632 * @see android.view.ViewGroup 633 */ 634public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback, 635 AccessibilityEventSource { 636 private static final boolean DBG = false; 637 638 /** 639 * The logging tag used by this class with android.util.Log. 640 */ 641 protected static final String VIEW_LOG_TAG = "View"; 642 643 /** 644 * Used to mark a View that has no ID. 645 */ 646 public static final int NO_ID = -1; 647 648 /** 649 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 650 * calling setFlags. 651 */ 652 private static final int NOT_FOCUSABLE = 0x00000000; 653 654 /** 655 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 656 * setFlags. 657 */ 658 private static final int FOCUSABLE = 0x00000001; 659 660 /** 661 * Mask for use with setFlags indicating bits used for focus. 662 */ 663 private static final int FOCUSABLE_MASK = 0x00000001; 664 665 /** 666 * This view will adjust its padding to fit sytem windows (e.g. status bar) 667 */ 668 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 669 670 /** 671 * This view is visible. 672 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 673 * android:visibility}. 674 */ 675 public static final int VISIBLE = 0x00000000; 676 677 /** 678 * This view is invisible, but it still takes up space for layout purposes. 679 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 680 * android:visibility}. 681 */ 682 public static final int INVISIBLE = 0x00000004; 683 684 /** 685 * This view is invisible, and it doesn't take any space for layout 686 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 687 * android:visibility}. 688 */ 689 public static final int GONE = 0x00000008; 690 691 /** 692 * Mask for use with setFlags indicating bits used for visibility. 693 * {@hide} 694 */ 695 static final int VISIBILITY_MASK = 0x0000000C; 696 697 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 698 699 /** 700 * This view is enabled. Interpretation varies by subclass. 701 * Use with ENABLED_MASK when calling setFlags. 702 * {@hide} 703 */ 704 static final int ENABLED = 0x00000000; 705 706 /** 707 * This view is disabled. Interpretation varies by subclass. 708 * Use with ENABLED_MASK when calling setFlags. 709 * {@hide} 710 */ 711 static final int DISABLED = 0x00000020; 712 713 /** 714 * Mask for use with setFlags indicating bits used for indicating whether 715 * this view is enabled 716 * {@hide} 717 */ 718 static final int ENABLED_MASK = 0x00000020; 719 720 /** 721 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 722 * called and further optimizations will be performed. It is okay to have 723 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 724 * {@hide} 725 */ 726 static final int WILL_NOT_DRAW = 0x00000080; 727 728 /** 729 * Mask for use with setFlags indicating bits used for indicating whether 730 * this view is will draw 731 * {@hide} 732 */ 733 static final int DRAW_MASK = 0x00000080; 734 735 /** 736 * <p>This view doesn't show scrollbars.</p> 737 * {@hide} 738 */ 739 static final int SCROLLBARS_NONE = 0x00000000; 740 741 /** 742 * <p>This view shows horizontal scrollbars.</p> 743 * {@hide} 744 */ 745 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 746 747 /** 748 * <p>This view shows vertical scrollbars.</p> 749 * {@hide} 750 */ 751 static final int SCROLLBARS_VERTICAL = 0x00000200; 752 753 /** 754 * <p>Mask for use with setFlags indicating bits used for indicating which 755 * scrollbars are enabled.</p> 756 * {@hide} 757 */ 758 static final int SCROLLBARS_MASK = 0x00000300; 759 760 /** 761 * Indicates that the view should filter touches when its window is obscured. 762 * Refer to the class comments for more information about this security feature. 763 * {@hide} 764 */ 765 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 766 767 // note flag value 0x00000800 is now available for next flags... 768 769 /** 770 * <p>This view doesn't show fading edges.</p> 771 * {@hide} 772 */ 773 static final int FADING_EDGE_NONE = 0x00000000; 774 775 /** 776 * <p>This view shows horizontal fading edges.</p> 777 * {@hide} 778 */ 779 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 780 781 /** 782 * <p>This view shows vertical fading edges.</p> 783 * {@hide} 784 */ 785 static final int FADING_EDGE_VERTICAL = 0x00002000; 786 787 /** 788 * <p>Mask for use with setFlags indicating bits used for indicating which 789 * fading edges are enabled.</p> 790 * {@hide} 791 */ 792 static final int FADING_EDGE_MASK = 0x00003000; 793 794 /** 795 * <p>Indicates this view can be clicked. When clickable, a View reacts 796 * to clicks by notifying the OnClickListener.<p> 797 * {@hide} 798 */ 799 static final int CLICKABLE = 0x00004000; 800 801 /** 802 * <p>Indicates this view is caching its drawing into a bitmap.</p> 803 * {@hide} 804 */ 805 static final int DRAWING_CACHE_ENABLED = 0x00008000; 806 807 /** 808 * <p>Indicates that no icicle should be saved for this view.<p> 809 * {@hide} 810 */ 811 static final int SAVE_DISABLED = 0x000010000; 812 813 /** 814 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 815 * property.</p> 816 * {@hide} 817 */ 818 static final int SAVE_DISABLED_MASK = 0x000010000; 819 820 /** 821 * <p>Indicates that no drawing cache should ever be created for this view.<p> 822 * {@hide} 823 */ 824 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 825 826 /** 827 * <p>Indicates this view can take / keep focus when int touch mode.</p> 828 * {@hide} 829 */ 830 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 831 832 /** 833 * <p>Enables low quality mode for the drawing cache.</p> 834 */ 835 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 836 837 /** 838 * <p>Enables high quality mode for the drawing cache.</p> 839 */ 840 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 841 842 /** 843 * <p>Enables automatic quality mode for the drawing cache.</p> 844 */ 845 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 846 847 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 848 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 849 }; 850 851 /** 852 * <p>Mask for use with setFlags indicating bits used for the cache 853 * quality property.</p> 854 * {@hide} 855 */ 856 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 857 858 /** 859 * <p> 860 * Indicates this view can be long clicked. When long clickable, a View 861 * reacts to long clicks by notifying the OnLongClickListener or showing a 862 * context menu. 863 * </p> 864 * {@hide} 865 */ 866 static final int LONG_CLICKABLE = 0x00200000; 867 868 /** 869 * <p>Indicates that this view gets its drawable states from its direct parent 870 * and ignores its original internal states.</p> 871 * 872 * @hide 873 */ 874 static final int DUPLICATE_PARENT_STATE = 0x00400000; 875 876 /** 877 * The scrollbar style to display the scrollbars inside the content area, 878 * without increasing the padding. The scrollbars will be overlaid with 879 * translucency on the view's content. 880 */ 881 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 882 883 /** 884 * The scrollbar style to display the scrollbars inside the padded area, 885 * increasing the padding of the view. The scrollbars will not overlap the 886 * content area of the view. 887 */ 888 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 889 890 /** 891 * The scrollbar style to display the scrollbars at the edge of the view, 892 * without increasing the padding. The scrollbars will be overlaid with 893 * translucency. 894 */ 895 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 896 897 /** 898 * The scrollbar style to display the scrollbars at the edge of the view, 899 * increasing the padding of the view. The scrollbars will only overlap the 900 * background, if any. 901 */ 902 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 903 904 /** 905 * Mask to check if the scrollbar style is overlay or inset. 906 * {@hide} 907 */ 908 static final int SCROLLBARS_INSET_MASK = 0x01000000; 909 910 /** 911 * Mask to check if the scrollbar style is inside or outside. 912 * {@hide} 913 */ 914 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 915 916 /** 917 * Mask for scrollbar style. 918 * {@hide} 919 */ 920 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 921 922 /** 923 * View flag indicating that the screen should remain on while the 924 * window containing this view is visible to the user. This effectively 925 * takes care of automatically setting the WindowManager's 926 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 927 */ 928 public static final int KEEP_SCREEN_ON = 0x04000000; 929 930 /** 931 * View flag indicating whether this view should have sound effects enabled 932 * for events such as clicking and touching. 933 */ 934 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 935 936 /** 937 * View flag indicating whether this view should have haptic feedback 938 * enabled for events such as long presses. 939 */ 940 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 941 942 /** 943 * <p>Indicates that the view hierarchy should stop saving state when 944 * it reaches this view. If state saving is initiated immediately at 945 * the view, it will be allowed. 946 * {@hide} 947 */ 948 static final int PARENT_SAVE_DISABLED = 0x20000000; 949 950 /** 951 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 952 * {@hide} 953 */ 954 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 955 956 /** 957 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 958 * should add all focusable Views regardless if they are focusable in touch mode. 959 */ 960 public static final int FOCUSABLES_ALL = 0x00000000; 961 962 /** 963 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 964 * should add only Views focusable in touch mode. 965 */ 966 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 967 968 /** 969 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 970 * item. 971 */ 972 public static final int FOCUS_BACKWARD = 0x00000001; 973 974 /** 975 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 976 * item. 977 */ 978 public static final int FOCUS_FORWARD = 0x00000002; 979 980 /** 981 * Use with {@link #focusSearch(int)}. Move focus to the left. 982 */ 983 public static final int FOCUS_LEFT = 0x00000011; 984 985 /** 986 * Use with {@link #focusSearch(int)}. Move focus up. 987 */ 988 public static final int FOCUS_UP = 0x00000021; 989 990 /** 991 * Use with {@link #focusSearch(int)}. Move focus to the right. 992 */ 993 public static final int FOCUS_RIGHT = 0x00000042; 994 995 /** 996 * Use with {@link #focusSearch(int)}. Move focus down. 997 */ 998 public static final int FOCUS_DOWN = 0x00000082; 999 1000 /** 1001 * Bits of {@link #getMeasuredWidthAndState()} and 1002 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1003 */ 1004 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1005 1006 /** 1007 * Bits of {@link #getMeasuredWidthAndState()} and 1008 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1009 */ 1010 public static final int MEASURED_STATE_MASK = 0xff000000; 1011 1012 /** 1013 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1014 * for functions that combine both width and height into a single int, 1015 * such as {@link #getMeasuredState()} and the childState argument of 1016 * {@link #resolveSizeAndState(int, int, int)}. 1017 */ 1018 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1019 1020 /** 1021 * Bit of {@link #getMeasuredWidthAndState()} and 1022 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1023 * is smaller that the space the view would like to have. 1024 */ 1025 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1026 1027 /** 1028 * Base View state sets 1029 */ 1030 // Singles 1031 /** 1032 * Indicates the view has no states set. States are used with 1033 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1034 * view depending on its state. 1035 * 1036 * @see android.graphics.drawable.Drawable 1037 * @see #getDrawableState() 1038 */ 1039 protected static final int[] EMPTY_STATE_SET; 1040 /** 1041 * Indicates the view is enabled. States are used with 1042 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1043 * view depending on its state. 1044 * 1045 * @see android.graphics.drawable.Drawable 1046 * @see #getDrawableState() 1047 */ 1048 protected static final int[] ENABLED_STATE_SET; 1049 /** 1050 * Indicates the view is focused. States are used with 1051 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1052 * view depending on its state. 1053 * 1054 * @see android.graphics.drawable.Drawable 1055 * @see #getDrawableState() 1056 */ 1057 protected static final int[] FOCUSED_STATE_SET; 1058 /** 1059 * Indicates the view is selected. States are used with 1060 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1061 * view depending on its state. 1062 * 1063 * @see android.graphics.drawable.Drawable 1064 * @see #getDrawableState() 1065 */ 1066 protected static final int[] SELECTED_STATE_SET; 1067 /** 1068 * Indicates the view is pressed. States are used with 1069 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1070 * view depending on its state. 1071 * 1072 * @see android.graphics.drawable.Drawable 1073 * @see #getDrawableState() 1074 * @hide 1075 */ 1076 protected static final int[] PRESSED_STATE_SET; 1077 /** 1078 * Indicates the view's window has focus. States are used with 1079 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1080 * view depending on its state. 1081 * 1082 * @see android.graphics.drawable.Drawable 1083 * @see #getDrawableState() 1084 */ 1085 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1086 // Doubles 1087 /** 1088 * Indicates the view is enabled and has the focus. 1089 * 1090 * @see #ENABLED_STATE_SET 1091 * @see #FOCUSED_STATE_SET 1092 */ 1093 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1094 /** 1095 * Indicates the view is enabled and selected. 1096 * 1097 * @see #ENABLED_STATE_SET 1098 * @see #SELECTED_STATE_SET 1099 */ 1100 protected static final int[] ENABLED_SELECTED_STATE_SET; 1101 /** 1102 * Indicates the view is enabled and that its window has focus. 1103 * 1104 * @see #ENABLED_STATE_SET 1105 * @see #WINDOW_FOCUSED_STATE_SET 1106 */ 1107 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1108 /** 1109 * Indicates the view is focused and selected. 1110 * 1111 * @see #FOCUSED_STATE_SET 1112 * @see #SELECTED_STATE_SET 1113 */ 1114 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1115 /** 1116 * Indicates the view has the focus and that its window has the focus. 1117 * 1118 * @see #FOCUSED_STATE_SET 1119 * @see #WINDOW_FOCUSED_STATE_SET 1120 */ 1121 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1122 /** 1123 * Indicates the view is selected and that its window has the focus. 1124 * 1125 * @see #SELECTED_STATE_SET 1126 * @see #WINDOW_FOCUSED_STATE_SET 1127 */ 1128 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1129 // Triples 1130 /** 1131 * Indicates the view is enabled, focused and selected. 1132 * 1133 * @see #ENABLED_STATE_SET 1134 * @see #FOCUSED_STATE_SET 1135 * @see #SELECTED_STATE_SET 1136 */ 1137 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1138 /** 1139 * Indicates the view is enabled, focused and its window has the focus. 1140 * 1141 * @see #ENABLED_STATE_SET 1142 * @see #FOCUSED_STATE_SET 1143 * @see #WINDOW_FOCUSED_STATE_SET 1144 */ 1145 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1146 /** 1147 * Indicates the view is enabled, selected and its window has the focus. 1148 * 1149 * @see #ENABLED_STATE_SET 1150 * @see #SELECTED_STATE_SET 1151 * @see #WINDOW_FOCUSED_STATE_SET 1152 */ 1153 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1154 /** 1155 * Indicates the view is focused, selected and its window has the focus. 1156 * 1157 * @see #FOCUSED_STATE_SET 1158 * @see #SELECTED_STATE_SET 1159 * @see #WINDOW_FOCUSED_STATE_SET 1160 */ 1161 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1162 /** 1163 * Indicates the view is enabled, focused, selected and its window 1164 * has the focus. 1165 * 1166 * @see #ENABLED_STATE_SET 1167 * @see #FOCUSED_STATE_SET 1168 * @see #SELECTED_STATE_SET 1169 * @see #WINDOW_FOCUSED_STATE_SET 1170 */ 1171 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1172 /** 1173 * Indicates the view is pressed and its window has the focus. 1174 * 1175 * @see #PRESSED_STATE_SET 1176 * @see #WINDOW_FOCUSED_STATE_SET 1177 */ 1178 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1179 /** 1180 * Indicates the view is pressed and selected. 1181 * 1182 * @see #PRESSED_STATE_SET 1183 * @see #SELECTED_STATE_SET 1184 */ 1185 protected static final int[] PRESSED_SELECTED_STATE_SET; 1186 /** 1187 * Indicates the view is pressed, selected and its window has the focus. 1188 * 1189 * @see #PRESSED_STATE_SET 1190 * @see #SELECTED_STATE_SET 1191 * @see #WINDOW_FOCUSED_STATE_SET 1192 */ 1193 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1194 /** 1195 * Indicates the view is pressed and focused. 1196 * 1197 * @see #PRESSED_STATE_SET 1198 * @see #FOCUSED_STATE_SET 1199 */ 1200 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1201 /** 1202 * Indicates the view is pressed, focused and its window has the focus. 1203 * 1204 * @see #PRESSED_STATE_SET 1205 * @see #FOCUSED_STATE_SET 1206 * @see #WINDOW_FOCUSED_STATE_SET 1207 */ 1208 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1209 /** 1210 * Indicates the view is pressed, focused and selected. 1211 * 1212 * @see #PRESSED_STATE_SET 1213 * @see #SELECTED_STATE_SET 1214 * @see #FOCUSED_STATE_SET 1215 */ 1216 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1217 /** 1218 * Indicates the view is pressed, focused, selected and its window has the focus. 1219 * 1220 * @see #PRESSED_STATE_SET 1221 * @see #FOCUSED_STATE_SET 1222 * @see #SELECTED_STATE_SET 1223 * @see #WINDOW_FOCUSED_STATE_SET 1224 */ 1225 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1226 /** 1227 * Indicates the view is pressed and enabled. 1228 * 1229 * @see #PRESSED_STATE_SET 1230 * @see #ENABLED_STATE_SET 1231 */ 1232 protected static final int[] PRESSED_ENABLED_STATE_SET; 1233 /** 1234 * Indicates the view is pressed, enabled and its window has the focus. 1235 * 1236 * @see #PRESSED_STATE_SET 1237 * @see #ENABLED_STATE_SET 1238 * @see #WINDOW_FOCUSED_STATE_SET 1239 */ 1240 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1241 /** 1242 * Indicates the view is pressed, enabled and selected. 1243 * 1244 * @see #PRESSED_STATE_SET 1245 * @see #ENABLED_STATE_SET 1246 * @see #SELECTED_STATE_SET 1247 */ 1248 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1249 /** 1250 * Indicates the view is pressed, enabled, selected and its window has the 1251 * focus. 1252 * 1253 * @see #PRESSED_STATE_SET 1254 * @see #ENABLED_STATE_SET 1255 * @see #SELECTED_STATE_SET 1256 * @see #WINDOW_FOCUSED_STATE_SET 1257 */ 1258 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1259 /** 1260 * Indicates the view is pressed, enabled and focused. 1261 * 1262 * @see #PRESSED_STATE_SET 1263 * @see #ENABLED_STATE_SET 1264 * @see #FOCUSED_STATE_SET 1265 */ 1266 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1267 /** 1268 * Indicates the view is pressed, enabled, focused and its window has the 1269 * focus. 1270 * 1271 * @see #PRESSED_STATE_SET 1272 * @see #ENABLED_STATE_SET 1273 * @see #FOCUSED_STATE_SET 1274 * @see #WINDOW_FOCUSED_STATE_SET 1275 */ 1276 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1277 /** 1278 * Indicates the view is pressed, enabled, focused and selected. 1279 * 1280 * @see #PRESSED_STATE_SET 1281 * @see #ENABLED_STATE_SET 1282 * @see #SELECTED_STATE_SET 1283 * @see #FOCUSED_STATE_SET 1284 */ 1285 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1286 /** 1287 * Indicates the view is pressed, enabled, focused, selected and its window 1288 * has the focus. 1289 * 1290 * @see #PRESSED_STATE_SET 1291 * @see #ENABLED_STATE_SET 1292 * @see #SELECTED_STATE_SET 1293 * @see #FOCUSED_STATE_SET 1294 * @see #WINDOW_FOCUSED_STATE_SET 1295 */ 1296 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1297 1298 /** 1299 * The order here is very important to {@link #getDrawableState()} 1300 */ 1301 private static final int[][] VIEW_STATE_SETS; 1302 1303 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1304 static final int VIEW_STATE_SELECTED = 1 << 1; 1305 static final int VIEW_STATE_FOCUSED = 1 << 2; 1306 static final int VIEW_STATE_ENABLED = 1 << 3; 1307 static final int VIEW_STATE_PRESSED = 1 << 4; 1308 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1309 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1310 static final int VIEW_STATE_HOVERED = 1 << 7; 1311 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1312 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1313 1314 static final int[] VIEW_STATE_IDS = new int[] { 1315 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1316 R.attr.state_selected, VIEW_STATE_SELECTED, 1317 R.attr.state_focused, VIEW_STATE_FOCUSED, 1318 R.attr.state_enabled, VIEW_STATE_ENABLED, 1319 R.attr.state_pressed, VIEW_STATE_PRESSED, 1320 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1321 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1322 R.attr.state_hovered, VIEW_STATE_HOVERED, 1323 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1324 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED, 1325 }; 1326 1327 static { 1328 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1329 throw new IllegalStateException( 1330 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1331 } 1332 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1333 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1334 int viewState = R.styleable.ViewDrawableStates[i]; 1335 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1336 if (VIEW_STATE_IDS[j] == viewState) { 1337 orderedIds[i * 2] = viewState; 1338 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1339 } 1340 } 1341 } 1342 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1343 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1344 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1345 int numBits = Integer.bitCount(i); 1346 int[] set = new int[numBits]; 1347 int pos = 0; 1348 for (int j = 0; j < orderedIds.length; j += 2) { 1349 if ((i & orderedIds[j+1]) != 0) { 1350 set[pos++] = orderedIds[j]; 1351 } 1352 } 1353 VIEW_STATE_SETS[i] = set; 1354 } 1355 1356 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1357 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1358 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1359 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1360 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1361 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1362 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1363 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1364 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1365 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1366 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1367 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1368 | VIEW_STATE_FOCUSED]; 1369 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1370 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1371 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1372 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1373 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1374 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1375 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1376 | VIEW_STATE_ENABLED]; 1377 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1378 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1379 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1380 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1381 | VIEW_STATE_ENABLED]; 1382 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1383 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1384 | VIEW_STATE_ENABLED]; 1385 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1386 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1387 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1388 1389 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1390 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1391 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1392 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1393 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1394 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1395 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1396 | VIEW_STATE_PRESSED]; 1397 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1398 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1399 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1400 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1401 | VIEW_STATE_PRESSED]; 1402 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1403 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1404 | VIEW_STATE_PRESSED]; 1405 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1406 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1407 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1408 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1409 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1410 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1411 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1412 | VIEW_STATE_PRESSED]; 1413 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1414 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1415 | VIEW_STATE_PRESSED]; 1416 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1417 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1418 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1419 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1420 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1421 | VIEW_STATE_PRESSED]; 1422 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1423 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1424 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1425 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1426 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1427 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1428 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1429 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1430 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1431 | VIEW_STATE_PRESSED]; 1432 } 1433 1434 /** 1435 * Accessibility event types that are dispatched for text population. 1436 */ 1437 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1438 AccessibilityEvent.TYPE_VIEW_CLICKED 1439 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1440 | AccessibilityEvent.TYPE_VIEW_SELECTED 1441 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1442 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1443 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1444 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1445 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1446 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED; 1447 1448 /** 1449 * Temporary Rect currently for use in setBackground(). This will probably 1450 * be extended in the future to hold our own class with more than just 1451 * a Rect. :) 1452 */ 1453 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1454 1455 /** 1456 * Map used to store views' tags. 1457 */ 1458 private SparseArray<Object> mKeyedTags; 1459 1460 /** 1461 * The next available accessiiblity id. 1462 */ 1463 private static int sNextAccessibilityViewId; 1464 1465 /** 1466 * The animation currently associated with this view. 1467 * @hide 1468 */ 1469 protected Animation mCurrentAnimation = null; 1470 1471 /** 1472 * Width as measured during measure pass. 1473 * {@hide} 1474 */ 1475 @ViewDebug.ExportedProperty(category = "measurement") 1476 int mMeasuredWidth; 1477 1478 /** 1479 * Height as measured during measure pass. 1480 * {@hide} 1481 */ 1482 @ViewDebug.ExportedProperty(category = "measurement") 1483 int mMeasuredHeight; 1484 1485 /** 1486 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1487 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1488 * its display list. This flag, used only when hw accelerated, allows us to clear the 1489 * flag while retaining this information until it's needed (at getDisplayList() time and 1490 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1491 * 1492 * {@hide} 1493 */ 1494 boolean mRecreateDisplayList = false; 1495 1496 /** 1497 * The view's identifier. 1498 * {@hide} 1499 * 1500 * @see #setId(int) 1501 * @see #getId() 1502 */ 1503 @ViewDebug.ExportedProperty(resolveId = true) 1504 int mID = NO_ID; 1505 1506 /** 1507 * The stable ID of this view for accessibility purposes. 1508 */ 1509 int mAccessibilityViewId = NO_ID; 1510 1511 /** 1512 * The view's tag. 1513 * {@hide} 1514 * 1515 * @see #setTag(Object) 1516 * @see #getTag() 1517 */ 1518 protected Object mTag; 1519 1520 // for mPrivateFlags: 1521 /** {@hide} */ 1522 static final int WANTS_FOCUS = 0x00000001; 1523 /** {@hide} */ 1524 static final int FOCUSED = 0x00000002; 1525 /** {@hide} */ 1526 static final int SELECTED = 0x00000004; 1527 /** {@hide} */ 1528 static final int IS_ROOT_NAMESPACE = 0x00000008; 1529 /** {@hide} */ 1530 static final int HAS_BOUNDS = 0x00000010; 1531 /** {@hide} */ 1532 static final int DRAWN = 0x00000020; 1533 /** 1534 * When this flag is set, this view is running an animation on behalf of its 1535 * children and should therefore not cancel invalidate requests, even if they 1536 * lie outside of this view's bounds. 1537 * 1538 * {@hide} 1539 */ 1540 static final int DRAW_ANIMATION = 0x00000040; 1541 /** {@hide} */ 1542 static final int SKIP_DRAW = 0x00000080; 1543 /** {@hide} */ 1544 static final int ONLY_DRAWS_BACKGROUND = 0x00000100; 1545 /** {@hide} */ 1546 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1547 /** {@hide} */ 1548 static final int DRAWABLE_STATE_DIRTY = 0x00000400; 1549 /** {@hide} */ 1550 static final int MEASURED_DIMENSION_SET = 0x00000800; 1551 /** {@hide} */ 1552 static final int FORCE_LAYOUT = 0x00001000; 1553 /** {@hide} */ 1554 static final int LAYOUT_REQUIRED = 0x00002000; 1555 1556 private static final int PRESSED = 0x00004000; 1557 1558 /** {@hide} */ 1559 static final int DRAWING_CACHE_VALID = 0x00008000; 1560 /** 1561 * Flag used to indicate that this view should be drawn once more (and only once 1562 * more) after its animation has completed. 1563 * {@hide} 1564 */ 1565 static final int ANIMATION_STARTED = 0x00010000; 1566 1567 private static final int SAVE_STATE_CALLED = 0x00020000; 1568 1569 /** 1570 * Indicates that the View returned true when onSetAlpha() was called and that 1571 * the alpha must be restored. 1572 * {@hide} 1573 */ 1574 static final int ALPHA_SET = 0x00040000; 1575 1576 /** 1577 * Set by {@link #setScrollContainer(boolean)}. 1578 */ 1579 static final int SCROLL_CONTAINER = 0x00080000; 1580 1581 /** 1582 * Set by {@link #setScrollContainer(boolean)}. 1583 */ 1584 static final int SCROLL_CONTAINER_ADDED = 0x00100000; 1585 1586 /** 1587 * View flag indicating whether this view was invalidated (fully or partially.) 1588 * 1589 * @hide 1590 */ 1591 static final int DIRTY = 0x00200000; 1592 1593 /** 1594 * View flag indicating whether this view was invalidated by an opaque 1595 * invalidate request. 1596 * 1597 * @hide 1598 */ 1599 static final int DIRTY_OPAQUE = 0x00400000; 1600 1601 /** 1602 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}. 1603 * 1604 * @hide 1605 */ 1606 static final int DIRTY_MASK = 0x00600000; 1607 1608 /** 1609 * Indicates whether the background is opaque. 1610 * 1611 * @hide 1612 */ 1613 static final int OPAQUE_BACKGROUND = 0x00800000; 1614 1615 /** 1616 * Indicates whether the scrollbars are opaque. 1617 * 1618 * @hide 1619 */ 1620 static final int OPAQUE_SCROLLBARS = 0x01000000; 1621 1622 /** 1623 * Indicates whether the view is opaque. 1624 * 1625 * @hide 1626 */ 1627 static final int OPAQUE_MASK = 0x01800000; 1628 1629 /** 1630 * Indicates a prepressed state; 1631 * the short time between ACTION_DOWN and recognizing 1632 * a 'real' press. Prepressed is used to recognize quick taps 1633 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1634 * 1635 * @hide 1636 */ 1637 private static final int PREPRESSED = 0x02000000; 1638 1639 /** 1640 * Indicates whether the view is temporarily detached. 1641 * 1642 * @hide 1643 */ 1644 static final int CANCEL_NEXT_UP_EVENT = 0x04000000; 1645 1646 /** 1647 * Indicates that we should awaken scroll bars once attached 1648 * 1649 * @hide 1650 */ 1651 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1652 1653 /** 1654 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1655 * @hide 1656 */ 1657 private static final int HOVERED = 0x10000000; 1658 1659 /** 1660 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1661 * for transform operations 1662 * 1663 * @hide 1664 */ 1665 private static final int PIVOT_EXPLICITLY_SET = 0x20000000; 1666 1667 /** {@hide} */ 1668 static final int ACTIVATED = 0x40000000; 1669 1670 /** 1671 * Indicates that this view was specifically invalidated, not just dirtied because some 1672 * child view was invalidated. The flag is used to determine when we need to recreate 1673 * a view's display list (as opposed to just returning a reference to its existing 1674 * display list). 1675 * 1676 * @hide 1677 */ 1678 static final int INVALIDATED = 0x80000000; 1679 1680 /* Masks for mPrivateFlags2 */ 1681 1682 /** 1683 * Indicates that this view has reported that it can accept the current drag's content. 1684 * Cleared when the drag operation concludes. 1685 * @hide 1686 */ 1687 static final int DRAG_CAN_ACCEPT = 0x00000001; 1688 1689 /** 1690 * Indicates that this view is currently directly under the drag location in a 1691 * drag-and-drop operation involving content that it can accept. Cleared when 1692 * the drag exits the view, or when the drag operation concludes. 1693 * @hide 1694 */ 1695 static final int DRAG_HOVERED = 0x00000002; 1696 1697 /** 1698 * Horizontal layout direction of this view is from Left to Right. 1699 * Use with {@link #setLayoutDirection}. 1700 */ 1701 public static final int LAYOUT_DIRECTION_LTR = 0x00000001; 1702 1703 /** 1704 * Horizontal layout direction of this view is from Right to Left. 1705 * Use with {@link #setLayoutDirection}. 1706 */ 1707 public static final int LAYOUT_DIRECTION_RTL = 0x00000002; 1708 1709 /** 1710 * Horizontal layout direction of this view is inherited from its parent. 1711 * Use with {@link #setLayoutDirection}. 1712 */ 1713 public static final int LAYOUT_DIRECTION_INHERIT = 0x00000004; 1714 1715 /** 1716 * Horizontal layout direction of this view is from deduced from the default language 1717 * script for the locale. Use with {@link #setLayoutDirection}. 1718 */ 1719 public static final int LAYOUT_DIRECTION_LOCALE = 0x00000008; 1720 1721 /** 1722 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1723 * @hide 1724 */ 1725 static final int LAYOUT_DIRECTION_MASK_SHIFT = 2; 1726 1727 /** 1728 * Mask for use with private flags indicating bits used for horizontal layout direction. 1729 * @hide 1730 */ 1731 static final int LAYOUT_DIRECTION_MASK = 0x0000000F << LAYOUT_DIRECTION_MASK_SHIFT; 1732 1733 /** 1734 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1735 * right-to-left direction. 1736 * @hide 1737 */ 1738 static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000010 << LAYOUT_DIRECTION_MASK_SHIFT; 1739 1740 /** 1741 * Indicates whether the view horizontal layout direction has been resolved. 1742 * @hide 1743 */ 1744 static final int LAYOUT_DIRECTION_RESOLVED = 0x00000020 << LAYOUT_DIRECTION_MASK_SHIFT; 1745 1746 /** 1747 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1748 * @hide 1749 */ 1750 static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x00000030 << LAYOUT_DIRECTION_MASK_SHIFT; 1751 1752 /* 1753 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1754 * flag value. 1755 * @hide 1756 */ 1757 private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR, 1758 LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE}; 1759 1760 /** 1761 * Default horizontal layout direction. 1762 * @hide 1763 */ 1764 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1765 1766 1767 /** 1768 * Indicates that the view is tracking some sort of transient state 1769 * that the app should not need to be aware of, but that the framework 1770 * should take special care to preserve. 1771 * 1772 * @hide 1773 */ 1774 static final int HAS_TRANSIENT_STATE = 0x00000100; 1775 1776 1777 /* End of masks for mPrivateFlags2 */ 1778 1779 static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED; 1780 1781 /** 1782 * Always allow a user to over-scroll this view, provided it is a 1783 * view that can scroll. 1784 * 1785 * @see #getOverScrollMode() 1786 * @see #setOverScrollMode(int) 1787 */ 1788 public static final int OVER_SCROLL_ALWAYS = 0; 1789 1790 /** 1791 * Allow a user to over-scroll this view only if the content is large 1792 * enough to meaningfully scroll, provided it is a view that can scroll. 1793 * 1794 * @see #getOverScrollMode() 1795 * @see #setOverScrollMode(int) 1796 */ 1797 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 1798 1799 /** 1800 * Never allow a user to over-scroll this view. 1801 * 1802 * @see #getOverScrollMode() 1803 * @see #setOverScrollMode(int) 1804 */ 1805 public static final int OVER_SCROLL_NEVER = 2; 1806 1807 /** 1808 * View has requested the system UI (status bar) to be visible (the default). 1809 * 1810 * @see #setSystemUiVisibility(int) 1811 */ 1812 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 1813 1814 /** 1815 * View has requested the system UI to enter an unobtrusive "low profile" mode. 1816 * 1817 * This is for use in games, book readers, video players, or any other "immersive" application 1818 * where the usual system chrome is deemed too distracting. 1819 * 1820 * In low profile mode, the status bar and/or navigation icons may dim. 1821 * 1822 * @see #setSystemUiVisibility(int) 1823 */ 1824 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 1825 1826 /** 1827 * View has requested that the system navigation be temporarily hidden. 1828 * 1829 * This is an even less obtrusive state than that called for by 1830 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 1831 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 1832 * those to disappear. This is useful (in conjunction with the 1833 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 1834 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 1835 * window flags) for displaying content using every last pixel on the display. 1836 * 1837 * There is a limitation: because navigation controls are so important, the least user 1838 * interaction will cause them to reappear immediately. 1839 * 1840 * @see #setSystemUiVisibility(int) 1841 */ 1842 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 1843 1844 /** 1845 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 1846 */ 1847 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 1848 1849 /** 1850 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 1851 */ 1852 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 1853 1854 /** 1855 * @hide 1856 * 1857 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1858 * out of the public fields to keep the undefined bits out of the developer's way. 1859 * 1860 * Flag to make the status bar not expandable. Unless you also 1861 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 1862 */ 1863 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 1864 1865 /** 1866 * @hide 1867 * 1868 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1869 * out of the public fields to keep the undefined bits out of the developer's way. 1870 * 1871 * Flag to hide notification icons and scrolling ticker text. 1872 */ 1873 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 1874 1875 /** 1876 * @hide 1877 * 1878 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1879 * out of the public fields to keep the undefined bits out of the developer's way. 1880 * 1881 * Flag to disable incoming notification alerts. This will not block 1882 * icons, but it will block sound, vibrating and other visual or aural notifications. 1883 */ 1884 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 1885 1886 /** 1887 * @hide 1888 * 1889 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1890 * out of the public fields to keep the undefined bits out of the developer's way. 1891 * 1892 * Flag to hide only the scrolling ticker. Note that 1893 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 1894 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 1895 */ 1896 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 1897 1898 /** 1899 * @hide 1900 * 1901 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1902 * out of the public fields to keep the undefined bits out of the developer's way. 1903 * 1904 * Flag to hide the center system info area. 1905 */ 1906 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 1907 1908 /** 1909 * @hide 1910 * 1911 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1912 * out of the public fields to keep the undefined bits out of the developer's way. 1913 * 1914 * Flag to hide only the home button. Don't use this 1915 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1916 */ 1917 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 1918 1919 /** 1920 * @hide 1921 * 1922 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1923 * out of the public fields to keep the undefined bits out of the developer's way. 1924 * 1925 * Flag to hide only the back button. Don't use this 1926 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1927 */ 1928 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 1929 1930 /** 1931 * @hide 1932 * 1933 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1934 * out of the public fields to keep the undefined bits out of the developer's way. 1935 * 1936 * Flag to hide only the clock. You might use this if your activity has 1937 * its own clock making the status bar's clock redundant. 1938 */ 1939 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 1940 1941 /** 1942 * @hide 1943 * 1944 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1945 * out of the public fields to keep the undefined bits out of the developer's way. 1946 * 1947 * Flag to hide only the recent apps button. Don't use this 1948 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1949 */ 1950 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 1951 1952 /** 1953 * @hide 1954 * 1955 * NOTE: This flag may only be used in subtreeSystemUiVisibility, etc. etc. 1956 * 1957 * This hides HOME and RECENT and is provided for compatibility with interim implementations. 1958 */ 1959 @Deprecated 1960 public static final int STATUS_BAR_DISABLE_NAVIGATION = 1961 STATUS_BAR_DISABLE_HOME | STATUS_BAR_DISABLE_RECENT; 1962 1963 /** 1964 * @hide 1965 */ 1966 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 1967 1968 /** 1969 * These are the system UI flags that can be cleared by events outside 1970 * of an application. Currently this is just the ability to tap on the 1971 * screen while hiding the navigation bar to have it return. 1972 * @hide 1973 */ 1974 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 1975 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION; 1976 1977 /** 1978 * Find views that render the specified text. 1979 * 1980 * @see #findViewsWithText(ArrayList, CharSequence, int) 1981 */ 1982 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 1983 1984 /** 1985 * Find find views that contain the specified content description. 1986 * 1987 * @see #findViewsWithText(ArrayList, CharSequence, int) 1988 */ 1989 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 1990 1991 /** 1992 * Find views that contain {@link AccessibilityNodeProvider}. Such 1993 * a View is a root of virtual view hierarchy and may contain the searched 1994 * text. If this flag is set Views with providers are automatically 1995 * added and it is a responsibility of the client to call the APIs of 1996 * the provider to determine whether the virtual tree rooted at this View 1997 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 1998 * represeting the virtual views with this text. 1999 * 2000 * @see #findViewsWithText(ArrayList, CharSequence, int) 2001 * 2002 * @hide 2003 */ 2004 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2005 2006 /** 2007 * Indicates that the screen has changed state and is now off. 2008 * 2009 * @see #onScreenStateChanged(int) 2010 */ 2011 public static final int SCREEN_STATE_OFF = 0x0; 2012 2013 /** 2014 * Indicates that the screen has changed state and is now on. 2015 * 2016 * @see #onScreenStateChanged(int) 2017 */ 2018 public static final int SCREEN_STATE_ON = 0x1; 2019 2020 /** 2021 * Controls the over-scroll mode for this view. 2022 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2023 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2024 * and {@link #OVER_SCROLL_NEVER}. 2025 */ 2026 private int mOverScrollMode; 2027 2028 /** 2029 * The parent this view is attached to. 2030 * {@hide} 2031 * 2032 * @see #getParent() 2033 */ 2034 protected ViewParent mParent; 2035 2036 /** 2037 * {@hide} 2038 */ 2039 AttachInfo mAttachInfo; 2040 2041 /** 2042 * {@hide} 2043 */ 2044 @ViewDebug.ExportedProperty(flagMapping = { 2045 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT, 2046 name = "FORCE_LAYOUT"), 2047 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED, 2048 name = "LAYOUT_REQUIRED"), 2049 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID, 2050 name = "DRAWING_CACHE_INVALID", outputIf = false), 2051 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true), 2052 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false), 2053 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2054 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY") 2055 }) 2056 int mPrivateFlags; 2057 int mPrivateFlags2; 2058 2059 /** 2060 * This view's request for the visibility of the status bar. 2061 * @hide 2062 */ 2063 @ViewDebug.ExportedProperty(flagMapping = { 2064 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2065 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2066 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2067 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2068 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2069 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2070 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2071 equals = SYSTEM_UI_FLAG_VISIBLE, 2072 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2073 }) 2074 int mSystemUiVisibility; 2075 2076 /** 2077 * Count of how many windows this view has been attached to. 2078 */ 2079 int mWindowAttachCount; 2080 2081 /** 2082 * The layout parameters associated with this view and used by the parent 2083 * {@link android.view.ViewGroup} to determine how this view should be 2084 * laid out. 2085 * {@hide} 2086 */ 2087 protected ViewGroup.LayoutParams mLayoutParams; 2088 2089 /** 2090 * The view flags hold various views states. 2091 * {@hide} 2092 */ 2093 @ViewDebug.ExportedProperty 2094 int mViewFlags; 2095 2096 static class TransformationInfo { 2097 /** 2098 * The transform matrix for the View. This transform is calculated internally 2099 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2100 * is used by default. Do *not* use this variable directly; instead call 2101 * getMatrix(), which will automatically recalculate the matrix if necessary 2102 * to get the correct matrix based on the latest rotation and scale properties. 2103 */ 2104 private final Matrix mMatrix = new Matrix(); 2105 2106 /** 2107 * The transform matrix for the View. This transform is calculated internally 2108 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2109 * is used by default. Do *not* use this variable directly; instead call 2110 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2111 * to get the correct matrix based on the latest rotation and scale properties. 2112 */ 2113 private Matrix mInverseMatrix; 2114 2115 /** 2116 * An internal variable that tracks whether we need to recalculate the 2117 * transform matrix, based on whether the rotation or scaleX/Y properties 2118 * have changed since the matrix was last calculated. 2119 */ 2120 boolean mMatrixDirty = false; 2121 2122 /** 2123 * An internal variable that tracks whether we need to recalculate the 2124 * transform matrix, based on whether the rotation or scaleX/Y properties 2125 * have changed since the matrix was last calculated. 2126 */ 2127 private boolean mInverseMatrixDirty = true; 2128 2129 /** 2130 * A variable that tracks whether we need to recalculate the 2131 * transform matrix, based on whether the rotation or scaleX/Y properties 2132 * have changed since the matrix was last calculated. This variable 2133 * is only valid after a call to updateMatrix() or to a function that 2134 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2135 */ 2136 private boolean mMatrixIsIdentity = true; 2137 2138 /** 2139 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2140 */ 2141 private Camera mCamera = null; 2142 2143 /** 2144 * This matrix is used when computing the matrix for 3D rotations. 2145 */ 2146 private Matrix matrix3D = null; 2147 2148 /** 2149 * These prev values are used to recalculate a centered pivot point when necessary. The 2150 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2151 * set), so thes values are only used then as well. 2152 */ 2153 private int mPrevWidth = -1; 2154 private int mPrevHeight = -1; 2155 2156 /** 2157 * The degrees rotation around the vertical axis through the pivot point. 2158 */ 2159 @ViewDebug.ExportedProperty 2160 float mRotationY = 0f; 2161 2162 /** 2163 * The degrees rotation around the horizontal axis through the pivot point. 2164 */ 2165 @ViewDebug.ExportedProperty 2166 float mRotationX = 0f; 2167 2168 /** 2169 * The degrees rotation around the pivot point. 2170 */ 2171 @ViewDebug.ExportedProperty 2172 float mRotation = 0f; 2173 2174 /** 2175 * The amount of translation of the object away from its left property (post-layout). 2176 */ 2177 @ViewDebug.ExportedProperty 2178 float mTranslationX = 0f; 2179 2180 /** 2181 * The amount of translation of the object away from its top property (post-layout). 2182 */ 2183 @ViewDebug.ExportedProperty 2184 float mTranslationY = 0f; 2185 2186 /** 2187 * The amount of scale in the x direction around the pivot point. A 2188 * value of 1 means no scaling is applied. 2189 */ 2190 @ViewDebug.ExportedProperty 2191 float mScaleX = 1f; 2192 2193 /** 2194 * The amount of scale in the y direction around the pivot point. A 2195 * value of 1 means no scaling is applied. 2196 */ 2197 @ViewDebug.ExportedProperty 2198 float mScaleY = 1f; 2199 2200 /** 2201 * The x location of the point around which the view is rotated and scaled. 2202 */ 2203 @ViewDebug.ExportedProperty 2204 float mPivotX = 0f; 2205 2206 /** 2207 * The y location of the point around which the view is rotated and scaled. 2208 */ 2209 @ViewDebug.ExportedProperty 2210 float mPivotY = 0f; 2211 2212 /** 2213 * The opacity of the View. This is a value from 0 to 1, where 0 means 2214 * completely transparent and 1 means completely opaque. 2215 */ 2216 @ViewDebug.ExportedProperty 2217 float mAlpha = 1f; 2218 } 2219 2220 TransformationInfo mTransformationInfo; 2221 2222 private boolean mLastIsOpaque; 2223 2224 /** 2225 * Convenience value to check for float values that are close enough to zero to be considered 2226 * zero. 2227 */ 2228 private static final float NONZERO_EPSILON = .001f; 2229 2230 /** 2231 * The distance in pixels from the left edge of this view's parent 2232 * to the left edge of this view. 2233 * {@hide} 2234 */ 2235 @ViewDebug.ExportedProperty(category = "layout") 2236 protected int mLeft; 2237 /** 2238 * The distance in pixels from the left edge of this view's parent 2239 * to the right edge of this view. 2240 * {@hide} 2241 */ 2242 @ViewDebug.ExportedProperty(category = "layout") 2243 protected int mRight; 2244 /** 2245 * The distance in pixels from the top edge of this view's parent 2246 * to the top edge of this view. 2247 * {@hide} 2248 */ 2249 @ViewDebug.ExportedProperty(category = "layout") 2250 protected int mTop; 2251 /** 2252 * The distance in pixels from the top edge of this view's parent 2253 * to the bottom edge of this view. 2254 * {@hide} 2255 */ 2256 @ViewDebug.ExportedProperty(category = "layout") 2257 protected int mBottom; 2258 2259 /** 2260 * The offset, in pixels, by which the content of this view is scrolled 2261 * horizontally. 2262 * {@hide} 2263 */ 2264 @ViewDebug.ExportedProperty(category = "scrolling") 2265 protected int mScrollX; 2266 /** 2267 * The offset, in pixels, by which the content of this view is scrolled 2268 * vertically. 2269 * {@hide} 2270 */ 2271 @ViewDebug.ExportedProperty(category = "scrolling") 2272 protected int mScrollY; 2273 2274 /** 2275 * The left padding in pixels, that is the distance in pixels between the 2276 * left edge of this view and the left edge of its content. 2277 * {@hide} 2278 */ 2279 @ViewDebug.ExportedProperty(category = "padding") 2280 protected int mPaddingLeft; 2281 /** 2282 * The right padding in pixels, that is the distance in pixels between the 2283 * right edge of this view and the right edge of its content. 2284 * {@hide} 2285 */ 2286 @ViewDebug.ExportedProperty(category = "padding") 2287 protected int mPaddingRight; 2288 /** 2289 * The top padding in pixels, that is the distance in pixels between the 2290 * top edge of this view and the top edge of its content. 2291 * {@hide} 2292 */ 2293 @ViewDebug.ExportedProperty(category = "padding") 2294 protected int mPaddingTop; 2295 /** 2296 * The bottom padding in pixels, that is the distance in pixels between the 2297 * bottom edge of this view and the bottom edge of its content. 2298 * {@hide} 2299 */ 2300 @ViewDebug.ExportedProperty(category = "padding") 2301 protected int mPaddingBottom; 2302 2303 /** 2304 * Briefly describes the view and is primarily used for accessibility support. 2305 */ 2306 private CharSequence mContentDescription; 2307 2308 /** 2309 * Cache the paddingRight set by the user to append to the scrollbar's size. 2310 * 2311 * @hide 2312 */ 2313 @ViewDebug.ExportedProperty(category = "padding") 2314 protected int mUserPaddingRight; 2315 2316 /** 2317 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2318 * 2319 * @hide 2320 */ 2321 @ViewDebug.ExportedProperty(category = "padding") 2322 protected int mUserPaddingBottom; 2323 2324 /** 2325 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2326 * 2327 * @hide 2328 */ 2329 @ViewDebug.ExportedProperty(category = "padding") 2330 protected int mUserPaddingLeft; 2331 2332 /** 2333 * Cache if the user padding is relative. 2334 * 2335 */ 2336 @ViewDebug.ExportedProperty(category = "padding") 2337 boolean mUserPaddingRelative; 2338 2339 /** 2340 * Cache the paddingStart set by the user to append to the scrollbar's size. 2341 * 2342 */ 2343 @ViewDebug.ExportedProperty(category = "padding") 2344 int mUserPaddingStart; 2345 2346 /** 2347 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2348 * 2349 */ 2350 @ViewDebug.ExportedProperty(category = "padding") 2351 int mUserPaddingEnd; 2352 2353 /** 2354 * @hide 2355 */ 2356 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2357 /** 2358 * @hide 2359 */ 2360 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2361 2362 private Drawable mBGDrawable; 2363 2364 private int mBackgroundResource; 2365 private boolean mBackgroundSizeChanged; 2366 2367 static class ListenerInfo { 2368 /** 2369 * Listener used to dispatch focus change events. 2370 * This field should be made private, so it is hidden from the SDK. 2371 * {@hide} 2372 */ 2373 protected OnFocusChangeListener mOnFocusChangeListener; 2374 2375 /** 2376 * Listeners for layout change events. 2377 */ 2378 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2379 2380 /** 2381 * Listeners for attach events. 2382 */ 2383 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2384 2385 /** 2386 * Listener used to dispatch click events. 2387 * This field should be made private, so it is hidden from the SDK. 2388 * {@hide} 2389 */ 2390 public OnClickListener mOnClickListener; 2391 2392 /** 2393 * Listener used to dispatch long click events. 2394 * This field should be made private, so it is hidden from the SDK. 2395 * {@hide} 2396 */ 2397 protected OnLongClickListener mOnLongClickListener; 2398 2399 /** 2400 * Listener used to build the context menu. 2401 * This field should be made private, so it is hidden from the SDK. 2402 * {@hide} 2403 */ 2404 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2405 2406 private OnKeyListener mOnKeyListener; 2407 2408 private OnTouchListener mOnTouchListener; 2409 2410 private OnHoverListener mOnHoverListener; 2411 2412 private OnGenericMotionListener mOnGenericMotionListener; 2413 2414 private OnDragListener mOnDragListener; 2415 2416 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2417 } 2418 2419 ListenerInfo mListenerInfo; 2420 2421 /** 2422 * The application environment this view lives in. 2423 * This field should be made private, so it is hidden from the SDK. 2424 * {@hide} 2425 */ 2426 protected Context mContext; 2427 2428 private final Resources mResources; 2429 2430 private ScrollabilityCache mScrollCache; 2431 2432 private int[] mDrawableState = null; 2433 2434 /** 2435 * Set to true when drawing cache is enabled and cannot be created. 2436 * 2437 * @hide 2438 */ 2439 public boolean mCachingFailed; 2440 2441 private Bitmap mDrawingCache; 2442 private Bitmap mUnscaledDrawingCache; 2443 private HardwareLayer mHardwareLayer; 2444 DisplayList mDisplayList; 2445 2446 /** 2447 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2448 * the user may specify which view to go to next. 2449 */ 2450 private int mNextFocusLeftId = View.NO_ID; 2451 2452 /** 2453 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2454 * the user may specify which view to go to next. 2455 */ 2456 private int mNextFocusRightId = View.NO_ID; 2457 2458 /** 2459 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2460 * the user may specify which view to go to next. 2461 */ 2462 private int mNextFocusUpId = View.NO_ID; 2463 2464 /** 2465 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2466 * the user may specify which view to go to next. 2467 */ 2468 private int mNextFocusDownId = View.NO_ID; 2469 2470 /** 2471 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 2472 * the user may specify which view to go to next. 2473 */ 2474 int mNextFocusForwardId = View.NO_ID; 2475 2476 private CheckForLongPress mPendingCheckForLongPress; 2477 private CheckForTap mPendingCheckForTap = null; 2478 private PerformClick mPerformClick; 2479 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 2480 2481 private UnsetPressedState mUnsetPressedState; 2482 2483 /** 2484 * Whether the long press's action has been invoked. The tap's action is invoked on the 2485 * up event while a long press is invoked as soon as the long press duration is reached, so 2486 * a long press could be performed before the tap is checked, in which case the tap's action 2487 * should not be invoked. 2488 */ 2489 private boolean mHasPerformedLongPress; 2490 2491 /** 2492 * The minimum height of the view. We'll try our best to have the height 2493 * of this view to at least this amount. 2494 */ 2495 @ViewDebug.ExportedProperty(category = "measurement") 2496 private int mMinHeight; 2497 2498 /** 2499 * The minimum width of the view. We'll try our best to have the width 2500 * of this view to at least this amount. 2501 */ 2502 @ViewDebug.ExportedProperty(category = "measurement") 2503 private int mMinWidth; 2504 2505 /** 2506 * The delegate to handle touch events that are physically in this view 2507 * but should be handled by another view. 2508 */ 2509 private TouchDelegate mTouchDelegate = null; 2510 2511 /** 2512 * Solid color to use as a background when creating the drawing cache. Enables 2513 * the cache to use 16 bit bitmaps instead of 32 bit. 2514 */ 2515 private int mDrawingCacheBackgroundColor = 0; 2516 2517 /** 2518 * Special tree observer used when mAttachInfo is null. 2519 */ 2520 private ViewTreeObserver mFloatingTreeObserver; 2521 2522 /** 2523 * Cache the touch slop from the context that created the view. 2524 */ 2525 private int mTouchSlop; 2526 2527 /** 2528 * Object that handles automatic animation of view properties. 2529 */ 2530 private ViewPropertyAnimator mAnimator = null; 2531 2532 /** 2533 * Flag indicating that a drag can cross window boundaries. When 2534 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 2535 * with this flag set, all visible applications will be able to participate 2536 * in the drag operation and receive the dragged content. 2537 * 2538 * @hide 2539 */ 2540 public static final int DRAG_FLAG_GLOBAL = 1; 2541 2542 /** 2543 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 2544 */ 2545 private float mVerticalScrollFactor; 2546 2547 /** 2548 * Position of the vertical scroll bar. 2549 */ 2550 private int mVerticalScrollbarPosition; 2551 2552 /** 2553 * Position the scroll bar at the default position as determined by the system. 2554 */ 2555 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 2556 2557 /** 2558 * Position the scroll bar along the left edge. 2559 */ 2560 public static final int SCROLLBAR_POSITION_LEFT = 1; 2561 2562 /** 2563 * Position the scroll bar along the right edge. 2564 */ 2565 public static final int SCROLLBAR_POSITION_RIGHT = 2; 2566 2567 /** 2568 * Indicates that the view does not have a layer. 2569 * 2570 * @see #getLayerType() 2571 * @see #setLayerType(int, android.graphics.Paint) 2572 * @see #LAYER_TYPE_SOFTWARE 2573 * @see #LAYER_TYPE_HARDWARE 2574 */ 2575 public static final int LAYER_TYPE_NONE = 0; 2576 2577 /** 2578 * <p>Indicates that the view has a software layer. A software layer is backed 2579 * by a bitmap and causes the view to be rendered using Android's software 2580 * rendering pipeline, even if hardware acceleration is enabled.</p> 2581 * 2582 * <p>Software layers have various usages:</p> 2583 * <p>When the application is not using hardware acceleration, a software layer 2584 * is useful to apply a specific color filter and/or blending mode and/or 2585 * translucency to a view and all its children.</p> 2586 * <p>When the application is using hardware acceleration, a software layer 2587 * is useful to render drawing primitives not supported by the hardware 2588 * accelerated pipeline. It can also be used to cache a complex view tree 2589 * into a texture and reduce the complexity of drawing operations. For instance, 2590 * when animating a complex view tree with a translation, a software layer can 2591 * be used to render the view tree only once.</p> 2592 * <p>Software layers should be avoided when the affected view tree updates 2593 * often. Every update will require to re-render the software layer, which can 2594 * potentially be slow (particularly when hardware acceleration is turned on 2595 * since the layer will have to be uploaded into a hardware texture after every 2596 * update.)</p> 2597 * 2598 * @see #getLayerType() 2599 * @see #setLayerType(int, android.graphics.Paint) 2600 * @see #LAYER_TYPE_NONE 2601 * @see #LAYER_TYPE_HARDWARE 2602 */ 2603 public static final int LAYER_TYPE_SOFTWARE = 1; 2604 2605 /** 2606 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 2607 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 2608 * OpenGL hardware) and causes the view to be rendered using Android's hardware 2609 * rendering pipeline, but only if hardware acceleration is turned on for the 2610 * view hierarchy. When hardware acceleration is turned off, hardware layers 2611 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 2612 * 2613 * <p>A hardware layer is useful to apply a specific color filter and/or 2614 * blending mode and/or translucency to a view and all its children.</p> 2615 * <p>A hardware layer can be used to cache a complex view tree into a 2616 * texture and reduce the complexity of drawing operations. For instance, 2617 * when animating a complex view tree with a translation, a hardware layer can 2618 * be used to render the view tree only once.</p> 2619 * <p>A hardware layer can also be used to increase the rendering quality when 2620 * rotation transformations are applied on a view. It can also be used to 2621 * prevent potential clipping issues when applying 3D transforms on a view.</p> 2622 * 2623 * @see #getLayerType() 2624 * @see #setLayerType(int, android.graphics.Paint) 2625 * @see #LAYER_TYPE_NONE 2626 * @see #LAYER_TYPE_SOFTWARE 2627 */ 2628 public static final int LAYER_TYPE_HARDWARE = 2; 2629 2630 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 2631 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 2632 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 2633 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 2634 }) 2635 int mLayerType = LAYER_TYPE_NONE; 2636 Paint mLayerPaint; 2637 Rect mLocalDirtyRect; 2638 2639 /** 2640 * Set to true when the view is sending hover accessibility events because it 2641 * is the innermost hovered view. 2642 */ 2643 private boolean mSendingHoverAccessibilityEvents; 2644 2645 /** 2646 * Delegate for injecting accessiblity functionality. 2647 */ 2648 AccessibilityDelegate mAccessibilityDelegate; 2649 2650 /** 2651 * Text direction is inherited thru {@link ViewGroup} 2652 */ 2653 public static final int TEXT_DIRECTION_INHERIT = 0; 2654 2655 /** 2656 * Text direction is using "first strong algorithm". The first strong directional character 2657 * determines the paragraph direction. If there is no strong directional character, the 2658 * paragraph direction is the view's resolved layout direction. 2659 * 2660 */ 2661 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 2662 2663 /** 2664 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 2665 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 2666 * If there are neither, the paragraph direction is the view's resolved layout direction. 2667 * 2668 */ 2669 public static final int TEXT_DIRECTION_ANY_RTL = 2; 2670 2671 /** 2672 * Text direction is forced to LTR. 2673 * 2674 */ 2675 public static final int TEXT_DIRECTION_LTR = 3; 2676 2677 /** 2678 * Text direction is forced to RTL. 2679 * 2680 */ 2681 public static final int TEXT_DIRECTION_RTL = 4; 2682 2683 /** 2684 * Text direction is coming from the system Locale. 2685 * 2686 */ 2687 public static final int TEXT_DIRECTION_LOCALE = 5; 2688 2689 /** 2690 * Default text direction is inherited 2691 * 2692 */ 2693 protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT; 2694 2695 /** 2696 * The text direction that has been defined by {@link #setTextDirection(int)}. 2697 * 2698 */ 2699 @ViewDebug.ExportedProperty(category = "text", mapping = { 2700 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 2701 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 2702 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 2703 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 2704 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 2705 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 2706 }) 2707 private int mTextDirection = DEFAULT_TEXT_DIRECTION; 2708 2709 /** 2710 * The resolved text direction. This needs resolution if the value is 2711 * TEXT_DIRECTION_INHERIT. The resolution matches mTextDirection if it is 2712 * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent 2713 * chain of the view. 2714 * 2715 */ 2716 @ViewDebug.ExportedProperty(category = "text", mapping = { 2717 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 2718 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 2719 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 2720 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 2721 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 2722 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 2723 }) 2724 private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT; 2725 2726 /** 2727 * Consistency verifier for debugging purposes. 2728 * @hide 2729 */ 2730 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 2731 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 2732 new InputEventConsistencyVerifier(this, 0) : null; 2733 2734 /** 2735 * Simple constructor to use when creating a view from code. 2736 * 2737 * @param context The Context the view is running in, through which it can 2738 * access the current theme, resources, etc. 2739 */ 2740 public View(Context context) { 2741 mContext = context; 2742 mResources = context != null ? context.getResources() : null; 2743 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 2744 mPrivateFlags2 |= (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT); 2745 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 2746 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 2747 mUserPaddingStart = -1; 2748 mUserPaddingEnd = -1; 2749 mUserPaddingRelative = false; 2750 } 2751 2752 /** 2753 * Constructor that is called when inflating a view from XML. This is called 2754 * when a view is being constructed from an XML file, supplying attributes 2755 * that were specified in the XML file. This version uses a default style of 2756 * 0, so the only attribute values applied are those in the Context's Theme 2757 * and the given AttributeSet. 2758 * 2759 * <p> 2760 * The method onFinishInflate() will be called after all children have been 2761 * added. 2762 * 2763 * @param context The Context the view is running in, through which it can 2764 * access the current theme, resources, etc. 2765 * @param attrs The attributes of the XML tag that is inflating the view. 2766 * @see #View(Context, AttributeSet, int) 2767 */ 2768 public View(Context context, AttributeSet attrs) { 2769 this(context, attrs, 0); 2770 } 2771 2772 /** 2773 * Perform inflation from XML and apply a class-specific base style. This 2774 * constructor of View allows subclasses to use their own base style when 2775 * they are inflating. For example, a Button class's constructor would call 2776 * this version of the super class constructor and supply 2777 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 2778 * the theme's button style to modify all of the base view attributes (in 2779 * particular its background) as well as the Button class's attributes. 2780 * 2781 * @param context The Context the view is running in, through which it can 2782 * access the current theme, resources, etc. 2783 * @param attrs The attributes of the XML tag that is inflating the view. 2784 * @param defStyle The default style to apply to this view. If 0, no style 2785 * will be applied (beyond what is included in the theme). This may 2786 * either be an attribute resource, whose value will be retrieved 2787 * from the current theme, or an explicit style resource. 2788 * @see #View(Context, AttributeSet) 2789 */ 2790 public View(Context context, AttributeSet attrs, int defStyle) { 2791 this(context); 2792 2793 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 2794 defStyle, 0); 2795 2796 Drawable background = null; 2797 2798 int leftPadding = -1; 2799 int topPadding = -1; 2800 int rightPadding = -1; 2801 int bottomPadding = -1; 2802 int startPadding = -1; 2803 int endPadding = -1; 2804 2805 int padding = -1; 2806 2807 int viewFlagValues = 0; 2808 int viewFlagMasks = 0; 2809 2810 boolean setScrollContainer = false; 2811 2812 int x = 0; 2813 int y = 0; 2814 2815 float tx = 0; 2816 float ty = 0; 2817 float rotation = 0; 2818 float rotationX = 0; 2819 float rotationY = 0; 2820 float sx = 1f; 2821 float sy = 1f; 2822 boolean transformSet = false; 2823 2824 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 2825 2826 int overScrollMode = mOverScrollMode; 2827 final int N = a.getIndexCount(); 2828 for (int i = 0; i < N; i++) { 2829 int attr = a.getIndex(i); 2830 switch (attr) { 2831 case com.android.internal.R.styleable.View_background: 2832 background = a.getDrawable(attr); 2833 break; 2834 case com.android.internal.R.styleable.View_padding: 2835 padding = a.getDimensionPixelSize(attr, -1); 2836 break; 2837 case com.android.internal.R.styleable.View_paddingLeft: 2838 leftPadding = a.getDimensionPixelSize(attr, -1); 2839 break; 2840 case com.android.internal.R.styleable.View_paddingTop: 2841 topPadding = a.getDimensionPixelSize(attr, -1); 2842 break; 2843 case com.android.internal.R.styleable.View_paddingRight: 2844 rightPadding = a.getDimensionPixelSize(attr, -1); 2845 break; 2846 case com.android.internal.R.styleable.View_paddingBottom: 2847 bottomPadding = a.getDimensionPixelSize(attr, -1); 2848 break; 2849 case com.android.internal.R.styleable.View_paddingStart: 2850 startPadding = a.getDimensionPixelSize(attr, -1); 2851 break; 2852 case com.android.internal.R.styleable.View_paddingEnd: 2853 endPadding = a.getDimensionPixelSize(attr, -1); 2854 break; 2855 case com.android.internal.R.styleable.View_scrollX: 2856 x = a.getDimensionPixelOffset(attr, 0); 2857 break; 2858 case com.android.internal.R.styleable.View_scrollY: 2859 y = a.getDimensionPixelOffset(attr, 0); 2860 break; 2861 case com.android.internal.R.styleable.View_alpha: 2862 setAlpha(a.getFloat(attr, 1f)); 2863 break; 2864 case com.android.internal.R.styleable.View_transformPivotX: 2865 setPivotX(a.getDimensionPixelOffset(attr, 0)); 2866 break; 2867 case com.android.internal.R.styleable.View_transformPivotY: 2868 setPivotY(a.getDimensionPixelOffset(attr, 0)); 2869 break; 2870 case com.android.internal.R.styleable.View_translationX: 2871 tx = a.getDimensionPixelOffset(attr, 0); 2872 transformSet = true; 2873 break; 2874 case com.android.internal.R.styleable.View_translationY: 2875 ty = a.getDimensionPixelOffset(attr, 0); 2876 transformSet = true; 2877 break; 2878 case com.android.internal.R.styleable.View_rotation: 2879 rotation = a.getFloat(attr, 0); 2880 transformSet = true; 2881 break; 2882 case com.android.internal.R.styleable.View_rotationX: 2883 rotationX = a.getFloat(attr, 0); 2884 transformSet = true; 2885 break; 2886 case com.android.internal.R.styleable.View_rotationY: 2887 rotationY = a.getFloat(attr, 0); 2888 transformSet = true; 2889 break; 2890 case com.android.internal.R.styleable.View_scaleX: 2891 sx = a.getFloat(attr, 1f); 2892 transformSet = true; 2893 break; 2894 case com.android.internal.R.styleable.View_scaleY: 2895 sy = a.getFloat(attr, 1f); 2896 transformSet = true; 2897 break; 2898 case com.android.internal.R.styleable.View_id: 2899 mID = a.getResourceId(attr, NO_ID); 2900 break; 2901 case com.android.internal.R.styleable.View_tag: 2902 mTag = a.getText(attr); 2903 break; 2904 case com.android.internal.R.styleable.View_fitsSystemWindows: 2905 if (a.getBoolean(attr, false)) { 2906 viewFlagValues |= FITS_SYSTEM_WINDOWS; 2907 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 2908 } 2909 break; 2910 case com.android.internal.R.styleable.View_focusable: 2911 if (a.getBoolean(attr, false)) { 2912 viewFlagValues |= FOCUSABLE; 2913 viewFlagMasks |= FOCUSABLE_MASK; 2914 } 2915 break; 2916 case com.android.internal.R.styleable.View_focusableInTouchMode: 2917 if (a.getBoolean(attr, false)) { 2918 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 2919 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 2920 } 2921 break; 2922 case com.android.internal.R.styleable.View_clickable: 2923 if (a.getBoolean(attr, false)) { 2924 viewFlagValues |= CLICKABLE; 2925 viewFlagMasks |= CLICKABLE; 2926 } 2927 break; 2928 case com.android.internal.R.styleable.View_longClickable: 2929 if (a.getBoolean(attr, false)) { 2930 viewFlagValues |= LONG_CLICKABLE; 2931 viewFlagMasks |= LONG_CLICKABLE; 2932 } 2933 break; 2934 case com.android.internal.R.styleable.View_saveEnabled: 2935 if (!a.getBoolean(attr, true)) { 2936 viewFlagValues |= SAVE_DISABLED; 2937 viewFlagMasks |= SAVE_DISABLED_MASK; 2938 } 2939 break; 2940 case com.android.internal.R.styleable.View_duplicateParentState: 2941 if (a.getBoolean(attr, false)) { 2942 viewFlagValues |= DUPLICATE_PARENT_STATE; 2943 viewFlagMasks |= DUPLICATE_PARENT_STATE; 2944 } 2945 break; 2946 case com.android.internal.R.styleable.View_visibility: 2947 final int visibility = a.getInt(attr, 0); 2948 if (visibility != 0) { 2949 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 2950 viewFlagMasks |= VISIBILITY_MASK; 2951 } 2952 break; 2953 case com.android.internal.R.styleable.View_layoutDirection: 2954 // Clear any layout direction flags (included resolved bits) already set 2955 mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK); 2956 // Set the layout direction flags depending on the value of the attribute 2957 final int layoutDirection = a.getInt(attr, -1); 2958 final int value = (layoutDirection != -1) ? 2959 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 2960 mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT); 2961 break; 2962 case com.android.internal.R.styleable.View_drawingCacheQuality: 2963 final int cacheQuality = a.getInt(attr, 0); 2964 if (cacheQuality != 0) { 2965 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 2966 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 2967 } 2968 break; 2969 case com.android.internal.R.styleable.View_contentDescription: 2970 mContentDescription = a.getString(attr); 2971 break; 2972 case com.android.internal.R.styleable.View_soundEffectsEnabled: 2973 if (!a.getBoolean(attr, true)) { 2974 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 2975 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 2976 } 2977 break; 2978 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 2979 if (!a.getBoolean(attr, true)) { 2980 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 2981 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 2982 } 2983 break; 2984 case R.styleable.View_scrollbars: 2985 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 2986 if (scrollbars != SCROLLBARS_NONE) { 2987 viewFlagValues |= scrollbars; 2988 viewFlagMasks |= SCROLLBARS_MASK; 2989 initializeScrollbars(a); 2990 } 2991 break; 2992 //noinspection deprecation 2993 case R.styleable.View_fadingEdge: 2994 if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) { 2995 // Ignore the attribute starting with ICS 2996 break; 2997 } 2998 // With builds < ICS, fall through and apply fading edges 2999 case R.styleable.View_requiresFadingEdge: 3000 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3001 if (fadingEdge != FADING_EDGE_NONE) { 3002 viewFlagValues |= fadingEdge; 3003 viewFlagMasks |= FADING_EDGE_MASK; 3004 initializeFadingEdge(a); 3005 } 3006 break; 3007 case R.styleable.View_scrollbarStyle: 3008 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3009 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3010 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3011 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3012 } 3013 break; 3014 case R.styleable.View_isScrollContainer: 3015 setScrollContainer = true; 3016 if (a.getBoolean(attr, false)) { 3017 setScrollContainer(true); 3018 } 3019 break; 3020 case com.android.internal.R.styleable.View_keepScreenOn: 3021 if (a.getBoolean(attr, false)) { 3022 viewFlagValues |= KEEP_SCREEN_ON; 3023 viewFlagMasks |= KEEP_SCREEN_ON; 3024 } 3025 break; 3026 case R.styleable.View_filterTouchesWhenObscured: 3027 if (a.getBoolean(attr, false)) { 3028 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3029 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3030 } 3031 break; 3032 case R.styleable.View_nextFocusLeft: 3033 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3034 break; 3035 case R.styleable.View_nextFocusRight: 3036 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3037 break; 3038 case R.styleable.View_nextFocusUp: 3039 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3040 break; 3041 case R.styleable.View_nextFocusDown: 3042 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3043 break; 3044 case R.styleable.View_nextFocusForward: 3045 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3046 break; 3047 case R.styleable.View_minWidth: 3048 mMinWidth = a.getDimensionPixelSize(attr, 0); 3049 break; 3050 case R.styleable.View_minHeight: 3051 mMinHeight = a.getDimensionPixelSize(attr, 0); 3052 break; 3053 case R.styleable.View_onClick: 3054 if (context.isRestricted()) { 3055 throw new IllegalStateException("The android:onClick attribute cannot " 3056 + "be used within a restricted context"); 3057 } 3058 3059 final String handlerName = a.getString(attr); 3060 if (handlerName != null) { 3061 setOnClickListener(new OnClickListener() { 3062 private Method mHandler; 3063 3064 public void onClick(View v) { 3065 if (mHandler == null) { 3066 try { 3067 mHandler = getContext().getClass().getMethod(handlerName, 3068 View.class); 3069 } catch (NoSuchMethodException e) { 3070 int id = getId(); 3071 String idText = id == NO_ID ? "" : " with id '" 3072 + getContext().getResources().getResourceEntryName( 3073 id) + "'"; 3074 throw new IllegalStateException("Could not find a method " + 3075 handlerName + "(View) in the activity " 3076 + getContext().getClass() + " for onClick handler" 3077 + " on view " + View.this.getClass() + idText, e); 3078 } 3079 } 3080 3081 try { 3082 mHandler.invoke(getContext(), View.this); 3083 } catch (IllegalAccessException e) { 3084 throw new IllegalStateException("Could not execute non " 3085 + "public method of the activity", e); 3086 } catch (InvocationTargetException e) { 3087 throw new IllegalStateException("Could not execute " 3088 + "method of the activity", e); 3089 } 3090 } 3091 }); 3092 } 3093 break; 3094 case R.styleable.View_overScrollMode: 3095 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3096 break; 3097 case R.styleable.View_verticalScrollbarPosition: 3098 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3099 break; 3100 case R.styleable.View_layerType: 3101 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3102 break; 3103 case R.styleable.View_textDirection: 3104 mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION); 3105 break; 3106 } 3107 } 3108 3109 a.recycle(); 3110 3111 setOverScrollMode(overScrollMode); 3112 3113 if (background != null) { 3114 setBackgroundDrawable(background); 3115 } 3116 3117 // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved 3118 // layout direction). Those cached values will be used later during padding resolution. 3119 mUserPaddingStart = startPadding; 3120 mUserPaddingEnd = endPadding; 3121 3122 updateUserPaddingRelative(); 3123 3124 if (padding >= 0) { 3125 leftPadding = padding; 3126 topPadding = padding; 3127 rightPadding = padding; 3128 bottomPadding = padding; 3129 } 3130 3131 // If the user specified the padding (either with android:padding or 3132 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 3133 // use the default padding or the padding from the background drawable 3134 // (stored at this point in mPadding*) 3135 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft, 3136 topPadding >= 0 ? topPadding : mPaddingTop, 3137 rightPadding >= 0 ? rightPadding : mPaddingRight, 3138 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3139 3140 if (viewFlagMasks != 0) { 3141 setFlags(viewFlagValues, viewFlagMasks); 3142 } 3143 3144 // Needs to be called after mViewFlags is set 3145 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3146 recomputePadding(); 3147 } 3148 3149 if (x != 0 || y != 0) { 3150 scrollTo(x, y); 3151 } 3152 3153 if (transformSet) { 3154 setTranslationX(tx); 3155 setTranslationY(ty); 3156 setRotation(rotation); 3157 setRotationX(rotationX); 3158 setRotationY(rotationY); 3159 setScaleX(sx); 3160 setScaleY(sy); 3161 } 3162 3163 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3164 setScrollContainer(true); 3165 } 3166 3167 computeOpaqueFlags(); 3168 } 3169 3170 private void updateUserPaddingRelative() { 3171 mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0); 3172 } 3173 3174 /** 3175 * Non-public constructor for use in testing 3176 */ 3177 View() { 3178 mResources = null; 3179 } 3180 3181 /** 3182 * <p> 3183 * Initializes the fading edges from a given set of styled attributes. This 3184 * method should be called by subclasses that need fading edges and when an 3185 * instance of these subclasses is created programmatically rather than 3186 * being inflated from XML. This method is automatically called when the XML 3187 * is inflated. 3188 * </p> 3189 * 3190 * @param a the styled attributes set to initialize the fading edges from 3191 */ 3192 protected void initializeFadingEdge(TypedArray a) { 3193 initScrollCache(); 3194 3195 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3196 R.styleable.View_fadingEdgeLength, 3197 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3198 } 3199 3200 /** 3201 * Returns the size of the vertical faded edges used to indicate that more 3202 * content in this view is visible. 3203 * 3204 * @return The size in pixels of the vertical faded edge or 0 if vertical 3205 * faded edges are not enabled for this view. 3206 * @attr ref android.R.styleable#View_fadingEdgeLength 3207 */ 3208 public int getVerticalFadingEdgeLength() { 3209 if (isVerticalFadingEdgeEnabled()) { 3210 ScrollabilityCache cache = mScrollCache; 3211 if (cache != null) { 3212 return cache.fadingEdgeLength; 3213 } 3214 } 3215 return 0; 3216 } 3217 3218 /** 3219 * Set the size of the faded edge used to indicate that more content in this 3220 * view is available. Will not change whether the fading edge is enabled; use 3221 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3222 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3223 * for the vertical or horizontal fading edges. 3224 * 3225 * @param length The size in pixels of the faded edge used to indicate that more 3226 * content in this view is visible. 3227 */ 3228 public void setFadingEdgeLength(int length) { 3229 initScrollCache(); 3230 mScrollCache.fadingEdgeLength = length; 3231 } 3232 3233 /** 3234 * Returns the size of the horizontal faded edges used to indicate that more 3235 * content in this view is visible. 3236 * 3237 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3238 * faded edges are not enabled for this view. 3239 * @attr ref android.R.styleable#View_fadingEdgeLength 3240 */ 3241 public int getHorizontalFadingEdgeLength() { 3242 if (isHorizontalFadingEdgeEnabled()) { 3243 ScrollabilityCache cache = mScrollCache; 3244 if (cache != null) { 3245 return cache.fadingEdgeLength; 3246 } 3247 } 3248 return 0; 3249 } 3250 3251 /** 3252 * Returns the width of the vertical scrollbar. 3253 * 3254 * @return The width in pixels of the vertical scrollbar or 0 if there 3255 * is no vertical scrollbar. 3256 */ 3257 public int getVerticalScrollbarWidth() { 3258 ScrollabilityCache cache = mScrollCache; 3259 if (cache != null) { 3260 ScrollBarDrawable scrollBar = cache.scrollBar; 3261 if (scrollBar != null) { 3262 int size = scrollBar.getSize(true); 3263 if (size <= 0) { 3264 size = cache.scrollBarSize; 3265 } 3266 return size; 3267 } 3268 return 0; 3269 } 3270 return 0; 3271 } 3272 3273 /** 3274 * Returns the height of the horizontal scrollbar. 3275 * 3276 * @return The height in pixels of the horizontal scrollbar or 0 if 3277 * there is no horizontal scrollbar. 3278 */ 3279 protected int getHorizontalScrollbarHeight() { 3280 ScrollabilityCache cache = mScrollCache; 3281 if (cache != null) { 3282 ScrollBarDrawable scrollBar = cache.scrollBar; 3283 if (scrollBar != null) { 3284 int size = scrollBar.getSize(false); 3285 if (size <= 0) { 3286 size = cache.scrollBarSize; 3287 } 3288 return size; 3289 } 3290 return 0; 3291 } 3292 return 0; 3293 } 3294 3295 /** 3296 * <p> 3297 * Initializes the scrollbars from a given set of styled attributes. This 3298 * method should be called by subclasses that need scrollbars and when an 3299 * instance of these subclasses is created programmatically rather than 3300 * being inflated from XML. This method is automatically called when the XML 3301 * is inflated. 3302 * </p> 3303 * 3304 * @param a the styled attributes set to initialize the scrollbars from 3305 */ 3306 protected void initializeScrollbars(TypedArray a) { 3307 initScrollCache(); 3308 3309 final ScrollabilityCache scrollabilityCache = mScrollCache; 3310 3311 if (scrollabilityCache.scrollBar == null) { 3312 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 3313 } 3314 3315 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 3316 3317 if (!fadeScrollbars) { 3318 scrollabilityCache.state = ScrollabilityCache.ON; 3319 } 3320 scrollabilityCache.fadeScrollBars = fadeScrollbars; 3321 3322 3323 scrollabilityCache.scrollBarFadeDuration = a.getInt( 3324 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 3325 .getScrollBarFadeDuration()); 3326 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 3327 R.styleable.View_scrollbarDefaultDelayBeforeFade, 3328 ViewConfiguration.getScrollDefaultDelay()); 3329 3330 3331 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 3332 com.android.internal.R.styleable.View_scrollbarSize, 3333 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3334 3335 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3336 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3337 3338 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3339 if (thumb != null) { 3340 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3341 } 3342 3343 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3344 false); 3345 if (alwaysDraw) { 3346 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3347 } 3348 3349 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3350 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3351 3352 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3353 if (thumb != null) { 3354 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3355 } 3356 3357 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3358 false); 3359 if (alwaysDraw) { 3360 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3361 } 3362 3363 // Re-apply user/background padding so that scrollbar(s) get added 3364 resolvePadding(); 3365 } 3366 3367 /** 3368 * <p> 3369 * Initalizes the scrollability cache if necessary. 3370 * </p> 3371 */ 3372 private void initScrollCache() { 3373 if (mScrollCache == null) { 3374 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 3375 } 3376 } 3377 3378 /** 3379 * Set the position of the vertical scroll bar. Should be one of 3380 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 3381 * {@link #SCROLLBAR_POSITION_RIGHT}. 3382 * 3383 * @param position Where the vertical scroll bar should be positioned. 3384 */ 3385 public void setVerticalScrollbarPosition(int position) { 3386 if (mVerticalScrollbarPosition != position) { 3387 mVerticalScrollbarPosition = position; 3388 computeOpaqueFlags(); 3389 resolvePadding(); 3390 } 3391 } 3392 3393 /** 3394 * @return The position where the vertical scroll bar will show, if applicable. 3395 * @see #setVerticalScrollbarPosition(int) 3396 */ 3397 public int getVerticalScrollbarPosition() { 3398 return mVerticalScrollbarPosition; 3399 } 3400 3401 ListenerInfo getListenerInfo() { 3402 if (mListenerInfo != null) { 3403 return mListenerInfo; 3404 } 3405 mListenerInfo = new ListenerInfo(); 3406 return mListenerInfo; 3407 } 3408 3409 /** 3410 * Register a callback to be invoked when focus of this view changed. 3411 * 3412 * @param l The callback that will run. 3413 */ 3414 public void setOnFocusChangeListener(OnFocusChangeListener l) { 3415 getListenerInfo().mOnFocusChangeListener = l; 3416 } 3417 3418 /** 3419 * Add a listener that will be called when the bounds of the view change due to 3420 * layout processing. 3421 * 3422 * @param listener The listener that will be called when layout bounds change. 3423 */ 3424 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 3425 ListenerInfo li = getListenerInfo(); 3426 if (li.mOnLayoutChangeListeners == null) { 3427 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 3428 } 3429 if (!li.mOnLayoutChangeListeners.contains(listener)) { 3430 li.mOnLayoutChangeListeners.add(listener); 3431 } 3432 } 3433 3434 /** 3435 * Remove a listener for layout changes. 3436 * 3437 * @param listener The listener for layout bounds change. 3438 */ 3439 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 3440 ListenerInfo li = mListenerInfo; 3441 if (li == null || li.mOnLayoutChangeListeners == null) { 3442 return; 3443 } 3444 li.mOnLayoutChangeListeners.remove(listener); 3445 } 3446 3447 /** 3448 * Add a listener for attach state changes. 3449 * 3450 * This listener will be called whenever this view is attached or detached 3451 * from a window. Remove the listener using 3452 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 3453 * 3454 * @param listener Listener to attach 3455 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 3456 */ 3457 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3458 ListenerInfo li = getListenerInfo(); 3459 if (li.mOnAttachStateChangeListeners == null) { 3460 li.mOnAttachStateChangeListeners 3461 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 3462 } 3463 li.mOnAttachStateChangeListeners.add(listener); 3464 } 3465 3466 /** 3467 * Remove a listener for attach state changes. The listener will receive no further 3468 * notification of window attach/detach events. 3469 * 3470 * @param listener Listener to remove 3471 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 3472 */ 3473 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3474 ListenerInfo li = mListenerInfo; 3475 if (li == null || li.mOnAttachStateChangeListeners == null) { 3476 return; 3477 } 3478 li.mOnAttachStateChangeListeners.remove(listener); 3479 } 3480 3481 /** 3482 * Returns the focus-change callback registered for this view. 3483 * 3484 * @return The callback, or null if one is not registered. 3485 */ 3486 public OnFocusChangeListener getOnFocusChangeListener() { 3487 ListenerInfo li = mListenerInfo; 3488 return li != null ? li.mOnFocusChangeListener : null; 3489 } 3490 3491 /** 3492 * Register a callback to be invoked when this view is clicked. If this view is not 3493 * clickable, it becomes clickable. 3494 * 3495 * @param l The callback that will run 3496 * 3497 * @see #setClickable(boolean) 3498 */ 3499 public void setOnClickListener(OnClickListener l) { 3500 if (!isClickable()) { 3501 setClickable(true); 3502 } 3503 getListenerInfo().mOnClickListener = l; 3504 } 3505 3506 /** 3507 * Return whether this view has an attached OnClickListener. Returns 3508 * true if there is a listener, false if there is none. 3509 */ 3510 public boolean hasOnClickListeners() { 3511 ListenerInfo li = mListenerInfo; 3512 return (li != null && li.mOnClickListener != null); 3513 } 3514 3515 /** 3516 * Register a callback to be invoked when this view is clicked and held. If this view is not 3517 * long clickable, it becomes long clickable. 3518 * 3519 * @param l The callback that will run 3520 * 3521 * @see #setLongClickable(boolean) 3522 */ 3523 public void setOnLongClickListener(OnLongClickListener l) { 3524 if (!isLongClickable()) { 3525 setLongClickable(true); 3526 } 3527 getListenerInfo().mOnLongClickListener = l; 3528 } 3529 3530 /** 3531 * Register a callback to be invoked when the context menu for this view is 3532 * being built. If this view is not long clickable, it becomes long clickable. 3533 * 3534 * @param l The callback that will run 3535 * 3536 */ 3537 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 3538 if (!isLongClickable()) { 3539 setLongClickable(true); 3540 } 3541 getListenerInfo().mOnCreateContextMenuListener = l; 3542 } 3543 3544 /** 3545 * Call this view's OnClickListener, if it is defined. Performs all normal 3546 * actions associated with clicking: reporting accessibility event, playing 3547 * a sound, etc. 3548 * 3549 * @return True there was an assigned OnClickListener that was called, false 3550 * otherwise is returned. 3551 */ 3552 public boolean performClick() { 3553 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 3554 3555 ListenerInfo li = mListenerInfo; 3556 if (li != null && li.mOnClickListener != null) { 3557 playSoundEffect(SoundEffectConstants.CLICK); 3558 li.mOnClickListener.onClick(this); 3559 return true; 3560 } 3561 3562 return false; 3563 } 3564 3565 /** 3566 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 3567 * this only calls the listener, and does not do any associated clicking 3568 * actions like reporting an accessibility event. 3569 * 3570 * @return True there was an assigned OnClickListener that was called, false 3571 * otherwise is returned. 3572 */ 3573 public boolean callOnClick() { 3574 ListenerInfo li = mListenerInfo; 3575 if (li != null && li.mOnClickListener != null) { 3576 li.mOnClickListener.onClick(this); 3577 return true; 3578 } 3579 return false; 3580 } 3581 3582 /** 3583 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 3584 * OnLongClickListener did not consume the event. 3585 * 3586 * @return True if one of the above receivers consumed the event, false otherwise. 3587 */ 3588 public boolean performLongClick() { 3589 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 3590 3591 boolean handled = false; 3592 ListenerInfo li = mListenerInfo; 3593 if (li != null && li.mOnLongClickListener != null) { 3594 handled = li.mOnLongClickListener.onLongClick(View.this); 3595 } 3596 if (!handled) { 3597 handled = showContextMenu(); 3598 } 3599 if (handled) { 3600 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 3601 } 3602 return handled; 3603 } 3604 3605 /** 3606 * Performs button-related actions during a touch down event. 3607 * 3608 * @param event The event. 3609 * @return True if the down was consumed. 3610 * 3611 * @hide 3612 */ 3613 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 3614 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 3615 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 3616 return true; 3617 } 3618 } 3619 return false; 3620 } 3621 3622 /** 3623 * Bring up the context menu for this view. 3624 * 3625 * @return Whether a context menu was displayed. 3626 */ 3627 public boolean showContextMenu() { 3628 return getParent().showContextMenuForChild(this); 3629 } 3630 3631 /** 3632 * Bring up the context menu for this view, referring to the item under the specified point. 3633 * 3634 * @param x The referenced x coordinate. 3635 * @param y The referenced y coordinate. 3636 * @param metaState The keyboard modifiers that were pressed. 3637 * @return Whether a context menu was displayed. 3638 * 3639 * @hide 3640 */ 3641 public boolean showContextMenu(float x, float y, int metaState) { 3642 return showContextMenu(); 3643 } 3644 3645 /** 3646 * Start an action mode. 3647 * 3648 * @param callback Callback that will control the lifecycle of the action mode 3649 * @return The new action mode if it is started, null otherwise 3650 * 3651 * @see ActionMode 3652 */ 3653 public ActionMode startActionMode(ActionMode.Callback callback) { 3654 ViewParent parent = getParent(); 3655 if (parent == null) return null; 3656 return parent.startActionModeForChild(this, callback); 3657 } 3658 3659 /** 3660 * Register a callback to be invoked when a key is pressed in this view. 3661 * @param l the key listener to attach to this view 3662 */ 3663 public void setOnKeyListener(OnKeyListener l) { 3664 getListenerInfo().mOnKeyListener = l; 3665 } 3666 3667 /** 3668 * Register a callback to be invoked when a touch event is sent to this view. 3669 * @param l the touch listener to attach to this view 3670 */ 3671 public void setOnTouchListener(OnTouchListener l) { 3672 getListenerInfo().mOnTouchListener = l; 3673 } 3674 3675 /** 3676 * Register a callback to be invoked when a generic motion event is sent to this view. 3677 * @param l the generic motion listener to attach to this view 3678 */ 3679 public void setOnGenericMotionListener(OnGenericMotionListener l) { 3680 getListenerInfo().mOnGenericMotionListener = l; 3681 } 3682 3683 /** 3684 * Register a callback to be invoked when a hover event is sent to this view. 3685 * @param l the hover listener to attach to this view 3686 */ 3687 public void setOnHoverListener(OnHoverListener l) { 3688 getListenerInfo().mOnHoverListener = l; 3689 } 3690 3691 /** 3692 * Register a drag event listener callback object for this View. The parameter is 3693 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 3694 * View, the system calls the 3695 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 3696 * @param l An implementation of {@link android.view.View.OnDragListener}. 3697 */ 3698 public void setOnDragListener(OnDragListener l) { 3699 getListenerInfo().mOnDragListener = l; 3700 } 3701 3702 /** 3703 * Give this view focus. This will cause 3704 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3705 * 3706 * Note: this does not check whether this {@link View} should get focus, it just 3707 * gives it focus no matter what. It should only be called internally by framework 3708 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 3709 * 3710 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 3711 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 3712 * focus moved when requestFocus() is called. It may not always 3713 * apply, in which case use the default View.FOCUS_DOWN. 3714 * @param previouslyFocusedRect The rectangle of the view that had focus 3715 * prior in this View's coordinate system. 3716 */ 3717 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 3718 if (DBG) { 3719 System.out.println(this + " requestFocus()"); 3720 } 3721 3722 if ((mPrivateFlags & FOCUSED) == 0) { 3723 mPrivateFlags |= FOCUSED; 3724 3725 if (mParent != null) { 3726 mParent.requestChildFocus(this, this); 3727 } 3728 3729 onFocusChanged(true, direction, previouslyFocusedRect); 3730 refreshDrawableState(); 3731 } 3732 } 3733 3734 /** 3735 * Request that a rectangle of this view be visible on the screen, 3736 * scrolling if necessary just enough. 3737 * 3738 * <p>A View should call this if it maintains some notion of which part 3739 * of its content is interesting. For example, a text editing view 3740 * should call this when its cursor moves. 3741 * 3742 * @param rectangle The rectangle. 3743 * @return Whether any parent scrolled. 3744 */ 3745 public boolean requestRectangleOnScreen(Rect rectangle) { 3746 return requestRectangleOnScreen(rectangle, false); 3747 } 3748 3749 /** 3750 * Request that a rectangle of this view be visible on the screen, 3751 * scrolling if necessary just enough. 3752 * 3753 * <p>A View should call this if it maintains some notion of which part 3754 * of its content is interesting. For example, a text editing view 3755 * should call this when its cursor moves. 3756 * 3757 * <p>When <code>immediate</code> is set to true, scrolling will not be 3758 * animated. 3759 * 3760 * @param rectangle The rectangle. 3761 * @param immediate True to forbid animated scrolling, false otherwise 3762 * @return Whether any parent scrolled. 3763 */ 3764 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 3765 View child = this; 3766 ViewParent parent = mParent; 3767 boolean scrolled = false; 3768 while (parent != null) { 3769 scrolled |= parent.requestChildRectangleOnScreen(child, 3770 rectangle, immediate); 3771 3772 // offset rect so next call has the rectangle in the 3773 // coordinate system of its direct child. 3774 rectangle.offset(child.getLeft(), child.getTop()); 3775 rectangle.offset(-child.getScrollX(), -child.getScrollY()); 3776 3777 if (!(parent instanceof View)) { 3778 break; 3779 } 3780 3781 child = (View) parent; 3782 parent = child.getParent(); 3783 } 3784 return scrolled; 3785 } 3786 3787 /** 3788 * Called when this view wants to give up focus. If focus is cleared 3789 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 3790 * <p> 3791 * <strong>Note:</strong> When a View clears focus the framework is trying 3792 * to give focus to the first focusable View from the top. Hence, if this 3793 * View is the first from the top that can take focus, then its focus will 3794 * not be cleared nor will the focus change callback be invoked. 3795 * </p> 3796 */ 3797 public void clearFocus() { 3798 if (DBG) { 3799 System.out.println(this + " clearFocus()"); 3800 } 3801 3802 if ((mPrivateFlags & FOCUSED) != 0) { 3803 mPrivateFlags &= ~FOCUSED; 3804 3805 if (mParent != null) { 3806 mParent.clearChildFocus(this); 3807 } 3808 3809 onFocusChanged(false, 0, null); 3810 refreshDrawableState(); 3811 } 3812 } 3813 3814 /** 3815 * Called to clear the focus of a view that is about to be removed. 3816 * Doesn't call clearChildFocus, which prevents this view from taking 3817 * focus again before it has been removed from the parent 3818 */ 3819 void clearFocusForRemoval() { 3820 if ((mPrivateFlags & FOCUSED) != 0) { 3821 mPrivateFlags &= ~FOCUSED; 3822 3823 onFocusChanged(false, 0, null); 3824 refreshDrawableState(); 3825 3826 // The view cleared focus and invoked the callbacks, so now is the 3827 // time to give focus to the the first focusable from the top to 3828 // ensure that the gain focus is announced after clear focus. 3829 getRootView().requestFocus(FOCUS_FORWARD); 3830 } 3831 } 3832 3833 /** 3834 * Called internally by the view system when a new view is getting focus. 3835 * This is what clears the old focus. 3836 */ 3837 void unFocus() { 3838 if (DBG) { 3839 System.out.println(this + " unFocus()"); 3840 } 3841 3842 if ((mPrivateFlags & FOCUSED) != 0) { 3843 mPrivateFlags &= ~FOCUSED; 3844 3845 onFocusChanged(false, 0, null); 3846 refreshDrawableState(); 3847 } 3848 } 3849 3850 /** 3851 * Returns true if this view has focus iteself, or is the ancestor of the 3852 * view that has focus. 3853 * 3854 * @return True if this view has or contains focus, false otherwise. 3855 */ 3856 @ViewDebug.ExportedProperty(category = "focus") 3857 public boolean hasFocus() { 3858 return (mPrivateFlags & FOCUSED) != 0; 3859 } 3860 3861 /** 3862 * Returns true if this view is focusable or if it contains a reachable View 3863 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 3864 * is a View whose parents do not block descendants focus. 3865 * 3866 * Only {@link #VISIBLE} views are considered focusable. 3867 * 3868 * @return True if the view is focusable or if the view contains a focusable 3869 * View, false otherwise. 3870 * 3871 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 3872 */ 3873 public boolean hasFocusable() { 3874 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 3875 } 3876 3877 /** 3878 * Called by the view system when the focus state of this view changes. 3879 * When the focus change event is caused by directional navigation, direction 3880 * and previouslyFocusedRect provide insight into where the focus is coming from. 3881 * When overriding, be sure to call up through to the super class so that 3882 * the standard focus handling will occur. 3883 * 3884 * @param gainFocus True if the View has focus; false otherwise. 3885 * @param direction The direction focus has moved when requestFocus() 3886 * is called to give this view focus. Values are 3887 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 3888 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 3889 * It may not always apply, in which case use the default. 3890 * @param previouslyFocusedRect The rectangle, in this view's coordinate 3891 * system, of the previously focused view. If applicable, this will be 3892 * passed in as finer grained information about where the focus is coming 3893 * from (in addition to direction). Will be <code>null</code> otherwise. 3894 */ 3895 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 3896 if (gainFocus) { 3897 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 3898 } 3899 3900 InputMethodManager imm = InputMethodManager.peekInstance(); 3901 if (!gainFocus) { 3902 if (isPressed()) { 3903 setPressed(false); 3904 } 3905 if (imm != null && mAttachInfo != null 3906 && mAttachInfo.mHasWindowFocus) { 3907 imm.focusOut(this); 3908 } 3909 onFocusLost(); 3910 } else if (imm != null && mAttachInfo != null 3911 && mAttachInfo.mHasWindowFocus) { 3912 imm.focusIn(this); 3913 } 3914 3915 invalidate(true); 3916 ListenerInfo li = mListenerInfo; 3917 if (li != null && li.mOnFocusChangeListener != null) { 3918 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 3919 } 3920 3921 if (mAttachInfo != null) { 3922 mAttachInfo.mKeyDispatchState.reset(this); 3923 } 3924 } 3925 3926 /** 3927 * Sends an accessibility event of the given type. If accessiiblity is 3928 * not enabled this method has no effect. The default implementation calls 3929 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 3930 * to populate information about the event source (this View), then calls 3931 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 3932 * populate the text content of the event source including its descendants, 3933 * and last calls 3934 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 3935 * on its parent to resuest sending of the event to interested parties. 3936 * <p> 3937 * If an {@link AccessibilityDelegate} has been specified via calling 3938 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3939 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 3940 * responsible for handling this call. 3941 * </p> 3942 * 3943 * @param eventType The type of the event to send, as defined by several types from 3944 * {@link android.view.accessibility.AccessibilityEvent}, such as 3945 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 3946 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 3947 * 3948 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 3949 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3950 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 3951 * @see AccessibilityDelegate 3952 */ 3953 public void sendAccessibilityEvent(int eventType) { 3954 if (mAccessibilityDelegate != null) { 3955 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 3956 } else { 3957 sendAccessibilityEventInternal(eventType); 3958 } 3959 } 3960 3961 /** 3962 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 3963 * {@link AccessibilityEvent} to make an announcement which is related to some 3964 * sort of a context change for which none of the events representing UI transitions 3965 * is a good fit. For example, announcing a new page in a book. If accessibility 3966 * is not enabled this method does nothing. 3967 * 3968 * @param text The announcement text. 3969 */ 3970 public void announceForAccessibility(CharSequence text) { 3971 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 3972 AccessibilityEvent event = AccessibilityEvent.obtain( 3973 AccessibilityEvent.TYPE_ANNOUNCEMENT); 3974 event.getText().add(text); 3975 sendAccessibilityEventUnchecked(event); 3976 } 3977 } 3978 3979 /** 3980 * @see #sendAccessibilityEvent(int) 3981 * 3982 * Note: Called from the default {@link AccessibilityDelegate}. 3983 */ 3984 void sendAccessibilityEventInternal(int eventType) { 3985 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 3986 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 3987 } 3988 } 3989 3990 /** 3991 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 3992 * takes as an argument an empty {@link AccessibilityEvent} and does not 3993 * perform a check whether accessibility is enabled. 3994 * <p> 3995 * If an {@link AccessibilityDelegate} has been specified via calling 3996 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3997 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 3998 * is responsible for handling this call. 3999 * </p> 4000 * 4001 * @param event The event to send. 4002 * 4003 * @see #sendAccessibilityEvent(int) 4004 */ 4005 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 4006 if (mAccessibilityDelegate != null) { 4007 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 4008 } else { 4009 sendAccessibilityEventUncheckedInternal(event); 4010 } 4011 } 4012 4013 /** 4014 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 4015 * 4016 * Note: Called from the default {@link AccessibilityDelegate}. 4017 */ 4018 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 4019 if (!isShown()) { 4020 return; 4021 } 4022 onInitializeAccessibilityEvent(event); 4023 // Only a subset of accessibility events populates text content. 4024 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 4025 dispatchPopulateAccessibilityEvent(event); 4026 } 4027 // In the beginning we called #isShown(), so we know that getParent() is not null. 4028 getParent().requestSendAccessibilityEvent(this, event); 4029 } 4030 4031 /** 4032 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 4033 * to its children for adding their text content to the event. Note that the 4034 * event text is populated in a separate dispatch path since we add to the 4035 * event not only the text of the source but also the text of all its descendants. 4036 * A typical implementation will call 4037 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 4038 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4039 * on each child. Override this method if custom population of the event text 4040 * content is required. 4041 * <p> 4042 * If an {@link AccessibilityDelegate} has been specified via calling 4043 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4044 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 4045 * is responsible for handling this call. 4046 * </p> 4047 * <p> 4048 * <em>Note:</em> Accessibility events of certain types are not dispatched for 4049 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 4050 * </p> 4051 * 4052 * @param event The event. 4053 * 4054 * @return True if the event population was completed. 4055 */ 4056 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 4057 if (mAccessibilityDelegate != null) { 4058 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 4059 } else { 4060 return dispatchPopulateAccessibilityEventInternal(event); 4061 } 4062 } 4063 4064 /** 4065 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4066 * 4067 * Note: Called from the default {@link AccessibilityDelegate}. 4068 */ 4069 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4070 onPopulateAccessibilityEvent(event); 4071 return false; 4072 } 4073 4074 /** 4075 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4076 * giving a chance to this View to populate the accessibility event with its 4077 * text content. While this method is free to modify event 4078 * attributes other than text content, doing so should normally be performed in 4079 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 4080 * <p> 4081 * Example: Adding formatted date string to an accessibility event in addition 4082 * to the text added by the super implementation: 4083 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4084 * super.onPopulateAccessibilityEvent(event); 4085 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 4086 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 4087 * mCurrentDate.getTimeInMillis(), flags); 4088 * event.getText().add(selectedDateUtterance); 4089 * }</pre> 4090 * <p> 4091 * If an {@link AccessibilityDelegate} has been specified via calling 4092 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4093 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 4094 * is responsible for handling this call. 4095 * </p> 4096 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4097 * information to the event, in case the default implementation has basic information to add. 4098 * </p> 4099 * 4100 * @param event The accessibility event which to populate. 4101 * 4102 * @see #sendAccessibilityEvent(int) 4103 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4104 */ 4105 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4106 if (mAccessibilityDelegate != null) { 4107 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 4108 } else { 4109 onPopulateAccessibilityEventInternal(event); 4110 } 4111 } 4112 4113 /** 4114 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 4115 * 4116 * Note: Called from the default {@link AccessibilityDelegate}. 4117 */ 4118 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4119 4120 } 4121 4122 /** 4123 * Initializes an {@link AccessibilityEvent} with information about 4124 * this View which is the event source. In other words, the source of 4125 * an accessibility event is the view whose state change triggered firing 4126 * the event. 4127 * <p> 4128 * Example: Setting the password property of an event in addition 4129 * to properties set by the super implementation: 4130 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4131 * super.onInitializeAccessibilityEvent(event); 4132 * event.setPassword(true); 4133 * }</pre> 4134 * <p> 4135 * If an {@link AccessibilityDelegate} has been specified via calling 4136 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4137 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 4138 * is responsible for handling this call. 4139 * </p> 4140 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4141 * information to the event, in case the default implementation has basic information to add. 4142 * </p> 4143 * @param event The event to initialize. 4144 * 4145 * @see #sendAccessibilityEvent(int) 4146 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4147 */ 4148 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4149 if (mAccessibilityDelegate != null) { 4150 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 4151 } else { 4152 onInitializeAccessibilityEventInternal(event); 4153 } 4154 } 4155 4156 /** 4157 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4158 * 4159 * Note: Called from the default {@link AccessibilityDelegate}. 4160 */ 4161 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 4162 event.setSource(this); 4163 event.setClassName(View.class.getName()); 4164 event.setPackageName(getContext().getPackageName()); 4165 event.setEnabled(isEnabled()); 4166 event.setContentDescription(mContentDescription); 4167 4168 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) { 4169 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList; 4170 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, 4171 FOCUSABLES_ALL); 4172 event.setItemCount(focusablesTempList.size()); 4173 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 4174 focusablesTempList.clear(); 4175 } 4176 } 4177 4178 /** 4179 * Returns an {@link AccessibilityNodeInfo} representing this view from the 4180 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 4181 * This method is responsible for obtaining an accessibility node info from a 4182 * pool of reusable instances and calling 4183 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 4184 * initialize the former. 4185 * <p> 4186 * Note: The client is responsible for recycling the obtained instance by calling 4187 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 4188 * </p> 4189 * 4190 * @return A populated {@link AccessibilityNodeInfo}. 4191 * 4192 * @see AccessibilityNodeInfo 4193 */ 4194 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 4195 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 4196 if (provider != null) { 4197 return provider.createAccessibilityNodeInfo(View.NO_ID); 4198 } else { 4199 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 4200 onInitializeAccessibilityNodeInfo(info); 4201 return info; 4202 } 4203 } 4204 4205 /** 4206 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 4207 * The base implementation sets: 4208 * <ul> 4209 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 4210 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 4211 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 4212 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 4213 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 4214 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 4215 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 4216 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 4217 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 4218 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 4219 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 4220 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 4221 * </ul> 4222 * <p> 4223 * Subclasses should override this method, call the super implementation, 4224 * and set additional attributes. 4225 * </p> 4226 * <p> 4227 * If an {@link AccessibilityDelegate} has been specified via calling 4228 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4229 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 4230 * is responsible for handling this call. 4231 * </p> 4232 * 4233 * @param info The instance to initialize. 4234 */ 4235 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 4236 if (mAccessibilityDelegate != null) { 4237 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 4238 } else { 4239 onInitializeAccessibilityNodeInfoInternal(info); 4240 } 4241 } 4242 4243 /** 4244 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 4245 * 4246 * Note: Called from the default {@link AccessibilityDelegate}. 4247 */ 4248 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 4249 Rect bounds = mAttachInfo.mTmpInvalRect; 4250 getDrawingRect(bounds); 4251 info.setBoundsInParent(bounds); 4252 4253 int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation; 4254 getLocationOnScreen(locationOnScreen); 4255 bounds.offsetTo(0, 0); 4256 bounds.offset(locationOnScreen[0], locationOnScreen[1]); 4257 info.setBoundsInScreen(bounds); 4258 4259 if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { 4260 ViewParent parent = getParent(); 4261 if (parent instanceof View) { 4262 View parentView = (View) parent; 4263 info.setParent(parentView); 4264 } 4265 } 4266 4267 info.setPackageName(mContext.getPackageName()); 4268 info.setClassName(View.class.getName()); 4269 info.setContentDescription(getContentDescription()); 4270 4271 info.setEnabled(isEnabled()); 4272 info.setClickable(isClickable()); 4273 info.setFocusable(isFocusable()); 4274 info.setFocused(isFocused()); 4275 info.setSelected(isSelected()); 4276 info.setLongClickable(isLongClickable()); 4277 4278 // TODO: These make sense only if we are in an AdapterView but all 4279 // views can be selected. Maybe from accessiiblity perspective 4280 // we should report as selectable view in an AdapterView. 4281 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 4282 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 4283 4284 if (isFocusable()) { 4285 if (isFocused()) { 4286 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 4287 } else { 4288 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 4289 } 4290 } 4291 } 4292 4293 /** 4294 * Sets a delegate for implementing accessibility support via compositon as 4295 * opposed to inheritance. The delegate's primary use is for implementing 4296 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 4297 * 4298 * @param delegate The delegate instance. 4299 * 4300 * @see AccessibilityDelegate 4301 */ 4302 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 4303 mAccessibilityDelegate = delegate; 4304 } 4305 4306 /** 4307 * Gets the provider for managing a virtual view hierarchy rooted at this View 4308 * and reported to {@link android.accessibilityservice.AccessibilityService}s 4309 * that explore the window content. 4310 * <p> 4311 * If this method returns an instance, this instance is responsible for managing 4312 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 4313 * View including the one representing the View itself. Similarly the returned 4314 * instance is responsible for performing accessibility actions on any virtual 4315 * view or the root view itself. 4316 * </p> 4317 * <p> 4318 * If an {@link AccessibilityDelegate} has been specified via calling 4319 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4320 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 4321 * is responsible for handling this call. 4322 * </p> 4323 * 4324 * @return The provider. 4325 * 4326 * @see AccessibilityNodeProvider 4327 */ 4328 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 4329 if (mAccessibilityDelegate != null) { 4330 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 4331 } else { 4332 return null; 4333 } 4334 } 4335 4336 /** 4337 * Gets the unique identifier of this view on the screen for accessibility purposes. 4338 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 4339 * 4340 * @return The view accessibility id. 4341 * 4342 * @hide 4343 */ 4344 public int getAccessibilityViewId() { 4345 if (mAccessibilityViewId == NO_ID) { 4346 mAccessibilityViewId = sNextAccessibilityViewId++; 4347 } 4348 return mAccessibilityViewId; 4349 } 4350 4351 /** 4352 * Gets the unique identifier of the window in which this View reseides. 4353 * 4354 * @return The window accessibility id. 4355 * 4356 * @hide 4357 */ 4358 public int getAccessibilityWindowId() { 4359 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 4360 } 4361 4362 /** 4363 * Gets the {@link View} description. It briefly describes the view and is 4364 * primarily used for accessibility support. Set this property to enable 4365 * better accessibility support for your application. This is especially 4366 * true for views that do not have textual representation (For example, 4367 * ImageButton). 4368 * 4369 * @return The content descriptiopn. 4370 * 4371 * @attr ref android.R.styleable#View_contentDescription 4372 */ 4373 public CharSequence getContentDescription() { 4374 return mContentDescription; 4375 } 4376 4377 /** 4378 * Sets the {@link View} description. It briefly describes the view and is 4379 * primarily used for accessibility support. Set this property to enable 4380 * better accessibility support for your application. This is especially 4381 * true for views that do not have textual representation (For example, 4382 * ImageButton). 4383 * 4384 * @param contentDescription The content description. 4385 * 4386 * @attr ref android.R.styleable#View_contentDescription 4387 */ 4388 @RemotableViewMethod 4389 public void setContentDescription(CharSequence contentDescription) { 4390 mContentDescription = contentDescription; 4391 } 4392 4393 /** 4394 * Invoked whenever this view loses focus, either by losing window focus or by losing 4395 * focus within its window. This method can be used to clear any state tied to the 4396 * focus. For instance, if a button is held pressed with the trackball and the window 4397 * loses focus, this method can be used to cancel the press. 4398 * 4399 * Subclasses of View overriding this method should always call super.onFocusLost(). 4400 * 4401 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 4402 * @see #onWindowFocusChanged(boolean) 4403 * 4404 * @hide pending API council approval 4405 */ 4406 protected void onFocusLost() { 4407 resetPressedState(); 4408 } 4409 4410 private void resetPressedState() { 4411 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 4412 return; 4413 } 4414 4415 if (isPressed()) { 4416 setPressed(false); 4417 4418 if (!mHasPerformedLongPress) { 4419 removeLongPressCallback(); 4420 } 4421 } 4422 } 4423 4424 /** 4425 * Returns true if this view has focus 4426 * 4427 * @return True if this view has focus, false otherwise. 4428 */ 4429 @ViewDebug.ExportedProperty(category = "focus") 4430 public boolean isFocused() { 4431 return (mPrivateFlags & FOCUSED) != 0; 4432 } 4433 4434 /** 4435 * Find the view in the hierarchy rooted at this view that currently has 4436 * focus. 4437 * 4438 * @return The view that currently has focus, or null if no focused view can 4439 * be found. 4440 */ 4441 public View findFocus() { 4442 return (mPrivateFlags & FOCUSED) != 0 ? this : null; 4443 } 4444 4445 /** 4446 * Change whether this view is one of the set of scrollable containers in 4447 * its window. This will be used to determine whether the window can 4448 * resize or must pan when a soft input area is open -- scrollable 4449 * containers allow the window to use resize mode since the container 4450 * will appropriately shrink. 4451 */ 4452 public void setScrollContainer(boolean isScrollContainer) { 4453 if (isScrollContainer) { 4454 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) { 4455 mAttachInfo.mScrollContainers.add(this); 4456 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 4457 } 4458 mPrivateFlags |= SCROLL_CONTAINER; 4459 } else { 4460 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 4461 mAttachInfo.mScrollContainers.remove(this); 4462 } 4463 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED); 4464 } 4465 } 4466 4467 /** 4468 * Returns the quality of the drawing cache. 4469 * 4470 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4471 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4472 * 4473 * @see #setDrawingCacheQuality(int) 4474 * @see #setDrawingCacheEnabled(boolean) 4475 * @see #isDrawingCacheEnabled() 4476 * 4477 * @attr ref android.R.styleable#View_drawingCacheQuality 4478 */ 4479 public int getDrawingCacheQuality() { 4480 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 4481 } 4482 4483 /** 4484 * Set the drawing cache quality of this view. This value is used only when the 4485 * drawing cache is enabled 4486 * 4487 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4488 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4489 * 4490 * @see #getDrawingCacheQuality() 4491 * @see #setDrawingCacheEnabled(boolean) 4492 * @see #isDrawingCacheEnabled() 4493 * 4494 * @attr ref android.R.styleable#View_drawingCacheQuality 4495 */ 4496 public void setDrawingCacheQuality(int quality) { 4497 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 4498 } 4499 4500 /** 4501 * Returns whether the screen should remain on, corresponding to the current 4502 * value of {@link #KEEP_SCREEN_ON}. 4503 * 4504 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 4505 * 4506 * @see #setKeepScreenOn(boolean) 4507 * 4508 * @attr ref android.R.styleable#View_keepScreenOn 4509 */ 4510 public boolean getKeepScreenOn() { 4511 return (mViewFlags & KEEP_SCREEN_ON) != 0; 4512 } 4513 4514 /** 4515 * Controls whether the screen should remain on, modifying the 4516 * value of {@link #KEEP_SCREEN_ON}. 4517 * 4518 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 4519 * 4520 * @see #getKeepScreenOn() 4521 * 4522 * @attr ref android.R.styleable#View_keepScreenOn 4523 */ 4524 public void setKeepScreenOn(boolean keepScreenOn) { 4525 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 4526 } 4527 4528 /** 4529 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4530 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4531 * 4532 * @attr ref android.R.styleable#View_nextFocusLeft 4533 */ 4534 public int getNextFocusLeftId() { 4535 return mNextFocusLeftId; 4536 } 4537 4538 /** 4539 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4540 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 4541 * decide automatically. 4542 * 4543 * @attr ref android.R.styleable#View_nextFocusLeft 4544 */ 4545 public void setNextFocusLeftId(int nextFocusLeftId) { 4546 mNextFocusLeftId = nextFocusLeftId; 4547 } 4548 4549 /** 4550 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4551 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4552 * 4553 * @attr ref android.R.styleable#View_nextFocusRight 4554 */ 4555 public int getNextFocusRightId() { 4556 return mNextFocusRightId; 4557 } 4558 4559 /** 4560 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4561 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 4562 * decide automatically. 4563 * 4564 * @attr ref android.R.styleable#View_nextFocusRight 4565 */ 4566 public void setNextFocusRightId(int nextFocusRightId) { 4567 mNextFocusRightId = nextFocusRightId; 4568 } 4569 4570 /** 4571 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4572 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4573 * 4574 * @attr ref android.R.styleable#View_nextFocusUp 4575 */ 4576 public int getNextFocusUpId() { 4577 return mNextFocusUpId; 4578 } 4579 4580 /** 4581 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4582 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 4583 * decide automatically. 4584 * 4585 * @attr ref android.R.styleable#View_nextFocusUp 4586 */ 4587 public void setNextFocusUpId(int nextFocusUpId) { 4588 mNextFocusUpId = nextFocusUpId; 4589 } 4590 4591 /** 4592 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4593 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4594 * 4595 * @attr ref android.R.styleable#View_nextFocusDown 4596 */ 4597 public int getNextFocusDownId() { 4598 return mNextFocusDownId; 4599 } 4600 4601 /** 4602 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4603 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 4604 * decide automatically. 4605 * 4606 * @attr ref android.R.styleable#View_nextFocusDown 4607 */ 4608 public void setNextFocusDownId(int nextFocusDownId) { 4609 mNextFocusDownId = nextFocusDownId; 4610 } 4611 4612 /** 4613 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4614 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4615 * 4616 * @attr ref android.R.styleable#View_nextFocusForward 4617 */ 4618 public int getNextFocusForwardId() { 4619 return mNextFocusForwardId; 4620 } 4621 4622 /** 4623 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4624 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 4625 * decide automatically. 4626 * 4627 * @attr ref android.R.styleable#View_nextFocusForward 4628 */ 4629 public void setNextFocusForwardId(int nextFocusForwardId) { 4630 mNextFocusForwardId = nextFocusForwardId; 4631 } 4632 4633 /** 4634 * Returns the visibility of this view and all of its ancestors 4635 * 4636 * @return True if this view and all of its ancestors are {@link #VISIBLE} 4637 */ 4638 public boolean isShown() { 4639 View current = this; 4640 //noinspection ConstantConditions 4641 do { 4642 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 4643 return false; 4644 } 4645 ViewParent parent = current.mParent; 4646 if (parent == null) { 4647 return false; // We are not attached to the view root 4648 } 4649 if (!(parent instanceof View)) { 4650 return true; 4651 } 4652 current = (View) parent; 4653 } while (current != null); 4654 4655 return false; 4656 } 4657 4658 /** 4659 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag 4660 * is set 4661 * 4662 * @param insets Insets for system windows 4663 * 4664 * @return True if this view applied the insets, false otherwise 4665 */ 4666 protected boolean fitSystemWindows(Rect insets) { 4667 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 4668 mPaddingLeft = insets.left; 4669 mPaddingTop = insets.top; 4670 mPaddingRight = insets.right; 4671 mPaddingBottom = insets.bottom; 4672 requestLayout(); 4673 return true; 4674 } 4675 return false; 4676 } 4677 4678 /** 4679 * Set whether or not this view should account for system screen decorations 4680 * such as the status bar and inset its content. This allows this view to be 4681 * positioned in absolute screen coordinates and remain visible to the user. 4682 * 4683 * <p>This should only be used by top-level window decor views. 4684 * 4685 * @param fitSystemWindows true to inset content for system screen decorations, false for 4686 * default behavior. 4687 * 4688 * @attr ref android.R.styleable#View_fitsSystemWindows 4689 */ 4690 public void setFitsSystemWindows(boolean fitSystemWindows) { 4691 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 4692 } 4693 4694 /** 4695 * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view 4696 * will account for system screen decorations such as the status bar and inset its 4697 * content. This allows the view to be positioned in absolute screen coordinates 4698 * and remain visible to the user. 4699 * 4700 * @return true if this view will adjust its content bounds for system screen decorations. 4701 * 4702 * @attr ref android.R.styleable#View_fitsSystemWindows 4703 */ 4704 public boolean fitsSystemWindows() { 4705 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 4706 } 4707 4708 /** 4709 * Returns the visibility status for this view. 4710 * 4711 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4712 * @attr ref android.R.styleable#View_visibility 4713 */ 4714 @ViewDebug.ExportedProperty(mapping = { 4715 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 4716 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 4717 @ViewDebug.IntToString(from = GONE, to = "GONE") 4718 }) 4719 public int getVisibility() { 4720 return mViewFlags & VISIBILITY_MASK; 4721 } 4722 4723 /** 4724 * Set the enabled state of this view. 4725 * 4726 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4727 * @attr ref android.R.styleable#View_visibility 4728 */ 4729 @RemotableViewMethod 4730 public void setVisibility(int visibility) { 4731 setFlags(visibility, VISIBILITY_MASK); 4732 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); 4733 } 4734 4735 /** 4736 * Returns the enabled status for this view. The interpretation of the 4737 * enabled state varies by subclass. 4738 * 4739 * @return True if this view is enabled, false otherwise. 4740 */ 4741 @ViewDebug.ExportedProperty 4742 public boolean isEnabled() { 4743 return (mViewFlags & ENABLED_MASK) == ENABLED; 4744 } 4745 4746 /** 4747 * Set the enabled state of this view. The interpretation of the enabled 4748 * state varies by subclass. 4749 * 4750 * @param enabled True if this view is enabled, false otherwise. 4751 */ 4752 @RemotableViewMethod 4753 public void setEnabled(boolean enabled) { 4754 if (enabled == isEnabled()) return; 4755 4756 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 4757 4758 /* 4759 * The View most likely has to change its appearance, so refresh 4760 * the drawable state. 4761 */ 4762 refreshDrawableState(); 4763 4764 // Invalidate too, since the default behavior for views is to be 4765 // be drawn at 50% alpha rather than to change the drawable. 4766 invalidate(true); 4767 } 4768 4769 /** 4770 * Set whether this view can receive the focus. 4771 * 4772 * Setting this to false will also ensure that this view is not focusable 4773 * in touch mode. 4774 * 4775 * @param focusable If true, this view can receive the focus. 4776 * 4777 * @see #setFocusableInTouchMode(boolean) 4778 * @attr ref android.R.styleable#View_focusable 4779 */ 4780 public void setFocusable(boolean focusable) { 4781 if (!focusable) { 4782 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 4783 } 4784 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 4785 } 4786 4787 /** 4788 * Set whether this view can receive focus while in touch mode. 4789 * 4790 * Setting this to true will also ensure that this view is focusable. 4791 * 4792 * @param focusableInTouchMode If true, this view can receive the focus while 4793 * in touch mode. 4794 * 4795 * @see #setFocusable(boolean) 4796 * @attr ref android.R.styleable#View_focusableInTouchMode 4797 */ 4798 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 4799 // Focusable in touch mode should always be set before the focusable flag 4800 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 4801 // which, in touch mode, will not successfully request focus on this view 4802 // because the focusable in touch mode flag is not set 4803 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 4804 if (focusableInTouchMode) { 4805 setFlags(FOCUSABLE, FOCUSABLE_MASK); 4806 } 4807 } 4808 4809 /** 4810 * Set whether this view should have sound effects enabled for events such as 4811 * clicking and touching. 4812 * 4813 * <p>You may wish to disable sound effects for a view if you already play sounds, 4814 * for instance, a dial key that plays dtmf tones. 4815 * 4816 * @param soundEffectsEnabled whether sound effects are enabled for this view. 4817 * @see #isSoundEffectsEnabled() 4818 * @see #playSoundEffect(int) 4819 * @attr ref android.R.styleable#View_soundEffectsEnabled 4820 */ 4821 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 4822 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 4823 } 4824 4825 /** 4826 * @return whether this view should have sound effects enabled for events such as 4827 * clicking and touching. 4828 * 4829 * @see #setSoundEffectsEnabled(boolean) 4830 * @see #playSoundEffect(int) 4831 * @attr ref android.R.styleable#View_soundEffectsEnabled 4832 */ 4833 @ViewDebug.ExportedProperty 4834 public boolean isSoundEffectsEnabled() { 4835 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 4836 } 4837 4838 /** 4839 * Set whether this view should have haptic feedback for events such as 4840 * long presses. 4841 * 4842 * <p>You may wish to disable haptic feedback if your view already controls 4843 * its own haptic feedback. 4844 * 4845 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 4846 * @see #isHapticFeedbackEnabled() 4847 * @see #performHapticFeedback(int) 4848 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4849 */ 4850 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 4851 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 4852 } 4853 4854 /** 4855 * @return whether this view should have haptic feedback enabled for events 4856 * long presses. 4857 * 4858 * @see #setHapticFeedbackEnabled(boolean) 4859 * @see #performHapticFeedback(int) 4860 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4861 */ 4862 @ViewDebug.ExportedProperty 4863 public boolean isHapticFeedbackEnabled() { 4864 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 4865 } 4866 4867 /** 4868 * Returns the layout direction for this view. 4869 * 4870 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 4871 * {@link #LAYOUT_DIRECTION_RTL}, 4872 * {@link #LAYOUT_DIRECTION_INHERIT} or 4873 * {@link #LAYOUT_DIRECTION_LOCALE}. 4874 * @attr ref android.R.styleable#View_layoutDirection 4875 */ 4876 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4877 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 4878 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 4879 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 4880 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 4881 }) 4882 public int getLayoutDirection() { 4883 return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT; 4884 } 4885 4886 /** 4887 * Set the layout direction for this view. This will propagate a reset of layout direction 4888 * resolution to the view's children and resolve layout direction for this view. 4889 * 4890 * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR}, 4891 * {@link #LAYOUT_DIRECTION_RTL}, 4892 * {@link #LAYOUT_DIRECTION_INHERIT} or 4893 * {@link #LAYOUT_DIRECTION_LOCALE}. 4894 * 4895 * @attr ref android.R.styleable#View_layoutDirection 4896 */ 4897 @RemotableViewMethod 4898 public void setLayoutDirection(int layoutDirection) { 4899 if (getLayoutDirection() != layoutDirection) { 4900 // Reset the current layout direction 4901 mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK; 4902 // Reset the current resolved layout direction 4903 resetResolvedLayoutDirection(); 4904 // Set the new layout direction (filtered) and ask for a layout pass 4905 mPrivateFlags2 |= 4906 ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK); 4907 requestLayout(); 4908 } 4909 } 4910 4911 /** 4912 * Returns the resolved layout direction for this view. 4913 * 4914 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 4915 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 4916 */ 4917 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4918 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 4919 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 4920 }) 4921 public int getResolvedLayoutDirection() { 4922 resolveLayoutDirectionIfNeeded(); 4923 return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ? 4924 LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 4925 } 4926 4927 /** 4928 * Indicates whether or not this view's layout is right-to-left. This is resolved from 4929 * layout attribute and/or the inherited value from the parent 4930 * 4931 * @return true if the layout is right-to-left. 4932 */ 4933 @ViewDebug.ExportedProperty(category = "layout") 4934 public boolean isLayoutRtl() { 4935 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 4936 } 4937 4938 /** 4939 * Indicates whether the view is currently tracking transient state that the 4940 * app should not need to concern itself with saving and restoring, but that 4941 * the framework should take special note to preserve when possible. 4942 * 4943 * @return true if the view has transient state 4944 */ 4945 @ViewDebug.ExportedProperty(category = "layout") 4946 public boolean hasTransientState() { 4947 return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE; 4948 } 4949 4950 /** 4951 * Set whether this view is currently tracking transient state that the 4952 * framework should attempt to preserve when possible. 4953 * 4954 * @param hasTransientState true if this view has transient state 4955 */ 4956 public void setHasTransientState(boolean hasTransientState) { 4957 if (hasTransientState() == hasTransientState) return; 4958 4959 mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) | 4960 (hasTransientState ? HAS_TRANSIENT_STATE : 0); 4961 if (mParent != null) { 4962 try { 4963 mParent.childHasTransientStateChanged(this, hasTransientState); 4964 } catch (AbstractMethodError e) { 4965 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 4966 " does not fully implement ViewParent", e); 4967 } 4968 } 4969 } 4970 4971 /** 4972 * If this view doesn't do any drawing on its own, set this flag to 4973 * allow further optimizations. By default, this flag is not set on 4974 * View, but could be set on some View subclasses such as ViewGroup. 4975 * 4976 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 4977 * you should clear this flag. 4978 * 4979 * @param willNotDraw whether or not this View draw on its own 4980 */ 4981 public void setWillNotDraw(boolean willNotDraw) { 4982 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 4983 } 4984 4985 /** 4986 * Returns whether or not this View draws on its own. 4987 * 4988 * @return true if this view has nothing to draw, false otherwise 4989 */ 4990 @ViewDebug.ExportedProperty(category = "drawing") 4991 public boolean willNotDraw() { 4992 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 4993 } 4994 4995 /** 4996 * When a View's drawing cache is enabled, drawing is redirected to an 4997 * offscreen bitmap. Some views, like an ImageView, must be able to 4998 * bypass this mechanism if they already draw a single bitmap, to avoid 4999 * unnecessary usage of the memory. 5000 * 5001 * @param willNotCacheDrawing true if this view does not cache its 5002 * drawing, false otherwise 5003 */ 5004 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 5005 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 5006 } 5007 5008 /** 5009 * Returns whether or not this View can cache its drawing or not. 5010 * 5011 * @return true if this view does not cache its drawing, false otherwise 5012 */ 5013 @ViewDebug.ExportedProperty(category = "drawing") 5014 public boolean willNotCacheDrawing() { 5015 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 5016 } 5017 5018 /** 5019 * Indicates whether this view reacts to click events or not. 5020 * 5021 * @return true if the view is clickable, false otherwise 5022 * 5023 * @see #setClickable(boolean) 5024 * @attr ref android.R.styleable#View_clickable 5025 */ 5026 @ViewDebug.ExportedProperty 5027 public boolean isClickable() { 5028 return (mViewFlags & CLICKABLE) == CLICKABLE; 5029 } 5030 5031 /** 5032 * Enables or disables click events for this view. When a view 5033 * is clickable it will change its state to "pressed" on every click. 5034 * Subclasses should set the view clickable to visually react to 5035 * user's clicks. 5036 * 5037 * @param clickable true to make the view clickable, false otherwise 5038 * 5039 * @see #isClickable() 5040 * @attr ref android.R.styleable#View_clickable 5041 */ 5042 public void setClickable(boolean clickable) { 5043 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 5044 } 5045 5046 /** 5047 * Indicates whether this view reacts to long click events or not. 5048 * 5049 * @return true if the view is long clickable, false otherwise 5050 * 5051 * @see #setLongClickable(boolean) 5052 * @attr ref android.R.styleable#View_longClickable 5053 */ 5054 public boolean isLongClickable() { 5055 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 5056 } 5057 5058 /** 5059 * Enables or disables long click events for this view. When a view is long 5060 * clickable it reacts to the user holding down the button for a longer 5061 * duration than a tap. This event can either launch the listener or a 5062 * context menu. 5063 * 5064 * @param longClickable true to make the view long clickable, false otherwise 5065 * @see #isLongClickable() 5066 * @attr ref android.R.styleable#View_longClickable 5067 */ 5068 public void setLongClickable(boolean longClickable) { 5069 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 5070 } 5071 5072 /** 5073 * Sets the pressed state for this view. 5074 * 5075 * @see #isClickable() 5076 * @see #setClickable(boolean) 5077 * 5078 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 5079 * the View's internal state from a previously set "pressed" state. 5080 */ 5081 public void setPressed(boolean pressed) { 5082 final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED); 5083 5084 if (pressed) { 5085 mPrivateFlags |= PRESSED; 5086 } else { 5087 mPrivateFlags &= ~PRESSED; 5088 } 5089 5090 if (needsRefresh) { 5091 refreshDrawableState(); 5092 } 5093 dispatchSetPressed(pressed); 5094 } 5095 5096 /** 5097 * Dispatch setPressed to all of this View's children. 5098 * 5099 * @see #setPressed(boolean) 5100 * 5101 * @param pressed The new pressed state 5102 */ 5103 protected void dispatchSetPressed(boolean pressed) { 5104 } 5105 5106 /** 5107 * Indicates whether the view is currently in pressed state. Unless 5108 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 5109 * the pressed state. 5110 * 5111 * @see #setPressed(boolean) 5112 * @see #isClickable() 5113 * @see #setClickable(boolean) 5114 * 5115 * @return true if the view is currently pressed, false otherwise 5116 */ 5117 public boolean isPressed() { 5118 return (mPrivateFlags & PRESSED) == PRESSED; 5119 } 5120 5121 /** 5122 * Indicates whether this view will save its state (that is, 5123 * whether its {@link #onSaveInstanceState} method will be called). 5124 * 5125 * @return Returns true if the view state saving is enabled, else false. 5126 * 5127 * @see #setSaveEnabled(boolean) 5128 * @attr ref android.R.styleable#View_saveEnabled 5129 */ 5130 public boolean isSaveEnabled() { 5131 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 5132 } 5133 5134 /** 5135 * Controls whether the saving of this view's state is 5136 * enabled (that is, whether its {@link #onSaveInstanceState} method 5137 * will be called). Note that even if freezing is enabled, the 5138 * view still must have an id assigned to it (via {@link #setId(int)}) 5139 * for its state to be saved. This flag can only disable the 5140 * saving of this view; any child views may still have their state saved. 5141 * 5142 * @param enabled Set to false to <em>disable</em> state saving, or true 5143 * (the default) to allow it. 5144 * 5145 * @see #isSaveEnabled() 5146 * @see #setId(int) 5147 * @see #onSaveInstanceState() 5148 * @attr ref android.R.styleable#View_saveEnabled 5149 */ 5150 public void setSaveEnabled(boolean enabled) { 5151 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 5152 } 5153 5154 /** 5155 * Gets whether the framework should discard touches when the view's 5156 * window is obscured by another visible window. 5157 * Refer to the {@link View} security documentation for more details. 5158 * 5159 * @return True if touch filtering is enabled. 5160 * 5161 * @see #setFilterTouchesWhenObscured(boolean) 5162 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 5163 */ 5164 @ViewDebug.ExportedProperty 5165 public boolean getFilterTouchesWhenObscured() { 5166 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 5167 } 5168 5169 /** 5170 * Sets whether the framework should discard touches when the view's 5171 * window is obscured by another visible window. 5172 * Refer to the {@link View} security documentation for more details. 5173 * 5174 * @param enabled True if touch filtering should be enabled. 5175 * 5176 * @see #getFilterTouchesWhenObscured 5177 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 5178 */ 5179 public void setFilterTouchesWhenObscured(boolean enabled) { 5180 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 5181 FILTER_TOUCHES_WHEN_OBSCURED); 5182 } 5183 5184 /** 5185 * Indicates whether the entire hierarchy under this view will save its 5186 * state when a state saving traversal occurs from its parent. The default 5187 * is true; if false, these views will not be saved unless 5188 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 5189 * 5190 * @return Returns true if the view state saving from parent is enabled, else false. 5191 * 5192 * @see #setSaveFromParentEnabled(boolean) 5193 */ 5194 public boolean isSaveFromParentEnabled() { 5195 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 5196 } 5197 5198 /** 5199 * Controls whether the entire hierarchy under this view will save its 5200 * state when a state saving traversal occurs from its parent. The default 5201 * is true; if false, these views will not be saved unless 5202 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 5203 * 5204 * @param enabled Set to false to <em>disable</em> state saving, or true 5205 * (the default) to allow it. 5206 * 5207 * @see #isSaveFromParentEnabled() 5208 * @see #setId(int) 5209 * @see #onSaveInstanceState() 5210 */ 5211 public void setSaveFromParentEnabled(boolean enabled) { 5212 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 5213 } 5214 5215 5216 /** 5217 * Returns whether this View is able to take focus. 5218 * 5219 * @return True if this view can take focus, or false otherwise. 5220 * @attr ref android.R.styleable#View_focusable 5221 */ 5222 @ViewDebug.ExportedProperty(category = "focus") 5223 public final boolean isFocusable() { 5224 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 5225 } 5226 5227 /** 5228 * When a view is focusable, it may not want to take focus when in touch mode. 5229 * For example, a button would like focus when the user is navigating via a D-pad 5230 * so that the user can click on it, but once the user starts touching the screen, 5231 * the button shouldn't take focus 5232 * @return Whether the view is focusable in touch mode. 5233 * @attr ref android.R.styleable#View_focusableInTouchMode 5234 */ 5235 @ViewDebug.ExportedProperty 5236 public final boolean isFocusableInTouchMode() { 5237 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 5238 } 5239 5240 /** 5241 * Find the nearest view in the specified direction that can take focus. 5242 * This does not actually give focus to that view. 5243 * 5244 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5245 * 5246 * @return The nearest focusable in the specified direction, or null if none 5247 * can be found. 5248 */ 5249 public View focusSearch(int direction) { 5250 if (mParent != null) { 5251 return mParent.focusSearch(this, direction); 5252 } else { 5253 return null; 5254 } 5255 } 5256 5257 /** 5258 * This method is the last chance for the focused view and its ancestors to 5259 * respond to an arrow key. This is called when the focused view did not 5260 * consume the key internally, nor could the view system find a new view in 5261 * the requested direction to give focus to. 5262 * 5263 * @param focused The currently focused view. 5264 * @param direction The direction focus wants to move. One of FOCUS_UP, 5265 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 5266 * @return True if the this view consumed this unhandled move. 5267 */ 5268 public boolean dispatchUnhandledMove(View focused, int direction) { 5269 return false; 5270 } 5271 5272 /** 5273 * If a user manually specified the next view id for a particular direction, 5274 * use the root to look up the view. 5275 * @param root The root view of the hierarchy containing this view. 5276 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 5277 * or FOCUS_BACKWARD. 5278 * @return The user specified next view, or null if there is none. 5279 */ 5280 View findUserSetNextFocus(View root, int direction) { 5281 switch (direction) { 5282 case FOCUS_LEFT: 5283 if (mNextFocusLeftId == View.NO_ID) return null; 5284 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 5285 case FOCUS_RIGHT: 5286 if (mNextFocusRightId == View.NO_ID) return null; 5287 return findViewInsideOutShouldExist(root, mNextFocusRightId); 5288 case FOCUS_UP: 5289 if (mNextFocusUpId == View.NO_ID) return null; 5290 return findViewInsideOutShouldExist(root, mNextFocusUpId); 5291 case FOCUS_DOWN: 5292 if (mNextFocusDownId == View.NO_ID) return null; 5293 return findViewInsideOutShouldExist(root, mNextFocusDownId); 5294 case FOCUS_FORWARD: 5295 if (mNextFocusForwardId == View.NO_ID) return null; 5296 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 5297 case FOCUS_BACKWARD: { 5298 if (mID == View.NO_ID) return null; 5299 final int id = mID; 5300 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5301 @Override 5302 public boolean apply(View t) { 5303 return t.mNextFocusForwardId == id; 5304 } 5305 }); 5306 } 5307 } 5308 return null; 5309 } 5310 5311 private View findViewInsideOutShouldExist(View root, final int childViewId) { 5312 View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5313 @Override 5314 public boolean apply(View t) { 5315 return t.mID == childViewId; 5316 } 5317 }); 5318 5319 if (result == null) { 5320 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified " 5321 + "by user for id " + childViewId); 5322 } 5323 return result; 5324 } 5325 5326 /** 5327 * Find and return all focusable views that are descendants of this view, 5328 * possibly including this view if it is focusable itself. 5329 * 5330 * @param direction The direction of the focus 5331 * @return A list of focusable views 5332 */ 5333 public ArrayList<View> getFocusables(int direction) { 5334 ArrayList<View> result = new ArrayList<View>(24); 5335 addFocusables(result, direction); 5336 return result; 5337 } 5338 5339 /** 5340 * Add any focusable views that are descendants of this view (possibly 5341 * including this view if it is focusable itself) to views. If we are in touch mode, 5342 * only add views that are also focusable in touch mode. 5343 * 5344 * @param views Focusable views found so far 5345 * @param direction The direction of the focus 5346 */ 5347 public void addFocusables(ArrayList<View> views, int direction) { 5348 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 5349 } 5350 5351 /** 5352 * Adds any focusable views that are descendants of this view (possibly 5353 * including this view if it is focusable itself) to views. This method 5354 * adds all focusable views regardless if we are in touch mode or 5355 * only views focusable in touch mode if we are in touch mode depending on 5356 * the focusable mode paramater. 5357 * 5358 * @param views Focusable views found so far or null if all we are interested is 5359 * the number of focusables. 5360 * @param direction The direction of the focus. 5361 * @param focusableMode The type of focusables to be added. 5362 * 5363 * @see #FOCUSABLES_ALL 5364 * @see #FOCUSABLES_TOUCH_MODE 5365 */ 5366 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 5367 if (!isFocusable()) { 5368 return; 5369 } 5370 5371 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 5372 isInTouchMode() && !isFocusableInTouchMode()) { 5373 return; 5374 } 5375 5376 if (views != null) { 5377 views.add(this); 5378 } 5379 } 5380 5381 /** 5382 * Finds the Views that contain given text. The containment is case insensitive. 5383 * The search is performed by either the text that the View renders or the content 5384 * description that describes the view for accessibility purposes and the view does 5385 * not render or both. Clients can specify how the search is to be performed via 5386 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 5387 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 5388 * 5389 * @param outViews The output list of matching Views. 5390 * @param searched The text to match against. 5391 * 5392 * @see #FIND_VIEWS_WITH_TEXT 5393 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 5394 * @see #setContentDescription(CharSequence) 5395 */ 5396 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 5397 if (getAccessibilityNodeProvider() != null) { 5398 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 5399 outViews.add(this); 5400 } 5401 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 5402 && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) { 5403 String searchedLowerCase = searched.toString().toLowerCase(); 5404 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 5405 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 5406 outViews.add(this); 5407 } 5408 } 5409 } 5410 5411 /** 5412 * Find and return all touchable views that are descendants of this view, 5413 * possibly including this view if it is touchable itself. 5414 * 5415 * @return A list of touchable views 5416 */ 5417 public ArrayList<View> getTouchables() { 5418 ArrayList<View> result = new ArrayList<View>(); 5419 addTouchables(result); 5420 return result; 5421 } 5422 5423 /** 5424 * Add any touchable views that are descendants of this view (possibly 5425 * including this view if it is touchable itself) to views. 5426 * 5427 * @param views Touchable views found so far 5428 */ 5429 public void addTouchables(ArrayList<View> views) { 5430 final int viewFlags = mViewFlags; 5431 5432 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 5433 && (viewFlags & ENABLED_MASK) == ENABLED) { 5434 views.add(this); 5435 } 5436 } 5437 5438 /** 5439 * Call this to try to give focus to a specific view or to one of its 5440 * descendants. 5441 * 5442 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5443 * false), or if it is focusable and it is not focusable in touch mode 5444 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5445 * 5446 * See also {@link #focusSearch(int)}, which is what you call to say that you 5447 * have focus, and you want your parent to look for the next one. 5448 * 5449 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 5450 * {@link #FOCUS_DOWN} and <code>null</code>. 5451 * 5452 * @return Whether this view or one of its descendants actually took focus. 5453 */ 5454 public final boolean requestFocus() { 5455 return requestFocus(View.FOCUS_DOWN); 5456 } 5457 5458 5459 /** 5460 * Call this to try to give focus to a specific view or to one of its 5461 * descendants and give it a hint about what direction focus is heading. 5462 * 5463 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5464 * false), or if it is focusable and it is not focusable in touch mode 5465 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5466 * 5467 * See also {@link #focusSearch(int)}, which is what you call to say that you 5468 * have focus, and you want your parent to look for the next one. 5469 * 5470 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 5471 * <code>null</code> set for the previously focused rectangle. 5472 * 5473 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5474 * @return Whether this view or one of its descendants actually took focus. 5475 */ 5476 public final boolean requestFocus(int direction) { 5477 return requestFocus(direction, null); 5478 } 5479 5480 /** 5481 * Call this to try to give focus to a specific view or to one of its descendants 5482 * and give it hints about the direction and a specific rectangle that the focus 5483 * is coming from. The rectangle can help give larger views a finer grained hint 5484 * about where focus is coming from, and therefore, where to show selection, or 5485 * forward focus change internally. 5486 * 5487 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5488 * false), or if it is focusable and it is not focusable in touch mode 5489 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5490 * 5491 * A View will not take focus if it is not visible. 5492 * 5493 * A View will not take focus if one of its parents has 5494 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 5495 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 5496 * 5497 * See also {@link #focusSearch(int)}, which is what you call to say that you 5498 * have focus, and you want your parent to look for the next one. 5499 * 5500 * You may wish to override this method if your custom {@link View} has an internal 5501 * {@link View} that it wishes to forward the request to. 5502 * 5503 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5504 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 5505 * to give a finer grained hint about where focus is coming from. May be null 5506 * if there is no hint. 5507 * @return Whether this view or one of its descendants actually took focus. 5508 */ 5509 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 5510 // need to be focusable 5511 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 5512 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5513 return false; 5514 } 5515 5516 // need to be focusable in touch mode if in touch mode 5517 if (isInTouchMode() && 5518 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 5519 return false; 5520 } 5521 5522 // need to not have any parents blocking us 5523 if (hasAncestorThatBlocksDescendantFocus()) { 5524 return false; 5525 } 5526 5527 handleFocusGainInternal(direction, previouslyFocusedRect); 5528 return true; 5529 } 5530 5531 /** 5532 * Call this to try to give focus to a specific view or to one of its descendants. This is a 5533 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 5534 * touch mode to request focus when they are touched. 5535 * 5536 * @return Whether this view or one of its descendants actually took focus. 5537 * 5538 * @see #isInTouchMode() 5539 * 5540 */ 5541 public final boolean requestFocusFromTouch() { 5542 // Leave touch mode if we need to 5543 if (isInTouchMode()) { 5544 ViewRootImpl viewRoot = getViewRootImpl(); 5545 if (viewRoot != null) { 5546 viewRoot.ensureTouchMode(false); 5547 } 5548 } 5549 return requestFocus(View.FOCUS_DOWN); 5550 } 5551 5552 /** 5553 * @return Whether any ancestor of this view blocks descendant focus. 5554 */ 5555 private boolean hasAncestorThatBlocksDescendantFocus() { 5556 ViewParent ancestor = mParent; 5557 while (ancestor instanceof ViewGroup) { 5558 final ViewGroup vgAncestor = (ViewGroup) ancestor; 5559 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 5560 return true; 5561 } else { 5562 ancestor = vgAncestor.getParent(); 5563 } 5564 } 5565 return false; 5566 } 5567 5568 /** 5569 * @hide 5570 */ 5571 public void dispatchStartTemporaryDetach() { 5572 onStartTemporaryDetach(); 5573 } 5574 5575 /** 5576 * This is called when a container is going to temporarily detach a child, with 5577 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 5578 * It will either be followed by {@link #onFinishTemporaryDetach()} or 5579 * {@link #onDetachedFromWindow()} when the container is done. 5580 */ 5581 public void onStartTemporaryDetach() { 5582 removeUnsetPressCallback(); 5583 mPrivateFlags |= CANCEL_NEXT_UP_EVENT; 5584 } 5585 5586 /** 5587 * @hide 5588 */ 5589 public void dispatchFinishTemporaryDetach() { 5590 onFinishTemporaryDetach(); 5591 } 5592 5593 /** 5594 * Called after {@link #onStartTemporaryDetach} when the container is done 5595 * changing the view. 5596 */ 5597 public void onFinishTemporaryDetach() { 5598 } 5599 5600 /** 5601 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 5602 * for this view's window. Returns null if the view is not currently attached 5603 * to the window. Normally you will not need to use this directly, but 5604 * just use the standard high-level event callbacks like 5605 * {@link #onKeyDown(int, KeyEvent)}. 5606 */ 5607 public KeyEvent.DispatcherState getKeyDispatcherState() { 5608 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 5609 } 5610 5611 /** 5612 * Dispatch a key event before it is processed by any input method 5613 * associated with the view hierarchy. This can be used to intercept 5614 * key events in special situations before the IME consumes them; a 5615 * typical example would be handling the BACK key to update the application's 5616 * UI instead of allowing the IME to see it and close itself. 5617 * 5618 * @param event The key event to be dispatched. 5619 * @return True if the event was handled, false otherwise. 5620 */ 5621 public boolean dispatchKeyEventPreIme(KeyEvent event) { 5622 return onKeyPreIme(event.getKeyCode(), event); 5623 } 5624 5625 /** 5626 * Dispatch a key event to the next view on the focus path. This path runs 5627 * from the top of the view tree down to the currently focused view. If this 5628 * view has focus, it will dispatch to itself. Otherwise it will dispatch 5629 * the next node down the focus path. This method also fires any key 5630 * listeners. 5631 * 5632 * @param event The key event to be dispatched. 5633 * @return True if the event was handled, false otherwise. 5634 */ 5635 public boolean dispatchKeyEvent(KeyEvent event) { 5636 if (mInputEventConsistencyVerifier != null) { 5637 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 5638 } 5639 5640 // Give any attached key listener a first crack at the event. 5641 //noinspection SimplifiableIfStatement 5642 ListenerInfo li = mListenerInfo; 5643 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5644 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 5645 return true; 5646 } 5647 5648 if (event.dispatch(this, mAttachInfo != null 5649 ? mAttachInfo.mKeyDispatchState : null, this)) { 5650 return true; 5651 } 5652 5653 if (mInputEventConsistencyVerifier != null) { 5654 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5655 } 5656 return false; 5657 } 5658 5659 /** 5660 * Dispatches a key shortcut event. 5661 * 5662 * @param event The key event to be dispatched. 5663 * @return True if the event was handled by the view, false otherwise. 5664 */ 5665 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 5666 return onKeyShortcut(event.getKeyCode(), event); 5667 } 5668 5669 /** 5670 * Pass the touch screen motion event down to the target view, or this 5671 * view if it is the target. 5672 * 5673 * @param event The motion event to be dispatched. 5674 * @return True if the event was handled by the view, false otherwise. 5675 */ 5676 public boolean dispatchTouchEvent(MotionEvent event) { 5677 if (mInputEventConsistencyVerifier != null) { 5678 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 5679 } 5680 5681 if (onFilterTouchEventForSecurity(event)) { 5682 //noinspection SimplifiableIfStatement 5683 ListenerInfo li = mListenerInfo; 5684 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5685 && li.mOnTouchListener.onTouch(this, event)) { 5686 return true; 5687 } 5688 5689 if (onTouchEvent(event)) { 5690 return true; 5691 } 5692 } 5693 5694 if (mInputEventConsistencyVerifier != null) { 5695 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5696 } 5697 return false; 5698 } 5699 5700 /** 5701 * Filter the touch event to apply security policies. 5702 * 5703 * @param event The motion event to be filtered. 5704 * @return True if the event should be dispatched, false if the event should be dropped. 5705 * 5706 * @see #getFilterTouchesWhenObscured 5707 */ 5708 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 5709 //noinspection RedundantIfStatement 5710 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 5711 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 5712 // Window is obscured, drop this touch. 5713 return false; 5714 } 5715 return true; 5716 } 5717 5718 /** 5719 * Pass a trackball motion event down to the focused view. 5720 * 5721 * @param event The motion event to be dispatched. 5722 * @return True if the event was handled by the view, false otherwise. 5723 */ 5724 public boolean dispatchTrackballEvent(MotionEvent event) { 5725 if (mInputEventConsistencyVerifier != null) { 5726 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 5727 } 5728 5729 return onTrackballEvent(event); 5730 } 5731 5732 /** 5733 * Dispatch a generic motion event. 5734 * <p> 5735 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5736 * are delivered to the view under the pointer. All other generic motion events are 5737 * delivered to the focused view. Hover events are handled specially and are delivered 5738 * to {@link #onHoverEvent(MotionEvent)}. 5739 * </p> 5740 * 5741 * @param event The motion event to be dispatched. 5742 * @return True if the event was handled by the view, false otherwise. 5743 */ 5744 public boolean dispatchGenericMotionEvent(MotionEvent event) { 5745 if (mInputEventConsistencyVerifier != null) { 5746 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 5747 } 5748 5749 final int source = event.getSource(); 5750 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5751 final int action = event.getAction(); 5752 if (action == MotionEvent.ACTION_HOVER_ENTER 5753 || action == MotionEvent.ACTION_HOVER_MOVE 5754 || action == MotionEvent.ACTION_HOVER_EXIT) { 5755 if (dispatchHoverEvent(event)) { 5756 return true; 5757 } 5758 } else if (dispatchGenericPointerEvent(event)) { 5759 return true; 5760 } 5761 } else if (dispatchGenericFocusedEvent(event)) { 5762 return true; 5763 } 5764 5765 if (dispatchGenericMotionEventInternal(event)) { 5766 return true; 5767 } 5768 5769 if (mInputEventConsistencyVerifier != null) { 5770 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5771 } 5772 return false; 5773 } 5774 5775 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 5776 //noinspection SimplifiableIfStatement 5777 ListenerInfo li = mListenerInfo; 5778 if (li != null && li.mOnGenericMotionListener != null 5779 && (mViewFlags & ENABLED_MASK) == ENABLED 5780 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 5781 return true; 5782 } 5783 5784 if (onGenericMotionEvent(event)) { 5785 return true; 5786 } 5787 5788 if (mInputEventConsistencyVerifier != null) { 5789 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5790 } 5791 return false; 5792 } 5793 5794 /** 5795 * Dispatch a hover event. 5796 * <p> 5797 * Do not call this method directly. 5798 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5799 * </p> 5800 * 5801 * @param event The motion event to be dispatched. 5802 * @return True if the event was handled by the view, false otherwise. 5803 */ 5804 protected boolean dispatchHoverEvent(MotionEvent event) { 5805 //noinspection SimplifiableIfStatement 5806 ListenerInfo li = mListenerInfo; 5807 if (li != null && li.mOnHoverListener != null 5808 && (mViewFlags & ENABLED_MASK) == ENABLED 5809 && li.mOnHoverListener.onHover(this, event)) { 5810 return true; 5811 } 5812 5813 return onHoverEvent(event); 5814 } 5815 5816 /** 5817 * Returns true if the view has a child to which it has recently sent 5818 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 5819 * it does not have a hovered child, then it must be the innermost hovered view. 5820 * @hide 5821 */ 5822 protected boolean hasHoveredChild() { 5823 return false; 5824 } 5825 5826 /** 5827 * Dispatch a generic motion event to the view under the first pointer. 5828 * <p> 5829 * Do not call this method directly. 5830 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5831 * </p> 5832 * 5833 * @param event The motion event to be dispatched. 5834 * @return True if the event was handled by the view, false otherwise. 5835 */ 5836 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 5837 return false; 5838 } 5839 5840 /** 5841 * Dispatch a generic motion event to the currently focused view. 5842 * <p> 5843 * Do not call this method directly. 5844 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5845 * </p> 5846 * 5847 * @param event The motion event to be dispatched. 5848 * @return True if the event was handled by the view, false otherwise. 5849 */ 5850 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 5851 return false; 5852 } 5853 5854 /** 5855 * Dispatch a pointer event. 5856 * <p> 5857 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 5858 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 5859 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 5860 * and should not be expected to handle other pointing device features. 5861 * </p> 5862 * 5863 * @param event The motion event to be dispatched. 5864 * @return True if the event was handled by the view, false otherwise. 5865 * @hide 5866 */ 5867 public final boolean dispatchPointerEvent(MotionEvent event) { 5868 if (event.isTouchEvent()) { 5869 return dispatchTouchEvent(event); 5870 } else { 5871 return dispatchGenericMotionEvent(event); 5872 } 5873 } 5874 5875 /** 5876 * Called when the window containing this view gains or loses window focus. 5877 * ViewGroups should override to route to their children. 5878 * 5879 * @param hasFocus True if the window containing this view now has focus, 5880 * false otherwise. 5881 */ 5882 public void dispatchWindowFocusChanged(boolean hasFocus) { 5883 onWindowFocusChanged(hasFocus); 5884 } 5885 5886 /** 5887 * Called when the window containing this view gains or loses focus. Note 5888 * that this is separate from view focus: to receive key events, both 5889 * your view and its window must have focus. If a window is displayed 5890 * on top of yours that takes input focus, then your own window will lose 5891 * focus but the view focus will remain unchanged. 5892 * 5893 * @param hasWindowFocus True if the window containing this view now has 5894 * focus, false otherwise. 5895 */ 5896 public void onWindowFocusChanged(boolean hasWindowFocus) { 5897 InputMethodManager imm = InputMethodManager.peekInstance(); 5898 if (!hasWindowFocus) { 5899 if (isPressed()) { 5900 setPressed(false); 5901 } 5902 if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5903 imm.focusOut(this); 5904 } 5905 removeLongPressCallback(); 5906 removeTapCallback(); 5907 onFocusLost(); 5908 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5909 imm.focusIn(this); 5910 } 5911 refreshDrawableState(); 5912 } 5913 5914 /** 5915 * Returns true if this view is in a window that currently has window focus. 5916 * Note that this is not the same as the view itself having focus. 5917 * 5918 * @return True if this view is in a window that currently has window focus. 5919 */ 5920 public boolean hasWindowFocus() { 5921 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 5922 } 5923 5924 /** 5925 * Dispatch a view visibility change down the view hierarchy. 5926 * ViewGroups should override to route to their children. 5927 * @param changedView The view whose visibility changed. Could be 'this' or 5928 * an ancestor view. 5929 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5930 * {@link #INVISIBLE} or {@link #GONE}. 5931 */ 5932 protected void dispatchVisibilityChanged(View changedView, int visibility) { 5933 onVisibilityChanged(changedView, visibility); 5934 } 5935 5936 /** 5937 * Called when the visibility of the view or an ancestor of the view is changed. 5938 * @param changedView The view whose visibility changed. Could be 'this' or 5939 * an ancestor view. 5940 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5941 * {@link #INVISIBLE} or {@link #GONE}. 5942 */ 5943 protected void onVisibilityChanged(View changedView, int visibility) { 5944 if (visibility == VISIBLE) { 5945 if (mAttachInfo != null) { 5946 initialAwakenScrollBars(); 5947 } else { 5948 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH; 5949 } 5950 } 5951 } 5952 5953 /** 5954 * Dispatch a hint about whether this view is displayed. For instance, when 5955 * a View moves out of the screen, it might receives a display hint indicating 5956 * the view is not displayed. Applications should not <em>rely</em> on this hint 5957 * as there is no guarantee that they will receive one. 5958 * 5959 * @param hint A hint about whether or not this view is displayed: 5960 * {@link #VISIBLE} or {@link #INVISIBLE}. 5961 */ 5962 public void dispatchDisplayHint(int hint) { 5963 onDisplayHint(hint); 5964 } 5965 5966 /** 5967 * Gives this view a hint about whether is displayed or not. For instance, when 5968 * a View moves out of the screen, it might receives a display hint indicating 5969 * the view is not displayed. Applications should not <em>rely</em> on this hint 5970 * as there is no guarantee that they will receive one. 5971 * 5972 * @param hint A hint about whether or not this view is displayed: 5973 * {@link #VISIBLE} or {@link #INVISIBLE}. 5974 */ 5975 protected void onDisplayHint(int hint) { 5976 } 5977 5978 /** 5979 * Dispatch a window visibility change down the view hierarchy. 5980 * ViewGroups should override to route to their children. 5981 * 5982 * @param visibility The new visibility of the window. 5983 * 5984 * @see #onWindowVisibilityChanged(int) 5985 */ 5986 public void dispatchWindowVisibilityChanged(int visibility) { 5987 onWindowVisibilityChanged(visibility); 5988 } 5989 5990 /** 5991 * Called when the window containing has change its visibility 5992 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 5993 * that this tells you whether or not your window is being made visible 5994 * to the window manager; this does <em>not</em> tell you whether or not 5995 * your window is obscured by other windows on the screen, even if it 5996 * is itself visible. 5997 * 5998 * @param visibility The new visibility of the window. 5999 */ 6000 protected void onWindowVisibilityChanged(int visibility) { 6001 if (visibility == VISIBLE) { 6002 initialAwakenScrollBars(); 6003 } 6004 } 6005 6006 /** 6007 * Returns the current visibility of the window this view is attached to 6008 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 6009 * 6010 * @return Returns the current visibility of the view's window. 6011 */ 6012 public int getWindowVisibility() { 6013 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 6014 } 6015 6016 /** 6017 * Retrieve the overall visible display size in which the window this view is 6018 * attached to has been positioned in. This takes into account screen 6019 * decorations above the window, for both cases where the window itself 6020 * is being position inside of them or the window is being placed under 6021 * then and covered insets are used for the window to position its content 6022 * inside. In effect, this tells you the available area where content can 6023 * be placed and remain visible to users. 6024 * 6025 * <p>This function requires an IPC back to the window manager to retrieve 6026 * the requested information, so should not be used in performance critical 6027 * code like drawing. 6028 * 6029 * @param outRect Filled in with the visible display frame. If the view 6030 * is not attached to a window, this is simply the raw display size. 6031 */ 6032 public void getWindowVisibleDisplayFrame(Rect outRect) { 6033 if (mAttachInfo != null) { 6034 try { 6035 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 6036 } catch (RemoteException e) { 6037 return; 6038 } 6039 // XXX This is really broken, and probably all needs to be done 6040 // in the window manager, and we need to know more about whether 6041 // we want the area behind or in front of the IME. 6042 final Rect insets = mAttachInfo.mVisibleInsets; 6043 outRect.left += insets.left; 6044 outRect.top += insets.top; 6045 outRect.right -= insets.right; 6046 outRect.bottom -= insets.bottom; 6047 return; 6048 } 6049 Display d = WindowManagerImpl.getDefault().getDefaultDisplay(); 6050 d.getRectSize(outRect); 6051 } 6052 6053 /** 6054 * Dispatch a notification about a resource configuration change down 6055 * the view hierarchy. 6056 * ViewGroups should override to route to their children. 6057 * 6058 * @param newConfig The new resource configuration. 6059 * 6060 * @see #onConfigurationChanged(android.content.res.Configuration) 6061 */ 6062 public void dispatchConfigurationChanged(Configuration newConfig) { 6063 onConfigurationChanged(newConfig); 6064 } 6065 6066 /** 6067 * Called when the current configuration of the resources being used 6068 * by the application have changed. You can use this to decide when 6069 * to reload resources that can changed based on orientation and other 6070 * configuration characterstics. You only need to use this if you are 6071 * not relying on the normal {@link android.app.Activity} mechanism of 6072 * recreating the activity instance upon a configuration change. 6073 * 6074 * @param newConfig The new resource configuration. 6075 */ 6076 protected void onConfigurationChanged(Configuration newConfig) { 6077 } 6078 6079 /** 6080 * Private function to aggregate all per-view attributes in to the view 6081 * root. 6082 */ 6083 void dispatchCollectViewAttributes(int visibility) { 6084 performCollectViewAttributes(visibility); 6085 } 6086 6087 void performCollectViewAttributes(int visibility) { 6088 if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) { 6089 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 6090 mAttachInfo.mKeepScreenOn = true; 6091 } 6092 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility; 6093 ListenerInfo li = mListenerInfo; 6094 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 6095 mAttachInfo.mHasSystemUiListeners = true; 6096 } 6097 } 6098 } 6099 6100 void needGlobalAttributesUpdate(boolean force) { 6101 final AttachInfo ai = mAttachInfo; 6102 if (ai != null) { 6103 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 6104 || ai.mHasSystemUiListeners) { 6105 ai.mRecomputeGlobalAttributes = true; 6106 } 6107 } 6108 } 6109 6110 /** 6111 * Returns whether the device is currently in touch mode. Touch mode is entered 6112 * once the user begins interacting with the device by touch, and affects various 6113 * things like whether focus is always visible to the user. 6114 * 6115 * @return Whether the device is in touch mode. 6116 */ 6117 @ViewDebug.ExportedProperty 6118 public boolean isInTouchMode() { 6119 if (mAttachInfo != null) { 6120 return mAttachInfo.mInTouchMode; 6121 } else { 6122 return ViewRootImpl.isInTouchMode(); 6123 } 6124 } 6125 6126 /** 6127 * Returns the context the view is running in, through which it can 6128 * access the current theme, resources, etc. 6129 * 6130 * @return The view's Context. 6131 */ 6132 @ViewDebug.CapturedViewProperty 6133 public final Context getContext() { 6134 return mContext; 6135 } 6136 6137 /** 6138 * Handle a key event before it is processed by any input method 6139 * associated with the view hierarchy. This can be used to intercept 6140 * key events in special situations before the IME consumes them; a 6141 * typical example would be handling the BACK key to update the application's 6142 * UI instead of allowing the IME to see it and close itself. 6143 * 6144 * @param keyCode The value in event.getKeyCode(). 6145 * @param event Description of the key event. 6146 * @return If you handled the event, return true. If you want to allow the 6147 * event to be handled by the next receiver, return false. 6148 */ 6149 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 6150 return false; 6151 } 6152 6153 /** 6154 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 6155 * KeyEvent.Callback.onKeyDown()}: perform press of the view 6156 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 6157 * is released, if the view is enabled and clickable. 6158 * 6159 * @param keyCode A key code that represents the button pressed, from 6160 * {@link android.view.KeyEvent}. 6161 * @param event The KeyEvent object that defines the button action. 6162 */ 6163 public boolean onKeyDown(int keyCode, KeyEvent event) { 6164 boolean result = false; 6165 6166 switch (keyCode) { 6167 case KeyEvent.KEYCODE_DPAD_CENTER: 6168 case KeyEvent.KEYCODE_ENTER: { 6169 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6170 return true; 6171 } 6172 // Long clickable items don't necessarily have to be clickable 6173 if (((mViewFlags & CLICKABLE) == CLICKABLE || 6174 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 6175 (event.getRepeatCount() == 0)) { 6176 setPressed(true); 6177 checkForLongClick(0); 6178 return true; 6179 } 6180 break; 6181 } 6182 } 6183 return result; 6184 } 6185 6186 /** 6187 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 6188 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 6189 * the event). 6190 */ 6191 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 6192 return false; 6193 } 6194 6195 /** 6196 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 6197 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 6198 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 6199 * {@link KeyEvent#KEYCODE_ENTER} is released. 6200 * 6201 * @param keyCode A key code that represents the button pressed, from 6202 * {@link android.view.KeyEvent}. 6203 * @param event The KeyEvent object that defines the button action. 6204 */ 6205 public boolean onKeyUp(int keyCode, KeyEvent event) { 6206 boolean result = false; 6207 6208 switch (keyCode) { 6209 case KeyEvent.KEYCODE_DPAD_CENTER: 6210 case KeyEvent.KEYCODE_ENTER: { 6211 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6212 return true; 6213 } 6214 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 6215 setPressed(false); 6216 6217 if (!mHasPerformedLongPress) { 6218 // This is a tap, so remove the longpress check 6219 removeLongPressCallback(); 6220 6221 result = performClick(); 6222 } 6223 } 6224 break; 6225 } 6226 } 6227 return result; 6228 } 6229 6230 /** 6231 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 6232 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 6233 * the event). 6234 * 6235 * @param keyCode A key code that represents the button pressed, from 6236 * {@link android.view.KeyEvent}. 6237 * @param repeatCount The number of times the action was made. 6238 * @param event The KeyEvent object that defines the button action. 6239 */ 6240 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 6241 return false; 6242 } 6243 6244 /** 6245 * Called on the focused view when a key shortcut event is not handled. 6246 * Override this method to implement local key shortcuts for the View. 6247 * Key shortcuts can also be implemented by setting the 6248 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 6249 * 6250 * @param keyCode The value in event.getKeyCode(). 6251 * @param event Description of the key event. 6252 * @return If you handled the event, return true. If you want to allow the 6253 * event to be handled by the next receiver, return false. 6254 */ 6255 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 6256 return false; 6257 } 6258 6259 /** 6260 * Check whether the called view is a text editor, in which case it 6261 * would make sense to automatically display a soft input window for 6262 * it. Subclasses should override this if they implement 6263 * {@link #onCreateInputConnection(EditorInfo)} to return true if 6264 * a call on that method would return a non-null InputConnection, and 6265 * they are really a first-class editor that the user would normally 6266 * start typing on when the go into a window containing your view. 6267 * 6268 * <p>The default implementation always returns false. This does 6269 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 6270 * will not be called or the user can not otherwise perform edits on your 6271 * view; it is just a hint to the system that this is not the primary 6272 * purpose of this view. 6273 * 6274 * @return Returns true if this view is a text editor, else false. 6275 */ 6276 public boolean onCheckIsTextEditor() { 6277 return false; 6278 } 6279 6280 /** 6281 * Create a new InputConnection for an InputMethod to interact 6282 * with the view. The default implementation returns null, since it doesn't 6283 * support input methods. You can override this to implement such support. 6284 * This is only needed for views that take focus and text input. 6285 * 6286 * <p>When implementing this, you probably also want to implement 6287 * {@link #onCheckIsTextEditor()} to indicate you will return a 6288 * non-null InputConnection. 6289 * 6290 * @param outAttrs Fill in with attribute information about the connection. 6291 */ 6292 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 6293 return null; 6294 } 6295 6296 /** 6297 * Called by the {@link android.view.inputmethod.InputMethodManager} 6298 * when a view who is not the current 6299 * input connection target is trying to make a call on the manager. The 6300 * default implementation returns false; you can override this to return 6301 * true for certain views if you are performing InputConnection proxying 6302 * to them. 6303 * @param view The View that is making the InputMethodManager call. 6304 * @return Return true to allow the call, false to reject. 6305 */ 6306 public boolean checkInputConnectionProxy(View view) { 6307 return false; 6308 } 6309 6310 /** 6311 * Show the context menu for this view. It is not safe to hold on to the 6312 * menu after returning from this method. 6313 * 6314 * You should normally not overload this method. Overload 6315 * {@link #onCreateContextMenu(ContextMenu)} or define an 6316 * {@link OnCreateContextMenuListener} to add items to the context menu. 6317 * 6318 * @param menu The context menu to populate 6319 */ 6320 public void createContextMenu(ContextMenu menu) { 6321 ContextMenuInfo menuInfo = getContextMenuInfo(); 6322 6323 // Sets the current menu info so all items added to menu will have 6324 // my extra info set. 6325 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 6326 6327 onCreateContextMenu(menu); 6328 ListenerInfo li = mListenerInfo; 6329 if (li != null && li.mOnCreateContextMenuListener != null) { 6330 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 6331 } 6332 6333 // Clear the extra information so subsequent items that aren't mine don't 6334 // have my extra info. 6335 ((MenuBuilder)menu).setCurrentMenuInfo(null); 6336 6337 if (mParent != null) { 6338 mParent.createContextMenu(menu); 6339 } 6340 } 6341 6342 /** 6343 * Views should implement this if they have extra information to associate 6344 * with the context menu. The return result is supplied as a parameter to 6345 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 6346 * callback. 6347 * 6348 * @return Extra information about the item for which the context menu 6349 * should be shown. This information will vary across different 6350 * subclasses of View. 6351 */ 6352 protected ContextMenuInfo getContextMenuInfo() { 6353 return null; 6354 } 6355 6356 /** 6357 * Views should implement this if the view itself is going to add items to 6358 * the context menu. 6359 * 6360 * @param menu the context menu to populate 6361 */ 6362 protected void onCreateContextMenu(ContextMenu menu) { 6363 } 6364 6365 /** 6366 * Implement this method to handle trackball motion events. The 6367 * <em>relative</em> movement of the trackball since the last event 6368 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 6369 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 6370 * that a movement of 1 corresponds to the user pressing one DPAD key (so 6371 * they will often be fractional values, representing the more fine-grained 6372 * movement information available from a trackball). 6373 * 6374 * @param event The motion event. 6375 * @return True if the event was handled, false otherwise. 6376 */ 6377 public boolean onTrackballEvent(MotionEvent event) { 6378 return false; 6379 } 6380 6381 /** 6382 * Implement this method to handle generic motion events. 6383 * <p> 6384 * Generic motion events describe joystick movements, mouse hovers, track pad 6385 * touches, scroll wheel movements and other input events. The 6386 * {@link MotionEvent#getSource() source} of the motion event specifies 6387 * the class of input that was received. Implementations of this method 6388 * must examine the bits in the source before processing the event. 6389 * The following code example shows how this is done. 6390 * </p><p> 6391 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 6392 * are delivered to the view under the pointer. All other generic motion events are 6393 * delivered to the focused view. 6394 * </p> 6395 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 6396 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 6397 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 6398 * // process the joystick movement... 6399 * return true; 6400 * } 6401 * } 6402 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 6403 * switch (event.getAction()) { 6404 * case MotionEvent.ACTION_HOVER_MOVE: 6405 * // process the mouse hover movement... 6406 * return true; 6407 * case MotionEvent.ACTION_SCROLL: 6408 * // process the scroll wheel movement... 6409 * return true; 6410 * } 6411 * } 6412 * return super.onGenericMotionEvent(event); 6413 * }</pre> 6414 * 6415 * @param event The generic motion event being processed. 6416 * @return True if the event was handled, false otherwise. 6417 */ 6418 public boolean onGenericMotionEvent(MotionEvent event) { 6419 return false; 6420 } 6421 6422 /** 6423 * Implement this method to handle hover events. 6424 * <p> 6425 * This method is called whenever a pointer is hovering into, over, or out of the 6426 * bounds of a view and the view is not currently being touched. 6427 * Hover events are represented as pointer events with action 6428 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 6429 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 6430 * </p> 6431 * <ul> 6432 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 6433 * when the pointer enters the bounds of the view.</li> 6434 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 6435 * when the pointer has already entered the bounds of the view and has moved.</li> 6436 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 6437 * when the pointer has exited the bounds of the view or when the pointer is 6438 * about to go down due to a button click, tap, or similar user action that 6439 * causes the view to be touched.</li> 6440 * </ul> 6441 * <p> 6442 * The view should implement this method to return true to indicate that it is 6443 * handling the hover event, such as by changing its drawable state. 6444 * </p><p> 6445 * The default implementation calls {@link #setHovered} to update the hovered state 6446 * of the view when a hover enter or hover exit event is received, if the view 6447 * is enabled and is clickable. The default implementation also sends hover 6448 * accessibility events. 6449 * </p> 6450 * 6451 * @param event The motion event that describes the hover. 6452 * @return True if the view handled the hover event. 6453 * 6454 * @see #isHovered 6455 * @see #setHovered 6456 * @see #onHoverChanged 6457 */ 6458 public boolean onHoverEvent(MotionEvent event) { 6459 // The root view may receive hover (or touch) events that are outside the bounds of 6460 // the window. This code ensures that we only send accessibility events for 6461 // hovers that are actually within the bounds of the root view. 6462 final int action = event.getAction(); 6463 if (!mSendingHoverAccessibilityEvents) { 6464 if ((action == MotionEvent.ACTION_HOVER_ENTER 6465 || action == MotionEvent.ACTION_HOVER_MOVE) 6466 && !hasHoveredChild() 6467 && pointInView(event.getX(), event.getY())) { 6468 mSendingHoverAccessibilityEvents = true; 6469 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 6470 } 6471 } else { 6472 if (action == MotionEvent.ACTION_HOVER_EXIT 6473 || (action == MotionEvent.ACTION_HOVER_MOVE 6474 && !pointInView(event.getX(), event.getY()))) { 6475 mSendingHoverAccessibilityEvents = false; 6476 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 6477 } 6478 } 6479 6480 if (isHoverable()) { 6481 switch (action) { 6482 case MotionEvent.ACTION_HOVER_ENTER: 6483 setHovered(true); 6484 break; 6485 case MotionEvent.ACTION_HOVER_EXIT: 6486 setHovered(false); 6487 break; 6488 } 6489 6490 // Dispatch the event to onGenericMotionEvent before returning true. 6491 // This is to provide compatibility with existing applications that 6492 // handled HOVER_MOVE events in onGenericMotionEvent and that would 6493 // break because of the new default handling for hoverable views 6494 // in onHoverEvent. 6495 // Note that onGenericMotionEvent will be called by default when 6496 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 6497 dispatchGenericMotionEventInternal(event); 6498 return true; 6499 } 6500 return false; 6501 } 6502 6503 /** 6504 * Returns true if the view should handle {@link #onHoverEvent} 6505 * by calling {@link #setHovered} to change its hovered state. 6506 * 6507 * @return True if the view is hoverable. 6508 */ 6509 private boolean isHoverable() { 6510 final int viewFlags = mViewFlags; 6511 //noinspection SimplifiableIfStatement 6512 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6513 return false; 6514 } 6515 6516 return (viewFlags & CLICKABLE) == CLICKABLE 6517 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6518 } 6519 6520 /** 6521 * Returns true if the view is currently hovered. 6522 * 6523 * @return True if the view is currently hovered. 6524 * 6525 * @see #setHovered 6526 * @see #onHoverChanged 6527 */ 6528 @ViewDebug.ExportedProperty 6529 public boolean isHovered() { 6530 return (mPrivateFlags & HOVERED) != 0; 6531 } 6532 6533 /** 6534 * Sets whether the view is currently hovered. 6535 * <p> 6536 * Calling this method also changes the drawable state of the view. This 6537 * enables the view to react to hover by using different drawable resources 6538 * to change its appearance. 6539 * </p><p> 6540 * The {@link #onHoverChanged} method is called when the hovered state changes. 6541 * </p> 6542 * 6543 * @param hovered True if the view is hovered. 6544 * 6545 * @see #isHovered 6546 * @see #onHoverChanged 6547 */ 6548 public void setHovered(boolean hovered) { 6549 if (hovered) { 6550 if ((mPrivateFlags & HOVERED) == 0) { 6551 mPrivateFlags |= HOVERED; 6552 refreshDrawableState(); 6553 onHoverChanged(true); 6554 } 6555 } else { 6556 if ((mPrivateFlags & HOVERED) != 0) { 6557 mPrivateFlags &= ~HOVERED; 6558 refreshDrawableState(); 6559 onHoverChanged(false); 6560 } 6561 } 6562 } 6563 6564 /** 6565 * Implement this method to handle hover state changes. 6566 * <p> 6567 * This method is called whenever the hover state changes as a result of a 6568 * call to {@link #setHovered}. 6569 * </p> 6570 * 6571 * @param hovered The current hover state, as returned by {@link #isHovered}. 6572 * 6573 * @see #isHovered 6574 * @see #setHovered 6575 */ 6576 public void onHoverChanged(boolean hovered) { 6577 } 6578 6579 /** 6580 * Implement this method to handle touch screen motion events. 6581 * 6582 * @param event The motion event. 6583 * @return True if the event was handled, false otherwise. 6584 */ 6585 public boolean onTouchEvent(MotionEvent event) { 6586 final int viewFlags = mViewFlags; 6587 6588 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6589 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) { 6590 setPressed(false); 6591 } 6592 // A disabled view that is clickable still consumes the touch 6593 // events, it just doesn't respond to them. 6594 return (((viewFlags & CLICKABLE) == CLICKABLE || 6595 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 6596 } 6597 6598 if (mTouchDelegate != null) { 6599 if (mTouchDelegate.onTouchEvent(event)) { 6600 return true; 6601 } 6602 } 6603 6604 if (((viewFlags & CLICKABLE) == CLICKABLE || 6605 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 6606 switch (event.getAction()) { 6607 case MotionEvent.ACTION_UP: 6608 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; 6609 if ((mPrivateFlags & PRESSED) != 0 || prepressed) { 6610 // take focus if we don't have it already and we should in 6611 // touch mode. 6612 boolean focusTaken = false; 6613 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 6614 focusTaken = requestFocus(); 6615 } 6616 6617 if (prepressed) { 6618 // The button is being released before we actually 6619 // showed it as pressed. Make it show the pressed 6620 // state now (before scheduling the click) to ensure 6621 // the user sees it. 6622 setPressed(true); 6623 } 6624 6625 if (!mHasPerformedLongPress) { 6626 // This is a tap, so remove the longpress check 6627 removeLongPressCallback(); 6628 6629 // Only perform take click actions if we were in the pressed state 6630 if (!focusTaken) { 6631 // Use a Runnable and post this rather than calling 6632 // performClick directly. This lets other visual state 6633 // of the view update before click actions start. 6634 if (mPerformClick == null) { 6635 mPerformClick = new PerformClick(); 6636 } 6637 if (!post(mPerformClick)) { 6638 performClick(); 6639 } 6640 } 6641 } 6642 6643 if (mUnsetPressedState == null) { 6644 mUnsetPressedState = new UnsetPressedState(); 6645 } 6646 6647 if (prepressed) { 6648 postDelayed(mUnsetPressedState, 6649 ViewConfiguration.getPressedStateDuration()); 6650 } else if (!post(mUnsetPressedState)) { 6651 // If the post failed, unpress right now 6652 mUnsetPressedState.run(); 6653 } 6654 removeTapCallback(); 6655 } 6656 break; 6657 6658 case MotionEvent.ACTION_DOWN: 6659 mHasPerformedLongPress = false; 6660 6661 if (performButtonActionOnTouchDown(event)) { 6662 break; 6663 } 6664 6665 // Walk up the hierarchy to determine if we're inside a scrolling container. 6666 boolean isInScrollingContainer = isInScrollingContainer(); 6667 6668 // For views inside a scrolling container, delay the pressed feedback for 6669 // a short period in case this is a scroll. 6670 if (isInScrollingContainer) { 6671 mPrivateFlags |= PREPRESSED; 6672 if (mPendingCheckForTap == null) { 6673 mPendingCheckForTap = new CheckForTap(); 6674 } 6675 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 6676 } else { 6677 // Not inside a scrolling container, so show the feedback right away 6678 setPressed(true); 6679 checkForLongClick(0); 6680 } 6681 break; 6682 6683 case MotionEvent.ACTION_CANCEL: 6684 setPressed(false); 6685 removeTapCallback(); 6686 break; 6687 6688 case MotionEvent.ACTION_MOVE: 6689 final int x = (int) event.getX(); 6690 final int y = (int) event.getY(); 6691 6692 // Be lenient about moving outside of buttons 6693 if (!pointInView(x, y, mTouchSlop)) { 6694 // Outside button 6695 removeTapCallback(); 6696 if ((mPrivateFlags & PRESSED) != 0) { 6697 // Remove any future long press/tap checks 6698 removeLongPressCallback(); 6699 6700 setPressed(false); 6701 } 6702 } 6703 break; 6704 } 6705 return true; 6706 } 6707 6708 return false; 6709 } 6710 6711 /** 6712 * @hide 6713 */ 6714 public boolean isInScrollingContainer() { 6715 ViewParent p = getParent(); 6716 while (p != null && p instanceof ViewGroup) { 6717 if (((ViewGroup) p).shouldDelayChildPressedState()) { 6718 return true; 6719 } 6720 p = p.getParent(); 6721 } 6722 return false; 6723 } 6724 6725 /** 6726 * Remove the longpress detection timer. 6727 */ 6728 private void removeLongPressCallback() { 6729 if (mPendingCheckForLongPress != null) { 6730 removeCallbacks(mPendingCheckForLongPress); 6731 } 6732 } 6733 6734 /** 6735 * Remove the pending click action 6736 */ 6737 private void removePerformClickCallback() { 6738 if (mPerformClick != null) { 6739 removeCallbacks(mPerformClick); 6740 } 6741 } 6742 6743 /** 6744 * Remove the prepress detection timer. 6745 */ 6746 private void removeUnsetPressCallback() { 6747 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) { 6748 setPressed(false); 6749 removeCallbacks(mUnsetPressedState); 6750 } 6751 } 6752 6753 /** 6754 * Remove the tap detection timer. 6755 */ 6756 private void removeTapCallback() { 6757 if (mPendingCheckForTap != null) { 6758 mPrivateFlags &= ~PREPRESSED; 6759 removeCallbacks(mPendingCheckForTap); 6760 } 6761 } 6762 6763 /** 6764 * Cancels a pending long press. Your subclass can use this if you 6765 * want the context menu to come up if the user presses and holds 6766 * at the same place, but you don't want it to come up if they press 6767 * and then move around enough to cause scrolling. 6768 */ 6769 public void cancelLongPress() { 6770 removeLongPressCallback(); 6771 6772 /* 6773 * The prepressed state handled by the tap callback is a display 6774 * construct, but the tap callback will post a long press callback 6775 * less its own timeout. Remove it here. 6776 */ 6777 removeTapCallback(); 6778 } 6779 6780 /** 6781 * Remove the pending callback for sending a 6782 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 6783 */ 6784 private void removeSendViewScrolledAccessibilityEventCallback() { 6785 if (mSendViewScrolledAccessibilityEvent != null) { 6786 removeCallbacks(mSendViewScrolledAccessibilityEvent); 6787 } 6788 } 6789 6790 /** 6791 * Sets the TouchDelegate for this View. 6792 */ 6793 public void setTouchDelegate(TouchDelegate delegate) { 6794 mTouchDelegate = delegate; 6795 } 6796 6797 /** 6798 * Gets the TouchDelegate for this View. 6799 */ 6800 public TouchDelegate getTouchDelegate() { 6801 return mTouchDelegate; 6802 } 6803 6804 /** 6805 * Set flags controlling behavior of this view. 6806 * 6807 * @param flags Constant indicating the value which should be set 6808 * @param mask Constant indicating the bit range that should be changed 6809 */ 6810 void setFlags(int flags, int mask) { 6811 int old = mViewFlags; 6812 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 6813 6814 int changed = mViewFlags ^ old; 6815 if (changed == 0) { 6816 return; 6817 } 6818 int privateFlags = mPrivateFlags; 6819 6820 /* Check if the FOCUSABLE bit has changed */ 6821 if (((changed & FOCUSABLE_MASK) != 0) && 6822 ((privateFlags & HAS_BOUNDS) !=0)) { 6823 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 6824 && ((privateFlags & FOCUSED) != 0)) { 6825 /* Give up focus if we are no longer focusable */ 6826 clearFocus(); 6827 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 6828 && ((privateFlags & FOCUSED) == 0)) { 6829 /* 6830 * Tell the view system that we are now available to take focus 6831 * if no one else already has it. 6832 */ 6833 if (mParent != null) mParent.focusableViewAvailable(this); 6834 } 6835 } 6836 6837 if ((flags & VISIBILITY_MASK) == VISIBLE) { 6838 if ((changed & VISIBILITY_MASK) != 0) { 6839 /* 6840 * If this view is becoming visible, invalidate it in case it changed while 6841 * it was not visible. Marking it drawn ensures that the invalidation will 6842 * go through. 6843 */ 6844 mPrivateFlags |= DRAWN; 6845 invalidate(true); 6846 6847 needGlobalAttributesUpdate(true); 6848 6849 // a view becoming visible is worth notifying the parent 6850 // about in case nothing has focus. even if this specific view 6851 // isn't focusable, it may contain something that is, so let 6852 // the root view try to give this focus if nothing else does. 6853 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 6854 mParent.focusableViewAvailable(this); 6855 } 6856 } 6857 } 6858 6859 /* Check if the GONE bit has changed */ 6860 if ((changed & GONE) != 0) { 6861 needGlobalAttributesUpdate(false); 6862 requestLayout(); 6863 6864 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 6865 if (hasFocus()) clearFocus(); 6866 destroyDrawingCache(); 6867 if (mParent instanceof View) { 6868 // GONE views noop invalidation, so invalidate the parent 6869 ((View) mParent).invalidate(true); 6870 } 6871 // Mark the view drawn to ensure that it gets invalidated properly the next 6872 // time it is visible and gets invalidated 6873 mPrivateFlags |= DRAWN; 6874 } 6875 if (mAttachInfo != null) { 6876 mAttachInfo.mViewVisibilityChanged = true; 6877 } 6878 } 6879 6880 /* Check if the VISIBLE bit has changed */ 6881 if ((changed & INVISIBLE) != 0) { 6882 needGlobalAttributesUpdate(false); 6883 /* 6884 * If this view is becoming invisible, set the DRAWN flag so that 6885 * the next invalidate() will not be skipped. 6886 */ 6887 mPrivateFlags |= DRAWN; 6888 6889 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 6890 // root view becoming invisible shouldn't clear focus 6891 if (getRootView() != this) { 6892 clearFocus(); 6893 } 6894 } 6895 if (mAttachInfo != null) { 6896 mAttachInfo.mViewVisibilityChanged = true; 6897 } 6898 } 6899 6900 if ((changed & VISIBILITY_MASK) != 0) { 6901 if (mParent instanceof ViewGroup) { 6902 ((ViewGroup) mParent).onChildVisibilityChanged(this, 6903 (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK)); 6904 ((View) mParent).invalidate(true); 6905 } else if (mParent != null) { 6906 mParent.invalidateChild(this, null); 6907 } 6908 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6909 } 6910 6911 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 6912 destroyDrawingCache(); 6913 } 6914 6915 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 6916 destroyDrawingCache(); 6917 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6918 invalidateParentCaches(); 6919 } 6920 6921 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 6922 destroyDrawingCache(); 6923 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6924 } 6925 6926 if ((changed & DRAW_MASK) != 0) { 6927 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 6928 if (mBGDrawable != null) { 6929 mPrivateFlags &= ~SKIP_DRAW; 6930 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 6931 } else { 6932 mPrivateFlags |= SKIP_DRAW; 6933 } 6934 } else { 6935 mPrivateFlags &= ~SKIP_DRAW; 6936 } 6937 requestLayout(); 6938 invalidate(true); 6939 } 6940 6941 if ((changed & KEEP_SCREEN_ON) != 0) { 6942 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 6943 mParent.recomputeViewAttributes(this); 6944 } 6945 } 6946 } 6947 6948 /** 6949 * Change the view's z order in the tree, so it's on top of other sibling 6950 * views 6951 */ 6952 public void bringToFront() { 6953 if (mParent != null) { 6954 mParent.bringChildToFront(this); 6955 } 6956 } 6957 6958 /** 6959 * This is called in response to an internal scroll in this view (i.e., the 6960 * view scrolled its own contents). This is typically as a result of 6961 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 6962 * called. 6963 * 6964 * @param l Current horizontal scroll origin. 6965 * @param t Current vertical scroll origin. 6966 * @param oldl Previous horizontal scroll origin. 6967 * @param oldt Previous vertical scroll origin. 6968 */ 6969 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 6970 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6971 postSendViewScrolledAccessibilityEventCallback(); 6972 } 6973 6974 mBackgroundSizeChanged = true; 6975 6976 final AttachInfo ai = mAttachInfo; 6977 if (ai != null) { 6978 ai.mViewScrollChanged = true; 6979 } 6980 } 6981 6982 /** 6983 * Interface definition for a callback to be invoked when the layout bounds of a view 6984 * changes due to layout processing. 6985 */ 6986 public interface OnLayoutChangeListener { 6987 /** 6988 * Called when the focus state of a view has changed. 6989 * 6990 * @param v The view whose state has changed. 6991 * @param left The new value of the view's left property. 6992 * @param top The new value of the view's top property. 6993 * @param right The new value of the view's right property. 6994 * @param bottom The new value of the view's bottom property. 6995 * @param oldLeft The previous value of the view's left property. 6996 * @param oldTop The previous value of the view's top property. 6997 * @param oldRight The previous value of the view's right property. 6998 * @param oldBottom The previous value of the view's bottom property. 6999 */ 7000 void onLayoutChange(View v, int left, int top, int right, int bottom, 7001 int oldLeft, int oldTop, int oldRight, int oldBottom); 7002 } 7003 7004 /** 7005 * This is called during layout when the size of this view has changed. If 7006 * you were just added to the view hierarchy, you're called with the old 7007 * values of 0. 7008 * 7009 * @param w Current width of this view. 7010 * @param h Current height of this view. 7011 * @param oldw Old width of this view. 7012 * @param oldh Old height of this view. 7013 */ 7014 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 7015 } 7016 7017 /** 7018 * Called by draw to draw the child views. This may be overridden 7019 * by derived classes to gain control just before its children are drawn 7020 * (but after its own view has been drawn). 7021 * @param canvas the canvas on which to draw the view 7022 */ 7023 protected void dispatchDraw(Canvas canvas) { 7024 } 7025 7026 /** 7027 * Gets the parent of this view. Note that the parent is a 7028 * ViewParent and not necessarily a View. 7029 * 7030 * @return Parent of this view. 7031 */ 7032 public final ViewParent getParent() { 7033 return mParent; 7034 } 7035 7036 /** 7037 * Set the horizontal scrolled position of your view. This will cause a call to 7038 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7039 * invalidated. 7040 * @param value the x position to scroll to 7041 */ 7042 public void setScrollX(int value) { 7043 scrollTo(value, mScrollY); 7044 } 7045 7046 /** 7047 * Set the vertical scrolled position of your view. This will cause a call to 7048 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7049 * invalidated. 7050 * @param value the y position to scroll to 7051 */ 7052 public void setScrollY(int value) { 7053 scrollTo(mScrollX, value); 7054 } 7055 7056 /** 7057 * Return the scrolled left position of this view. This is the left edge of 7058 * the displayed part of your view. You do not need to draw any pixels 7059 * farther left, since those are outside of the frame of your view on 7060 * screen. 7061 * 7062 * @return The left edge of the displayed part of your view, in pixels. 7063 */ 7064 public final int getScrollX() { 7065 return mScrollX; 7066 } 7067 7068 /** 7069 * Return the scrolled top position of this view. This is the top edge of 7070 * the displayed part of your view. You do not need to draw any pixels above 7071 * it, since those are outside of the frame of your view on screen. 7072 * 7073 * @return The top edge of the displayed part of your view, in pixels. 7074 */ 7075 public final int getScrollY() { 7076 return mScrollY; 7077 } 7078 7079 /** 7080 * Return the width of the your view. 7081 * 7082 * @return The width of your view, in pixels. 7083 */ 7084 @ViewDebug.ExportedProperty(category = "layout") 7085 public final int getWidth() { 7086 return mRight - mLeft; 7087 } 7088 7089 /** 7090 * Return the height of your view. 7091 * 7092 * @return The height of your view, in pixels. 7093 */ 7094 @ViewDebug.ExportedProperty(category = "layout") 7095 public final int getHeight() { 7096 return mBottom - mTop; 7097 } 7098 7099 /** 7100 * Return the visible drawing bounds of your view. Fills in the output 7101 * rectangle with the values from getScrollX(), getScrollY(), 7102 * getWidth(), and getHeight(). 7103 * 7104 * @param outRect The (scrolled) drawing bounds of the view. 7105 */ 7106 public void getDrawingRect(Rect outRect) { 7107 outRect.left = mScrollX; 7108 outRect.top = mScrollY; 7109 outRect.right = mScrollX + (mRight - mLeft); 7110 outRect.bottom = mScrollY + (mBottom - mTop); 7111 } 7112 7113 /** 7114 * Like {@link #getMeasuredWidthAndState()}, but only returns the 7115 * raw width component (that is the result is masked by 7116 * {@link #MEASURED_SIZE_MASK}). 7117 * 7118 * @return The raw measured width of this view. 7119 */ 7120 public final int getMeasuredWidth() { 7121 return mMeasuredWidth & MEASURED_SIZE_MASK; 7122 } 7123 7124 /** 7125 * Return the full width measurement information for this view as computed 7126 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 7127 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 7128 * This should be used during measurement and layout calculations only. Use 7129 * {@link #getWidth()} to see how wide a view is after layout. 7130 * 7131 * @return The measured width of this view as a bit mask. 7132 */ 7133 public final int getMeasuredWidthAndState() { 7134 return mMeasuredWidth; 7135 } 7136 7137 /** 7138 * Like {@link #getMeasuredHeightAndState()}, but only returns the 7139 * raw width component (that is the result is masked by 7140 * {@link #MEASURED_SIZE_MASK}). 7141 * 7142 * @return The raw measured height of this view. 7143 */ 7144 public final int getMeasuredHeight() { 7145 return mMeasuredHeight & MEASURED_SIZE_MASK; 7146 } 7147 7148 /** 7149 * Return the full height measurement information for this view as computed 7150 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 7151 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 7152 * This should be used during measurement and layout calculations only. Use 7153 * {@link #getHeight()} to see how wide a view is after layout. 7154 * 7155 * @return The measured width of this view as a bit mask. 7156 */ 7157 public final int getMeasuredHeightAndState() { 7158 return mMeasuredHeight; 7159 } 7160 7161 /** 7162 * Return only the state bits of {@link #getMeasuredWidthAndState()} 7163 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 7164 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 7165 * and the height component is at the shifted bits 7166 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 7167 */ 7168 public final int getMeasuredState() { 7169 return (mMeasuredWidth&MEASURED_STATE_MASK) 7170 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 7171 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 7172 } 7173 7174 /** 7175 * The transform matrix of this view, which is calculated based on the current 7176 * roation, scale, and pivot properties. 7177 * 7178 * @see #getRotation() 7179 * @see #getScaleX() 7180 * @see #getScaleY() 7181 * @see #getPivotX() 7182 * @see #getPivotY() 7183 * @return The current transform matrix for the view 7184 */ 7185 public Matrix getMatrix() { 7186 if (mTransformationInfo != null) { 7187 updateMatrix(); 7188 return mTransformationInfo.mMatrix; 7189 } 7190 return Matrix.IDENTITY_MATRIX; 7191 } 7192 7193 /** 7194 * Utility function to determine if the value is far enough away from zero to be 7195 * considered non-zero. 7196 * @param value A floating point value to check for zero-ness 7197 * @return whether the passed-in value is far enough away from zero to be considered non-zero 7198 */ 7199 private static boolean nonzero(float value) { 7200 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 7201 } 7202 7203 /** 7204 * Returns true if the transform matrix is the identity matrix. 7205 * Recomputes the matrix if necessary. 7206 * 7207 * @return True if the transform matrix is the identity matrix, false otherwise. 7208 */ 7209 final boolean hasIdentityMatrix() { 7210 if (mTransformationInfo != null) { 7211 updateMatrix(); 7212 return mTransformationInfo.mMatrixIsIdentity; 7213 } 7214 return true; 7215 } 7216 7217 void ensureTransformationInfo() { 7218 if (mTransformationInfo == null) { 7219 mTransformationInfo = new TransformationInfo(); 7220 } 7221 } 7222 7223 /** 7224 * Recomputes the transform matrix if necessary. 7225 */ 7226 private void updateMatrix() { 7227 final TransformationInfo info = mTransformationInfo; 7228 if (info == null) { 7229 return; 7230 } 7231 if (info.mMatrixDirty) { 7232 // transform-related properties have changed since the last time someone 7233 // asked for the matrix; recalculate it with the current values 7234 7235 // Figure out if we need to update the pivot point 7236 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7237 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 7238 info.mPrevWidth = mRight - mLeft; 7239 info.mPrevHeight = mBottom - mTop; 7240 info.mPivotX = info.mPrevWidth / 2f; 7241 info.mPivotY = info.mPrevHeight / 2f; 7242 } 7243 } 7244 info.mMatrix.reset(); 7245 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 7246 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 7247 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 7248 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 7249 } else { 7250 if (info.mCamera == null) { 7251 info.mCamera = new Camera(); 7252 info.matrix3D = new Matrix(); 7253 } 7254 info.mCamera.save(); 7255 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 7256 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 7257 info.mCamera.getMatrix(info.matrix3D); 7258 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 7259 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 7260 info.mPivotY + info.mTranslationY); 7261 info.mMatrix.postConcat(info.matrix3D); 7262 info.mCamera.restore(); 7263 } 7264 info.mMatrixDirty = false; 7265 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 7266 info.mInverseMatrixDirty = true; 7267 } 7268 } 7269 7270 /** 7271 * Utility method to retrieve the inverse of the current mMatrix property. 7272 * We cache the matrix to avoid recalculating it when transform properties 7273 * have not changed. 7274 * 7275 * @return The inverse of the current matrix of this view. 7276 */ 7277 final Matrix getInverseMatrix() { 7278 final TransformationInfo info = mTransformationInfo; 7279 if (info != null) { 7280 updateMatrix(); 7281 if (info.mInverseMatrixDirty) { 7282 if (info.mInverseMatrix == null) { 7283 info.mInverseMatrix = new Matrix(); 7284 } 7285 info.mMatrix.invert(info.mInverseMatrix); 7286 info.mInverseMatrixDirty = false; 7287 } 7288 return info.mInverseMatrix; 7289 } 7290 return Matrix.IDENTITY_MATRIX; 7291 } 7292 7293 /** 7294 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 7295 * views are drawn) from the camera to this view. The camera's distance 7296 * affects 3D transformations, for instance rotations around the X and Y 7297 * axis. If the rotationX or rotationY properties are changed and this view is 7298 * large (more than half the size of the screen), it is recommended to always 7299 * use a camera distance that's greater than the height (X axis rotation) or 7300 * the width (Y axis rotation) of this view.</p> 7301 * 7302 * <p>The distance of the camera from the view plane can have an affect on the 7303 * perspective distortion of the view when it is rotated around the x or y axis. 7304 * For example, a large distance will result in a large viewing angle, and there 7305 * will not be much perspective distortion of the view as it rotates. A short 7306 * distance may cause much more perspective distortion upon rotation, and can 7307 * also result in some drawing artifacts if the rotated view ends up partially 7308 * behind the camera (which is why the recommendation is to use a distance at 7309 * least as far as the size of the view, if the view is to be rotated.)</p> 7310 * 7311 * <p>The distance is expressed in "depth pixels." The default distance depends 7312 * on the screen density. For instance, on a medium density display, the 7313 * default distance is 1280. On a high density display, the default distance 7314 * is 1920.</p> 7315 * 7316 * <p>If you want to specify a distance that leads to visually consistent 7317 * results across various densities, use the following formula:</p> 7318 * <pre> 7319 * float scale = context.getResources().getDisplayMetrics().density; 7320 * view.setCameraDistance(distance * scale); 7321 * </pre> 7322 * 7323 * <p>The density scale factor of a high density display is 1.5, 7324 * and 1920 = 1280 * 1.5.</p> 7325 * 7326 * @param distance The distance in "depth pixels", if negative the opposite 7327 * value is used 7328 * 7329 * @see #setRotationX(float) 7330 * @see #setRotationY(float) 7331 */ 7332 public void setCameraDistance(float distance) { 7333 invalidateParentCaches(); 7334 invalidate(false); 7335 7336 ensureTransformationInfo(); 7337 final float dpi = mResources.getDisplayMetrics().densityDpi; 7338 final TransformationInfo info = mTransformationInfo; 7339 if (info.mCamera == null) { 7340 info.mCamera = new Camera(); 7341 info.matrix3D = new Matrix(); 7342 } 7343 7344 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 7345 info.mMatrixDirty = true; 7346 7347 invalidate(false); 7348 } 7349 7350 /** 7351 * The degrees that the view is rotated around the pivot point. 7352 * 7353 * @see #setRotation(float) 7354 * @see #getPivotX() 7355 * @see #getPivotY() 7356 * 7357 * @return The degrees of rotation. 7358 */ 7359 @ViewDebug.ExportedProperty(category = "drawing") 7360 public float getRotation() { 7361 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 7362 } 7363 7364 /** 7365 * Sets the degrees that the view is rotated around the pivot point. Increasing values 7366 * result in clockwise rotation. 7367 * 7368 * @param rotation The degrees of rotation. 7369 * 7370 * @see #getRotation() 7371 * @see #getPivotX() 7372 * @see #getPivotY() 7373 * @see #setRotationX(float) 7374 * @see #setRotationY(float) 7375 * 7376 * @attr ref android.R.styleable#View_rotation 7377 */ 7378 public void setRotation(float rotation) { 7379 ensureTransformationInfo(); 7380 final TransformationInfo info = mTransformationInfo; 7381 if (info.mRotation != rotation) { 7382 invalidateParentCaches(); 7383 // Double-invalidation is necessary to capture view's old and new areas 7384 invalidate(false); 7385 info.mRotation = rotation; 7386 info.mMatrixDirty = true; 7387 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7388 invalidate(false); 7389 } 7390 } 7391 7392 /** 7393 * The degrees that the view is rotated around the vertical axis through the pivot point. 7394 * 7395 * @see #getPivotX() 7396 * @see #getPivotY() 7397 * @see #setRotationY(float) 7398 * 7399 * @return The degrees of Y rotation. 7400 */ 7401 @ViewDebug.ExportedProperty(category = "drawing") 7402 public float getRotationY() { 7403 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 7404 } 7405 7406 /** 7407 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 7408 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 7409 * down the y axis. 7410 * 7411 * When rotating large views, it is recommended to adjust the camera distance 7412 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 7413 * 7414 * @param rotationY The degrees of Y rotation. 7415 * 7416 * @see #getRotationY() 7417 * @see #getPivotX() 7418 * @see #getPivotY() 7419 * @see #setRotation(float) 7420 * @see #setRotationX(float) 7421 * @see #setCameraDistance(float) 7422 * 7423 * @attr ref android.R.styleable#View_rotationY 7424 */ 7425 public void setRotationY(float rotationY) { 7426 ensureTransformationInfo(); 7427 final TransformationInfo info = mTransformationInfo; 7428 if (info.mRotationY != rotationY) { 7429 invalidateParentCaches(); 7430 // Double-invalidation is necessary to capture view's old and new areas 7431 invalidate(false); 7432 info.mRotationY = rotationY; 7433 info.mMatrixDirty = true; 7434 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7435 invalidate(false); 7436 } 7437 } 7438 7439 /** 7440 * The degrees that the view is rotated around the horizontal axis through the pivot point. 7441 * 7442 * @see #getPivotX() 7443 * @see #getPivotY() 7444 * @see #setRotationX(float) 7445 * 7446 * @return The degrees of X rotation. 7447 */ 7448 @ViewDebug.ExportedProperty(category = "drawing") 7449 public float getRotationX() { 7450 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 7451 } 7452 7453 /** 7454 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 7455 * Increasing values result in clockwise rotation from the viewpoint of looking down the 7456 * x axis. 7457 * 7458 * When rotating large views, it is recommended to adjust the camera distance 7459 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 7460 * 7461 * @param rotationX The degrees of X rotation. 7462 * 7463 * @see #getRotationX() 7464 * @see #getPivotX() 7465 * @see #getPivotY() 7466 * @see #setRotation(float) 7467 * @see #setRotationY(float) 7468 * @see #setCameraDistance(float) 7469 * 7470 * @attr ref android.R.styleable#View_rotationX 7471 */ 7472 public void setRotationX(float rotationX) { 7473 ensureTransformationInfo(); 7474 final TransformationInfo info = mTransformationInfo; 7475 if (info.mRotationX != rotationX) { 7476 invalidateParentCaches(); 7477 // Double-invalidation is necessary to capture view's old and new areas 7478 invalidate(false); 7479 info.mRotationX = rotationX; 7480 info.mMatrixDirty = true; 7481 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7482 invalidate(false); 7483 } 7484 } 7485 7486 /** 7487 * The amount that the view is scaled in x around the pivot point, as a proportion of 7488 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 7489 * 7490 * <p>By default, this is 1.0f. 7491 * 7492 * @see #getPivotX() 7493 * @see #getPivotY() 7494 * @return The scaling factor. 7495 */ 7496 @ViewDebug.ExportedProperty(category = "drawing") 7497 public float getScaleX() { 7498 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 7499 } 7500 7501 /** 7502 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 7503 * the view's unscaled width. A value of 1 means that no scaling is applied. 7504 * 7505 * @param scaleX The scaling factor. 7506 * @see #getPivotX() 7507 * @see #getPivotY() 7508 * 7509 * @attr ref android.R.styleable#View_scaleX 7510 */ 7511 public void setScaleX(float scaleX) { 7512 ensureTransformationInfo(); 7513 final TransformationInfo info = mTransformationInfo; 7514 if (info.mScaleX != scaleX) { 7515 invalidateParentCaches(); 7516 // Double-invalidation is necessary to capture view's old and new areas 7517 invalidate(false); 7518 info.mScaleX = scaleX; 7519 info.mMatrixDirty = true; 7520 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7521 invalidate(false); 7522 } 7523 } 7524 7525 /** 7526 * The amount that the view is scaled in y around the pivot point, as a proportion of 7527 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 7528 * 7529 * <p>By default, this is 1.0f. 7530 * 7531 * @see #getPivotX() 7532 * @see #getPivotY() 7533 * @return The scaling factor. 7534 */ 7535 @ViewDebug.ExportedProperty(category = "drawing") 7536 public float getScaleY() { 7537 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 7538 } 7539 7540 /** 7541 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 7542 * the view's unscaled width. A value of 1 means that no scaling is applied. 7543 * 7544 * @param scaleY The scaling factor. 7545 * @see #getPivotX() 7546 * @see #getPivotY() 7547 * 7548 * @attr ref android.R.styleable#View_scaleY 7549 */ 7550 public void setScaleY(float scaleY) { 7551 ensureTransformationInfo(); 7552 final TransformationInfo info = mTransformationInfo; 7553 if (info.mScaleY != scaleY) { 7554 invalidateParentCaches(); 7555 // Double-invalidation is necessary to capture view's old and new areas 7556 invalidate(false); 7557 info.mScaleY = scaleY; 7558 info.mMatrixDirty = true; 7559 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7560 invalidate(false); 7561 } 7562 } 7563 7564 /** 7565 * The x location of the point around which the view is {@link #setRotation(float) rotated} 7566 * and {@link #setScaleX(float) scaled}. 7567 * 7568 * @see #getRotation() 7569 * @see #getScaleX() 7570 * @see #getScaleY() 7571 * @see #getPivotY() 7572 * @return The x location of the pivot point. 7573 */ 7574 @ViewDebug.ExportedProperty(category = "drawing") 7575 public float getPivotX() { 7576 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 7577 } 7578 7579 /** 7580 * Sets the x location of the point around which the view is 7581 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 7582 * By default, the pivot point is centered on the object. 7583 * Setting this property disables this behavior and causes the view to use only the 7584 * explicitly set pivotX and pivotY values. 7585 * 7586 * @param pivotX The x location of the pivot point. 7587 * @see #getRotation() 7588 * @see #getScaleX() 7589 * @see #getScaleY() 7590 * @see #getPivotY() 7591 * 7592 * @attr ref android.R.styleable#View_transformPivotX 7593 */ 7594 public void setPivotX(float pivotX) { 7595 ensureTransformationInfo(); 7596 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7597 final TransformationInfo info = mTransformationInfo; 7598 if (info.mPivotX != pivotX) { 7599 invalidateParentCaches(); 7600 // Double-invalidation is necessary to capture view's old and new areas 7601 invalidate(false); 7602 info.mPivotX = pivotX; 7603 info.mMatrixDirty = true; 7604 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7605 invalidate(false); 7606 } 7607 } 7608 7609 /** 7610 * The y location of the point around which the view is {@link #setRotation(float) rotated} 7611 * and {@link #setScaleY(float) scaled}. 7612 * 7613 * @see #getRotation() 7614 * @see #getScaleX() 7615 * @see #getScaleY() 7616 * @see #getPivotY() 7617 * @return The y location of the pivot point. 7618 */ 7619 @ViewDebug.ExportedProperty(category = "drawing") 7620 public float getPivotY() { 7621 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 7622 } 7623 7624 /** 7625 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 7626 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 7627 * Setting this property disables this behavior and causes the view to use only the 7628 * explicitly set pivotX and pivotY values. 7629 * 7630 * @param pivotY The y location of the pivot point. 7631 * @see #getRotation() 7632 * @see #getScaleX() 7633 * @see #getScaleY() 7634 * @see #getPivotY() 7635 * 7636 * @attr ref android.R.styleable#View_transformPivotY 7637 */ 7638 public void setPivotY(float pivotY) { 7639 ensureTransformationInfo(); 7640 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7641 final TransformationInfo info = mTransformationInfo; 7642 if (info.mPivotY != pivotY) { 7643 invalidateParentCaches(); 7644 // Double-invalidation is necessary to capture view's old and new areas 7645 invalidate(false); 7646 info.mPivotY = pivotY; 7647 info.mMatrixDirty = true; 7648 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7649 invalidate(false); 7650 } 7651 } 7652 7653 /** 7654 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 7655 * completely transparent and 1 means the view is completely opaque. 7656 * 7657 * <p>By default this is 1.0f. 7658 * @return The opacity of the view. 7659 */ 7660 @ViewDebug.ExportedProperty(category = "drawing") 7661 public float getAlpha() { 7662 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 7663 } 7664 7665 /** 7666 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 7667 * completely transparent and 1 means the view is completely opaque.</p> 7668 * 7669 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 7670 * responsible for applying the opacity itself. Otherwise, calling this method is 7671 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 7672 * setting a hardware layer.</p> 7673 * 7674 * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have 7675 * performance implications. It is generally best to use the alpha property sparingly and 7676 * transiently, as in the case of fading animations.</p> 7677 * 7678 * @param alpha The opacity of the view. 7679 * 7680 * @see #setLayerType(int, android.graphics.Paint) 7681 * 7682 * @attr ref android.R.styleable#View_alpha 7683 */ 7684 public void setAlpha(float alpha) { 7685 ensureTransformationInfo(); 7686 if (mTransformationInfo.mAlpha != alpha) { 7687 mTransformationInfo.mAlpha = alpha; 7688 invalidateParentCaches(); 7689 if (onSetAlpha((int) (alpha * 255))) { 7690 mPrivateFlags |= ALPHA_SET; 7691 // subclass is handling alpha - don't optimize rendering cache invalidation 7692 invalidate(true); 7693 } else { 7694 mPrivateFlags &= ~ALPHA_SET; 7695 invalidate(false); 7696 } 7697 } 7698 } 7699 7700 /** 7701 * Faster version of setAlpha() which performs the same steps except there are 7702 * no calls to invalidate(). The caller of this function should perform proper invalidation 7703 * on the parent and this object. The return value indicates whether the subclass handles 7704 * alpha (the return value for onSetAlpha()). 7705 * 7706 * @param alpha The new value for the alpha property 7707 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 7708 * the new value for the alpha property is different from the old value 7709 */ 7710 boolean setAlphaNoInvalidation(float alpha) { 7711 ensureTransformationInfo(); 7712 if (mTransformationInfo.mAlpha != alpha) { 7713 mTransformationInfo.mAlpha = alpha; 7714 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 7715 if (subclassHandlesAlpha) { 7716 mPrivateFlags |= ALPHA_SET; 7717 return true; 7718 } else { 7719 mPrivateFlags &= ~ALPHA_SET; 7720 } 7721 } 7722 return false; 7723 } 7724 7725 /** 7726 * Top position of this view relative to its parent. 7727 * 7728 * @return The top of this view, in pixels. 7729 */ 7730 @ViewDebug.CapturedViewProperty 7731 public final int getTop() { 7732 return mTop; 7733 } 7734 7735 /** 7736 * Sets the top position of this view relative to its parent. This method is meant to be called 7737 * by the layout system and should not generally be called otherwise, because the property 7738 * may be changed at any time by the layout. 7739 * 7740 * @param top The top of this view, in pixels. 7741 */ 7742 public final void setTop(int top) { 7743 if (top != mTop) { 7744 updateMatrix(); 7745 final boolean matrixIsIdentity = mTransformationInfo == null 7746 || mTransformationInfo.mMatrixIsIdentity; 7747 if (matrixIsIdentity) { 7748 if (mAttachInfo != null) { 7749 int minTop; 7750 int yLoc; 7751 if (top < mTop) { 7752 minTop = top; 7753 yLoc = top - mTop; 7754 } else { 7755 minTop = mTop; 7756 yLoc = 0; 7757 } 7758 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 7759 } 7760 } else { 7761 // Double-invalidation is necessary to capture view's old and new areas 7762 invalidate(true); 7763 } 7764 7765 int width = mRight - mLeft; 7766 int oldHeight = mBottom - mTop; 7767 7768 mTop = top; 7769 7770 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7771 7772 if (!matrixIsIdentity) { 7773 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7774 // A change in dimension means an auto-centered pivot point changes, too 7775 mTransformationInfo.mMatrixDirty = true; 7776 } 7777 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7778 invalidate(true); 7779 } 7780 mBackgroundSizeChanged = true; 7781 invalidateParentIfNeeded(); 7782 } 7783 } 7784 7785 /** 7786 * Bottom position of this view relative to its parent. 7787 * 7788 * @return The bottom of this view, in pixels. 7789 */ 7790 @ViewDebug.CapturedViewProperty 7791 public final int getBottom() { 7792 return mBottom; 7793 } 7794 7795 /** 7796 * True if this view has changed since the last time being drawn. 7797 * 7798 * @return The dirty state of this view. 7799 */ 7800 public boolean isDirty() { 7801 return (mPrivateFlags & DIRTY_MASK) != 0; 7802 } 7803 7804 /** 7805 * Sets the bottom position of this view relative to its parent. This method is meant to be 7806 * called by the layout system and should not generally be called otherwise, because the 7807 * property may be changed at any time by the layout. 7808 * 7809 * @param bottom The bottom of this view, in pixels. 7810 */ 7811 public final void setBottom(int bottom) { 7812 if (bottom != mBottom) { 7813 updateMatrix(); 7814 final boolean matrixIsIdentity = mTransformationInfo == null 7815 || mTransformationInfo.mMatrixIsIdentity; 7816 if (matrixIsIdentity) { 7817 if (mAttachInfo != null) { 7818 int maxBottom; 7819 if (bottom < mBottom) { 7820 maxBottom = mBottom; 7821 } else { 7822 maxBottom = bottom; 7823 } 7824 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 7825 } 7826 } else { 7827 // Double-invalidation is necessary to capture view's old and new areas 7828 invalidate(true); 7829 } 7830 7831 int width = mRight - mLeft; 7832 int oldHeight = mBottom - mTop; 7833 7834 mBottom = bottom; 7835 7836 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7837 7838 if (!matrixIsIdentity) { 7839 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7840 // A change in dimension means an auto-centered pivot point changes, too 7841 mTransformationInfo.mMatrixDirty = true; 7842 } 7843 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7844 invalidate(true); 7845 } 7846 mBackgroundSizeChanged = true; 7847 invalidateParentIfNeeded(); 7848 } 7849 } 7850 7851 /** 7852 * Left position of this view relative to its parent. 7853 * 7854 * @return The left edge of this view, in pixels. 7855 */ 7856 @ViewDebug.CapturedViewProperty 7857 public final int getLeft() { 7858 return mLeft; 7859 } 7860 7861 /** 7862 * Sets the left position of this view relative to its parent. This method is meant to be called 7863 * by the layout system and should not generally be called otherwise, because the property 7864 * may be changed at any time by the layout. 7865 * 7866 * @param left The bottom of this view, in pixels. 7867 */ 7868 public final void setLeft(int left) { 7869 if (left != mLeft) { 7870 updateMatrix(); 7871 final boolean matrixIsIdentity = mTransformationInfo == null 7872 || mTransformationInfo.mMatrixIsIdentity; 7873 if (matrixIsIdentity) { 7874 if (mAttachInfo != null) { 7875 int minLeft; 7876 int xLoc; 7877 if (left < mLeft) { 7878 minLeft = left; 7879 xLoc = left - mLeft; 7880 } else { 7881 minLeft = mLeft; 7882 xLoc = 0; 7883 } 7884 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 7885 } 7886 } else { 7887 // Double-invalidation is necessary to capture view's old and new areas 7888 invalidate(true); 7889 } 7890 7891 int oldWidth = mRight - mLeft; 7892 int height = mBottom - mTop; 7893 7894 mLeft = left; 7895 7896 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7897 7898 if (!matrixIsIdentity) { 7899 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7900 // A change in dimension means an auto-centered pivot point changes, too 7901 mTransformationInfo.mMatrixDirty = true; 7902 } 7903 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7904 invalidate(true); 7905 } 7906 mBackgroundSizeChanged = true; 7907 invalidateParentIfNeeded(); 7908 } 7909 } 7910 7911 /** 7912 * Right position of this view relative to its parent. 7913 * 7914 * @return The right edge of this view, in pixels. 7915 */ 7916 @ViewDebug.CapturedViewProperty 7917 public final int getRight() { 7918 return mRight; 7919 } 7920 7921 /** 7922 * Sets the right position of this view relative to its parent. This method is meant to be called 7923 * by the layout system and should not generally be called otherwise, because the property 7924 * may be changed at any time by the layout. 7925 * 7926 * @param right The bottom of this view, in pixels. 7927 */ 7928 public final void setRight(int right) { 7929 if (right != mRight) { 7930 updateMatrix(); 7931 final boolean matrixIsIdentity = mTransformationInfo == null 7932 || mTransformationInfo.mMatrixIsIdentity; 7933 if (matrixIsIdentity) { 7934 if (mAttachInfo != null) { 7935 int maxRight; 7936 if (right < mRight) { 7937 maxRight = mRight; 7938 } else { 7939 maxRight = right; 7940 } 7941 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 7942 } 7943 } else { 7944 // Double-invalidation is necessary to capture view's old and new areas 7945 invalidate(true); 7946 } 7947 7948 int oldWidth = mRight - mLeft; 7949 int height = mBottom - mTop; 7950 7951 mRight = right; 7952 7953 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7954 7955 if (!matrixIsIdentity) { 7956 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7957 // A change in dimension means an auto-centered pivot point changes, too 7958 mTransformationInfo.mMatrixDirty = true; 7959 } 7960 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7961 invalidate(true); 7962 } 7963 mBackgroundSizeChanged = true; 7964 invalidateParentIfNeeded(); 7965 } 7966 } 7967 7968 /** 7969 * The visual x position of this view, in pixels. This is equivalent to the 7970 * {@link #setTranslationX(float) translationX} property plus the current 7971 * {@link #getLeft() left} property. 7972 * 7973 * @return The visual x position of this view, in pixels. 7974 */ 7975 @ViewDebug.ExportedProperty(category = "drawing") 7976 public float getX() { 7977 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 7978 } 7979 7980 /** 7981 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 7982 * {@link #setTranslationX(float) translationX} property to be the difference between 7983 * the x value passed in and the current {@link #getLeft() left} property. 7984 * 7985 * @param x The visual x position of this view, in pixels. 7986 */ 7987 public void setX(float x) { 7988 setTranslationX(x - mLeft); 7989 } 7990 7991 /** 7992 * The visual y position of this view, in pixels. This is equivalent to the 7993 * {@link #setTranslationY(float) translationY} property plus the current 7994 * {@link #getTop() top} property. 7995 * 7996 * @return The visual y position of this view, in pixels. 7997 */ 7998 @ViewDebug.ExportedProperty(category = "drawing") 7999 public float getY() { 8000 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 8001 } 8002 8003 /** 8004 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 8005 * {@link #setTranslationY(float) translationY} property to be the difference between 8006 * the y value passed in and the current {@link #getTop() top} property. 8007 * 8008 * @param y The visual y position of this view, in pixels. 8009 */ 8010 public void setY(float y) { 8011 setTranslationY(y - mTop); 8012 } 8013 8014 8015 /** 8016 * The horizontal location of this view relative to its {@link #getLeft() left} position. 8017 * This position is post-layout, in addition to wherever the object's 8018 * layout placed it. 8019 * 8020 * @return The horizontal position of this view relative to its left position, in pixels. 8021 */ 8022 @ViewDebug.ExportedProperty(category = "drawing") 8023 public float getTranslationX() { 8024 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 8025 } 8026 8027 /** 8028 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 8029 * This effectively positions the object post-layout, in addition to wherever the object's 8030 * layout placed it. 8031 * 8032 * @param translationX The horizontal position of this view relative to its left position, 8033 * in pixels. 8034 * 8035 * @attr ref android.R.styleable#View_translationX 8036 */ 8037 public void setTranslationX(float translationX) { 8038 ensureTransformationInfo(); 8039 final TransformationInfo info = mTransformationInfo; 8040 if (info.mTranslationX != translationX) { 8041 invalidateParentCaches(); 8042 // Double-invalidation is necessary to capture view's old and new areas 8043 invalidate(false); 8044 info.mTranslationX = translationX; 8045 info.mMatrixDirty = true; 8046 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8047 invalidate(false); 8048 } 8049 } 8050 8051 /** 8052 * The horizontal location of this view relative to its {@link #getTop() top} position. 8053 * This position is post-layout, in addition to wherever the object's 8054 * layout placed it. 8055 * 8056 * @return The vertical position of this view relative to its top position, 8057 * in pixels. 8058 */ 8059 @ViewDebug.ExportedProperty(category = "drawing") 8060 public float getTranslationY() { 8061 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 8062 } 8063 8064 /** 8065 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 8066 * This effectively positions the object post-layout, in addition to wherever the object's 8067 * layout placed it. 8068 * 8069 * @param translationY The vertical position of this view relative to its top position, 8070 * in pixels. 8071 * 8072 * @attr ref android.R.styleable#View_translationY 8073 */ 8074 public void setTranslationY(float translationY) { 8075 ensureTransformationInfo(); 8076 final TransformationInfo info = mTransformationInfo; 8077 if (info.mTranslationY != translationY) { 8078 invalidateParentCaches(); 8079 // Double-invalidation is necessary to capture view's old and new areas 8080 invalidate(false); 8081 info.mTranslationY = translationY; 8082 info.mMatrixDirty = true; 8083 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8084 invalidate(false); 8085 } 8086 } 8087 8088 /** 8089 * Hit rectangle in parent's coordinates 8090 * 8091 * @param outRect The hit rectangle of the view. 8092 */ 8093 public void getHitRect(Rect outRect) { 8094 updateMatrix(); 8095 final TransformationInfo info = mTransformationInfo; 8096 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 8097 outRect.set(mLeft, mTop, mRight, mBottom); 8098 } else { 8099 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 8100 tmpRect.set(-info.mPivotX, -info.mPivotY, 8101 getWidth() - info.mPivotX, getHeight() - info.mPivotY); 8102 info.mMatrix.mapRect(tmpRect); 8103 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 8104 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 8105 } 8106 } 8107 8108 /** 8109 * Determines whether the given point, in local coordinates is inside the view. 8110 */ 8111 /*package*/ final boolean pointInView(float localX, float localY) { 8112 return localX >= 0 && localX < (mRight - mLeft) 8113 && localY >= 0 && localY < (mBottom - mTop); 8114 } 8115 8116 /** 8117 * Utility method to determine whether the given point, in local coordinates, 8118 * is inside the view, where the area of the view is expanded by the slop factor. 8119 * This method is called while processing touch-move events to determine if the event 8120 * is still within the view. 8121 */ 8122 private boolean pointInView(float localX, float localY, float slop) { 8123 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 8124 localY < ((mBottom - mTop) + slop); 8125 } 8126 8127 /** 8128 * When a view has focus and the user navigates away from it, the next view is searched for 8129 * starting from the rectangle filled in by this method. 8130 * 8131 * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)}) 8132 * of the view. However, if your view maintains some idea of internal selection, 8133 * such as a cursor, or a selected row or column, you should override this method and 8134 * fill in a more specific rectangle. 8135 * 8136 * @param r The rectangle to fill in, in this view's coordinates. 8137 */ 8138 public void getFocusedRect(Rect r) { 8139 getDrawingRect(r); 8140 } 8141 8142 /** 8143 * If some part of this view is not clipped by any of its parents, then 8144 * return that area in r in global (root) coordinates. To convert r to local 8145 * coordinates (without taking possible View rotations into account), offset 8146 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 8147 * If the view is completely clipped or translated out, return false. 8148 * 8149 * @param r If true is returned, r holds the global coordinates of the 8150 * visible portion of this view. 8151 * @param globalOffset If true is returned, globalOffset holds the dx,dy 8152 * between this view and its root. globalOffet may be null. 8153 * @return true if r is non-empty (i.e. part of the view is visible at the 8154 * root level. 8155 */ 8156 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 8157 int width = mRight - mLeft; 8158 int height = mBottom - mTop; 8159 if (width > 0 && height > 0) { 8160 r.set(0, 0, width, height); 8161 if (globalOffset != null) { 8162 globalOffset.set(-mScrollX, -mScrollY); 8163 } 8164 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 8165 } 8166 return false; 8167 } 8168 8169 public final boolean getGlobalVisibleRect(Rect r) { 8170 return getGlobalVisibleRect(r, null); 8171 } 8172 8173 public final boolean getLocalVisibleRect(Rect r) { 8174 Point offset = new Point(); 8175 if (getGlobalVisibleRect(r, offset)) { 8176 r.offset(-offset.x, -offset.y); // make r local 8177 return true; 8178 } 8179 return false; 8180 } 8181 8182 /** 8183 * Offset this view's vertical location by the specified number of pixels. 8184 * 8185 * @param offset the number of pixels to offset the view by 8186 */ 8187 public void offsetTopAndBottom(int offset) { 8188 if (offset != 0) { 8189 updateMatrix(); 8190 final boolean matrixIsIdentity = mTransformationInfo == null 8191 || mTransformationInfo.mMatrixIsIdentity; 8192 if (matrixIsIdentity) { 8193 final ViewParent p = mParent; 8194 if (p != null && mAttachInfo != null) { 8195 final Rect r = mAttachInfo.mTmpInvalRect; 8196 int minTop; 8197 int maxBottom; 8198 int yLoc; 8199 if (offset < 0) { 8200 minTop = mTop + offset; 8201 maxBottom = mBottom; 8202 yLoc = offset; 8203 } else { 8204 minTop = mTop; 8205 maxBottom = mBottom + offset; 8206 yLoc = 0; 8207 } 8208 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 8209 p.invalidateChild(this, r); 8210 } 8211 } else { 8212 invalidate(false); 8213 } 8214 8215 mTop += offset; 8216 mBottom += offset; 8217 8218 if (!matrixIsIdentity) { 8219 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8220 invalidate(false); 8221 } 8222 invalidateParentIfNeeded(); 8223 } 8224 } 8225 8226 /** 8227 * Offset this view's horizontal location by the specified amount of pixels. 8228 * 8229 * @param offset the numer of pixels to offset the view by 8230 */ 8231 public void offsetLeftAndRight(int offset) { 8232 if (offset != 0) { 8233 updateMatrix(); 8234 final boolean matrixIsIdentity = mTransformationInfo == null 8235 || mTransformationInfo.mMatrixIsIdentity; 8236 if (matrixIsIdentity) { 8237 final ViewParent p = mParent; 8238 if (p != null && mAttachInfo != null) { 8239 final Rect r = mAttachInfo.mTmpInvalRect; 8240 int minLeft; 8241 int maxRight; 8242 if (offset < 0) { 8243 minLeft = mLeft + offset; 8244 maxRight = mRight; 8245 } else { 8246 minLeft = mLeft; 8247 maxRight = mRight + offset; 8248 } 8249 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 8250 p.invalidateChild(this, r); 8251 } 8252 } else { 8253 invalidate(false); 8254 } 8255 8256 mLeft += offset; 8257 mRight += offset; 8258 8259 if (!matrixIsIdentity) { 8260 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8261 invalidate(false); 8262 } 8263 invalidateParentIfNeeded(); 8264 } 8265 } 8266 8267 /** 8268 * Get the LayoutParams associated with this view. All views should have 8269 * layout parameters. These supply parameters to the <i>parent</i> of this 8270 * view specifying how it should be arranged. There are many subclasses of 8271 * ViewGroup.LayoutParams, and these correspond to the different subclasses 8272 * of ViewGroup that are responsible for arranging their children. 8273 * 8274 * This method may return null if this View is not attached to a parent 8275 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 8276 * was not invoked successfully. When a View is attached to a parent 8277 * ViewGroup, this method must not return null. 8278 * 8279 * @return The LayoutParams associated with this view, or null if no 8280 * parameters have been set yet 8281 */ 8282 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 8283 public ViewGroup.LayoutParams getLayoutParams() { 8284 return mLayoutParams; 8285 } 8286 8287 /** 8288 * Set the layout parameters associated with this view. These supply 8289 * parameters to the <i>parent</i> of this view specifying how it should be 8290 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 8291 * correspond to the different subclasses of ViewGroup that are responsible 8292 * for arranging their children. 8293 * 8294 * @param params The layout parameters for this view, cannot be null 8295 */ 8296 public void setLayoutParams(ViewGroup.LayoutParams params) { 8297 if (params == null) { 8298 throw new NullPointerException("Layout parameters cannot be null"); 8299 } 8300 mLayoutParams = params; 8301 if (mParent instanceof ViewGroup) { 8302 ((ViewGroup) mParent).onSetLayoutParams(this, params); 8303 } 8304 requestLayout(); 8305 } 8306 8307 /** 8308 * Set the scrolled position of your view. This will cause a call to 8309 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8310 * invalidated. 8311 * @param x the x position to scroll to 8312 * @param y the y position to scroll to 8313 */ 8314 public void scrollTo(int x, int y) { 8315 if (mScrollX != x || mScrollY != y) { 8316 int oldX = mScrollX; 8317 int oldY = mScrollY; 8318 mScrollX = x; 8319 mScrollY = y; 8320 invalidateParentCaches(); 8321 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 8322 if (!awakenScrollBars()) { 8323 invalidate(true); 8324 } 8325 } 8326 } 8327 8328 /** 8329 * Move the scrolled position of your view. This will cause a call to 8330 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8331 * invalidated. 8332 * @param x the amount of pixels to scroll by horizontally 8333 * @param y the amount of pixels to scroll by vertically 8334 */ 8335 public void scrollBy(int x, int y) { 8336 scrollTo(mScrollX + x, mScrollY + y); 8337 } 8338 8339 /** 8340 * <p>Trigger the scrollbars to draw. When invoked this method starts an 8341 * animation to fade the scrollbars out after a default delay. If a subclass 8342 * provides animated scrolling, the start delay should equal the duration 8343 * of the scrolling animation.</p> 8344 * 8345 * <p>The animation starts only if at least one of the scrollbars is 8346 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 8347 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8348 * this method returns true, and false otherwise. If the animation is 8349 * started, this method calls {@link #invalidate()}; in that case the 8350 * caller should not call {@link #invalidate()}.</p> 8351 * 8352 * <p>This method should be invoked every time a subclass directly updates 8353 * the scroll parameters.</p> 8354 * 8355 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 8356 * and {@link #scrollTo(int, int)}.</p> 8357 * 8358 * @return true if the animation is played, false otherwise 8359 * 8360 * @see #awakenScrollBars(int) 8361 * @see #scrollBy(int, int) 8362 * @see #scrollTo(int, int) 8363 * @see #isHorizontalScrollBarEnabled() 8364 * @see #isVerticalScrollBarEnabled() 8365 * @see #setHorizontalScrollBarEnabled(boolean) 8366 * @see #setVerticalScrollBarEnabled(boolean) 8367 */ 8368 protected boolean awakenScrollBars() { 8369 return mScrollCache != null && 8370 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 8371 } 8372 8373 /** 8374 * Trigger the scrollbars to draw. 8375 * This method differs from awakenScrollBars() only in its default duration. 8376 * initialAwakenScrollBars() will show the scroll bars for longer than 8377 * usual to give the user more of a chance to notice them. 8378 * 8379 * @return true if the animation is played, false otherwise. 8380 */ 8381 private boolean initialAwakenScrollBars() { 8382 return mScrollCache != null && 8383 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 8384 } 8385 8386 /** 8387 * <p> 8388 * Trigger the scrollbars to draw. When invoked this method starts an 8389 * animation to fade the scrollbars out after a fixed delay. If a subclass 8390 * provides animated scrolling, the start delay should equal the duration of 8391 * the scrolling animation. 8392 * </p> 8393 * 8394 * <p> 8395 * The animation starts only if at least one of the scrollbars is enabled, 8396 * as specified by {@link #isHorizontalScrollBarEnabled()} and 8397 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8398 * this method returns true, and false otherwise. If the animation is 8399 * started, this method calls {@link #invalidate()}; in that case the caller 8400 * should not call {@link #invalidate()}. 8401 * </p> 8402 * 8403 * <p> 8404 * This method should be invoked everytime a subclass directly updates the 8405 * scroll parameters. 8406 * </p> 8407 * 8408 * @param startDelay the delay, in milliseconds, after which the animation 8409 * should start; when the delay is 0, the animation starts 8410 * immediately 8411 * @return true if the animation is played, false otherwise 8412 * 8413 * @see #scrollBy(int, int) 8414 * @see #scrollTo(int, int) 8415 * @see #isHorizontalScrollBarEnabled() 8416 * @see #isVerticalScrollBarEnabled() 8417 * @see #setHorizontalScrollBarEnabled(boolean) 8418 * @see #setVerticalScrollBarEnabled(boolean) 8419 */ 8420 protected boolean awakenScrollBars(int startDelay) { 8421 return awakenScrollBars(startDelay, true); 8422 } 8423 8424 /** 8425 * <p> 8426 * Trigger the scrollbars to draw. When invoked this method starts an 8427 * animation to fade the scrollbars out after a fixed delay. If a subclass 8428 * provides animated scrolling, the start delay should equal the duration of 8429 * the scrolling animation. 8430 * </p> 8431 * 8432 * <p> 8433 * The animation starts only if at least one of the scrollbars is enabled, 8434 * as specified by {@link #isHorizontalScrollBarEnabled()} and 8435 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8436 * this method returns true, and false otherwise. If the animation is 8437 * started, this method calls {@link #invalidate()} if the invalidate parameter 8438 * is set to true; in that case the caller 8439 * should not call {@link #invalidate()}. 8440 * </p> 8441 * 8442 * <p> 8443 * This method should be invoked everytime a subclass directly updates the 8444 * scroll parameters. 8445 * </p> 8446 * 8447 * @param startDelay the delay, in milliseconds, after which the animation 8448 * should start; when the delay is 0, the animation starts 8449 * immediately 8450 * 8451 * @param invalidate Wheter this method should call invalidate 8452 * 8453 * @return true if the animation is played, false otherwise 8454 * 8455 * @see #scrollBy(int, int) 8456 * @see #scrollTo(int, int) 8457 * @see #isHorizontalScrollBarEnabled() 8458 * @see #isVerticalScrollBarEnabled() 8459 * @see #setHorizontalScrollBarEnabled(boolean) 8460 * @see #setVerticalScrollBarEnabled(boolean) 8461 */ 8462 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 8463 final ScrollabilityCache scrollCache = mScrollCache; 8464 8465 if (scrollCache == null || !scrollCache.fadeScrollBars) { 8466 return false; 8467 } 8468 8469 if (scrollCache.scrollBar == null) { 8470 scrollCache.scrollBar = new ScrollBarDrawable(); 8471 } 8472 8473 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 8474 8475 if (invalidate) { 8476 // Invalidate to show the scrollbars 8477 invalidate(true); 8478 } 8479 8480 if (scrollCache.state == ScrollabilityCache.OFF) { 8481 // FIXME: this is copied from WindowManagerService. 8482 // We should get this value from the system when it 8483 // is possible to do so. 8484 final int KEY_REPEAT_FIRST_DELAY = 750; 8485 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 8486 } 8487 8488 // Tell mScrollCache when we should start fading. This may 8489 // extend the fade start time if one was already scheduled 8490 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 8491 scrollCache.fadeStartTime = fadeStartTime; 8492 scrollCache.state = ScrollabilityCache.ON; 8493 8494 // Schedule our fader to run, unscheduling any old ones first 8495 if (mAttachInfo != null) { 8496 mAttachInfo.mHandler.removeCallbacks(scrollCache); 8497 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 8498 } 8499 8500 return true; 8501 } 8502 8503 return false; 8504 } 8505 8506 /** 8507 * Do not invalidate views which are not visible and which are not running an animation. They 8508 * will not get drawn and they should not set dirty flags as if they will be drawn 8509 */ 8510 private boolean skipInvalidate() { 8511 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 8512 (!(mParent instanceof ViewGroup) || 8513 !((ViewGroup) mParent).isViewTransitioning(this)); 8514 } 8515 /** 8516 * Mark the area defined by dirty as needing to be drawn. If the view is 8517 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 8518 * in the future. This must be called from a UI thread. To call from a non-UI 8519 * thread, call {@link #postInvalidate()}. 8520 * 8521 * WARNING: This method is destructive to dirty. 8522 * @param dirty the rectangle representing the bounds of the dirty region 8523 */ 8524 public void invalidate(Rect dirty) { 8525 if (ViewDebug.TRACE_HIERARCHY) { 8526 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8527 } 8528 8529 if (skipInvalidate()) { 8530 return; 8531 } 8532 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8533 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8534 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8535 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8536 mPrivateFlags |= INVALIDATED; 8537 mPrivateFlags |= DIRTY; 8538 final ViewParent p = mParent; 8539 final AttachInfo ai = mAttachInfo; 8540 //noinspection PointlessBooleanExpression,ConstantConditions 8541 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8542 if (p != null && ai != null && ai.mHardwareAccelerated) { 8543 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8544 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8545 p.invalidateChild(this, null); 8546 return; 8547 } 8548 } 8549 if (p != null && ai != null) { 8550 final int scrollX = mScrollX; 8551 final int scrollY = mScrollY; 8552 final Rect r = ai.mTmpInvalRect; 8553 r.set(dirty.left - scrollX, dirty.top - scrollY, 8554 dirty.right - scrollX, dirty.bottom - scrollY); 8555 mParent.invalidateChild(this, r); 8556 } 8557 } 8558 } 8559 8560 /** 8561 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 8562 * The coordinates of the dirty rect are relative to the view. 8563 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 8564 * will be called at some point in the future. This must be called from 8565 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 8566 * @param l the left position of the dirty region 8567 * @param t the top position of the dirty region 8568 * @param r the right position of the dirty region 8569 * @param b the bottom position of the dirty region 8570 */ 8571 public void invalidate(int l, int t, int r, int b) { 8572 if (ViewDebug.TRACE_HIERARCHY) { 8573 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8574 } 8575 8576 if (skipInvalidate()) { 8577 return; 8578 } 8579 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8580 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8581 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8582 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8583 mPrivateFlags |= INVALIDATED; 8584 mPrivateFlags |= DIRTY; 8585 final ViewParent p = mParent; 8586 final AttachInfo ai = mAttachInfo; 8587 //noinspection PointlessBooleanExpression,ConstantConditions 8588 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8589 if (p != null && ai != null && ai.mHardwareAccelerated) { 8590 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8591 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8592 p.invalidateChild(this, null); 8593 return; 8594 } 8595 } 8596 if (p != null && ai != null && l < r && t < b) { 8597 final int scrollX = mScrollX; 8598 final int scrollY = mScrollY; 8599 final Rect tmpr = ai.mTmpInvalRect; 8600 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 8601 p.invalidateChild(this, tmpr); 8602 } 8603 } 8604 } 8605 8606 /** 8607 * Invalidate the whole view. If the view is visible, 8608 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 8609 * the future. This must be called from a UI thread. To call from a non-UI thread, 8610 * call {@link #postInvalidate()}. 8611 */ 8612 public void invalidate() { 8613 invalidate(true); 8614 } 8615 8616 /** 8617 * This is where the invalidate() work actually happens. A full invalidate() 8618 * causes the drawing cache to be invalidated, but this function can be called with 8619 * invalidateCache set to false to skip that invalidation step for cases that do not 8620 * need it (for example, a component that remains at the same dimensions with the same 8621 * content). 8622 * 8623 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 8624 * well. This is usually true for a full invalidate, but may be set to false if the 8625 * View's contents or dimensions have not changed. 8626 */ 8627 void invalidate(boolean invalidateCache) { 8628 if (ViewDebug.TRACE_HIERARCHY) { 8629 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8630 } 8631 8632 if (skipInvalidate()) { 8633 return; 8634 } 8635 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8636 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) || 8637 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) { 8638 mLastIsOpaque = isOpaque(); 8639 mPrivateFlags &= ~DRAWN; 8640 mPrivateFlags |= DIRTY; 8641 if (invalidateCache) { 8642 mPrivateFlags |= INVALIDATED; 8643 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8644 } 8645 final AttachInfo ai = mAttachInfo; 8646 final ViewParent p = mParent; 8647 //noinspection PointlessBooleanExpression,ConstantConditions 8648 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8649 if (p != null && ai != null && ai.mHardwareAccelerated) { 8650 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8651 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8652 p.invalidateChild(this, null); 8653 return; 8654 } 8655 } 8656 8657 if (p != null && ai != null) { 8658 final Rect r = ai.mTmpInvalRect; 8659 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8660 // Don't call invalidate -- we don't want to internally scroll 8661 // our own bounds 8662 p.invalidateChild(this, r); 8663 } 8664 } 8665 } 8666 8667 /** 8668 * Used to indicate that the parent of this view should clear its caches. This functionality 8669 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8670 * which is necessary when various parent-managed properties of the view change, such as 8671 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 8672 * clears the parent caches and does not causes an invalidate event. 8673 * 8674 * @hide 8675 */ 8676 protected void invalidateParentCaches() { 8677 if (mParent instanceof View) { 8678 ((View) mParent).mPrivateFlags |= INVALIDATED; 8679 } 8680 } 8681 8682 /** 8683 * Used to indicate that the parent of this view should be invalidated. This functionality 8684 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8685 * which is necessary when various parent-managed properties of the view change, such as 8686 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 8687 * an invalidation event to the parent. 8688 * 8689 * @hide 8690 */ 8691 protected void invalidateParentIfNeeded() { 8692 if (isHardwareAccelerated() && mParent instanceof View) { 8693 ((View) mParent).invalidate(true); 8694 } 8695 } 8696 8697 /** 8698 * Indicates whether this View is opaque. An opaque View guarantees that it will 8699 * draw all the pixels overlapping its bounds using a fully opaque color. 8700 * 8701 * Subclasses of View should override this method whenever possible to indicate 8702 * whether an instance is opaque. Opaque Views are treated in a special way by 8703 * the View hierarchy, possibly allowing it to perform optimizations during 8704 * invalidate/draw passes. 8705 * 8706 * @return True if this View is guaranteed to be fully opaque, false otherwise. 8707 */ 8708 @ViewDebug.ExportedProperty(category = "drawing") 8709 public boolean isOpaque() { 8710 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK && 8711 ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1) 8712 >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD); 8713 } 8714 8715 /** 8716 * @hide 8717 */ 8718 protected void computeOpaqueFlags() { 8719 // Opaque if: 8720 // - Has a background 8721 // - Background is opaque 8722 // - Doesn't have scrollbars or scrollbars are inside overlay 8723 8724 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) { 8725 mPrivateFlags |= OPAQUE_BACKGROUND; 8726 } else { 8727 mPrivateFlags &= ~OPAQUE_BACKGROUND; 8728 } 8729 8730 final int flags = mViewFlags; 8731 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 8732 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 8733 mPrivateFlags |= OPAQUE_SCROLLBARS; 8734 } else { 8735 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 8736 } 8737 } 8738 8739 /** 8740 * @hide 8741 */ 8742 protected boolean hasOpaqueScrollbars() { 8743 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 8744 } 8745 8746 /** 8747 * @return A handler associated with the thread running the View. This 8748 * handler can be used to pump events in the UI events queue. 8749 */ 8750 public Handler getHandler() { 8751 if (mAttachInfo != null) { 8752 return mAttachInfo.mHandler; 8753 } 8754 return null; 8755 } 8756 8757 /** 8758 * Gets the view root associated with the View. 8759 * @return The view root, or null if none. 8760 * @hide 8761 */ 8762 public ViewRootImpl getViewRootImpl() { 8763 if (mAttachInfo != null) { 8764 return mAttachInfo.mViewRootImpl; 8765 } 8766 return null; 8767 } 8768 8769 /** 8770 * <p>Causes the Runnable to be added to the message queue. 8771 * The runnable will be run on the user interface thread.</p> 8772 * 8773 * <p>This method can be invoked from outside of the UI thread 8774 * only when this View is attached to a window.</p> 8775 * 8776 * @param action The Runnable that will be executed. 8777 * 8778 * @return Returns true if the Runnable was successfully placed in to the 8779 * message queue. Returns false on failure, usually because the 8780 * looper processing the message queue is exiting. 8781 */ 8782 public boolean post(Runnable action) { 8783 final AttachInfo attachInfo = mAttachInfo; 8784 if (attachInfo != null) { 8785 return attachInfo.mHandler.post(action); 8786 } 8787 // Assume that post will succeed later 8788 ViewRootImpl.getRunQueue().post(action); 8789 return true; 8790 } 8791 8792 /** 8793 * <p>Causes the Runnable to be added to the message queue, to be run 8794 * after the specified amount of time elapses. 8795 * The runnable will be run on the user interface thread.</p> 8796 * 8797 * <p>This method can be invoked from outside of the UI thread 8798 * only when this View is attached to a window.</p> 8799 * 8800 * @param action The Runnable that will be executed. 8801 * @param delayMillis The delay (in milliseconds) until the Runnable 8802 * will be executed. 8803 * 8804 * @return true if the Runnable was successfully placed in to the 8805 * message queue. Returns false on failure, usually because the 8806 * looper processing the message queue is exiting. Note that a 8807 * result of true does not mean the Runnable will be processed -- 8808 * if the looper is quit before the delivery time of the message 8809 * occurs then the message will be dropped. 8810 */ 8811 public boolean postDelayed(Runnable action, long delayMillis) { 8812 final AttachInfo attachInfo = mAttachInfo; 8813 if (attachInfo != null) { 8814 return attachInfo.mHandler.postDelayed(action, delayMillis); 8815 } 8816 // Assume that post will succeed later 8817 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 8818 return true; 8819 } 8820 8821 /** 8822 * <p>Causes the Runnable to execute on the next animation time step. 8823 * The runnable will be run on the user interface thread.</p> 8824 * 8825 * <p>This method can be invoked from outside of the UI thread 8826 * only when this View is attached to a window.</p> 8827 * 8828 * @param action The Runnable that will be executed. 8829 * 8830 * @hide 8831 */ 8832 public void postOnAnimation(Runnable action) { 8833 final AttachInfo attachInfo = mAttachInfo; 8834 if (attachInfo != null) { 8835 attachInfo.mViewRootImpl.mChoreographer.postAnimationCallback(action, null); 8836 } else { 8837 // Assume that post will succeed later 8838 ViewRootImpl.getRunQueue().post(action); 8839 } 8840 } 8841 8842 /** 8843 * <p>Causes the Runnable to execute on the next animation time step, 8844 * after the specified amount of time elapses. 8845 * The runnable will be run on the user interface thread.</p> 8846 * 8847 * <p>This method can be invoked from outside of the UI thread 8848 * only when this View is attached to a window.</p> 8849 * 8850 * @param action The Runnable that will be executed. 8851 * @param delayMillis The delay (in milliseconds) until the Runnable 8852 * will be executed. 8853 * 8854 * @hide 8855 */ 8856 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 8857 final AttachInfo attachInfo = mAttachInfo; 8858 if (attachInfo != null) { 8859 attachInfo.mViewRootImpl.mChoreographer.postAnimationCallbackDelayed( 8860 action, null, delayMillis); 8861 } else { 8862 // Assume that post will succeed later 8863 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 8864 } 8865 } 8866 8867 /** 8868 * <p>Removes the specified Runnable from the message queue.</p> 8869 * 8870 * <p>This method can be invoked from outside of the UI thread 8871 * only when this View is attached to a window.</p> 8872 * 8873 * @param action The Runnable to remove from the message handling queue 8874 * 8875 * @return true if this view could ask the Handler to remove the Runnable, 8876 * false otherwise. When the returned value is true, the Runnable 8877 * may or may not have been actually removed from the message queue 8878 * (for instance, if the Runnable was not in the queue already.) 8879 */ 8880 public boolean removeCallbacks(Runnable action) { 8881 if (action != null) { 8882 final AttachInfo attachInfo = mAttachInfo; 8883 if (attachInfo != null) { 8884 attachInfo.mHandler.removeCallbacks(action); 8885 attachInfo.mViewRootImpl.mChoreographer.removeAnimationCallbacks(action, null); 8886 } else { 8887 // Assume that post will succeed later 8888 ViewRootImpl.getRunQueue().removeCallbacks(action); 8889 } 8890 } 8891 return true; 8892 } 8893 8894 /** 8895 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 8896 * Use this to invalidate the View from a non-UI thread.</p> 8897 * 8898 * <p>This method can be invoked from outside of the UI thread 8899 * only when this View is attached to a window.</p> 8900 * 8901 * @see #invalidate() 8902 */ 8903 public void postInvalidate() { 8904 postInvalidateDelayed(0); 8905 } 8906 8907 /** 8908 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 8909 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 8910 * 8911 * <p>This method can be invoked from outside of the UI thread 8912 * only when this View is attached to a window.</p> 8913 * 8914 * @param left The left coordinate of the rectangle to invalidate. 8915 * @param top The top coordinate of the rectangle to invalidate. 8916 * @param right The right coordinate of the rectangle to invalidate. 8917 * @param bottom The bottom coordinate of the rectangle to invalidate. 8918 * 8919 * @see #invalidate(int, int, int, int) 8920 * @see #invalidate(Rect) 8921 */ 8922 public void postInvalidate(int left, int top, int right, int bottom) { 8923 postInvalidateDelayed(0, left, top, right, bottom); 8924 } 8925 8926 /** 8927 * <p>Cause an invalidate to happen on a subsequent cycle through the event 8928 * loop. Waits for the specified amount of time.</p> 8929 * 8930 * <p>This method can be invoked from outside of the UI thread 8931 * only when this View is attached to a window.</p> 8932 * 8933 * @param delayMilliseconds the duration in milliseconds to delay the 8934 * invalidation by 8935 */ 8936 public void postInvalidateDelayed(long delayMilliseconds) { 8937 // We try only with the AttachInfo because there's no point in invalidating 8938 // if we are not attached to our window 8939 final AttachInfo attachInfo = mAttachInfo; 8940 if (attachInfo != null) { 8941 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 8942 } 8943 } 8944 8945 /** 8946 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 8947 * through the event loop. Waits for the specified amount of time.</p> 8948 * 8949 * <p>This method can be invoked from outside of the UI thread 8950 * only when this View is attached to a window.</p> 8951 * 8952 * @param delayMilliseconds the duration in milliseconds to delay the 8953 * invalidation by 8954 * @param left The left coordinate of the rectangle to invalidate. 8955 * @param top The top coordinate of the rectangle to invalidate. 8956 * @param right The right coordinate of the rectangle to invalidate. 8957 * @param bottom The bottom coordinate of the rectangle to invalidate. 8958 */ 8959 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 8960 int right, int bottom) { 8961 8962 // We try only with the AttachInfo because there's no point in invalidating 8963 // if we are not attached to our window 8964 final AttachInfo attachInfo = mAttachInfo; 8965 if (attachInfo != null) { 8966 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 8967 info.target = this; 8968 info.left = left; 8969 info.top = top; 8970 info.right = right; 8971 info.bottom = bottom; 8972 8973 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 8974 } 8975 } 8976 8977 /** 8978 * <p>Cause an invalidate to happen on the next animation time step, typically the 8979 * next display frame.</p> 8980 * 8981 * <p>This method can be invoked from outside of the UI thread 8982 * only when this View is attached to a window.</p> 8983 * 8984 * @hide 8985 */ 8986 public void postInvalidateOnAnimation() { 8987 // We try only with the AttachInfo because there's no point in invalidating 8988 // if we are not attached to our window 8989 final AttachInfo attachInfo = mAttachInfo; 8990 if (attachInfo != null) { 8991 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 8992 } 8993 } 8994 8995 /** 8996 * <p>Cause an invalidate of the specified area to happen on the next animation 8997 * time step, typically the next display frame.</p> 8998 * 8999 * <p>This method can be invoked from outside of the UI thread 9000 * only when this View is attached to a window.</p> 9001 * 9002 * @param left The left coordinate of the rectangle to invalidate. 9003 * @param top The top coordinate of the rectangle to invalidate. 9004 * @param right The right coordinate of the rectangle to invalidate. 9005 * @param bottom The bottom coordinate of the rectangle to invalidate. 9006 * 9007 * @hide 9008 */ 9009 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 9010 // We try only with the AttachInfo because there's no point in invalidating 9011 // if we are not attached to our window 9012 final AttachInfo attachInfo = mAttachInfo; 9013 if (attachInfo != null) { 9014 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 9015 info.target = this; 9016 info.left = left; 9017 info.top = top; 9018 info.right = right; 9019 info.bottom = bottom; 9020 9021 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 9022 } 9023 } 9024 9025 /** 9026 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 9027 * This event is sent at most once every 9028 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 9029 */ 9030 private void postSendViewScrolledAccessibilityEventCallback() { 9031 if (mSendViewScrolledAccessibilityEvent == null) { 9032 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 9033 } 9034 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 9035 mSendViewScrolledAccessibilityEvent.mIsPending = true; 9036 postDelayed(mSendViewScrolledAccessibilityEvent, 9037 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 9038 } 9039 } 9040 9041 /** 9042 * Called by a parent to request that a child update its values for mScrollX 9043 * and mScrollY if necessary. This will typically be done if the child is 9044 * animating a scroll using a {@link android.widget.Scroller Scroller} 9045 * object. 9046 */ 9047 public void computeScroll() { 9048 } 9049 9050 /** 9051 * <p>Indicate whether the horizontal edges are faded when the view is 9052 * scrolled horizontally.</p> 9053 * 9054 * @return true if the horizontal edges should are faded on scroll, false 9055 * otherwise 9056 * 9057 * @see #setHorizontalFadingEdgeEnabled(boolean) 9058 * @attr ref android.R.styleable#View_requiresFadingEdge 9059 */ 9060 public boolean isHorizontalFadingEdgeEnabled() { 9061 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 9062 } 9063 9064 /** 9065 * <p>Define whether the horizontal edges should be faded when this view 9066 * is scrolled horizontally.</p> 9067 * 9068 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 9069 * be faded when the view is scrolled 9070 * horizontally 9071 * 9072 * @see #isHorizontalFadingEdgeEnabled() 9073 * @attr ref android.R.styleable#View_requiresFadingEdge 9074 */ 9075 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 9076 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 9077 if (horizontalFadingEdgeEnabled) { 9078 initScrollCache(); 9079 } 9080 9081 mViewFlags ^= FADING_EDGE_HORIZONTAL; 9082 } 9083 } 9084 9085 /** 9086 * <p>Indicate whether the vertical edges are faded when the view is 9087 * scrolled horizontally.</p> 9088 * 9089 * @return true if the vertical edges should are faded on scroll, false 9090 * otherwise 9091 * 9092 * @see #setVerticalFadingEdgeEnabled(boolean) 9093 * @attr ref android.R.styleable#View_requiresFadingEdge 9094 */ 9095 public boolean isVerticalFadingEdgeEnabled() { 9096 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 9097 } 9098 9099 /** 9100 * <p>Define whether the vertical edges should be faded when this view 9101 * is scrolled vertically.</p> 9102 * 9103 * @param verticalFadingEdgeEnabled true if the vertical edges should 9104 * be faded when the view is scrolled 9105 * vertically 9106 * 9107 * @see #isVerticalFadingEdgeEnabled() 9108 * @attr ref android.R.styleable#View_requiresFadingEdge 9109 */ 9110 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 9111 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 9112 if (verticalFadingEdgeEnabled) { 9113 initScrollCache(); 9114 } 9115 9116 mViewFlags ^= FADING_EDGE_VERTICAL; 9117 } 9118 } 9119 9120 /** 9121 * Returns the strength, or intensity, of the top faded edge. The strength is 9122 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 9123 * returns 0.0 or 1.0 but no value in between. 9124 * 9125 * Subclasses should override this method to provide a smoother fade transition 9126 * when scrolling occurs. 9127 * 9128 * @return the intensity of the top fade as a float between 0.0f and 1.0f 9129 */ 9130 protected float getTopFadingEdgeStrength() { 9131 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 9132 } 9133 9134 /** 9135 * Returns the strength, or intensity, of the bottom faded edge. The strength is 9136 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 9137 * returns 0.0 or 1.0 but no value in between. 9138 * 9139 * Subclasses should override this method to provide a smoother fade transition 9140 * when scrolling occurs. 9141 * 9142 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 9143 */ 9144 protected float getBottomFadingEdgeStrength() { 9145 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 9146 computeVerticalScrollRange() ? 1.0f : 0.0f; 9147 } 9148 9149 /** 9150 * Returns the strength, or intensity, of the left faded edge. The strength is 9151 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 9152 * returns 0.0 or 1.0 but no value in between. 9153 * 9154 * Subclasses should override this method to provide a smoother fade transition 9155 * when scrolling occurs. 9156 * 9157 * @return the intensity of the left fade as a float between 0.0f and 1.0f 9158 */ 9159 protected float getLeftFadingEdgeStrength() { 9160 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 9161 } 9162 9163 /** 9164 * Returns the strength, or intensity, of the right faded edge. The strength is 9165 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 9166 * returns 0.0 or 1.0 but no value in between. 9167 * 9168 * Subclasses should override this method to provide a smoother fade transition 9169 * when scrolling occurs. 9170 * 9171 * @return the intensity of the right fade as a float between 0.0f and 1.0f 9172 */ 9173 protected float getRightFadingEdgeStrength() { 9174 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 9175 computeHorizontalScrollRange() ? 1.0f : 0.0f; 9176 } 9177 9178 /** 9179 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 9180 * scrollbar is not drawn by default.</p> 9181 * 9182 * @return true if the horizontal scrollbar should be painted, false 9183 * otherwise 9184 * 9185 * @see #setHorizontalScrollBarEnabled(boolean) 9186 */ 9187 public boolean isHorizontalScrollBarEnabled() { 9188 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 9189 } 9190 9191 /** 9192 * <p>Define whether the horizontal scrollbar should be drawn or not. The 9193 * scrollbar is not drawn by default.</p> 9194 * 9195 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 9196 * be painted 9197 * 9198 * @see #isHorizontalScrollBarEnabled() 9199 */ 9200 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 9201 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 9202 mViewFlags ^= SCROLLBARS_HORIZONTAL; 9203 computeOpaqueFlags(); 9204 resolvePadding(); 9205 } 9206 } 9207 9208 /** 9209 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 9210 * scrollbar is not drawn by default.</p> 9211 * 9212 * @return true if the vertical scrollbar should be painted, false 9213 * otherwise 9214 * 9215 * @see #setVerticalScrollBarEnabled(boolean) 9216 */ 9217 public boolean isVerticalScrollBarEnabled() { 9218 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 9219 } 9220 9221 /** 9222 * <p>Define whether the vertical scrollbar should be drawn or not. The 9223 * scrollbar is not drawn by default.</p> 9224 * 9225 * @param verticalScrollBarEnabled true if the vertical scrollbar should 9226 * be painted 9227 * 9228 * @see #isVerticalScrollBarEnabled() 9229 */ 9230 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 9231 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 9232 mViewFlags ^= SCROLLBARS_VERTICAL; 9233 computeOpaqueFlags(); 9234 resolvePadding(); 9235 } 9236 } 9237 9238 /** 9239 * @hide 9240 */ 9241 protected void recomputePadding() { 9242 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 9243 } 9244 9245 /** 9246 * Define whether scrollbars will fade when the view is not scrolling. 9247 * 9248 * @param fadeScrollbars wheter to enable fading 9249 * 9250 */ 9251 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 9252 initScrollCache(); 9253 final ScrollabilityCache scrollabilityCache = mScrollCache; 9254 scrollabilityCache.fadeScrollBars = fadeScrollbars; 9255 if (fadeScrollbars) { 9256 scrollabilityCache.state = ScrollabilityCache.OFF; 9257 } else { 9258 scrollabilityCache.state = ScrollabilityCache.ON; 9259 } 9260 } 9261 9262 /** 9263 * 9264 * Returns true if scrollbars will fade when this view is not scrolling 9265 * 9266 * @return true if scrollbar fading is enabled 9267 */ 9268 public boolean isScrollbarFadingEnabled() { 9269 return mScrollCache != null && mScrollCache.fadeScrollBars; 9270 } 9271 9272 /** 9273 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 9274 * inset. When inset, they add to the padding of the view. And the scrollbars 9275 * can be drawn inside the padding area or on the edge of the view. For example, 9276 * if a view has a background drawable and you want to draw the scrollbars 9277 * inside the padding specified by the drawable, you can use 9278 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 9279 * appear at the edge of the view, ignoring the padding, then you can use 9280 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 9281 * @param style the style of the scrollbars. Should be one of 9282 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 9283 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 9284 * @see #SCROLLBARS_INSIDE_OVERLAY 9285 * @see #SCROLLBARS_INSIDE_INSET 9286 * @see #SCROLLBARS_OUTSIDE_OVERLAY 9287 * @see #SCROLLBARS_OUTSIDE_INSET 9288 */ 9289 public void setScrollBarStyle(int style) { 9290 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 9291 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 9292 computeOpaqueFlags(); 9293 resolvePadding(); 9294 } 9295 } 9296 9297 /** 9298 * <p>Returns the current scrollbar style.</p> 9299 * @return the current scrollbar style 9300 * @see #SCROLLBARS_INSIDE_OVERLAY 9301 * @see #SCROLLBARS_INSIDE_INSET 9302 * @see #SCROLLBARS_OUTSIDE_OVERLAY 9303 * @see #SCROLLBARS_OUTSIDE_INSET 9304 */ 9305 @ViewDebug.ExportedProperty(mapping = { 9306 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 9307 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 9308 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 9309 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 9310 }) 9311 public int getScrollBarStyle() { 9312 return mViewFlags & SCROLLBARS_STYLE_MASK; 9313 } 9314 9315 /** 9316 * <p>Compute the horizontal range that the horizontal scrollbar 9317 * represents.</p> 9318 * 9319 * <p>The range is expressed in arbitrary units that must be the same as the 9320 * units used by {@link #computeHorizontalScrollExtent()} and 9321 * {@link #computeHorizontalScrollOffset()}.</p> 9322 * 9323 * <p>The default range is the drawing width of this view.</p> 9324 * 9325 * @return the total horizontal range represented by the horizontal 9326 * scrollbar 9327 * 9328 * @see #computeHorizontalScrollExtent() 9329 * @see #computeHorizontalScrollOffset() 9330 * @see android.widget.ScrollBarDrawable 9331 */ 9332 protected int computeHorizontalScrollRange() { 9333 return getWidth(); 9334 } 9335 9336 /** 9337 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 9338 * within the horizontal range. This value is used to compute the position 9339 * of the thumb within the scrollbar's track.</p> 9340 * 9341 * <p>The range is expressed in arbitrary units that must be the same as the 9342 * units used by {@link #computeHorizontalScrollRange()} and 9343 * {@link #computeHorizontalScrollExtent()}.</p> 9344 * 9345 * <p>The default offset is the scroll offset of this view.</p> 9346 * 9347 * @return the horizontal offset of the scrollbar's thumb 9348 * 9349 * @see #computeHorizontalScrollRange() 9350 * @see #computeHorizontalScrollExtent() 9351 * @see android.widget.ScrollBarDrawable 9352 */ 9353 protected int computeHorizontalScrollOffset() { 9354 return mScrollX; 9355 } 9356 9357 /** 9358 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 9359 * within the horizontal range. This value is used to compute the length 9360 * of the thumb within the scrollbar's track.</p> 9361 * 9362 * <p>The range is expressed in arbitrary units that must be the same as the 9363 * units used by {@link #computeHorizontalScrollRange()} and 9364 * {@link #computeHorizontalScrollOffset()}.</p> 9365 * 9366 * <p>The default extent is the drawing width of this view.</p> 9367 * 9368 * @return the horizontal extent of the scrollbar's thumb 9369 * 9370 * @see #computeHorizontalScrollRange() 9371 * @see #computeHorizontalScrollOffset() 9372 * @see android.widget.ScrollBarDrawable 9373 */ 9374 protected int computeHorizontalScrollExtent() { 9375 return getWidth(); 9376 } 9377 9378 /** 9379 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 9380 * 9381 * <p>The range is expressed in arbitrary units that must be the same as the 9382 * units used by {@link #computeVerticalScrollExtent()} and 9383 * {@link #computeVerticalScrollOffset()}.</p> 9384 * 9385 * @return the total vertical range represented by the vertical scrollbar 9386 * 9387 * <p>The default range is the drawing height of this view.</p> 9388 * 9389 * @see #computeVerticalScrollExtent() 9390 * @see #computeVerticalScrollOffset() 9391 * @see android.widget.ScrollBarDrawable 9392 */ 9393 protected int computeVerticalScrollRange() { 9394 return getHeight(); 9395 } 9396 9397 /** 9398 * <p>Compute the vertical offset of the vertical scrollbar's thumb 9399 * within the horizontal range. This value is used to compute the position 9400 * of the thumb within the scrollbar's track.</p> 9401 * 9402 * <p>The range is expressed in arbitrary units that must be the same as the 9403 * units used by {@link #computeVerticalScrollRange()} and 9404 * {@link #computeVerticalScrollExtent()}.</p> 9405 * 9406 * <p>The default offset is the scroll offset of this view.</p> 9407 * 9408 * @return the vertical offset of the scrollbar's thumb 9409 * 9410 * @see #computeVerticalScrollRange() 9411 * @see #computeVerticalScrollExtent() 9412 * @see android.widget.ScrollBarDrawable 9413 */ 9414 protected int computeVerticalScrollOffset() { 9415 return mScrollY; 9416 } 9417 9418 /** 9419 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 9420 * within the vertical range. This value is used to compute the length 9421 * of the thumb within the scrollbar's track.</p> 9422 * 9423 * <p>The range is expressed in arbitrary units that must be the same as the 9424 * units used by {@link #computeVerticalScrollRange()} and 9425 * {@link #computeVerticalScrollOffset()}.</p> 9426 * 9427 * <p>The default extent is the drawing height of this view.</p> 9428 * 9429 * @return the vertical extent of the scrollbar's thumb 9430 * 9431 * @see #computeVerticalScrollRange() 9432 * @see #computeVerticalScrollOffset() 9433 * @see android.widget.ScrollBarDrawable 9434 */ 9435 protected int computeVerticalScrollExtent() { 9436 return getHeight(); 9437 } 9438 9439 /** 9440 * Check if this view can be scrolled horizontally in a certain direction. 9441 * 9442 * @param direction Negative to check scrolling left, positive to check scrolling right. 9443 * @return true if this view can be scrolled in the specified direction, false otherwise. 9444 */ 9445 public boolean canScrollHorizontally(int direction) { 9446 final int offset = computeHorizontalScrollOffset(); 9447 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 9448 if (range == 0) return false; 9449 if (direction < 0) { 9450 return offset > 0; 9451 } else { 9452 return offset < range - 1; 9453 } 9454 } 9455 9456 /** 9457 * Check if this view can be scrolled vertically in a certain direction. 9458 * 9459 * @param direction Negative to check scrolling up, positive to check scrolling down. 9460 * @return true if this view can be scrolled in the specified direction, false otherwise. 9461 */ 9462 public boolean canScrollVertically(int direction) { 9463 final int offset = computeVerticalScrollOffset(); 9464 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 9465 if (range == 0) return false; 9466 if (direction < 0) { 9467 return offset > 0; 9468 } else { 9469 return offset < range - 1; 9470 } 9471 } 9472 9473 /** 9474 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 9475 * scrollbars are painted only if they have been awakened first.</p> 9476 * 9477 * @param canvas the canvas on which to draw the scrollbars 9478 * 9479 * @see #awakenScrollBars(int) 9480 */ 9481 protected final void onDrawScrollBars(Canvas canvas) { 9482 // scrollbars are drawn only when the animation is running 9483 final ScrollabilityCache cache = mScrollCache; 9484 if (cache != null) { 9485 9486 int state = cache.state; 9487 9488 if (state == ScrollabilityCache.OFF) { 9489 return; 9490 } 9491 9492 boolean invalidate = false; 9493 9494 if (state == ScrollabilityCache.FADING) { 9495 // We're fading -- get our fade interpolation 9496 if (cache.interpolatorValues == null) { 9497 cache.interpolatorValues = new float[1]; 9498 } 9499 9500 float[] values = cache.interpolatorValues; 9501 9502 // Stops the animation if we're done 9503 if (cache.scrollBarInterpolator.timeToValues(values) == 9504 Interpolator.Result.FREEZE_END) { 9505 cache.state = ScrollabilityCache.OFF; 9506 } else { 9507 cache.scrollBar.setAlpha(Math.round(values[0])); 9508 } 9509 9510 // This will make the scroll bars inval themselves after 9511 // drawing. We only want this when we're fading so that 9512 // we prevent excessive redraws 9513 invalidate = true; 9514 } else { 9515 // We're just on -- but we may have been fading before so 9516 // reset alpha 9517 cache.scrollBar.setAlpha(255); 9518 } 9519 9520 9521 final int viewFlags = mViewFlags; 9522 9523 final boolean drawHorizontalScrollBar = 9524 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 9525 final boolean drawVerticalScrollBar = 9526 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 9527 && !isVerticalScrollBarHidden(); 9528 9529 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 9530 final int width = mRight - mLeft; 9531 final int height = mBottom - mTop; 9532 9533 final ScrollBarDrawable scrollBar = cache.scrollBar; 9534 9535 final int scrollX = mScrollX; 9536 final int scrollY = mScrollY; 9537 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 9538 9539 int left, top, right, bottom; 9540 9541 if (drawHorizontalScrollBar) { 9542 int size = scrollBar.getSize(false); 9543 if (size <= 0) { 9544 size = cache.scrollBarSize; 9545 } 9546 9547 scrollBar.setParameters(computeHorizontalScrollRange(), 9548 computeHorizontalScrollOffset(), 9549 computeHorizontalScrollExtent(), false); 9550 final int verticalScrollBarGap = drawVerticalScrollBar ? 9551 getVerticalScrollbarWidth() : 0; 9552 top = scrollY + height - size - (mUserPaddingBottom & inside); 9553 left = scrollX + (mPaddingLeft & inside); 9554 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 9555 bottom = top + size; 9556 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 9557 if (invalidate) { 9558 invalidate(left, top, right, bottom); 9559 } 9560 } 9561 9562 if (drawVerticalScrollBar) { 9563 int size = scrollBar.getSize(true); 9564 if (size <= 0) { 9565 size = cache.scrollBarSize; 9566 } 9567 9568 scrollBar.setParameters(computeVerticalScrollRange(), 9569 computeVerticalScrollOffset(), 9570 computeVerticalScrollExtent(), true); 9571 switch (mVerticalScrollbarPosition) { 9572 default: 9573 case SCROLLBAR_POSITION_DEFAULT: 9574 case SCROLLBAR_POSITION_RIGHT: 9575 left = scrollX + width - size - (mUserPaddingRight & inside); 9576 break; 9577 case SCROLLBAR_POSITION_LEFT: 9578 left = scrollX + (mUserPaddingLeft & inside); 9579 break; 9580 } 9581 top = scrollY + (mPaddingTop & inside); 9582 right = left + size; 9583 bottom = scrollY + height - (mUserPaddingBottom & inside); 9584 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 9585 if (invalidate) { 9586 invalidate(left, top, right, bottom); 9587 } 9588 } 9589 } 9590 } 9591 } 9592 9593 /** 9594 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 9595 * FastScroller is visible. 9596 * @return whether to temporarily hide the vertical scrollbar 9597 * @hide 9598 */ 9599 protected boolean isVerticalScrollBarHidden() { 9600 return false; 9601 } 9602 9603 /** 9604 * <p>Draw the horizontal scrollbar if 9605 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 9606 * 9607 * @param canvas the canvas on which to draw the scrollbar 9608 * @param scrollBar the scrollbar's drawable 9609 * 9610 * @see #isHorizontalScrollBarEnabled() 9611 * @see #computeHorizontalScrollRange() 9612 * @see #computeHorizontalScrollExtent() 9613 * @see #computeHorizontalScrollOffset() 9614 * @see android.widget.ScrollBarDrawable 9615 * @hide 9616 */ 9617 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 9618 int l, int t, int r, int b) { 9619 scrollBar.setBounds(l, t, r, b); 9620 scrollBar.draw(canvas); 9621 } 9622 9623 /** 9624 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 9625 * returns true.</p> 9626 * 9627 * @param canvas the canvas on which to draw the scrollbar 9628 * @param scrollBar the scrollbar's drawable 9629 * 9630 * @see #isVerticalScrollBarEnabled() 9631 * @see #computeVerticalScrollRange() 9632 * @see #computeVerticalScrollExtent() 9633 * @see #computeVerticalScrollOffset() 9634 * @see android.widget.ScrollBarDrawable 9635 * @hide 9636 */ 9637 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 9638 int l, int t, int r, int b) { 9639 scrollBar.setBounds(l, t, r, b); 9640 scrollBar.draw(canvas); 9641 } 9642 9643 /** 9644 * Implement this to do your drawing. 9645 * 9646 * @param canvas the canvas on which the background will be drawn 9647 */ 9648 protected void onDraw(Canvas canvas) { 9649 } 9650 9651 /* 9652 * Caller is responsible for calling requestLayout if necessary. 9653 * (This allows addViewInLayout to not request a new layout.) 9654 */ 9655 void assignParent(ViewParent parent) { 9656 if (mParent == null) { 9657 mParent = parent; 9658 } else if (parent == null) { 9659 mParent = null; 9660 } else { 9661 throw new RuntimeException("view " + this + " being added, but" 9662 + " it already has a parent"); 9663 } 9664 } 9665 9666 /** 9667 * This is called when the view is attached to a window. At this point it 9668 * has a Surface and will start drawing. Note that this function is 9669 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 9670 * however it may be called any time before the first onDraw -- including 9671 * before or after {@link #onMeasure(int, int)}. 9672 * 9673 * @see #onDetachedFromWindow() 9674 */ 9675 protected void onAttachedToWindow() { 9676 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 9677 mParent.requestTransparentRegion(this); 9678 } 9679 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 9680 initialAwakenScrollBars(); 9681 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH; 9682 } 9683 jumpDrawablesToCurrentState(); 9684 // Order is important here: LayoutDirection MUST be resolved before Padding 9685 // and TextDirection 9686 resolveLayoutDirectionIfNeeded(); 9687 resolvePadding(); 9688 resolveTextDirection(); 9689 if (isFocused()) { 9690 InputMethodManager imm = InputMethodManager.peekInstance(); 9691 imm.focusIn(this); 9692 } 9693 } 9694 9695 /** 9696 * @see #onScreenStateChanged(int) 9697 */ 9698 void dispatchScreenStateChanged(int screenState) { 9699 onScreenStateChanged(screenState); 9700 } 9701 9702 /** 9703 * This method is called whenever the state of the screen this view is 9704 * attached to changes. A state change will usually occurs when the screen 9705 * turns on or off (whether it happens automatically or the user does it 9706 * manually.) 9707 * 9708 * @param screenState The new state of the screen. Can be either 9709 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 9710 */ 9711 public void onScreenStateChanged(int screenState) { 9712 } 9713 9714 /** 9715 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 9716 * that the parent directionality can and will be resolved before its children. 9717 */ 9718 private void resolveLayoutDirectionIfNeeded() { 9719 // Do not resolve if it is not needed 9720 if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return; 9721 9722 // Clear any previous layout direction resolution 9723 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK; 9724 9725 // Set resolved depending on layout direction 9726 switch (getLayoutDirection()) { 9727 case LAYOUT_DIRECTION_INHERIT: 9728 // We cannot do the resolution if there is no parent 9729 if (mParent == null) return; 9730 9731 // If this is root view, no need to look at parent's layout dir. 9732 if (mParent instanceof ViewGroup) { 9733 ViewGroup viewGroup = ((ViewGroup) mParent); 9734 9735 // Check if the parent view group can resolve 9736 if (! viewGroup.canResolveLayoutDirection()) { 9737 return; 9738 } 9739 if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 9740 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9741 } 9742 } 9743 break; 9744 case LAYOUT_DIRECTION_RTL: 9745 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9746 break; 9747 case LAYOUT_DIRECTION_LOCALE: 9748 if(isLayoutDirectionRtl(Locale.getDefault())) { 9749 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9750 } 9751 break; 9752 default: 9753 // Nothing to do, LTR by default 9754 } 9755 9756 // Set to resolved 9757 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED; 9758 onResolvedLayoutDirectionChanged(); 9759 // Resolve padding 9760 resolvePadding(); 9761 } 9762 9763 /** 9764 * Called when layout direction has been resolved. 9765 * 9766 * The default implementation does nothing. 9767 */ 9768 public void onResolvedLayoutDirectionChanged() { 9769 } 9770 9771 /** 9772 * Resolve padding depending on layout direction. 9773 */ 9774 public void resolvePadding() { 9775 // If the user specified the absolute padding (either with android:padding or 9776 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 9777 // use the default padding or the padding from the background drawable 9778 // (stored at this point in mPadding*) 9779 int resolvedLayoutDirection = getResolvedLayoutDirection(); 9780 switch (resolvedLayoutDirection) { 9781 case LAYOUT_DIRECTION_RTL: 9782 // Start user padding override Right user padding. Otherwise, if Right user 9783 // padding is not defined, use the default Right padding. If Right user padding 9784 // is defined, just use it. 9785 if (mUserPaddingStart >= 0) { 9786 mUserPaddingRight = mUserPaddingStart; 9787 } else if (mUserPaddingRight < 0) { 9788 mUserPaddingRight = mPaddingRight; 9789 } 9790 if (mUserPaddingEnd >= 0) { 9791 mUserPaddingLeft = mUserPaddingEnd; 9792 } else if (mUserPaddingLeft < 0) { 9793 mUserPaddingLeft = mPaddingLeft; 9794 } 9795 break; 9796 case LAYOUT_DIRECTION_LTR: 9797 default: 9798 // Start user padding override Left user padding. Otherwise, if Left user 9799 // padding is not defined, use the default left padding. If Left user padding 9800 // is defined, just use it. 9801 if (mUserPaddingStart >= 0) { 9802 mUserPaddingLeft = mUserPaddingStart; 9803 } else if (mUserPaddingLeft < 0) { 9804 mUserPaddingLeft = mPaddingLeft; 9805 } 9806 if (mUserPaddingEnd >= 0) { 9807 mUserPaddingRight = mUserPaddingEnd; 9808 } else if (mUserPaddingRight < 0) { 9809 mUserPaddingRight = mPaddingRight; 9810 } 9811 } 9812 9813 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 9814 9815 if(isPaddingRelative()) { 9816 setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom); 9817 } else { 9818 recomputePadding(); 9819 } 9820 onPaddingChanged(resolvedLayoutDirection); 9821 } 9822 9823 /** 9824 * Resolve padding depending on the layout direction. Subclasses that care about 9825 * padding resolution should override this method. The default implementation does 9826 * nothing. 9827 * 9828 * @param layoutDirection the direction of the layout 9829 * 9830 * @see {@link #LAYOUT_DIRECTION_LTR} 9831 * @see {@link #LAYOUT_DIRECTION_RTL} 9832 */ 9833 public void onPaddingChanged(int layoutDirection) { 9834 } 9835 9836 /** 9837 * Check if layout direction resolution can be done. 9838 * 9839 * @return true if layout direction resolution can be done otherwise return false. 9840 */ 9841 public boolean canResolveLayoutDirection() { 9842 switch (getLayoutDirection()) { 9843 case LAYOUT_DIRECTION_INHERIT: 9844 return (mParent != null); 9845 default: 9846 return true; 9847 } 9848 } 9849 9850 /** 9851 * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset} 9852 * when reset is done. 9853 */ 9854 public void resetResolvedLayoutDirection() { 9855 // Reset the current resolved bits 9856 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK; 9857 onResolvedLayoutDirectionReset(); 9858 // Reset also the text direction 9859 resetResolvedTextDirection(); 9860 } 9861 9862 /** 9863 * Called during reset of resolved layout direction. 9864 * 9865 * Subclasses need to override this method to clear cached information that depends on the 9866 * resolved layout direction, or to inform child views that inherit their layout direction. 9867 * 9868 * The default implementation does nothing. 9869 */ 9870 public void onResolvedLayoutDirectionReset() { 9871 } 9872 9873 /** 9874 * Check if a Locale uses an RTL script. 9875 * 9876 * @param locale Locale to check 9877 * @return true if the Locale uses an RTL script. 9878 */ 9879 protected static boolean isLayoutDirectionRtl(Locale locale) { 9880 return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale)); 9881 } 9882 9883 /** 9884 * This is called when the view is detached from a window. At this point it 9885 * no longer has a surface for drawing. 9886 * 9887 * @see #onAttachedToWindow() 9888 */ 9889 protected void onDetachedFromWindow() { 9890 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 9891 9892 removeUnsetPressCallback(); 9893 removeLongPressCallback(); 9894 removePerformClickCallback(); 9895 removeSendViewScrolledAccessibilityEventCallback(); 9896 9897 destroyDrawingCache(); 9898 9899 destroyLayer(); 9900 9901 if (mDisplayList != null) { 9902 mDisplayList.invalidate(); 9903 } 9904 9905 if (mAttachInfo != null) { 9906 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 9907 } 9908 9909 mCurrentAnimation = null; 9910 9911 resetResolvedLayoutDirection(); 9912 } 9913 9914 /** 9915 * @return The number of times this view has been attached to a window 9916 */ 9917 protected int getWindowAttachCount() { 9918 return mWindowAttachCount; 9919 } 9920 9921 /** 9922 * Retrieve a unique token identifying the window this view is attached to. 9923 * @return Return the window's token for use in 9924 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 9925 */ 9926 public IBinder getWindowToken() { 9927 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 9928 } 9929 9930 /** 9931 * Retrieve a unique token identifying the top-level "real" window of 9932 * the window that this view is attached to. That is, this is like 9933 * {@link #getWindowToken}, except if the window this view in is a panel 9934 * window (attached to another containing window), then the token of 9935 * the containing window is returned instead. 9936 * 9937 * @return Returns the associated window token, either 9938 * {@link #getWindowToken()} or the containing window's token. 9939 */ 9940 public IBinder getApplicationWindowToken() { 9941 AttachInfo ai = mAttachInfo; 9942 if (ai != null) { 9943 IBinder appWindowToken = ai.mPanelParentWindowToken; 9944 if (appWindowToken == null) { 9945 appWindowToken = ai.mWindowToken; 9946 } 9947 return appWindowToken; 9948 } 9949 return null; 9950 } 9951 9952 /** 9953 * Retrieve private session object this view hierarchy is using to 9954 * communicate with the window manager. 9955 * @return the session object to communicate with the window manager 9956 */ 9957 /*package*/ IWindowSession getWindowSession() { 9958 return mAttachInfo != null ? mAttachInfo.mSession : null; 9959 } 9960 9961 /** 9962 * @param info the {@link android.view.View.AttachInfo} to associated with 9963 * this view 9964 */ 9965 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 9966 //System.out.println("Attached! " + this); 9967 mAttachInfo = info; 9968 mWindowAttachCount++; 9969 // We will need to evaluate the drawable state at least once. 9970 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 9971 if (mFloatingTreeObserver != null) { 9972 info.mTreeObserver.merge(mFloatingTreeObserver); 9973 mFloatingTreeObserver = null; 9974 } 9975 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 9976 mAttachInfo.mScrollContainers.add(this); 9977 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 9978 } 9979 performCollectViewAttributes(visibility); 9980 onAttachedToWindow(); 9981 9982 ListenerInfo li = mListenerInfo; 9983 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9984 li != null ? li.mOnAttachStateChangeListeners : null; 9985 if (listeners != null && listeners.size() > 0) { 9986 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9987 // perform the dispatching. The iterator is a safe guard against listeners that 9988 // could mutate the list by calling the various add/remove methods. This prevents 9989 // the array from being modified while we iterate it. 9990 for (OnAttachStateChangeListener listener : listeners) { 9991 listener.onViewAttachedToWindow(this); 9992 } 9993 } 9994 9995 int vis = info.mWindowVisibility; 9996 if (vis != GONE) { 9997 onWindowVisibilityChanged(vis); 9998 } 9999 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 10000 // If nobody has evaluated the drawable state yet, then do it now. 10001 refreshDrawableState(); 10002 } 10003 } 10004 10005 void dispatchDetachedFromWindow() { 10006 AttachInfo info = mAttachInfo; 10007 if (info != null) { 10008 int vis = info.mWindowVisibility; 10009 if (vis != GONE) { 10010 onWindowVisibilityChanged(GONE); 10011 } 10012 } 10013 10014 onDetachedFromWindow(); 10015 10016 ListenerInfo li = mListenerInfo; 10017 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 10018 li != null ? li.mOnAttachStateChangeListeners : null; 10019 if (listeners != null && listeners.size() > 0) { 10020 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 10021 // perform the dispatching. The iterator is a safe guard against listeners that 10022 // could mutate the list by calling the various add/remove methods. This prevents 10023 // the array from being modified while we iterate it. 10024 for (OnAttachStateChangeListener listener : listeners) { 10025 listener.onViewDetachedFromWindow(this); 10026 } 10027 } 10028 10029 if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) { 10030 mAttachInfo.mScrollContainers.remove(this); 10031 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 10032 } 10033 10034 mAttachInfo = null; 10035 } 10036 10037 /** 10038 * Store this view hierarchy's frozen state into the given container. 10039 * 10040 * @param container The SparseArray in which to save the view's state. 10041 * 10042 * @see #restoreHierarchyState(android.util.SparseArray) 10043 * @see #dispatchSaveInstanceState(android.util.SparseArray) 10044 * @see #onSaveInstanceState() 10045 */ 10046 public void saveHierarchyState(SparseArray<Parcelable> container) { 10047 dispatchSaveInstanceState(container); 10048 } 10049 10050 /** 10051 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 10052 * this view and its children. May be overridden to modify how freezing happens to a 10053 * view's children; for example, some views may want to not store state for their children. 10054 * 10055 * @param container The SparseArray in which to save the view's state. 10056 * 10057 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 10058 * @see #saveHierarchyState(android.util.SparseArray) 10059 * @see #onSaveInstanceState() 10060 */ 10061 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 10062 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 10063 mPrivateFlags &= ~SAVE_STATE_CALLED; 10064 Parcelable state = onSaveInstanceState(); 10065 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 10066 throw new IllegalStateException( 10067 "Derived class did not call super.onSaveInstanceState()"); 10068 } 10069 if (state != null) { 10070 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 10071 // + ": " + state); 10072 container.put(mID, state); 10073 } 10074 } 10075 } 10076 10077 /** 10078 * Hook allowing a view to generate a representation of its internal state 10079 * that can later be used to create a new instance with that same state. 10080 * This state should only contain information that is not persistent or can 10081 * not be reconstructed later. For example, you will never store your 10082 * current position on screen because that will be computed again when a 10083 * new instance of the view is placed in its view hierarchy. 10084 * <p> 10085 * Some examples of things you may store here: the current cursor position 10086 * in a text view (but usually not the text itself since that is stored in a 10087 * content provider or other persistent storage), the currently selected 10088 * item in a list view. 10089 * 10090 * @return Returns a Parcelable object containing the view's current dynamic 10091 * state, or null if there is nothing interesting to save. The 10092 * default implementation returns null. 10093 * @see #onRestoreInstanceState(android.os.Parcelable) 10094 * @see #saveHierarchyState(android.util.SparseArray) 10095 * @see #dispatchSaveInstanceState(android.util.SparseArray) 10096 * @see #setSaveEnabled(boolean) 10097 */ 10098 protected Parcelable onSaveInstanceState() { 10099 mPrivateFlags |= SAVE_STATE_CALLED; 10100 return BaseSavedState.EMPTY_STATE; 10101 } 10102 10103 /** 10104 * Restore this view hierarchy's frozen state from the given container. 10105 * 10106 * @param container The SparseArray which holds previously frozen states. 10107 * 10108 * @see #saveHierarchyState(android.util.SparseArray) 10109 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 10110 * @see #onRestoreInstanceState(android.os.Parcelable) 10111 */ 10112 public void restoreHierarchyState(SparseArray<Parcelable> container) { 10113 dispatchRestoreInstanceState(container); 10114 } 10115 10116 /** 10117 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 10118 * state for this view and its children. May be overridden to modify how restoring 10119 * happens to a view's children; for example, some views may want to not store state 10120 * for their children. 10121 * 10122 * @param container The SparseArray which holds previously saved state. 10123 * 10124 * @see #dispatchSaveInstanceState(android.util.SparseArray) 10125 * @see #restoreHierarchyState(android.util.SparseArray) 10126 * @see #onRestoreInstanceState(android.os.Parcelable) 10127 */ 10128 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 10129 if (mID != NO_ID) { 10130 Parcelable state = container.get(mID); 10131 if (state != null) { 10132 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 10133 // + ": " + state); 10134 mPrivateFlags &= ~SAVE_STATE_CALLED; 10135 onRestoreInstanceState(state); 10136 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 10137 throw new IllegalStateException( 10138 "Derived class did not call super.onRestoreInstanceState()"); 10139 } 10140 } 10141 } 10142 } 10143 10144 /** 10145 * Hook allowing a view to re-apply a representation of its internal state that had previously 10146 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 10147 * null state. 10148 * 10149 * @param state The frozen state that had previously been returned by 10150 * {@link #onSaveInstanceState}. 10151 * 10152 * @see #onSaveInstanceState() 10153 * @see #restoreHierarchyState(android.util.SparseArray) 10154 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 10155 */ 10156 protected void onRestoreInstanceState(Parcelable state) { 10157 mPrivateFlags |= SAVE_STATE_CALLED; 10158 if (state != BaseSavedState.EMPTY_STATE && state != null) { 10159 throw new IllegalArgumentException("Wrong state class, expecting View State but " 10160 + "received " + state.getClass().toString() + " instead. This usually happens " 10161 + "when two views of different type have the same id in the same hierarchy. " 10162 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 10163 + "other views do not use the same id."); 10164 } 10165 } 10166 10167 /** 10168 * <p>Return the time at which the drawing of the view hierarchy started.</p> 10169 * 10170 * @return the drawing start time in milliseconds 10171 */ 10172 public long getDrawingTime() { 10173 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 10174 } 10175 10176 /** 10177 * <p>Enables or disables the duplication of the parent's state into this view. When 10178 * duplication is enabled, this view gets its drawable state from its parent rather 10179 * than from its own internal properties.</p> 10180 * 10181 * <p>Note: in the current implementation, setting this property to true after the 10182 * view was added to a ViewGroup might have no effect at all. This property should 10183 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 10184 * 10185 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 10186 * property is enabled, an exception will be thrown.</p> 10187 * 10188 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 10189 * parent, these states should not be affected by this method.</p> 10190 * 10191 * @param enabled True to enable duplication of the parent's drawable state, false 10192 * to disable it. 10193 * 10194 * @see #getDrawableState() 10195 * @see #isDuplicateParentStateEnabled() 10196 */ 10197 public void setDuplicateParentStateEnabled(boolean enabled) { 10198 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 10199 } 10200 10201 /** 10202 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 10203 * 10204 * @return True if this view's drawable state is duplicated from the parent, 10205 * false otherwise 10206 * 10207 * @see #getDrawableState() 10208 * @see #setDuplicateParentStateEnabled(boolean) 10209 */ 10210 public boolean isDuplicateParentStateEnabled() { 10211 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 10212 } 10213 10214 /** 10215 * <p>Specifies the type of layer backing this view. The layer can be 10216 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 10217 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 10218 * 10219 * <p>A layer is associated with an optional {@link android.graphics.Paint} 10220 * instance that controls how the layer is composed on screen. The following 10221 * properties of the paint are taken into account when composing the layer:</p> 10222 * <ul> 10223 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 10224 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 10225 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 10226 * </ul> 10227 * 10228 * <p>If this view has an alpha value set to < 1.0 by calling 10229 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 10230 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 10231 * equivalent to setting a hardware layer on this view and providing a paint with 10232 * the desired alpha value.<p> 10233 * 10234 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 10235 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 10236 * for more information on when and how to use layers.</p> 10237 * 10238 * @param layerType The ype of layer to use with this view, must be one of 10239 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 10240 * {@link #LAYER_TYPE_HARDWARE} 10241 * @param paint The paint used to compose the layer. This argument is optional 10242 * and can be null. It is ignored when the layer type is 10243 * {@link #LAYER_TYPE_NONE} 10244 * 10245 * @see #getLayerType() 10246 * @see #LAYER_TYPE_NONE 10247 * @see #LAYER_TYPE_SOFTWARE 10248 * @see #LAYER_TYPE_HARDWARE 10249 * @see #setAlpha(float) 10250 * 10251 * @attr ref android.R.styleable#View_layerType 10252 */ 10253 public void setLayerType(int layerType, Paint paint) { 10254 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 10255 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 10256 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 10257 } 10258 10259 if (layerType == mLayerType) { 10260 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 10261 mLayerPaint = paint == null ? new Paint() : paint; 10262 invalidateParentCaches(); 10263 invalidate(true); 10264 } 10265 return; 10266 } 10267 10268 // Destroy any previous software drawing cache if needed 10269 switch (mLayerType) { 10270 case LAYER_TYPE_HARDWARE: 10271 destroyLayer(); 10272 // fall through - non-accelerated views may use software layer mechanism instead 10273 case LAYER_TYPE_SOFTWARE: 10274 destroyDrawingCache(); 10275 break; 10276 default: 10277 break; 10278 } 10279 10280 mLayerType = layerType; 10281 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 10282 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 10283 mLocalDirtyRect = layerDisabled ? null : new Rect(); 10284 10285 invalidateParentCaches(); 10286 invalidate(true); 10287 } 10288 10289 /** 10290 * Indicates whether this view has a static layer. A view with layer type 10291 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 10292 * dynamic. 10293 */ 10294 boolean hasStaticLayer() { 10295 return true; 10296 } 10297 10298 /** 10299 * Indicates what type of layer is currently associated with this view. By default 10300 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 10301 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 10302 * for more information on the different types of layers. 10303 * 10304 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 10305 * {@link #LAYER_TYPE_HARDWARE} 10306 * 10307 * @see #setLayerType(int, android.graphics.Paint) 10308 * @see #buildLayer() 10309 * @see #LAYER_TYPE_NONE 10310 * @see #LAYER_TYPE_SOFTWARE 10311 * @see #LAYER_TYPE_HARDWARE 10312 */ 10313 public int getLayerType() { 10314 return mLayerType; 10315 } 10316 10317 /** 10318 * Forces this view's layer to be created and this view to be rendered 10319 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 10320 * invoking this method will have no effect. 10321 * 10322 * This method can for instance be used to render a view into its layer before 10323 * starting an animation. If this view is complex, rendering into the layer 10324 * before starting the animation will avoid skipping frames. 10325 * 10326 * @throws IllegalStateException If this view is not attached to a window 10327 * 10328 * @see #setLayerType(int, android.graphics.Paint) 10329 */ 10330 public void buildLayer() { 10331 if (mLayerType == LAYER_TYPE_NONE) return; 10332 10333 if (mAttachInfo == null) { 10334 throw new IllegalStateException("This view must be attached to a window first"); 10335 } 10336 10337 switch (mLayerType) { 10338 case LAYER_TYPE_HARDWARE: 10339 if (mAttachInfo.mHardwareRenderer != null && 10340 mAttachInfo.mHardwareRenderer.isEnabled() && 10341 mAttachInfo.mHardwareRenderer.validate()) { 10342 getHardwareLayer(); 10343 } 10344 break; 10345 case LAYER_TYPE_SOFTWARE: 10346 buildDrawingCache(true); 10347 break; 10348 } 10349 } 10350 10351 // Make sure the HardwareRenderer.validate() was invoked before calling this method 10352 void flushLayer() { 10353 if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) { 10354 mHardwareLayer.flush(); 10355 } 10356 } 10357 10358 /** 10359 * <p>Returns a hardware layer that can be used to draw this view again 10360 * without executing its draw method.</p> 10361 * 10362 * @return A HardwareLayer ready to render, or null if an error occurred. 10363 */ 10364 HardwareLayer getHardwareLayer() { 10365 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 10366 !mAttachInfo.mHardwareRenderer.isEnabled()) { 10367 return null; 10368 } 10369 10370 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 10371 10372 final int width = mRight - mLeft; 10373 final int height = mBottom - mTop; 10374 10375 if (width == 0 || height == 0) { 10376 return null; 10377 } 10378 10379 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 10380 if (mHardwareLayer == null) { 10381 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 10382 width, height, isOpaque()); 10383 mLocalDirtyRect.setEmpty(); 10384 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 10385 mHardwareLayer.resize(width, height); 10386 mLocalDirtyRect.setEmpty(); 10387 } 10388 10389 // The layer is not valid if the underlying GPU resources cannot be allocated 10390 if (!mHardwareLayer.isValid()) { 10391 return null; 10392 } 10393 10394 mHardwareLayer.redraw(getDisplayList(), mLocalDirtyRect); 10395 mLocalDirtyRect.setEmpty(); 10396 } 10397 10398 return mHardwareLayer; 10399 } 10400 10401 /** 10402 * Destroys this View's hardware layer if possible. 10403 * 10404 * @return True if the layer was destroyed, false otherwise. 10405 * 10406 * @see #setLayerType(int, android.graphics.Paint) 10407 * @see #LAYER_TYPE_HARDWARE 10408 */ 10409 boolean destroyLayer() { 10410 if (mHardwareLayer != null) { 10411 AttachInfo info = mAttachInfo; 10412 if (info != null && info.mHardwareRenderer != null && 10413 info.mHardwareRenderer.isEnabled() && info.mHardwareRenderer.validate()) { 10414 mHardwareLayer.destroy(); 10415 mHardwareLayer = null; 10416 10417 invalidate(true); 10418 invalidateParentCaches(); 10419 } 10420 return true; 10421 } 10422 return false; 10423 } 10424 10425 /** 10426 * Destroys all hardware rendering resources. This method is invoked 10427 * when the system needs to reclaim resources. Upon execution of this 10428 * method, you should free any OpenGL resources created by the view. 10429 * 10430 * Note: you <strong>must</strong> call 10431 * <code>super.destroyHardwareResources()</code> when overriding 10432 * this method. 10433 * 10434 * @hide 10435 */ 10436 protected void destroyHardwareResources() { 10437 destroyLayer(); 10438 } 10439 10440 /** 10441 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 10442 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 10443 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 10444 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 10445 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 10446 * null.</p> 10447 * 10448 * <p>Enabling the drawing cache is similar to 10449 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 10450 * acceleration is turned off. When hardware acceleration is turned on, enabling the 10451 * drawing cache has no effect on rendering because the system uses a different mechanism 10452 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 10453 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 10454 * for information on how to enable software and hardware layers.</p> 10455 * 10456 * <p>This API can be used to manually generate 10457 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 10458 * {@link #getDrawingCache()}.</p> 10459 * 10460 * @param enabled true to enable the drawing cache, false otherwise 10461 * 10462 * @see #isDrawingCacheEnabled() 10463 * @see #getDrawingCache() 10464 * @see #buildDrawingCache() 10465 * @see #setLayerType(int, android.graphics.Paint) 10466 */ 10467 public void setDrawingCacheEnabled(boolean enabled) { 10468 mCachingFailed = false; 10469 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 10470 } 10471 10472 /** 10473 * <p>Indicates whether the drawing cache is enabled for this view.</p> 10474 * 10475 * @return true if the drawing cache is enabled 10476 * 10477 * @see #setDrawingCacheEnabled(boolean) 10478 * @see #getDrawingCache() 10479 */ 10480 @ViewDebug.ExportedProperty(category = "drawing") 10481 public boolean isDrawingCacheEnabled() { 10482 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 10483 } 10484 10485 /** 10486 * Debugging utility which recursively outputs the dirty state of a view and its 10487 * descendants. 10488 * 10489 * @hide 10490 */ 10491 @SuppressWarnings({"UnusedDeclaration"}) 10492 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 10493 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) + 10494 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" + 10495 (mPrivateFlags & View.DRAWING_CACHE_VALID) + 10496 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")"); 10497 if (clear) { 10498 mPrivateFlags &= clearMask; 10499 } 10500 if (this instanceof ViewGroup) { 10501 ViewGroup parent = (ViewGroup) this; 10502 final int count = parent.getChildCount(); 10503 for (int i = 0; i < count; i++) { 10504 final View child = parent.getChildAt(i); 10505 child.outputDirtyFlags(indent + " ", clear, clearMask); 10506 } 10507 } 10508 } 10509 10510 /** 10511 * This method is used by ViewGroup to cause its children to restore or recreate their 10512 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 10513 * to recreate its own display list, which would happen if it went through the normal 10514 * draw/dispatchDraw mechanisms. 10515 * 10516 * @hide 10517 */ 10518 protected void dispatchGetDisplayList() {} 10519 10520 /** 10521 * A view that is not attached or hardware accelerated cannot create a display list. 10522 * This method checks these conditions and returns the appropriate result. 10523 * 10524 * @return true if view has the ability to create a display list, false otherwise. 10525 * 10526 * @hide 10527 */ 10528 public boolean canHaveDisplayList() { 10529 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 10530 } 10531 10532 /** 10533 * @return The HardwareRenderer associated with that view or null if hardware rendering 10534 * is not supported or this this has not been attached to a window. 10535 * 10536 * @hide 10537 */ 10538 public HardwareRenderer getHardwareRenderer() { 10539 if (mAttachInfo != null) { 10540 return mAttachInfo.mHardwareRenderer; 10541 } 10542 return null; 10543 } 10544 10545 /** 10546 * <p>Returns a display list that can be used to draw this view again 10547 * without executing its draw method.</p> 10548 * 10549 * @return A DisplayList ready to replay, or null if caching is not enabled. 10550 * 10551 * @hide 10552 */ 10553 public DisplayList getDisplayList() { 10554 if (!canHaveDisplayList()) { 10555 return null; 10556 } 10557 10558 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || 10559 mDisplayList == null || !mDisplayList.isValid() || 10560 mRecreateDisplayList)) { 10561 // Don't need to recreate the display list, just need to tell our 10562 // children to restore/recreate theirs 10563 if (mDisplayList != null && mDisplayList.isValid() && 10564 !mRecreateDisplayList) { 10565 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10566 mPrivateFlags &= ~DIRTY_MASK; 10567 dispatchGetDisplayList(); 10568 10569 return mDisplayList; 10570 } 10571 10572 // If we got here, we're recreating it. Mark it as such to ensure that 10573 // we copy in child display lists into ours in drawChild() 10574 mRecreateDisplayList = true; 10575 if (mDisplayList == null) { 10576 final String name = getClass().getSimpleName(); 10577 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(name); 10578 // If we're creating a new display list, make sure our parent gets invalidated 10579 // since they will need to recreate their display list to account for this 10580 // new child display list. 10581 invalidateParentCaches(); 10582 } 10583 10584 final HardwareCanvas canvas = mDisplayList.start(); 10585 int restoreCount = 0; 10586 try { 10587 int width = mRight - mLeft; 10588 int height = mBottom - mTop; 10589 10590 canvas.setViewport(width, height); 10591 // The dirty rect should always be null for a display list 10592 canvas.onPreDraw(null); 10593 10594 computeScroll(); 10595 10596 restoreCount = canvas.save(); 10597 canvas.translate(-mScrollX, -mScrollY); 10598 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10599 mPrivateFlags &= ~DIRTY_MASK; 10600 10601 // Fast path for layouts with no backgrounds 10602 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10603 dispatchDraw(canvas); 10604 } else { 10605 draw(canvas); 10606 } 10607 } finally { 10608 canvas.restoreToCount(restoreCount); 10609 canvas.onPostDraw(); 10610 10611 mDisplayList.end(); 10612 } 10613 } else { 10614 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10615 mPrivateFlags &= ~DIRTY_MASK; 10616 } 10617 10618 return mDisplayList; 10619 } 10620 10621 /** 10622 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 10623 * 10624 * @return A non-scaled bitmap representing this view or null if cache is disabled. 10625 * 10626 * @see #getDrawingCache(boolean) 10627 */ 10628 public Bitmap getDrawingCache() { 10629 return getDrawingCache(false); 10630 } 10631 10632 /** 10633 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 10634 * is null when caching is disabled. If caching is enabled and the cache is not ready, 10635 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 10636 * draw from the cache when the cache is enabled. To benefit from the cache, you must 10637 * request the drawing cache by calling this method and draw it on screen if the 10638 * returned bitmap is not null.</p> 10639 * 10640 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10641 * this method will create a bitmap of the same size as this view. Because this bitmap 10642 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10643 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10644 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10645 * size than the view. This implies that your application must be able to handle this 10646 * size.</p> 10647 * 10648 * @param autoScale Indicates whether the generated bitmap should be scaled based on 10649 * the current density of the screen when the application is in compatibility 10650 * mode. 10651 * 10652 * @return A bitmap representing this view or null if cache is disabled. 10653 * 10654 * @see #setDrawingCacheEnabled(boolean) 10655 * @see #isDrawingCacheEnabled() 10656 * @see #buildDrawingCache(boolean) 10657 * @see #destroyDrawingCache() 10658 */ 10659 public Bitmap getDrawingCache(boolean autoScale) { 10660 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 10661 return null; 10662 } 10663 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 10664 buildDrawingCache(autoScale); 10665 } 10666 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 10667 } 10668 10669 /** 10670 * <p>Frees the resources used by the drawing cache. If you call 10671 * {@link #buildDrawingCache()} manually without calling 10672 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10673 * should cleanup the cache with this method afterwards.</p> 10674 * 10675 * @see #setDrawingCacheEnabled(boolean) 10676 * @see #buildDrawingCache() 10677 * @see #getDrawingCache() 10678 */ 10679 public void destroyDrawingCache() { 10680 if (mDrawingCache != null) { 10681 mDrawingCache.recycle(); 10682 mDrawingCache = null; 10683 } 10684 if (mUnscaledDrawingCache != null) { 10685 mUnscaledDrawingCache.recycle(); 10686 mUnscaledDrawingCache = null; 10687 } 10688 } 10689 10690 /** 10691 * Setting a solid background color for the drawing cache's bitmaps will improve 10692 * performance and memory usage. Note, though that this should only be used if this 10693 * view will always be drawn on top of a solid color. 10694 * 10695 * @param color The background color to use for the drawing cache's bitmap 10696 * 10697 * @see #setDrawingCacheEnabled(boolean) 10698 * @see #buildDrawingCache() 10699 * @see #getDrawingCache() 10700 */ 10701 public void setDrawingCacheBackgroundColor(int color) { 10702 if (color != mDrawingCacheBackgroundColor) { 10703 mDrawingCacheBackgroundColor = color; 10704 mPrivateFlags &= ~DRAWING_CACHE_VALID; 10705 } 10706 } 10707 10708 /** 10709 * @see #setDrawingCacheBackgroundColor(int) 10710 * 10711 * @return The background color to used for the drawing cache's bitmap 10712 */ 10713 public int getDrawingCacheBackgroundColor() { 10714 return mDrawingCacheBackgroundColor; 10715 } 10716 10717 /** 10718 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 10719 * 10720 * @see #buildDrawingCache(boolean) 10721 */ 10722 public void buildDrawingCache() { 10723 buildDrawingCache(false); 10724 } 10725 10726 /** 10727 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 10728 * 10729 * <p>If you call {@link #buildDrawingCache()} manually without calling 10730 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10731 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 10732 * 10733 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10734 * this method will create a bitmap of the same size as this view. Because this bitmap 10735 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10736 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10737 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10738 * size than the view. This implies that your application must be able to handle this 10739 * size.</p> 10740 * 10741 * <p>You should avoid calling this method when hardware acceleration is enabled. If 10742 * you do not need the drawing cache bitmap, calling this method will increase memory 10743 * usage and cause the view to be rendered in software once, thus negatively impacting 10744 * performance.</p> 10745 * 10746 * @see #getDrawingCache() 10747 * @see #destroyDrawingCache() 10748 */ 10749 public void buildDrawingCache(boolean autoScale) { 10750 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 10751 mDrawingCache == null : mUnscaledDrawingCache == null)) { 10752 mCachingFailed = false; 10753 10754 if (ViewDebug.TRACE_HIERARCHY) { 10755 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 10756 } 10757 10758 int width = mRight - mLeft; 10759 int height = mBottom - mTop; 10760 10761 final AttachInfo attachInfo = mAttachInfo; 10762 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 10763 10764 if (autoScale && scalingRequired) { 10765 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 10766 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 10767 } 10768 10769 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 10770 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 10771 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 10772 10773 if (width <= 0 || height <= 0 || 10774 // Projected bitmap size in bytes 10775 (width * height * (opaque && !use32BitCache ? 2 : 4) > 10776 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 10777 destroyDrawingCache(); 10778 mCachingFailed = true; 10779 return; 10780 } 10781 10782 boolean clear = true; 10783 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 10784 10785 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 10786 Bitmap.Config quality; 10787 if (!opaque) { 10788 // Never pick ARGB_4444 because it looks awful 10789 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 10790 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 10791 case DRAWING_CACHE_QUALITY_AUTO: 10792 quality = Bitmap.Config.ARGB_8888; 10793 break; 10794 case DRAWING_CACHE_QUALITY_LOW: 10795 quality = Bitmap.Config.ARGB_8888; 10796 break; 10797 case DRAWING_CACHE_QUALITY_HIGH: 10798 quality = Bitmap.Config.ARGB_8888; 10799 break; 10800 default: 10801 quality = Bitmap.Config.ARGB_8888; 10802 break; 10803 } 10804 } else { 10805 // Optimization for translucent windows 10806 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 10807 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 10808 } 10809 10810 // Try to cleanup memory 10811 if (bitmap != null) bitmap.recycle(); 10812 10813 try { 10814 bitmap = Bitmap.createBitmap(width, height, quality); 10815 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 10816 if (autoScale) { 10817 mDrawingCache = bitmap; 10818 } else { 10819 mUnscaledDrawingCache = bitmap; 10820 } 10821 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 10822 } catch (OutOfMemoryError e) { 10823 // If there is not enough memory to create the bitmap cache, just 10824 // ignore the issue as bitmap caches are not required to draw the 10825 // view hierarchy 10826 if (autoScale) { 10827 mDrawingCache = null; 10828 } else { 10829 mUnscaledDrawingCache = null; 10830 } 10831 mCachingFailed = true; 10832 return; 10833 } 10834 10835 clear = drawingCacheBackgroundColor != 0; 10836 } 10837 10838 Canvas canvas; 10839 if (attachInfo != null) { 10840 canvas = attachInfo.mCanvas; 10841 if (canvas == null) { 10842 canvas = new Canvas(); 10843 } 10844 canvas.setBitmap(bitmap); 10845 // Temporarily clobber the cached Canvas in case one of our children 10846 // is also using a drawing cache. Without this, the children would 10847 // steal the canvas by attaching their own bitmap to it and bad, bad 10848 // thing would happen (invisible views, corrupted drawings, etc.) 10849 attachInfo.mCanvas = null; 10850 } else { 10851 // This case should hopefully never or seldom happen 10852 canvas = new Canvas(bitmap); 10853 } 10854 10855 if (clear) { 10856 bitmap.eraseColor(drawingCacheBackgroundColor); 10857 } 10858 10859 computeScroll(); 10860 final int restoreCount = canvas.save(); 10861 10862 if (autoScale && scalingRequired) { 10863 final float scale = attachInfo.mApplicationScale; 10864 canvas.scale(scale, scale); 10865 } 10866 10867 canvas.translate(-mScrollX, -mScrollY); 10868 10869 mPrivateFlags |= DRAWN; 10870 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 10871 mLayerType != LAYER_TYPE_NONE) { 10872 mPrivateFlags |= DRAWING_CACHE_VALID; 10873 } 10874 10875 // Fast path for layouts with no backgrounds 10876 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10877 if (ViewDebug.TRACE_HIERARCHY) { 10878 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 10879 } 10880 mPrivateFlags &= ~DIRTY_MASK; 10881 dispatchDraw(canvas); 10882 } else { 10883 draw(canvas); 10884 } 10885 10886 canvas.restoreToCount(restoreCount); 10887 canvas.setBitmap(null); 10888 10889 if (attachInfo != null) { 10890 // Restore the cached Canvas for our siblings 10891 attachInfo.mCanvas = canvas; 10892 } 10893 } 10894 } 10895 10896 /** 10897 * Create a snapshot of the view into a bitmap. We should probably make 10898 * some form of this public, but should think about the API. 10899 */ 10900 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 10901 int width = mRight - mLeft; 10902 int height = mBottom - mTop; 10903 10904 final AttachInfo attachInfo = mAttachInfo; 10905 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 10906 width = (int) ((width * scale) + 0.5f); 10907 height = (int) ((height * scale) + 0.5f); 10908 10909 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 10910 if (bitmap == null) { 10911 throw new OutOfMemoryError(); 10912 } 10913 10914 Resources resources = getResources(); 10915 if (resources != null) { 10916 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 10917 } 10918 10919 Canvas canvas; 10920 if (attachInfo != null) { 10921 canvas = attachInfo.mCanvas; 10922 if (canvas == null) { 10923 canvas = new Canvas(); 10924 } 10925 canvas.setBitmap(bitmap); 10926 // Temporarily clobber the cached Canvas in case one of our children 10927 // is also using a drawing cache. Without this, the children would 10928 // steal the canvas by attaching their own bitmap to it and bad, bad 10929 // things would happen (invisible views, corrupted drawings, etc.) 10930 attachInfo.mCanvas = null; 10931 } else { 10932 // This case should hopefully never or seldom happen 10933 canvas = new Canvas(bitmap); 10934 } 10935 10936 if ((backgroundColor & 0xff000000) != 0) { 10937 bitmap.eraseColor(backgroundColor); 10938 } 10939 10940 computeScroll(); 10941 final int restoreCount = canvas.save(); 10942 canvas.scale(scale, scale); 10943 canvas.translate(-mScrollX, -mScrollY); 10944 10945 // Temporarily remove the dirty mask 10946 int flags = mPrivateFlags; 10947 mPrivateFlags &= ~DIRTY_MASK; 10948 10949 // Fast path for layouts with no backgrounds 10950 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10951 dispatchDraw(canvas); 10952 } else { 10953 draw(canvas); 10954 } 10955 10956 mPrivateFlags = flags; 10957 10958 canvas.restoreToCount(restoreCount); 10959 canvas.setBitmap(null); 10960 10961 if (attachInfo != null) { 10962 // Restore the cached Canvas for our siblings 10963 attachInfo.mCanvas = canvas; 10964 } 10965 10966 return bitmap; 10967 } 10968 10969 /** 10970 * Indicates whether this View is currently in edit mode. A View is usually 10971 * in edit mode when displayed within a developer tool. For instance, if 10972 * this View is being drawn by a visual user interface builder, this method 10973 * should return true. 10974 * 10975 * Subclasses should check the return value of this method to provide 10976 * different behaviors if their normal behavior might interfere with the 10977 * host environment. For instance: the class spawns a thread in its 10978 * constructor, the drawing code relies on device-specific features, etc. 10979 * 10980 * This method is usually checked in the drawing code of custom widgets. 10981 * 10982 * @return True if this View is in edit mode, false otherwise. 10983 */ 10984 public boolean isInEditMode() { 10985 return false; 10986 } 10987 10988 /** 10989 * If the View draws content inside its padding and enables fading edges, 10990 * it needs to support padding offsets. Padding offsets are added to the 10991 * fading edges to extend the length of the fade so that it covers pixels 10992 * drawn inside the padding. 10993 * 10994 * Subclasses of this class should override this method if they need 10995 * to draw content inside the padding. 10996 * 10997 * @return True if padding offset must be applied, false otherwise. 10998 * 10999 * @see #getLeftPaddingOffset() 11000 * @see #getRightPaddingOffset() 11001 * @see #getTopPaddingOffset() 11002 * @see #getBottomPaddingOffset() 11003 * 11004 * @since CURRENT 11005 */ 11006 protected boolean isPaddingOffsetRequired() { 11007 return false; 11008 } 11009 11010 /** 11011 * Amount by which to extend the left fading region. Called only when 11012 * {@link #isPaddingOffsetRequired()} returns true. 11013 * 11014 * @return The left padding offset in pixels. 11015 * 11016 * @see #isPaddingOffsetRequired() 11017 * 11018 * @since CURRENT 11019 */ 11020 protected int getLeftPaddingOffset() { 11021 return 0; 11022 } 11023 11024 /** 11025 * Amount by which to extend the right fading region. Called only when 11026 * {@link #isPaddingOffsetRequired()} returns true. 11027 * 11028 * @return The right padding offset in pixels. 11029 * 11030 * @see #isPaddingOffsetRequired() 11031 * 11032 * @since CURRENT 11033 */ 11034 protected int getRightPaddingOffset() { 11035 return 0; 11036 } 11037 11038 /** 11039 * Amount by which to extend the top fading region. Called only when 11040 * {@link #isPaddingOffsetRequired()} returns true. 11041 * 11042 * @return The top padding offset in pixels. 11043 * 11044 * @see #isPaddingOffsetRequired() 11045 * 11046 * @since CURRENT 11047 */ 11048 protected int getTopPaddingOffset() { 11049 return 0; 11050 } 11051 11052 /** 11053 * Amount by which to extend the bottom fading region. Called only when 11054 * {@link #isPaddingOffsetRequired()} returns true. 11055 * 11056 * @return The bottom padding offset in pixels. 11057 * 11058 * @see #isPaddingOffsetRequired() 11059 * 11060 * @since CURRENT 11061 */ 11062 protected int getBottomPaddingOffset() { 11063 return 0; 11064 } 11065 11066 /** 11067 * @hide 11068 * @param offsetRequired 11069 */ 11070 protected int getFadeTop(boolean offsetRequired) { 11071 int top = mPaddingTop; 11072 if (offsetRequired) top += getTopPaddingOffset(); 11073 return top; 11074 } 11075 11076 /** 11077 * @hide 11078 * @param offsetRequired 11079 */ 11080 protected int getFadeHeight(boolean offsetRequired) { 11081 int padding = mPaddingTop; 11082 if (offsetRequired) padding += getTopPaddingOffset(); 11083 return mBottom - mTop - mPaddingBottom - padding; 11084 } 11085 11086 /** 11087 * <p>Indicates whether this view is attached to a hardware accelerated 11088 * window or not.</p> 11089 * 11090 * <p>Even if this method returns true, it does not mean that every call 11091 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 11092 * accelerated {@link android.graphics.Canvas}. For instance, if this view 11093 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 11094 * window is hardware accelerated, 11095 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 11096 * return false, and this method will return true.</p> 11097 * 11098 * @return True if the view is attached to a window and the window is 11099 * hardware accelerated; false in any other case. 11100 */ 11101 public boolean isHardwareAccelerated() { 11102 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 11103 } 11104 11105 /** 11106 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 11107 * case of an active Animation being run on the view. 11108 */ 11109 private boolean drawAnimation(ViewGroup parent, long drawingTime, 11110 Animation a, boolean scalingRequired) { 11111 Transformation invalidationTransform; 11112 final int flags = parent.mGroupFlags; 11113 final boolean initialized = a.isInitialized(); 11114 if (!initialized) { 11115 a.initialize(mRight - mLeft, mBottom - mTop, getWidth(), getHeight()); 11116 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 11117 onAnimationStart(); 11118 } 11119 11120 boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f); 11121 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 11122 if (parent.mInvalidationTransformation == null) { 11123 parent.mInvalidationTransformation = new Transformation(); 11124 } 11125 invalidationTransform = parent.mInvalidationTransformation; 11126 a.getTransformation(drawingTime, invalidationTransform, 1f); 11127 } else { 11128 invalidationTransform = parent.mChildTransformation; 11129 } 11130 if (more) { 11131 if (!a.willChangeBounds()) { 11132 if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) == 11133 parent.FLAG_OPTIMIZE_INVALIDATE) { 11134 parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED; 11135 } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) { 11136 // The child need to draw an animation, potentially offscreen, so 11137 // make sure we do not cancel invalidate requests 11138 parent.mPrivateFlags |= DRAW_ANIMATION; 11139 parent.invalidate(mLeft, mTop, mRight, mBottom); 11140 } 11141 } else { 11142 if (parent.mInvalidateRegion == null) { 11143 parent.mInvalidateRegion = new RectF(); 11144 } 11145 final RectF region = parent.mInvalidateRegion; 11146 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 11147 invalidationTransform); 11148 11149 // The child need to draw an animation, potentially offscreen, so 11150 // make sure we do not cancel invalidate requests 11151 parent.mPrivateFlags |= DRAW_ANIMATION; 11152 11153 final int left = mLeft + (int) region.left; 11154 final int top = mTop + (int) region.top; 11155 parent.invalidate(left, top, left + (int) (region.width() + .5f), 11156 top + (int) (region.height() + .5f)); 11157 } 11158 } 11159 return more; 11160 } 11161 11162 /** 11163 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 11164 * This draw() method is an implementation detail and is not intended to be overridden or 11165 * to be called from anywhere else other than ViewGroup.drawChild(). 11166 */ 11167 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 11168 boolean more = false; 11169 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 11170 final int flags = parent.mGroupFlags; 11171 11172 if ((flags & parent.FLAG_CLEAR_TRANSFORMATION) == parent.FLAG_CLEAR_TRANSFORMATION) { 11173 parent.mChildTransformation.clear(); 11174 parent.mGroupFlags &= ~parent.FLAG_CLEAR_TRANSFORMATION; 11175 } 11176 11177 Transformation transformToApply = null; 11178 boolean concatMatrix = false; 11179 11180 boolean scalingRequired = false; 11181 boolean caching; 11182 int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE; 11183 11184 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 11185 if ((flags & parent.FLAG_CHILDREN_DRAWN_WITH_CACHE) == parent.FLAG_CHILDREN_DRAWN_WITH_CACHE || 11186 (flags & parent.FLAG_ALWAYS_DRAWN_WITH_CACHE) == parent.FLAG_ALWAYS_DRAWN_WITH_CACHE) { 11187 caching = true; 11188 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 11189 } else { 11190 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 11191 } 11192 11193 final Animation a = getAnimation(); 11194 if (a != null) { 11195 more = drawAnimation(parent, drawingTime, a, scalingRequired); 11196 concatMatrix = a.willChangeTransformationMatrix(); 11197 transformToApply = parent.mChildTransformation; 11198 } else if ((flags & parent.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) == 11199 parent.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) { 11200 final boolean hasTransform = 11201 parent.getChildStaticTransformation(this, parent.mChildTransformation); 11202 if (hasTransform) { 11203 final int transformType = parent.mChildTransformation.getTransformationType(); 11204 transformToApply = transformType != Transformation.TYPE_IDENTITY ? 11205 parent.mChildTransformation : null; 11206 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 11207 } 11208 } 11209 11210 concatMatrix |= !childHasIdentityMatrix; 11211 11212 // Sets the flag as early as possible to allow draw() implementations 11213 // to call invalidate() successfully when doing animations 11214 mPrivateFlags |= DRAWN; 11215 11216 if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 11217 (mPrivateFlags & DRAW_ANIMATION) == 0) { 11218 return more; 11219 } 11220 11221 if (hardwareAccelerated) { 11222 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 11223 // retain the flag's value temporarily in the mRecreateDisplayList flag 11224 mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED; 11225 mPrivateFlags &= ~INVALIDATED; 11226 } 11227 11228 computeScroll(); 11229 11230 final int sx = mScrollX; 11231 final int sy = mScrollY; 11232 11233 DisplayList displayList = null; 11234 Bitmap cache = null; 11235 boolean hasDisplayList = false; 11236 if (caching) { 11237 if (!hardwareAccelerated) { 11238 if (layerType != LAYER_TYPE_NONE) { 11239 layerType = LAYER_TYPE_SOFTWARE; 11240 buildDrawingCache(true); 11241 } 11242 cache = getDrawingCache(true); 11243 } else { 11244 switch (layerType) { 11245 case LAYER_TYPE_SOFTWARE: 11246 buildDrawingCache(true); 11247 cache = getDrawingCache(true); 11248 break; 11249 case LAYER_TYPE_NONE: 11250 // Delay getting the display list until animation-driven alpha values are 11251 // set up and possibly passed on to the view 11252 hasDisplayList = canHaveDisplayList(); 11253 break; 11254 } 11255 } 11256 } 11257 11258 final boolean hasNoCache = cache == null || hasDisplayList; 11259 final boolean offsetForScroll = cache == null && !hasDisplayList && 11260 layerType != LAYER_TYPE_HARDWARE; 11261 11262 final int restoreTo = canvas.save(); 11263 if (offsetForScroll) { 11264 canvas.translate(mLeft - sx, mTop - sy); 11265 } else { 11266 canvas.translate(mLeft, mTop); 11267 if (scalingRequired) { 11268 // mAttachInfo cannot be null, otherwise scalingRequired == false 11269 final float scale = 1.0f / mAttachInfo.mApplicationScale; 11270 canvas.scale(scale, scale); 11271 } 11272 } 11273 11274 float alpha = getAlpha(); 11275 if (transformToApply != null || alpha < 1.0f || !hasIdentityMatrix()) { 11276 if (transformToApply != null || !childHasIdentityMatrix) { 11277 int transX = 0; 11278 int transY = 0; 11279 11280 if (offsetForScroll) { 11281 transX = -sx; 11282 transY = -sy; 11283 } 11284 11285 if (transformToApply != null) { 11286 if (concatMatrix) { 11287 // Undo the scroll translation, apply the transformation matrix, 11288 // then redo the scroll translate to get the correct result. 11289 canvas.translate(-transX, -transY); 11290 canvas.concat(transformToApply.getMatrix()); 11291 canvas.translate(transX, transY); 11292 parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION; 11293 } 11294 11295 float transformAlpha = transformToApply.getAlpha(); 11296 if (transformAlpha < 1.0f) { 11297 alpha *= transformToApply.getAlpha(); 11298 parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION; 11299 } 11300 } 11301 11302 if (!childHasIdentityMatrix) { 11303 canvas.translate(-transX, -transY); 11304 canvas.concat(getMatrix()); 11305 canvas.translate(transX, transY); 11306 } 11307 } 11308 11309 if (alpha < 1.0f) { 11310 parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION; 11311 if (hasNoCache) { 11312 final int multipliedAlpha = (int) (255 * alpha); 11313 if (!onSetAlpha(multipliedAlpha)) { 11314 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 11315 if ((flags & parent.FLAG_CLIP_CHILDREN) == parent.FLAG_CLIP_CHILDREN || 11316 layerType != LAYER_TYPE_NONE) { 11317 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 11318 } 11319 if (layerType == LAYER_TYPE_NONE) { 11320 final int scrollX = hasDisplayList ? 0 : sx; 11321 final int scrollY = hasDisplayList ? 0 : sy; 11322 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 11323 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 11324 } 11325 } else { 11326 // Alpha is handled by the child directly, clobber the layer's alpha 11327 mPrivateFlags |= ALPHA_SET; 11328 } 11329 } 11330 } 11331 } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) { 11332 onSetAlpha(255); 11333 mPrivateFlags &= ~ALPHA_SET; 11334 } 11335 11336 if ((flags & parent.FLAG_CLIP_CHILDREN) == parent.FLAG_CLIP_CHILDREN) { 11337 if (offsetForScroll) { 11338 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 11339 } else { 11340 if (!scalingRequired || cache == null) { 11341 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 11342 } else { 11343 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 11344 } 11345 } 11346 } 11347 11348 if (hasDisplayList) { 11349 displayList = getDisplayList(); 11350 if (!displayList.isValid()) { 11351 // Uncommon, but possible. If a view is removed from the hierarchy during the call 11352 // to getDisplayList(), the display list will be marked invalid and we should not 11353 // try to use it again. 11354 displayList = null; 11355 hasDisplayList = false; 11356 } 11357 } 11358 11359 if (hasNoCache) { 11360 boolean layerRendered = false; 11361 if (layerType == LAYER_TYPE_HARDWARE) { 11362 final HardwareLayer layer = getHardwareLayer(); 11363 if (layer != null && layer.isValid()) { 11364 mLayerPaint.setAlpha((int) (alpha * 255)); 11365 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 11366 layerRendered = true; 11367 } else { 11368 final int scrollX = hasDisplayList ? 0 : sx; 11369 final int scrollY = hasDisplayList ? 0 : sy; 11370 canvas.saveLayer(scrollX, scrollY, 11371 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 11372 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 11373 } 11374 } 11375 11376 if (!layerRendered) { 11377 if (!hasDisplayList) { 11378 // Fast path for layouts with no backgrounds 11379 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 11380 if (ViewDebug.TRACE_HIERARCHY) { 11381 ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW); 11382 } 11383 mPrivateFlags &= ~DIRTY_MASK; 11384 dispatchDraw(canvas); 11385 } else { 11386 draw(canvas); 11387 } 11388 } else { 11389 mPrivateFlags &= ~DIRTY_MASK; 11390 ((HardwareCanvas) canvas).drawDisplayList(displayList, 11391 mRight - mLeft, mBottom - mTop, null, flags); 11392 } 11393 } 11394 } else if (cache != null) { 11395 mPrivateFlags &= ~DIRTY_MASK; 11396 Paint cachePaint; 11397 11398 if (layerType == LAYER_TYPE_NONE) { 11399 cachePaint = parent.mCachePaint; 11400 if (cachePaint == null) { 11401 cachePaint = new Paint(); 11402 cachePaint.setDither(false); 11403 parent.mCachePaint = cachePaint; 11404 } 11405 if (alpha < 1.0f) { 11406 cachePaint.setAlpha((int) (alpha * 255)); 11407 parent.mGroupFlags |= parent.FLAG_ALPHA_LOWER_THAN_ONE; 11408 } else if ((flags & parent.FLAG_ALPHA_LOWER_THAN_ONE) == 11409 parent.FLAG_ALPHA_LOWER_THAN_ONE) { 11410 cachePaint.setAlpha(255); 11411 parent.mGroupFlags &= ~parent.FLAG_ALPHA_LOWER_THAN_ONE; 11412 } 11413 } else { 11414 cachePaint = mLayerPaint; 11415 cachePaint.setAlpha((int) (alpha * 255)); 11416 } 11417 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 11418 } 11419 11420 canvas.restoreToCount(restoreTo); 11421 11422 if (a != null && !more) { 11423 if (!hardwareAccelerated && !a.getFillAfter()) { 11424 onSetAlpha(255); 11425 } 11426 parent.finishAnimatingView(this, a); 11427 } 11428 11429 if (more && hardwareAccelerated) { 11430 // invalidation is the trigger to recreate display lists, so if we're using 11431 // display lists to render, force an invalidate to allow the animation to 11432 // continue drawing another frame 11433 parent.invalidate(true); 11434 if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) { 11435 // alpha animations should cause the child to recreate its display list 11436 invalidate(true); 11437 } 11438 } 11439 11440 mRecreateDisplayList = false; 11441 11442 return more; 11443 } 11444 11445 /** 11446 * Manually render this view (and all of its children) to the given Canvas. 11447 * The view must have already done a full layout before this function is 11448 * called. When implementing a view, implement 11449 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 11450 * If you do need to override this method, call the superclass version. 11451 * 11452 * @param canvas The Canvas to which the View is rendered. 11453 */ 11454 public void draw(Canvas canvas) { 11455 if (ViewDebug.TRACE_HIERARCHY) { 11456 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 11457 } 11458 11459 final int privateFlags = mPrivateFlags; 11460 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 11461 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 11462 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 11463 11464 /* 11465 * Draw traversal performs several drawing steps which must be executed 11466 * in the appropriate order: 11467 * 11468 * 1. Draw the background 11469 * 2. If necessary, save the canvas' layers to prepare for fading 11470 * 3. Draw view's content 11471 * 4. Draw children 11472 * 5. If necessary, draw the fading edges and restore layers 11473 * 6. Draw decorations (scrollbars for instance) 11474 */ 11475 11476 // Step 1, draw the background, if needed 11477 int saveCount; 11478 11479 if (!dirtyOpaque) { 11480 final Drawable background = mBGDrawable; 11481 if (background != null) { 11482 final int scrollX = mScrollX; 11483 final int scrollY = mScrollY; 11484 11485 if (mBackgroundSizeChanged) { 11486 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 11487 mBackgroundSizeChanged = false; 11488 } 11489 11490 if ((scrollX | scrollY) == 0) { 11491 background.draw(canvas); 11492 } else { 11493 canvas.translate(scrollX, scrollY); 11494 background.draw(canvas); 11495 canvas.translate(-scrollX, -scrollY); 11496 } 11497 } 11498 } 11499 11500 // skip step 2 & 5 if possible (common case) 11501 final int viewFlags = mViewFlags; 11502 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 11503 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 11504 if (!verticalEdges && !horizontalEdges) { 11505 // Step 3, draw the content 11506 if (!dirtyOpaque) onDraw(canvas); 11507 11508 // Step 4, draw the children 11509 dispatchDraw(canvas); 11510 11511 // Step 6, draw decorations (scrollbars) 11512 onDrawScrollBars(canvas); 11513 11514 // we're done... 11515 return; 11516 } 11517 11518 /* 11519 * Here we do the full fledged routine... 11520 * (this is an uncommon case where speed matters less, 11521 * this is why we repeat some of the tests that have been 11522 * done above) 11523 */ 11524 11525 boolean drawTop = false; 11526 boolean drawBottom = false; 11527 boolean drawLeft = false; 11528 boolean drawRight = false; 11529 11530 float topFadeStrength = 0.0f; 11531 float bottomFadeStrength = 0.0f; 11532 float leftFadeStrength = 0.0f; 11533 float rightFadeStrength = 0.0f; 11534 11535 // Step 2, save the canvas' layers 11536 int paddingLeft = mPaddingLeft; 11537 11538 final boolean offsetRequired = isPaddingOffsetRequired(); 11539 if (offsetRequired) { 11540 paddingLeft += getLeftPaddingOffset(); 11541 } 11542 11543 int left = mScrollX + paddingLeft; 11544 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 11545 int top = mScrollY + getFadeTop(offsetRequired); 11546 int bottom = top + getFadeHeight(offsetRequired); 11547 11548 if (offsetRequired) { 11549 right += getRightPaddingOffset(); 11550 bottom += getBottomPaddingOffset(); 11551 } 11552 11553 final ScrollabilityCache scrollabilityCache = mScrollCache; 11554 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 11555 int length = (int) fadeHeight; 11556 11557 // clip the fade length if top and bottom fades overlap 11558 // overlapping fades produce odd-looking artifacts 11559 if (verticalEdges && (top + length > bottom - length)) { 11560 length = (bottom - top) / 2; 11561 } 11562 11563 // also clip horizontal fades if necessary 11564 if (horizontalEdges && (left + length > right - length)) { 11565 length = (right - left) / 2; 11566 } 11567 11568 if (verticalEdges) { 11569 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 11570 drawTop = topFadeStrength * fadeHeight > 1.0f; 11571 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 11572 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 11573 } 11574 11575 if (horizontalEdges) { 11576 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 11577 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 11578 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 11579 drawRight = rightFadeStrength * fadeHeight > 1.0f; 11580 } 11581 11582 saveCount = canvas.getSaveCount(); 11583 11584 int solidColor = getSolidColor(); 11585 if (solidColor == 0) { 11586 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 11587 11588 if (drawTop) { 11589 canvas.saveLayer(left, top, right, top + length, null, flags); 11590 } 11591 11592 if (drawBottom) { 11593 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 11594 } 11595 11596 if (drawLeft) { 11597 canvas.saveLayer(left, top, left + length, bottom, null, flags); 11598 } 11599 11600 if (drawRight) { 11601 canvas.saveLayer(right - length, top, right, bottom, null, flags); 11602 } 11603 } else { 11604 scrollabilityCache.setFadeColor(solidColor); 11605 } 11606 11607 // Step 3, draw the content 11608 if (!dirtyOpaque) onDraw(canvas); 11609 11610 // Step 4, draw the children 11611 dispatchDraw(canvas); 11612 11613 // Step 5, draw the fade effect and restore layers 11614 final Paint p = scrollabilityCache.paint; 11615 final Matrix matrix = scrollabilityCache.matrix; 11616 final Shader fade = scrollabilityCache.shader; 11617 11618 if (drawTop) { 11619 matrix.setScale(1, fadeHeight * topFadeStrength); 11620 matrix.postTranslate(left, top); 11621 fade.setLocalMatrix(matrix); 11622 canvas.drawRect(left, top, right, top + length, p); 11623 } 11624 11625 if (drawBottom) { 11626 matrix.setScale(1, fadeHeight * bottomFadeStrength); 11627 matrix.postRotate(180); 11628 matrix.postTranslate(left, bottom); 11629 fade.setLocalMatrix(matrix); 11630 canvas.drawRect(left, bottom - length, right, bottom, p); 11631 } 11632 11633 if (drawLeft) { 11634 matrix.setScale(1, fadeHeight * leftFadeStrength); 11635 matrix.postRotate(-90); 11636 matrix.postTranslate(left, top); 11637 fade.setLocalMatrix(matrix); 11638 canvas.drawRect(left, top, left + length, bottom, p); 11639 } 11640 11641 if (drawRight) { 11642 matrix.setScale(1, fadeHeight * rightFadeStrength); 11643 matrix.postRotate(90); 11644 matrix.postTranslate(right, top); 11645 fade.setLocalMatrix(matrix); 11646 canvas.drawRect(right - length, top, right, bottom, p); 11647 } 11648 11649 canvas.restoreToCount(saveCount); 11650 11651 // Step 6, draw decorations (scrollbars) 11652 onDrawScrollBars(canvas); 11653 } 11654 11655 /** 11656 * Override this if your view is known to always be drawn on top of a solid color background, 11657 * and needs to draw fading edges. Returning a non-zero color enables the view system to 11658 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 11659 * should be set to 0xFF. 11660 * 11661 * @see #setVerticalFadingEdgeEnabled(boolean) 11662 * @see #setHorizontalFadingEdgeEnabled(boolean) 11663 * 11664 * @return The known solid color background for this view, or 0 if the color may vary 11665 */ 11666 @ViewDebug.ExportedProperty(category = "drawing") 11667 public int getSolidColor() { 11668 return 0; 11669 } 11670 11671 /** 11672 * Build a human readable string representation of the specified view flags. 11673 * 11674 * @param flags the view flags to convert to a string 11675 * @return a String representing the supplied flags 11676 */ 11677 private static String printFlags(int flags) { 11678 String output = ""; 11679 int numFlags = 0; 11680 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 11681 output += "TAKES_FOCUS"; 11682 numFlags++; 11683 } 11684 11685 switch (flags & VISIBILITY_MASK) { 11686 case INVISIBLE: 11687 if (numFlags > 0) { 11688 output += " "; 11689 } 11690 output += "INVISIBLE"; 11691 // USELESS HERE numFlags++; 11692 break; 11693 case GONE: 11694 if (numFlags > 0) { 11695 output += " "; 11696 } 11697 output += "GONE"; 11698 // USELESS HERE numFlags++; 11699 break; 11700 default: 11701 break; 11702 } 11703 return output; 11704 } 11705 11706 /** 11707 * Build a human readable string representation of the specified private 11708 * view flags. 11709 * 11710 * @param privateFlags the private view flags to convert to a string 11711 * @return a String representing the supplied flags 11712 */ 11713 private static String printPrivateFlags(int privateFlags) { 11714 String output = ""; 11715 int numFlags = 0; 11716 11717 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 11718 output += "WANTS_FOCUS"; 11719 numFlags++; 11720 } 11721 11722 if ((privateFlags & FOCUSED) == FOCUSED) { 11723 if (numFlags > 0) { 11724 output += " "; 11725 } 11726 output += "FOCUSED"; 11727 numFlags++; 11728 } 11729 11730 if ((privateFlags & SELECTED) == SELECTED) { 11731 if (numFlags > 0) { 11732 output += " "; 11733 } 11734 output += "SELECTED"; 11735 numFlags++; 11736 } 11737 11738 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 11739 if (numFlags > 0) { 11740 output += " "; 11741 } 11742 output += "IS_ROOT_NAMESPACE"; 11743 numFlags++; 11744 } 11745 11746 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 11747 if (numFlags > 0) { 11748 output += " "; 11749 } 11750 output += "HAS_BOUNDS"; 11751 numFlags++; 11752 } 11753 11754 if ((privateFlags & DRAWN) == DRAWN) { 11755 if (numFlags > 0) { 11756 output += " "; 11757 } 11758 output += "DRAWN"; 11759 // USELESS HERE numFlags++; 11760 } 11761 return output; 11762 } 11763 11764 /** 11765 * <p>Indicates whether or not this view's layout will be requested during 11766 * the next hierarchy layout pass.</p> 11767 * 11768 * @return true if the layout will be forced during next layout pass 11769 */ 11770 public boolean isLayoutRequested() { 11771 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 11772 } 11773 11774 /** 11775 * Assign a size and position to a view and all of its 11776 * descendants 11777 * 11778 * <p>This is the second phase of the layout mechanism. 11779 * (The first is measuring). In this phase, each parent calls 11780 * layout on all of its children to position them. 11781 * This is typically done using the child measurements 11782 * that were stored in the measure pass().</p> 11783 * 11784 * <p>Derived classes should not override this method. 11785 * Derived classes with children should override 11786 * onLayout. In that method, they should 11787 * call layout on each of their children.</p> 11788 * 11789 * @param l Left position, relative to parent 11790 * @param t Top position, relative to parent 11791 * @param r Right position, relative to parent 11792 * @param b Bottom position, relative to parent 11793 */ 11794 @SuppressWarnings({"unchecked"}) 11795 public void layout(int l, int t, int r, int b) { 11796 int oldL = mLeft; 11797 int oldT = mTop; 11798 int oldB = mBottom; 11799 int oldR = mRight; 11800 boolean changed = setFrame(l, t, r, b); 11801 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 11802 if (ViewDebug.TRACE_HIERARCHY) { 11803 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 11804 } 11805 11806 onLayout(changed, l, t, r, b); 11807 mPrivateFlags &= ~LAYOUT_REQUIRED; 11808 11809 ListenerInfo li = mListenerInfo; 11810 if (li != null && li.mOnLayoutChangeListeners != null) { 11811 ArrayList<OnLayoutChangeListener> listenersCopy = 11812 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 11813 int numListeners = listenersCopy.size(); 11814 for (int i = 0; i < numListeners; ++i) { 11815 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 11816 } 11817 } 11818 } 11819 mPrivateFlags &= ~FORCE_LAYOUT; 11820 } 11821 11822 /** 11823 * Called from layout when this view should 11824 * assign a size and position to each of its children. 11825 * 11826 * Derived classes with children should override 11827 * this method and call layout on each of 11828 * their children. 11829 * @param changed This is a new size or position for this view 11830 * @param left Left position, relative to parent 11831 * @param top Top position, relative to parent 11832 * @param right Right position, relative to parent 11833 * @param bottom Bottom position, relative to parent 11834 */ 11835 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 11836 } 11837 11838 /** 11839 * Assign a size and position to this view. 11840 * 11841 * This is called from layout. 11842 * 11843 * @param left Left position, relative to parent 11844 * @param top Top position, relative to parent 11845 * @param right Right position, relative to parent 11846 * @param bottom Bottom position, relative to parent 11847 * @return true if the new size and position are different than the 11848 * previous ones 11849 * {@hide} 11850 */ 11851 protected boolean setFrame(int left, int top, int right, int bottom) { 11852 boolean changed = false; 11853 11854 if (DBG) { 11855 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 11856 + right + "," + bottom + ")"); 11857 } 11858 11859 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 11860 changed = true; 11861 11862 // Remember our drawn bit 11863 int drawn = mPrivateFlags & DRAWN; 11864 11865 int oldWidth = mRight - mLeft; 11866 int oldHeight = mBottom - mTop; 11867 int newWidth = right - left; 11868 int newHeight = bottom - top; 11869 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 11870 11871 // Invalidate our old position 11872 invalidate(sizeChanged); 11873 11874 mLeft = left; 11875 mTop = top; 11876 mRight = right; 11877 mBottom = bottom; 11878 11879 mPrivateFlags |= HAS_BOUNDS; 11880 11881 11882 if (sizeChanged) { 11883 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 11884 // A change in dimension means an auto-centered pivot point changes, too 11885 if (mTransformationInfo != null) { 11886 mTransformationInfo.mMatrixDirty = true; 11887 } 11888 } 11889 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 11890 } 11891 11892 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 11893 // If we are visible, force the DRAWN bit to on so that 11894 // this invalidate will go through (at least to our parent). 11895 // This is because someone may have invalidated this view 11896 // before this call to setFrame came in, thereby clearing 11897 // the DRAWN bit. 11898 mPrivateFlags |= DRAWN; 11899 invalidate(sizeChanged); 11900 // parent display list may need to be recreated based on a change in the bounds 11901 // of any child 11902 invalidateParentCaches(); 11903 } 11904 11905 // Reset drawn bit to original value (invalidate turns it off) 11906 mPrivateFlags |= drawn; 11907 11908 mBackgroundSizeChanged = true; 11909 } 11910 return changed; 11911 } 11912 11913 /** 11914 * Finalize inflating a view from XML. This is called as the last phase 11915 * of inflation, after all child views have been added. 11916 * 11917 * <p>Even if the subclass overrides onFinishInflate, they should always be 11918 * sure to call the super method, so that we get called. 11919 */ 11920 protected void onFinishInflate() { 11921 } 11922 11923 /** 11924 * Returns the resources associated with this view. 11925 * 11926 * @return Resources object. 11927 */ 11928 public Resources getResources() { 11929 return mResources; 11930 } 11931 11932 /** 11933 * Invalidates the specified Drawable. 11934 * 11935 * @param drawable the drawable to invalidate 11936 */ 11937 public void invalidateDrawable(Drawable drawable) { 11938 if (verifyDrawable(drawable)) { 11939 final Rect dirty = drawable.getBounds(); 11940 final int scrollX = mScrollX; 11941 final int scrollY = mScrollY; 11942 11943 invalidate(dirty.left + scrollX, dirty.top + scrollY, 11944 dirty.right + scrollX, dirty.bottom + scrollY); 11945 } 11946 } 11947 11948 /** 11949 * Schedules an action on a drawable to occur at a specified time. 11950 * 11951 * @param who the recipient of the action 11952 * @param what the action to run on the drawable 11953 * @param when the time at which the action must occur. Uses the 11954 * {@link SystemClock#uptimeMillis} timebase. 11955 */ 11956 public void scheduleDrawable(Drawable who, Runnable what, long when) { 11957 if (verifyDrawable(who) && what != null) { 11958 final long delay = when - SystemClock.uptimeMillis(); 11959 if (mAttachInfo != null) { 11960 mAttachInfo.mViewRootImpl.mChoreographer.postAnimationCallbackDelayed( 11961 what, who, Choreographer.subtractFrameDelay(delay)); 11962 } else { 11963 ViewRootImpl.getRunQueue().postDelayed(what, delay); 11964 } 11965 } 11966 } 11967 11968 /** 11969 * Cancels a scheduled action on a drawable. 11970 * 11971 * @param who the recipient of the action 11972 * @param what the action to cancel 11973 */ 11974 public void unscheduleDrawable(Drawable who, Runnable what) { 11975 if (verifyDrawable(who) && what != null) { 11976 if (mAttachInfo != null) { 11977 mAttachInfo.mViewRootImpl.mChoreographer.removeAnimationCallbacks(what, who); 11978 } else { 11979 ViewRootImpl.getRunQueue().removeCallbacks(what); 11980 } 11981 } 11982 } 11983 11984 /** 11985 * Unschedule any events associated with the given Drawable. This can be 11986 * used when selecting a new Drawable into a view, so that the previous 11987 * one is completely unscheduled. 11988 * 11989 * @param who The Drawable to unschedule. 11990 * 11991 * @see #drawableStateChanged 11992 */ 11993 public void unscheduleDrawable(Drawable who) { 11994 if (mAttachInfo != null && who != null) { 11995 mAttachInfo.mViewRootImpl.mChoreographer.removeAnimationCallbacks(null, who); 11996 } 11997 } 11998 11999 /** 12000 * Return the layout direction of a given Drawable. 12001 * 12002 * @param who the Drawable to query 12003 */ 12004 public int getResolvedLayoutDirection(Drawable who) { 12005 return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT; 12006 } 12007 12008 /** 12009 * If your view subclass is displaying its own Drawable objects, it should 12010 * override this function and return true for any Drawable it is 12011 * displaying. This allows animations for those drawables to be 12012 * scheduled. 12013 * 12014 * <p>Be sure to call through to the super class when overriding this 12015 * function. 12016 * 12017 * @param who The Drawable to verify. Return true if it is one you are 12018 * displaying, else return the result of calling through to the 12019 * super class. 12020 * 12021 * @return boolean If true than the Drawable is being displayed in the 12022 * view; else false and it is not allowed to animate. 12023 * 12024 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 12025 * @see #drawableStateChanged() 12026 */ 12027 protected boolean verifyDrawable(Drawable who) { 12028 return who == mBGDrawable; 12029 } 12030 12031 /** 12032 * This function is called whenever the state of the view changes in such 12033 * a way that it impacts the state of drawables being shown. 12034 * 12035 * <p>Be sure to call through to the superclass when overriding this 12036 * function. 12037 * 12038 * @see Drawable#setState(int[]) 12039 */ 12040 protected void drawableStateChanged() { 12041 Drawable d = mBGDrawable; 12042 if (d != null && d.isStateful()) { 12043 d.setState(getDrawableState()); 12044 } 12045 } 12046 12047 /** 12048 * Call this to force a view to update its drawable state. This will cause 12049 * drawableStateChanged to be called on this view. Views that are interested 12050 * in the new state should call getDrawableState. 12051 * 12052 * @see #drawableStateChanged 12053 * @see #getDrawableState 12054 */ 12055 public void refreshDrawableState() { 12056 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 12057 drawableStateChanged(); 12058 12059 ViewParent parent = mParent; 12060 if (parent != null) { 12061 parent.childDrawableStateChanged(this); 12062 } 12063 } 12064 12065 /** 12066 * Return an array of resource IDs of the drawable states representing the 12067 * current state of the view. 12068 * 12069 * @return The current drawable state 12070 * 12071 * @see Drawable#setState(int[]) 12072 * @see #drawableStateChanged() 12073 * @see #onCreateDrawableState(int) 12074 */ 12075 public final int[] getDrawableState() { 12076 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 12077 return mDrawableState; 12078 } else { 12079 mDrawableState = onCreateDrawableState(0); 12080 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 12081 return mDrawableState; 12082 } 12083 } 12084 12085 /** 12086 * Generate the new {@link android.graphics.drawable.Drawable} state for 12087 * this view. This is called by the view 12088 * system when the cached Drawable state is determined to be invalid. To 12089 * retrieve the current state, you should use {@link #getDrawableState}. 12090 * 12091 * @param extraSpace if non-zero, this is the number of extra entries you 12092 * would like in the returned array in which you can place your own 12093 * states. 12094 * 12095 * @return Returns an array holding the current {@link Drawable} state of 12096 * the view. 12097 * 12098 * @see #mergeDrawableStates(int[], int[]) 12099 */ 12100 protected int[] onCreateDrawableState(int extraSpace) { 12101 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 12102 mParent instanceof View) { 12103 return ((View) mParent).onCreateDrawableState(extraSpace); 12104 } 12105 12106 int[] drawableState; 12107 12108 int privateFlags = mPrivateFlags; 12109 12110 int viewStateIndex = 0; 12111 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 12112 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 12113 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 12114 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 12115 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 12116 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 12117 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 12118 HardwareRenderer.isAvailable()) { 12119 // This is set if HW acceleration is requested, even if the current 12120 // process doesn't allow it. This is just to allow app preview 12121 // windows to better match their app. 12122 viewStateIndex |= VIEW_STATE_ACCELERATED; 12123 } 12124 if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 12125 12126 final int privateFlags2 = mPrivateFlags2; 12127 if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 12128 if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 12129 12130 drawableState = VIEW_STATE_SETS[viewStateIndex]; 12131 12132 //noinspection ConstantIfStatement 12133 if (false) { 12134 Log.i("View", "drawableStateIndex=" + viewStateIndex); 12135 Log.i("View", toString() 12136 + " pressed=" + ((privateFlags & PRESSED) != 0) 12137 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 12138 + " fo=" + hasFocus() 12139 + " sl=" + ((privateFlags & SELECTED) != 0) 12140 + " wf=" + hasWindowFocus() 12141 + ": " + Arrays.toString(drawableState)); 12142 } 12143 12144 if (extraSpace == 0) { 12145 return drawableState; 12146 } 12147 12148 final int[] fullState; 12149 if (drawableState != null) { 12150 fullState = new int[drawableState.length + extraSpace]; 12151 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 12152 } else { 12153 fullState = new int[extraSpace]; 12154 } 12155 12156 return fullState; 12157 } 12158 12159 /** 12160 * Merge your own state values in <var>additionalState</var> into the base 12161 * state values <var>baseState</var> that were returned by 12162 * {@link #onCreateDrawableState(int)}. 12163 * 12164 * @param baseState The base state values returned by 12165 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 12166 * own additional state values. 12167 * 12168 * @param additionalState The additional state values you would like 12169 * added to <var>baseState</var>; this array is not modified. 12170 * 12171 * @return As a convenience, the <var>baseState</var> array you originally 12172 * passed into the function is returned. 12173 * 12174 * @see #onCreateDrawableState(int) 12175 */ 12176 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 12177 final int N = baseState.length; 12178 int i = N - 1; 12179 while (i >= 0 && baseState[i] == 0) { 12180 i--; 12181 } 12182 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 12183 return baseState; 12184 } 12185 12186 /** 12187 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 12188 * on all Drawable objects associated with this view. 12189 */ 12190 public void jumpDrawablesToCurrentState() { 12191 if (mBGDrawable != null) { 12192 mBGDrawable.jumpToCurrentState(); 12193 } 12194 } 12195 12196 /** 12197 * Sets the background color for this view. 12198 * @param color the color of the background 12199 */ 12200 @RemotableViewMethod 12201 public void setBackgroundColor(int color) { 12202 if (mBGDrawable instanceof ColorDrawable) { 12203 ((ColorDrawable) mBGDrawable).setColor(color); 12204 } else { 12205 setBackgroundDrawable(new ColorDrawable(color)); 12206 } 12207 } 12208 12209 /** 12210 * Set the background to a given resource. The resource should refer to 12211 * a Drawable object or 0 to remove the background. 12212 * @param resid The identifier of the resource. 12213 * @attr ref android.R.styleable#View_background 12214 */ 12215 @RemotableViewMethod 12216 public void setBackgroundResource(int resid) { 12217 if (resid != 0 && resid == mBackgroundResource) { 12218 return; 12219 } 12220 12221 Drawable d= null; 12222 if (resid != 0) { 12223 d = mResources.getDrawable(resid); 12224 } 12225 setBackgroundDrawable(d); 12226 12227 mBackgroundResource = resid; 12228 } 12229 12230 /** 12231 * Set the background to a given Drawable, or remove the background. If the 12232 * background has padding, this View's padding is set to the background's 12233 * padding. However, when a background is removed, this View's padding isn't 12234 * touched. If setting the padding is desired, please use 12235 * {@link #setPadding(int, int, int, int)}. 12236 * 12237 * @param d The Drawable to use as the background, or null to remove the 12238 * background 12239 */ 12240 public void setBackgroundDrawable(Drawable d) { 12241 if (d == mBGDrawable) { 12242 return; 12243 } 12244 12245 boolean requestLayout = false; 12246 12247 mBackgroundResource = 0; 12248 12249 /* 12250 * Regardless of whether we're setting a new background or not, we want 12251 * to clear the previous drawable. 12252 */ 12253 if (mBGDrawable != null) { 12254 mBGDrawable.setCallback(null); 12255 unscheduleDrawable(mBGDrawable); 12256 } 12257 12258 if (d != null) { 12259 Rect padding = sThreadLocal.get(); 12260 if (padding == null) { 12261 padding = new Rect(); 12262 sThreadLocal.set(padding); 12263 } 12264 if (d.getPadding(padding)) { 12265 switch (d.getResolvedLayoutDirectionSelf()) { 12266 case LAYOUT_DIRECTION_RTL: 12267 setPadding(padding.right, padding.top, padding.left, padding.bottom); 12268 break; 12269 case LAYOUT_DIRECTION_LTR: 12270 default: 12271 setPadding(padding.left, padding.top, padding.right, padding.bottom); 12272 } 12273 } 12274 12275 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 12276 // if it has a different minimum size, we should layout again 12277 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 12278 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 12279 requestLayout = true; 12280 } 12281 12282 d.setCallback(this); 12283 if (d.isStateful()) { 12284 d.setState(getDrawableState()); 12285 } 12286 d.setVisible(getVisibility() == VISIBLE, false); 12287 mBGDrawable = d; 12288 12289 if ((mPrivateFlags & SKIP_DRAW) != 0) { 12290 mPrivateFlags &= ~SKIP_DRAW; 12291 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 12292 requestLayout = true; 12293 } 12294 } else { 12295 /* Remove the background */ 12296 mBGDrawable = null; 12297 12298 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 12299 /* 12300 * This view ONLY drew the background before and we're removing 12301 * the background, so now it won't draw anything 12302 * (hence we SKIP_DRAW) 12303 */ 12304 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 12305 mPrivateFlags |= SKIP_DRAW; 12306 } 12307 12308 /* 12309 * When the background is set, we try to apply its padding to this 12310 * View. When the background is removed, we don't touch this View's 12311 * padding. This is noted in the Javadocs. Hence, we don't need to 12312 * requestLayout(), the invalidate() below is sufficient. 12313 */ 12314 12315 // The old background's minimum size could have affected this 12316 // View's layout, so let's requestLayout 12317 requestLayout = true; 12318 } 12319 12320 computeOpaqueFlags(); 12321 12322 if (requestLayout) { 12323 requestLayout(); 12324 } 12325 12326 mBackgroundSizeChanged = true; 12327 invalidate(true); 12328 } 12329 12330 /** 12331 * Gets the background drawable 12332 * @return The drawable used as the background for this view, if any. 12333 */ 12334 public Drawable getBackground() { 12335 return mBGDrawable; 12336 } 12337 12338 /** 12339 * Sets the padding. The view may add on the space required to display 12340 * the scrollbars, depending on the style and visibility of the scrollbars. 12341 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 12342 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 12343 * from the values set in this call. 12344 * 12345 * @attr ref android.R.styleable#View_padding 12346 * @attr ref android.R.styleable#View_paddingBottom 12347 * @attr ref android.R.styleable#View_paddingLeft 12348 * @attr ref android.R.styleable#View_paddingRight 12349 * @attr ref android.R.styleable#View_paddingTop 12350 * @param left the left padding in pixels 12351 * @param top the top padding in pixels 12352 * @param right the right padding in pixels 12353 * @param bottom the bottom padding in pixels 12354 */ 12355 public void setPadding(int left, int top, int right, int bottom) { 12356 mUserPaddingStart = -1; 12357 mUserPaddingEnd = -1; 12358 mUserPaddingRelative = false; 12359 12360 internalSetPadding(left, top, right, bottom); 12361 } 12362 12363 private void internalSetPadding(int left, int top, int right, int bottom) { 12364 mUserPaddingLeft = left; 12365 mUserPaddingRight = right; 12366 mUserPaddingBottom = bottom; 12367 12368 final int viewFlags = mViewFlags; 12369 boolean changed = false; 12370 12371 // Common case is there are no scroll bars. 12372 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 12373 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 12374 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 12375 ? 0 : getVerticalScrollbarWidth(); 12376 switch (mVerticalScrollbarPosition) { 12377 case SCROLLBAR_POSITION_DEFAULT: 12378 if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12379 left += offset; 12380 } else { 12381 right += offset; 12382 } 12383 break; 12384 case SCROLLBAR_POSITION_RIGHT: 12385 right += offset; 12386 break; 12387 case SCROLLBAR_POSITION_LEFT: 12388 left += offset; 12389 break; 12390 } 12391 } 12392 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 12393 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 12394 ? 0 : getHorizontalScrollbarHeight(); 12395 } 12396 } 12397 12398 if (mPaddingLeft != left) { 12399 changed = true; 12400 mPaddingLeft = left; 12401 } 12402 if (mPaddingTop != top) { 12403 changed = true; 12404 mPaddingTop = top; 12405 } 12406 if (mPaddingRight != right) { 12407 changed = true; 12408 mPaddingRight = right; 12409 } 12410 if (mPaddingBottom != bottom) { 12411 changed = true; 12412 mPaddingBottom = bottom; 12413 } 12414 12415 if (changed) { 12416 requestLayout(); 12417 } 12418 } 12419 12420 /** 12421 * Sets the relative padding. The view may add on the space required to display 12422 * the scrollbars, depending on the style and visibility of the scrollbars. 12423 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 12424 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 12425 * from the values set in this call. 12426 * 12427 * @attr ref android.R.styleable#View_padding 12428 * @attr ref android.R.styleable#View_paddingBottom 12429 * @attr ref android.R.styleable#View_paddingStart 12430 * @attr ref android.R.styleable#View_paddingEnd 12431 * @attr ref android.R.styleable#View_paddingTop 12432 * @param start the start padding in pixels 12433 * @param top the top padding in pixels 12434 * @param end the end padding in pixels 12435 * @param bottom the bottom padding in pixels 12436 */ 12437 public void setPaddingRelative(int start, int top, int end, int bottom) { 12438 mUserPaddingStart = start; 12439 mUserPaddingEnd = end; 12440 mUserPaddingRelative = true; 12441 12442 switch(getResolvedLayoutDirection()) { 12443 case LAYOUT_DIRECTION_RTL: 12444 internalSetPadding(end, top, start, bottom); 12445 break; 12446 case LAYOUT_DIRECTION_LTR: 12447 default: 12448 internalSetPadding(start, top, end, bottom); 12449 } 12450 } 12451 12452 /** 12453 * Returns the top padding of this view. 12454 * 12455 * @return the top padding in pixels 12456 */ 12457 public int getPaddingTop() { 12458 return mPaddingTop; 12459 } 12460 12461 /** 12462 * Returns the bottom padding of this view. If there are inset and enabled 12463 * scrollbars, this value may include the space required to display the 12464 * scrollbars as well. 12465 * 12466 * @return the bottom padding in pixels 12467 */ 12468 public int getPaddingBottom() { 12469 return mPaddingBottom; 12470 } 12471 12472 /** 12473 * Returns the left padding of this view. If there are inset and enabled 12474 * scrollbars, this value may include the space required to display the 12475 * scrollbars as well. 12476 * 12477 * @return the left padding in pixels 12478 */ 12479 public int getPaddingLeft() { 12480 return mPaddingLeft; 12481 } 12482 12483 /** 12484 * Returns the start padding of this view. If there are inset and enabled 12485 * scrollbars, this value may include the space required to display the 12486 * scrollbars as well. 12487 * 12488 * @return the start padding in pixels 12489 */ 12490 public int getPaddingStart() { 12491 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 12492 mPaddingRight : mPaddingLeft; 12493 } 12494 12495 /** 12496 * Returns the right padding of this view. If there are inset and enabled 12497 * scrollbars, this value may include the space required to display the 12498 * scrollbars as well. 12499 * 12500 * @return the right padding in pixels 12501 */ 12502 public int getPaddingRight() { 12503 return mPaddingRight; 12504 } 12505 12506 /** 12507 * Returns the end padding of this view. If there are inset and enabled 12508 * scrollbars, this value may include the space required to display the 12509 * scrollbars as well. 12510 * 12511 * @return the end padding in pixels 12512 */ 12513 public int getPaddingEnd() { 12514 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 12515 mPaddingLeft : mPaddingRight; 12516 } 12517 12518 /** 12519 * Return if the padding as been set thru relative values 12520 * {@link #setPaddingRelative(int, int, int, int)} or thru 12521 * @attr ref android.R.styleable#View_paddingStart or 12522 * @attr ref android.R.styleable#View_paddingEnd 12523 * 12524 * @return true if the padding is relative or false if it is not. 12525 */ 12526 public boolean isPaddingRelative() { 12527 return mUserPaddingRelative; 12528 } 12529 12530 /** 12531 * Changes the selection state of this view. A view can be selected or not. 12532 * Note that selection is not the same as focus. Views are typically 12533 * selected in the context of an AdapterView like ListView or GridView; 12534 * the selected view is the view that is highlighted. 12535 * 12536 * @param selected true if the view must be selected, false otherwise 12537 */ 12538 public void setSelected(boolean selected) { 12539 if (((mPrivateFlags & SELECTED) != 0) != selected) { 12540 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 12541 if (!selected) resetPressedState(); 12542 invalidate(true); 12543 refreshDrawableState(); 12544 dispatchSetSelected(selected); 12545 } 12546 } 12547 12548 /** 12549 * Dispatch setSelected to all of this View's children. 12550 * 12551 * @see #setSelected(boolean) 12552 * 12553 * @param selected The new selected state 12554 */ 12555 protected void dispatchSetSelected(boolean selected) { 12556 } 12557 12558 /** 12559 * Indicates the selection state of this view. 12560 * 12561 * @return true if the view is selected, false otherwise 12562 */ 12563 @ViewDebug.ExportedProperty 12564 public boolean isSelected() { 12565 return (mPrivateFlags & SELECTED) != 0; 12566 } 12567 12568 /** 12569 * Changes the activated state of this view. A view can be activated or not. 12570 * Note that activation is not the same as selection. Selection is 12571 * a transient property, representing the view (hierarchy) the user is 12572 * currently interacting with. Activation is a longer-term state that the 12573 * user can move views in and out of. For example, in a list view with 12574 * single or multiple selection enabled, the views in the current selection 12575 * set are activated. (Um, yeah, we are deeply sorry about the terminology 12576 * here.) The activated state is propagated down to children of the view it 12577 * is set on. 12578 * 12579 * @param activated true if the view must be activated, false otherwise 12580 */ 12581 public void setActivated(boolean activated) { 12582 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 12583 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 12584 invalidate(true); 12585 refreshDrawableState(); 12586 dispatchSetActivated(activated); 12587 } 12588 } 12589 12590 /** 12591 * Dispatch setActivated to all of this View's children. 12592 * 12593 * @see #setActivated(boolean) 12594 * 12595 * @param activated The new activated state 12596 */ 12597 protected void dispatchSetActivated(boolean activated) { 12598 } 12599 12600 /** 12601 * Indicates the activation state of this view. 12602 * 12603 * @return true if the view is activated, false otherwise 12604 */ 12605 @ViewDebug.ExportedProperty 12606 public boolean isActivated() { 12607 return (mPrivateFlags & ACTIVATED) != 0; 12608 } 12609 12610 /** 12611 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 12612 * observer can be used to get notifications when global events, like 12613 * layout, happen. 12614 * 12615 * The returned ViewTreeObserver observer is not guaranteed to remain 12616 * valid for the lifetime of this View. If the caller of this method keeps 12617 * a long-lived reference to ViewTreeObserver, it should always check for 12618 * the return value of {@link ViewTreeObserver#isAlive()}. 12619 * 12620 * @return The ViewTreeObserver for this view's hierarchy. 12621 */ 12622 public ViewTreeObserver getViewTreeObserver() { 12623 if (mAttachInfo != null) { 12624 return mAttachInfo.mTreeObserver; 12625 } 12626 if (mFloatingTreeObserver == null) { 12627 mFloatingTreeObserver = new ViewTreeObserver(); 12628 } 12629 return mFloatingTreeObserver; 12630 } 12631 12632 /** 12633 * <p>Finds the topmost view in the current view hierarchy.</p> 12634 * 12635 * @return the topmost view containing this view 12636 */ 12637 public View getRootView() { 12638 if (mAttachInfo != null) { 12639 final View v = mAttachInfo.mRootView; 12640 if (v != null) { 12641 return v; 12642 } 12643 } 12644 12645 View parent = this; 12646 12647 while (parent.mParent != null && parent.mParent instanceof View) { 12648 parent = (View) parent.mParent; 12649 } 12650 12651 return parent; 12652 } 12653 12654 /** 12655 * <p>Computes the coordinates of this view on the screen. The argument 12656 * must be an array of two integers. After the method returns, the array 12657 * contains the x and y location in that order.</p> 12658 * 12659 * @param location an array of two integers in which to hold the coordinates 12660 */ 12661 public void getLocationOnScreen(int[] location) { 12662 getLocationInWindow(location); 12663 12664 final AttachInfo info = mAttachInfo; 12665 if (info != null) { 12666 location[0] += info.mWindowLeft; 12667 location[1] += info.mWindowTop; 12668 } 12669 } 12670 12671 /** 12672 * <p>Computes the coordinates of this view in its window. The argument 12673 * must be an array of two integers. After the method returns, the array 12674 * contains the x and y location in that order.</p> 12675 * 12676 * @param location an array of two integers in which to hold the coordinates 12677 */ 12678 public void getLocationInWindow(int[] location) { 12679 if (location == null || location.length < 2) { 12680 throw new IllegalArgumentException("location must be an array of two integers"); 12681 } 12682 12683 if (mAttachInfo == null) { 12684 // When the view is not attached to a window, this method does not make sense 12685 location[0] = location[1] = 0; 12686 return; 12687 } 12688 12689 float[] position = mAttachInfo.mTmpTransformLocation; 12690 position[0] = position[1] = 0.0f; 12691 12692 if (!hasIdentityMatrix()) { 12693 getMatrix().mapPoints(position); 12694 } 12695 12696 position[0] += mLeft; 12697 position[1] += mTop; 12698 12699 ViewParent viewParent = mParent; 12700 while (viewParent instanceof View) { 12701 final View view = (View) viewParent; 12702 12703 position[0] -= view.mScrollX; 12704 position[1] -= view.mScrollY; 12705 12706 if (!view.hasIdentityMatrix()) { 12707 view.getMatrix().mapPoints(position); 12708 } 12709 12710 position[0] += view.mLeft; 12711 position[1] += view.mTop; 12712 12713 viewParent = view.mParent; 12714 } 12715 12716 if (viewParent instanceof ViewRootImpl) { 12717 // *cough* 12718 final ViewRootImpl vr = (ViewRootImpl) viewParent; 12719 position[1] -= vr.mCurScrollY; 12720 } 12721 12722 location[0] = (int) (position[0] + 0.5f); 12723 location[1] = (int) (position[1] + 0.5f); 12724 } 12725 12726 /** 12727 * {@hide} 12728 * @param id the id of the view to be found 12729 * @return the view of the specified id, null if cannot be found 12730 */ 12731 protected View findViewTraversal(int id) { 12732 if (id == mID) { 12733 return this; 12734 } 12735 return null; 12736 } 12737 12738 /** 12739 * {@hide} 12740 * @param tag the tag of the view to be found 12741 * @return the view of specified tag, null if cannot be found 12742 */ 12743 protected View findViewWithTagTraversal(Object tag) { 12744 if (tag != null && tag.equals(mTag)) { 12745 return this; 12746 } 12747 return null; 12748 } 12749 12750 /** 12751 * {@hide} 12752 * @param predicate The predicate to evaluate. 12753 * @param childToSkip If not null, ignores this child during the recursive traversal. 12754 * @return The first view that matches the predicate or null. 12755 */ 12756 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 12757 if (predicate.apply(this)) { 12758 return this; 12759 } 12760 return null; 12761 } 12762 12763 /** 12764 * Look for a child view with the given id. If this view has the given 12765 * id, return this view. 12766 * 12767 * @param id The id to search for. 12768 * @return The view that has the given id in the hierarchy or null 12769 */ 12770 public final View findViewById(int id) { 12771 if (id < 0) { 12772 return null; 12773 } 12774 return findViewTraversal(id); 12775 } 12776 12777 /** 12778 * Finds a view by its unuque and stable accessibility id. 12779 * 12780 * @param accessibilityId The searched accessibility id. 12781 * @return The found view. 12782 */ 12783 final View findViewByAccessibilityId(int accessibilityId) { 12784 if (accessibilityId < 0) { 12785 return null; 12786 } 12787 return findViewByAccessibilityIdTraversal(accessibilityId); 12788 } 12789 12790 /** 12791 * Performs the traversal to find a view by its unuque and stable accessibility id. 12792 * 12793 * <strong>Note:</strong>This method does not stop at the root namespace 12794 * boundary since the user can touch the screen at an arbitrary location 12795 * potentially crossing the root namespace bounday which will send an 12796 * accessibility event to accessibility services and they should be able 12797 * to obtain the event source. Also accessibility ids are guaranteed to be 12798 * unique in the window. 12799 * 12800 * @param accessibilityId The accessibility id. 12801 * @return The found view. 12802 */ 12803 View findViewByAccessibilityIdTraversal(int accessibilityId) { 12804 if (getAccessibilityViewId() == accessibilityId) { 12805 return this; 12806 } 12807 return null; 12808 } 12809 12810 /** 12811 * Look for a child view with the given tag. If this view has the given 12812 * tag, return this view. 12813 * 12814 * @param tag The tag to search for, using "tag.equals(getTag())". 12815 * @return The View that has the given tag in the hierarchy or null 12816 */ 12817 public final View findViewWithTag(Object tag) { 12818 if (tag == null) { 12819 return null; 12820 } 12821 return findViewWithTagTraversal(tag); 12822 } 12823 12824 /** 12825 * {@hide} 12826 * Look for a child view that matches the specified predicate. 12827 * If this view matches the predicate, return this view. 12828 * 12829 * @param predicate The predicate to evaluate. 12830 * @return The first view that matches the predicate or null. 12831 */ 12832 public final View findViewByPredicate(Predicate<View> predicate) { 12833 return findViewByPredicateTraversal(predicate, null); 12834 } 12835 12836 /** 12837 * {@hide} 12838 * Look for a child view that matches the specified predicate, 12839 * starting with the specified view and its descendents and then 12840 * recusively searching the ancestors and siblings of that view 12841 * until this view is reached. 12842 * 12843 * This method is useful in cases where the predicate does not match 12844 * a single unique view (perhaps multiple views use the same id) 12845 * and we are trying to find the view that is "closest" in scope to the 12846 * starting view. 12847 * 12848 * @param start The view to start from. 12849 * @param predicate The predicate to evaluate. 12850 * @return The first view that matches the predicate or null. 12851 */ 12852 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 12853 View childToSkip = null; 12854 for (;;) { 12855 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 12856 if (view != null || start == this) { 12857 return view; 12858 } 12859 12860 ViewParent parent = start.getParent(); 12861 if (parent == null || !(parent instanceof View)) { 12862 return null; 12863 } 12864 12865 childToSkip = start; 12866 start = (View) parent; 12867 } 12868 } 12869 12870 /** 12871 * Sets the identifier for this view. The identifier does not have to be 12872 * unique in this view's hierarchy. The identifier should be a positive 12873 * number. 12874 * 12875 * @see #NO_ID 12876 * @see #getId() 12877 * @see #findViewById(int) 12878 * 12879 * @param id a number used to identify the view 12880 * 12881 * @attr ref android.R.styleable#View_id 12882 */ 12883 public void setId(int id) { 12884 mID = id; 12885 } 12886 12887 /** 12888 * {@hide} 12889 * 12890 * @param isRoot true if the view belongs to the root namespace, false 12891 * otherwise 12892 */ 12893 public void setIsRootNamespace(boolean isRoot) { 12894 if (isRoot) { 12895 mPrivateFlags |= IS_ROOT_NAMESPACE; 12896 } else { 12897 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 12898 } 12899 } 12900 12901 /** 12902 * {@hide} 12903 * 12904 * @return true if the view belongs to the root namespace, false otherwise 12905 */ 12906 public boolean isRootNamespace() { 12907 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 12908 } 12909 12910 /** 12911 * Returns this view's identifier. 12912 * 12913 * @return a positive integer used to identify the view or {@link #NO_ID} 12914 * if the view has no ID 12915 * 12916 * @see #setId(int) 12917 * @see #findViewById(int) 12918 * @attr ref android.R.styleable#View_id 12919 */ 12920 @ViewDebug.CapturedViewProperty 12921 public int getId() { 12922 return mID; 12923 } 12924 12925 /** 12926 * Returns this view's tag. 12927 * 12928 * @return the Object stored in this view as a tag 12929 * 12930 * @see #setTag(Object) 12931 * @see #getTag(int) 12932 */ 12933 @ViewDebug.ExportedProperty 12934 public Object getTag() { 12935 return mTag; 12936 } 12937 12938 /** 12939 * Sets the tag associated with this view. A tag can be used to mark 12940 * a view in its hierarchy and does not have to be unique within the 12941 * hierarchy. Tags can also be used to store data within a view without 12942 * resorting to another data structure. 12943 * 12944 * @param tag an Object to tag the view with 12945 * 12946 * @see #getTag() 12947 * @see #setTag(int, Object) 12948 */ 12949 public void setTag(final Object tag) { 12950 mTag = tag; 12951 } 12952 12953 /** 12954 * Returns the tag associated with this view and the specified key. 12955 * 12956 * @param key The key identifying the tag 12957 * 12958 * @return the Object stored in this view as a tag 12959 * 12960 * @see #setTag(int, Object) 12961 * @see #getTag() 12962 */ 12963 public Object getTag(int key) { 12964 if (mKeyedTags != null) return mKeyedTags.get(key); 12965 return null; 12966 } 12967 12968 /** 12969 * Sets a tag associated with this view and a key. A tag can be used 12970 * to mark a view in its hierarchy and does not have to be unique within 12971 * the hierarchy. Tags can also be used to store data within a view 12972 * without resorting to another data structure. 12973 * 12974 * The specified key should be an id declared in the resources of the 12975 * application to ensure it is unique (see the <a 12976 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 12977 * Keys identified as belonging to 12978 * the Android framework or not associated with any package will cause 12979 * an {@link IllegalArgumentException} to be thrown. 12980 * 12981 * @param key The key identifying the tag 12982 * @param tag An Object to tag the view with 12983 * 12984 * @throws IllegalArgumentException If they specified key is not valid 12985 * 12986 * @see #setTag(Object) 12987 * @see #getTag(int) 12988 */ 12989 public void setTag(int key, final Object tag) { 12990 // If the package id is 0x00 or 0x01, it's either an undefined package 12991 // or a framework id 12992 if ((key >>> 24) < 2) { 12993 throw new IllegalArgumentException("The key must be an application-specific " 12994 + "resource id."); 12995 } 12996 12997 setKeyedTag(key, tag); 12998 } 12999 13000 /** 13001 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 13002 * framework id. 13003 * 13004 * @hide 13005 */ 13006 public void setTagInternal(int key, Object tag) { 13007 if ((key >>> 24) != 0x1) { 13008 throw new IllegalArgumentException("The key must be a framework-specific " 13009 + "resource id."); 13010 } 13011 13012 setKeyedTag(key, tag); 13013 } 13014 13015 private void setKeyedTag(int key, Object tag) { 13016 if (mKeyedTags == null) { 13017 mKeyedTags = new SparseArray<Object>(); 13018 } 13019 13020 mKeyedTags.put(key, tag); 13021 } 13022 13023 /** 13024 * @param consistency The type of consistency. See ViewDebug for more information. 13025 * 13026 * @hide 13027 */ 13028 protected boolean dispatchConsistencyCheck(int consistency) { 13029 return onConsistencyCheck(consistency); 13030 } 13031 13032 /** 13033 * Method that subclasses should implement to check their consistency. The type of 13034 * consistency check is indicated by the bit field passed as a parameter. 13035 * 13036 * @param consistency The type of consistency. See ViewDebug for more information. 13037 * 13038 * @throws IllegalStateException if the view is in an inconsistent state. 13039 * 13040 * @hide 13041 */ 13042 protected boolean onConsistencyCheck(int consistency) { 13043 boolean result = true; 13044 13045 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 13046 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 13047 13048 if (checkLayout) { 13049 if (getParent() == null) { 13050 result = false; 13051 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 13052 "View " + this + " does not have a parent."); 13053 } 13054 13055 if (mAttachInfo == null) { 13056 result = false; 13057 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 13058 "View " + this + " is not attached to a window."); 13059 } 13060 } 13061 13062 if (checkDrawing) { 13063 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 13064 // from their draw() method 13065 13066 if ((mPrivateFlags & DRAWN) != DRAWN && 13067 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 13068 result = false; 13069 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 13070 "View " + this + " was invalidated but its drawing cache is valid."); 13071 } 13072 } 13073 13074 return result; 13075 } 13076 13077 /** 13078 * Prints information about this view in the log output, with the tag 13079 * {@link #VIEW_LOG_TAG}. 13080 * 13081 * @hide 13082 */ 13083 public void debug() { 13084 debug(0); 13085 } 13086 13087 /** 13088 * Prints information about this view in the log output, with the tag 13089 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 13090 * indentation defined by the <code>depth</code>. 13091 * 13092 * @param depth the indentation level 13093 * 13094 * @hide 13095 */ 13096 protected void debug(int depth) { 13097 String output = debugIndent(depth - 1); 13098 13099 output += "+ " + this; 13100 int id = getId(); 13101 if (id != -1) { 13102 output += " (id=" + id + ")"; 13103 } 13104 Object tag = getTag(); 13105 if (tag != null) { 13106 output += " (tag=" + tag + ")"; 13107 } 13108 Log.d(VIEW_LOG_TAG, output); 13109 13110 if ((mPrivateFlags & FOCUSED) != 0) { 13111 output = debugIndent(depth) + " FOCUSED"; 13112 Log.d(VIEW_LOG_TAG, output); 13113 } 13114 13115 output = debugIndent(depth); 13116 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 13117 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 13118 + "} "; 13119 Log.d(VIEW_LOG_TAG, output); 13120 13121 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 13122 || mPaddingBottom != 0) { 13123 output = debugIndent(depth); 13124 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 13125 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 13126 Log.d(VIEW_LOG_TAG, output); 13127 } 13128 13129 output = debugIndent(depth); 13130 output += "mMeasureWidth=" + mMeasuredWidth + 13131 " mMeasureHeight=" + mMeasuredHeight; 13132 Log.d(VIEW_LOG_TAG, output); 13133 13134 output = debugIndent(depth); 13135 if (mLayoutParams == null) { 13136 output += "BAD! no layout params"; 13137 } else { 13138 output = mLayoutParams.debug(output); 13139 } 13140 Log.d(VIEW_LOG_TAG, output); 13141 13142 output = debugIndent(depth); 13143 output += "flags={"; 13144 output += View.printFlags(mViewFlags); 13145 output += "}"; 13146 Log.d(VIEW_LOG_TAG, output); 13147 13148 output = debugIndent(depth); 13149 output += "privateFlags={"; 13150 output += View.printPrivateFlags(mPrivateFlags); 13151 output += "}"; 13152 Log.d(VIEW_LOG_TAG, output); 13153 } 13154 13155 /** 13156 * Creates a string of whitespaces used for indentation. 13157 * 13158 * @param depth the indentation level 13159 * @return a String containing (depth * 2 + 3) * 2 white spaces 13160 * 13161 * @hide 13162 */ 13163 protected static String debugIndent(int depth) { 13164 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 13165 for (int i = 0; i < (depth * 2) + 3; i++) { 13166 spaces.append(' ').append(' '); 13167 } 13168 return spaces.toString(); 13169 } 13170 13171 /** 13172 * <p>Return the offset of the widget's text baseline from the widget's top 13173 * boundary. If this widget does not support baseline alignment, this 13174 * method returns -1. </p> 13175 * 13176 * @return the offset of the baseline within the widget's bounds or -1 13177 * if baseline alignment is not supported 13178 */ 13179 @ViewDebug.ExportedProperty(category = "layout") 13180 public int getBaseline() { 13181 return -1; 13182 } 13183 13184 /** 13185 * Call this when something has changed which has invalidated the 13186 * layout of this view. This will schedule a layout pass of the view 13187 * tree. 13188 */ 13189 public void requestLayout() { 13190 if (ViewDebug.TRACE_HIERARCHY) { 13191 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 13192 } 13193 13194 mPrivateFlags |= FORCE_LAYOUT; 13195 mPrivateFlags |= INVALIDATED; 13196 13197 if (mParent != null) { 13198 if (mLayoutParams != null) { 13199 mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection()); 13200 } 13201 if (!mParent.isLayoutRequested()) { 13202 mParent.requestLayout(); 13203 } 13204 } 13205 } 13206 13207 /** 13208 * Forces this view to be laid out during the next layout pass. 13209 * This method does not call requestLayout() or forceLayout() 13210 * on the parent. 13211 */ 13212 public void forceLayout() { 13213 mPrivateFlags |= FORCE_LAYOUT; 13214 mPrivateFlags |= INVALIDATED; 13215 } 13216 13217 /** 13218 * <p> 13219 * This is called to find out how big a view should be. The parent 13220 * supplies constraint information in the width and height parameters. 13221 * </p> 13222 * 13223 * <p> 13224 * The actual measurement work of a view is performed in 13225 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 13226 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 13227 * </p> 13228 * 13229 * 13230 * @param widthMeasureSpec Horizontal space requirements as imposed by the 13231 * parent 13232 * @param heightMeasureSpec Vertical space requirements as imposed by the 13233 * parent 13234 * 13235 * @see #onMeasure(int, int) 13236 */ 13237 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 13238 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 13239 widthMeasureSpec != mOldWidthMeasureSpec || 13240 heightMeasureSpec != mOldHeightMeasureSpec) { 13241 13242 // first clears the measured dimension flag 13243 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 13244 13245 if (ViewDebug.TRACE_HIERARCHY) { 13246 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 13247 } 13248 13249 // measure ourselves, this should set the measured dimension flag back 13250 onMeasure(widthMeasureSpec, heightMeasureSpec); 13251 13252 // flag not set, setMeasuredDimension() was not invoked, we raise 13253 // an exception to warn the developer 13254 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 13255 throw new IllegalStateException("onMeasure() did not set the" 13256 + " measured dimension by calling" 13257 + " setMeasuredDimension()"); 13258 } 13259 13260 mPrivateFlags |= LAYOUT_REQUIRED; 13261 } 13262 13263 mOldWidthMeasureSpec = widthMeasureSpec; 13264 mOldHeightMeasureSpec = heightMeasureSpec; 13265 } 13266 13267 /** 13268 * <p> 13269 * Measure the view and its content to determine the measured width and the 13270 * measured height. This method is invoked by {@link #measure(int, int)} and 13271 * should be overriden by subclasses to provide accurate and efficient 13272 * measurement of their contents. 13273 * </p> 13274 * 13275 * <p> 13276 * <strong>CONTRACT:</strong> When overriding this method, you 13277 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 13278 * measured width and height of this view. Failure to do so will trigger an 13279 * <code>IllegalStateException</code>, thrown by 13280 * {@link #measure(int, int)}. Calling the superclass' 13281 * {@link #onMeasure(int, int)} is a valid use. 13282 * </p> 13283 * 13284 * <p> 13285 * The base class implementation of measure defaults to the background size, 13286 * unless a larger size is allowed by the MeasureSpec. Subclasses should 13287 * override {@link #onMeasure(int, int)} to provide better measurements of 13288 * their content. 13289 * </p> 13290 * 13291 * <p> 13292 * If this method is overridden, it is the subclass's responsibility to make 13293 * sure the measured height and width are at least the view's minimum height 13294 * and width ({@link #getSuggestedMinimumHeight()} and 13295 * {@link #getSuggestedMinimumWidth()}). 13296 * </p> 13297 * 13298 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 13299 * The requirements are encoded with 13300 * {@link android.view.View.MeasureSpec}. 13301 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 13302 * The requirements are encoded with 13303 * {@link android.view.View.MeasureSpec}. 13304 * 13305 * @see #getMeasuredWidth() 13306 * @see #getMeasuredHeight() 13307 * @see #setMeasuredDimension(int, int) 13308 * @see #getSuggestedMinimumHeight() 13309 * @see #getSuggestedMinimumWidth() 13310 * @see android.view.View.MeasureSpec#getMode(int) 13311 * @see android.view.View.MeasureSpec#getSize(int) 13312 */ 13313 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 13314 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 13315 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 13316 } 13317 13318 /** 13319 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 13320 * measured width and measured height. Failing to do so will trigger an 13321 * exception at measurement time.</p> 13322 * 13323 * @param measuredWidth The measured width of this view. May be a complex 13324 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 13325 * {@link #MEASURED_STATE_TOO_SMALL}. 13326 * @param measuredHeight The measured height of this view. May be a complex 13327 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 13328 * {@link #MEASURED_STATE_TOO_SMALL}. 13329 */ 13330 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 13331 mMeasuredWidth = measuredWidth; 13332 mMeasuredHeight = measuredHeight; 13333 13334 mPrivateFlags |= MEASURED_DIMENSION_SET; 13335 } 13336 13337 /** 13338 * Merge two states as returned by {@link #getMeasuredState()}. 13339 * @param curState The current state as returned from a view or the result 13340 * of combining multiple views. 13341 * @param newState The new view state to combine. 13342 * @return Returns a new integer reflecting the combination of the two 13343 * states. 13344 */ 13345 public static int combineMeasuredStates(int curState, int newState) { 13346 return curState | newState; 13347 } 13348 13349 /** 13350 * Version of {@link #resolveSizeAndState(int, int, int)} 13351 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 13352 */ 13353 public static int resolveSize(int size, int measureSpec) { 13354 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 13355 } 13356 13357 /** 13358 * Utility to reconcile a desired size and state, with constraints imposed 13359 * by a MeasureSpec. Will take the desired size, unless a different size 13360 * is imposed by the constraints. The returned value is a compound integer, 13361 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 13362 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 13363 * size is smaller than the size the view wants to be. 13364 * 13365 * @param size How big the view wants to be 13366 * @param measureSpec Constraints imposed by the parent 13367 * @return Size information bit mask as defined by 13368 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 13369 */ 13370 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 13371 int result = size; 13372 int specMode = MeasureSpec.getMode(measureSpec); 13373 int specSize = MeasureSpec.getSize(measureSpec); 13374 switch (specMode) { 13375 case MeasureSpec.UNSPECIFIED: 13376 result = size; 13377 break; 13378 case MeasureSpec.AT_MOST: 13379 if (specSize < size) { 13380 result = specSize | MEASURED_STATE_TOO_SMALL; 13381 } else { 13382 result = size; 13383 } 13384 break; 13385 case MeasureSpec.EXACTLY: 13386 result = specSize; 13387 break; 13388 } 13389 return result | (childMeasuredState&MEASURED_STATE_MASK); 13390 } 13391 13392 /** 13393 * Utility to return a default size. Uses the supplied size if the 13394 * MeasureSpec imposed no constraints. Will get larger if allowed 13395 * by the MeasureSpec. 13396 * 13397 * @param size Default size for this view 13398 * @param measureSpec Constraints imposed by the parent 13399 * @return The size this view should be. 13400 */ 13401 public static int getDefaultSize(int size, int measureSpec) { 13402 int result = size; 13403 int specMode = MeasureSpec.getMode(measureSpec); 13404 int specSize = MeasureSpec.getSize(measureSpec); 13405 13406 switch (specMode) { 13407 case MeasureSpec.UNSPECIFIED: 13408 result = size; 13409 break; 13410 case MeasureSpec.AT_MOST: 13411 case MeasureSpec.EXACTLY: 13412 result = specSize; 13413 break; 13414 } 13415 return result; 13416 } 13417 13418 /** 13419 * Returns the suggested minimum height that the view should use. This 13420 * returns the maximum of the view's minimum height 13421 * and the background's minimum height 13422 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 13423 * <p> 13424 * When being used in {@link #onMeasure(int, int)}, the caller should still 13425 * ensure the returned height is within the requirements of the parent. 13426 * 13427 * @return The suggested minimum height of the view. 13428 */ 13429 protected int getSuggestedMinimumHeight() { 13430 int suggestedMinHeight = mMinHeight; 13431 13432 if (mBGDrawable != null) { 13433 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 13434 if (suggestedMinHeight < bgMinHeight) { 13435 suggestedMinHeight = bgMinHeight; 13436 } 13437 } 13438 13439 return suggestedMinHeight; 13440 } 13441 13442 /** 13443 * Returns the suggested minimum width that the view should use. This 13444 * returns the maximum of the view's minimum width) 13445 * and the background's minimum width 13446 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 13447 * <p> 13448 * When being used in {@link #onMeasure(int, int)}, the caller should still 13449 * ensure the returned width is within the requirements of the parent. 13450 * 13451 * @return The suggested minimum width of the view. 13452 */ 13453 protected int getSuggestedMinimumWidth() { 13454 int suggestedMinWidth = mMinWidth; 13455 13456 if (mBGDrawable != null) { 13457 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 13458 if (suggestedMinWidth < bgMinWidth) { 13459 suggestedMinWidth = bgMinWidth; 13460 } 13461 } 13462 13463 return suggestedMinWidth; 13464 } 13465 13466 /** 13467 * Sets the minimum height of the view. It is not guaranteed the view will 13468 * be able to achieve this minimum height (for example, if its parent layout 13469 * constrains it with less available height). 13470 * 13471 * @param minHeight The minimum height the view will try to be. 13472 */ 13473 public void setMinimumHeight(int minHeight) { 13474 mMinHeight = minHeight; 13475 } 13476 13477 /** 13478 * Sets the minimum width of the view. It is not guaranteed the view will 13479 * be able to achieve this minimum width (for example, if its parent layout 13480 * constrains it with less available width). 13481 * 13482 * @param minWidth The minimum width the view will try to be. 13483 */ 13484 public void setMinimumWidth(int minWidth) { 13485 mMinWidth = minWidth; 13486 } 13487 13488 /** 13489 * Get the animation currently associated with this view. 13490 * 13491 * @return The animation that is currently playing or 13492 * scheduled to play for this view. 13493 */ 13494 public Animation getAnimation() { 13495 return mCurrentAnimation; 13496 } 13497 13498 /** 13499 * Start the specified animation now. 13500 * 13501 * @param animation the animation to start now 13502 */ 13503 public void startAnimation(Animation animation) { 13504 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 13505 setAnimation(animation); 13506 invalidateParentCaches(); 13507 invalidate(true); 13508 } 13509 13510 /** 13511 * Cancels any animations for this view. 13512 */ 13513 public void clearAnimation() { 13514 if (mCurrentAnimation != null) { 13515 mCurrentAnimation.detach(); 13516 } 13517 mCurrentAnimation = null; 13518 invalidateParentIfNeeded(); 13519 } 13520 13521 /** 13522 * Sets the next animation to play for this view. 13523 * If you want the animation to play immediately, use 13524 * startAnimation. This method provides allows fine-grained 13525 * control over the start time and invalidation, but you 13526 * must make sure that 1) the animation has a start time set, and 13527 * 2) the view will be invalidated when the animation is supposed to 13528 * start. 13529 * 13530 * @param animation The next animation, or null. 13531 */ 13532 public void setAnimation(Animation animation) { 13533 mCurrentAnimation = animation; 13534 if (animation != null) { 13535 animation.reset(); 13536 } 13537 } 13538 13539 /** 13540 * Invoked by a parent ViewGroup to notify the start of the animation 13541 * currently associated with this view. If you override this method, 13542 * always call super.onAnimationStart(); 13543 * 13544 * @see #setAnimation(android.view.animation.Animation) 13545 * @see #getAnimation() 13546 */ 13547 protected void onAnimationStart() { 13548 mPrivateFlags |= ANIMATION_STARTED; 13549 } 13550 13551 /** 13552 * Invoked by a parent ViewGroup to notify the end of the animation 13553 * currently associated with this view. If you override this method, 13554 * always call super.onAnimationEnd(); 13555 * 13556 * @see #setAnimation(android.view.animation.Animation) 13557 * @see #getAnimation() 13558 */ 13559 protected void onAnimationEnd() { 13560 mPrivateFlags &= ~ANIMATION_STARTED; 13561 } 13562 13563 /** 13564 * Invoked if there is a Transform that involves alpha. Subclass that can 13565 * draw themselves with the specified alpha should return true, and then 13566 * respect that alpha when their onDraw() is called. If this returns false 13567 * then the view may be redirected to draw into an offscreen buffer to 13568 * fulfill the request, which will look fine, but may be slower than if the 13569 * subclass handles it internally. The default implementation returns false. 13570 * 13571 * @param alpha The alpha (0..255) to apply to the view's drawing 13572 * @return true if the view can draw with the specified alpha. 13573 */ 13574 protected boolean onSetAlpha(int alpha) { 13575 return false; 13576 } 13577 13578 /** 13579 * This is used by the RootView to perform an optimization when 13580 * the view hierarchy contains one or several SurfaceView. 13581 * SurfaceView is always considered transparent, but its children are not, 13582 * therefore all View objects remove themselves from the global transparent 13583 * region (passed as a parameter to this function). 13584 * 13585 * @param region The transparent region for this ViewAncestor (window). 13586 * 13587 * @return Returns true if the effective visibility of the view at this 13588 * point is opaque, regardless of the transparent region; returns false 13589 * if it is possible for underlying windows to be seen behind the view. 13590 * 13591 * {@hide} 13592 */ 13593 public boolean gatherTransparentRegion(Region region) { 13594 final AttachInfo attachInfo = mAttachInfo; 13595 if (region != null && attachInfo != null) { 13596 final int pflags = mPrivateFlags; 13597 if ((pflags & SKIP_DRAW) == 0) { 13598 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 13599 // remove it from the transparent region. 13600 final int[] location = attachInfo.mTransparentLocation; 13601 getLocationInWindow(location); 13602 region.op(location[0], location[1], location[0] + mRight - mLeft, 13603 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 13604 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 13605 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 13606 // exists, so we remove the background drawable's non-transparent 13607 // parts from this transparent region. 13608 applyDrawableToTransparentRegion(mBGDrawable, region); 13609 } 13610 } 13611 return true; 13612 } 13613 13614 /** 13615 * Play a sound effect for this view. 13616 * 13617 * <p>The framework will play sound effects for some built in actions, such as 13618 * clicking, but you may wish to play these effects in your widget, 13619 * for instance, for internal navigation. 13620 * 13621 * <p>The sound effect will only be played if sound effects are enabled by the user, and 13622 * {@link #isSoundEffectsEnabled()} is true. 13623 * 13624 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 13625 */ 13626 public void playSoundEffect(int soundConstant) { 13627 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 13628 return; 13629 } 13630 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 13631 } 13632 13633 /** 13634 * BZZZTT!!1! 13635 * 13636 * <p>Provide haptic feedback to the user for this view. 13637 * 13638 * <p>The framework will provide haptic feedback for some built in actions, 13639 * such as long presses, but you may wish to provide feedback for your 13640 * own widget. 13641 * 13642 * <p>The feedback will only be performed if 13643 * {@link #isHapticFeedbackEnabled()} is true. 13644 * 13645 * @param feedbackConstant One of the constants defined in 13646 * {@link HapticFeedbackConstants} 13647 */ 13648 public boolean performHapticFeedback(int feedbackConstant) { 13649 return performHapticFeedback(feedbackConstant, 0); 13650 } 13651 13652 /** 13653 * BZZZTT!!1! 13654 * 13655 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 13656 * 13657 * @param feedbackConstant One of the constants defined in 13658 * {@link HapticFeedbackConstants} 13659 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 13660 */ 13661 public boolean performHapticFeedback(int feedbackConstant, int flags) { 13662 if (mAttachInfo == null) { 13663 return false; 13664 } 13665 //noinspection SimplifiableIfStatement 13666 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 13667 && !isHapticFeedbackEnabled()) { 13668 return false; 13669 } 13670 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 13671 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 13672 } 13673 13674 /** 13675 * Request that the visibility of the status bar be changed. 13676 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 13677 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 13678 */ 13679 public void setSystemUiVisibility(int visibility) { 13680 if (visibility != mSystemUiVisibility) { 13681 mSystemUiVisibility = visibility; 13682 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 13683 mParent.recomputeViewAttributes(this); 13684 } 13685 } 13686 } 13687 13688 /** 13689 * Returns the status bar visibility that this view has requested. 13690 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 13691 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 13692 */ 13693 public int getSystemUiVisibility() { 13694 return mSystemUiVisibility; 13695 } 13696 13697 /** 13698 * Set a listener to receive callbacks when the visibility of the system bar changes. 13699 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 13700 */ 13701 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 13702 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 13703 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 13704 mParent.recomputeViewAttributes(this); 13705 } 13706 } 13707 13708 /** 13709 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 13710 * the view hierarchy. 13711 */ 13712 public void dispatchSystemUiVisibilityChanged(int visibility) { 13713 ListenerInfo li = mListenerInfo; 13714 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 13715 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 13716 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 13717 } 13718 } 13719 13720 void updateLocalSystemUiVisibility(int localValue, int localChanges) { 13721 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 13722 if (val != mSystemUiVisibility) { 13723 setSystemUiVisibility(val); 13724 } 13725 } 13726 13727 /** 13728 * Creates an image that the system displays during the drag and drop 13729 * operation. This is called a "drag shadow". The default implementation 13730 * for a DragShadowBuilder based on a View returns an image that has exactly the same 13731 * appearance as the given View. The default also positions the center of the drag shadow 13732 * directly under the touch point. If no View is provided (the constructor with no parameters 13733 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 13734 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 13735 * default is an invisible drag shadow. 13736 * <p> 13737 * You are not required to use the View you provide to the constructor as the basis of the 13738 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 13739 * anything you want as the drag shadow. 13740 * </p> 13741 * <p> 13742 * You pass a DragShadowBuilder object to the system when you start the drag. The system 13743 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 13744 * size and position of the drag shadow. It uses this data to construct a 13745 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 13746 * so that your application can draw the shadow image in the Canvas. 13747 * </p> 13748 * 13749 * <div class="special reference"> 13750 * <h3>Developer Guides</h3> 13751 * <p>For a guide to implementing drag and drop features, read the 13752 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 13753 * </div> 13754 */ 13755 public static class DragShadowBuilder { 13756 private final WeakReference<View> mView; 13757 13758 /** 13759 * Constructs a shadow image builder based on a View. By default, the resulting drag 13760 * shadow will have the same appearance and dimensions as the View, with the touch point 13761 * over the center of the View. 13762 * @param view A View. Any View in scope can be used. 13763 */ 13764 public DragShadowBuilder(View view) { 13765 mView = new WeakReference<View>(view); 13766 } 13767 13768 /** 13769 * Construct a shadow builder object with no associated View. This 13770 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 13771 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 13772 * to supply the drag shadow's dimensions and appearance without 13773 * reference to any View object. If they are not overridden, then the result is an 13774 * invisible drag shadow. 13775 */ 13776 public DragShadowBuilder() { 13777 mView = new WeakReference<View>(null); 13778 } 13779 13780 /** 13781 * Returns the View object that had been passed to the 13782 * {@link #View.DragShadowBuilder(View)} 13783 * constructor. If that View parameter was {@code null} or if the 13784 * {@link #View.DragShadowBuilder()} 13785 * constructor was used to instantiate the builder object, this method will return 13786 * null. 13787 * 13788 * @return The View object associate with this builder object. 13789 */ 13790 @SuppressWarnings({"JavadocReference"}) 13791 final public View getView() { 13792 return mView.get(); 13793 } 13794 13795 /** 13796 * Provides the metrics for the shadow image. These include the dimensions of 13797 * the shadow image, and the point within that shadow that should 13798 * be centered under the touch location while dragging. 13799 * <p> 13800 * The default implementation sets the dimensions of the shadow to be the 13801 * same as the dimensions of the View itself and centers the shadow under 13802 * the touch point. 13803 * </p> 13804 * 13805 * @param shadowSize A {@link android.graphics.Point} containing the width and height 13806 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 13807 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 13808 * image. 13809 * 13810 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 13811 * shadow image that should be underneath the touch point during the drag and drop 13812 * operation. Your application must set {@link android.graphics.Point#x} to the 13813 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 13814 */ 13815 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 13816 final View view = mView.get(); 13817 if (view != null) { 13818 shadowSize.set(view.getWidth(), view.getHeight()); 13819 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 13820 } else { 13821 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 13822 } 13823 } 13824 13825 /** 13826 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 13827 * based on the dimensions it received from the 13828 * {@link #onProvideShadowMetrics(Point, Point)} callback. 13829 * 13830 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 13831 */ 13832 public void onDrawShadow(Canvas canvas) { 13833 final View view = mView.get(); 13834 if (view != null) { 13835 view.draw(canvas); 13836 } else { 13837 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 13838 } 13839 } 13840 } 13841 13842 /** 13843 * Starts a drag and drop operation. When your application calls this method, it passes a 13844 * {@link android.view.View.DragShadowBuilder} object to the system. The 13845 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 13846 * to get metrics for the drag shadow, and then calls the object's 13847 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 13848 * <p> 13849 * Once the system has the drag shadow, it begins the drag and drop operation by sending 13850 * drag events to all the View objects in your application that are currently visible. It does 13851 * this either by calling the View object's drag listener (an implementation of 13852 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 13853 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 13854 * Both are passed a {@link android.view.DragEvent} object that has a 13855 * {@link android.view.DragEvent#getAction()} value of 13856 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 13857 * </p> 13858 * <p> 13859 * Your application can invoke startDrag() on any attached View object. The View object does not 13860 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 13861 * be related to the View the user selected for dragging. 13862 * </p> 13863 * @param data A {@link android.content.ClipData} object pointing to the data to be 13864 * transferred by the drag and drop operation. 13865 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 13866 * drag shadow. 13867 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 13868 * drop operation. This Object is put into every DragEvent object sent by the system during the 13869 * current drag. 13870 * <p> 13871 * myLocalState is a lightweight mechanism for the sending information from the dragged View 13872 * to the target Views. For example, it can contain flags that differentiate between a 13873 * a copy operation and a move operation. 13874 * </p> 13875 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 13876 * so the parameter should be set to 0. 13877 * @return {@code true} if the method completes successfully, or 13878 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 13879 * do a drag, and so no drag operation is in progress. 13880 */ 13881 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 13882 Object myLocalState, int flags) { 13883 if (ViewDebug.DEBUG_DRAG) { 13884 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 13885 } 13886 boolean okay = false; 13887 13888 Point shadowSize = new Point(); 13889 Point shadowTouchPoint = new Point(); 13890 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 13891 13892 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 13893 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 13894 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 13895 } 13896 13897 if (ViewDebug.DEBUG_DRAG) { 13898 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 13899 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 13900 } 13901 Surface surface = new Surface(); 13902 try { 13903 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 13904 flags, shadowSize.x, shadowSize.y, surface); 13905 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 13906 + " surface=" + surface); 13907 if (token != null) { 13908 Canvas canvas = surface.lockCanvas(null); 13909 try { 13910 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 13911 shadowBuilder.onDrawShadow(canvas); 13912 } finally { 13913 surface.unlockCanvasAndPost(canvas); 13914 } 13915 13916 final ViewRootImpl root = getViewRootImpl(); 13917 13918 // Cache the local state object for delivery with DragEvents 13919 root.setLocalDragState(myLocalState); 13920 13921 // repurpose 'shadowSize' for the last touch point 13922 root.getLastTouchPoint(shadowSize); 13923 13924 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 13925 shadowSize.x, shadowSize.y, 13926 shadowTouchPoint.x, shadowTouchPoint.y, data); 13927 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 13928 13929 // Off and running! Release our local surface instance; the drag 13930 // shadow surface is now managed by the system process. 13931 surface.release(); 13932 } 13933 } catch (Exception e) { 13934 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 13935 surface.destroy(); 13936 } 13937 13938 return okay; 13939 } 13940 13941 /** 13942 * Handles drag events sent by the system following a call to 13943 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 13944 *<p> 13945 * When the system calls this method, it passes a 13946 * {@link android.view.DragEvent} object. A call to 13947 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 13948 * in DragEvent. The method uses these to determine what is happening in the drag and drop 13949 * operation. 13950 * @param event The {@link android.view.DragEvent} sent by the system. 13951 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 13952 * in DragEvent, indicating the type of drag event represented by this object. 13953 * @return {@code true} if the method was successful, otherwise {@code false}. 13954 * <p> 13955 * The method should return {@code true} in response to an action type of 13956 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 13957 * operation. 13958 * </p> 13959 * <p> 13960 * The method should also return {@code true} in response to an action type of 13961 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 13962 * {@code false} if it didn't. 13963 * </p> 13964 */ 13965 public boolean onDragEvent(DragEvent event) { 13966 return false; 13967 } 13968 13969 /** 13970 * Detects if this View is enabled and has a drag event listener. 13971 * If both are true, then it calls the drag event listener with the 13972 * {@link android.view.DragEvent} it received. If the drag event listener returns 13973 * {@code true}, then dispatchDragEvent() returns {@code true}. 13974 * <p> 13975 * For all other cases, the method calls the 13976 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 13977 * method and returns its result. 13978 * </p> 13979 * <p> 13980 * This ensures that a drag event is always consumed, even if the View does not have a drag 13981 * event listener. However, if the View has a listener and the listener returns true, then 13982 * onDragEvent() is not called. 13983 * </p> 13984 */ 13985 public boolean dispatchDragEvent(DragEvent event) { 13986 //noinspection SimplifiableIfStatement 13987 ListenerInfo li = mListenerInfo; 13988 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 13989 && li.mOnDragListener.onDrag(this, event)) { 13990 return true; 13991 } 13992 return onDragEvent(event); 13993 } 13994 13995 boolean canAcceptDrag() { 13996 return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0; 13997 } 13998 13999 /** 14000 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 14001 * it is ever exposed at all. 14002 * @hide 14003 */ 14004 public void onCloseSystemDialogs(String reason) { 14005 } 14006 14007 /** 14008 * Given a Drawable whose bounds have been set to draw into this view, 14009 * update a Region being computed for 14010 * {@link #gatherTransparentRegion(android.graphics.Region)} so 14011 * that any non-transparent parts of the Drawable are removed from the 14012 * given transparent region. 14013 * 14014 * @param dr The Drawable whose transparency is to be applied to the region. 14015 * @param region A Region holding the current transparency information, 14016 * where any parts of the region that are set are considered to be 14017 * transparent. On return, this region will be modified to have the 14018 * transparency information reduced by the corresponding parts of the 14019 * Drawable that are not transparent. 14020 * {@hide} 14021 */ 14022 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 14023 if (DBG) { 14024 Log.i("View", "Getting transparent region for: " + this); 14025 } 14026 final Region r = dr.getTransparentRegion(); 14027 final Rect db = dr.getBounds(); 14028 final AttachInfo attachInfo = mAttachInfo; 14029 if (r != null && attachInfo != null) { 14030 final int w = getRight()-getLeft(); 14031 final int h = getBottom()-getTop(); 14032 if (db.left > 0) { 14033 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 14034 r.op(0, 0, db.left, h, Region.Op.UNION); 14035 } 14036 if (db.right < w) { 14037 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 14038 r.op(db.right, 0, w, h, Region.Op.UNION); 14039 } 14040 if (db.top > 0) { 14041 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 14042 r.op(0, 0, w, db.top, Region.Op.UNION); 14043 } 14044 if (db.bottom < h) { 14045 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 14046 r.op(0, db.bottom, w, h, Region.Op.UNION); 14047 } 14048 final int[] location = attachInfo.mTransparentLocation; 14049 getLocationInWindow(location); 14050 r.translate(location[0], location[1]); 14051 region.op(r, Region.Op.INTERSECT); 14052 } else { 14053 region.op(db, Region.Op.DIFFERENCE); 14054 } 14055 } 14056 14057 private void checkForLongClick(int delayOffset) { 14058 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 14059 mHasPerformedLongPress = false; 14060 14061 if (mPendingCheckForLongPress == null) { 14062 mPendingCheckForLongPress = new CheckForLongPress(); 14063 } 14064 mPendingCheckForLongPress.rememberWindowAttachCount(); 14065 postDelayed(mPendingCheckForLongPress, 14066 ViewConfiguration.getLongPressTimeout() - delayOffset); 14067 } 14068 } 14069 14070 /** 14071 * Inflate a view from an XML resource. This convenience method wraps the {@link 14072 * LayoutInflater} class, which provides a full range of options for view inflation. 14073 * 14074 * @param context The Context object for your activity or application. 14075 * @param resource The resource ID to inflate 14076 * @param root A view group that will be the parent. Used to properly inflate the 14077 * layout_* parameters. 14078 * @see LayoutInflater 14079 */ 14080 public static View inflate(Context context, int resource, ViewGroup root) { 14081 LayoutInflater factory = LayoutInflater.from(context); 14082 return factory.inflate(resource, root); 14083 } 14084 14085 /** 14086 * Scroll the view with standard behavior for scrolling beyond the normal 14087 * content boundaries. Views that call this method should override 14088 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 14089 * results of an over-scroll operation. 14090 * 14091 * Views can use this method to handle any touch or fling-based scrolling. 14092 * 14093 * @param deltaX Change in X in pixels 14094 * @param deltaY Change in Y in pixels 14095 * @param scrollX Current X scroll value in pixels before applying deltaX 14096 * @param scrollY Current Y scroll value in pixels before applying deltaY 14097 * @param scrollRangeX Maximum content scroll range along the X axis 14098 * @param scrollRangeY Maximum content scroll range along the Y axis 14099 * @param maxOverScrollX Number of pixels to overscroll by in either direction 14100 * along the X axis. 14101 * @param maxOverScrollY Number of pixels to overscroll by in either direction 14102 * along the Y axis. 14103 * @param isTouchEvent true if this scroll operation is the result of a touch event. 14104 * @return true if scrolling was clamped to an over-scroll boundary along either 14105 * axis, false otherwise. 14106 */ 14107 @SuppressWarnings({"UnusedParameters"}) 14108 protected boolean overScrollBy(int deltaX, int deltaY, 14109 int scrollX, int scrollY, 14110 int scrollRangeX, int scrollRangeY, 14111 int maxOverScrollX, int maxOverScrollY, 14112 boolean isTouchEvent) { 14113 final int overScrollMode = mOverScrollMode; 14114 final boolean canScrollHorizontal = 14115 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 14116 final boolean canScrollVertical = 14117 computeVerticalScrollRange() > computeVerticalScrollExtent(); 14118 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 14119 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 14120 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 14121 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 14122 14123 int newScrollX = scrollX + deltaX; 14124 if (!overScrollHorizontal) { 14125 maxOverScrollX = 0; 14126 } 14127 14128 int newScrollY = scrollY + deltaY; 14129 if (!overScrollVertical) { 14130 maxOverScrollY = 0; 14131 } 14132 14133 // Clamp values if at the limits and record 14134 final int left = -maxOverScrollX; 14135 final int right = maxOverScrollX + scrollRangeX; 14136 final int top = -maxOverScrollY; 14137 final int bottom = maxOverScrollY + scrollRangeY; 14138 14139 boolean clampedX = false; 14140 if (newScrollX > right) { 14141 newScrollX = right; 14142 clampedX = true; 14143 } else if (newScrollX < left) { 14144 newScrollX = left; 14145 clampedX = true; 14146 } 14147 14148 boolean clampedY = false; 14149 if (newScrollY > bottom) { 14150 newScrollY = bottom; 14151 clampedY = true; 14152 } else if (newScrollY < top) { 14153 newScrollY = top; 14154 clampedY = true; 14155 } 14156 14157 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 14158 14159 return clampedX || clampedY; 14160 } 14161 14162 /** 14163 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 14164 * respond to the results of an over-scroll operation. 14165 * 14166 * @param scrollX New X scroll value in pixels 14167 * @param scrollY New Y scroll value in pixels 14168 * @param clampedX True if scrollX was clamped to an over-scroll boundary 14169 * @param clampedY True if scrollY was clamped to an over-scroll boundary 14170 */ 14171 protected void onOverScrolled(int scrollX, int scrollY, 14172 boolean clampedX, boolean clampedY) { 14173 // Intentionally empty. 14174 } 14175 14176 /** 14177 * Returns the over-scroll mode for this view. The result will be 14178 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 14179 * (allow over-scrolling only if the view content is larger than the container), 14180 * or {@link #OVER_SCROLL_NEVER}. 14181 * 14182 * @return This view's over-scroll mode. 14183 */ 14184 public int getOverScrollMode() { 14185 return mOverScrollMode; 14186 } 14187 14188 /** 14189 * Set the over-scroll mode for this view. Valid over-scroll modes are 14190 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 14191 * (allow over-scrolling only if the view content is larger than the container), 14192 * or {@link #OVER_SCROLL_NEVER}. 14193 * 14194 * Setting the over-scroll mode of a view will have an effect only if the 14195 * view is capable of scrolling. 14196 * 14197 * @param overScrollMode The new over-scroll mode for this view. 14198 */ 14199 public void setOverScrollMode(int overScrollMode) { 14200 if (overScrollMode != OVER_SCROLL_ALWAYS && 14201 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 14202 overScrollMode != OVER_SCROLL_NEVER) { 14203 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 14204 } 14205 mOverScrollMode = overScrollMode; 14206 } 14207 14208 /** 14209 * Gets a scale factor that determines the distance the view should scroll 14210 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 14211 * @return The vertical scroll scale factor. 14212 * @hide 14213 */ 14214 protected float getVerticalScrollFactor() { 14215 if (mVerticalScrollFactor == 0) { 14216 TypedValue outValue = new TypedValue(); 14217 if (!mContext.getTheme().resolveAttribute( 14218 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 14219 throw new IllegalStateException( 14220 "Expected theme to define listPreferredItemHeight."); 14221 } 14222 mVerticalScrollFactor = outValue.getDimension( 14223 mContext.getResources().getDisplayMetrics()); 14224 } 14225 return mVerticalScrollFactor; 14226 } 14227 14228 /** 14229 * Gets a scale factor that determines the distance the view should scroll 14230 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 14231 * @return The horizontal scroll scale factor. 14232 * @hide 14233 */ 14234 protected float getHorizontalScrollFactor() { 14235 // TODO: Should use something else. 14236 return getVerticalScrollFactor(); 14237 } 14238 14239 /** 14240 * Return the value specifying the text direction or policy that was set with 14241 * {@link #setTextDirection(int)}. 14242 * 14243 * @return the defined text direction. It can be one of: 14244 * 14245 * {@link #TEXT_DIRECTION_INHERIT}, 14246 * {@link #TEXT_DIRECTION_FIRST_STRONG} 14247 * {@link #TEXT_DIRECTION_ANY_RTL}, 14248 * {@link #TEXT_DIRECTION_LTR}, 14249 * {@link #TEXT_DIRECTION_RTL}, 14250 * {@link #TEXT_DIRECTION_LOCALE}, 14251 */ 14252 public int getTextDirection() { 14253 return mTextDirection; 14254 } 14255 14256 /** 14257 * Set the text direction. 14258 * 14259 * @param textDirection the direction to set. Should be one of: 14260 * 14261 * {@link #TEXT_DIRECTION_INHERIT}, 14262 * {@link #TEXT_DIRECTION_FIRST_STRONG} 14263 * {@link #TEXT_DIRECTION_ANY_RTL}, 14264 * {@link #TEXT_DIRECTION_LTR}, 14265 * {@link #TEXT_DIRECTION_RTL}, 14266 * {@link #TEXT_DIRECTION_LOCALE}, 14267 */ 14268 public void setTextDirection(int textDirection) { 14269 if (textDirection != mTextDirection) { 14270 mTextDirection = textDirection; 14271 resetResolvedTextDirection(); 14272 requestLayout(); 14273 } 14274 } 14275 14276 /** 14277 * Return the resolved text direction. 14278 * 14279 * @return the resolved text direction. Return one of: 14280 * 14281 * {@link #TEXT_DIRECTION_FIRST_STRONG} 14282 * {@link #TEXT_DIRECTION_ANY_RTL}, 14283 * {@link #TEXT_DIRECTION_LTR}, 14284 * {@link #TEXT_DIRECTION_RTL}, 14285 * {@link #TEXT_DIRECTION_LOCALE}, 14286 */ 14287 public int getResolvedTextDirection() { 14288 if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) { 14289 resolveTextDirection(); 14290 } 14291 return mResolvedTextDirection; 14292 } 14293 14294 /** 14295 * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when 14296 * resolution is done. 14297 */ 14298 public void resolveTextDirection() { 14299 if (mResolvedTextDirection != TEXT_DIRECTION_INHERIT) { 14300 // Resolution has already been done. 14301 return; 14302 } 14303 if (mTextDirection != TEXT_DIRECTION_INHERIT) { 14304 mResolvedTextDirection = mTextDirection; 14305 } else if (mParent != null && mParent instanceof ViewGroup) { 14306 mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection(); 14307 } else { 14308 mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG; 14309 } 14310 onResolvedTextDirectionChanged(); 14311 } 14312 14313 /** 14314 * Called when text direction has been resolved. Subclasses that care about text direction 14315 * resolution should override this method. 14316 * 14317 * The default implementation does nothing. 14318 */ 14319 public void onResolvedTextDirectionChanged() { 14320 } 14321 14322 /** 14323 * Reset resolved text direction. Text direction can be resolved with a call to 14324 * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when 14325 * reset is done. 14326 */ 14327 public void resetResolvedTextDirection() { 14328 mResolvedTextDirection = TEXT_DIRECTION_INHERIT; 14329 onResolvedTextDirectionReset(); 14330 } 14331 14332 /** 14333 * Called when text direction is reset. Subclasses that care about text direction reset should 14334 * override this method and do a reset of the text direction of their children. The default 14335 * implementation does nothing. 14336 */ 14337 public void onResolvedTextDirectionReset() { 14338 } 14339 14340 // 14341 // Properties 14342 // 14343 /** 14344 * A Property wrapper around the <code>alpha</code> functionality handled by the 14345 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 14346 */ 14347 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 14348 @Override 14349 public void setValue(View object, float value) { 14350 object.setAlpha(value); 14351 } 14352 14353 @Override 14354 public Float get(View object) { 14355 return object.getAlpha(); 14356 } 14357 }; 14358 14359 /** 14360 * A Property wrapper around the <code>translationX</code> functionality handled by the 14361 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 14362 */ 14363 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 14364 @Override 14365 public void setValue(View object, float value) { 14366 object.setTranslationX(value); 14367 } 14368 14369 @Override 14370 public Float get(View object) { 14371 return object.getTranslationX(); 14372 } 14373 }; 14374 14375 /** 14376 * A Property wrapper around the <code>translationY</code> functionality handled by the 14377 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 14378 */ 14379 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 14380 @Override 14381 public void setValue(View object, float value) { 14382 object.setTranslationY(value); 14383 } 14384 14385 @Override 14386 public Float get(View object) { 14387 return object.getTranslationY(); 14388 } 14389 }; 14390 14391 /** 14392 * A Property wrapper around the <code>x</code> functionality handled by the 14393 * {@link View#setX(float)} and {@link View#getX()} methods. 14394 */ 14395 public static final Property<View, Float> X = new FloatProperty<View>("x") { 14396 @Override 14397 public void setValue(View object, float value) { 14398 object.setX(value); 14399 } 14400 14401 @Override 14402 public Float get(View object) { 14403 return object.getX(); 14404 } 14405 }; 14406 14407 /** 14408 * A Property wrapper around the <code>y</code> functionality handled by the 14409 * {@link View#setY(float)} and {@link View#getY()} methods. 14410 */ 14411 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 14412 @Override 14413 public void setValue(View object, float value) { 14414 object.setY(value); 14415 } 14416 14417 @Override 14418 public Float get(View object) { 14419 return object.getY(); 14420 } 14421 }; 14422 14423 /** 14424 * A Property wrapper around the <code>rotation</code> functionality handled by the 14425 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 14426 */ 14427 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 14428 @Override 14429 public void setValue(View object, float value) { 14430 object.setRotation(value); 14431 } 14432 14433 @Override 14434 public Float get(View object) { 14435 return object.getRotation(); 14436 } 14437 }; 14438 14439 /** 14440 * A Property wrapper around the <code>rotationX</code> functionality handled by the 14441 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 14442 */ 14443 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 14444 @Override 14445 public void setValue(View object, float value) { 14446 object.setRotationX(value); 14447 } 14448 14449 @Override 14450 public Float get(View object) { 14451 return object.getRotationX(); 14452 } 14453 }; 14454 14455 /** 14456 * A Property wrapper around the <code>rotationY</code> functionality handled by the 14457 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 14458 */ 14459 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 14460 @Override 14461 public void setValue(View object, float value) { 14462 object.setRotationY(value); 14463 } 14464 14465 @Override 14466 public Float get(View object) { 14467 return object.getRotationY(); 14468 } 14469 }; 14470 14471 /** 14472 * A Property wrapper around the <code>scaleX</code> functionality handled by the 14473 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 14474 */ 14475 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 14476 @Override 14477 public void setValue(View object, float value) { 14478 object.setScaleX(value); 14479 } 14480 14481 @Override 14482 public Float get(View object) { 14483 return object.getScaleX(); 14484 } 14485 }; 14486 14487 /** 14488 * A Property wrapper around the <code>scaleY</code> functionality handled by the 14489 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 14490 */ 14491 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 14492 @Override 14493 public void setValue(View object, float value) { 14494 object.setScaleY(value); 14495 } 14496 14497 @Override 14498 public Float get(View object) { 14499 return object.getScaleY(); 14500 } 14501 }; 14502 14503 /** 14504 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 14505 * Each MeasureSpec represents a requirement for either the width or the height. 14506 * A MeasureSpec is comprised of a size and a mode. There are three possible 14507 * modes: 14508 * <dl> 14509 * <dt>UNSPECIFIED</dt> 14510 * <dd> 14511 * The parent has not imposed any constraint on the child. It can be whatever size 14512 * it wants. 14513 * </dd> 14514 * 14515 * <dt>EXACTLY</dt> 14516 * <dd> 14517 * The parent has determined an exact size for the child. The child is going to be 14518 * given those bounds regardless of how big it wants to be. 14519 * </dd> 14520 * 14521 * <dt>AT_MOST</dt> 14522 * <dd> 14523 * The child can be as large as it wants up to the specified size. 14524 * </dd> 14525 * </dl> 14526 * 14527 * MeasureSpecs are implemented as ints to reduce object allocation. This class 14528 * is provided to pack and unpack the <size, mode> tuple into the int. 14529 */ 14530 public static class MeasureSpec { 14531 private static final int MODE_SHIFT = 30; 14532 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 14533 14534 /** 14535 * Measure specification mode: The parent has not imposed any constraint 14536 * on the child. It can be whatever size it wants. 14537 */ 14538 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 14539 14540 /** 14541 * Measure specification mode: The parent has determined an exact size 14542 * for the child. The child is going to be given those bounds regardless 14543 * of how big it wants to be. 14544 */ 14545 public static final int EXACTLY = 1 << MODE_SHIFT; 14546 14547 /** 14548 * Measure specification mode: The child can be as large as it wants up 14549 * to the specified size. 14550 */ 14551 public static final int AT_MOST = 2 << MODE_SHIFT; 14552 14553 /** 14554 * Creates a measure specification based on the supplied size and mode. 14555 * 14556 * The mode must always be one of the following: 14557 * <ul> 14558 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 14559 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 14560 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 14561 * </ul> 14562 * 14563 * @param size the size of the measure specification 14564 * @param mode the mode of the measure specification 14565 * @return the measure specification based on size and mode 14566 */ 14567 public static int makeMeasureSpec(int size, int mode) { 14568 return size + mode; 14569 } 14570 14571 /** 14572 * Extracts the mode from the supplied measure specification. 14573 * 14574 * @param measureSpec the measure specification to extract the mode from 14575 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 14576 * {@link android.view.View.MeasureSpec#AT_MOST} or 14577 * {@link android.view.View.MeasureSpec#EXACTLY} 14578 */ 14579 public static int getMode(int measureSpec) { 14580 return (measureSpec & MODE_MASK); 14581 } 14582 14583 /** 14584 * Extracts the size from the supplied measure specification. 14585 * 14586 * @param measureSpec the measure specification to extract the size from 14587 * @return the size in pixels defined in the supplied measure specification 14588 */ 14589 public static int getSize(int measureSpec) { 14590 return (measureSpec & ~MODE_MASK); 14591 } 14592 14593 /** 14594 * Returns a String representation of the specified measure 14595 * specification. 14596 * 14597 * @param measureSpec the measure specification to convert to a String 14598 * @return a String with the following format: "MeasureSpec: MODE SIZE" 14599 */ 14600 public static String toString(int measureSpec) { 14601 int mode = getMode(measureSpec); 14602 int size = getSize(measureSpec); 14603 14604 StringBuilder sb = new StringBuilder("MeasureSpec: "); 14605 14606 if (mode == UNSPECIFIED) 14607 sb.append("UNSPECIFIED "); 14608 else if (mode == EXACTLY) 14609 sb.append("EXACTLY "); 14610 else if (mode == AT_MOST) 14611 sb.append("AT_MOST "); 14612 else 14613 sb.append(mode).append(" "); 14614 14615 sb.append(size); 14616 return sb.toString(); 14617 } 14618 } 14619 14620 class CheckForLongPress implements Runnable { 14621 14622 private int mOriginalWindowAttachCount; 14623 14624 public void run() { 14625 if (isPressed() && (mParent != null) 14626 && mOriginalWindowAttachCount == mWindowAttachCount) { 14627 if (performLongClick()) { 14628 mHasPerformedLongPress = true; 14629 } 14630 } 14631 } 14632 14633 public void rememberWindowAttachCount() { 14634 mOriginalWindowAttachCount = mWindowAttachCount; 14635 } 14636 } 14637 14638 private final class CheckForTap implements Runnable { 14639 public void run() { 14640 mPrivateFlags &= ~PREPRESSED; 14641 setPressed(true); 14642 checkForLongClick(ViewConfiguration.getTapTimeout()); 14643 } 14644 } 14645 14646 private final class PerformClick implements Runnable { 14647 public void run() { 14648 performClick(); 14649 } 14650 } 14651 14652 /** @hide */ 14653 public void hackTurnOffWindowResizeAnim(boolean off) { 14654 mAttachInfo.mTurnOffWindowResizeAnim = off; 14655 } 14656 14657 /** 14658 * This method returns a ViewPropertyAnimator object, which can be used to animate 14659 * specific properties on this View. 14660 * 14661 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 14662 */ 14663 public ViewPropertyAnimator animate() { 14664 if (mAnimator == null) { 14665 mAnimator = new ViewPropertyAnimator(this); 14666 } 14667 return mAnimator; 14668 } 14669 14670 /** 14671 * Interface definition for a callback to be invoked when a key event is 14672 * dispatched to this view. The callback will be invoked before the key 14673 * event is given to the view. 14674 */ 14675 public interface OnKeyListener { 14676 /** 14677 * Called when a key is dispatched to a view. This allows listeners to 14678 * get a chance to respond before the target view. 14679 * 14680 * @param v The view the key has been dispatched to. 14681 * @param keyCode The code for the physical key that was pressed 14682 * @param event The KeyEvent object containing full information about 14683 * the event. 14684 * @return True if the listener has consumed the event, false otherwise. 14685 */ 14686 boolean onKey(View v, int keyCode, KeyEvent event); 14687 } 14688 14689 /** 14690 * Interface definition for a callback to be invoked when a touch event is 14691 * dispatched to this view. The callback will be invoked before the touch 14692 * event is given to the view. 14693 */ 14694 public interface OnTouchListener { 14695 /** 14696 * Called when a touch event is dispatched to a view. This allows listeners to 14697 * get a chance to respond before the target view. 14698 * 14699 * @param v The view the touch event has been dispatched to. 14700 * @param event The MotionEvent object containing full information about 14701 * the event. 14702 * @return True if the listener has consumed the event, false otherwise. 14703 */ 14704 boolean onTouch(View v, MotionEvent event); 14705 } 14706 14707 /** 14708 * Interface definition for a callback to be invoked when a hover event is 14709 * dispatched to this view. The callback will be invoked before the hover 14710 * event is given to the view. 14711 */ 14712 public interface OnHoverListener { 14713 /** 14714 * Called when a hover event is dispatched to a view. This allows listeners to 14715 * get a chance to respond before the target view. 14716 * 14717 * @param v The view the hover event has been dispatched to. 14718 * @param event The MotionEvent object containing full information about 14719 * the event. 14720 * @return True if the listener has consumed the event, false otherwise. 14721 */ 14722 boolean onHover(View v, MotionEvent event); 14723 } 14724 14725 /** 14726 * Interface definition for a callback to be invoked when a generic motion event is 14727 * dispatched to this view. The callback will be invoked before the generic motion 14728 * event is given to the view. 14729 */ 14730 public interface OnGenericMotionListener { 14731 /** 14732 * Called when a generic motion event is dispatched to a view. This allows listeners to 14733 * get a chance to respond before the target view. 14734 * 14735 * @param v The view the generic motion event has been dispatched to. 14736 * @param event The MotionEvent object containing full information about 14737 * the event. 14738 * @return True if the listener has consumed the event, false otherwise. 14739 */ 14740 boolean onGenericMotion(View v, MotionEvent event); 14741 } 14742 14743 /** 14744 * Interface definition for a callback to be invoked when a view has been clicked and held. 14745 */ 14746 public interface OnLongClickListener { 14747 /** 14748 * Called when a view has been clicked and held. 14749 * 14750 * @param v The view that was clicked and held. 14751 * 14752 * @return true if the callback consumed the long click, false otherwise. 14753 */ 14754 boolean onLongClick(View v); 14755 } 14756 14757 /** 14758 * Interface definition for a callback to be invoked when a drag is being dispatched 14759 * to this view. The callback will be invoked before the hosting view's own 14760 * onDrag(event) method. If the listener wants to fall back to the hosting view's 14761 * onDrag(event) behavior, it should return 'false' from this callback. 14762 * 14763 * <div class="special reference"> 14764 * <h3>Developer Guides</h3> 14765 * <p>For a guide to implementing drag and drop features, read the 14766 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 14767 * </div> 14768 */ 14769 public interface OnDragListener { 14770 /** 14771 * Called when a drag event is dispatched to a view. This allows listeners 14772 * to get a chance to override base View behavior. 14773 * 14774 * @param v The View that received the drag event. 14775 * @param event The {@link android.view.DragEvent} object for the drag event. 14776 * @return {@code true} if the drag event was handled successfully, or {@code false} 14777 * if the drag event was not handled. Note that {@code false} will trigger the View 14778 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 14779 */ 14780 boolean onDrag(View v, DragEvent event); 14781 } 14782 14783 /** 14784 * Interface definition for a callback to be invoked when the focus state of 14785 * a view changed. 14786 */ 14787 public interface OnFocusChangeListener { 14788 /** 14789 * Called when the focus state of a view has changed. 14790 * 14791 * @param v The view whose state has changed. 14792 * @param hasFocus The new focus state of v. 14793 */ 14794 void onFocusChange(View v, boolean hasFocus); 14795 } 14796 14797 /** 14798 * Interface definition for a callback to be invoked when a view is clicked. 14799 */ 14800 public interface OnClickListener { 14801 /** 14802 * Called when a view has been clicked. 14803 * 14804 * @param v The view that was clicked. 14805 */ 14806 void onClick(View v); 14807 } 14808 14809 /** 14810 * Interface definition for a callback to be invoked when the context menu 14811 * for this view is being built. 14812 */ 14813 public interface OnCreateContextMenuListener { 14814 /** 14815 * Called when the context menu for this view is being built. It is not 14816 * safe to hold onto the menu after this method returns. 14817 * 14818 * @param menu The context menu that is being built 14819 * @param v The view for which the context menu is being built 14820 * @param menuInfo Extra information about the item for which the 14821 * context menu should be shown. This information will vary 14822 * depending on the class of v. 14823 */ 14824 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 14825 } 14826 14827 /** 14828 * Interface definition for a callback to be invoked when the status bar changes 14829 * visibility. This reports <strong>global</strong> changes to the system UI 14830 * state, not just what the application is requesting. 14831 * 14832 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 14833 */ 14834 public interface OnSystemUiVisibilityChangeListener { 14835 /** 14836 * Called when the status bar changes visibility because of a call to 14837 * {@link View#setSystemUiVisibility(int)}. 14838 * 14839 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 14840 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. This tells you the 14841 * <strong>global</strong> state of the UI visibility flags, not what your 14842 * app is currently applying. 14843 */ 14844 public void onSystemUiVisibilityChange(int visibility); 14845 } 14846 14847 /** 14848 * Interface definition for a callback to be invoked when this view is attached 14849 * or detached from its window. 14850 */ 14851 public interface OnAttachStateChangeListener { 14852 /** 14853 * Called when the view is attached to a window. 14854 * @param v The view that was attached 14855 */ 14856 public void onViewAttachedToWindow(View v); 14857 /** 14858 * Called when the view is detached from a window. 14859 * @param v The view that was detached 14860 */ 14861 public void onViewDetachedFromWindow(View v); 14862 } 14863 14864 private final class UnsetPressedState implements Runnable { 14865 public void run() { 14866 setPressed(false); 14867 } 14868 } 14869 14870 /** 14871 * Base class for derived classes that want to save and restore their own 14872 * state in {@link android.view.View#onSaveInstanceState()}. 14873 */ 14874 public static class BaseSavedState extends AbsSavedState { 14875 /** 14876 * Constructor used when reading from a parcel. Reads the state of the superclass. 14877 * 14878 * @param source 14879 */ 14880 public BaseSavedState(Parcel source) { 14881 super(source); 14882 } 14883 14884 /** 14885 * Constructor called by derived classes when creating their SavedState objects 14886 * 14887 * @param superState The state of the superclass of this view 14888 */ 14889 public BaseSavedState(Parcelable superState) { 14890 super(superState); 14891 } 14892 14893 public static final Parcelable.Creator<BaseSavedState> CREATOR = 14894 new Parcelable.Creator<BaseSavedState>() { 14895 public BaseSavedState createFromParcel(Parcel in) { 14896 return new BaseSavedState(in); 14897 } 14898 14899 public BaseSavedState[] newArray(int size) { 14900 return new BaseSavedState[size]; 14901 } 14902 }; 14903 } 14904 14905 /** 14906 * A set of information given to a view when it is attached to its parent 14907 * window. 14908 */ 14909 static class AttachInfo { 14910 interface Callbacks { 14911 void playSoundEffect(int effectId); 14912 boolean performHapticFeedback(int effectId, boolean always); 14913 } 14914 14915 /** 14916 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 14917 * to a Handler. This class contains the target (View) to invalidate and 14918 * the coordinates of the dirty rectangle. 14919 * 14920 * For performance purposes, this class also implements a pool of up to 14921 * POOL_LIMIT objects that get reused. This reduces memory allocations 14922 * whenever possible. 14923 */ 14924 static class InvalidateInfo implements Poolable<InvalidateInfo> { 14925 private static final int POOL_LIMIT = 10; 14926 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 14927 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 14928 public InvalidateInfo newInstance() { 14929 return new InvalidateInfo(); 14930 } 14931 14932 public void onAcquired(InvalidateInfo element) { 14933 } 14934 14935 public void onReleased(InvalidateInfo element) { 14936 element.target = null; 14937 } 14938 }, POOL_LIMIT) 14939 ); 14940 14941 private InvalidateInfo mNext; 14942 private boolean mIsPooled; 14943 14944 View target; 14945 14946 int left; 14947 int top; 14948 int right; 14949 int bottom; 14950 14951 public void setNextPoolable(InvalidateInfo element) { 14952 mNext = element; 14953 } 14954 14955 public InvalidateInfo getNextPoolable() { 14956 return mNext; 14957 } 14958 14959 static InvalidateInfo acquire() { 14960 return sPool.acquire(); 14961 } 14962 14963 void release() { 14964 sPool.release(this); 14965 } 14966 14967 public boolean isPooled() { 14968 return mIsPooled; 14969 } 14970 14971 public void setPooled(boolean isPooled) { 14972 mIsPooled = isPooled; 14973 } 14974 } 14975 14976 final IWindowSession mSession; 14977 14978 final IWindow mWindow; 14979 14980 final IBinder mWindowToken; 14981 14982 final Callbacks mRootCallbacks; 14983 14984 HardwareCanvas mHardwareCanvas; 14985 14986 /** 14987 * The top view of the hierarchy. 14988 */ 14989 View mRootView; 14990 14991 IBinder mPanelParentWindowToken; 14992 Surface mSurface; 14993 14994 boolean mHardwareAccelerated; 14995 boolean mHardwareAccelerationRequested; 14996 HardwareRenderer mHardwareRenderer; 14997 14998 boolean mScreenOn; 14999 15000 /** 15001 * Scale factor used by the compatibility mode 15002 */ 15003 float mApplicationScale; 15004 15005 /** 15006 * Indicates whether the application is in compatibility mode 15007 */ 15008 boolean mScalingRequired; 15009 15010 /** 15011 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 15012 */ 15013 boolean mTurnOffWindowResizeAnim; 15014 15015 /** 15016 * Left position of this view's window 15017 */ 15018 int mWindowLeft; 15019 15020 /** 15021 * Top position of this view's window 15022 */ 15023 int mWindowTop; 15024 15025 /** 15026 * Indicates whether views need to use 32-bit drawing caches 15027 */ 15028 boolean mUse32BitDrawingCache; 15029 15030 /** 15031 * For windows that are full-screen but using insets to layout inside 15032 * of the screen decorations, these are the current insets for the 15033 * content of the window. 15034 */ 15035 final Rect mContentInsets = new Rect(); 15036 15037 /** 15038 * For windows that are full-screen but using insets to layout inside 15039 * of the screen decorations, these are the current insets for the 15040 * actual visible parts of the window. 15041 */ 15042 final Rect mVisibleInsets = new Rect(); 15043 15044 /** 15045 * The internal insets given by this window. This value is 15046 * supplied by the client (through 15047 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 15048 * be given to the window manager when changed to be used in laying 15049 * out windows behind it. 15050 */ 15051 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 15052 = new ViewTreeObserver.InternalInsetsInfo(); 15053 15054 /** 15055 * All views in the window's hierarchy that serve as scroll containers, 15056 * used to determine if the window can be resized or must be panned 15057 * to adjust for a soft input area. 15058 */ 15059 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 15060 15061 final KeyEvent.DispatcherState mKeyDispatchState 15062 = new KeyEvent.DispatcherState(); 15063 15064 /** 15065 * Indicates whether the view's window currently has the focus. 15066 */ 15067 boolean mHasWindowFocus; 15068 15069 /** 15070 * The current visibility of the window. 15071 */ 15072 int mWindowVisibility; 15073 15074 /** 15075 * Indicates the time at which drawing started to occur. 15076 */ 15077 long mDrawingTime; 15078 15079 /** 15080 * Indicates whether or not ignoring the DIRTY_MASK flags. 15081 */ 15082 boolean mIgnoreDirtyState; 15083 15084 /** 15085 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 15086 * to avoid clearing that flag prematurely. 15087 */ 15088 boolean mSetIgnoreDirtyState = false; 15089 15090 /** 15091 * Indicates whether the view's window is currently in touch mode. 15092 */ 15093 boolean mInTouchMode; 15094 15095 /** 15096 * Indicates that ViewAncestor should trigger a global layout change 15097 * the next time it performs a traversal 15098 */ 15099 boolean mRecomputeGlobalAttributes; 15100 15101 /** 15102 * Always report new attributes at next traversal. 15103 */ 15104 boolean mForceReportNewAttributes; 15105 15106 /** 15107 * Set during a traveral if any views want to keep the screen on. 15108 */ 15109 boolean mKeepScreenOn; 15110 15111 /** 15112 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 15113 */ 15114 int mSystemUiVisibility; 15115 15116 /** 15117 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 15118 * attached. 15119 */ 15120 boolean mHasSystemUiListeners; 15121 15122 /** 15123 * Set if the visibility of any views has changed. 15124 */ 15125 boolean mViewVisibilityChanged; 15126 15127 /** 15128 * Set to true if a view has been scrolled. 15129 */ 15130 boolean mViewScrollChanged; 15131 15132 /** 15133 * Global to the view hierarchy used as a temporary for dealing with 15134 * x/y points in the transparent region computations. 15135 */ 15136 final int[] mTransparentLocation = new int[2]; 15137 15138 /** 15139 * Global to the view hierarchy used as a temporary for dealing with 15140 * x/y points in the ViewGroup.invalidateChild implementation. 15141 */ 15142 final int[] mInvalidateChildLocation = new int[2]; 15143 15144 15145 /** 15146 * Global to the view hierarchy used as a temporary for dealing with 15147 * x/y location when view is transformed. 15148 */ 15149 final float[] mTmpTransformLocation = new float[2]; 15150 15151 /** 15152 * The view tree observer used to dispatch global events like 15153 * layout, pre-draw, touch mode change, etc. 15154 */ 15155 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 15156 15157 /** 15158 * A Canvas used by the view hierarchy to perform bitmap caching. 15159 */ 15160 Canvas mCanvas; 15161 15162 /** 15163 * The view root impl. 15164 */ 15165 final ViewRootImpl mViewRootImpl; 15166 15167 /** 15168 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 15169 * handler can be used to pump events in the UI events queue. 15170 */ 15171 final Handler mHandler; 15172 15173 /** 15174 * Temporary for use in computing invalidate rectangles while 15175 * calling up the hierarchy. 15176 */ 15177 final Rect mTmpInvalRect = new Rect(); 15178 15179 /** 15180 * Temporary for use in computing hit areas with transformed views 15181 */ 15182 final RectF mTmpTransformRect = new RectF(); 15183 15184 /** 15185 * Temporary list for use in collecting focusable descendents of a view. 15186 */ 15187 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 15188 15189 /** 15190 * The id of the window for accessibility purposes. 15191 */ 15192 int mAccessibilityWindowId = View.NO_ID; 15193 15194 /** 15195 * Creates a new set of attachment information with the specified 15196 * events handler and thread. 15197 * 15198 * @param handler the events handler the view must use 15199 */ 15200 AttachInfo(IWindowSession session, IWindow window, 15201 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 15202 mSession = session; 15203 mWindow = window; 15204 mWindowToken = window.asBinder(); 15205 mViewRootImpl = viewRootImpl; 15206 mHandler = handler; 15207 mRootCallbacks = effectPlayer; 15208 } 15209 } 15210 15211 /** 15212 * <p>ScrollabilityCache holds various fields used by a View when scrolling 15213 * is supported. This avoids keeping too many unused fields in most 15214 * instances of View.</p> 15215 */ 15216 private static class ScrollabilityCache implements Runnable { 15217 15218 /** 15219 * Scrollbars are not visible 15220 */ 15221 public static final int OFF = 0; 15222 15223 /** 15224 * Scrollbars are visible 15225 */ 15226 public static final int ON = 1; 15227 15228 /** 15229 * Scrollbars are fading away 15230 */ 15231 public static final int FADING = 2; 15232 15233 public boolean fadeScrollBars; 15234 15235 public int fadingEdgeLength; 15236 public int scrollBarDefaultDelayBeforeFade; 15237 public int scrollBarFadeDuration; 15238 15239 public int scrollBarSize; 15240 public ScrollBarDrawable scrollBar; 15241 public float[] interpolatorValues; 15242 public View host; 15243 15244 public final Paint paint; 15245 public final Matrix matrix; 15246 public Shader shader; 15247 15248 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 15249 15250 private static final float[] OPAQUE = { 255 }; 15251 private static final float[] TRANSPARENT = { 0.0f }; 15252 15253 /** 15254 * When fading should start. This time moves into the future every time 15255 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 15256 */ 15257 public long fadeStartTime; 15258 15259 15260 /** 15261 * The current state of the scrollbars: ON, OFF, or FADING 15262 */ 15263 public int state = OFF; 15264 15265 private int mLastColor; 15266 15267 public ScrollabilityCache(ViewConfiguration configuration, View host) { 15268 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 15269 scrollBarSize = configuration.getScaledScrollBarSize(); 15270 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 15271 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 15272 15273 paint = new Paint(); 15274 matrix = new Matrix(); 15275 // use use a height of 1, and then wack the matrix each time we 15276 // actually use it. 15277 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 15278 15279 paint.setShader(shader); 15280 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 15281 this.host = host; 15282 } 15283 15284 public void setFadeColor(int color) { 15285 if (color != 0 && color != mLastColor) { 15286 mLastColor = color; 15287 color |= 0xFF000000; 15288 15289 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 15290 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 15291 15292 paint.setShader(shader); 15293 // Restore the default transfer mode (src_over) 15294 paint.setXfermode(null); 15295 } 15296 } 15297 15298 public void run() { 15299 long now = AnimationUtils.currentAnimationTimeMillis(); 15300 if (now >= fadeStartTime) { 15301 15302 // the animation fades the scrollbars out by changing 15303 // the opacity (alpha) from fully opaque to fully 15304 // transparent 15305 int nextFrame = (int) now; 15306 int framesCount = 0; 15307 15308 Interpolator interpolator = scrollBarInterpolator; 15309 15310 // Start opaque 15311 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 15312 15313 // End transparent 15314 nextFrame += scrollBarFadeDuration; 15315 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 15316 15317 state = FADING; 15318 15319 // Kick off the fade animation 15320 host.invalidate(true); 15321 } 15322 } 15323 } 15324 15325 /** 15326 * Resuable callback for sending 15327 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 15328 */ 15329 private class SendViewScrolledAccessibilityEvent implements Runnable { 15330 public volatile boolean mIsPending; 15331 15332 public void run() { 15333 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 15334 mIsPending = false; 15335 } 15336 } 15337 15338 /** 15339 * <p> 15340 * This class represents a delegate that can be registered in a {@link View} 15341 * to enhance accessibility support via composition rather via inheritance. 15342 * It is specifically targeted to widget developers that extend basic View 15343 * classes i.e. classes in package android.view, that would like their 15344 * applications to be backwards compatible. 15345 * </p> 15346 * <p> 15347 * A scenario in which a developer would like to use an accessibility delegate 15348 * is overriding a method introduced in a later API version then the minimal API 15349 * version supported by the application. For example, the method 15350 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 15351 * in API version 4 when the accessibility APIs were first introduced. If a 15352 * developer would like his application to run on API version 4 devices (assuming 15353 * all other APIs used by the application are version 4 or lower) and take advantage 15354 * of this method, instead of overriding the method which would break the application's 15355 * backwards compatibility, he can override the corresponding method in this 15356 * delegate and register the delegate in the target View if the API version of 15357 * the system is high enough i.e. the API version is same or higher to the API 15358 * version that introduced 15359 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 15360 * </p> 15361 * <p> 15362 * Here is an example implementation: 15363 * </p> 15364 * <code><pre><p> 15365 * if (Build.VERSION.SDK_INT >= 14) { 15366 * // If the API version is equal of higher than the version in 15367 * // which onInitializeAccessibilityNodeInfo was introduced we 15368 * // register a delegate with a customized implementation. 15369 * View view = findViewById(R.id.view_id); 15370 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 15371 * public void onInitializeAccessibilityNodeInfo(View host, 15372 * AccessibilityNodeInfo info) { 15373 * // Let the default implementation populate the info. 15374 * super.onInitializeAccessibilityNodeInfo(host, info); 15375 * // Set some other information. 15376 * info.setEnabled(host.isEnabled()); 15377 * } 15378 * }); 15379 * } 15380 * </code></pre></p> 15381 * <p> 15382 * This delegate contains methods that correspond to the accessibility methods 15383 * in View. If a delegate has been specified the implementation in View hands 15384 * off handling to the corresponding method in this delegate. The default 15385 * implementation the delegate methods behaves exactly as the corresponding 15386 * method in View for the case of no accessibility delegate been set. Hence, 15387 * to customize the behavior of a View method, clients can override only the 15388 * corresponding delegate method without altering the behavior of the rest 15389 * accessibility related methods of the host view. 15390 * </p> 15391 */ 15392 public static class AccessibilityDelegate { 15393 15394 /** 15395 * Sends an accessibility event of the given type. If accessibility is not 15396 * enabled this method has no effect. 15397 * <p> 15398 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 15399 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 15400 * been set. 15401 * </p> 15402 * 15403 * @param host The View hosting the delegate. 15404 * @param eventType The type of the event to send. 15405 * 15406 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 15407 */ 15408 public void sendAccessibilityEvent(View host, int eventType) { 15409 host.sendAccessibilityEventInternal(eventType); 15410 } 15411 15412 /** 15413 * Sends an accessibility event. This method behaves exactly as 15414 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 15415 * empty {@link AccessibilityEvent} and does not perform a check whether 15416 * accessibility is enabled. 15417 * <p> 15418 * The default implementation behaves as 15419 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 15420 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 15421 * the case of no accessibility delegate been set. 15422 * </p> 15423 * 15424 * @param host The View hosting the delegate. 15425 * @param event The event to send. 15426 * 15427 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 15428 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 15429 */ 15430 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 15431 host.sendAccessibilityEventUncheckedInternal(event); 15432 } 15433 15434 /** 15435 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 15436 * to its children for adding their text content to the event. 15437 * <p> 15438 * The default implementation behaves as 15439 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 15440 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 15441 * the case of no accessibility delegate been set. 15442 * </p> 15443 * 15444 * @param host The View hosting the delegate. 15445 * @param event The event. 15446 * @return True if the event population was completed. 15447 * 15448 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 15449 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 15450 */ 15451 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 15452 return host.dispatchPopulateAccessibilityEventInternal(event); 15453 } 15454 15455 /** 15456 * Gives a chance to the host View to populate the accessibility event with its 15457 * text content. 15458 * <p> 15459 * The default implementation behaves as 15460 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 15461 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 15462 * the case of no accessibility delegate been set. 15463 * </p> 15464 * 15465 * @param host The View hosting the delegate. 15466 * @param event The accessibility event which to populate. 15467 * 15468 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 15469 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 15470 */ 15471 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 15472 host.onPopulateAccessibilityEventInternal(event); 15473 } 15474 15475 /** 15476 * Initializes an {@link AccessibilityEvent} with information about the 15477 * the host View which is the event source. 15478 * <p> 15479 * The default implementation behaves as 15480 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 15481 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 15482 * the case of no accessibility delegate been set. 15483 * </p> 15484 * 15485 * @param host The View hosting the delegate. 15486 * @param event The event to initialize. 15487 * 15488 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 15489 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 15490 */ 15491 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 15492 host.onInitializeAccessibilityEventInternal(event); 15493 } 15494 15495 /** 15496 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 15497 * <p> 15498 * The default implementation behaves as 15499 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 15500 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 15501 * the case of no accessibility delegate been set. 15502 * </p> 15503 * 15504 * @param host The View hosting the delegate. 15505 * @param info The instance to initialize. 15506 * 15507 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 15508 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 15509 */ 15510 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 15511 host.onInitializeAccessibilityNodeInfoInternal(info); 15512 } 15513 15514 /** 15515 * Called when a child of the host View has requested sending an 15516 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 15517 * to augment the event. 15518 * <p> 15519 * The default implementation behaves as 15520 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 15521 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 15522 * the case of no accessibility delegate been set. 15523 * </p> 15524 * 15525 * @param host The View hosting the delegate. 15526 * @param child The child which requests sending the event. 15527 * @param event The event to be sent. 15528 * @return True if the event should be sent 15529 * 15530 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 15531 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 15532 */ 15533 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 15534 AccessibilityEvent event) { 15535 return host.onRequestSendAccessibilityEventInternal(child, event); 15536 } 15537 15538 /** 15539 * Gets the provider for managing a virtual view hierarchy rooted at this View 15540 * and reported to {@link android.accessibilityservice.AccessibilityService}s 15541 * that explore the window content. 15542 * <p> 15543 * The default implementation behaves as 15544 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 15545 * the case of no accessibility delegate been set. 15546 * </p> 15547 * 15548 * @return The provider. 15549 * 15550 * @see AccessibilityNodeProvider 15551 */ 15552 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 15553 return null; 15554 } 15555 } 15556} 15557