View.java revision 705240631beffaedc28bc0b950e8b7f09b6d3b5d
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.content.ClipData; 20import android.content.Context; 21import android.content.res.Configuration; 22import android.content.res.Resources; 23import android.content.res.TypedArray; 24import android.graphics.Bitmap; 25import android.graphics.Camera; 26import android.graphics.Canvas; 27import android.graphics.Interpolator; 28import android.graphics.LinearGradient; 29import android.graphics.Matrix; 30import android.graphics.Paint; 31import android.graphics.PixelFormat; 32import android.graphics.Point; 33import android.graphics.PorterDuff; 34import android.graphics.PorterDuffXfermode; 35import android.graphics.Rect; 36import android.graphics.RectF; 37import android.graphics.Region; 38import android.graphics.Shader; 39import android.graphics.drawable.ColorDrawable; 40import android.graphics.drawable.Drawable; 41import android.os.Handler; 42import android.os.IBinder; 43import android.os.Message; 44import android.os.Parcel; 45import android.os.Parcelable; 46import android.os.RemoteException; 47import android.os.SystemClock; 48import android.text.TextUtils; 49import android.util.AttributeSet; 50import android.util.FloatProperty; 51import android.util.LocaleUtil; 52import android.util.Log; 53import android.util.Pool; 54import android.util.Poolable; 55import android.util.PoolableManager; 56import android.util.Pools; 57import android.util.Property; 58import android.util.SparseArray; 59import android.util.TypedValue; 60import android.view.ContextMenu.ContextMenuInfo; 61import android.view.accessibility.AccessibilityEvent; 62import android.view.accessibility.AccessibilityEventSource; 63import android.view.accessibility.AccessibilityManager; 64import android.view.accessibility.AccessibilityNodeInfo; 65import android.view.animation.Animation; 66import android.view.animation.AnimationUtils; 67import android.view.inputmethod.EditorInfo; 68import android.view.inputmethod.InputConnection; 69import android.view.inputmethod.InputMethodManager; 70import android.widget.ScrollBarDrawable; 71 72import static android.os.Build.VERSION_CODES.*; 73 74import com.android.internal.R; 75import com.android.internal.util.Predicate; 76import com.android.internal.view.menu.MenuBuilder; 77 78import java.lang.ref.WeakReference; 79import java.lang.reflect.InvocationTargetException; 80import java.lang.reflect.Method; 81import java.util.ArrayList; 82import java.util.Arrays; 83import java.util.Locale; 84import java.util.WeakHashMap; 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"> 99 * <p>For an introduction to using this class to develop your 100 * application's user interface, read the Developer Guide documentation on 101 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics 102 * include: 103 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a> 104 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a> 105 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a> 106 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a> 107 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a> 108 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a> 109 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a> 110 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>. 111 * </p> 112 * </div> 113 * 114 * <a name="Using"></a> 115 * <h3>Using Views</h3> 116 * <p> 117 * All of the views in a window are arranged in a single tree. You can add views 118 * either from code or by specifying a tree of views in one or more XML layout 119 * files. There are many specialized subclasses of views that act as controls or 120 * are capable of displaying text, images, or other content. 121 * </p> 122 * <p> 123 * Once you have created a tree of views, there are typically a few types of 124 * common operations you may wish to perform: 125 * <ul> 126 * <li><strong>Set properties:</strong> for example setting the text of a 127 * {@link android.widget.TextView}. The available properties and the methods 128 * that set them will vary among the different subclasses of views. Note that 129 * properties that are known at build time can be set in the XML layout 130 * files.</li> 131 * <li><strong>Set focus:</strong> The framework will handled moving focus in 132 * response to user input. To force focus to a specific view, call 133 * {@link #requestFocus}.</li> 134 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 135 * that will be notified when something interesting happens to the view. For 136 * example, all views will let you set a listener to be notified when the view 137 * gains or loses focus. You can register such a listener using 138 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 139 * Other view subclasses offer more specialized listeners. For example, a Button 140 * exposes a listener to notify clients when the button is clicked.</li> 141 * <li><strong>Set visibility:</strong> You can hide or show views using 142 * {@link #setVisibility(int)}.</li> 143 * </ul> 144 * </p> 145 * <p><em> 146 * Note: The Android framework is responsible for measuring, laying out and 147 * drawing views. You should not call methods that perform these actions on 148 * views yourself unless you are actually implementing a 149 * {@link android.view.ViewGroup}. 150 * </em></p> 151 * 152 * <a name="Lifecycle"></a> 153 * <h3>Implementing a Custom View</h3> 154 * 155 * <p> 156 * To implement a custom view, you will usually begin by providing overrides for 157 * some of the standard methods that the framework calls on all views. You do 158 * not need to override all of these methods. In fact, you can start by just 159 * overriding {@link #onDraw(android.graphics.Canvas)}. 160 * <table border="2" width="85%" align="center" cellpadding="5"> 161 * <thead> 162 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 163 * </thead> 164 * 165 * <tbody> 166 * <tr> 167 * <td rowspan="2">Creation</td> 168 * <td>Constructors</td> 169 * <td>There is a form of the constructor that are called when the view 170 * is created from code and a form that is called when the view is 171 * inflated from a layout file. The second form should parse and apply 172 * any attributes defined in the layout file. 173 * </td> 174 * </tr> 175 * <tr> 176 * <td><code>{@link #onFinishInflate()}</code></td> 177 * <td>Called after a view and all of its children has been inflated 178 * from XML.</td> 179 * </tr> 180 * 181 * <tr> 182 * <td rowspan="3">Layout</td> 183 * <td><code>{@link #onMeasure(int, int)}</code></td> 184 * <td>Called to determine the size requirements for this view and all 185 * of its children. 186 * </td> 187 * </tr> 188 * <tr> 189 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 190 * <td>Called when this view should assign a size and position to all 191 * of its children. 192 * </td> 193 * </tr> 194 * <tr> 195 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 196 * <td>Called when the size of this view has changed. 197 * </td> 198 * </tr> 199 * 200 * <tr> 201 * <td>Drawing</td> 202 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 203 * <td>Called when the view should render its content. 204 * </td> 205 * </tr> 206 * 207 * <tr> 208 * <td rowspan="4">Event processing</td> 209 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 210 * <td>Called when a new key event occurs. 211 * </td> 212 * </tr> 213 * <tr> 214 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 215 * <td>Called when a key up event occurs. 216 * </td> 217 * </tr> 218 * <tr> 219 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 220 * <td>Called when a trackball motion event occurs. 221 * </td> 222 * </tr> 223 * <tr> 224 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 225 * <td>Called when a touch screen motion event occurs. 226 * </td> 227 * </tr> 228 * 229 * <tr> 230 * <td rowspan="2">Focus</td> 231 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 232 * <td>Called when the view gains or loses focus. 233 * </td> 234 * </tr> 235 * 236 * <tr> 237 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 238 * <td>Called when the window containing the view gains or loses focus. 239 * </td> 240 * </tr> 241 * 242 * <tr> 243 * <td rowspan="3">Attaching</td> 244 * <td><code>{@link #onAttachedToWindow()}</code></td> 245 * <td>Called when the view is attached to a window. 246 * </td> 247 * </tr> 248 * 249 * <tr> 250 * <td><code>{@link #onDetachedFromWindow}</code></td> 251 * <td>Called when the view is detached from its window. 252 * </td> 253 * </tr> 254 * 255 * <tr> 256 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 257 * <td>Called when the visibility of the window containing the view 258 * has changed. 259 * </td> 260 * </tr> 261 * </tbody> 262 * 263 * </table> 264 * </p> 265 * 266 * <a name="IDs"></a> 267 * <h3>IDs</h3> 268 * Views may have an integer id associated with them. These ids are typically 269 * assigned in the layout XML files, and are used to find specific views within 270 * the view tree. A common pattern is to: 271 * <ul> 272 * <li>Define a Button in the layout file and assign it a unique ID. 273 * <pre> 274 * <Button 275 * android:id="@+id/my_button" 276 * android:layout_width="wrap_content" 277 * android:layout_height="wrap_content" 278 * android:text="@string/my_button_text"/> 279 * </pre></li> 280 * <li>From the onCreate method of an Activity, find the Button 281 * <pre class="prettyprint"> 282 * Button myButton = (Button) findViewById(R.id.my_button); 283 * </pre></li> 284 * </ul> 285 * <p> 286 * View IDs need not be unique throughout the tree, but it is good practice to 287 * ensure that they are at least unique within the part of the tree you are 288 * searching. 289 * </p> 290 * 291 * <a name="Position"></a> 292 * <h3>Position</h3> 293 * <p> 294 * The geometry of a view is that of a rectangle. A view has a location, 295 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 296 * two dimensions, expressed as a width and a height. The unit for location 297 * and dimensions is the pixel. 298 * </p> 299 * 300 * <p> 301 * It is possible to retrieve the location of a view by invoking the methods 302 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 303 * coordinate of the rectangle representing the view. The latter returns the 304 * top, or Y, coordinate of the rectangle representing the view. These methods 305 * both return the location of the view relative to its parent. For instance, 306 * when getLeft() returns 20, that means the view is located 20 pixels to the 307 * right of the left edge of its direct parent. 308 * </p> 309 * 310 * <p> 311 * In addition, several convenience methods are offered to avoid unnecessary 312 * computations, namely {@link #getRight()} and {@link #getBottom()}. 313 * These methods return the coordinates of the right and bottom edges of the 314 * rectangle representing the view. For instance, calling {@link #getRight()} 315 * is similar to the following computation: <code>getLeft() + getWidth()</code> 316 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 317 * </p> 318 * 319 * <a name="SizePaddingMargins"></a> 320 * <h3>Size, padding and margins</h3> 321 * <p> 322 * The size of a view is expressed with a width and a height. A view actually 323 * possess two pairs of width and height values. 324 * </p> 325 * 326 * <p> 327 * The first pair is known as <em>measured width</em> and 328 * <em>measured height</em>. These dimensions define how big a view wants to be 329 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 330 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 331 * and {@link #getMeasuredHeight()}. 332 * </p> 333 * 334 * <p> 335 * The second pair is simply known as <em>width</em> and <em>height</em>, or 336 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 337 * dimensions define the actual size of the view on screen, at drawing time and 338 * after layout. These values may, but do not have to, be different from the 339 * measured width and height. The width and height can be obtained by calling 340 * {@link #getWidth()} and {@link #getHeight()}. 341 * </p> 342 * 343 * <p> 344 * To measure its dimensions, a view takes into account its padding. The padding 345 * is expressed in pixels for the left, top, right and bottom parts of the view. 346 * Padding can be used to offset the content of the view by a specific amount of 347 * pixels. For instance, a left padding of 2 will push the view's content by 348 * 2 pixels to the right of the left edge. Padding can be set using the 349 * {@link #setPadding(int, int, int, int)} method and queried by calling 350 * {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 351 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}. 352 * </p> 353 * 354 * <p> 355 * Even though a view can define a padding, it does not provide any support for 356 * margins. However, view groups provide such a support. Refer to 357 * {@link android.view.ViewGroup} and 358 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 359 * </p> 360 * 361 * <a name="Layout"></a> 362 * <h3>Layout</h3> 363 * <p> 364 * Layout is a two pass process: a measure pass and a layout pass. The measuring 365 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 366 * of the view tree. Each view pushes dimension specifications down the tree 367 * during the recursion. At the end of the measure pass, every view has stored 368 * its measurements. The second pass happens in 369 * {@link #layout(int,int,int,int)} and is also top-down. During 370 * this pass each parent is responsible for positioning all of its children 371 * using the sizes computed in the measure pass. 372 * </p> 373 * 374 * <p> 375 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 376 * {@link #getMeasuredHeight()} values must be set, along with those for all of 377 * that view's descendants. A view's measured width and measured height values 378 * must respect the constraints imposed by the view's parents. This guarantees 379 * that at the end of the measure pass, all parents accept all of their 380 * children's measurements. A parent view may call measure() more than once on 381 * its children. For example, the parent may measure each child once with 382 * unspecified dimensions to find out how big they want to be, then call 383 * measure() on them again with actual numbers if the sum of all the children's 384 * unconstrained sizes is too big or too small. 385 * </p> 386 * 387 * <p> 388 * The measure pass uses two classes to communicate dimensions. The 389 * {@link MeasureSpec} class is used by views to tell their parents how they 390 * want to be measured and positioned. The base LayoutParams class just 391 * describes how big the view wants to be for both width and height. For each 392 * dimension, it can specify one of: 393 * <ul> 394 * <li> an exact number 395 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 396 * (minus padding) 397 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 398 * enclose its content (plus padding). 399 * </ul> 400 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 401 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 402 * an X and Y value. 403 * </p> 404 * 405 * <p> 406 * MeasureSpecs are used to push requirements down the tree from parent to 407 * child. A MeasureSpec can be in one of three modes: 408 * <ul> 409 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 410 * of a child view. For example, a LinearLayout may call measure() on its child 411 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 412 * tall the child view wants to be given a width of 240 pixels. 413 * <li>EXACTLY: This is used by the parent to impose an exact size on the 414 * child. The child must use this size, and guarantee that all of its 415 * descendants will fit within this size. 416 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 417 * child. The child must gurantee that it and all of its descendants will fit 418 * within this size. 419 * </ul> 420 * </p> 421 * 422 * <p> 423 * To intiate a layout, call {@link #requestLayout}. This method is typically 424 * called by a view on itself when it believes that is can no longer fit within 425 * its current bounds. 426 * </p> 427 * 428 * <a name="Drawing"></a> 429 * <h3>Drawing</h3> 430 * <p> 431 * Drawing is handled by walking the tree and rendering each view that 432 * intersects the the invalid region. Because the tree is traversed in-order, 433 * this means that parents will draw before (i.e., behind) their children, with 434 * siblings drawn in the order they appear in the tree. 435 * If you set a background drawable for a View, then the View will draw it for you 436 * before calling back to its <code>onDraw()</code> method. 437 * </p> 438 * 439 * <p> 440 * Note that the framework will not draw views that are not in the invalid region. 441 * </p> 442 * 443 * <p> 444 * To force a view to draw, call {@link #invalidate()}. 445 * </p> 446 * 447 * <a name="EventHandlingThreading"></a> 448 * <h3>Event Handling and Threading</h3> 449 * <p> 450 * The basic cycle of a view is as follows: 451 * <ol> 452 * <li>An event comes in and is dispatched to the appropriate view. The view 453 * handles the event and notifies any listeners.</li> 454 * <li>If in the course of processing the event, the view's bounds may need 455 * to be changed, the view will call {@link #requestLayout()}.</li> 456 * <li>Similarly, if in the course of processing the event the view's appearance 457 * may need to be changed, the view will call {@link #invalidate()}.</li> 458 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 459 * the framework will take care of measuring, laying out, and drawing the tree 460 * as appropriate.</li> 461 * </ol> 462 * </p> 463 * 464 * <p><em>Note: The entire view tree is single threaded. You must always be on 465 * the UI thread when calling any method on any view.</em> 466 * If you are doing work on other threads and want to update the state of a view 467 * from that thread, you should use a {@link Handler}. 468 * </p> 469 * 470 * <a name="FocusHandling"></a> 471 * <h3>Focus Handling</h3> 472 * <p> 473 * The framework will handle routine focus movement in response to user input. 474 * This includes changing the focus as views are removed or hidden, or as new 475 * views become available. Views indicate their willingness to take focus 476 * through the {@link #isFocusable} method. To change whether a view can take 477 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 478 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 479 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 480 * </p> 481 * <p> 482 * Focus movement is based on an algorithm which finds the nearest neighbor in a 483 * given direction. In rare cases, the default algorithm may not match the 484 * intended behavior of the developer. In these situations, you can provide 485 * explicit overrides by using these XML attributes in the layout file: 486 * <pre> 487 * nextFocusDown 488 * nextFocusLeft 489 * nextFocusRight 490 * nextFocusUp 491 * </pre> 492 * </p> 493 * 494 * 495 * <p> 496 * To get a particular view to take focus, call {@link #requestFocus()}. 497 * </p> 498 * 499 * <a name="TouchMode"></a> 500 * <h3>Touch Mode</h3> 501 * <p> 502 * When a user is navigating a user interface via directional keys such as a D-pad, it is 503 * necessary to give focus to actionable items such as buttons so the user can see 504 * what will take input. If the device has touch capabilities, however, and the user 505 * begins interacting with the interface by touching it, it is no longer necessary to 506 * always highlight, or give focus to, a particular view. This motivates a mode 507 * for interaction named 'touch mode'. 508 * </p> 509 * <p> 510 * For a touch capable device, once the user touches the screen, the device 511 * will enter touch mode. From this point onward, only views for which 512 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 513 * Other views that are touchable, like buttons, will not take focus when touched; they will 514 * only fire the on click listeners. 515 * </p> 516 * <p> 517 * Any time a user hits a directional key, such as a D-pad direction, the view device will 518 * exit touch mode, and find a view to take focus, so that the user may resume interacting 519 * with the user interface without touching the screen again. 520 * </p> 521 * <p> 522 * The touch mode state is maintained across {@link android.app.Activity}s. Call 523 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 524 * </p> 525 * 526 * <a name="Scrolling"></a> 527 * <h3>Scrolling</h3> 528 * <p> 529 * The framework provides basic support for views that wish to internally 530 * scroll their content. This includes keeping track of the X and Y scroll 531 * offset as well as mechanisms for drawing scrollbars. See 532 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 533 * {@link #awakenScrollBars()} for more details. 534 * </p> 535 * 536 * <a name="Tags"></a> 537 * <h3>Tags</h3> 538 * <p> 539 * Unlike IDs, tags are not used to identify views. Tags are essentially an 540 * extra piece of information that can be associated with a view. They are most 541 * often used as a convenience to store data related to views in the views 542 * themselves rather than by putting them in a separate structure. 543 * </p> 544 * 545 * <a name="Animation"></a> 546 * <h3>Animation</h3> 547 * <p> 548 * You can attach an {@link Animation} object to a view using 549 * {@link #setAnimation(Animation)} or 550 * {@link #startAnimation(Animation)}. The animation can alter the scale, 551 * rotation, translation and alpha of a view over time. If the animation is 552 * attached to a view that has children, the animation will affect the entire 553 * subtree rooted by that node. When an animation is started, the framework will 554 * take care of redrawing the appropriate views until the animation completes. 555 * </p> 556 * <p> 557 * Starting with Android 3.0, the preferred way of animating views is to use the 558 * {@link android.animation} package APIs. 559 * </p> 560 * 561 * <a name="Security"></a> 562 * <h3>Security</h3> 563 * <p> 564 * Sometimes it is essential that an application be able to verify that an action 565 * is being performed with the full knowledge and consent of the user, such as 566 * granting a permission request, making a purchase or clicking on an advertisement. 567 * Unfortunately, a malicious application could try to spoof the user into 568 * performing these actions, unaware, by concealing the intended purpose of the view. 569 * As a remedy, the framework offers a touch filtering mechanism that can be used to 570 * improve the security of views that provide access to sensitive functionality. 571 * </p><p> 572 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 573 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 574 * will discard touches that are received whenever the view's window is obscured by 575 * another visible window. As a result, the view will not receive touches whenever a 576 * toast, dialog or other window appears above the view's window. 577 * </p><p> 578 * For more fine-grained control over security, consider overriding the 579 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 580 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 581 * </p> 582 * 583 * @attr ref android.R.styleable#View_alpha 584 * @attr ref android.R.styleable#View_background 585 * @attr ref android.R.styleable#View_clickable 586 * @attr ref android.R.styleable#View_contentDescription 587 * @attr ref android.R.styleable#View_drawingCacheQuality 588 * @attr ref android.R.styleable#View_duplicateParentState 589 * @attr ref android.R.styleable#View_id 590 * @attr ref android.R.styleable#View_requiresFadingEdge 591 * @attr ref android.R.styleable#View_fadingEdgeLength 592 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 593 * @attr ref android.R.styleable#View_fitsSystemWindows 594 * @attr ref android.R.styleable#View_isScrollContainer 595 * @attr ref android.R.styleable#View_focusable 596 * @attr ref android.R.styleable#View_focusableInTouchMode 597 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 598 * @attr ref android.R.styleable#View_keepScreenOn 599 * @attr ref android.R.styleable#View_layerType 600 * @attr ref android.R.styleable#View_longClickable 601 * @attr ref android.R.styleable#View_minHeight 602 * @attr ref android.R.styleable#View_minWidth 603 * @attr ref android.R.styleable#View_nextFocusDown 604 * @attr ref android.R.styleable#View_nextFocusLeft 605 * @attr ref android.R.styleable#View_nextFocusRight 606 * @attr ref android.R.styleable#View_nextFocusUp 607 * @attr ref android.R.styleable#View_onClick 608 * @attr ref android.R.styleable#View_padding 609 * @attr ref android.R.styleable#View_paddingBottom 610 * @attr ref android.R.styleable#View_paddingLeft 611 * @attr ref android.R.styleable#View_paddingRight 612 * @attr ref android.R.styleable#View_paddingTop 613 * @attr ref android.R.styleable#View_saveEnabled 614 * @attr ref android.R.styleable#View_rotation 615 * @attr ref android.R.styleable#View_rotationX 616 * @attr ref android.R.styleable#View_rotationY 617 * @attr ref android.R.styleable#View_scaleX 618 * @attr ref android.R.styleable#View_scaleY 619 * @attr ref android.R.styleable#View_scrollX 620 * @attr ref android.R.styleable#View_scrollY 621 * @attr ref android.R.styleable#View_scrollbarSize 622 * @attr ref android.R.styleable#View_scrollbarStyle 623 * @attr ref android.R.styleable#View_scrollbars 624 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 625 * @attr ref android.R.styleable#View_scrollbarFadeDuration 626 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 627 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 628 * @attr ref android.R.styleable#View_scrollbarThumbVertical 629 * @attr ref android.R.styleable#View_scrollbarTrackVertical 630 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 631 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 632 * @attr ref android.R.styleable#View_soundEffectsEnabled 633 * @attr ref android.R.styleable#View_tag 634 * @attr ref android.R.styleable#View_transformPivotX 635 * @attr ref android.R.styleable#View_transformPivotY 636 * @attr ref android.R.styleable#View_translationX 637 * @attr ref android.R.styleable#View_translationY 638 * @attr ref android.R.styleable#View_visibility 639 * 640 * @see android.view.ViewGroup 641 */ 642public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback, 643 AccessibilityEventSource { 644 private static final boolean DBG = false; 645 646 /** 647 * The logging tag used by this class with android.util.Log. 648 */ 649 protected static final String VIEW_LOG_TAG = "View"; 650 651 /** 652 * Used to mark a View that has no ID. 653 */ 654 public static final int NO_ID = -1; 655 656 /** 657 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 658 * calling setFlags. 659 */ 660 private static final int NOT_FOCUSABLE = 0x00000000; 661 662 /** 663 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 664 * setFlags. 665 */ 666 private static final int FOCUSABLE = 0x00000001; 667 668 /** 669 * Mask for use with setFlags indicating bits used for focus. 670 */ 671 private static final int FOCUSABLE_MASK = 0x00000001; 672 673 /** 674 * This view will adjust its padding to fit sytem windows (e.g. status bar) 675 */ 676 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 677 678 /** 679 * This view is visible. 680 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 681 * android:visibility}. 682 */ 683 public static final int VISIBLE = 0x00000000; 684 685 /** 686 * This view is invisible, but it still takes up space for layout purposes. 687 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 688 * android:visibility}. 689 */ 690 public static final int INVISIBLE = 0x00000004; 691 692 /** 693 * This view is invisible, and it doesn't take any space for layout 694 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 695 * android:visibility}. 696 */ 697 public static final int GONE = 0x00000008; 698 699 /** 700 * Mask for use with setFlags indicating bits used for visibility. 701 * {@hide} 702 */ 703 static final int VISIBILITY_MASK = 0x0000000C; 704 705 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 706 707 /** 708 * This view is enabled. Intrepretation varies by subclass. 709 * Use with ENABLED_MASK when calling setFlags. 710 * {@hide} 711 */ 712 static final int ENABLED = 0x00000000; 713 714 /** 715 * This view is disabled. Intrepretation varies by subclass. 716 * Use with ENABLED_MASK when calling setFlags. 717 * {@hide} 718 */ 719 static final int DISABLED = 0x00000020; 720 721 /** 722 * Mask for use with setFlags indicating bits used for indicating whether 723 * this view is enabled 724 * {@hide} 725 */ 726 static final int ENABLED_MASK = 0x00000020; 727 728 /** 729 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 730 * called and further optimizations will be performed. It is okay to have 731 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 732 * {@hide} 733 */ 734 static final int WILL_NOT_DRAW = 0x00000080; 735 736 /** 737 * Mask for use with setFlags indicating bits used for indicating whether 738 * this view is will draw 739 * {@hide} 740 */ 741 static final int DRAW_MASK = 0x00000080; 742 743 /** 744 * <p>This view doesn't show scrollbars.</p> 745 * {@hide} 746 */ 747 static final int SCROLLBARS_NONE = 0x00000000; 748 749 /** 750 * <p>This view shows horizontal scrollbars.</p> 751 * {@hide} 752 */ 753 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 754 755 /** 756 * <p>This view shows vertical scrollbars.</p> 757 * {@hide} 758 */ 759 static final int SCROLLBARS_VERTICAL = 0x00000200; 760 761 /** 762 * <p>Mask for use with setFlags indicating bits used for indicating which 763 * scrollbars are enabled.</p> 764 * {@hide} 765 */ 766 static final int SCROLLBARS_MASK = 0x00000300; 767 768 /** 769 * Indicates that the view should filter touches when its window is obscured. 770 * Refer to the class comments for more information about this security feature. 771 * {@hide} 772 */ 773 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 774 775 // note flag value 0x00000800 is now available for next flags... 776 777 /** 778 * <p>This view doesn't show fading edges.</p> 779 * {@hide} 780 */ 781 static final int FADING_EDGE_NONE = 0x00000000; 782 783 /** 784 * <p>This view shows horizontal fading edges.</p> 785 * {@hide} 786 */ 787 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 788 789 /** 790 * <p>This view shows vertical fading edges.</p> 791 * {@hide} 792 */ 793 static final int FADING_EDGE_VERTICAL = 0x00002000; 794 795 /** 796 * <p>Mask for use with setFlags indicating bits used for indicating which 797 * fading edges are enabled.</p> 798 * {@hide} 799 */ 800 static final int FADING_EDGE_MASK = 0x00003000; 801 802 /** 803 * <p>Indicates this view can be clicked. When clickable, a View reacts 804 * to clicks by notifying the OnClickListener.<p> 805 * {@hide} 806 */ 807 static final int CLICKABLE = 0x00004000; 808 809 /** 810 * <p>Indicates this view is caching its drawing into a bitmap.</p> 811 * {@hide} 812 */ 813 static final int DRAWING_CACHE_ENABLED = 0x00008000; 814 815 /** 816 * <p>Indicates that no icicle should be saved for this view.<p> 817 * {@hide} 818 */ 819 static final int SAVE_DISABLED = 0x000010000; 820 821 /** 822 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 823 * property.</p> 824 * {@hide} 825 */ 826 static final int SAVE_DISABLED_MASK = 0x000010000; 827 828 /** 829 * <p>Indicates that no drawing cache should ever be created for this view.<p> 830 * {@hide} 831 */ 832 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 833 834 /** 835 * <p>Indicates this view can take / keep focus when int touch mode.</p> 836 * {@hide} 837 */ 838 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 839 840 /** 841 * <p>Enables low quality mode for the drawing cache.</p> 842 */ 843 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 844 845 /** 846 * <p>Enables high quality mode for the drawing cache.</p> 847 */ 848 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 849 850 /** 851 * <p>Enables automatic quality mode for the drawing cache.</p> 852 */ 853 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 854 855 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 856 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 857 }; 858 859 /** 860 * <p>Mask for use with setFlags indicating bits used for the cache 861 * quality property.</p> 862 * {@hide} 863 */ 864 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 865 866 /** 867 * <p> 868 * Indicates this view can be long clicked. When long clickable, a View 869 * reacts to long clicks by notifying the OnLongClickListener or showing a 870 * context menu. 871 * </p> 872 * {@hide} 873 */ 874 static final int LONG_CLICKABLE = 0x00200000; 875 876 /** 877 * <p>Indicates that this view gets its drawable states from its direct parent 878 * and ignores its original internal states.</p> 879 * 880 * @hide 881 */ 882 static final int DUPLICATE_PARENT_STATE = 0x00400000; 883 884 /** 885 * The scrollbar style to display the scrollbars inside the content area, 886 * without increasing the padding. The scrollbars will be overlaid with 887 * translucency on the view's content. 888 */ 889 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 890 891 /** 892 * The scrollbar style to display the scrollbars inside the padded area, 893 * increasing the padding of the view. The scrollbars will not overlap the 894 * content area of the view. 895 */ 896 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 897 898 /** 899 * The scrollbar style to display the scrollbars at the edge of the view, 900 * without increasing the padding. The scrollbars will be overlaid with 901 * translucency. 902 */ 903 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 904 905 /** 906 * The scrollbar style to display the scrollbars at the edge of the view, 907 * increasing the padding of the view. The scrollbars will only overlap the 908 * background, if any. 909 */ 910 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 911 912 /** 913 * Mask to check if the scrollbar style is overlay or inset. 914 * {@hide} 915 */ 916 static final int SCROLLBARS_INSET_MASK = 0x01000000; 917 918 /** 919 * Mask to check if the scrollbar style is inside or outside. 920 * {@hide} 921 */ 922 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 923 924 /** 925 * Mask for scrollbar style. 926 * {@hide} 927 */ 928 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 929 930 /** 931 * View flag indicating that the screen should remain on while the 932 * window containing this view is visible to the user. This effectively 933 * takes care of automatically setting the WindowManager's 934 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 935 */ 936 public static final int KEEP_SCREEN_ON = 0x04000000; 937 938 /** 939 * View flag indicating whether this view should have sound effects enabled 940 * for events such as clicking and touching. 941 */ 942 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 943 944 /** 945 * View flag indicating whether this view should have haptic feedback 946 * enabled for events such as long presses. 947 */ 948 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 949 950 /** 951 * <p>Indicates that the view hierarchy should stop saving state when 952 * it reaches this view. If state saving is initiated immediately at 953 * the view, it will be allowed. 954 * {@hide} 955 */ 956 static final int PARENT_SAVE_DISABLED = 0x20000000; 957 958 /** 959 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 960 * {@hide} 961 */ 962 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 963 964 /** 965 * Horizontal direction of this view is from Left to Right. 966 * Use with {@link #setLayoutDirection}. 967 * {@hide} 968 */ 969 public static final int LAYOUT_DIRECTION_LTR = 0x00000000; 970 971 /** 972 * Horizontal direction of this view is from Right to Left. 973 * Use with {@link #setLayoutDirection}. 974 * {@hide} 975 */ 976 public static final int LAYOUT_DIRECTION_RTL = 0x40000000; 977 978 /** 979 * Horizontal direction of this view is inherited from its parent. 980 * Use with {@link #setLayoutDirection}. 981 * {@hide} 982 */ 983 public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000; 984 985 /** 986 * Horizontal direction of this view is from deduced from the default language 987 * script for the locale. Use with {@link #setLayoutDirection}. 988 * {@hide} 989 */ 990 public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000; 991 992 /** 993 * Mask for use with setFlags indicating bits used for horizontalDirection. 994 * {@hide} 995 */ 996 static final int LAYOUT_DIRECTION_MASK = 0xC0000000; 997 998 /* 999 * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct 1000 * flag value. 1001 * {@hide} 1002 */ 1003 private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR, 1004 LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE}; 1005 1006 /** 1007 * Default horizontalDirection. 1008 * {@hide} 1009 */ 1010 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1011 1012 /** 1013 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1014 * should add all focusable Views regardless if they are focusable in touch mode. 1015 */ 1016 public static final int FOCUSABLES_ALL = 0x00000000; 1017 1018 /** 1019 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1020 * should add only Views focusable in touch mode. 1021 */ 1022 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1023 1024 /** 1025 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1026 * item. 1027 */ 1028 public static final int FOCUS_BACKWARD = 0x00000001; 1029 1030 /** 1031 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1032 * item. 1033 */ 1034 public static final int FOCUS_FORWARD = 0x00000002; 1035 1036 /** 1037 * Use with {@link #focusSearch(int)}. Move focus to the left. 1038 */ 1039 public static final int FOCUS_LEFT = 0x00000011; 1040 1041 /** 1042 * Use with {@link #focusSearch(int)}. Move focus up. 1043 */ 1044 public static final int FOCUS_UP = 0x00000021; 1045 1046 /** 1047 * Use with {@link #focusSearch(int)}. Move focus to the right. 1048 */ 1049 public static final int FOCUS_RIGHT = 0x00000042; 1050 1051 /** 1052 * Use with {@link #focusSearch(int)}. Move focus down. 1053 */ 1054 public static final int FOCUS_DOWN = 0x00000082; 1055 1056 /** 1057 * Bits of {@link #getMeasuredWidthAndState()} and 1058 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1059 */ 1060 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1061 1062 /** 1063 * Bits of {@link #getMeasuredWidthAndState()} and 1064 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1065 */ 1066 public static final int MEASURED_STATE_MASK = 0xff000000; 1067 1068 /** 1069 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1070 * for functions that combine both width and height into a single int, 1071 * such as {@link #getMeasuredState()} and the childState argument of 1072 * {@link #resolveSizeAndState(int, int, int)}. 1073 */ 1074 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1075 1076 /** 1077 * Bit of {@link #getMeasuredWidthAndState()} and 1078 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1079 * is smaller that the space the view would like to have. 1080 */ 1081 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1082 1083 /** 1084 * Base View state sets 1085 */ 1086 // Singles 1087 /** 1088 * Indicates the view has no states set. States are used with 1089 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1090 * view depending on its state. 1091 * 1092 * @see android.graphics.drawable.Drawable 1093 * @see #getDrawableState() 1094 */ 1095 protected static final int[] EMPTY_STATE_SET; 1096 /** 1097 * Indicates the view is enabled. States are used with 1098 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1099 * view depending on its state. 1100 * 1101 * @see android.graphics.drawable.Drawable 1102 * @see #getDrawableState() 1103 */ 1104 protected static final int[] ENABLED_STATE_SET; 1105 /** 1106 * Indicates the view is focused. States are used with 1107 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1108 * view depending on its state. 1109 * 1110 * @see android.graphics.drawable.Drawable 1111 * @see #getDrawableState() 1112 */ 1113 protected static final int[] FOCUSED_STATE_SET; 1114 /** 1115 * Indicates the view is selected. States are used with 1116 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1117 * view depending on its state. 1118 * 1119 * @see android.graphics.drawable.Drawable 1120 * @see #getDrawableState() 1121 */ 1122 protected static final int[] SELECTED_STATE_SET; 1123 /** 1124 * Indicates the view is pressed. States are used with 1125 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1126 * view depending on its state. 1127 * 1128 * @see android.graphics.drawable.Drawable 1129 * @see #getDrawableState() 1130 * @hide 1131 */ 1132 protected static final int[] PRESSED_STATE_SET; 1133 /** 1134 * Indicates the view's window has focus. States are used with 1135 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1136 * view depending on its state. 1137 * 1138 * @see android.graphics.drawable.Drawable 1139 * @see #getDrawableState() 1140 */ 1141 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1142 // Doubles 1143 /** 1144 * Indicates the view is enabled and has the focus. 1145 * 1146 * @see #ENABLED_STATE_SET 1147 * @see #FOCUSED_STATE_SET 1148 */ 1149 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1150 /** 1151 * Indicates the view is enabled and selected. 1152 * 1153 * @see #ENABLED_STATE_SET 1154 * @see #SELECTED_STATE_SET 1155 */ 1156 protected static final int[] ENABLED_SELECTED_STATE_SET; 1157 /** 1158 * Indicates the view is enabled and that its window has focus. 1159 * 1160 * @see #ENABLED_STATE_SET 1161 * @see #WINDOW_FOCUSED_STATE_SET 1162 */ 1163 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1164 /** 1165 * Indicates the view is focused and selected. 1166 * 1167 * @see #FOCUSED_STATE_SET 1168 * @see #SELECTED_STATE_SET 1169 */ 1170 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1171 /** 1172 * Indicates the view has the focus and that its window has the focus. 1173 * 1174 * @see #FOCUSED_STATE_SET 1175 * @see #WINDOW_FOCUSED_STATE_SET 1176 */ 1177 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1178 /** 1179 * Indicates the view is selected and that its window has the focus. 1180 * 1181 * @see #SELECTED_STATE_SET 1182 * @see #WINDOW_FOCUSED_STATE_SET 1183 */ 1184 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1185 // Triples 1186 /** 1187 * Indicates the view is enabled, focused and selected. 1188 * 1189 * @see #ENABLED_STATE_SET 1190 * @see #FOCUSED_STATE_SET 1191 * @see #SELECTED_STATE_SET 1192 */ 1193 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1194 /** 1195 * Indicates the view is enabled, focused and its window has the focus. 1196 * 1197 * @see #ENABLED_STATE_SET 1198 * @see #FOCUSED_STATE_SET 1199 * @see #WINDOW_FOCUSED_STATE_SET 1200 */ 1201 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1202 /** 1203 * Indicates the view is enabled, selected and its window has the focus. 1204 * 1205 * @see #ENABLED_STATE_SET 1206 * @see #SELECTED_STATE_SET 1207 * @see #WINDOW_FOCUSED_STATE_SET 1208 */ 1209 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1210 /** 1211 * Indicates the view is focused, selected and its window has the focus. 1212 * 1213 * @see #FOCUSED_STATE_SET 1214 * @see #SELECTED_STATE_SET 1215 * @see #WINDOW_FOCUSED_STATE_SET 1216 */ 1217 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1218 /** 1219 * Indicates the view is enabled, focused, selected and its window 1220 * has the focus. 1221 * 1222 * @see #ENABLED_STATE_SET 1223 * @see #FOCUSED_STATE_SET 1224 * @see #SELECTED_STATE_SET 1225 * @see #WINDOW_FOCUSED_STATE_SET 1226 */ 1227 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1228 /** 1229 * Indicates the view is pressed and its window has the focus. 1230 * 1231 * @see #PRESSED_STATE_SET 1232 * @see #WINDOW_FOCUSED_STATE_SET 1233 */ 1234 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1235 /** 1236 * Indicates the view is pressed and selected. 1237 * 1238 * @see #PRESSED_STATE_SET 1239 * @see #SELECTED_STATE_SET 1240 */ 1241 protected static final int[] PRESSED_SELECTED_STATE_SET; 1242 /** 1243 * Indicates the view is pressed, selected and its window has the focus. 1244 * 1245 * @see #PRESSED_STATE_SET 1246 * @see #SELECTED_STATE_SET 1247 * @see #WINDOW_FOCUSED_STATE_SET 1248 */ 1249 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1250 /** 1251 * Indicates the view is pressed and focused. 1252 * 1253 * @see #PRESSED_STATE_SET 1254 * @see #FOCUSED_STATE_SET 1255 */ 1256 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1257 /** 1258 * Indicates the view is pressed, focused and its window has the focus. 1259 * 1260 * @see #PRESSED_STATE_SET 1261 * @see #FOCUSED_STATE_SET 1262 * @see #WINDOW_FOCUSED_STATE_SET 1263 */ 1264 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1265 /** 1266 * Indicates the view is pressed, focused and selected. 1267 * 1268 * @see #PRESSED_STATE_SET 1269 * @see #SELECTED_STATE_SET 1270 * @see #FOCUSED_STATE_SET 1271 */ 1272 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1273 /** 1274 * Indicates the view is pressed, focused, selected and its window has the focus. 1275 * 1276 * @see #PRESSED_STATE_SET 1277 * @see #FOCUSED_STATE_SET 1278 * @see #SELECTED_STATE_SET 1279 * @see #WINDOW_FOCUSED_STATE_SET 1280 */ 1281 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1282 /** 1283 * Indicates the view is pressed and enabled. 1284 * 1285 * @see #PRESSED_STATE_SET 1286 * @see #ENABLED_STATE_SET 1287 */ 1288 protected static final int[] PRESSED_ENABLED_STATE_SET; 1289 /** 1290 * Indicates the view is pressed, enabled and its window has the focus. 1291 * 1292 * @see #PRESSED_STATE_SET 1293 * @see #ENABLED_STATE_SET 1294 * @see #WINDOW_FOCUSED_STATE_SET 1295 */ 1296 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1297 /** 1298 * Indicates the view is pressed, enabled and selected. 1299 * 1300 * @see #PRESSED_STATE_SET 1301 * @see #ENABLED_STATE_SET 1302 * @see #SELECTED_STATE_SET 1303 */ 1304 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1305 /** 1306 * Indicates the view is pressed, enabled, selected and its window has the 1307 * focus. 1308 * 1309 * @see #PRESSED_STATE_SET 1310 * @see #ENABLED_STATE_SET 1311 * @see #SELECTED_STATE_SET 1312 * @see #WINDOW_FOCUSED_STATE_SET 1313 */ 1314 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1315 /** 1316 * Indicates the view is pressed, enabled and focused. 1317 * 1318 * @see #PRESSED_STATE_SET 1319 * @see #ENABLED_STATE_SET 1320 * @see #FOCUSED_STATE_SET 1321 */ 1322 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1323 /** 1324 * Indicates the view is pressed, enabled, focused and its window has the 1325 * focus. 1326 * 1327 * @see #PRESSED_STATE_SET 1328 * @see #ENABLED_STATE_SET 1329 * @see #FOCUSED_STATE_SET 1330 * @see #WINDOW_FOCUSED_STATE_SET 1331 */ 1332 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1333 /** 1334 * Indicates the view is pressed, enabled, focused and selected. 1335 * 1336 * @see #PRESSED_STATE_SET 1337 * @see #ENABLED_STATE_SET 1338 * @see #SELECTED_STATE_SET 1339 * @see #FOCUSED_STATE_SET 1340 */ 1341 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1342 /** 1343 * Indicates the view is pressed, enabled, focused, selected and its window 1344 * has the focus. 1345 * 1346 * @see #PRESSED_STATE_SET 1347 * @see #ENABLED_STATE_SET 1348 * @see #SELECTED_STATE_SET 1349 * @see #FOCUSED_STATE_SET 1350 * @see #WINDOW_FOCUSED_STATE_SET 1351 */ 1352 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1353 1354 /** 1355 * The order here is very important to {@link #getDrawableState()} 1356 */ 1357 private static final int[][] VIEW_STATE_SETS; 1358 1359 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1360 static final int VIEW_STATE_SELECTED = 1 << 1; 1361 static final int VIEW_STATE_FOCUSED = 1 << 2; 1362 static final int VIEW_STATE_ENABLED = 1 << 3; 1363 static final int VIEW_STATE_PRESSED = 1 << 4; 1364 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1365 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1366 static final int VIEW_STATE_HOVERED = 1 << 7; 1367 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1368 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1369 1370 static final int[] VIEW_STATE_IDS = new int[] { 1371 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1372 R.attr.state_selected, VIEW_STATE_SELECTED, 1373 R.attr.state_focused, VIEW_STATE_FOCUSED, 1374 R.attr.state_enabled, VIEW_STATE_ENABLED, 1375 R.attr.state_pressed, VIEW_STATE_PRESSED, 1376 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1377 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1378 R.attr.state_hovered, VIEW_STATE_HOVERED, 1379 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1380 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED, 1381 }; 1382 1383 static { 1384 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1385 throw new IllegalStateException( 1386 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1387 } 1388 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1389 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1390 int viewState = R.styleable.ViewDrawableStates[i]; 1391 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1392 if (VIEW_STATE_IDS[j] == viewState) { 1393 orderedIds[i * 2] = viewState; 1394 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1395 } 1396 } 1397 } 1398 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1399 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1400 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1401 int numBits = Integer.bitCount(i); 1402 int[] set = new int[numBits]; 1403 int pos = 0; 1404 for (int j = 0; j < orderedIds.length; j += 2) { 1405 if ((i & orderedIds[j+1]) != 0) { 1406 set[pos++] = orderedIds[j]; 1407 } 1408 } 1409 VIEW_STATE_SETS[i] = set; 1410 } 1411 1412 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1413 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1414 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1415 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1416 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1417 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1418 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1419 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1420 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1421 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1422 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1423 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1424 | VIEW_STATE_FOCUSED]; 1425 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1426 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1427 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1428 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1429 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1430 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1431 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1432 | VIEW_STATE_ENABLED]; 1433 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1434 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1435 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1436 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1437 | VIEW_STATE_ENABLED]; 1438 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1439 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1440 | VIEW_STATE_ENABLED]; 1441 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1442 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1443 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1444 1445 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1446 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1447 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1448 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1449 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1450 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1451 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1452 | VIEW_STATE_PRESSED]; 1453 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1454 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1455 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1456 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1457 | VIEW_STATE_PRESSED]; 1458 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1459 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1460 | VIEW_STATE_PRESSED]; 1461 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1462 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1463 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1464 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1465 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1466 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1467 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1468 | VIEW_STATE_PRESSED]; 1469 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1470 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1471 | VIEW_STATE_PRESSED]; 1472 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1473 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1474 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1475 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1476 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1477 | VIEW_STATE_PRESSED]; 1478 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1479 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1480 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1481 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1482 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1483 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1484 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1485 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1486 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1487 | VIEW_STATE_PRESSED]; 1488 } 1489 1490 /** 1491 * Temporary Rect currently for use in setBackground(). This will probably 1492 * be extended in the future to hold our own class with more than just 1493 * a Rect. :) 1494 */ 1495 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1496 1497 /** 1498 * Map used to store views' tags. 1499 */ 1500 private static WeakHashMap<View, SparseArray<Object>> sTags; 1501 1502 /** 1503 * Lock used to access sTags. 1504 */ 1505 private static final Object sTagsLock = new Object(); 1506 1507 /** 1508 * The next available accessiiblity id. 1509 */ 1510 private static int sNextAccessibilityViewId; 1511 1512 /** 1513 * The animation currently associated with this view. 1514 * @hide 1515 */ 1516 protected Animation mCurrentAnimation = null; 1517 1518 /** 1519 * Width as measured during measure pass. 1520 * {@hide} 1521 */ 1522 @ViewDebug.ExportedProperty(category = "measurement") 1523 int mMeasuredWidth; 1524 1525 /** 1526 * Height as measured during measure pass. 1527 * {@hide} 1528 */ 1529 @ViewDebug.ExportedProperty(category = "measurement") 1530 int mMeasuredHeight; 1531 1532 /** 1533 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1534 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1535 * its display list. This flag, used only when hw accelerated, allows us to clear the 1536 * flag while retaining this information until it's needed (at getDisplayList() time and 1537 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1538 * 1539 * {@hide} 1540 */ 1541 boolean mRecreateDisplayList = false; 1542 1543 /** 1544 * The view's identifier. 1545 * {@hide} 1546 * 1547 * @see #setId(int) 1548 * @see #getId() 1549 */ 1550 @ViewDebug.ExportedProperty(resolveId = true) 1551 int mID = NO_ID; 1552 1553 /** 1554 * The stable ID of this view for accessibility porposes. 1555 */ 1556 int mAccessibilityViewId = NO_ID; 1557 1558 /** 1559 * The view's tag. 1560 * {@hide} 1561 * 1562 * @see #setTag(Object) 1563 * @see #getTag() 1564 */ 1565 protected Object mTag; 1566 1567 // for mPrivateFlags: 1568 /** {@hide} */ 1569 static final int WANTS_FOCUS = 0x00000001; 1570 /** {@hide} */ 1571 static final int FOCUSED = 0x00000002; 1572 /** {@hide} */ 1573 static final int SELECTED = 0x00000004; 1574 /** {@hide} */ 1575 static final int IS_ROOT_NAMESPACE = 0x00000008; 1576 /** {@hide} */ 1577 static final int HAS_BOUNDS = 0x00000010; 1578 /** {@hide} */ 1579 static final int DRAWN = 0x00000020; 1580 /** 1581 * When this flag is set, this view is running an animation on behalf of its 1582 * children and should therefore not cancel invalidate requests, even if they 1583 * lie outside of this view's bounds. 1584 * 1585 * {@hide} 1586 */ 1587 static final int DRAW_ANIMATION = 0x00000040; 1588 /** {@hide} */ 1589 static final int SKIP_DRAW = 0x00000080; 1590 /** {@hide} */ 1591 static final int ONLY_DRAWS_BACKGROUND = 0x00000100; 1592 /** {@hide} */ 1593 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1594 /** {@hide} */ 1595 static final int DRAWABLE_STATE_DIRTY = 0x00000400; 1596 /** {@hide} */ 1597 static final int MEASURED_DIMENSION_SET = 0x00000800; 1598 /** {@hide} */ 1599 static final int FORCE_LAYOUT = 0x00001000; 1600 /** {@hide} */ 1601 static final int LAYOUT_REQUIRED = 0x00002000; 1602 1603 private static final int PRESSED = 0x00004000; 1604 1605 /** {@hide} */ 1606 static final int DRAWING_CACHE_VALID = 0x00008000; 1607 /** 1608 * Flag used to indicate that this view should be drawn once more (and only once 1609 * more) after its animation has completed. 1610 * {@hide} 1611 */ 1612 static final int ANIMATION_STARTED = 0x00010000; 1613 1614 private static final int SAVE_STATE_CALLED = 0x00020000; 1615 1616 /** 1617 * Indicates that the View returned true when onSetAlpha() was called and that 1618 * the alpha must be restored. 1619 * {@hide} 1620 */ 1621 static final int ALPHA_SET = 0x00040000; 1622 1623 /** 1624 * Set by {@link #setScrollContainer(boolean)}. 1625 */ 1626 static final int SCROLL_CONTAINER = 0x00080000; 1627 1628 /** 1629 * Set by {@link #setScrollContainer(boolean)}. 1630 */ 1631 static final int SCROLL_CONTAINER_ADDED = 0x00100000; 1632 1633 /** 1634 * View flag indicating whether this view was invalidated (fully or partially.) 1635 * 1636 * @hide 1637 */ 1638 static final int DIRTY = 0x00200000; 1639 1640 /** 1641 * View flag indicating whether this view was invalidated by an opaque 1642 * invalidate request. 1643 * 1644 * @hide 1645 */ 1646 static final int DIRTY_OPAQUE = 0x00400000; 1647 1648 /** 1649 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}. 1650 * 1651 * @hide 1652 */ 1653 static final int DIRTY_MASK = 0x00600000; 1654 1655 /** 1656 * Indicates whether the background is opaque. 1657 * 1658 * @hide 1659 */ 1660 static final int OPAQUE_BACKGROUND = 0x00800000; 1661 1662 /** 1663 * Indicates whether the scrollbars are opaque. 1664 * 1665 * @hide 1666 */ 1667 static final int OPAQUE_SCROLLBARS = 0x01000000; 1668 1669 /** 1670 * Indicates whether the view is opaque. 1671 * 1672 * @hide 1673 */ 1674 static final int OPAQUE_MASK = 0x01800000; 1675 1676 /** 1677 * Indicates a prepressed state; 1678 * the short time between ACTION_DOWN and recognizing 1679 * a 'real' press. Prepressed is used to recognize quick taps 1680 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1681 * 1682 * @hide 1683 */ 1684 private static final int PREPRESSED = 0x02000000; 1685 1686 /** 1687 * Indicates whether the view is temporarily detached. 1688 * 1689 * @hide 1690 */ 1691 static final int CANCEL_NEXT_UP_EVENT = 0x04000000; 1692 1693 /** 1694 * Indicates that we should awaken scroll bars once attached 1695 * 1696 * @hide 1697 */ 1698 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1699 1700 /** 1701 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1702 * @hide 1703 */ 1704 private static final int HOVERED = 0x10000000; 1705 1706 /** 1707 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1708 * for transform operations 1709 * 1710 * @hide 1711 */ 1712 private static final int PIVOT_EXPLICITLY_SET = 0x20000000; 1713 1714 /** {@hide} */ 1715 static final int ACTIVATED = 0x40000000; 1716 1717 /** 1718 * Indicates that this view was specifically invalidated, not just dirtied because some 1719 * child view was invalidated. The flag is used to determine when we need to recreate 1720 * a view's display list (as opposed to just returning a reference to its existing 1721 * display list). 1722 * 1723 * @hide 1724 */ 1725 static final int INVALIDATED = 0x80000000; 1726 1727 /* Masks for mPrivateFlags2 */ 1728 1729 /** 1730 * Indicates that this view has reported that it can accept the current drag's content. 1731 * Cleared when the drag operation concludes. 1732 * @hide 1733 */ 1734 static final int DRAG_CAN_ACCEPT = 0x00000001; 1735 1736 /** 1737 * Indicates that this view is currently directly under the drag location in a 1738 * drag-and-drop operation involving content that it can accept. Cleared when 1739 * the drag exits the view, or when the drag operation concludes. 1740 * @hide 1741 */ 1742 static final int DRAG_HOVERED = 0x00000002; 1743 1744 /** 1745 * Indicates whether the view layout direction has been resolved and drawn to the 1746 * right-to-left direction. 1747 * 1748 * @hide 1749 */ 1750 static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004; 1751 1752 /** 1753 * Indicates whether the view layout direction has been resolved. 1754 * 1755 * @hide 1756 */ 1757 static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008; 1758 1759 1760 /* End of masks for mPrivateFlags2 */ 1761 1762 static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED; 1763 1764 /** 1765 * Always allow a user to over-scroll this view, provided it is a 1766 * view that can scroll. 1767 * 1768 * @see #getOverScrollMode() 1769 * @see #setOverScrollMode(int) 1770 */ 1771 public static final int OVER_SCROLL_ALWAYS = 0; 1772 1773 /** 1774 * Allow a user to over-scroll this view only if the content is large 1775 * enough to meaningfully scroll, provided it is a view that can scroll. 1776 * 1777 * @see #getOverScrollMode() 1778 * @see #setOverScrollMode(int) 1779 */ 1780 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 1781 1782 /** 1783 * Never allow a user to over-scroll this view. 1784 * 1785 * @see #getOverScrollMode() 1786 * @see #setOverScrollMode(int) 1787 */ 1788 public static final int OVER_SCROLL_NEVER = 2; 1789 1790 /** 1791 * View has requested the system UI (status bar) to be visible (the default). 1792 * 1793 * @see #setSystemUiVisibility(int) 1794 */ 1795 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 1796 1797 /** 1798 * View has requested the system UI to enter an unobtrusive "low profile" mode. 1799 * 1800 * This is for use in games, book readers, video players, or any other "immersive" application 1801 * where the usual system chrome is deemed too distracting. 1802 * 1803 * In low profile mode, the status bar and/or navigation icons may dim. 1804 * 1805 * @see #setSystemUiVisibility(int) 1806 */ 1807 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 1808 1809 /** 1810 * View has requested that the system navigation be temporarily hidden. 1811 * 1812 * This is an even less obtrusive state than that called for by 1813 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 1814 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 1815 * those to disappear. This is useful (in conjunction with the 1816 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 1817 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 1818 * window flags) for displaying content using every last pixel on the display. 1819 * 1820 * There is a limitation: because navigation controls are so important, the least user 1821 * interaction will cause them to reappear immediately. 1822 * 1823 * @see #setSystemUiVisibility(int) 1824 */ 1825 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 1826 1827 /** 1828 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 1829 */ 1830 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 1831 1832 /** 1833 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 1834 */ 1835 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 1836 1837 /** 1838 * @hide 1839 * 1840 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1841 * out of the public fields to keep the undefined bits out of the developer's way. 1842 * 1843 * Flag to make the status bar not expandable. Unless you also 1844 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 1845 */ 1846 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 1847 1848 /** 1849 * @hide 1850 * 1851 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1852 * out of the public fields to keep the undefined bits out of the developer's way. 1853 * 1854 * Flag to hide notification icons and scrolling ticker text. 1855 */ 1856 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 1857 1858 /** 1859 * @hide 1860 * 1861 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1862 * out of the public fields to keep the undefined bits out of the developer's way. 1863 * 1864 * Flag to disable incoming notification alerts. This will not block 1865 * icons, but it will block sound, vibrating and other visual or aural notifications. 1866 */ 1867 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 1868 1869 /** 1870 * @hide 1871 * 1872 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1873 * out of the public fields to keep the undefined bits out of the developer's way. 1874 * 1875 * Flag to hide only the scrolling ticker. Note that 1876 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 1877 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 1878 */ 1879 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 1880 1881 /** 1882 * @hide 1883 * 1884 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1885 * out of the public fields to keep the undefined bits out of the developer's way. 1886 * 1887 * Flag to hide the center system info area. 1888 */ 1889 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 1890 1891 /** 1892 * @hide 1893 * 1894 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1895 * out of the public fields to keep the undefined bits out of the developer's way. 1896 * 1897 * Flag to hide only the navigation buttons. Don't use this 1898 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1899 * 1900 * THIS DOES NOT DISABLE THE BACK BUTTON 1901 */ 1902 public static final int STATUS_BAR_DISABLE_NAVIGATION = 0x00200000; 1903 1904 /** 1905 * @hide 1906 * 1907 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1908 * out of the public fields to keep the undefined bits out of the developer's way. 1909 * 1910 * Flag to hide only the back button. Don't use this 1911 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1912 */ 1913 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 1914 1915 /** 1916 * @hide 1917 * 1918 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1919 * out of the public fields to keep the undefined bits out of the developer's way. 1920 * 1921 * Flag to hide only the clock. You might use this if your activity has 1922 * its own clock making the status bar's clock redundant. 1923 */ 1924 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 1925 1926 /** 1927 * @hide 1928 */ 1929 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 1930 1931 /** 1932 * Find views that render the specified text. 1933 * 1934 * @see #findViewsWithText(ArrayList, CharSequence, int) 1935 */ 1936 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 1937 1938 /** 1939 * Find find views that contain the specified content description. 1940 * 1941 * @see #findViewsWithText(ArrayList, CharSequence, int) 1942 */ 1943 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 1944 1945 /** 1946 * Controls the over-scroll mode for this view. 1947 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 1948 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 1949 * and {@link #OVER_SCROLL_NEVER}. 1950 */ 1951 private int mOverScrollMode; 1952 1953 /** 1954 * The parent this view is attached to. 1955 * {@hide} 1956 * 1957 * @see #getParent() 1958 */ 1959 protected ViewParent mParent; 1960 1961 /** 1962 * {@hide} 1963 */ 1964 AttachInfo mAttachInfo; 1965 1966 /** 1967 * {@hide} 1968 */ 1969 @ViewDebug.ExportedProperty(flagMapping = { 1970 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT, 1971 name = "FORCE_LAYOUT"), 1972 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED, 1973 name = "LAYOUT_REQUIRED"), 1974 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID, 1975 name = "DRAWING_CACHE_INVALID", outputIf = false), 1976 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true), 1977 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false), 1978 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 1979 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY") 1980 }) 1981 int mPrivateFlags; 1982 int mPrivateFlags2; 1983 1984 /** 1985 * This view's request for the visibility of the status bar. 1986 * @hide 1987 */ 1988 @ViewDebug.ExportedProperty(flagMapping = { 1989 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 1990 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 1991 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 1992 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 1993 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 1994 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 1995 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 1996 equals = SYSTEM_UI_FLAG_VISIBLE, 1997 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 1998 }) 1999 int mSystemUiVisibility; 2000 2001 /** 2002 * Count of how many windows this view has been attached to. 2003 */ 2004 int mWindowAttachCount; 2005 2006 /** 2007 * The layout parameters associated with this view and used by the parent 2008 * {@link android.view.ViewGroup} to determine how this view should be 2009 * laid out. 2010 * {@hide} 2011 */ 2012 protected ViewGroup.LayoutParams mLayoutParams; 2013 2014 /** 2015 * The view flags hold various views states. 2016 * {@hide} 2017 */ 2018 @ViewDebug.ExportedProperty 2019 int mViewFlags; 2020 2021 static class TransformationInfo { 2022 /** 2023 * The transform matrix for the View. This transform is calculated internally 2024 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2025 * is used by default. Do *not* use this variable directly; instead call 2026 * getMatrix(), which will automatically recalculate the matrix if necessary 2027 * to get the correct matrix based on the latest rotation and scale properties. 2028 */ 2029 private final Matrix mMatrix = new Matrix(); 2030 2031 /** 2032 * The transform matrix for the View. This transform is calculated internally 2033 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2034 * is used by default. Do *not* use this variable directly; instead call 2035 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2036 * to get the correct matrix based on the latest rotation and scale properties. 2037 */ 2038 private Matrix mInverseMatrix; 2039 2040 /** 2041 * An internal variable that tracks whether we need to recalculate the 2042 * transform matrix, based on whether the rotation or scaleX/Y properties 2043 * have changed since the matrix was last calculated. 2044 */ 2045 boolean mMatrixDirty = false; 2046 2047 /** 2048 * An internal variable that tracks whether we need to recalculate the 2049 * transform matrix, based on whether the rotation or scaleX/Y properties 2050 * have changed since the matrix was last calculated. 2051 */ 2052 private boolean mInverseMatrixDirty = true; 2053 2054 /** 2055 * A variable that tracks whether we need to recalculate the 2056 * transform matrix, based on whether the rotation or scaleX/Y properties 2057 * have changed since the matrix was last calculated. This variable 2058 * is only valid after a call to updateMatrix() or to a function that 2059 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2060 */ 2061 private boolean mMatrixIsIdentity = true; 2062 2063 /** 2064 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2065 */ 2066 private Camera mCamera = null; 2067 2068 /** 2069 * This matrix is used when computing the matrix for 3D rotations. 2070 */ 2071 private Matrix matrix3D = null; 2072 2073 /** 2074 * These prev values are used to recalculate a centered pivot point when necessary. The 2075 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2076 * set), so thes values are only used then as well. 2077 */ 2078 private int mPrevWidth = -1; 2079 private int mPrevHeight = -1; 2080 2081 /** 2082 * The degrees rotation around the vertical axis through the pivot point. 2083 */ 2084 @ViewDebug.ExportedProperty 2085 float mRotationY = 0f; 2086 2087 /** 2088 * The degrees rotation around the horizontal axis through the pivot point. 2089 */ 2090 @ViewDebug.ExportedProperty 2091 float mRotationX = 0f; 2092 2093 /** 2094 * The degrees rotation around the pivot point. 2095 */ 2096 @ViewDebug.ExportedProperty 2097 float mRotation = 0f; 2098 2099 /** 2100 * The amount of translation of the object away from its left property (post-layout). 2101 */ 2102 @ViewDebug.ExportedProperty 2103 float mTranslationX = 0f; 2104 2105 /** 2106 * The amount of translation of the object away from its top property (post-layout). 2107 */ 2108 @ViewDebug.ExportedProperty 2109 float mTranslationY = 0f; 2110 2111 /** 2112 * The amount of scale in the x direction around the pivot point. A 2113 * value of 1 means no scaling is applied. 2114 */ 2115 @ViewDebug.ExportedProperty 2116 float mScaleX = 1f; 2117 2118 /** 2119 * The amount of scale in the y direction around the pivot point. A 2120 * value of 1 means no scaling is applied. 2121 */ 2122 @ViewDebug.ExportedProperty 2123 float mScaleY = 1f; 2124 2125 /** 2126 * The amount of scale in the x direction around the pivot point. A 2127 * value of 1 means no scaling is applied. 2128 */ 2129 @ViewDebug.ExportedProperty 2130 float mPivotX = 0f; 2131 2132 /** 2133 * The amount of scale in the y direction around the pivot point. A 2134 * value of 1 means no scaling is applied. 2135 */ 2136 @ViewDebug.ExportedProperty 2137 float mPivotY = 0f; 2138 2139 /** 2140 * The opacity of the View. This is a value from 0 to 1, where 0 means 2141 * completely transparent and 1 means completely opaque. 2142 */ 2143 @ViewDebug.ExportedProperty 2144 float mAlpha = 1f; 2145 } 2146 2147 TransformationInfo mTransformationInfo; 2148 2149 private boolean mLastIsOpaque; 2150 2151 /** 2152 * Convenience value to check for float values that are close enough to zero to be considered 2153 * zero. 2154 */ 2155 private static final float NONZERO_EPSILON = .001f; 2156 2157 /** 2158 * The distance in pixels from the left edge of this view's parent 2159 * to the left edge of this view. 2160 * {@hide} 2161 */ 2162 @ViewDebug.ExportedProperty(category = "layout") 2163 protected int mLeft; 2164 /** 2165 * The distance in pixels from the left edge of this view's parent 2166 * to the right edge of this view. 2167 * {@hide} 2168 */ 2169 @ViewDebug.ExportedProperty(category = "layout") 2170 protected int mRight; 2171 /** 2172 * The distance in pixels from the top edge of this view's parent 2173 * to the top edge of this view. 2174 * {@hide} 2175 */ 2176 @ViewDebug.ExportedProperty(category = "layout") 2177 protected int mTop; 2178 /** 2179 * The distance in pixels from the top edge of this view's parent 2180 * to the bottom edge of this view. 2181 * {@hide} 2182 */ 2183 @ViewDebug.ExportedProperty(category = "layout") 2184 protected int mBottom; 2185 2186 /** 2187 * The offset, in pixels, by which the content of this view is scrolled 2188 * horizontally. 2189 * {@hide} 2190 */ 2191 @ViewDebug.ExportedProperty(category = "scrolling") 2192 protected int mScrollX; 2193 /** 2194 * The offset, in pixels, by which the content of this view is scrolled 2195 * vertically. 2196 * {@hide} 2197 */ 2198 @ViewDebug.ExportedProperty(category = "scrolling") 2199 protected int mScrollY; 2200 2201 /** 2202 * The left padding in pixels, that is the distance in pixels between the 2203 * left edge of this view and the left edge of its content. 2204 * {@hide} 2205 */ 2206 @ViewDebug.ExportedProperty(category = "padding") 2207 protected int mPaddingLeft; 2208 /** 2209 * The right padding in pixels, that is the distance in pixels between the 2210 * right edge of this view and the right edge of its content. 2211 * {@hide} 2212 */ 2213 @ViewDebug.ExportedProperty(category = "padding") 2214 protected int mPaddingRight; 2215 /** 2216 * The top padding in pixels, that is the distance in pixels between the 2217 * top edge of this view and the top edge of its content. 2218 * {@hide} 2219 */ 2220 @ViewDebug.ExportedProperty(category = "padding") 2221 protected int mPaddingTop; 2222 /** 2223 * The bottom padding in pixels, that is the distance in pixels between the 2224 * bottom edge of this view and the bottom edge of its content. 2225 * {@hide} 2226 */ 2227 @ViewDebug.ExportedProperty(category = "padding") 2228 protected int mPaddingBottom; 2229 2230 /** 2231 * Briefly describes the view and is primarily used for accessibility support. 2232 */ 2233 private CharSequence mContentDescription; 2234 2235 /** 2236 * Cache the paddingRight set by the user to append to the scrollbar's size. 2237 * 2238 * @hide 2239 */ 2240 @ViewDebug.ExportedProperty(category = "padding") 2241 protected int mUserPaddingRight; 2242 2243 /** 2244 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2245 * 2246 * @hide 2247 */ 2248 @ViewDebug.ExportedProperty(category = "padding") 2249 protected int mUserPaddingBottom; 2250 2251 /** 2252 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2253 * 2254 * @hide 2255 */ 2256 @ViewDebug.ExportedProperty(category = "padding") 2257 protected int mUserPaddingLeft; 2258 2259 /** 2260 * Cache if the user padding is relative. 2261 * 2262 */ 2263 @ViewDebug.ExportedProperty(category = "padding") 2264 boolean mUserPaddingRelative; 2265 2266 /** 2267 * Cache the paddingStart set by the user to append to the scrollbar's size. 2268 * 2269 */ 2270 @ViewDebug.ExportedProperty(category = "padding") 2271 int mUserPaddingStart; 2272 2273 /** 2274 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2275 * 2276 */ 2277 @ViewDebug.ExportedProperty(category = "padding") 2278 int mUserPaddingEnd; 2279 2280 /** 2281 * @hide 2282 */ 2283 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2284 /** 2285 * @hide 2286 */ 2287 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2288 2289 private Drawable mBGDrawable; 2290 2291 private int mBackgroundResource; 2292 private boolean mBackgroundSizeChanged; 2293 2294 /** 2295 * Listener used to dispatch focus change events. 2296 * This field should be made private, so it is hidden from the SDK. 2297 * {@hide} 2298 */ 2299 protected OnFocusChangeListener mOnFocusChangeListener; 2300 2301 /** 2302 * Listeners for layout change events. 2303 */ 2304 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2305 2306 /** 2307 * Listeners for attach events. 2308 */ 2309 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2310 2311 /** 2312 * Listener used to dispatch click events. 2313 * This field should be made private, so it is hidden from the SDK. 2314 * {@hide} 2315 */ 2316 protected OnClickListener mOnClickListener; 2317 2318 /** 2319 * Listener used to dispatch long click events. 2320 * This field should be made private, so it is hidden from the SDK. 2321 * {@hide} 2322 */ 2323 protected OnLongClickListener mOnLongClickListener; 2324 2325 /** 2326 * Listener used to build the context menu. 2327 * This field should be made private, so it is hidden from the SDK. 2328 * {@hide} 2329 */ 2330 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2331 2332 private OnKeyListener mOnKeyListener; 2333 2334 private OnTouchListener mOnTouchListener; 2335 2336 private OnHoverListener mOnHoverListener; 2337 2338 private OnGenericMotionListener mOnGenericMotionListener; 2339 2340 private OnDragListener mOnDragListener; 2341 2342 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2343 2344 /** 2345 * The application environment this view lives in. 2346 * This field should be made private, so it is hidden from the SDK. 2347 * {@hide} 2348 */ 2349 protected Context mContext; 2350 2351 private final Resources mResources; 2352 2353 private ScrollabilityCache mScrollCache; 2354 2355 private int[] mDrawableState = null; 2356 2357 /** 2358 * Set to true when drawing cache is enabled and cannot be created. 2359 * 2360 * @hide 2361 */ 2362 public boolean mCachingFailed; 2363 2364 private Bitmap mDrawingCache; 2365 private Bitmap mUnscaledDrawingCache; 2366 private HardwareLayer mHardwareLayer; 2367 DisplayList mDisplayList; 2368 2369 /** 2370 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2371 * the user may specify which view to go to next. 2372 */ 2373 private int mNextFocusLeftId = View.NO_ID; 2374 2375 /** 2376 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2377 * the user may specify which view to go to next. 2378 */ 2379 private int mNextFocusRightId = View.NO_ID; 2380 2381 /** 2382 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2383 * the user may specify which view to go to next. 2384 */ 2385 private int mNextFocusUpId = View.NO_ID; 2386 2387 /** 2388 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2389 * the user may specify which view to go to next. 2390 */ 2391 private int mNextFocusDownId = View.NO_ID; 2392 2393 /** 2394 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 2395 * the user may specify which view to go to next. 2396 */ 2397 int mNextFocusForwardId = View.NO_ID; 2398 2399 private CheckForLongPress mPendingCheckForLongPress; 2400 private CheckForTap mPendingCheckForTap = null; 2401 private PerformClick mPerformClick; 2402 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 2403 2404 private UnsetPressedState mUnsetPressedState; 2405 2406 /** 2407 * Whether the long press's action has been invoked. The tap's action is invoked on the 2408 * up event while a long press is invoked as soon as the long press duration is reached, so 2409 * a long press could be performed before the tap is checked, in which case the tap's action 2410 * should not be invoked. 2411 */ 2412 private boolean mHasPerformedLongPress; 2413 2414 /** 2415 * The minimum height of the view. We'll try our best to have the height 2416 * of this view to at least this amount. 2417 */ 2418 @ViewDebug.ExportedProperty(category = "measurement") 2419 private int mMinHeight; 2420 2421 /** 2422 * The minimum width of the view. We'll try our best to have the width 2423 * of this view to at least this amount. 2424 */ 2425 @ViewDebug.ExportedProperty(category = "measurement") 2426 private int mMinWidth; 2427 2428 /** 2429 * The delegate to handle touch events that are physically in this view 2430 * but should be handled by another view. 2431 */ 2432 private TouchDelegate mTouchDelegate = null; 2433 2434 /** 2435 * Solid color to use as a background when creating the drawing cache. Enables 2436 * the cache to use 16 bit bitmaps instead of 32 bit. 2437 */ 2438 private int mDrawingCacheBackgroundColor = 0; 2439 2440 /** 2441 * Special tree observer used when mAttachInfo is null. 2442 */ 2443 private ViewTreeObserver mFloatingTreeObserver; 2444 2445 /** 2446 * Cache the touch slop from the context that created the view. 2447 */ 2448 private int mTouchSlop; 2449 2450 /** 2451 * Object that handles automatic animation of view properties. 2452 */ 2453 private ViewPropertyAnimator mAnimator = null; 2454 2455 /** 2456 * Flag indicating that a drag can cross window boundaries. When 2457 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 2458 * with this flag set, all visible applications will be able to participate 2459 * in the drag operation and receive the dragged content. 2460 * 2461 * @hide 2462 */ 2463 public static final int DRAG_FLAG_GLOBAL = 1; 2464 2465 /** 2466 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 2467 */ 2468 private float mVerticalScrollFactor; 2469 2470 /** 2471 * Position of the vertical scroll bar. 2472 */ 2473 private int mVerticalScrollbarPosition; 2474 2475 /** 2476 * Position the scroll bar at the default position as determined by the system. 2477 */ 2478 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 2479 2480 /** 2481 * Position the scroll bar along the left edge. 2482 */ 2483 public static final int SCROLLBAR_POSITION_LEFT = 1; 2484 2485 /** 2486 * Position the scroll bar along the right edge. 2487 */ 2488 public static final int SCROLLBAR_POSITION_RIGHT = 2; 2489 2490 /** 2491 * Indicates that the view does not have a layer. 2492 * 2493 * @see #getLayerType() 2494 * @see #setLayerType(int, android.graphics.Paint) 2495 * @see #LAYER_TYPE_SOFTWARE 2496 * @see #LAYER_TYPE_HARDWARE 2497 */ 2498 public static final int LAYER_TYPE_NONE = 0; 2499 2500 /** 2501 * <p>Indicates that the view has a software layer. A software layer is backed 2502 * by a bitmap and causes the view to be rendered using Android's software 2503 * rendering pipeline, even if hardware acceleration is enabled.</p> 2504 * 2505 * <p>Software layers have various usages:</p> 2506 * <p>When the application is not using hardware acceleration, a software layer 2507 * is useful to apply a specific color filter and/or blending mode and/or 2508 * translucency to a view and all its children.</p> 2509 * <p>When the application is using hardware acceleration, a software layer 2510 * is useful to render drawing primitives not supported by the hardware 2511 * accelerated pipeline. It can also be used to cache a complex view tree 2512 * into a texture and reduce the complexity of drawing operations. For instance, 2513 * when animating a complex view tree with a translation, a software layer can 2514 * be used to render the view tree only once.</p> 2515 * <p>Software layers should be avoided when the affected view tree updates 2516 * often. Every update will require to re-render the software layer, which can 2517 * potentially be slow (particularly when hardware acceleration is turned on 2518 * since the layer will have to be uploaded into a hardware texture after every 2519 * update.)</p> 2520 * 2521 * @see #getLayerType() 2522 * @see #setLayerType(int, android.graphics.Paint) 2523 * @see #LAYER_TYPE_NONE 2524 * @see #LAYER_TYPE_HARDWARE 2525 */ 2526 public static final int LAYER_TYPE_SOFTWARE = 1; 2527 2528 /** 2529 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 2530 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 2531 * OpenGL hardware) and causes the view to be rendered using Android's hardware 2532 * rendering pipeline, but only if hardware acceleration is turned on for the 2533 * view hierarchy. When hardware acceleration is turned off, hardware layers 2534 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 2535 * 2536 * <p>A hardware layer is useful to apply a specific color filter and/or 2537 * blending mode and/or translucency to a view and all its children.</p> 2538 * <p>A hardware layer can be used to cache a complex view tree into a 2539 * texture and reduce the complexity of drawing operations. For instance, 2540 * when animating a complex view tree with a translation, a hardware layer can 2541 * be used to render the view tree only once.</p> 2542 * <p>A hardware layer can also be used to increase the rendering quality when 2543 * rotation transformations are applied on a view. It can also be used to 2544 * prevent potential clipping issues when applying 3D transforms on a view.</p> 2545 * 2546 * @see #getLayerType() 2547 * @see #setLayerType(int, android.graphics.Paint) 2548 * @see #LAYER_TYPE_NONE 2549 * @see #LAYER_TYPE_SOFTWARE 2550 */ 2551 public static final int LAYER_TYPE_HARDWARE = 2; 2552 2553 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 2554 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 2555 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 2556 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 2557 }) 2558 int mLayerType = LAYER_TYPE_NONE; 2559 Paint mLayerPaint; 2560 Rect mLocalDirtyRect; 2561 2562 /** 2563 * Set to true when the view is sending hover accessibility events because it 2564 * is the innermost hovered view. 2565 */ 2566 private boolean mSendingHoverAccessibilityEvents; 2567 2568 /** 2569 * Delegate for injecting accessiblity functionality. 2570 */ 2571 AccessibilityDelegate mAccessibilityDelegate; 2572 2573 /** 2574 * Text direction is inherited thru {@link ViewGroup} 2575 * @hide 2576 */ 2577 public static final int TEXT_DIRECTION_INHERIT = 0; 2578 2579 /** 2580 * Text direction is using "first strong algorithm". The first strong directional character 2581 * determines the paragraph direction. If there is no strong directional character, the 2582 * paragraph direction is the view's resolved ayout direction. 2583 * 2584 * @hide 2585 */ 2586 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 2587 2588 /** 2589 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 2590 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 2591 * If there are neither, the paragraph direction is the view's resolved layout direction. 2592 * 2593 * @hide 2594 */ 2595 public static final int TEXT_DIRECTION_ANY_RTL = 2; 2596 2597 /** 2598 * Text direction is forced to LTR. 2599 * 2600 * @hide 2601 */ 2602 public static final int TEXT_DIRECTION_LTR = 3; 2603 2604 /** 2605 * Text direction is forced to RTL. 2606 * 2607 * @hide 2608 */ 2609 public static final int TEXT_DIRECTION_RTL = 4; 2610 2611 /** 2612 * Default text direction is inherited 2613 * 2614 * @hide 2615 */ 2616 protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT; 2617 2618 /** 2619 * The text direction that has been defined by {@link #setTextDirection(int)}. 2620 * 2621 * {@hide} 2622 */ 2623 @ViewDebug.ExportedProperty(category = "text", mapping = { 2624 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 2625 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 2626 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 2627 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 2628 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL") 2629 }) 2630 private int mTextDirection = DEFAULT_TEXT_DIRECTION; 2631 2632 /** 2633 * The resolved text direction. This needs resolution if the value is 2634 * TEXT_DIRECTION_INHERIT. The resolution matches mTextDirection if that is 2635 * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent 2636 * chain of the view. 2637 * 2638 * {@hide} 2639 */ 2640 @ViewDebug.ExportedProperty(category = "text", mapping = { 2641 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 2642 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 2643 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 2644 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 2645 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL") 2646 }) 2647 private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT; 2648 2649 /** 2650 * Consistency verifier for debugging purposes. 2651 * @hide 2652 */ 2653 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 2654 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 2655 new InputEventConsistencyVerifier(this, 0) : null; 2656 2657 /** 2658 * Simple constructor to use when creating a view from code. 2659 * 2660 * @param context The Context the view is running in, through which it can 2661 * access the current theme, resources, etc. 2662 */ 2663 public View(Context context) { 2664 mContext = context; 2665 mResources = context != null ? context.getResources() : null; 2666 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT; 2667 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 2668 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 2669 mUserPaddingStart = -1; 2670 mUserPaddingEnd = -1; 2671 mUserPaddingRelative = false; 2672 } 2673 2674 /** 2675 * Constructor that is called when inflating a view from XML. This is called 2676 * when a view is being constructed from an XML file, supplying attributes 2677 * that were specified in the XML file. This version uses a default style of 2678 * 0, so the only attribute values applied are those in the Context's Theme 2679 * and the given AttributeSet. 2680 * 2681 * <p> 2682 * The method onFinishInflate() will be called after all children have been 2683 * added. 2684 * 2685 * @param context The Context the view is running in, through which it can 2686 * access the current theme, resources, etc. 2687 * @param attrs The attributes of the XML tag that is inflating the view. 2688 * @see #View(Context, AttributeSet, int) 2689 */ 2690 public View(Context context, AttributeSet attrs) { 2691 this(context, attrs, 0); 2692 } 2693 2694 /** 2695 * Perform inflation from XML and apply a class-specific base style. This 2696 * constructor of View allows subclasses to use their own base style when 2697 * they are inflating. For example, a Button class's constructor would call 2698 * this version of the super class constructor and supply 2699 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 2700 * the theme's button style to modify all of the base view attributes (in 2701 * particular its background) as well as the Button class's attributes. 2702 * 2703 * @param context The Context the view is running in, through which it can 2704 * access the current theme, resources, etc. 2705 * @param attrs The attributes of the XML tag that is inflating the view. 2706 * @param defStyle The default style to apply to this view. If 0, no style 2707 * will be applied (beyond what is included in the theme). This may 2708 * either be an attribute resource, whose value will be retrieved 2709 * from the current theme, or an explicit style resource. 2710 * @see #View(Context, AttributeSet) 2711 */ 2712 public View(Context context, AttributeSet attrs, int defStyle) { 2713 this(context); 2714 2715 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 2716 defStyle, 0); 2717 2718 Drawable background = null; 2719 2720 int leftPadding = -1; 2721 int topPadding = -1; 2722 int rightPadding = -1; 2723 int bottomPadding = -1; 2724 int startPadding = -1; 2725 int endPadding = -1; 2726 2727 int padding = -1; 2728 2729 int viewFlagValues = 0; 2730 int viewFlagMasks = 0; 2731 2732 boolean setScrollContainer = false; 2733 2734 int x = 0; 2735 int y = 0; 2736 2737 float tx = 0; 2738 float ty = 0; 2739 float rotation = 0; 2740 float rotationX = 0; 2741 float rotationY = 0; 2742 float sx = 1f; 2743 float sy = 1f; 2744 boolean transformSet = false; 2745 2746 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 2747 2748 int overScrollMode = mOverScrollMode; 2749 final int N = a.getIndexCount(); 2750 for (int i = 0; i < N; i++) { 2751 int attr = a.getIndex(i); 2752 switch (attr) { 2753 case com.android.internal.R.styleable.View_background: 2754 background = a.getDrawable(attr); 2755 break; 2756 case com.android.internal.R.styleable.View_padding: 2757 padding = a.getDimensionPixelSize(attr, -1); 2758 break; 2759 case com.android.internal.R.styleable.View_paddingLeft: 2760 leftPadding = a.getDimensionPixelSize(attr, -1); 2761 break; 2762 case com.android.internal.R.styleable.View_paddingTop: 2763 topPadding = a.getDimensionPixelSize(attr, -1); 2764 break; 2765 case com.android.internal.R.styleable.View_paddingRight: 2766 rightPadding = a.getDimensionPixelSize(attr, -1); 2767 break; 2768 case com.android.internal.R.styleable.View_paddingBottom: 2769 bottomPadding = a.getDimensionPixelSize(attr, -1); 2770 break; 2771 case com.android.internal.R.styleable.View_paddingStart: 2772 startPadding = a.getDimensionPixelSize(attr, -1); 2773 break; 2774 case com.android.internal.R.styleable.View_paddingEnd: 2775 endPadding = a.getDimensionPixelSize(attr, -1); 2776 break; 2777 case com.android.internal.R.styleable.View_scrollX: 2778 x = a.getDimensionPixelOffset(attr, 0); 2779 break; 2780 case com.android.internal.R.styleable.View_scrollY: 2781 y = a.getDimensionPixelOffset(attr, 0); 2782 break; 2783 case com.android.internal.R.styleable.View_alpha: 2784 setAlpha(a.getFloat(attr, 1f)); 2785 break; 2786 case com.android.internal.R.styleable.View_transformPivotX: 2787 setPivotX(a.getDimensionPixelOffset(attr, 0)); 2788 break; 2789 case com.android.internal.R.styleable.View_transformPivotY: 2790 setPivotY(a.getDimensionPixelOffset(attr, 0)); 2791 break; 2792 case com.android.internal.R.styleable.View_translationX: 2793 tx = a.getDimensionPixelOffset(attr, 0); 2794 transformSet = true; 2795 break; 2796 case com.android.internal.R.styleable.View_translationY: 2797 ty = a.getDimensionPixelOffset(attr, 0); 2798 transformSet = true; 2799 break; 2800 case com.android.internal.R.styleable.View_rotation: 2801 rotation = a.getFloat(attr, 0); 2802 transformSet = true; 2803 break; 2804 case com.android.internal.R.styleable.View_rotationX: 2805 rotationX = a.getFloat(attr, 0); 2806 transformSet = true; 2807 break; 2808 case com.android.internal.R.styleable.View_rotationY: 2809 rotationY = a.getFloat(attr, 0); 2810 transformSet = true; 2811 break; 2812 case com.android.internal.R.styleable.View_scaleX: 2813 sx = a.getFloat(attr, 1f); 2814 transformSet = true; 2815 break; 2816 case com.android.internal.R.styleable.View_scaleY: 2817 sy = a.getFloat(attr, 1f); 2818 transformSet = true; 2819 break; 2820 case com.android.internal.R.styleable.View_id: 2821 mID = a.getResourceId(attr, NO_ID); 2822 break; 2823 case com.android.internal.R.styleable.View_tag: 2824 mTag = a.getText(attr); 2825 break; 2826 case com.android.internal.R.styleable.View_fitsSystemWindows: 2827 if (a.getBoolean(attr, false)) { 2828 viewFlagValues |= FITS_SYSTEM_WINDOWS; 2829 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 2830 } 2831 break; 2832 case com.android.internal.R.styleable.View_focusable: 2833 if (a.getBoolean(attr, false)) { 2834 viewFlagValues |= FOCUSABLE; 2835 viewFlagMasks |= FOCUSABLE_MASK; 2836 } 2837 break; 2838 case com.android.internal.R.styleable.View_focusableInTouchMode: 2839 if (a.getBoolean(attr, false)) { 2840 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 2841 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 2842 } 2843 break; 2844 case com.android.internal.R.styleable.View_clickable: 2845 if (a.getBoolean(attr, false)) { 2846 viewFlagValues |= CLICKABLE; 2847 viewFlagMasks |= CLICKABLE; 2848 } 2849 break; 2850 case com.android.internal.R.styleable.View_longClickable: 2851 if (a.getBoolean(attr, false)) { 2852 viewFlagValues |= LONG_CLICKABLE; 2853 viewFlagMasks |= LONG_CLICKABLE; 2854 } 2855 break; 2856 case com.android.internal.R.styleable.View_saveEnabled: 2857 if (!a.getBoolean(attr, true)) { 2858 viewFlagValues |= SAVE_DISABLED; 2859 viewFlagMasks |= SAVE_DISABLED_MASK; 2860 } 2861 break; 2862 case com.android.internal.R.styleable.View_duplicateParentState: 2863 if (a.getBoolean(attr, false)) { 2864 viewFlagValues |= DUPLICATE_PARENT_STATE; 2865 viewFlagMasks |= DUPLICATE_PARENT_STATE; 2866 } 2867 break; 2868 case com.android.internal.R.styleable.View_visibility: 2869 final int visibility = a.getInt(attr, 0); 2870 if (visibility != 0) { 2871 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 2872 viewFlagMasks |= VISIBILITY_MASK; 2873 } 2874 break; 2875 case com.android.internal.R.styleable.View_layoutDirection: 2876 // Clear any HORIZONTAL_DIRECTION flag already set 2877 viewFlagValues &= ~LAYOUT_DIRECTION_MASK; 2878 // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute 2879 final int layoutDirection = a.getInt(attr, -1); 2880 if (layoutDirection != -1) { 2881 viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection]; 2882 } else { 2883 // Set to default (LAYOUT_DIRECTION_INHERIT) 2884 viewFlagValues |= LAYOUT_DIRECTION_DEFAULT; 2885 } 2886 viewFlagMasks |= LAYOUT_DIRECTION_MASK; 2887 break; 2888 case com.android.internal.R.styleable.View_drawingCacheQuality: 2889 final int cacheQuality = a.getInt(attr, 0); 2890 if (cacheQuality != 0) { 2891 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 2892 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 2893 } 2894 break; 2895 case com.android.internal.R.styleable.View_contentDescription: 2896 mContentDescription = a.getString(attr); 2897 break; 2898 case com.android.internal.R.styleable.View_soundEffectsEnabled: 2899 if (!a.getBoolean(attr, true)) { 2900 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 2901 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 2902 } 2903 break; 2904 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 2905 if (!a.getBoolean(attr, true)) { 2906 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 2907 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 2908 } 2909 break; 2910 case R.styleable.View_scrollbars: 2911 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 2912 if (scrollbars != SCROLLBARS_NONE) { 2913 viewFlagValues |= scrollbars; 2914 viewFlagMasks |= SCROLLBARS_MASK; 2915 initializeScrollbars(a); 2916 } 2917 break; 2918 case R.styleable.View_fadingEdge: 2919 if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) { 2920 // Ignore the attribute starting with ICS 2921 break; 2922 } 2923 // With builds < ICS, fall through and apply fading edges 2924 case R.styleable.View_requiresFadingEdge: 2925 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 2926 if (fadingEdge != FADING_EDGE_NONE) { 2927 viewFlagValues |= fadingEdge; 2928 viewFlagMasks |= FADING_EDGE_MASK; 2929 initializeFadingEdge(a); 2930 } 2931 break; 2932 case R.styleable.View_scrollbarStyle: 2933 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 2934 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 2935 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 2936 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 2937 } 2938 break; 2939 case R.styleable.View_isScrollContainer: 2940 setScrollContainer = true; 2941 if (a.getBoolean(attr, false)) { 2942 setScrollContainer(true); 2943 } 2944 break; 2945 case com.android.internal.R.styleable.View_keepScreenOn: 2946 if (a.getBoolean(attr, false)) { 2947 viewFlagValues |= KEEP_SCREEN_ON; 2948 viewFlagMasks |= KEEP_SCREEN_ON; 2949 } 2950 break; 2951 case R.styleable.View_filterTouchesWhenObscured: 2952 if (a.getBoolean(attr, false)) { 2953 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 2954 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 2955 } 2956 break; 2957 case R.styleable.View_nextFocusLeft: 2958 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 2959 break; 2960 case R.styleable.View_nextFocusRight: 2961 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 2962 break; 2963 case R.styleable.View_nextFocusUp: 2964 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 2965 break; 2966 case R.styleable.View_nextFocusDown: 2967 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 2968 break; 2969 case R.styleable.View_nextFocusForward: 2970 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 2971 break; 2972 case R.styleable.View_minWidth: 2973 mMinWidth = a.getDimensionPixelSize(attr, 0); 2974 break; 2975 case R.styleable.View_minHeight: 2976 mMinHeight = a.getDimensionPixelSize(attr, 0); 2977 break; 2978 case R.styleable.View_onClick: 2979 if (context.isRestricted()) { 2980 throw new IllegalStateException("The android:onClick attribute cannot " 2981 + "be used within a restricted context"); 2982 } 2983 2984 final String handlerName = a.getString(attr); 2985 if (handlerName != null) { 2986 setOnClickListener(new OnClickListener() { 2987 private Method mHandler; 2988 2989 public void onClick(View v) { 2990 if (mHandler == null) { 2991 try { 2992 mHandler = getContext().getClass().getMethod(handlerName, 2993 View.class); 2994 } catch (NoSuchMethodException e) { 2995 int id = getId(); 2996 String idText = id == NO_ID ? "" : " with id '" 2997 + getContext().getResources().getResourceEntryName( 2998 id) + "'"; 2999 throw new IllegalStateException("Could not find a method " + 3000 handlerName + "(View) in the activity " 3001 + getContext().getClass() + " for onClick handler" 3002 + " on view " + View.this.getClass() + idText, e); 3003 } 3004 } 3005 3006 try { 3007 mHandler.invoke(getContext(), View.this); 3008 } catch (IllegalAccessException e) { 3009 throw new IllegalStateException("Could not execute non " 3010 + "public method of the activity", e); 3011 } catch (InvocationTargetException e) { 3012 throw new IllegalStateException("Could not execute " 3013 + "method of the activity", e); 3014 } 3015 } 3016 }); 3017 } 3018 break; 3019 case R.styleable.View_overScrollMode: 3020 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3021 break; 3022 case R.styleable.View_verticalScrollbarPosition: 3023 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3024 break; 3025 case R.styleable.View_layerType: 3026 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3027 break; 3028 case R.styleable.View_textDirection: 3029 mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION); 3030 break; 3031 } 3032 } 3033 3034 a.recycle(); 3035 3036 setOverScrollMode(overScrollMode); 3037 3038 if (background != null) { 3039 setBackgroundDrawable(background); 3040 } 3041 3042 mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0); 3043 3044 // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved 3045 // layout direction). Those cached values will be used later during padding resolution. 3046 mUserPaddingStart = startPadding; 3047 mUserPaddingEnd = endPadding; 3048 3049 if (padding >= 0) { 3050 leftPadding = padding; 3051 topPadding = padding; 3052 rightPadding = padding; 3053 bottomPadding = padding; 3054 } 3055 3056 // If the user specified the padding (either with android:padding or 3057 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 3058 // use the default padding or the padding from the background drawable 3059 // (stored at this point in mPadding*) 3060 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft, 3061 topPadding >= 0 ? topPadding : mPaddingTop, 3062 rightPadding >= 0 ? rightPadding : mPaddingRight, 3063 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3064 3065 if (viewFlagMasks != 0) { 3066 setFlags(viewFlagValues, viewFlagMasks); 3067 } 3068 3069 // Needs to be called after mViewFlags is set 3070 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3071 recomputePadding(); 3072 } 3073 3074 if (x != 0 || y != 0) { 3075 scrollTo(x, y); 3076 } 3077 3078 if (transformSet) { 3079 setTranslationX(tx); 3080 setTranslationY(ty); 3081 setRotation(rotation); 3082 setRotationX(rotationX); 3083 setRotationY(rotationY); 3084 setScaleX(sx); 3085 setScaleY(sy); 3086 } 3087 3088 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3089 setScrollContainer(true); 3090 } 3091 3092 computeOpaqueFlags(); 3093 } 3094 3095 /** 3096 * Non-public constructor for use in testing 3097 */ 3098 View() { 3099 mResources = null; 3100 } 3101 3102 /** 3103 * <p> 3104 * Initializes the fading edges from a given set of styled attributes. This 3105 * method should be called by subclasses that need fading edges and when an 3106 * instance of these subclasses is created programmatically rather than 3107 * being inflated from XML. This method is automatically called when the XML 3108 * is inflated. 3109 * </p> 3110 * 3111 * @param a the styled attributes set to initialize the fading edges from 3112 */ 3113 protected void initializeFadingEdge(TypedArray a) { 3114 initScrollCache(); 3115 3116 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3117 R.styleable.View_fadingEdgeLength, 3118 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3119 } 3120 3121 /** 3122 * Returns the size of the vertical faded edges used to indicate that more 3123 * content in this view is visible. 3124 * 3125 * @return The size in pixels of the vertical faded edge or 0 if vertical 3126 * faded edges are not enabled for this view. 3127 * @attr ref android.R.styleable#View_fadingEdgeLength 3128 */ 3129 public int getVerticalFadingEdgeLength() { 3130 if (isVerticalFadingEdgeEnabled()) { 3131 ScrollabilityCache cache = mScrollCache; 3132 if (cache != null) { 3133 return cache.fadingEdgeLength; 3134 } 3135 } 3136 return 0; 3137 } 3138 3139 /** 3140 * Set the size of the faded edge used to indicate that more content in this 3141 * view is available. Will not change whether the fading edge is enabled; use 3142 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3143 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3144 * for the vertical or horizontal fading edges. 3145 * 3146 * @param length The size in pixels of the faded edge used to indicate that more 3147 * content in this view is visible. 3148 */ 3149 public void setFadingEdgeLength(int length) { 3150 initScrollCache(); 3151 mScrollCache.fadingEdgeLength = length; 3152 } 3153 3154 /** 3155 * Returns the size of the horizontal faded edges used to indicate that more 3156 * content in this view is visible. 3157 * 3158 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3159 * faded edges are not enabled for this view. 3160 * @attr ref android.R.styleable#View_fadingEdgeLength 3161 */ 3162 public int getHorizontalFadingEdgeLength() { 3163 if (isHorizontalFadingEdgeEnabled()) { 3164 ScrollabilityCache cache = mScrollCache; 3165 if (cache != null) { 3166 return cache.fadingEdgeLength; 3167 } 3168 } 3169 return 0; 3170 } 3171 3172 /** 3173 * Returns the width of the vertical scrollbar. 3174 * 3175 * @return The width in pixels of the vertical scrollbar or 0 if there 3176 * is no vertical scrollbar. 3177 */ 3178 public int getVerticalScrollbarWidth() { 3179 ScrollabilityCache cache = mScrollCache; 3180 if (cache != null) { 3181 ScrollBarDrawable scrollBar = cache.scrollBar; 3182 if (scrollBar != null) { 3183 int size = scrollBar.getSize(true); 3184 if (size <= 0) { 3185 size = cache.scrollBarSize; 3186 } 3187 return size; 3188 } 3189 return 0; 3190 } 3191 return 0; 3192 } 3193 3194 /** 3195 * Returns the height of the horizontal scrollbar. 3196 * 3197 * @return The height in pixels of the horizontal scrollbar or 0 if 3198 * there is no horizontal scrollbar. 3199 */ 3200 protected int getHorizontalScrollbarHeight() { 3201 ScrollabilityCache cache = mScrollCache; 3202 if (cache != null) { 3203 ScrollBarDrawable scrollBar = cache.scrollBar; 3204 if (scrollBar != null) { 3205 int size = scrollBar.getSize(false); 3206 if (size <= 0) { 3207 size = cache.scrollBarSize; 3208 } 3209 return size; 3210 } 3211 return 0; 3212 } 3213 return 0; 3214 } 3215 3216 /** 3217 * <p> 3218 * Initializes the scrollbars from a given set of styled attributes. This 3219 * method should be called by subclasses that need scrollbars and when an 3220 * instance of these subclasses is created programmatically rather than 3221 * being inflated from XML. This method is automatically called when the XML 3222 * is inflated. 3223 * </p> 3224 * 3225 * @param a the styled attributes set to initialize the scrollbars from 3226 */ 3227 protected void initializeScrollbars(TypedArray a) { 3228 initScrollCache(); 3229 3230 final ScrollabilityCache scrollabilityCache = mScrollCache; 3231 3232 if (scrollabilityCache.scrollBar == null) { 3233 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 3234 } 3235 3236 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 3237 3238 if (!fadeScrollbars) { 3239 scrollabilityCache.state = ScrollabilityCache.ON; 3240 } 3241 scrollabilityCache.fadeScrollBars = fadeScrollbars; 3242 3243 3244 scrollabilityCache.scrollBarFadeDuration = a.getInt( 3245 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 3246 .getScrollBarFadeDuration()); 3247 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 3248 R.styleable.View_scrollbarDefaultDelayBeforeFade, 3249 ViewConfiguration.getScrollDefaultDelay()); 3250 3251 3252 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 3253 com.android.internal.R.styleable.View_scrollbarSize, 3254 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3255 3256 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3257 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3258 3259 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3260 if (thumb != null) { 3261 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3262 } 3263 3264 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3265 false); 3266 if (alwaysDraw) { 3267 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3268 } 3269 3270 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3271 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3272 3273 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3274 if (thumb != null) { 3275 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3276 } 3277 3278 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3279 false); 3280 if (alwaysDraw) { 3281 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3282 } 3283 3284 // Re-apply user/background padding so that scrollbar(s) get added 3285 resolvePadding(); 3286 } 3287 3288 /** 3289 * <p> 3290 * Initalizes the scrollability cache if necessary. 3291 * </p> 3292 */ 3293 private void initScrollCache() { 3294 if (mScrollCache == null) { 3295 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 3296 } 3297 } 3298 3299 /** 3300 * Set the position of the vertical scroll bar. Should be one of 3301 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 3302 * {@link #SCROLLBAR_POSITION_RIGHT}. 3303 * 3304 * @param position Where the vertical scroll bar should be positioned. 3305 */ 3306 public void setVerticalScrollbarPosition(int position) { 3307 if (mVerticalScrollbarPosition != position) { 3308 mVerticalScrollbarPosition = position; 3309 computeOpaqueFlags(); 3310 resolvePadding(); 3311 } 3312 } 3313 3314 /** 3315 * @return The position where the vertical scroll bar will show, if applicable. 3316 * @see #setVerticalScrollbarPosition(int) 3317 */ 3318 public int getVerticalScrollbarPosition() { 3319 return mVerticalScrollbarPosition; 3320 } 3321 3322 /** 3323 * Register a callback to be invoked when focus of this view changed. 3324 * 3325 * @param l The callback that will run. 3326 */ 3327 public void setOnFocusChangeListener(OnFocusChangeListener l) { 3328 mOnFocusChangeListener = l; 3329 } 3330 3331 /** 3332 * Add a listener that will be called when the bounds of the view change due to 3333 * layout processing. 3334 * 3335 * @param listener The listener that will be called when layout bounds change. 3336 */ 3337 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 3338 if (mOnLayoutChangeListeners == null) { 3339 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 3340 } 3341 mOnLayoutChangeListeners.add(listener); 3342 } 3343 3344 /** 3345 * Remove a listener for layout changes. 3346 * 3347 * @param listener The listener for layout bounds change. 3348 */ 3349 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 3350 if (mOnLayoutChangeListeners == null) { 3351 return; 3352 } 3353 mOnLayoutChangeListeners.remove(listener); 3354 } 3355 3356 /** 3357 * Add a listener for attach state changes. 3358 * 3359 * This listener will be called whenever this view is attached or detached 3360 * from a window. Remove the listener using 3361 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 3362 * 3363 * @param listener Listener to attach 3364 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 3365 */ 3366 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3367 if (mOnAttachStateChangeListeners == null) { 3368 mOnAttachStateChangeListeners = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 3369 } 3370 mOnAttachStateChangeListeners.add(listener); 3371 } 3372 3373 /** 3374 * Remove a listener for attach state changes. The listener will receive no further 3375 * notification of window attach/detach events. 3376 * 3377 * @param listener Listener to remove 3378 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 3379 */ 3380 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3381 if (mOnAttachStateChangeListeners == null) { 3382 return; 3383 } 3384 mOnAttachStateChangeListeners.remove(listener); 3385 } 3386 3387 /** 3388 * Returns the focus-change callback registered for this view. 3389 * 3390 * @return The callback, or null if one is not registered. 3391 */ 3392 public OnFocusChangeListener getOnFocusChangeListener() { 3393 return mOnFocusChangeListener; 3394 } 3395 3396 /** 3397 * Register a callback to be invoked when this view is clicked. If this view is not 3398 * clickable, it becomes clickable. 3399 * 3400 * @param l The callback that will run 3401 * 3402 * @see #setClickable(boolean) 3403 */ 3404 public void setOnClickListener(OnClickListener l) { 3405 if (!isClickable()) { 3406 setClickable(true); 3407 } 3408 mOnClickListener = l; 3409 } 3410 3411 /** 3412 * Register a callback to be invoked when this view is clicked and held. If this view is not 3413 * long clickable, it becomes long clickable. 3414 * 3415 * @param l The callback that will run 3416 * 3417 * @see #setLongClickable(boolean) 3418 */ 3419 public void setOnLongClickListener(OnLongClickListener l) { 3420 if (!isLongClickable()) { 3421 setLongClickable(true); 3422 } 3423 mOnLongClickListener = l; 3424 } 3425 3426 /** 3427 * Register a callback to be invoked when the context menu for this view is 3428 * being built. If this view is not long clickable, it becomes long clickable. 3429 * 3430 * @param l The callback that will run 3431 * 3432 */ 3433 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 3434 if (!isLongClickable()) { 3435 setLongClickable(true); 3436 } 3437 mOnCreateContextMenuListener = l; 3438 } 3439 3440 /** 3441 * Call this view's OnClickListener, if it is defined. 3442 * 3443 * @return True there was an assigned OnClickListener that was called, false 3444 * otherwise is returned. 3445 */ 3446 public boolean performClick() { 3447 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 3448 3449 if (mOnClickListener != null) { 3450 playSoundEffect(SoundEffectConstants.CLICK); 3451 mOnClickListener.onClick(this); 3452 return true; 3453 } 3454 3455 return false; 3456 } 3457 3458 /** 3459 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 3460 * OnLongClickListener did not consume the event. 3461 * 3462 * @return True if one of the above receivers consumed the event, false otherwise. 3463 */ 3464 public boolean performLongClick() { 3465 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 3466 3467 boolean handled = false; 3468 if (mOnLongClickListener != null) { 3469 handled = mOnLongClickListener.onLongClick(View.this); 3470 } 3471 if (!handled) { 3472 handled = showContextMenu(); 3473 } 3474 if (handled) { 3475 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 3476 } 3477 return handled; 3478 } 3479 3480 /** 3481 * Performs button-related actions during a touch down event. 3482 * 3483 * @param event The event. 3484 * @return True if the down was consumed. 3485 * 3486 * @hide 3487 */ 3488 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 3489 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 3490 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 3491 return true; 3492 } 3493 } 3494 return false; 3495 } 3496 3497 /** 3498 * Bring up the context menu for this view. 3499 * 3500 * @return Whether a context menu was displayed. 3501 */ 3502 public boolean showContextMenu() { 3503 return getParent().showContextMenuForChild(this); 3504 } 3505 3506 /** 3507 * Bring up the context menu for this view, referring to the item under the specified point. 3508 * 3509 * @param x The referenced x coordinate. 3510 * @param y The referenced y coordinate. 3511 * @param metaState The keyboard modifiers that were pressed. 3512 * @return Whether a context menu was displayed. 3513 * 3514 * @hide 3515 */ 3516 public boolean showContextMenu(float x, float y, int metaState) { 3517 return showContextMenu(); 3518 } 3519 3520 /** 3521 * Start an action mode. 3522 * 3523 * @param callback Callback that will control the lifecycle of the action mode 3524 * @return The new action mode if it is started, null otherwise 3525 * 3526 * @see ActionMode 3527 */ 3528 public ActionMode startActionMode(ActionMode.Callback callback) { 3529 return getParent().startActionModeForChild(this, callback); 3530 } 3531 3532 /** 3533 * Register a callback to be invoked when a key is pressed in this view. 3534 * @param l the key listener to attach to this view 3535 */ 3536 public void setOnKeyListener(OnKeyListener l) { 3537 mOnKeyListener = l; 3538 } 3539 3540 /** 3541 * Register a callback to be invoked when a touch event is sent to this view. 3542 * @param l the touch listener to attach to this view 3543 */ 3544 public void setOnTouchListener(OnTouchListener l) { 3545 mOnTouchListener = l; 3546 } 3547 3548 /** 3549 * Register a callback to be invoked when a generic motion event is sent to this view. 3550 * @param l the generic motion listener to attach to this view 3551 */ 3552 public void setOnGenericMotionListener(OnGenericMotionListener l) { 3553 mOnGenericMotionListener = l; 3554 } 3555 3556 /** 3557 * Register a callback to be invoked when a hover event is sent to this view. 3558 * @param l the hover listener to attach to this view 3559 */ 3560 public void setOnHoverListener(OnHoverListener l) { 3561 mOnHoverListener = l; 3562 } 3563 3564 /** 3565 * Register a drag event listener callback object for this View. The parameter is 3566 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 3567 * View, the system calls the 3568 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 3569 * @param l An implementation of {@link android.view.View.OnDragListener}. 3570 */ 3571 public void setOnDragListener(OnDragListener l) { 3572 mOnDragListener = l; 3573 } 3574 3575 /** 3576 * Give this view focus. This will cause 3577 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3578 * 3579 * Note: this does not check whether this {@link View} should get focus, it just 3580 * gives it focus no matter what. It should only be called internally by framework 3581 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 3582 * 3583 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 3584 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 3585 * focus moved when requestFocus() is called. It may not always 3586 * apply, in which case use the default View.FOCUS_DOWN. 3587 * @param previouslyFocusedRect The rectangle of the view that had focus 3588 * prior in this View's coordinate system. 3589 */ 3590 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 3591 if (DBG) { 3592 System.out.println(this + " requestFocus()"); 3593 } 3594 3595 if ((mPrivateFlags & FOCUSED) == 0) { 3596 mPrivateFlags |= FOCUSED; 3597 3598 if (mParent != null) { 3599 mParent.requestChildFocus(this, this); 3600 } 3601 3602 onFocusChanged(true, direction, previouslyFocusedRect); 3603 refreshDrawableState(); 3604 } 3605 } 3606 3607 /** 3608 * Request that a rectangle of this view be visible on the screen, 3609 * scrolling if necessary just enough. 3610 * 3611 * <p>A View should call this if it maintains some notion of which part 3612 * of its content is interesting. For example, a text editing view 3613 * should call this when its cursor moves. 3614 * 3615 * @param rectangle The rectangle. 3616 * @return Whether any parent scrolled. 3617 */ 3618 public boolean requestRectangleOnScreen(Rect rectangle) { 3619 return requestRectangleOnScreen(rectangle, false); 3620 } 3621 3622 /** 3623 * Request that a rectangle of this view be visible on the screen, 3624 * scrolling if necessary just enough. 3625 * 3626 * <p>A View should call this if it maintains some notion of which part 3627 * of its content is interesting. For example, a text editing view 3628 * should call this when its cursor moves. 3629 * 3630 * <p>When <code>immediate</code> is set to true, scrolling will not be 3631 * animated. 3632 * 3633 * @param rectangle The rectangle. 3634 * @param immediate True to forbid animated scrolling, false otherwise 3635 * @return Whether any parent scrolled. 3636 */ 3637 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 3638 View child = this; 3639 ViewParent parent = mParent; 3640 boolean scrolled = false; 3641 while (parent != null) { 3642 scrolled |= parent.requestChildRectangleOnScreen(child, 3643 rectangle, immediate); 3644 3645 // offset rect so next call has the rectangle in the 3646 // coordinate system of its direct child. 3647 rectangle.offset(child.getLeft(), child.getTop()); 3648 rectangle.offset(-child.getScrollX(), -child.getScrollY()); 3649 3650 if (!(parent instanceof View)) { 3651 break; 3652 } 3653 3654 child = (View) parent; 3655 parent = child.getParent(); 3656 } 3657 return scrolled; 3658 } 3659 3660 /** 3661 * Called when this view wants to give up focus. This will cause 3662 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3663 */ 3664 public void clearFocus() { 3665 if (DBG) { 3666 System.out.println(this + " clearFocus()"); 3667 } 3668 3669 if ((mPrivateFlags & FOCUSED) != 0) { 3670 mPrivateFlags &= ~FOCUSED; 3671 3672 if (mParent != null) { 3673 mParent.clearChildFocus(this); 3674 } 3675 3676 onFocusChanged(false, 0, null); 3677 refreshDrawableState(); 3678 } 3679 } 3680 3681 /** 3682 * Called to clear the focus of a view that is about to be removed. 3683 * Doesn't call clearChildFocus, which prevents this view from taking 3684 * focus again before it has been removed from the parent 3685 */ 3686 void clearFocusForRemoval() { 3687 if ((mPrivateFlags & FOCUSED) != 0) { 3688 mPrivateFlags &= ~FOCUSED; 3689 3690 onFocusChanged(false, 0, null); 3691 refreshDrawableState(); 3692 } 3693 } 3694 3695 /** 3696 * Called internally by the view system when a new view is getting focus. 3697 * This is what clears the old focus. 3698 */ 3699 void unFocus() { 3700 if (DBG) { 3701 System.out.println(this + " unFocus()"); 3702 } 3703 3704 if ((mPrivateFlags & FOCUSED) != 0) { 3705 mPrivateFlags &= ~FOCUSED; 3706 3707 onFocusChanged(false, 0, null); 3708 refreshDrawableState(); 3709 } 3710 } 3711 3712 /** 3713 * Returns true if this view has focus iteself, or is the ancestor of the 3714 * view that has focus. 3715 * 3716 * @return True if this view has or contains focus, false otherwise. 3717 */ 3718 @ViewDebug.ExportedProperty(category = "focus") 3719 public boolean hasFocus() { 3720 return (mPrivateFlags & FOCUSED) != 0; 3721 } 3722 3723 /** 3724 * Returns true if this view is focusable or if it contains a reachable View 3725 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 3726 * is a View whose parents do not block descendants focus. 3727 * 3728 * Only {@link #VISIBLE} views are considered focusable. 3729 * 3730 * @return True if the view is focusable or if the view contains a focusable 3731 * View, false otherwise. 3732 * 3733 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 3734 */ 3735 public boolean hasFocusable() { 3736 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 3737 } 3738 3739 /** 3740 * Called by the view system when the focus state of this view changes. 3741 * When the focus change event is caused by directional navigation, direction 3742 * and previouslyFocusedRect provide insight into where the focus is coming from. 3743 * When overriding, be sure to call up through to the super class so that 3744 * the standard focus handling will occur. 3745 * 3746 * @param gainFocus True if the View has focus; false otherwise. 3747 * @param direction The direction focus has moved when requestFocus() 3748 * is called to give this view focus. Values are 3749 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 3750 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 3751 * It may not always apply, in which case use the default. 3752 * @param previouslyFocusedRect The rectangle, in this view's coordinate 3753 * system, of the previously focused view. If applicable, this will be 3754 * passed in as finer grained information about where the focus is coming 3755 * from (in addition to direction). Will be <code>null</code> otherwise. 3756 */ 3757 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 3758 if (gainFocus) { 3759 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 3760 } 3761 3762 InputMethodManager imm = InputMethodManager.peekInstance(); 3763 if (!gainFocus) { 3764 if (isPressed()) { 3765 setPressed(false); 3766 } 3767 if (imm != null && mAttachInfo != null 3768 && mAttachInfo.mHasWindowFocus) { 3769 imm.focusOut(this); 3770 } 3771 onFocusLost(); 3772 } else if (imm != null && mAttachInfo != null 3773 && mAttachInfo.mHasWindowFocus) { 3774 imm.focusIn(this); 3775 } 3776 3777 invalidate(true); 3778 if (mOnFocusChangeListener != null) { 3779 mOnFocusChangeListener.onFocusChange(this, gainFocus); 3780 } 3781 3782 if (mAttachInfo != null) { 3783 mAttachInfo.mKeyDispatchState.reset(this); 3784 } 3785 } 3786 3787 /** 3788 * Sends an accessibility event of the given type. If accessiiblity is 3789 * not enabled this method has no effect. The default implementation calls 3790 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 3791 * to populate information about the event source (this View), then calls 3792 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 3793 * populate the text content of the event source including its descendants, 3794 * and last calls 3795 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 3796 * on its parent to resuest sending of the event to interested parties. 3797 * <p> 3798 * If an {@link AccessibilityDelegate} has been specified via calling 3799 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3800 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 3801 * responsible for handling this call. 3802 * </p> 3803 * 3804 * @param eventType The type of the event to send. 3805 * 3806 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 3807 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3808 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 3809 * @see AccessibilityDelegate 3810 */ 3811 public void sendAccessibilityEvent(int eventType) { 3812 if (mAccessibilityDelegate != null) { 3813 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 3814 } else { 3815 sendAccessibilityEventInternal(eventType); 3816 } 3817 } 3818 3819 /** 3820 * @see #sendAccessibilityEvent(int) 3821 * 3822 * Note: Called from the default {@link AccessibilityDelegate}. 3823 */ 3824 void sendAccessibilityEventInternal(int eventType) { 3825 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 3826 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 3827 } 3828 } 3829 3830 /** 3831 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 3832 * takes as an argument an empty {@link AccessibilityEvent} and does not 3833 * perform a check whether accessibility is enabled. 3834 * <p> 3835 * If an {@link AccessibilityDelegate} has been specified via calling 3836 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3837 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 3838 * is responsible for handling this call. 3839 * </p> 3840 * 3841 * @param event The event to send. 3842 * 3843 * @see #sendAccessibilityEvent(int) 3844 */ 3845 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 3846 if (mAccessibilityDelegate != null) { 3847 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 3848 } else { 3849 sendAccessibilityEventUncheckedInternal(event); 3850 } 3851 } 3852 3853 /** 3854 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 3855 * 3856 * Note: Called from the default {@link AccessibilityDelegate}. 3857 */ 3858 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 3859 if (!isShown()) { 3860 return; 3861 } 3862 onInitializeAccessibilityEvent(event); 3863 dispatchPopulateAccessibilityEvent(event); 3864 // In the beginning we called #isShown(), so we know that getParent() is not null. 3865 getParent().requestSendAccessibilityEvent(this, event); 3866 } 3867 3868 /** 3869 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 3870 * to its children for adding their text content to the event. Note that the 3871 * event text is populated in a separate dispatch path since we add to the 3872 * event not only the text of the source but also the text of all its descendants. 3873 * A typical implementation will call 3874 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 3875 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3876 * on each child. Override this method if custom population of the event text 3877 * content is required. 3878 * <p> 3879 * If an {@link AccessibilityDelegate} has been specified via calling 3880 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3881 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 3882 * is responsible for handling this call. 3883 * </p> 3884 * 3885 * @param event The event. 3886 * 3887 * @return True if the event population was completed. 3888 */ 3889 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 3890 if (mAccessibilityDelegate != null) { 3891 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 3892 } else { 3893 return dispatchPopulateAccessibilityEventInternal(event); 3894 } 3895 } 3896 3897 /** 3898 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3899 * 3900 * Note: Called from the default {@link AccessibilityDelegate}. 3901 */ 3902 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 3903 onPopulateAccessibilityEvent(event); 3904 return false; 3905 } 3906 3907 /** 3908 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3909 * giving a chance to this View to populate the accessibility event with its 3910 * text content. While the implementation is free to modify other event 3911 * attributes this should be performed in 3912 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 3913 * <p> 3914 * Example: Adding formatted date string to an accessibility event in addition 3915 * to the text added by the super implementation. 3916 * </p><p><pre><code> 3917 * public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3918 * super.onPopulateAccessibilityEvent(event); 3919 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 3920 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 3921 * mCurrentDate.getTimeInMillis(), flags); 3922 * event.getText().add(selectedDateUtterance); 3923 * } 3924 * </code></pre></p> 3925 * <p> 3926 * If an {@link AccessibilityDelegate} has been specified via calling 3927 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3928 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 3929 * is responsible for handling this call. 3930 * </p> 3931 * 3932 * @param event The accessibility event which to populate. 3933 * 3934 * @see #sendAccessibilityEvent(int) 3935 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3936 */ 3937 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3938 if (mAccessibilityDelegate != null) { 3939 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 3940 } else { 3941 onPopulateAccessibilityEventInternal(event); 3942 } 3943 } 3944 3945 /** 3946 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 3947 * 3948 * Note: Called from the default {@link AccessibilityDelegate}. 3949 */ 3950 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 3951 3952 } 3953 3954 /** 3955 * Initializes an {@link AccessibilityEvent} with information about 3956 * this View which is the event source. In other words, the source of 3957 * an accessibility event is the view whose state change triggered firing 3958 * the event. 3959 * <p> 3960 * Example: Setting the password property of an event in addition 3961 * to properties set by the super implementation. 3962 * </p><p><pre><code> 3963 * public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 3964 * super.onInitializeAccessibilityEvent(event); 3965 * event.setPassword(true); 3966 * } 3967 * </code></pre></p> 3968 * <p> 3969 * If an {@link AccessibilityDelegate} has been specified via calling 3970 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3971 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 3972 * is responsible for handling this call. 3973 * </p> 3974 * 3975 * @param event The event to initialize. 3976 * 3977 * @see #sendAccessibilityEvent(int) 3978 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3979 */ 3980 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 3981 if (mAccessibilityDelegate != null) { 3982 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 3983 } else { 3984 onInitializeAccessibilityEventInternal(event); 3985 } 3986 } 3987 3988 /** 3989 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 3990 * 3991 * Note: Called from the default {@link AccessibilityDelegate}. 3992 */ 3993 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 3994 event.setSource(this); 3995 event.setClassName(getClass().getName()); 3996 event.setPackageName(getContext().getPackageName()); 3997 event.setEnabled(isEnabled()); 3998 event.setContentDescription(mContentDescription); 3999 4000 final int eventType = event.getEventType(); 4001 switch (eventType) { 4002 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 4003 if (mAttachInfo != null) { 4004 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList; 4005 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, 4006 FOCUSABLES_ALL); 4007 event.setItemCount(focusablesTempList.size()); 4008 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 4009 focusablesTempList.clear(); 4010 } 4011 } break; 4012 case AccessibilityEvent.TYPE_VIEW_SCROLLED: { 4013 event.setScrollX(mScrollX); 4014 event.setScrollY(mScrollY); 4015 event.setItemCount(getHeight()); 4016 } break; 4017 } 4018 } 4019 4020 /** 4021 * Returns an {@link AccessibilityNodeInfo} representing this view from the 4022 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 4023 * This method is responsible for obtaining an accessibility node info from a 4024 * pool of reusable instances and calling 4025 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 4026 * initialize the former. 4027 * <p> 4028 * Note: The client is responsible for recycling the obtained instance by calling 4029 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 4030 * </p> 4031 * @return A populated {@link AccessibilityNodeInfo}. 4032 * 4033 * @see AccessibilityNodeInfo 4034 */ 4035 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 4036 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 4037 onInitializeAccessibilityNodeInfo(info); 4038 return info; 4039 } 4040 4041 /** 4042 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 4043 * The base implementation sets: 4044 * <ul> 4045 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 4046 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 4047 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 4048 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 4049 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 4050 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 4051 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 4052 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 4053 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 4054 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 4055 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 4056 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 4057 * </ul> 4058 * <p> 4059 * Subclasses should override this method, call the super implementation, 4060 * and set additional attributes. 4061 * </p> 4062 * <p> 4063 * If an {@link AccessibilityDelegate} has been specified via calling 4064 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4065 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 4066 * is responsible for handling this call. 4067 * </p> 4068 * 4069 * @param info The instance to initialize. 4070 */ 4071 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 4072 if (mAccessibilityDelegate != null) { 4073 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 4074 } else { 4075 onInitializeAccessibilityNodeInfoInternal(info); 4076 } 4077 } 4078 4079 /** 4080 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 4081 * 4082 * Note: Called from the default {@link AccessibilityDelegate}. 4083 */ 4084 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 4085 Rect bounds = mAttachInfo.mTmpInvalRect; 4086 getDrawingRect(bounds); 4087 info.setBoundsInParent(bounds); 4088 4089 int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation; 4090 getLocationOnScreen(locationOnScreen); 4091 bounds.offsetTo(0, 0); 4092 bounds.offset(locationOnScreen[0], locationOnScreen[1]); 4093 info.setBoundsInScreen(bounds); 4094 4095 ViewParent parent = getParent(); 4096 if (parent instanceof View) { 4097 View parentView = (View) parent; 4098 info.setParent(parentView); 4099 } 4100 4101 info.setPackageName(mContext.getPackageName()); 4102 info.setClassName(getClass().getName()); 4103 info.setContentDescription(getContentDescription()); 4104 4105 info.setEnabled(isEnabled()); 4106 info.setClickable(isClickable()); 4107 info.setFocusable(isFocusable()); 4108 info.setFocused(isFocused()); 4109 info.setSelected(isSelected()); 4110 info.setLongClickable(isLongClickable()); 4111 4112 // TODO: These make sense only if we are in an AdapterView but all 4113 // views can be selected. Maybe from accessiiblity perspective 4114 // we should report as selectable view in an AdapterView. 4115 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 4116 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 4117 4118 if (isFocusable()) { 4119 if (isFocused()) { 4120 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 4121 } else { 4122 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 4123 } 4124 } 4125 } 4126 4127 /** 4128 * Sets a delegate for implementing accessibility support via compositon as 4129 * opposed to inheritance. The delegate's primary use is for implementing 4130 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 4131 * 4132 * @param delegate The delegate instance. 4133 * 4134 * @see AccessibilityDelegate 4135 */ 4136 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 4137 mAccessibilityDelegate = delegate; 4138 } 4139 4140 /** 4141 * Gets the unique identifier of this view on the screen for accessibility purposes. 4142 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 4143 * 4144 * @return The view accessibility id. 4145 * 4146 * @hide 4147 */ 4148 public int getAccessibilityViewId() { 4149 if (mAccessibilityViewId == NO_ID) { 4150 mAccessibilityViewId = sNextAccessibilityViewId++; 4151 } 4152 return mAccessibilityViewId; 4153 } 4154 4155 /** 4156 * Gets the unique identifier of the window in which this View reseides. 4157 * 4158 * @return The window accessibility id. 4159 * 4160 * @hide 4161 */ 4162 public int getAccessibilityWindowId() { 4163 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 4164 } 4165 4166 /** 4167 * Gets the {@link View} description. It briefly describes the view and is 4168 * primarily used for accessibility support. Set this property to enable 4169 * better accessibility support for your application. This is especially 4170 * true for views that do not have textual representation (For example, 4171 * ImageButton). 4172 * 4173 * @return The content descriptiopn. 4174 * 4175 * @attr ref android.R.styleable#View_contentDescription 4176 */ 4177 public CharSequence getContentDescription() { 4178 return mContentDescription; 4179 } 4180 4181 /** 4182 * Sets the {@link View} description. It briefly describes the view and is 4183 * primarily used for accessibility support. Set this property to enable 4184 * better accessibility support for your application. This is especially 4185 * true for views that do not have textual representation (For example, 4186 * ImageButton). 4187 * 4188 * @param contentDescription The content description. 4189 * 4190 * @attr ref android.R.styleable#View_contentDescription 4191 */ 4192 public void setContentDescription(CharSequence contentDescription) { 4193 mContentDescription = contentDescription; 4194 } 4195 4196 /** 4197 * Invoked whenever this view loses focus, either by losing window focus or by losing 4198 * focus within its window. This method can be used to clear any state tied to the 4199 * focus. For instance, if a button is held pressed with the trackball and the window 4200 * loses focus, this method can be used to cancel the press. 4201 * 4202 * Subclasses of View overriding this method should always call super.onFocusLost(). 4203 * 4204 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 4205 * @see #onWindowFocusChanged(boolean) 4206 * 4207 * @hide pending API council approval 4208 */ 4209 protected void onFocusLost() { 4210 resetPressedState(); 4211 } 4212 4213 private void resetPressedState() { 4214 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 4215 return; 4216 } 4217 4218 if (isPressed()) { 4219 setPressed(false); 4220 4221 if (!mHasPerformedLongPress) { 4222 removeLongPressCallback(); 4223 } 4224 } 4225 } 4226 4227 /** 4228 * Returns true if this view has focus 4229 * 4230 * @return True if this view has focus, false otherwise. 4231 */ 4232 @ViewDebug.ExportedProperty(category = "focus") 4233 public boolean isFocused() { 4234 return (mPrivateFlags & FOCUSED) != 0; 4235 } 4236 4237 /** 4238 * Find the view in the hierarchy rooted at this view that currently has 4239 * focus. 4240 * 4241 * @return The view that currently has focus, or null if no focused view can 4242 * be found. 4243 */ 4244 public View findFocus() { 4245 return (mPrivateFlags & FOCUSED) != 0 ? this : null; 4246 } 4247 4248 /** 4249 * Change whether this view is one of the set of scrollable containers in 4250 * its window. This will be used to determine whether the window can 4251 * resize or must pan when a soft input area is open -- scrollable 4252 * containers allow the window to use resize mode since the container 4253 * will appropriately shrink. 4254 */ 4255 public void setScrollContainer(boolean isScrollContainer) { 4256 if (isScrollContainer) { 4257 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) { 4258 mAttachInfo.mScrollContainers.add(this); 4259 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 4260 } 4261 mPrivateFlags |= SCROLL_CONTAINER; 4262 } else { 4263 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 4264 mAttachInfo.mScrollContainers.remove(this); 4265 } 4266 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED); 4267 } 4268 } 4269 4270 /** 4271 * Returns the quality of the drawing cache. 4272 * 4273 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4274 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4275 * 4276 * @see #setDrawingCacheQuality(int) 4277 * @see #setDrawingCacheEnabled(boolean) 4278 * @see #isDrawingCacheEnabled() 4279 * 4280 * @attr ref android.R.styleable#View_drawingCacheQuality 4281 */ 4282 public int getDrawingCacheQuality() { 4283 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 4284 } 4285 4286 /** 4287 * Set the drawing cache quality of this view. This value is used only when the 4288 * drawing cache is enabled 4289 * 4290 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4291 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4292 * 4293 * @see #getDrawingCacheQuality() 4294 * @see #setDrawingCacheEnabled(boolean) 4295 * @see #isDrawingCacheEnabled() 4296 * 4297 * @attr ref android.R.styleable#View_drawingCacheQuality 4298 */ 4299 public void setDrawingCacheQuality(int quality) { 4300 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 4301 } 4302 4303 /** 4304 * Returns whether the screen should remain on, corresponding to the current 4305 * value of {@link #KEEP_SCREEN_ON}. 4306 * 4307 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 4308 * 4309 * @see #setKeepScreenOn(boolean) 4310 * 4311 * @attr ref android.R.styleable#View_keepScreenOn 4312 */ 4313 public boolean getKeepScreenOn() { 4314 return (mViewFlags & KEEP_SCREEN_ON) != 0; 4315 } 4316 4317 /** 4318 * Controls whether the screen should remain on, modifying the 4319 * value of {@link #KEEP_SCREEN_ON}. 4320 * 4321 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 4322 * 4323 * @see #getKeepScreenOn() 4324 * 4325 * @attr ref android.R.styleable#View_keepScreenOn 4326 */ 4327 public void setKeepScreenOn(boolean keepScreenOn) { 4328 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 4329 } 4330 4331 /** 4332 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4333 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4334 * 4335 * @attr ref android.R.styleable#View_nextFocusLeft 4336 */ 4337 public int getNextFocusLeftId() { 4338 return mNextFocusLeftId; 4339 } 4340 4341 /** 4342 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4343 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 4344 * decide automatically. 4345 * 4346 * @attr ref android.R.styleable#View_nextFocusLeft 4347 */ 4348 public void setNextFocusLeftId(int nextFocusLeftId) { 4349 mNextFocusLeftId = nextFocusLeftId; 4350 } 4351 4352 /** 4353 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4354 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4355 * 4356 * @attr ref android.R.styleable#View_nextFocusRight 4357 */ 4358 public int getNextFocusRightId() { 4359 return mNextFocusRightId; 4360 } 4361 4362 /** 4363 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4364 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 4365 * decide automatically. 4366 * 4367 * @attr ref android.R.styleable#View_nextFocusRight 4368 */ 4369 public void setNextFocusRightId(int nextFocusRightId) { 4370 mNextFocusRightId = nextFocusRightId; 4371 } 4372 4373 /** 4374 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4375 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4376 * 4377 * @attr ref android.R.styleable#View_nextFocusUp 4378 */ 4379 public int getNextFocusUpId() { 4380 return mNextFocusUpId; 4381 } 4382 4383 /** 4384 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4385 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 4386 * decide automatically. 4387 * 4388 * @attr ref android.R.styleable#View_nextFocusUp 4389 */ 4390 public void setNextFocusUpId(int nextFocusUpId) { 4391 mNextFocusUpId = nextFocusUpId; 4392 } 4393 4394 /** 4395 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4396 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4397 * 4398 * @attr ref android.R.styleable#View_nextFocusDown 4399 */ 4400 public int getNextFocusDownId() { 4401 return mNextFocusDownId; 4402 } 4403 4404 /** 4405 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4406 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 4407 * decide automatically. 4408 * 4409 * @attr ref android.R.styleable#View_nextFocusDown 4410 */ 4411 public void setNextFocusDownId(int nextFocusDownId) { 4412 mNextFocusDownId = nextFocusDownId; 4413 } 4414 4415 /** 4416 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4417 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4418 * 4419 * @attr ref android.R.styleable#View_nextFocusForward 4420 */ 4421 public int getNextFocusForwardId() { 4422 return mNextFocusForwardId; 4423 } 4424 4425 /** 4426 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4427 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 4428 * decide automatically. 4429 * 4430 * @attr ref android.R.styleable#View_nextFocusForward 4431 */ 4432 public void setNextFocusForwardId(int nextFocusForwardId) { 4433 mNextFocusForwardId = nextFocusForwardId; 4434 } 4435 4436 /** 4437 * Returns the visibility of this view and all of its ancestors 4438 * 4439 * @return True if this view and all of its ancestors are {@link #VISIBLE} 4440 */ 4441 public boolean isShown() { 4442 View current = this; 4443 //noinspection ConstantConditions 4444 do { 4445 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 4446 return false; 4447 } 4448 ViewParent parent = current.mParent; 4449 if (parent == null) { 4450 return false; // We are not attached to the view root 4451 } 4452 if (!(parent instanceof View)) { 4453 return true; 4454 } 4455 current = (View) parent; 4456 } while (current != null); 4457 4458 return false; 4459 } 4460 4461 /** 4462 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag 4463 * is set 4464 * 4465 * @param insets Insets for system windows 4466 * 4467 * @return True if this view applied the insets, false otherwise 4468 */ 4469 protected boolean fitSystemWindows(Rect insets) { 4470 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 4471 mPaddingLeft = insets.left; 4472 mPaddingTop = insets.top; 4473 mPaddingRight = insets.right; 4474 mPaddingBottom = insets.bottom; 4475 requestLayout(); 4476 return true; 4477 } 4478 return false; 4479 } 4480 4481 /** 4482 * Set whether or not this view should account for system screen decorations 4483 * such as the status bar and inset its content. This allows this view to be 4484 * positioned in absolute screen coordinates and remain visible to the user. 4485 * 4486 * <p>This should only be used by top-level window decor views. 4487 * 4488 * @param fitSystemWindows true to inset content for system screen decorations, false for 4489 * default behavior. 4490 * 4491 * @attr ref android.R.styleable#View_fitsSystemWindows 4492 */ 4493 public void setFitsSystemWindows(boolean fitSystemWindows) { 4494 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 4495 } 4496 4497 /** 4498 * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view 4499 * will account for system screen decorations such as the status bar and inset its 4500 * content. This allows the view to be positioned in absolute screen coordinates 4501 * and remain visible to the user. 4502 * 4503 * @return true if this view will adjust its content bounds for system screen decorations. 4504 * 4505 * @attr ref android.R.styleable#View_fitsSystemWindows 4506 */ 4507 public boolean fitsSystemWindows() { 4508 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 4509 } 4510 4511 /** 4512 * Returns the visibility status for this view. 4513 * 4514 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4515 * @attr ref android.R.styleable#View_visibility 4516 */ 4517 @ViewDebug.ExportedProperty(mapping = { 4518 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 4519 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 4520 @ViewDebug.IntToString(from = GONE, to = "GONE") 4521 }) 4522 public int getVisibility() { 4523 return mViewFlags & VISIBILITY_MASK; 4524 } 4525 4526 /** 4527 * Set the enabled state of this view. 4528 * 4529 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4530 * @attr ref android.R.styleable#View_visibility 4531 */ 4532 @RemotableViewMethod 4533 public void setVisibility(int visibility) { 4534 setFlags(visibility, VISIBILITY_MASK); 4535 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); 4536 } 4537 4538 /** 4539 * Returns the enabled status for this view. The interpretation of the 4540 * enabled state varies by subclass. 4541 * 4542 * @return True if this view is enabled, false otherwise. 4543 */ 4544 @ViewDebug.ExportedProperty 4545 public boolean isEnabled() { 4546 return (mViewFlags & ENABLED_MASK) == ENABLED; 4547 } 4548 4549 /** 4550 * Set the enabled state of this view. The interpretation of the enabled 4551 * state varies by subclass. 4552 * 4553 * @param enabled True if this view is enabled, false otherwise. 4554 */ 4555 @RemotableViewMethod 4556 public void setEnabled(boolean enabled) { 4557 if (enabled == isEnabled()) return; 4558 4559 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 4560 4561 /* 4562 * The View most likely has to change its appearance, so refresh 4563 * the drawable state. 4564 */ 4565 refreshDrawableState(); 4566 4567 // Invalidate too, since the default behavior for views is to be 4568 // be drawn at 50% alpha rather than to change the drawable. 4569 invalidate(true); 4570 } 4571 4572 /** 4573 * Set whether this view can receive the focus. 4574 * 4575 * Setting this to false will also ensure that this view is not focusable 4576 * in touch mode. 4577 * 4578 * @param focusable If true, this view can receive the focus. 4579 * 4580 * @see #setFocusableInTouchMode(boolean) 4581 * @attr ref android.R.styleable#View_focusable 4582 */ 4583 public void setFocusable(boolean focusable) { 4584 if (!focusable) { 4585 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 4586 } 4587 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 4588 } 4589 4590 /** 4591 * Set whether this view can receive focus while in touch mode. 4592 * 4593 * Setting this to true will also ensure that this view is focusable. 4594 * 4595 * @param focusableInTouchMode If true, this view can receive the focus while 4596 * in touch mode. 4597 * 4598 * @see #setFocusable(boolean) 4599 * @attr ref android.R.styleable#View_focusableInTouchMode 4600 */ 4601 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 4602 // Focusable in touch mode should always be set before the focusable flag 4603 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 4604 // which, in touch mode, will not successfully request focus on this view 4605 // because the focusable in touch mode flag is not set 4606 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 4607 if (focusableInTouchMode) { 4608 setFlags(FOCUSABLE, FOCUSABLE_MASK); 4609 } 4610 } 4611 4612 /** 4613 * Set whether this view should have sound effects enabled for events such as 4614 * clicking and touching. 4615 * 4616 * <p>You may wish to disable sound effects for a view if you already play sounds, 4617 * for instance, a dial key that plays dtmf tones. 4618 * 4619 * @param soundEffectsEnabled whether sound effects are enabled for this view. 4620 * @see #isSoundEffectsEnabled() 4621 * @see #playSoundEffect(int) 4622 * @attr ref android.R.styleable#View_soundEffectsEnabled 4623 */ 4624 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 4625 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 4626 } 4627 4628 /** 4629 * @return whether this view should have sound effects enabled for events such as 4630 * clicking and touching. 4631 * 4632 * @see #setSoundEffectsEnabled(boolean) 4633 * @see #playSoundEffect(int) 4634 * @attr ref android.R.styleable#View_soundEffectsEnabled 4635 */ 4636 @ViewDebug.ExportedProperty 4637 public boolean isSoundEffectsEnabled() { 4638 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 4639 } 4640 4641 /** 4642 * Set whether this view should have haptic feedback for events such as 4643 * long presses. 4644 * 4645 * <p>You may wish to disable haptic feedback if your view already controls 4646 * its own haptic feedback. 4647 * 4648 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 4649 * @see #isHapticFeedbackEnabled() 4650 * @see #performHapticFeedback(int) 4651 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4652 */ 4653 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 4654 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 4655 } 4656 4657 /** 4658 * @return whether this view should have haptic feedback enabled for events 4659 * long presses. 4660 * 4661 * @see #setHapticFeedbackEnabled(boolean) 4662 * @see #performHapticFeedback(int) 4663 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4664 */ 4665 @ViewDebug.ExportedProperty 4666 public boolean isHapticFeedbackEnabled() { 4667 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 4668 } 4669 4670 /** 4671 * Returns the layout direction for this view. 4672 * 4673 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 4674 * {@link #LAYOUT_DIRECTION_RTL}, 4675 * {@link #LAYOUT_DIRECTION_INHERIT} or 4676 * {@link #LAYOUT_DIRECTION_LOCALE}. 4677 * @attr ref android.R.styleable#View_layoutDirection 4678 * 4679 * @hide 4680 */ 4681 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4682 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 4683 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 4684 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 4685 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 4686 }) 4687 public int getLayoutDirection() { 4688 return mViewFlags & LAYOUT_DIRECTION_MASK; 4689 } 4690 4691 /** 4692 * Set the layout direction for this view. This will propagate a reset of layout direction 4693 * resolution to the view's children and resolve layout direction for this view. 4694 * 4695 * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR}, 4696 * {@link #LAYOUT_DIRECTION_RTL}, 4697 * {@link #LAYOUT_DIRECTION_INHERIT} or 4698 * {@link #LAYOUT_DIRECTION_LOCALE}. 4699 * 4700 * @attr ref android.R.styleable#View_layoutDirection 4701 * 4702 * @hide 4703 */ 4704 @RemotableViewMethod 4705 public void setLayoutDirection(int layoutDirection) { 4706 if (getLayoutDirection() != layoutDirection) { 4707 resetResolvedLayoutDirection(); 4708 // Setting the flag will also request a layout. 4709 setFlags(layoutDirection, LAYOUT_DIRECTION_MASK); 4710 } 4711 } 4712 4713 /** 4714 * Returns the resolved layout direction for this view. 4715 * 4716 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 4717 * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL. 4718 * 4719 * @hide 4720 */ 4721 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4722 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 4723 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 4724 }) 4725 public int getResolvedLayoutDirection() { 4726 resolveLayoutDirectionIfNeeded(); 4727 return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ? 4728 LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 4729 } 4730 4731 /** 4732 * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from 4733 * layout attribute and/or the inherited value from the parent.</p> 4734 * 4735 * @return true if the layout is right-to-left. 4736 * 4737 * @hide 4738 */ 4739 @ViewDebug.ExportedProperty(category = "layout") 4740 public boolean isLayoutRtl() { 4741 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 4742 } 4743 4744 /** 4745 * If this view doesn't do any drawing on its own, set this flag to 4746 * allow further optimizations. By default, this flag is not set on 4747 * View, but could be set on some View subclasses such as ViewGroup. 4748 * 4749 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 4750 * you should clear this flag. 4751 * 4752 * @param willNotDraw whether or not this View draw on its own 4753 */ 4754 public void setWillNotDraw(boolean willNotDraw) { 4755 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 4756 } 4757 4758 /** 4759 * Returns whether or not this View draws on its own. 4760 * 4761 * @return true if this view has nothing to draw, false otherwise 4762 */ 4763 @ViewDebug.ExportedProperty(category = "drawing") 4764 public boolean willNotDraw() { 4765 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 4766 } 4767 4768 /** 4769 * When a View's drawing cache is enabled, drawing is redirected to an 4770 * offscreen bitmap. Some views, like an ImageView, must be able to 4771 * bypass this mechanism if they already draw a single bitmap, to avoid 4772 * unnecessary usage of the memory. 4773 * 4774 * @param willNotCacheDrawing true if this view does not cache its 4775 * drawing, false otherwise 4776 */ 4777 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 4778 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 4779 } 4780 4781 /** 4782 * Returns whether or not this View can cache its drawing or not. 4783 * 4784 * @return true if this view does not cache its drawing, false otherwise 4785 */ 4786 @ViewDebug.ExportedProperty(category = "drawing") 4787 public boolean willNotCacheDrawing() { 4788 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 4789 } 4790 4791 /** 4792 * Indicates whether this view reacts to click events or not. 4793 * 4794 * @return true if the view is clickable, false otherwise 4795 * 4796 * @see #setClickable(boolean) 4797 * @attr ref android.R.styleable#View_clickable 4798 */ 4799 @ViewDebug.ExportedProperty 4800 public boolean isClickable() { 4801 return (mViewFlags & CLICKABLE) == CLICKABLE; 4802 } 4803 4804 /** 4805 * Enables or disables click events for this view. When a view 4806 * is clickable it will change its state to "pressed" on every click. 4807 * Subclasses should set the view clickable to visually react to 4808 * user's clicks. 4809 * 4810 * @param clickable true to make the view clickable, false otherwise 4811 * 4812 * @see #isClickable() 4813 * @attr ref android.R.styleable#View_clickable 4814 */ 4815 public void setClickable(boolean clickable) { 4816 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 4817 } 4818 4819 /** 4820 * Indicates whether this view reacts to long click events or not. 4821 * 4822 * @return true if the view is long clickable, false otherwise 4823 * 4824 * @see #setLongClickable(boolean) 4825 * @attr ref android.R.styleable#View_longClickable 4826 */ 4827 public boolean isLongClickable() { 4828 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 4829 } 4830 4831 /** 4832 * Enables or disables long click events for this view. When a view is long 4833 * clickable it reacts to the user holding down the button for a longer 4834 * duration than a tap. This event can either launch the listener or a 4835 * context menu. 4836 * 4837 * @param longClickable true to make the view long clickable, false otherwise 4838 * @see #isLongClickable() 4839 * @attr ref android.R.styleable#View_longClickable 4840 */ 4841 public void setLongClickable(boolean longClickable) { 4842 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 4843 } 4844 4845 /** 4846 * Sets the pressed state for this view. 4847 * 4848 * @see #isClickable() 4849 * @see #setClickable(boolean) 4850 * 4851 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 4852 * the View's internal state from a previously set "pressed" state. 4853 */ 4854 public void setPressed(boolean pressed) { 4855 if (pressed) { 4856 mPrivateFlags |= PRESSED; 4857 } else { 4858 mPrivateFlags &= ~PRESSED; 4859 } 4860 refreshDrawableState(); 4861 dispatchSetPressed(pressed); 4862 } 4863 4864 /** 4865 * Dispatch setPressed to all of this View's children. 4866 * 4867 * @see #setPressed(boolean) 4868 * 4869 * @param pressed The new pressed state 4870 */ 4871 protected void dispatchSetPressed(boolean pressed) { 4872 } 4873 4874 /** 4875 * Indicates whether the view is currently in pressed state. Unless 4876 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 4877 * the pressed state. 4878 * 4879 * @see #setPressed(boolean) 4880 * @see #isClickable() 4881 * @see #setClickable(boolean) 4882 * 4883 * @return true if the view is currently pressed, false otherwise 4884 */ 4885 public boolean isPressed() { 4886 return (mPrivateFlags & PRESSED) == PRESSED; 4887 } 4888 4889 /** 4890 * Indicates whether this view will save its state (that is, 4891 * whether its {@link #onSaveInstanceState} method will be called). 4892 * 4893 * @return Returns true if the view state saving is enabled, else false. 4894 * 4895 * @see #setSaveEnabled(boolean) 4896 * @attr ref android.R.styleable#View_saveEnabled 4897 */ 4898 public boolean isSaveEnabled() { 4899 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 4900 } 4901 4902 /** 4903 * Controls whether the saving of this view's state is 4904 * enabled (that is, whether its {@link #onSaveInstanceState} method 4905 * will be called). Note that even if freezing is enabled, the 4906 * view still must have an id assigned to it (via {@link #setId(int)}) 4907 * for its state to be saved. This flag can only disable the 4908 * saving of this view; any child views may still have their state saved. 4909 * 4910 * @param enabled Set to false to <em>disable</em> state saving, or true 4911 * (the default) to allow it. 4912 * 4913 * @see #isSaveEnabled() 4914 * @see #setId(int) 4915 * @see #onSaveInstanceState() 4916 * @attr ref android.R.styleable#View_saveEnabled 4917 */ 4918 public void setSaveEnabled(boolean enabled) { 4919 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 4920 } 4921 4922 /** 4923 * Gets whether the framework should discard touches when the view's 4924 * window is obscured by another visible window. 4925 * Refer to the {@link View} security documentation for more details. 4926 * 4927 * @return True if touch filtering is enabled. 4928 * 4929 * @see #setFilterTouchesWhenObscured(boolean) 4930 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4931 */ 4932 @ViewDebug.ExportedProperty 4933 public boolean getFilterTouchesWhenObscured() { 4934 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 4935 } 4936 4937 /** 4938 * Sets whether the framework should discard touches when the view's 4939 * window is obscured by another visible window. 4940 * Refer to the {@link View} security documentation for more details. 4941 * 4942 * @param enabled True if touch filtering should be enabled. 4943 * 4944 * @see #getFilterTouchesWhenObscured 4945 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4946 */ 4947 public void setFilterTouchesWhenObscured(boolean enabled) { 4948 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 4949 FILTER_TOUCHES_WHEN_OBSCURED); 4950 } 4951 4952 /** 4953 * Indicates whether the entire hierarchy under this view will save its 4954 * state when a state saving traversal occurs from its parent. The default 4955 * is true; if false, these views will not be saved unless 4956 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4957 * 4958 * @return Returns true if the view state saving from parent is enabled, else false. 4959 * 4960 * @see #setSaveFromParentEnabled(boolean) 4961 */ 4962 public boolean isSaveFromParentEnabled() { 4963 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 4964 } 4965 4966 /** 4967 * Controls whether the entire hierarchy under this view will save its 4968 * state when a state saving traversal occurs from its parent. The default 4969 * is true; if false, these views will not be saved unless 4970 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4971 * 4972 * @param enabled Set to false to <em>disable</em> state saving, or true 4973 * (the default) to allow it. 4974 * 4975 * @see #isSaveFromParentEnabled() 4976 * @see #setId(int) 4977 * @see #onSaveInstanceState() 4978 */ 4979 public void setSaveFromParentEnabled(boolean enabled) { 4980 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 4981 } 4982 4983 4984 /** 4985 * Returns whether this View is able to take focus. 4986 * 4987 * @return True if this view can take focus, or false otherwise. 4988 * @attr ref android.R.styleable#View_focusable 4989 */ 4990 @ViewDebug.ExportedProperty(category = "focus") 4991 public final boolean isFocusable() { 4992 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 4993 } 4994 4995 /** 4996 * When a view is focusable, it may not want to take focus when in touch mode. 4997 * For example, a button would like focus when the user is navigating via a D-pad 4998 * so that the user can click on it, but once the user starts touching the screen, 4999 * the button shouldn't take focus 5000 * @return Whether the view is focusable in touch mode. 5001 * @attr ref android.R.styleable#View_focusableInTouchMode 5002 */ 5003 @ViewDebug.ExportedProperty 5004 public final boolean isFocusableInTouchMode() { 5005 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 5006 } 5007 5008 /** 5009 * Find the nearest view in the specified direction that can take focus. 5010 * This does not actually give focus to that view. 5011 * 5012 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5013 * 5014 * @return The nearest focusable in the specified direction, or null if none 5015 * can be found. 5016 */ 5017 public View focusSearch(int direction) { 5018 if (mParent != null) { 5019 return mParent.focusSearch(this, direction); 5020 } else { 5021 return null; 5022 } 5023 } 5024 5025 /** 5026 * This method is the last chance for the focused view and its ancestors to 5027 * respond to an arrow key. This is called when the focused view did not 5028 * consume the key internally, nor could the view system find a new view in 5029 * the requested direction to give focus to. 5030 * 5031 * @param focused The currently focused view. 5032 * @param direction The direction focus wants to move. One of FOCUS_UP, 5033 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 5034 * @return True if the this view consumed this unhandled move. 5035 */ 5036 public boolean dispatchUnhandledMove(View focused, int direction) { 5037 return false; 5038 } 5039 5040 /** 5041 * If a user manually specified the next view id for a particular direction, 5042 * use the root to look up the view. 5043 * @param root The root view of the hierarchy containing this view. 5044 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 5045 * or FOCUS_BACKWARD. 5046 * @return The user specified next view, or null if there is none. 5047 */ 5048 View findUserSetNextFocus(View root, int direction) { 5049 switch (direction) { 5050 case FOCUS_LEFT: 5051 if (mNextFocusLeftId == View.NO_ID) return null; 5052 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 5053 case FOCUS_RIGHT: 5054 if (mNextFocusRightId == View.NO_ID) return null; 5055 return findViewInsideOutShouldExist(root, mNextFocusRightId); 5056 case FOCUS_UP: 5057 if (mNextFocusUpId == View.NO_ID) return null; 5058 return findViewInsideOutShouldExist(root, mNextFocusUpId); 5059 case FOCUS_DOWN: 5060 if (mNextFocusDownId == View.NO_ID) return null; 5061 return findViewInsideOutShouldExist(root, mNextFocusDownId); 5062 case FOCUS_FORWARD: 5063 if (mNextFocusForwardId == View.NO_ID) return null; 5064 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 5065 case FOCUS_BACKWARD: { 5066 final int id = mID; 5067 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5068 @Override 5069 public boolean apply(View t) { 5070 return t.mNextFocusForwardId == id; 5071 } 5072 }); 5073 } 5074 } 5075 return null; 5076 } 5077 5078 private View findViewInsideOutShouldExist(View root, final int childViewId) { 5079 View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5080 @Override 5081 public boolean apply(View t) { 5082 return t.mID == childViewId; 5083 } 5084 }); 5085 5086 if (result == null) { 5087 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified " 5088 + "by user for id " + childViewId); 5089 } 5090 return result; 5091 } 5092 5093 /** 5094 * Find and return all focusable views that are descendants of this view, 5095 * possibly including this view if it is focusable itself. 5096 * 5097 * @param direction The direction of the focus 5098 * @return A list of focusable views 5099 */ 5100 public ArrayList<View> getFocusables(int direction) { 5101 ArrayList<View> result = new ArrayList<View>(24); 5102 addFocusables(result, direction); 5103 return result; 5104 } 5105 5106 /** 5107 * Add any focusable views that are descendants of this view (possibly 5108 * including this view if it is focusable itself) to views. If we are in touch mode, 5109 * only add views that are also focusable in touch mode. 5110 * 5111 * @param views Focusable views found so far 5112 * @param direction The direction of the focus 5113 */ 5114 public void addFocusables(ArrayList<View> views, int direction) { 5115 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 5116 } 5117 5118 /** 5119 * Adds any focusable views that are descendants of this view (possibly 5120 * including this view if it is focusable itself) to views. This method 5121 * adds all focusable views regardless if we are in touch mode or 5122 * only views focusable in touch mode if we are in touch mode depending on 5123 * the focusable mode paramater. 5124 * 5125 * @param views Focusable views found so far or null if all we are interested is 5126 * the number of focusables. 5127 * @param direction The direction of the focus. 5128 * @param focusableMode The type of focusables to be added. 5129 * 5130 * @see #FOCUSABLES_ALL 5131 * @see #FOCUSABLES_TOUCH_MODE 5132 */ 5133 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 5134 if (!isFocusable()) { 5135 return; 5136 } 5137 5138 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 5139 isInTouchMode() && !isFocusableInTouchMode()) { 5140 return; 5141 } 5142 5143 if (views != null) { 5144 views.add(this); 5145 } 5146 } 5147 5148 /** 5149 * Finds the Views that contain given text. The containment is case insensitive. 5150 * The search is performed by either the text that the View renders or the content 5151 * description that describes the view for accessibility purposes and the view does 5152 * not render or both. Clients can specify how the search is to be performed via 5153 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 5154 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 5155 * 5156 * @param outViews The output list of matching Views. 5157 * @param searched The text to match against. 5158 * 5159 * @see #FIND_VIEWS_WITH_TEXT 5160 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 5161 * @see #setContentDescription(CharSequence) 5162 */ 5163 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 5164 if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 && !TextUtils.isEmpty(searched) 5165 && !TextUtils.isEmpty(mContentDescription)) { 5166 String searchedLowerCase = searched.toString().toLowerCase(); 5167 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 5168 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 5169 outViews.add(this); 5170 } 5171 } 5172 } 5173 5174 /** 5175 * Find and return all touchable views that are descendants of this view, 5176 * possibly including this view if it is touchable itself. 5177 * 5178 * @return A list of touchable views 5179 */ 5180 public ArrayList<View> getTouchables() { 5181 ArrayList<View> result = new ArrayList<View>(); 5182 addTouchables(result); 5183 return result; 5184 } 5185 5186 /** 5187 * Add any touchable views that are descendants of this view (possibly 5188 * including this view if it is touchable itself) to views. 5189 * 5190 * @param views Touchable views found so far 5191 */ 5192 public void addTouchables(ArrayList<View> views) { 5193 final int viewFlags = mViewFlags; 5194 5195 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 5196 && (viewFlags & ENABLED_MASK) == ENABLED) { 5197 views.add(this); 5198 } 5199 } 5200 5201 /** 5202 * Call this to try to give focus to a specific view or to one of its 5203 * descendants. 5204 * 5205 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5206 * false), or if it is focusable and it is not focusable in touch mode 5207 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5208 * 5209 * See also {@link #focusSearch(int)}, which is what you call to say that you 5210 * have focus, and you want your parent to look for the next one. 5211 * 5212 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 5213 * {@link #FOCUS_DOWN} and <code>null</code>. 5214 * 5215 * @return Whether this view or one of its descendants actually took focus. 5216 */ 5217 public final boolean requestFocus() { 5218 return requestFocus(View.FOCUS_DOWN); 5219 } 5220 5221 5222 /** 5223 * Call this to try to give focus to a specific view or to one of its 5224 * descendants and give it a hint about what direction focus is heading. 5225 * 5226 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5227 * false), or if it is focusable and it is not focusable in touch mode 5228 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5229 * 5230 * See also {@link #focusSearch(int)}, which is what you call to say that you 5231 * have focus, and you want your parent to look for the next one. 5232 * 5233 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 5234 * <code>null</code> set for the previously focused rectangle. 5235 * 5236 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5237 * @return Whether this view or one of its descendants actually took focus. 5238 */ 5239 public final boolean requestFocus(int direction) { 5240 return requestFocus(direction, null); 5241 } 5242 5243 /** 5244 * Call this to try to give focus to a specific view or to one of its descendants 5245 * and give it hints about the direction and a specific rectangle that the focus 5246 * is coming from. The rectangle can help give larger views a finer grained hint 5247 * about where focus is coming from, and therefore, where to show selection, or 5248 * forward focus change internally. 5249 * 5250 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5251 * false), or if it is focusable and it is not focusable in touch mode 5252 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5253 * 5254 * A View will not take focus if it is not visible. 5255 * 5256 * A View will not take focus if one of its parents has 5257 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 5258 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 5259 * 5260 * See also {@link #focusSearch(int)}, which is what you call to say that you 5261 * have focus, and you want your parent to look for the next one. 5262 * 5263 * You may wish to override this method if your custom {@link View} has an internal 5264 * {@link View} that it wishes to forward the request to. 5265 * 5266 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5267 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 5268 * to give a finer grained hint about where focus is coming from. May be null 5269 * if there is no hint. 5270 * @return Whether this view or one of its descendants actually took focus. 5271 */ 5272 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 5273 // need to be focusable 5274 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 5275 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5276 return false; 5277 } 5278 5279 // need to be focusable in touch mode if in touch mode 5280 if (isInTouchMode() && 5281 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 5282 return false; 5283 } 5284 5285 // need to not have any parents blocking us 5286 if (hasAncestorThatBlocksDescendantFocus()) { 5287 return false; 5288 } 5289 5290 handleFocusGainInternal(direction, previouslyFocusedRect); 5291 return true; 5292 } 5293 5294 /** Gets the ViewAncestor, or null if not attached. */ 5295 /*package*/ ViewRootImpl getViewRootImpl() { 5296 View root = getRootView(); 5297 return root != null ? (ViewRootImpl)root.getParent() : null; 5298 } 5299 5300 /** 5301 * Call this to try to give focus to a specific view or to one of its descendants. This is a 5302 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 5303 * touch mode to request focus when they are touched. 5304 * 5305 * @return Whether this view or one of its descendants actually took focus. 5306 * 5307 * @see #isInTouchMode() 5308 * 5309 */ 5310 public final boolean requestFocusFromTouch() { 5311 // Leave touch mode if we need to 5312 if (isInTouchMode()) { 5313 ViewRootImpl viewRoot = getViewRootImpl(); 5314 if (viewRoot != null) { 5315 viewRoot.ensureTouchMode(false); 5316 } 5317 } 5318 return requestFocus(View.FOCUS_DOWN); 5319 } 5320 5321 /** 5322 * @return Whether any ancestor of this view blocks descendant focus. 5323 */ 5324 private boolean hasAncestorThatBlocksDescendantFocus() { 5325 ViewParent ancestor = mParent; 5326 while (ancestor instanceof ViewGroup) { 5327 final ViewGroup vgAncestor = (ViewGroup) ancestor; 5328 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 5329 return true; 5330 } else { 5331 ancestor = vgAncestor.getParent(); 5332 } 5333 } 5334 return false; 5335 } 5336 5337 /** 5338 * @hide 5339 */ 5340 public void dispatchStartTemporaryDetach() { 5341 onStartTemporaryDetach(); 5342 } 5343 5344 /** 5345 * This is called when a container is going to temporarily detach a child, with 5346 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 5347 * It will either be followed by {@link #onFinishTemporaryDetach()} or 5348 * {@link #onDetachedFromWindow()} when the container is done. 5349 */ 5350 public void onStartTemporaryDetach() { 5351 removeUnsetPressCallback(); 5352 mPrivateFlags |= CANCEL_NEXT_UP_EVENT; 5353 } 5354 5355 /** 5356 * @hide 5357 */ 5358 public void dispatchFinishTemporaryDetach() { 5359 onFinishTemporaryDetach(); 5360 } 5361 5362 /** 5363 * Called after {@link #onStartTemporaryDetach} when the container is done 5364 * changing the view. 5365 */ 5366 public void onFinishTemporaryDetach() { 5367 } 5368 5369 /** 5370 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 5371 * for this view's window. Returns null if the view is not currently attached 5372 * to the window. Normally you will not need to use this directly, but 5373 * just use the standard high-level event callbacks like 5374 * {@link #onKeyDown(int, KeyEvent)}. 5375 */ 5376 public KeyEvent.DispatcherState getKeyDispatcherState() { 5377 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 5378 } 5379 5380 /** 5381 * Dispatch a key event before it is processed by any input method 5382 * associated with the view hierarchy. This can be used to intercept 5383 * key events in special situations before the IME consumes them; a 5384 * typical example would be handling the BACK key to update the application's 5385 * UI instead of allowing the IME to see it and close itself. 5386 * 5387 * @param event The key event to be dispatched. 5388 * @return True if the event was handled, false otherwise. 5389 */ 5390 public boolean dispatchKeyEventPreIme(KeyEvent event) { 5391 return onKeyPreIme(event.getKeyCode(), event); 5392 } 5393 5394 /** 5395 * Dispatch a key event to the next view on the focus path. This path runs 5396 * from the top of the view tree down to the currently focused view. If this 5397 * view has focus, it will dispatch to itself. Otherwise it will dispatch 5398 * the next node down the focus path. This method also fires any key 5399 * listeners. 5400 * 5401 * @param event The key event to be dispatched. 5402 * @return True if the event was handled, false otherwise. 5403 */ 5404 public boolean dispatchKeyEvent(KeyEvent event) { 5405 if (mInputEventConsistencyVerifier != null) { 5406 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 5407 } 5408 5409 // Give any attached key listener a first crack at the event. 5410 //noinspection SimplifiableIfStatement 5411 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5412 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 5413 return true; 5414 } 5415 5416 if (event.dispatch(this, mAttachInfo != null 5417 ? mAttachInfo.mKeyDispatchState : null, this)) { 5418 return true; 5419 } 5420 5421 if (mInputEventConsistencyVerifier != null) { 5422 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5423 } 5424 return false; 5425 } 5426 5427 /** 5428 * Dispatches a key shortcut event. 5429 * 5430 * @param event The key event to be dispatched. 5431 * @return True if the event was handled by the view, false otherwise. 5432 */ 5433 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 5434 return onKeyShortcut(event.getKeyCode(), event); 5435 } 5436 5437 /** 5438 * Pass the touch screen motion event down to the target view, or this 5439 * view if it is the target. 5440 * 5441 * @param event The motion event to be dispatched. 5442 * @return True if the event was handled by the view, false otherwise. 5443 */ 5444 public boolean dispatchTouchEvent(MotionEvent event) { 5445 if (mInputEventConsistencyVerifier != null) { 5446 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 5447 } 5448 5449 if (onFilterTouchEventForSecurity(event)) { 5450 //noinspection SimplifiableIfStatement 5451 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && 5452 mOnTouchListener.onTouch(this, event)) { 5453 return true; 5454 } 5455 5456 if (onTouchEvent(event)) { 5457 return true; 5458 } 5459 } 5460 5461 if (mInputEventConsistencyVerifier != null) { 5462 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5463 } 5464 return false; 5465 } 5466 5467 /** 5468 * Filter the touch event to apply security policies. 5469 * 5470 * @param event The motion event to be filtered. 5471 * @return True if the event should be dispatched, false if the event should be dropped. 5472 * 5473 * @see #getFilterTouchesWhenObscured 5474 */ 5475 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 5476 //noinspection RedundantIfStatement 5477 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 5478 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 5479 // Window is obscured, drop this touch. 5480 return false; 5481 } 5482 return true; 5483 } 5484 5485 /** 5486 * Pass a trackball motion event down to the focused view. 5487 * 5488 * @param event The motion event to be dispatched. 5489 * @return True if the event was handled by the view, false otherwise. 5490 */ 5491 public boolean dispatchTrackballEvent(MotionEvent event) { 5492 if (mInputEventConsistencyVerifier != null) { 5493 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 5494 } 5495 5496 return onTrackballEvent(event); 5497 } 5498 5499 /** 5500 * Dispatch a generic motion event. 5501 * <p> 5502 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5503 * are delivered to the view under the pointer. All other generic motion events are 5504 * delivered to the focused view. Hover events are handled specially and are delivered 5505 * to {@link #onHoverEvent(MotionEvent)}. 5506 * </p> 5507 * 5508 * @param event The motion event to be dispatched. 5509 * @return True if the event was handled by the view, false otherwise. 5510 */ 5511 public boolean dispatchGenericMotionEvent(MotionEvent event) { 5512 if (mInputEventConsistencyVerifier != null) { 5513 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 5514 } 5515 5516 final int source = event.getSource(); 5517 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5518 final int action = event.getAction(); 5519 if (action == MotionEvent.ACTION_HOVER_ENTER 5520 || action == MotionEvent.ACTION_HOVER_MOVE 5521 || action == MotionEvent.ACTION_HOVER_EXIT) { 5522 if (dispatchHoverEvent(event)) { 5523 return true; 5524 } 5525 } else if (dispatchGenericPointerEvent(event)) { 5526 return true; 5527 } 5528 } else if (dispatchGenericFocusedEvent(event)) { 5529 return true; 5530 } 5531 5532 if (dispatchGenericMotionEventInternal(event)) { 5533 return true; 5534 } 5535 5536 if (mInputEventConsistencyVerifier != null) { 5537 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5538 } 5539 return false; 5540 } 5541 5542 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 5543 //noinspection SimplifiableIfStatement 5544 if (mOnGenericMotionListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5545 && mOnGenericMotionListener.onGenericMotion(this, event)) { 5546 return true; 5547 } 5548 5549 if (onGenericMotionEvent(event)) { 5550 return true; 5551 } 5552 5553 if (mInputEventConsistencyVerifier != null) { 5554 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5555 } 5556 return false; 5557 } 5558 5559 /** 5560 * Dispatch a hover event. 5561 * <p> 5562 * Do not call this method directly. 5563 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5564 * </p> 5565 * 5566 * @param event The motion event to be dispatched. 5567 * @return True if the event was handled by the view, false otherwise. 5568 */ 5569 protected boolean dispatchHoverEvent(MotionEvent event) { 5570 //noinspection SimplifiableIfStatement 5571 if (mOnHoverListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5572 && mOnHoverListener.onHover(this, event)) { 5573 return true; 5574 } 5575 5576 return onHoverEvent(event); 5577 } 5578 5579 /** 5580 * Returns true if the view has a child to which it has recently sent 5581 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 5582 * it does not have a hovered child, then it must be the innermost hovered view. 5583 * @hide 5584 */ 5585 protected boolean hasHoveredChild() { 5586 return false; 5587 } 5588 5589 /** 5590 * Dispatch a generic motion event to the view under the first pointer. 5591 * <p> 5592 * Do not call this method directly. 5593 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5594 * </p> 5595 * 5596 * @param event The motion event to be dispatched. 5597 * @return True if the event was handled by the view, false otherwise. 5598 */ 5599 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 5600 return false; 5601 } 5602 5603 /** 5604 * Dispatch a generic motion event to the currently focused view. 5605 * <p> 5606 * Do not call this method directly. 5607 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5608 * </p> 5609 * 5610 * @param event The motion event to be dispatched. 5611 * @return True if the event was handled by the view, false otherwise. 5612 */ 5613 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 5614 return false; 5615 } 5616 5617 /** 5618 * Dispatch a pointer event. 5619 * <p> 5620 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 5621 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 5622 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 5623 * and should not be expected to handle other pointing device features. 5624 * </p> 5625 * 5626 * @param event The motion event to be dispatched. 5627 * @return True if the event was handled by the view, false otherwise. 5628 * @hide 5629 */ 5630 public final boolean dispatchPointerEvent(MotionEvent event) { 5631 if (event.isTouchEvent()) { 5632 return dispatchTouchEvent(event); 5633 } else { 5634 return dispatchGenericMotionEvent(event); 5635 } 5636 } 5637 5638 /** 5639 * Called when the window containing this view gains or loses window focus. 5640 * ViewGroups should override to route to their children. 5641 * 5642 * @param hasFocus True if the window containing this view now has focus, 5643 * false otherwise. 5644 */ 5645 public void dispatchWindowFocusChanged(boolean hasFocus) { 5646 onWindowFocusChanged(hasFocus); 5647 } 5648 5649 /** 5650 * Called when the window containing this view gains or loses focus. Note 5651 * that this is separate from view focus: to receive key events, both 5652 * your view and its window must have focus. If a window is displayed 5653 * on top of yours that takes input focus, then your own window will lose 5654 * focus but the view focus will remain unchanged. 5655 * 5656 * @param hasWindowFocus True if the window containing this view now has 5657 * focus, false otherwise. 5658 */ 5659 public void onWindowFocusChanged(boolean hasWindowFocus) { 5660 InputMethodManager imm = InputMethodManager.peekInstance(); 5661 if (!hasWindowFocus) { 5662 if (isPressed()) { 5663 setPressed(false); 5664 } 5665 if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5666 imm.focusOut(this); 5667 } 5668 removeLongPressCallback(); 5669 removeTapCallback(); 5670 onFocusLost(); 5671 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5672 imm.focusIn(this); 5673 } 5674 refreshDrawableState(); 5675 } 5676 5677 /** 5678 * Returns true if this view is in a window that currently has window focus. 5679 * Note that this is not the same as the view itself having focus. 5680 * 5681 * @return True if this view is in a window that currently has window focus. 5682 */ 5683 public boolean hasWindowFocus() { 5684 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 5685 } 5686 5687 /** 5688 * Dispatch a view visibility change down the view hierarchy. 5689 * ViewGroups should override to route to their children. 5690 * @param changedView The view whose visibility changed. Could be 'this' or 5691 * an ancestor view. 5692 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5693 * {@link #INVISIBLE} or {@link #GONE}. 5694 */ 5695 protected void dispatchVisibilityChanged(View changedView, int visibility) { 5696 onVisibilityChanged(changedView, visibility); 5697 } 5698 5699 /** 5700 * Called when the visibility of the view or an ancestor of the view is changed. 5701 * @param changedView The view whose visibility changed. Could be 'this' or 5702 * an ancestor view. 5703 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5704 * {@link #INVISIBLE} or {@link #GONE}. 5705 */ 5706 protected void onVisibilityChanged(View changedView, int visibility) { 5707 if (visibility == VISIBLE) { 5708 if (mAttachInfo != null) { 5709 initialAwakenScrollBars(); 5710 } else { 5711 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH; 5712 } 5713 } 5714 } 5715 5716 /** 5717 * Dispatch a hint about whether this view is displayed. For instance, when 5718 * a View moves out of the screen, it might receives a display hint indicating 5719 * the view is not displayed. Applications should not <em>rely</em> on this hint 5720 * as there is no guarantee that they will receive one. 5721 * 5722 * @param hint A hint about whether or not this view is displayed: 5723 * {@link #VISIBLE} or {@link #INVISIBLE}. 5724 */ 5725 public void dispatchDisplayHint(int hint) { 5726 onDisplayHint(hint); 5727 } 5728 5729 /** 5730 * Gives this view a hint about whether is displayed or not. For instance, when 5731 * a View moves out of the screen, it might receives a display hint indicating 5732 * the view is not displayed. Applications should not <em>rely</em> on this hint 5733 * as there is no guarantee that they will receive one. 5734 * 5735 * @param hint A hint about whether or not this view is displayed: 5736 * {@link #VISIBLE} or {@link #INVISIBLE}. 5737 */ 5738 protected void onDisplayHint(int hint) { 5739 } 5740 5741 /** 5742 * Dispatch a window visibility change down the view hierarchy. 5743 * ViewGroups should override to route to their children. 5744 * 5745 * @param visibility The new visibility of the window. 5746 * 5747 * @see #onWindowVisibilityChanged(int) 5748 */ 5749 public void dispatchWindowVisibilityChanged(int visibility) { 5750 onWindowVisibilityChanged(visibility); 5751 } 5752 5753 /** 5754 * Called when the window containing has change its visibility 5755 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 5756 * that this tells you whether or not your window is being made visible 5757 * to the window manager; this does <em>not</em> tell you whether or not 5758 * your window is obscured by other windows on the screen, even if it 5759 * is itself visible. 5760 * 5761 * @param visibility The new visibility of the window. 5762 */ 5763 protected void onWindowVisibilityChanged(int visibility) { 5764 if (visibility == VISIBLE) { 5765 initialAwakenScrollBars(); 5766 } 5767 } 5768 5769 /** 5770 * Returns the current visibility of the window this view is attached to 5771 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 5772 * 5773 * @return Returns the current visibility of the view's window. 5774 */ 5775 public int getWindowVisibility() { 5776 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 5777 } 5778 5779 /** 5780 * Retrieve the overall visible display size in which the window this view is 5781 * attached to has been positioned in. This takes into account screen 5782 * decorations above the window, for both cases where the window itself 5783 * is being position inside of them or the window is being placed under 5784 * then and covered insets are used for the window to position its content 5785 * inside. In effect, this tells you the available area where content can 5786 * be placed and remain visible to users. 5787 * 5788 * <p>This function requires an IPC back to the window manager to retrieve 5789 * the requested information, so should not be used in performance critical 5790 * code like drawing. 5791 * 5792 * @param outRect Filled in with the visible display frame. If the view 5793 * is not attached to a window, this is simply the raw display size. 5794 */ 5795 public void getWindowVisibleDisplayFrame(Rect outRect) { 5796 if (mAttachInfo != null) { 5797 try { 5798 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 5799 } catch (RemoteException e) { 5800 return; 5801 } 5802 // XXX This is really broken, and probably all needs to be done 5803 // in the window manager, and we need to know more about whether 5804 // we want the area behind or in front of the IME. 5805 final Rect insets = mAttachInfo.mVisibleInsets; 5806 outRect.left += insets.left; 5807 outRect.top += insets.top; 5808 outRect.right -= insets.right; 5809 outRect.bottom -= insets.bottom; 5810 return; 5811 } 5812 Display d = WindowManagerImpl.getDefault().getDefaultDisplay(); 5813 d.getRectSize(outRect); 5814 } 5815 5816 /** 5817 * Dispatch a notification about a resource configuration change down 5818 * the view hierarchy. 5819 * ViewGroups should override to route to their children. 5820 * 5821 * @param newConfig The new resource configuration. 5822 * 5823 * @see #onConfigurationChanged(android.content.res.Configuration) 5824 */ 5825 public void dispatchConfigurationChanged(Configuration newConfig) { 5826 onConfigurationChanged(newConfig); 5827 } 5828 5829 /** 5830 * Called when the current configuration of the resources being used 5831 * by the application have changed. You can use this to decide when 5832 * to reload resources that can changed based on orientation and other 5833 * configuration characterstics. You only need to use this if you are 5834 * not relying on the normal {@link android.app.Activity} mechanism of 5835 * recreating the activity instance upon a configuration change. 5836 * 5837 * @param newConfig The new resource configuration. 5838 */ 5839 protected void onConfigurationChanged(Configuration newConfig) { 5840 } 5841 5842 /** 5843 * Private function to aggregate all per-view attributes in to the view 5844 * root. 5845 */ 5846 void dispatchCollectViewAttributes(int visibility) { 5847 performCollectViewAttributes(visibility); 5848 } 5849 5850 void performCollectViewAttributes(int visibility) { 5851 if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) { 5852 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 5853 mAttachInfo.mKeepScreenOn = true; 5854 } 5855 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility; 5856 if (mOnSystemUiVisibilityChangeListener != null) { 5857 mAttachInfo.mHasSystemUiListeners = true; 5858 } 5859 } 5860 } 5861 5862 void needGlobalAttributesUpdate(boolean force) { 5863 final AttachInfo ai = mAttachInfo; 5864 if (ai != null) { 5865 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 5866 || ai.mHasSystemUiListeners) { 5867 ai.mRecomputeGlobalAttributes = true; 5868 } 5869 } 5870 } 5871 5872 /** 5873 * Returns whether the device is currently in touch mode. Touch mode is entered 5874 * once the user begins interacting with the device by touch, and affects various 5875 * things like whether focus is always visible to the user. 5876 * 5877 * @return Whether the device is in touch mode. 5878 */ 5879 @ViewDebug.ExportedProperty 5880 public boolean isInTouchMode() { 5881 if (mAttachInfo != null) { 5882 return mAttachInfo.mInTouchMode; 5883 } else { 5884 return ViewRootImpl.isInTouchMode(); 5885 } 5886 } 5887 5888 /** 5889 * Returns the context the view is running in, through which it can 5890 * access the current theme, resources, etc. 5891 * 5892 * @return The view's Context. 5893 */ 5894 @ViewDebug.CapturedViewProperty 5895 public final Context getContext() { 5896 return mContext; 5897 } 5898 5899 /** 5900 * Handle a key event before it is processed by any input method 5901 * associated with the view hierarchy. This can be used to intercept 5902 * key events in special situations before the IME consumes them; a 5903 * typical example would be handling the BACK key to update the application's 5904 * UI instead of allowing the IME to see it and close itself. 5905 * 5906 * @param keyCode The value in event.getKeyCode(). 5907 * @param event Description of the key event. 5908 * @return If you handled the event, return true. If you want to allow the 5909 * event to be handled by the next receiver, return false. 5910 */ 5911 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 5912 return false; 5913 } 5914 5915 /** 5916 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 5917 * KeyEvent.Callback.onKeyDown()}: perform press of the view 5918 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 5919 * is released, if the view is enabled and clickable. 5920 * 5921 * @param keyCode A key code that represents the button pressed, from 5922 * {@link android.view.KeyEvent}. 5923 * @param event The KeyEvent object that defines the button action. 5924 */ 5925 public boolean onKeyDown(int keyCode, KeyEvent event) { 5926 boolean result = false; 5927 5928 switch (keyCode) { 5929 case KeyEvent.KEYCODE_DPAD_CENTER: 5930 case KeyEvent.KEYCODE_ENTER: { 5931 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5932 return true; 5933 } 5934 // Long clickable items don't necessarily have to be clickable 5935 if (((mViewFlags & CLICKABLE) == CLICKABLE || 5936 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 5937 (event.getRepeatCount() == 0)) { 5938 setPressed(true); 5939 checkForLongClick(0); 5940 return true; 5941 } 5942 break; 5943 } 5944 } 5945 return result; 5946 } 5947 5948 /** 5949 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 5950 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 5951 * the event). 5952 */ 5953 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 5954 return false; 5955 } 5956 5957 /** 5958 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 5959 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 5960 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 5961 * {@link KeyEvent#KEYCODE_ENTER} is released. 5962 * 5963 * @param keyCode A key code that represents the button pressed, from 5964 * {@link android.view.KeyEvent}. 5965 * @param event The KeyEvent object that defines the button action. 5966 */ 5967 public boolean onKeyUp(int keyCode, KeyEvent event) { 5968 boolean result = false; 5969 5970 switch (keyCode) { 5971 case KeyEvent.KEYCODE_DPAD_CENTER: 5972 case KeyEvent.KEYCODE_ENTER: { 5973 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5974 return true; 5975 } 5976 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 5977 setPressed(false); 5978 5979 if (!mHasPerformedLongPress) { 5980 // This is a tap, so remove the longpress check 5981 removeLongPressCallback(); 5982 5983 result = performClick(); 5984 } 5985 } 5986 break; 5987 } 5988 } 5989 return result; 5990 } 5991 5992 /** 5993 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 5994 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 5995 * the event). 5996 * 5997 * @param keyCode A key code that represents the button pressed, from 5998 * {@link android.view.KeyEvent}. 5999 * @param repeatCount The number of times the action was made. 6000 * @param event The KeyEvent object that defines the button action. 6001 */ 6002 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 6003 return false; 6004 } 6005 6006 /** 6007 * Called on the focused view when a key shortcut event is not handled. 6008 * Override this method to implement local key shortcuts for the View. 6009 * Key shortcuts can also be implemented by setting the 6010 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 6011 * 6012 * @param keyCode The value in event.getKeyCode(). 6013 * @param event Description of the key event. 6014 * @return If you handled the event, return true. If you want to allow the 6015 * event to be handled by the next receiver, return false. 6016 */ 6017 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 6018 return false; 6019 } 6020 6021 /** 6022 * Check whether the called view is a text editor, in which case it 6023 * would make sense to automatically display a soft input window for 6024 * it. Subclasses should override this if they implement 6025 * {@link #onCreateInputConnection(EditorInfo)} to return true if 6026 * a call on that method would return a non-null InputConnection, and 6027 * they are really a first-class editor that the user would normally 6028 * start typing on when the go into a window containing your view. 6029 * 6030 * <p>The default implementation always returns false. This does 6031 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 6032 * will not be called or the user can not otherwise perform edits on your 6033 * view; it is just a hint to the system that this is not the primary 6034 * purpose of this view. 6035 * 6036 * @return Returns true if this view is a text editor, else false. 6037 */ 6038 public boolean onCheckIsTextEditor() { 6039 return false; 6040 } 6041 6042 /** 6043 * Create a new InputConnection for an InputMethod to interact 6044 * with the view. The default implementation returns null, since it doesn't 6045 * support input methods. You can override this to implement such support. 6046 * This is only needed for views that take focus and text input. 6047 * 6048 * <p>When implementing this, you probably also want to implement 6049 * {@link #onCheckIsTextEditor()} to indicate you will return a 6050 * non-null InputConnection. 6051 * 6052 * @param outAttrs Fill in with attribute information about the connection. 6053 */ 6054 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 6055 return null; 6056 } 6057 6058 /** 6059 * Called by the {@link android.view.inputmethod.InputMethodManager} 6060 * when a view who is not the current 6061 * input connection target is trying to make a call on the manager. The 6062 * default implementation returns false; you can override this to return 6063 * true for certain views if you are performing InputConnection proxying 6064 * to them. 6065 * @param view The View that is making the InputMethodManager call. 6066 * @return Return true to allow the call, false to reject. 6067 */ 6068 public boolean checkInputConnectionProxy(View view) { 6069 return false; 6070 } 6071 6072 /** 6073 * Show the context menu for this view. It is not safe to hold on to the 6074 * menu after returning from this method. 6075 * 6076 * You should normally not overload this method. Overload 6077 * {@link #onCreateContextMenu(ContextMenu)} or define an 6078 * {@link OnCreateContextMenuListener} to add items to the context menu. 6079 * 6080 * @param menu The context menu to populate 6081 */ 6082 public void createContextMenu(ContextMenu menu) { 6083 ContextMenuInfo menuInfo = getContextMenuInfo(); 6084 6085 // Sets the current menu info so all items added to menu will have 6086 // my extra info set. 6087 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 6088 6089 onCreateContextMenu(menu); 6090 if (mOnCreateContextMenuListener != null) { 6091 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 6092 } 6093 6094 // Clear the extra information so subsequent items that aren't mine don't 6095 // have my extra info. 6096 ((MenuBuilder)menu).setCurrentMenuInfo(null); 6097 6098 if (mParent != null) { 6099 mParent.createContextMenu(menu); 6100 } 6101 } 6102 6103 /** 6104 * Views should implement this if they have extra information to associate 6105 * with the context menu. The return result is supplied as a parameter to 6106 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 6107 * callback. 6108 * 6109 * @return Extra information about the item for which the context menu 6110 * should be shown. This information will vary across different 6111 * subclasses of View. 6112 */ 6113 protected ContextMenuInfo getContextMenuInfo() { 6114 return null; 6115 } 6116 6117 /** 6118 * Views should implement this if the view itself is going to add items to 6119 * the context menu. 6120 * 6121 * @param menu the context menu to populate 6122 */ 6123 protected void onCreateContextMenu(ContextMenu menu) { 6124 } 6125 6126 /** 6127 * Implement this method to handle trackball motion events. The 6128 * <em>relative</em> movement of the trackball since the last event 6129 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 6130 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 6131 * that a movement of 1 corresponds to the user pressing one DPAD key (so 6132 * they will often be fractional values, representing the more fine-grained 6133 * movement information available from a trackball). 6134 * 6135 * @param event The motion event. 6136 * @return True if the event was handled, false otherwise. 6137 */ 6138 public boolean onTrackballEvent(MotionEvent event) { 6139 return false; 6140 } 6141 6142 /** 6143 * Implement this method to handle generic motion events. 6144 * <p> 6145 * Generic motion events describe joystick movements, mouse hovers, track pad 6146 * touches, scroll wheel movements and other input events. The 6147 * {@link MotionEvent#getSource() source} of the motion event specifies 6148 * the class of input that was received. Implementations of this method 6149 * must examine the bits in the source before processing the event. 6150 * The following code example shows how this is done. 6151 * </p><p> 6152 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 6153 * are delivered to the view under the pointer. All other generic motion events are 6154 * delivered to the focused view. 6155 * </p> 6156 * <code> 6157 * public boolean onGenericMotionEvent(MotionEvent event) { 6158 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 6159 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 6160 * // process the joystick movement... 6161 * return true; 6162 * } 6163 * } 6164 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 6165 * switch (event.getAction()) { 6166 * case MotionEvent.ACTION_HOVER_MOVE: 6167 * // process the mouse hover movement... 6168 * return true; 6169 * case MotionEvent.ACTION_SCROLL: 6170 * // process the scroll wheel movement... 6171 * return true; 6172 * } 6173 * } 6174 * return super.onGenericMotionEvent(event); 6175 * } 6176 * </code> 6177 * 6178 * @param event The generic motion event being processed. 6179 * @return True if the event was handled, false otherwise. 6180 */ 6181 public boolean onGenericMotionEvent(MotionEvent event) { 6182 return false; 6183 } 6184 6185 /** 6186 * Implement this method to handle hover events. 6187 * <p> 6188 * This method is called whenever a pointer is hovering into, over, or out of the 6189 * bounds of a view and the view is not currently being touched. 6190 * Hover events are represented as pointer events with action 6191 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 6192 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 6193 * </p> 6194 * <ul> 6195 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 6196 * when the pointer enters the bounds of the view.</li> 6197 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 6198 * when the pointer has already entered the bounds of the view and has moved.</li> 6199 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 6200 * when the pointer has exited the bounds of the view or when the pointer is 6201 * about to go down due to a button click, tap, or similar user action that 6202 * causes the view to be touched.</li> 6203 * </ul> 6204 * <p> 6205 * The view should implement this method to return true to indicate that it is 6206 * handling the hover event, such as by changing its drawable state. 6207 * </p><p> 6208 * The default implementation calls {@link #setHovered} to update the hovered state 6209 * of the view when a hover enter or hover exit event is received, if the view 6210 * is enabled and is clickable. The default implementation also sends hover 6211 * accessibility events. 6212 * </p> 6213 * 6214 * @param event The motion event that describes the hover. 6215 * @return True if the view handled the hover event. 6216 * 6217 * @see #isHovered 6218 * @see #setHovered 6219 * @see #onHoverChanged 6220 */ 6221 public boolean onHoverEvent(MotionEvent event) { 6222 // The root view may receive hover (or touch) events that are outside the bounds of 6223 // the window. This code ensures that we only send accessibility events for 6224 // hovers that are actually within the bounds of the root view. 6225 final int action = event.getAction(); 6226 if (!mSendingHoverAccessibilityEvents) { 6227 if ((action == MotionEvent.ACTION_HOVER_ENTER 6228 || action == MotionEvent.ACTION_HOVER_MOVE) 6229 && !hasHoveredChild() 6230 && pointInView(event.getX(), event.getY())) { 6231 mSendingHoverAccessibilityEvents = true; 6232 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 6233 } 6234 } else { 6235 if (action == MotionEvent.ACTION_HOVER_EXIT 6236 || (action == MotionEvent.ACTION_HOVER_MOVE 6237 && !pointInView(event.getX(), event.getY()))) { 6238 mSendingHoverAccessibilityEvents = false; 6239 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 6240 } 6241 } 6242 6243 if (isHoverable()) { 6244 switch (action) { 6245 case MotionEvent.ACTION_HOVER_ENTER: 6246 setHovered(true); 6247 break; 6248 case MotionEvent.ACTION_HOVER_EXIT: 6249 setHovered(false); 6250 break; 6251 } 6252 6253 // Dispatch the event to onGenericMotionEvent before returning true. 6254 // This is to provide compatibility with existing applications that 6255 // handled HOVER_MOVE events in onGenericMotionEvent and that would 6256 // break because of the new default handling for hoverable views 6257 // in onHoverEvent. 6258 // Note that onGenericMotionEvent will be called by default when 6259 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 6260 dispatchGenericMotionEventInternal(event); 6261 return true; 6262 } 6263 return false; 6264 } 6265 6266 /** 6267 * Returns true if the view should handle {@link #onHoverEvent} 6268 * by calling {@link #setHovered} to change its hovered state. 6269 * 6270 * @return True if the view is hoverable. 6271 */ 6272 private boolean isHoverable() { 6273 final int viewFlags = mViewFlags; 6274 //noinspection SimplifiableIfStatement 6275 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6276 return false; 6277 } 6278 6279 return (viewFlags & CLICKABLE) == CLICKABLE 6280 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6281 } 6282 6283 /** 6284 * Returns true if the view is currently hovered. 6285 * 6286 * @return True if the view is currently hovered. 6287 * 6288 * @see #setHovered 6289 * @see #onHoverChanged 6290 */ 6291 @ViewDebug.ExportedProperty 6292 public boolean isHovered() { 6293 return (mPrivateFlags & HOVERED) != 0; 6294 } 6295 6296 /** 6297 * Sets whether the view is currently hovered. 6298 * <p> 6299 * Calling this method also changes the drawable state of the view. This 6300 * enables the view to react to hover by using different drawable resources 6301 * to change its appearance. 6302 * </p><p> 6303 * The {@link #onHoverChanged} method is called when the hovered state changes. 6304 * </p> 6305 * 6306 * @param hovered True if the view is hovered. 6307 * 6308 * @see #isHovered 6309 * @see #onHoverChanged 6310 */ 6311 public void setHovered(boolean hovered) { 6312 if (hovered) { 6313 if ((mPrivateFlags & HOVERED) == 0) { 6314 mPrivateFlags |= HOVERED; 6315 refreshDrawableState(); 6316 onHoverChanged(true); 6317 } 6318 } else { 6319 if ((mPrivateFlags & HOVERED) != 0) { 6320 mPrivateFlags &= ~HOVERED; 6321 refreshDrawableState(); 6322 onHoverChanged(false); 6323 } 6324 } 6325 } 6326 6327 /** 6328 * Implement this method to handle hover state changes. 6329 * <p> 6330 * This method is called whenever the hover state changes as a result of a 6331 * call to {@link #setHovered}. 6332 * </p> 6333 * 6334 * @param hovered The current hover state, as returned by {@link #isHovered}. 6335 * 6336 * @see #isHovered 6337 * @see #setHovered 6338 */ 6339 public void onHoverChanged(boolean hovered) { 6340 } 6341 6342 /** 6343 * Implement this method to handle touch screen motion events. 6344 * 6345 * @param event The motion event. 6346 * @return True if the event was handled, false otherwise. 6347 */ 6348 public boolean onTouchEvent(MotionEvent event) { 6349 final int viewFlags = mViewFlags; 6350 6351 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6352 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) { 6353 mPrivateFlags &= ~PRESSED; 6354 refreshDrawableState(); 6355 } 6356 // A disabled view that is clickable still consumes the touch 6357 // events, it just doesn't respond to them. 6358 return (((viewFlags & CLICKABLE) == CLICKABLE || 6359 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 6360 } 6361 6362 if (mTouchDelegate != null) { 6363 if (mTouchDelegate.onTouchEvent(event)) { 6364 return true; 6365 } 6366 } 6367 6368 if (((viewFlags & CLICKABLE) == CLICKABLE || 6369 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 6370 switch (event.getAction()) { 6371 case MotionEvent.ACTION_UP: 6372 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; 6373 if ((mPrivateFlags & PRESSED) != 0 || prepressed) { 6374 // take focus if we don't have it already and we should in 6375 // touch mode. 6376 boolean focusTaken = false; 6377 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 6378 focusTaken = requestFocus(); 6379 } 6380 6381 if (prepressed) { 6382 // The button is being released before we actually 6383 // showed it as pressed. Make it show the pressed 6384 // state now (before scheduling the click) to ensure 6385 // the user sees it. 6386 mPrivateFlags |= PRESSED; 6387 refreshDrawableState(); 6388 } 6389 6390 if (!mHasPerformedLongPress) { 6391 // This is a tap, so remove the longpress check 6392 removeLongPressCallback(); 6393 6394 // Only perform take click actions if we were in the pressed state 6395 if (!focusTaken) { 6396 // Use a Runnable and post this rather than calling 6397 // performClick directly. This lets other visual state 6398 // of the view update before click actions start. 6399 if (mPerformClick == null) { 6400 mPerformClick = new PerformClick(); 6401 } 6402 if (!post(mPerformClick)) { 6403 performClick(); 6404 } 6405 } 6406 } 6407 6408 if (mUnsetPressedState == null) { 6409 mUnsetPressedState = new UnsetPressedState(); 6410 } 6411 6412 if (prepressed) { 6413 postDelayed(mUnsetPressedState, 6414 ViewConfiguration.getPressedStateDuration()); 6415 } else if (!post(mUnsetPressedState)) { 6416 // If the post failed, unpress right now 6417 mUnsetPressedState.run(); 6418 } 6419 removeTapCallback(); 6420 } 6421 break; 6422 6423 case MotionEvent.ACTION_DOWN: 6424 mHasPerformedLongPress = false; 6425 6426 if (performButtonActionOnTouchDown(event)) { 6427 break; 6428 } 6429 6430 // Walk up the hierarchy to determine if we're inside a scrolling container. 6431 boolean isInScrollingContainer = isInScrollingContainer(); 6432 6433 // For views inside a scrolling container, delay the pressed feedback for 6434 // a short period in case this is a scroll. 6435 if (isInScrollingContainer) { 6436 mPrivateFlags |= PREPRESSED; 6437 if (mPendingCheckForTap == null) { 6438 mPendingCheckForTap = new CheckForTap(); 6439 } 6440 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 6441 } else { 6442 // Not inside a scrolling container, so show the feedback right away 6443 mPrivateFlags |= PRESSED; 6444 refreshDrawableState(); 6445 checkForLongClick(0); 6446 } 6447 break; 6448 6449 case MotionEvent.ACTION_CANCEL: 6450 mPrivateFlags &= ~PRESSED; 6451 refreshDrawableState(); 6452 removeTapCallback(); 6453 break; 6454 6455 case MotionEvent.ACTION_MOVE: 6456 final int x = (int) event.getX(); 6457 final int y = (int) event.getY(); 6458 6459 // Be lenient about moving outside of buttons 6460 if (!pointInView(x, y, mTouchSlop)) { 6461 // Outside button 6462 removeTapCallback(); 6463 if ((mPrivateFlags & PRESSED) != 0) { 6464 // Remove any future long press/tap checks 6465 removeLongPressCallback(); 6466 6467 // Need to switch from pressed to not pressed 6468 mPrivateFlags &= ~PRESSED; 6469 refreshDrawableState(); 6470 } 6471 } 6472 break; 6473 } 6474 return true; 6475 } 6476 6477 return false; 6478 } 6479 6480 /** 6481 * @hide 6482 */ 6483 public boolean isInScrollingContainer() { 6484 ViewParent p = getParent(); 6485 while (p != null && p instanceof ViewGroup) { 6486 if (((ViewGroup) p).shouldDelayChildPressedState()) { 6487 return true; 6488 } 6489 p = p.getParent(); 6490 } 6491 return false; 6492 } 6493 6494 /** 6495 * Remove the longpress detection timer. 6496 */ 6497 private void removeLongPressCallback() { 6498 if (mPendingCheckForLongPress != null) { 6499 removeCallbacks(mPendingCheckForLongPress); 6500 } 6501 } 6502 6503 /** 6504 * Remove the pending click action 6505 */ 6506 private void removePerformClickCallback() { 6507 if (mPerformClick != null) { 6508 removeCallbacks(mPerformClick); 6509 } 6510 } 6511 6512 /** 6513 * Remove the prepress detection timer. 6514 */ 6515 private void removeUnsetPressCallback() { 6516 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) { 6517 setPressed(false); 6518 removeCallbacks(mUnsetPressedState); 6519 } 6520 } 6521 6522 /** 6523 * Remove the tap detection timer. 6524 */ 6525 private void removeTapCallback() { 6526 if (mPendingCheckForTap != null) { 6527 mPrivateFlags &= ~PREPRESSED; 6528 removeCallbacks(mPendingCheckForTap); 6529 } 6530 } 6531 6532 /** 6533 * Cancels a pending long press. Your subclass can use this if you 6534 * want the context menu to come up if the user presses and holds 6535 * at the same place, but you don't want it to come up if they press 6536 * and then move around enough to cause scrolling. 6537 */ 6538 public void cancelLongPress() { 6539 removeLongPressCallback(); 6540 6541 /* 6542 * The prepressed state handled by the tap callback is a display 6543 * construct, but the tap callback will post a long press callback 6544 * less its own timeout. Remove it here. 6545 */ 6546 removeTapCallback(); 6547 } 6548 6549 /** 6550 * Remove the pending callback for sending a 6551 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 6552 */ 6553 private void removeSendViewScrolledAccessibilityEventCallback() { 6554 if (mSendViewScrolledAccessibilityEvent != null) { 6555 removeCallbacks(mSendViewScrolledAccessibilityEvent); 6556 } 6557 } 6558 6559 /** 6560 * Sets the TouchDelegate for this View. 6561 */ 6562 public void setTouchDelegate(TouchDelegate delegate) { 6563 mTouchDelegate = delegate; 6564 } 6565 6566 /** 6567 * Gets the TouchDelegate for this View. 6568 */ 6569 public TouchDelegate getTouchDelegate() { 6570 return mTouchDelegate; 6571 } 6572 6573 /** 6574 * Set flags controlling behavior of this view. 6575 * 6576 * @param flags Constant indicating the value which should be set 6577 * @param mask Constant indicating the bit range that should be changed 6578 */ 6579 void setFlags(int flags, int mask) { 6580 int old = mViewFlags; 6581 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 6582 6583 int changed = mViewFlags ^ old; 6584 if (changed == 0) { 6585 return; 6586 } 6587 int privateFlags = mPrivateFlags; 6588 6589 /* Check if the FOCUSABLE bit has changed */ 6590 if (((changed & FOCUSABLE_MASK) != 0) && 6591 ((privateFlags & HAS_BOUNDS) !=0)) { 6592 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 6593 && ((privateFlags & FOCUSED) != 0)) { 6594 /* Give up focus if we are no longer focusable */ 6595 clearFocus(); 6596 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 6597 && ((privateFlags & FOCUSED) == 0)) { 6598 /* 6599 * Tell the view system that we are now available to take focus 6600 * if no one else already has it. 6601 */ 6602 if (mParent != null) mParent.focusableViewAvailable(this); 6603 } 6604 } 6605 6606 if ((flags & VISIBILITY_MASK) == VISIBLE) { 6607 if ((changed & VISIBILITY_MASK) != 0) { 6608 /* 6609 * If this view is becoming visible, invalidate it in case it changed while 6610 * it was not visible. Marking it drawn ensures that the invalidation will 6611 * go through. 6612 */ 6613 mPrivateFlags |= DRAWN; 6614 invalidate(true); 6615 6616 needGlobalAttributesUpdate(true); 6617 6618 // a view becoming visible is worth notifying the parent 6619 // about in case nothing has focus. even if this specific view 6620 // isn't focusable, it may contain something that is, so let 6621 // the root view try to give this focus if nothing else does. 6622 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 6623 mParent.focusableViewAvailable(this); 6624 } 6625 } 6626 } 6627 6628 /* Check if the GONE bit has changed */ 6629 if ((changed & GONE) != 0) { 6630 needGlobalAttributesUpdate(false); 6631 requestLayout(); 6632 6633 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 6634 if (hasFocus()) clearFocus(); 6635 destroyDrawingCache(); 6636 if (mParent instanceof View) { 6637 // GONE views noop invalidation, so invalidate the parent 6638 ((View) mParent).invalidate(true); 6639 } 6640 // Mark the view drawn to ensure that it gets invalidated properly the next 6641 // time it is visible and gets invalidated 6642 mPrivateFlags |= DRAWN; 6643 } 6644 if (mAttachInfo != null) { 6645 mAttachInfo.mViewVisibilityChanged = true; 6646 } 6647 } 6648 6649 /* Check if the VISIBLE bit has changed */ 6650 if ((changed & INVISIBLE) != 0) { 6651 needGlobalAttributesUpdate(false); 6652 /* 6653 * If this view is becoming invisible, set the DRAWN flag so that 6654 * the next invalidate() will not be skipped. 6655 */ 6656 mPrivateFlags |= DRAWN; 6657 6658 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 6659 // root view becoming invisible shouldn't clear focus 6660 if (getRootView() != this) { 6661 clearFocus(); 6662 } 6663 } 6664 if (mAttachInfo != null) { 6665 mAttachInfo.mViewVisibilityChanged = true; 6666 } 6667 } 6668 6669 if ((changed & VISIBILITY_MASK) != 0) { 6670 if (mParent instanceof ViewGroup) { 6671 ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6672 ((View) mParent).invalidate(true); 6673 } else if (mParent != null) { 6674 mParent.invalidateChild(this, null); 6675 } 6676 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6677 } 6678 6679 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 6680 destroyDrawingCache(); 6681 } 6682 6683 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 6684 destroyDrawingCache(); 6685 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6686 invalidateParentCaches(); 6687 } 6688 6689 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 6690 destroyDrawingCache(); 6691 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6692 } 6693 6694 if ((changed & DRAW_MASK) != 0) { 6695 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 6696 if (mBGDrawable != null) { 6697 mPrivateFlags &= ~SKIP_DRAW; 6698 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 6699 } else { 6700 mPrivateFlags |= SKIP_DRAW; 6701 } 6702 } else { 6703 mPrivateFlags &= ~SKIP_DRAW; 6704 } 6705 requestLayout(); 6706 invalidate(true); 6707 } 6708 6709 if ((changed & KEEP_SCREEN_ON) != 0) { 6710 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 6711 mParent.recomputeViewAttributes(this); 6712 } 6713 } 6714 6715 if ((changed & LAYOUT_DIRECTION_MASK) != 0) { 6716 requestLayout(); 6717 } 6718 } 6719 6720 /** 6721 * Change the view's z order in the tree, so it's on top of other sibling 6722 * views 6723 */ 6724 public void bringToFront() { 6725 if (mParent != null) { 6726 mParent.bringChildToFront(this); 6727 } 6728 } 6729 6730 /** 6731 * This is called in response to an internal scroll in this view (i.e., the 6732 * view scrolled its own contents). This is typically as a result of 6733 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 6734 * called. 6735 * 6736 * @param l Current horizontal scroll origin. 6737 * @param t Current vertical scroll origin. 6738 * @param oldl Previous horizontal scroll origin. 6739 * @param oldt Previous vertical scroll origin. 6740 */ 6741 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 6742 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6743 postSendViewScrolledAccessibilityEventCallback(); 6744 } 6745 6746 mBackgroundSizeChanged = true; 6747 6748 final AttachInfo ai = mAttachInfo; 6749 if (ai != null) { 6750 ai.mViewScrollChanged = true; 6751 } 6752 } 6753 6754 /** 6755 * Interface definition for a callback to be invoked when the layout bounds of a view 6756 * changes due to layout processing. 6757 */ 6758 public interface OnLayoutChangeListener { 6759 /** 6760 * Called when the focus state of a view has changed. 6761 * 6762 * @param v The view whose state has changed. 6763 * @param left The new value of the view's left property. 6764 * @param top The new value of the view's top property. 6765 * @param right The new value of the view's right property. 6766 * @param bottom The new value of the view's bottom property. 6767 * @param oldLeft The previous value of the view's left property. 6768 * @param oldTop The previous value of the view's top property. 6769 * @param oldRight The previous value of the view's right property. 6770 * @param oldBottom The previous value of the view's bottom property. 6771 */ 6772 void onLayoutChange(View v, int left, int top, int right, int bottom, 6773 int oldLeft, int oldTop, int oldRight, int oldBottom); 6774 } 6775 6776 /** 6777 * This is called during layout when the size of this view has changed. If 6778 * you were just added to the view hierarchy, you're called with the old 6779 * values of 0. 6780 * 6781 * @param w Current width of this view. 6782 * @param h Current height of this view. 6783 * @param oldw Old width of this view. 6784 * @param oldh Old height of this view. 6785 */ 6786 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 6787 } 6788 6789 /** 6790 * Called by draw to draw the child views. This may be overridden 6791 * by derived classes to gain control just before its children are drawn 6792 * (but after its own view has been drawn). 6793 * @param canvas the canvas on which to draw the view 6794 */ 6795 protected void dispatchDraw(Canvas canvas) { 6796 } 6797 6798 /** 6799 * Gets the parent of this view. Note that the parent is a 6800 * ViewParent and not necessarily a View. 6801 * 6802 * @return Parent of this view. 6803 */ 6804 public final ViewParent getParent() { 6805 return mParent; 6806 } 6807 6808 /** 6809 * Set the horizontal scrolled position of your view. This will cause a call to 6810 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6811 * invalidated. 6812 * @param value the x position to scroll to 6813 */ 6814 public void setScrollX(int value) { 6815 scrollTo(value, mScrollY); 6816 } 6817 6818 /** 6819 * Set the vertical scrolled position of your view. This will cause a call to 6820 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6821 * invalidated. 6822 * @param value the y position to scroll to 6823 */ 6824 public void setScrollY(int value) { 6825 scrollTo(mScrollX, value); 6826 } 6827 6828 /** 6829 * Return the scrolled left position of this view. This is the left edge of 6830 * the displayed part of your view. You do not need to draw any pixels 6831 * farther left, since those are outside of the frame of your view on 6832 * screen. 6833 * 6834 * @return The left edge of the displayed part of your view, in pixels. 6835 */ 6836 public final int getScrollX() { 6837 return mScrollX; 6838 } 6839 6840 /** 6841 * Return the scrolled top position of this view. This is the top edge of 6842 * the displayed part of your view. You do not need to draw any pixels above 6843 * it, since those are outside of the frame of your view on screen. 6844 * 6845 * @return The top edge of the displayed part of your view, in pixels. 6846 */ 6847 public final int getScrollY() { 6848 return mScrollY; 6849 } 6850 6851 /** 6852 * Return the width of the your view. 6853 * 6854 * @return The width of your view, in pixels. 6855 */ 6856 @ViewDebug.ExportedProperty(category = "layout") 6857 public final int getWidth() { 6858 return mRight - mLeft; 6859 } 6860 6861 /** 6862 * Return the height of your view. 6863 * 6864 * @return The height of your view, in pixels. 6865 */ 6866 @ViewDebug.ExportedProperty(category = "layout") 6867 public final int getHeight() { 6868 return mBottom - mTop; 6869 } 6870 6871 /** 6872 * Return the visible drawing bounds of your view. Fills in the output 6873 * rectangle with the values from getScrollX(), getScrollY(), 6874 * getWidth(), and getHeight(). 6875 * 6876 * @param outRect The (scrolled) drawing bounds of the view. 6877 */ 6878 public void getDrawingRect(Rect outRect) { 6879 outRect.left = mScrollX; 6880 outRect.top = mScrollY; 6881 outRect.right = mScrollX + (mRight - mLeft); 6882 outRect.bottom = mScrollY + (mBottom - mTop); 6883 } 6884 6885 /** 6886 * Like {@link #getMeasuredWidthAndState()}, but only returns the 6887 * raw width component (that is the result is masked by 6888 * {@link #MEASURED_SIZE_MASK}). 6889 * 6890 * @return The raw measured width of this view. 6891 */ 6892 public final int getMeasuredWidth() { 6893 return mMeasuredWidth & MEASURED_SIZE_MASK; 6894 } 6895 6896 /** 6897 * Return the full width measurement information for this view as computed 6898 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6899 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6900 * This should be used during measurement and layout calculations only. Use 6901 * {@link #getWidth()} to see how wide a view is after layout. 6902 * 6903 * @return The measured width of this view as a bit mask. 6904 */ 6905 public final int getMeasuredWidthAndState() { 6906 return mMeasuredWidth; 6907 } 6908 6909 /** 6910 * Like {@link #getMeasuredHeightAndState()}, but only returns the 6911 * raw width component (that is the result is masked by 6912 * {@link #MEASURED_SIZE_MASK}). 6913 * 6914 * @return The raw measured height of this view. 6915 */ 6916 public final int getMeasuredHeight() { 6917 return mMeasuredHeight & MEASURED_SIZE_MASK; 6918 } 6919 6920 /** 6921 * Return the full height measurement information for this view as computed 6922 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6923 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6924 * This should be used during measurement and layout calculations only. Use 6925 * {@link #getHeight()} to see how wide a view is after layout. 6926 * 6927 * @return The measured width of this view as a bit mask. 6928 */ 6929 public final int getMeasuredHeightAndState() { 6930 return mMeasuredHeight; 6931 } 6932 6933 /** 6934 * Return only the state bits of {@link #getMeasuredWidthAndState()} 6935 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 6936 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 6937 * and the height component is at the shifted bits 6938 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 6939 */ 6940 public final int getMeasuredState() { 6941 return (mMeasuredWidth&MEASURED_STATE_MASK) 6942 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 6943 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 6944 } 6945 6946 /** 6947 * The transform matrix of this view, which is calculated based on the current 6948 * roation, scale, and pivot properties. 6949 * 6950 * @see #getRotation() 6951 * @see #getScaleX() 6952 * @see #getScaleY() 6953 * @see #getPivotX() 6954 * @see #getPivotY() 6955 * @return The current transform matrix for the view 6956 */ 6957 public Matrix getMatrix() { 6958 if (mTransformationInfo != null) { 6959 updateMatrix(); 6960 return mTransformationInfo.mMatrix; 6961 } 6962 return Matrix.IDENTITY_MATRIX; 6963 } 6964 6965 /** 6966 * Utility function to determine if the value is far enough away from zero to be 6967 * considered non-zero. 6968 * @param value A floating point value to check for zero-ness 6969 * @return whether the passed-in value is far enough away from zero to be considered non-zero 6970 */ 6971 private static boolean nonzero(float value) { 6972 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 6973 } 6974 6975 /** 6976 * Returns true if the transform matrix is the identity matrix. 6977 * Recomputes the matrix if necessary. 6978 * 6979 * @return True if the transform matrix is the identity matrix, false otherwise. 6980 */ 6981 final boolean hasIdentityMatrix() { 6982 if (mTransformationInfo != null) { 6983 updateMatrix(); 6984 return mTransformationInfo.mMatrixIsIdentity; 6985 } 6986 return true; 6987 } 6988 6989 void ensureTransformationInfo() { 6990 if (mTransformationInfo == null) { 6991 mTransformationInfo = new TransformationInfo(); 6992 } 6993 } 6994 6995 /** 6996 * Recomputes the transform matrix if necessary. 6997 */ 6998 private void updateMatrix() { 6999 final TransformationInfo info = mTransformationInfo; 7000 if (info == null) { 7001 return; 7002 } 7003 if (info.mMatrixDirty) { 7004 // transform-related properties have changed since the last time someone 7005 // asked for the matrix; recalculate it with the current values 7006 7007 // Figure out if we need to update the pivot point 7008 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7009 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 7010 info.mPrevWidth = mRight - mLeft; 7011 info.mPrevHeight = mBottom - mTop; 7012 info.mPivotX = info.mPrevWidth / 2f; 7013 info.mPivotY = info.mPrevHeight / 2f; 7014 } 7015 } 7016 info.mMatrix.reset(); 7017 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 7018 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 7019 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 7020 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 7021 } else { 7022 if (info.mCamera == null) { 7023 info.mCamera = new Camera(); 7024 info.matrix3D = new Matrix(); 7025 } 7026 info.mCamera.save(); 7027 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 7028 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 7029 info.mCamera.getMatrix(info.matrix3D); 7030 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 7031 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 7032 info.mPivotY + info.mTranslationY); 7033 info.mMatrix.postConcat(info.matrix3D); 7034 info.mCamera.restore(); 7035 } 7036 info.mMatrixDirty = false; 7037 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 7038 info.mInverseMatrixDirty = true; 7039 } 7040 } 7041 7042 /** 7043 * Utility method to retrieve the inverse of the current mMatrix property. 7044 * We cache the matrix to avoid recalculating it when transform properties 7045 * have not changed. 7046 * 7047 * @return The inverse of the current matrix of this view. 7048 */ 7049 final Matrix getInverseMatrix() { 7050 final TransformationInfo info = mTransformationInfo; 7051 if (info != null) { 7052 updateMatrix(); 7053 if (info.mInverseMatrixDirty) { 7054 if (info.mInverseMatrix == null) { 7055 info.mInverseMatrix = new Matrix(); 7056 } 7057 info.mMatrix.invert(info.mInverseMatrix); 7058 info.mInverseMatrixDirty = false; 7059 } 7060 return info.mInverseMatrix; 7061 } 7062 return Matrix.IDENTITY_MATRIX; 7063 } 7064 7065 /** 7066 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 7067 * views are drawn) from the camera to this view. The camera's distance 7068 * affects 3D transformations, for instance rotations around the X and Y 7069 * axis. If the rotationX or rotationY properties are changed and this view is 7070 * large (more than half the size of the screen), it is recommended to always 7071 * use a camera distance that's greater than the height (X axis rotation) or 7072 * the width (Y axis rotation) of this view.</p> 7073 * 7074 * <p>The distance of the camera from the view plane can have an affect on the 7075 * perspective distortion of the view when it is rotated around the x or y axis. 7076 * For example, a large distance will result in a large viewing angle, and there 7077 * will not be much perspective distortion of the view as it rotates. A short 7078 * distance may cause much more perspective distortion upon rotation, and can 7079 * also result in some drawing artifacts if the rotated view ends up partially 7080 * behind the camera (which is why the recommendation is to use a distance at 7081 * least as far as the size of the view, if the view is to be rotated.)</p> 7082 * 7083 * <p>The distance is expressed in "depth pixels." The default distance depends 7084 * on the screen density. For instance, on a medium density display, the 7085 * default distance is 1280. On a high density display, the default distance 7086 * is 1920.</p> 7087 * 7088 * <p>If you want to specify a distance that leads to visually consistent 7089 * results across various densities, use the following formula:</p> 7090 * <pre> 7091 * float scale = context.getResources().getDisplayMetrics().density; 7092 * view.setCameraDistance(distance * scale); 7093 * </pre> 7094 * 7095 * <p>The density scale factor of a high density display is 1.5, 7096 * and 1920 = 1280 * 1.5.</p> 7097 * 7098 * @param distance The distance in "depth pixels", if negative the opposite 7099 * value is used 7100 * 7101 * @see #setRotationX(float) 7102 * @see #setRotationY(float) 7103 */ 7104 public void setCameraDistance(float distance) { 7105 invalidateParentCaches(); 7106 invalidate(false); 7107 7108 ensureTransformationInfo(); 7109 final float dpi = mResources.getDisplayMetrics().densityDpi; 7110 final TransformationInfo info = mTransformationInfo; 7111 if (info.mCamera == null) { 7112 info.mCamera = new Camera(); 7113 info.matrix3D = new Matrix(); 7114 } 7115 7116 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 7117 info.mMatrixDirty = true; 7118 7119 invalidate(false); 7120 } 7121 7122 /** 7123 * The degrees that the view is rotated around the pivot point. 7124 * 7125 * @see #setRotation(float) 7126 * @see #getPivotX() 7127 * @see #getPivotY() 7128 * 7129 * @return The degrees of rotation. 7130 */ 7131 public float getRotation() { 7132 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 7133 } 7134 7135 /** 7136 * Sets the degrees that the view is rotated around the pivot point. Increasing values 7137 * result in clockwise rotation. 7138 * 7139 * @param rotation The degrees of rotation. 7140 * 7141 * @see #getRotation() 7142 * @see #getPivotX() 7143 * @see #getPivotY() 7144 * @see #setRotationX(float) 7145 * @see #setRotationY(float) 7146 * 7147 * @attr ref android.R.styleable#View_rotation 7148 */ 7149 public void setRotation(float rotation) { 7150 ensureTransformationInfo(); 7151 final TransformationInfo info = mTransformationInfo; 7152 if (info.mRotation != rotation) { 7153 invalidateParentCaches(); 7154 // Double-invalidation is necessary to capture view's old and new areas 7155 invalidate(false); 7156 info.mRotation = rotation; 7157 info.mMatrixDirty = true; 7158 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7159 invalidate(false); 7160 } 7161 } 7162 7163 /** 7164 * The degrees that the view is rotated around the vertical axis through the pivot point. 7165 * 7166 * @see #getPivotX() 7167 * @see #getPivotY() 7168 * @see #setRotationY(float) 7169 * 7170 * @return The degrees of Y rotation. 7171 */ 7172 public float getRotationY() { 7173 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 7174 } 7175 7176 /** 7177 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 7178 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 7179 * down the y axis. 7180 * 7181 * When rotating large views, it is recommended to adjust the camera distance 7182 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 7183 * 7184 * @param rotationY The degrees of Y rotation. 7185 * 7186 * @see #getRotationY() 7187 * @see #getPivotX() 7188 * @see #getPivotY() 7189 * @see #setRotation(float) 7190 * @see #setRotationX(float) 7191 * @see #setCameraDistance(float) 7192 * 7193 * @attr ref android.R.styleable#View_rotationY 7194 */ 7195 public void setRotationY(float rotationY) { 7196 ensureTransformationInfo(); 7197 final TransformationInfo info = mTransformationInfo; 7198 if (info.mRotationY != rotationY) { 7199 invalidateParentCaches(); 7200 // Double-invalidation is necessary to capture view's old and new areas 7201 invalidate(false); 7202 info.mRotationY = rotationY; 7203 info.mMatrixDirty = true; 7204 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7205 invalidate(false); 7206 } 7207 } 7208 7209 /** 7210 * The degrees that the view is rotated around the horizontal axis through the pivot point. 7211 * 7212 * @see #getPivotX() 7213 * @see #getPivotY() 7214 * @see #setRotationX(float) 7215 * 7216 * @return The degrees of X rotation. 7217 */ 7218 public float getRotationX() { 7219 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 7220 } 7221 7222 /** 7223 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 7224 * Increasing values result in clockwise rotation from the viewpoint of looking down the 7225 * x axis. 7226 * 7227 * When rotating large views, it is recommended to adjust the camera distance 7228 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 7229 * 7230 * @param rotationX The degrees of X rotation. 7231 * 7232 * @see #getRotationX() 7233 * @see #getPivotX() 7234 * @see #getPivotY() 7235 * @see #setRotation(float) 7236 * @see #setRotationY(float) 7237 * @see #setCameraDistance(float) 7238 * 7239 * @attr ref android.R.styleable#View_rotationX 7240 */ 7241 public void setRotationX(float rotationX) { 7242 ensureTransformationInfo(); 7243 final TransformationInfo info = mTransformationInfo; 7244 if (info.mRotationX != rotationX) { 7245 invalidateParentCaches(); 7246 // Double-invalidation is necessary to capture view's old and new areas 7247 invalidate(false); 7248 info.mRotationX = rotationX; 7249 info.mMatrixDirty = true; 7250 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7251 invalidate(false); 7252 } 7253 } 7254 7255 /** 7256 * The amount that the view is scaled in x around the pivot point, as a proportion of 7257 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 7258 * 7259 * <p>By default, this is 1.0f. 7260 * 7261 * @see #getPivotX() 7262 * @see #getPivotY() 7263 * @return The scaling factor. 7264 */ 7265 public float getScaleX() { 7266 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 7267 } 7268 7269 /** 7270 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 7271 * the view's unscaled width. A value of 1 means that no scaling is applied. 7272 * 7273 * @param scaleX The scaling factor. 7274 * @see #getPivotX() 7275 * @see #getPivotY() 7276 * 7277 * @attr ref android.R.styleable#View_scaleX 7278 */ 7279 public void setScaleX(float scaleX) { 7280 ensureTransformationInfo(); 7281 final TransformationInfo info = mTransformationInfo; 7282 if (info.mScaleX != scaleX) { 7283 invalidateParentCaches(); 7284 // Double-invalidation is necessary to capture view's old and new areas 7285 invalidate(false); 7286 info.mScaleX = scaleX; 7287 info.mMatrixDirty = true; 7288 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7289 invalidate(false); 7290 } 7291 } 7292 7293 /** 7294 * The amount that the view is scaled in y around the pivot point, as a proportion of 7295 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 7296 * 7297 * <p>By default, this is 1.0f. 7298 * 7299 * @see #getPivotX() 7300 * @see #getPivotY() 7301 * @return The scaling factor. 7302 */ 7303 public float getScaleY() { 7304 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 7305 } 7306 7307 /** 7308 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 7309 * the view's unscaled width. A value of 1 means that no scaling is applied. 7310 * 7311 * @param scaleY The scaling factor. 7312 * @see #getPivotX() 7313 * @see #getPivotY() 7314 * 7315 * @attr ref android.R.styleable#View_scaleY 7316 */ 7317 public void setScaleY(float scaleY) { 7318 ensureTransformationInfo(); 7319 final TransformationInfo info = mTransformationInfo; 7320 if (info.mScaleY != scaleY) { 7321 invalidateParentCaches(); 7322 // Double-invalidation is necessary to capture view's old and new areas 7323 invalidate(false); 7324 info.mScaleY = scaleY; 7325 info.mMatrixDirty = true; 7326 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7327 invalidate(false); 7328 } 7329 } 7330 7331 /** 7332 * The x location of the point around which the view is {@link #setRotation(float) rotated} 7333 * and {@link #setScaleX(float) scaled}. 7334 * 7335 * @see #getRotation() 7336 * @see #getScaleX() 7337 * @see #getScaleY() 7338 * @see #getPivotY() 7339 * @return The x location of the pivot point. 7340 */ 7341 public float getPivotX() { 7342 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 7343 } 7344 7345 /** 7346 * Sets the x location of the point around which the view is 7347 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 7348 * By default, the pivot point is centered on the object. 7349 * Setting this property disables this behavior and causes the view to use only the 7350 * explicitly set pivotX and pivotY values. 7351 * 7352 * @param pivotX The x location of the pivot point. 7353 * @see #getRotation() 7354 * @see #getScaleX() 7355 * @see #getScaleY() 7356 * @see #getPivotY() 7357 * 7358 * @attr ref android.R.styleable#View_transformPivotX 7359 */ 7360 public void setPivotX(float pivotX) { 7361 ensureTransformationInfo(); 7362 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7363 final TransformationInfo info = mTransformationInfo; 7364 if (info.mPivotX != pivotX) { 7365 invalidateParentCaches(); 7366 // Double-invalidation is necessary to capture view's old and new areas 7367 invalidate(false); 7368 info.mPivotX = pivotX; 7369 info.mMatrixDirty = true; 7370 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7371 invalidate(false); 7372 } 7373 } 7374 7375 /** 7376 * The y location of the point around which the view is {@link #setRotation(float) rotated} 7377 * and {@link #setScaleY(float) scaled}. 7378 * 7379 * @see #getRotation() 7380 * @see #getScaleX() 7381 * @see #getScaleY() 7382 * @see #getPivotY() 7383 * @return The y location of the pivot point. 7384 */ 7385 public float getPivotY() { 7386 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 7387 } 7388 7389 /** 7390 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 7391 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 7392 * Setting this property disables this behavior and causes the view to use only the 7393 * explicitly set pivotX and pivotY values. 7394 * 7395 * @param pivotY The y location of the pivot point. 7396 * @see #getRotation() 7397 * @see #getScaleX() 7398 * @see #getScaleY() 7399 * @see #getPivotY() 7400 * 7401 * @attr ref android.R.styleable#View_transformPivotY 7402 */ 7403 public void setPivotY(float pivotY) { 7404 ensureTransformationInfo(); 7405 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7406 final TransformationInfo info = mTransformationInfo; 7407 if (info.mPivotY != pivotY) { 7408 invalidateParentCaches(); 7409 // Double-invalidation is necessary to capture view's old and new areas 7410 invalidate(false); 7411 info.mPivotY = pivotY; 7412 info.mMatrixDirty = true; 7413 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7414 invalidate(false); 7415 } 7416 } 7417 7418 /** 7419 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 7420 * completely transparent and 1 means the view is completely opaque. 7421 * 7422 * <p>By default this is 1.0f. 7423 * @return The opacity of the view. 7424 */ 7425 public float getAlpha() { 7426 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 7427 } 7428 7429 /** 7430 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 7431 * completely transparent and 1 means the view is completely opaque.</p> 7432 * 7433 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 7434 * responsible for applying the opacity itself. Otherwise, calling this method is 7435 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 7436 * setting a hardware layer.</p> 7437 * 7438 * @param alpha The opacity of the view. 7439 * 7440 * @see #setLayerType(int, android.graphics.Paint) 7441 * 7442 * @attr ref android.R.styleable#View_alpha 7443 */ 7444 public void setAlpha(float alpha) { 7445 ensureTransformationInfo(); 7446 mTransformationInfo.mAlpha = alpha; 7447 invalidateParentCaches(); 7448 if (onSetAlpha((int) (alpha * 255))) { 7449 mPrivateFlags |= ALPHA_SET; 7450 // subclass is handling alpha - don't optimize rendering cache invalidation 7451 invalidate(true); 7452 } else { 7453 mPrivateFlags &= ~ALPHA_SET; 7454 invalidate(false); 7455 } 7456 } 7457 7458 /** 7459 * Faster version of setAlpha() which performs the same steps except there are 7460 * no calls to invalidate(). The caller of this function should perform proper invalidation 7461 * on the parent and this object. The return value indicates whether the subclass handles 7462 * alpha (the return value for onSetAlpha()). 7463 * 7464 * @param alpha The new value for the alpha property 7465 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) 7466 */ 7467 boolean setAlphaNoInvalidation(float alpha) { 7468 ensureTransformationInfo(); 7469 mTransformationInfo.mAlpha = alpha; 7470 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 7471 if (subclassHandlesAlpha) { 7472 mPrivateFlags |= ALPHA_SET; 7473 } else { 7474 mPrivateFlags &= ~ALPHA_SET; 7475 } 7476 return subclassHandlesAlpha; 7477 } 7478 7479 /** 7480 * Top position of this view relative to its parent. 7481 * 7482 * @return The top of this view, in pixels. 7483 */ 7484 @ViewDebug.CapturedViewProperty 7485 public final int getTop() { 7486 return mTop; 7487 } 7488 7489 /** 7490 * Sets the top position of this view relative to its parent. This method is meant to be called 7491 * by the layout system and should not generally be called otherwise, because the property 7492 * may be changed at any time by the layout. 7493 * 7494 * @param top The top of this view, in pixels. 7495 */ 7496 public final void setTop(int top) { 7497 if (top != mTop) { 7498 updateMatrix(); 7499 final boolean matrixIsIdentity = mTransformationInfo == null 7500 || mTransformationInfo.mMatrixIsIdentity; 7501 if (matrixIsIdentity) { 7502 if (mAttachInfo != null) { 7503 int minTop; 7504 int yLoc; 7505 if (top < mTop) { 7506 minTop = top; 7507 yLoc = top - mTop; 7508 } else { 7509 minTop = mTop; 7510 yLoc = 0; 7511 } 7512 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 7513 } 7514 } else { 7515 // Double-invalidation is necessary to capture view's old and new areas 7516 invalidate(true); 7517 } 7518 7519 int width = mRight - mLeft; 7520 int oldHeight = mBottom - mTop; 7521 7522 mTop = top; 7523 7524 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7525 7526 if (!matrixIsIdentity) { 7527 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7528 // A change in dimension means an auto-centered pivot point changes, too 7529 mTransformationInfo.mMatrixDirty = true; 7530 } 7531 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7532 invalidate(true); 7533 } 7534 mBackgroundSizeChanged = true; 7535 invalidateParentIfNeeded(); 7536 } 7537 } 7538 7539 /** 7540 * Bottom position of this view relative to its parent. 7541 * 7542 * @return The bottom of this view, in pixels. 7543 */ 7544 @ViewDebug.CapturedViewProperty 7545 public final int getBottom() { 7546 return mBottom; 7547 } 7548 7549 /** 7550 * True if this view has changed since the last time being drawn. 7551 * 7552 * @return The dirty state of this view. 7553 */ 7554 public boolean isDirty() { 7555 return (mPrivateFlags & DIRTY_MASK) != 0; 7556 } 7557 7558 /** 7559 * Sets the bottom position of this view relative to its parent. This method is meant to be 7560 * called by the layout system and should not generally be called otherwise, because the 7561 * property may be changed at any time by the layout. 7562 * 7563 * @param bottom The bottom of this view, in pixels. 7564 */ 7565 public final void setBottom(int bottom) { 7566 if (bottom != mBottom) { 7567 updateMatrix(); 7568 final boolean matrixIsIdentity = mTransformationInfo == null 7569 || mTransformationInfo.mMatrixIsIdentity; 7570 if (matrixIsIdentity) { 7571 if (mAttachInfo != null) { 7572 int maxBottom; 7573 if (bottom < mBottom) { 7574 maxBottom = mBottom; 7575 } else { 7576 maxBottom = bottom; 7577 } 7578 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 7579 } 7580 } else { 7581 // Double-invalidation is necessary to capture view's old and new areas 7582 invalidate(true); 7583 } 7584 7585 int width = mRight - mLeft; 7586 int oldHeight = mBottom - mTop; 7587 7588 mBottom = bottom; 7589 7590 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7591 7592 if (!matrixIsIdentity) { 7593 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7594 // A change in dimension means an auto-centered pivot point changes, too 7595 mTransformationInfo.mMatrixDirty = true; 7596 } 7597 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7598 invalidate(true); 7599 } 7600 mBackgroundSizeChanged = true; 7601 invalidateParentIfNeeded(); 7602 } 7603 } 7604 7605 /** 7606 * Left position of this view relative to its parent. 7607 * 7608 * @return The left edge of this view, in pixels. 7609 */ 7610 @ViewDebug.CapturedViewProperty 7611 public final int getLeft() { 7612 return mLeft; 7613 } 7614 7615 /** 7616 * Sets the left position of this view relative to its parent. This method is meant to be called 7617 * by the layout system and should not generally be called otherwise, because the property 7618 * may be changed at any time by the layout. 7619 * 7620 * @param left The bottom of this view, in pixels. 7621 */ 7622 public final void setLeft(int left) { 7623 if (left != mLeft) { 7624 updateMatrix(); 7625 final boolean matrixIsIdentity = mTransformationInfo == null 7626 || mTransformationInfo.mMatrixIsIdentity; 7627 if (matrixIsIdentity) { 7628 if (mAttachInfo != null) { 7629 int minLeft; 7630 int xLoc; 7631 if (left < mLeft) { 7632 minLeft = left; 7633 xLoc = left - mLeft; 7634 } else { 7635 minLeft = mLeft; 7636 xLoc = 0; 7637 } 7638 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 7639 } 7640 } else { 7641 // Double-invalidation is necessary to capture view's old and new areas 7642 invalidate(true); 7643 } 7644 7645 int oldWidth = mRight - mLeft; 7646 int height = mBottom - mTop; 7647 7648 mLeft = left; 7649 7650 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7651 7652 if (!matrixIsIdentity) { 7653 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7654 // A change in dimension means an auto-centered pivot point changes, too 7655 mTransformationInfo.mMatrixDirty = true; 7656 } 7657 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7658 invalidate(true); 7659 } 7660 mBackgroundSizeChanged = true; 7661 invalidateParentIfNeeded(); 7662 } 7663 } 7664 7665 /** 7666 * Right position of this view relative to its parent. 7667 * 7668 * @return The right edge of this view, in pixels. 7669 */ 7670 @ViewDebug.CapturedViewProperty 7671 public final int getRight() { 7672 return mRight; 7673 } 7674 7675 /** 7676 * Sets the right position of this view relative to its parent. This method is meant to be called 7677 * by the layout system and should not generally be called otherwise, because the property 7678 * may be changed at any time by the layout. 7679 * 7680 * @param right The bottom of this view, in pixels. 7681 */ 7682 public final void setRight(int right) { 7683 if (right != mRight) { 7684 updateMatrix(); 7685 final boolean matrixIsIdentity = mTransformationInfo == null 7686 || mTransformationInfo.mMatrixIsIdentity; 7687 if (matrixIsIdentity) { 7688 if (mAttachInfo != null) { 7689 int maxRight; 7690 if (right < mRight) { 7691 maxRight = mRight; 7692 } else { 7693 maxRight = right; 7694 } 7695 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 7696 } 7697 } else { 7698 // Double-invalidation is necessary to capture view's old and new areas 7699 invalidate(true); 7700 } 7701 7702 int oldWidth = mRight - mLeft; 7703 int height = mBottom - mTop; 7704 7705 mRight = right; 7706 7707 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7708 7709 if (!matrixIsIdentity) { 7710 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7711 // A change in dimension means an auto-centered pivot point changes, too 7712 mTransformationInfo.mMatrixDirty = true; 7713 } 7714 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7715 invalidate(true); 7716 } 7717 mBackgroundSizeChanged = true; 7718 invalidateParentIfNeeded(); 7719 } 7720 } 7721 7722 /** 7723 * The visual x position of this view, in pixels. This is equivalent to the 7724 * {@link #setTranslationX(float) translationX} property plus the current 7725 * {@link #getLeft() left} property. 7726 * 7727 * @return The visual x position of this view, in pixels. 7728 */ 7729 public float getX() { 7730 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 7731 } 7732 7733 /** 7734 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 7735 * {@link #setTranslationX(float) translationX} property to be the difference between 7736 * the x value passed in and the current {@link #getLeft() left} property. 7737 * 7738 * @param x The visual x position of this view, in pixels. 7739 */ 7740 public void setX(float x) { 7741 setTranslationX(x - mLeft); 7742 } 7743 7744 /** 7745 * The visual y position of this view, in pixels. This is equivalent to the 7746 * {@link #setTranslationY(float) translationY} property plus the current 7747 * {@link #getTop() top} property. 7748 * 7749 * @return The visual y position of this view, in pixels. 7750 */ 7751 public float getY() { 7752 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 7753 } 7754 7755 /** 7756 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 7757 * {@link #setTranslationY(float) translationY} property to be the difference between 7758 * the y value passed in and the current {@link #getTop() top} property. 7759 * 7760 * @param y The visual y position of this view, in pixels. 7761 */ 7762 public void setY(float y) { 7763 setTranslationY(y - mTop); 7764 } 7765 7766 7767 /** 7768 * The horizontal location of this view relative to its {@link #getLeft() left} position. 7769 * This position is post-layout, in addition to wherever the object's 7770 * layout placed it. 7771 * 7772 * @return The horizontal position of this view relative to its left position, in pixels. 7773 */ 7774 public float getTranslationX() { 7775 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 7776 } 7777 7778 /** 7779 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 7780 * This effectively positions the object post-layout, in addition to wherever the object's 7781 * layout placed it. 7782 * 7783 * @param translationX The horizontal position of this view relative to its left position, 7784 * in pixels. 7785 * 7786 * @attr ref android.R.styleable#View_translationX 7787 */ 7788 public void setTranslationX(float translationX) { 7789 ensureTransformationInfo(); 7790 final TransformationInfo info = mTransformationInfo; 7791 if (info.mTranslationX != translationX) { 7792 invalidateParentCaches(); 7793 // Double-invalidation is necessary to capture view's old and new areas 7794 invalidate(false); 7795 info.mTranslationX = translationX; 7796 info.mMatrixDirty = true; 7797 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7798 invalidate(false); 7799 } 7800 } 7801 7802 /** 7803 * The horizontal location of this view relative to its {@link #getTop() top} position. 7804 * This position is post-layout, in addition to wherever the object's 7805 * layout placed it. 7806 * 7807 * @return The vertical position of this view relative to its top position, 7808 * in pixels. 7809 */ 7810 public float getTranslationY() { 7811 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 7812 } 7813 7814 /** 7815 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 7816 * This effectively positions the object post-layout, in addition to wherever the object's 7817 * layout placed it. 7818 * 7819 * @param translationY The vertical position of this view relative to its top position, 7820 * in pixels. 7821 * 7822 * @attr ref android.R.styleable#View_translationY 7823 */ 7824 public void setTranslationY(float translationY) { 7825 ensureTransformationInfo(); 7826 final TransformationInfo info = mTransformationInfo; 7827 if (info.mTranslationY != translationY) { 7828 invalidateParentCaches(); 7829 // Double-invalidation is necessary to capture view's old and new areas 7830 invalidate(false); 7831 info.mTranslationY = translationY; 7832 info.mMatrixDirty = true; 7833 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7834 invalidate(false); 7835 } 7836 } 7837 7838 /** 7839 * @hide 7840 */ 7841 public void setFastTranslationX(float x) { 7842 ensureTransformationInfo(); 7843 final TransformationInfo info = mTransformationInfo; 7844 info.mTranslationX = x; 7845 info.mMatrixDirty = true; 7846 } 7847 7848 /** 7849 * @hide 7850 */ 7851 public void setFastTranslationY(float y) { 7852 ensureTransformationInfo(); 7853 final TransformationInfo info = mTransformationInfo; 7854 info.mTranslationY = y; 7855 info.mMatrixDirty = true; 7856 } 7857 7858 /** 7859 * @hide 7860 */ 7861 public void setFastX(float x) { 7862 ensureTransformationInfo(); 7863 final TransformationInfo info = mTransformationInfo; 7864 info.mTranslationX = x - mLeft; 7865 info.mMatrixDirty = true; 7866 } 7867 7868 /** 7869 * @hide 7870 */ 7871 public void setFastY(float y) { 7872 ensureTransformationInfo(); 7873 final TransformationInfo info = mTransformationInfo; 7874 info.mTranslationY = y - mTop; 7875 info.mMatrixDirty = true; 7876 } 7877 7878 /** 7879 * @hide 7880 */ 7881 public void setFastScaleX(float x) { 7882 ensureTransformationInfo(); 7883 final TransformationInfo info = mTransformationInfo; 7884 info.mScaleX = x; 7885 info.mMatrixDirty = true; 7886 } 7887 7888 /** 7889 * @hide 7890 */ 7891 public void setFastScaleY(float y) { 7892 ensureTransformationInfo(); 7893 final TransformationInfo info = mTransformationInfo; 7894 info.mScaleY = y; 7895 info.mMatrixDirty = true; 7896 } 7897 7898 /** 7899 * @hide 7900 */ 7901 public void setFastAlpha(float alpha) { 7902 ensureTransformationInfo(); 7903 mTransformationInfo.mAlpha = alpha; 7904 } 7905 7906 /** 7907 * @hide 7908 */ 7909 public void setFastRotationY(float y) { 7910 ensureTransformationInfo(); 7911 final TransformationInfo info = mTransformationInfo; 7912 info.mRotationY = y; 7913 info.mMatrixDirty = true; 7914 } 7915 7916 /** 7917 * Hit rectangle in parent's coordinates 7918 * 7919 * @param outRect The hit rectangle of the view. 7920 */ 7921 public void getHitRect(Rect outRect) { 7922 updateMatrix(); 7923 final TransformationInfo info = mTransformationInfo; 7924 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 7925 outRect.set(mLeft, mTop, mRight, mBottom); 7926 } else { 7927 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 7928 tmpRect.set(-info.mPivotX, -info.mPivotY, 7929 getWidth() - info.mPivotX, getHeight() - info.mPivotY); 7930 info.mMatrix.mapRect(tmpRect); 7931 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 7932 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 7933 } 7934 } 7935 7936 /** 7937 * Determines whether the given point, in local coordinates is inside the view. 7938 */ 7939 /*package*/ final boolean pointInView(float localX, float localY) { 7940 return localX >= 0 && localX < (mRight - mLeft) 7941 && localY >= 0 && localY < (mBottom - mTop); 7942 } 7943 7944 /** 7945 * Utility method to determine whether the given point, in local coordinates, 7946 * is inside the view, where the area of the view is expanded by the slop factor. 7947 * This method is called while processing touch-move events to determine if the event 7948 * is still within the view. 7949 */ 7950 private boolean pointInView(float localX, float localY, float slop) { 7951 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 7952 localY < ((mBottom - mTop) + slop); 7953 } 7954 7955 /** 7956 * When a view has focus and the user navigates away from it, the next view is searched for 7957 * starting from the rectangle filled in by this method. 7958 * 7959 * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)}) 7960 * of the view. However, if your view maintains some idea of internal selection, 7961 * such as a cursor, or a selected row or column, you should override this method and 7962 * fill in a more specific rectangle. 7963 * 7964 * @param r The rectangle to fill in, in this view's coordinates. 7965 */ 7966 public void getFocusedRect(Rect r) { 7967 getDrawingRect(r); 7968 } 7969 7970 /** 7971 * If some part of this view is not clipped by any of its parents, then 7972 * return that area in r in global (root) coordinates. To convert r to local 7973 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x, 7974 * -globalOffset.y)) If the view is completely clipped or translated out, 7975 * return false. 7976 * 7977 * @param r If true is returned, r holds the global coordinates of the 7978 * visible portion of this view. 7979 * @param globalOffset If true is returned, globalOffset holds the dx,dy 7980 * between this view and its root. globalOffet may be null. 7981 * @return true if r is non-empty (i.e. part of the view is visible at the 7982 * root level. 7983 */ 7984 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 7985 int width = mRight - mLeft; 7986 int height = mBottom - mTop; 7987 if (width > 0 && height > 0) { 7988 r.set(0, 0, width, height); 7989 if (globalOffset != null) { 7990 globalOffset.set(-mScrollX, -mScrollY); 7991 } 7992 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 7993 } 7994 return false; 7995 } 7996 7997 public final boolean getGlobalVisibleRect(Rect r) { 7998 return getGlobalVisibleRect(r, null); 7999 } 8000 8001 public final boolean getLocalVisibleRect(Rect r) { 8002 Point offset = new Point(); 8003 if (getGlobalVisibleRect(r, offset)) { 8004 r.offset(-offset.x, -offset.y); // make r local 8005 return true; 8006 } 8007 return false; 8008 } 8009 8010 /** 8011 * Offset this view's vertical location by the specified number of pixels. 8012 * 8013 * @param offset the number of pixels to offset the view by 8014 */ 8015 public void offsetTopAndBottom(int offset) { 8016 if (offset != 0) { 8017 updateMatrix(); 8018 final boolean matrixIsIdentity = mTransformationInfo == null 8019 || mTransformationInfo.mMatrixIsIdentity; 8020 if (matrixIsIdentity) { 8021 final ViewParent p = mParent; 8022 if (p != null && mAttachInfo != null) { 8023 final Rect r = mAttachInfo.mTmpInvalRect; 8024 int minTop; 8025 int maxBottom; 8026 int yLoc; 8027 if (offset < 0) { 8028 minTop = mTop + offset; 8029 maxBottom = mBottom; 8030 yLoc = offset; 8031 } else { 8032 minTop = mTop; 8033 maxBottom = mBottom + offset; 8034 yLoc = 0; 8035 } 8036 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 8037 p.invalidateChild(this, r); 8038 } 8039 } else { 8040 invalidate(false); 8041 } 8042 8043 mTop += offset; 8044 mBottom += offset; 8045 8046 if (!matrixIsIdentity) { 8047 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8048 invalidate(false); 8049 } 8050 invalidateParentIfNeeded(); 8051 } 8052 } 8053 8054 /** 8055 * Offset this view's horizontal location by the specified amount of pixels. 8056 * 8057 * @param offset the numer of pixels to offset the view by 8058 */ 8059 public void offsetLeftAndRight(int offset) { 8060 if (offset != 0) { 8061 updateMatrix(); 8062 final boolean matrixIsIdentity = mTransformationInfo == null 8063 || mTransformationInfo.mMatrixIsIdentity; 8064 if (matrixIsIdentity) { 8065 final ViewParent p = mParent; 8066 if (p != null && mAttachInfo != null) { 8067 final Rect r = mAttachInfo.mTmpInvalRect; 8068 int minLeft; 8069 int maxRight; 8070 if (offset < 0) { 8071 minLeft = mLeft + offset; 8072 maxRight = mRight; 8073 } else { 8074 minLeft = mLeft; 8075 maxRight = mRight + offset; 8076 } 8077 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 8078 p.invalidateChild(this, r); 8079 } 8080 } else { 8081 invalidate(false); 8082 } 8083 8084 mLeft += offset; 8085 mRight += offset; 8086 8087 if (!matrixIsIdentity) { 8088 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8089 invalidate(false); 8090 } 8091 invalidateParentIfNeeded(); 8092 } 8093 } 8094 8095 /** 8096 * Get the LayoutParams associated with this view. All views should have 8097 * layout parameters. These supply parameters to the <i>parent</i> of this 8098 * view specifying how it should be arranged. There are many subclasses of 8099 * ViewGroup.LayoutParams, and these correspond to the different subclasses 8100 * of ViewGroup that are responsible for arranging their children. 8101 * 8102 * This method may return null if this View is not attached to a parent 8103 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 8104 * was not invoked successfully. When a View is attached to a parent 8105 * ViewGroup, this method must not return null. 8106 * 8107 * @return The LayoutParams associated with this view, or null if no 8108 * parameters have been set yet 8109 */ 8110 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 8111 public ViewGroup.LayoutParams getLayoutParams() { 8112 return mLayoutParams; 8113 } 8114 8115 /** 8116 * Set the layout parameters associated with this view. These supply 8117 * parameters to the <i>parent</i> of this view specifying how it should be 8118 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 8119 * correspond to the different subclasses of ViewGroup that are responsible 8120 * for arranging their children. 8121 * 8122 * @param params The layout parameters for this view, cannot be null 8123 */ 8124 public void setLayoutParams(ViewGroup.LayoutParams params) { 8125 if (params == null) { 8126 throw new NullPointerException("Layout parameters cannot be null"); 8127 } 8128 mLayoutParams = params; 8129 requestLayout(); 8130 } 8131 8132 /** 8133 * Set the scrolled position of your view. This will cause a call to 8134 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8135 * invalidated. 8136 * @param x the x position to scroll to 8137 * @param y the y position to scroll to 8138 */ 8139 public void scrollTo(int x, int y) { 8140 if (mScrollX != x || mScrollY != y) { 8141 int oldX = mScrollX; 8142 int oldY = mScrollY; 8143 mScrollX = x; 8144 mScrollY = y; 8145 invalidateParentCaches(); 8146 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 8147 if (!awakenScrollBars()) { 8148 invalidate(true); 8149 } 8150 } 8151 } 8152 8153 /** 8154 * Move the scrolled position of your view. This will cause a call to 8155 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8156 * invalidated. 8157 * @param x the amount of pixels to scroll by horizontally 8158 * @param y the amount of pixels to scroll by vertically 8159 */ 8160 public void scrollBy(int x, int y) { 8161 scrollTo(mScrollX + x, mScrollY + y); 8162 } 8163 8164 /** 8165 * <p>Trigger the scrollbars to draw. When invoked this method starts an 8166 * animation to fade the scrollbars out after a default delay. If a subclass 8167 * provides animated scrolling, the start delay should equal the duration 8168 * of the scrolling animation.</p> 8169 * 8170 * <p>The animation starts only if at least one of the scrollbars is 8171 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 8172 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8173 * this method returns true, and false otherwise. If the animation is 8174 * started, this method calls {@link #invalidate()}; in that case the 8175 * caller should not call {@link #invalidate()}.</p> 8176 * 8177 * <p>This method should be invoked every time a subclass directly updates 8178 * the scroll parameters.</p> 8179 * 8180 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 8181 * and {@link #scrollTo(int, int)}.</p> 8182 * 8183 * @return true if the animation is played, false otherwise 8184 * 8185 * @see #awakenScrollBars(int) 8186 * @see #scrollBy(int, int) 8187 * @see #scrollTo(int, int) 8188 * @see #isHorizontalScrollBarEnabled() 8189 * @see #isVerticalScrollBarEnabled() 8190 * @see #setHorizontalScrollBarEnabled(boolean) 8191 * @see #setVerticalScrollBarEnabled(boolean) 8192 */ 8193 protected boolean awakenScrollBars() { 8194 return mScrollCache != null && 8195 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 8196 } 8197 8198 /** 8199 * Trigger the scrollbars to draw. 8200 * This method differs from awakenScrollBars() only in its default duration. 8201 * initialAwakenScrollBars() will show the scroll bars for longer than 8202 * usual to give the user more of a chance to notice them. 8203 * 8204 * @return true if the animation is played, false otherwise. 8205 */ 8206 private boolean initialAwakenScrollBars() { 8207 return mScrollCache != null && 8208 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 8209 } 8210 8211 /** 8212 * <p> 8213 * Trigger the scrollbars to draw. When invoked this method starts an 8214 * animation to fade the scrollbars out after a fixed delay. If a subclass 8215 * provides animated scrolling, the start delay should equal the duration of 8216 * the scrolling animation. 8217 * </p> 8218 * 8219 * <p> 8220 * The animation starts only if at least one of the scrollbars is enabled, 8221 * as specified by {@link #isHorizontalScrollBarEnabled()} and 8222 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8223 * this method returns true, and false otherwise. If the animation is 8224 * started, this method calls {@link #invalidate()}; in that case the caller 8225 * should not call {@link #invalidate()}. 8226 * </p> 8227 * 8228 * <p> 8229 * This method should be invoked everytime a subclass directly updates the 8230 * scroll parameters. 8231 * </p> 8232 * 8233 * @param startDelay the delay, in milliseconds, after which the animation 8234 * should start; when the delay is 0, the animation starts 8235 * immediately 8236 * @return true if the animation is played, false otherwise 8237 * 8238 * @see #scrollBy(int, int) 8239 * @see #scrollTo(int, int) 8240 * @see #isHorizontalScrollBarEnabled() 8241 * @see #isVerticalScrollBarEnabled() 8242 * @see #setHorizontalScrollBarEnabled(boolean) 8243 * @see #setVerticalScrollBarEnabled(boolean) 8244 */ 8245 protected boolean awakenScrollBars(int startDelay) { 8246 return awakenScrollBars(startDelay, true); 8247 } 8248 8249 /** 8250 * <p> 8251 * Trigger the scrollbars to draw. When invoked this method starts an 8252 * animation to fade the scrollbars out after a fixed delay. If a subclass 8253 * provides animated scrolling, the start delay should equal the duration of 8254 * the scrolling animation. 8255 * </p> 8256 * 8257 * <p> 8258 * The animation starts only if at least one of the scrollbars is enabled, 8259 * as specified by {@link #isHorizontalScrollBarEnabled()} and 8260 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8261 * this method returns true, and false otherwise. If the animation is 8262 * started, this method calls {@link #invalidate()} if the invalidate parameter 8263 * is set to true; in that case the caller 8264 * should not call {@link #invalidate()}. 8265 * </p> 8266 * 8267 * <p> 8268 * This method should be invoked everytime a subclass directly updates the 8269 * scroll parameters. 8270 * </p> 8271 * 8272 * @param startDelay the delay, in milliseconds, after which the animation 8273 * should start; when the delay is 0, the animation starts 8274 * immediately 8275 * 8276 * @param invalidate Wheter this method should call invalidate 8277 * 8278 * @return true if the animation is played, false otherwise 8279 * 8280 * @see #scrollBy(int, int) 8281 * @see #scrollTo(int, int) 8282 * @see #isHorizontalScrollBarEnabled() 8283 * @see #isVerticalScrollBarEnabled() 8284 * @see #setHorizontalScrollBarEnabled(boolean) 8285 * @see #setVerticalScrollBarEnabled(boolean) 8286 */ 8287 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 8288 final ScrollabilityCache scrollCache = mScrollCache; 8289 8290 if (scrollCache == null || !scrollCache.fadeScrollBars) { 8291 return false; 8292 } 8293 8294 if (scrollCache.scrollBar == null) { 8295 scrollCache.scrollBar = new ScrollBarDrawable(); 8296 } 8297 8298 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 8299 8300 if (invalidate) { 8301 // Invalidate to show the scrollbars 8302 invalidate(true); 8303 } 8304 8305 if (scrollCache.state == ScrollabilityCache.OFF) { 8306 // FIXME: this is copied from WindowManagerService. 8307 // We should get this value from the system when it 8308 // is possible to do so. 8309 final int KEY_REPEAT_FIRST_DELAY = 750; 8310 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 8311 } 8312 8313 // Tell mScrollCache when we should start fading. This may 8314 // extend the fade start time if one was already scheduled 8315 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 8316 scrollCache.fadeStartTime = fadeStartTime; 8317 scrollCache.state = ScrollabilityCache.ON; 8318 8319 // Schedule our fader to run, unscheduling any old ones first 8320 if (mAttachInfo != null) { 8321 mAttachInfo.mHandler.removeCallbacks(scrollCache); 8322 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 8323 } 8324 8325 return true; 8326 } 8327 8328 return false; 8329 } 8330 8331 /** 8332 * Do not invalidate views which are not visible and which are not running an animation. They 8333 * will not get drawn and they should not set dirty flags as if they will be drawn 8334 */ 8335 private boolean skipInvalidate() { 8336 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 8337 (!(mParent instanceof ViewGroup) || 8338 !((ViewGroup) mParent).isViewTransitioning(this)); 8339 } 8340 /** 8341 * Mark the the area defined by dirty as needing to be drawn. If the view is 8342 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 8343 * in the future. This must be called from a UI thread. To call from a non-UI 8344 * thread, call {@link #postInvalidate()}. 8345 * 8346 * WARNING: This method is destructive to dirty. 8347 * @param dirty the rectangle representing the bounds of the dirty region 8348 */ 8349 public void invalidate(Rect dirty) { 8350 if (ViewDebug.TRACE_HIERARCHY) { 8351 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8352 } 8353 8354 if (skipInvalidate()) { 8355 return; 8356 } 8357 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8358 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8359 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8360 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8361 mPrivateFlags |= INVALIDATED; 8362 mPrivateFlags |= DIRTY; 8363 final ViewParent p = mParent; 8364 final AttachInfo ai = mAttachInfo; 8365 //noinspection PointlessBooleanExpression,ConstantConditions 8366 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8367 if (p != null && ai != null && ai.mHardwareAccelerated) { 8368 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8369 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8370 p.invalidateChild(this, null); 8371 return; 8372 } 8373 } 8374 if (p != null && ai != null) { 8375 final int scrollX = mScrollX; 8376 final int scrollY = mScrollY; 8377 final Rect r = ai.mTmpInvalRect; 8378 r.set(dirty.left - scrollX, dirty.top - scrollY, 8379 dirty.right - scrollX, dirty.bottom - scrollY); 8380 mParent.invalidateChild(this, r); 8381 } 8382 } 8383 } 8384 8385 /** 8386 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn. 8387 * The coordinates of the dirty rect are relative to the view. 8388 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 8389 * will be called at some point in the future. This must be called from 8390 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 8391 * @param l the left position of the dirty region 8392 * @param t the top position of the dirty region 8393 * @param r the right position of the dirty region 8394 * @param b the bottom position of the dirty region 8395 */ 8396 public void invalidate(int l, int t, int r, int b) { 8397 if (ViewDebug.TRACE_HIERARCHY) { 8398 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8399 } 8400 8401 if (skipInvalidate()) { 8402 return; 8403 } 8404 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8405 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8406 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8407 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8408 mPrivateFlags |= INVALIDATED; 8409 mPrivateFlags |= DIRTY; 8410 final ViewParent p = mParent; 8411 final AttachInfo ai = mAttachInfo; 8412 //noinspection PointlessBooleanExpression,ConstantConditions 8413 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8414 if (p != null && ai != null && ai.mHardwareAccelerated) { 8415 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8416 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8417 p.invalidateChild(this, null); 8418 return; 8419 } 8420 } 8421 if (p != null && ai != null && l < r && t < b) { 8422 final int scrollX = mScrollX; 8423 final int scrollY = mScrollY; 8424 final Rect tmpr = ai.mTmpInvalRect; 8425 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 8426 p.invalidateChild(this, tmpr); 8427 } 8428 } 8429 } 8430 8431 /** 8432 * Invalidate the whole view. If the view is visible, 8433 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 8434 * the future. This must be called from a UI thread. To call from a non-UI thread, 8435 * call {@link #postInvalidate()}. 8436 */ 8437 public void invalidate() { 8438 invalidate(true); 8439 } 8440 8441 /** 8442 * This is where the invalidate() work actually happens. A full invalidate() 8443 * causes the drawing cache to be invalidated, but this function can be called with 8444 * invalidateCache set to false to skip that invalidation step for cases that do not 8445 * need it (for example, a component that remains at the same dimensions with the same 8446 * content). 8447 * 8448 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 8449 * well. This is usually true for a full invalidate, but may be set to false if the 8450 * View's contents or dimensions have not changed. 8451 */ 8452 void invalidate(boolean invalidateCache) { 8453 if (ViewDebug.TRACE_HIERARCHY) { 8454 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8455 } 8456 8457 if (skipInvalidate()) { 8458 return; 8459 } 8460 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8461 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) || 8462 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) { 8463 mLastIsOpaque = isOpaque(); 8464 mPrivateFlags &= ~DRAWN; 8465 mPrivateFlags |= DIRTY; 8466 if (invalidateCache) { 8467 mPrivateFlags |= INVALIDATED; 8468 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8469 } 8470 final AttachInfo ai = mAttachInfo; 8471 final ViewParent p = mParent; 8472 //noinspection PointlessBooleanExpression,ConstantConditions 8473 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8474 if (p != null && ai != null && ai.mHardwareAccelerated) { 8475 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8476 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8477 p.invalidateChild(this, null); 8478 return; 8479 } 8480 } 8481 8482 if (p != null && ai != null) { 8483 final Rect r = ai.mTmpInvalRect; 8484 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8485 // Don't call invalidate -- we don't want to internally scroll 8486 // our own bounds 8487 p.invalidateChild(this, r); 8488 } 8489 } 8490 } 8491 8492 /** 8493 * @hide 8494 */ 8495 public void fastInvalidate() { 8496 if (skipInvalidate()) { 8497 return; 8498 } 8499 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8500 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8501 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8502 if (mParent instanceof View) { 8503 ((View) mParent).mPrivateFlags |= INVALIDATED; 8504 } 8505 mPrivateFlags &= ~DRAWN; 8506 mPrivateFlags |= DIRTY; 8507 mPrivateFlags |= INVALIDATED; 8508 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8509 if (mParent != null && mAttachInfo != null) { 8510 if (mAttachInfo.mHardwareAccelerated) { 8511 mParent.invalidateChild(this, null); 8512 } else { 8513 final Rect r = mAttachInfo.mTmpInvalRect; 8514 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8515 // Don't call invalidate -- we don't want to internally scroll 8516 // our own bounds 8517 mParent.invalidateChild(this, r); 8518 } 8519 } 8520 } 8521 } 8522 8523 /** 8524 * Used to indicate that the parent of this view should clear its caches. This functionality 8525 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8526 * which is necessary when various parent-managed properties of the view change, such as 8527 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 8528 * clears the parent caches and does not causes an invalidate event. 8529 * 8530 * @hide 8531 */ 8532 protected void invalidateParentCaches() { 8533 if (mParent instanceof View) { 8534 ((View) mParent).mPrivateFlags |= INVALIDATED; 8535 } 8536 } 8537 8538 /** 8539 * Used to indicate that the parent of this view should be invalidated. This functionality 8540 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8541 * which is necessary when various parent-managed properties of the view change, such as 8542 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 8543 * an invalidation event to the parent. 8544 * 8545 * @hide 8546 */ 8547 protected void invalidateParentIfNeeded() { 8548 if (isHardwareAccelerated() && mParent instanceof View) { 8549 ((View) mParent).invalidate(true); 8550 } 8551 } 8552 8553 /** 8554 * Indicates whether this View is opaque. An opaque View guarantees that it will 8555 * draw all the pixels overlapping its bounds using a fully opaque color. 8556 * 8557 * Subclasses of View should override this method whenever possible to indicate 8558 * whether an instance is opaque. Opaque Views are treated in a special way by 8559 * the View hierarchy, possibly allowing it to perform optimizations during 8560 * invalidate/draw passes. 8561 * 8562 * @return True if this View is guaranteed to be fully opaque, false otherwise. 8563 */ 8564 @ViewDebug.ExportedProperty(category = "drawing") 8565 public boolean isOpaque() { 8566 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK && 8567 ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1) 8568 >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD); 8569 } 8570 8571 /** 8572 * @hide 8573 */ 8574 protected void computeOpaqueFlags() { 8575 // Opaque if: 8576 // - Has a background 8577 // - Background is opaque 8578 // - Doesn't have scrollbars or scrollbars are inside overlay 8579 8580 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) { 8581 mPrivateFlags |= OPAQUE_BACKGROUND; 8582 } else { 8583 mPrivateFlags &= ~OPAQUE_BACKGROUND; 8584 } 8585 8586 final int flags = mViewFlags; 8587 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 8588 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 8589 mPrivateFlags |= OPAQUE_SCROLLBARS; 8590 } else { 8591 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 8592 } 8593 } 8594 8595 /** 8596 * @hide 8597 */ 8598 protected boolean hasOpaqueScrollbars() { 8599 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 8600 } 8601 8602 /** 8603 * @return A handler associated with the thread running the View. This 8604 * handler can be used to pump events in the UI events queue. 8605 */ 8606 public Handler getHandler() { 8607 if (mAttachInfo != null) { 8608 return mAttachInfo.mHandler; 8609 } 8610 return null; 8611 } 8612 8613 /** 8614 * <p>Causes the Runnable to be added to the message queue. 8615 * The runnable will be run on the user interface thread.</p> 8616 * 8617 * <p>This method can be invoked from outside of the UI thread 8618 * only when this View is attached to a window.</p> 8619 * 8620 * @param action The Runnable that will be executed. 8621 * 8622 * @return Returns true if the Runnable was successfully placed in to the 8623 * message queue. Returns false on failure, usually because the 8624 * looper processing the message queue is exiting. 8625 */ 8626 public boolean post(Runnable action) { 8627 Handler handler; 8628 AttachInfo attachInfo = mAttachInfo; 8629 if (attachInfo != null) { 8630 handler = attachInfo.mHandler; 8631 } else { 8632 // Assume that post will succeed later 8633 ViewRootImpl.getRunQueue().post(action); 8634 return true; 8635 } 8636 8637 return handler.post(action); 8638 } 8639 8640 /** 8641 * <p>Causes the Runnable to be added to the message queue, to be run 8642 * after the specified amount of time elapses. 8643 * The runnable will be run on the user interface thread.</p> 8644 * 8645 * <p>This method can be invoked from outside of the UI thread 8646 * only when this View is attached to a window.</p> 8647 * 8648 * @param action The Runnable that will be executed. 8649 * @param delayMillis The delay (in milliseconds) until the Runnable 8650 * will be executed. 8651 * 8652 * @return true if the Runnable was successfully placed in to the 8653 * message queue. Returns false on failure, usually because the 8654 * looper processing the message queue is exiting. Note that a 8655 * result of true does not mean the Runnable will be processed -- 8656 * if the looper is quit before the delivery time of the message 8657 * occurs then the message will be dropped. 8658 */ 8659 public boolean postDelayed(Runnable action, long delayMillis) { 8660 Handler handler; 8661 AttachInfo attachInfo = mAttachInfo; 8662 if (attachInfo != null) { 8663 handler = attachInfo.mHandler; 8664 } else { 8665 // Assume that post will succeed later 8666 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 8667 return true; 8668 } 8669 8670 return handler.postDelayed(action, delayMillis); 8671 } 8672 8673 /** 8674 * <p>Removes the specified Runnable from the message queue.</p> 8675 * 8676 * <p>This method can be invoked from outside of the UI thread 8677 * only when this View is attached to a window.</p> 8678 * 8679 * @param action The Runnable to remove from the message handling queue 8680 * 8681 * @return true if this view could ask the Handler to remove the Runnable, 8682 * false otherwise. When the returned value is true, the Runnable 8683 * may or may not have been actually removed from the message queue 8684 * (for instance, if the Runnable was not in the queue already.) 8685 */ 8686 public boolean removeCallbacks(Runnable action) { 8687 Handler handler; 8688 AttachInfo attachInfo = mAttachInfo; 8689 if (attachInfo != null) { 8690 handler = attachInfo.mHandler; 8691 } else { 8692 // Assume that post will succeed later 8693 ViewRootImpl.getRunQueue().removeCallbacks(action); 8694 return true; 8695 } 8696 8697 handler.removeCallbacks(action); 8698 return true; 8699 } 8700 8701 /** 8702 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 8703 * Use this to invalidate the View from a non-UI thread.</p> 8704 * 8705 * <p>This method can be invoked from outside of the UI thread 8706 * only when this View is attached to a window.</p> 8707 * 8708 * @see #invalidate() 8709 */ 8710 public void postInvalidate() { 8711 postInvalidateDelayed(0); 8712 } 8713 8714 /** 8715 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 8716 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 8717 * 8718 * <p>This method can be invoked from outside of the UI thread 8719 * only when this View is attached to a window.</p> 8720 * 8721 * @param left The left coordinate of the rectangle to invalidate. 8722 * @param top The top coordinate of the rectangle to invalidate. 8723 * @param right The right coordinate of the rectangle to invalidate. 8724 * @param bottom The bottom coordinate of the rectangle to invalidate. 8725 * 8726 * @see #invalidate(int, int, int, int) 8727 * @see #invalidate(Rect) 8728 */ 8729 public void postInvalidate(int left, int top, int right, int bottom) { 8730 postInvalidateDelayed(0, left, top, right, bottom); 8731 } 8732 8733 /** 8734 * <p>Cause an invalidate to happen on a subsequent cycle through the event 8735 * loop. Waits for the specified amount of time.</p> 8736 * 8737 * <p>This method can be invoked from outside of the UI thread 8738 * only when this View is attached to a window.</p> 8739 * 8740 * @param delayMilliseconds the duration in milliseconds to delay the 8741 * invalidation by 8742 */ 8743 public void postInvalidateDelayed(long delayMilliseconds) { 8744 // We try only with the AttachInfo because there's no point in invalidating 8745 // if we are not attached to our window 8746 AttachInfo attachInfo = mAttachInfo; 8747 if (attachInfo != null) { 8748 Message msg = Message.obtain(); 8749 msg.what = AttachInfo.INVALIDATE_MSG; 8750 msg.obj = this; 8751 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8752 } 8753 } 8754 8755 /** 8756 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 8757 * through the event loop. Waits for the specified amount of time.</p> 8758 * 8759 * <p>This method can be invoked from outside of the UI thread 8760 * only when this View is attached to a window.</p> 8761 * 8762 * @param delayMilliseconds the duration in milliseconds to delay the 8763 * invalidation by 8764 * @param left The left coordinate of the rectangle to invalidate. 8765 * @param top The top coordinate of the rectangle to invalidate. 8766 * @param right The right coordinate of the rectangle to invalidate. 8767 * @param bottom The bottom coordinate of the rectangle to invalidate. 8768 */ 8769 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 8770 int right, int bottom) { 8771 8772 // We try only with the AttachInfo because there's no point in invalidating 8773 // if we are not attached to our window 8774 AttachInfo attachInfo = mAttachInfo; 8775 if (attachInfo != null) { 8776 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 8777 info.target = this; 8778 info.left = left; 8779 info.top = top; 8780 info.right = right; 8781 info.bottom = bottom; 8782 8783 final Message msg = Message.obtain(); 8784 msg.what = AttachInfo.INVALIDATE_RECT_MSG; 8785 msg.obj = info; 8786 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8787 } 8788 } 8789 8790 /** 8791 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 8792 * This event is sent at most once every 8793 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 8794 */ 8795 private void postSendViewScrolledAccessibilityEventCallback() { 8796 if (mSendViewScrolledAccessibilityEvent == null) { 8797 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 8798 } 8799 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 8800 mSendViewScrolledAccessibilityEvent.mIsPending = true; 8801 postDelayed(mSendViewScrolledAccessibilityEvent, 8802 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 8803 } 8804 } 8805 8806 /** 8807 * Called by a parent to request that a child update its values for mScrollX 8808 * and mScrollY if necessary. This will typically be done if the child is 8809 * animating a scroll using a {@link android.widget.Scroller Scroller} 8810 * object. 8811 */ 8812 public void computeScroll() { 8813 } 8814 8815 /** 8816 * <p>Indicate whether the horizontal edges are faded when the view is 8817 * scrolled horizontally.</p> 8818 * 8819 * @return true if the horizontal edges should are faded on scroll, false 8820 * otherwise 8821 * 8822 * @see #setHorizontalFadingEdgeEnabled(boolean) 8823 * @attr ref android.R.styleable#View_requiresFadingEdge 8824 */ 8825 public boolean isHorizontalFadingEdgeEnabled() { 8826 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 8827 } 8828 8829 /** 8830 * <p>Define whether the horizontal edges should be faded when this view 8831 * is scrolled horizontally.</p> 8832 * 8833 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 8834 * be faded when the view is scrolled 8835 * horizontally 8836 * 8837 * @see #isHorizontalFadingEdgeEnabled() 8838 * @attr ref android.R.styleable#View_requiresFadingEdge 8839 */ 8840 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 8841 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 8842 if (horizontalFadingEdgeEnabled) { 8843 initScrollCache(); 8844 } 8845 8846 mViewFlags ^= FADING_EDGE_HORIZONTAL; 8847 } 8848 } 8849 8850 /** 8851 * <p>Indicate whether the vertical edges are faded when the view is 8852 * scrolled horizontally.</p> 8853 * 8854 * @return true if the vertical edges should are faded on scroll, false 8855 * otherwise 8856 * 8857 * @see #setVerticalFadingEdgeEnabled(boolean) 8858 * @attr ref android.R.styleable#View_requiresFadingEdge 8859 */ 8860 public boolean isVerticalFadingEdgeEnabled() { 8861 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 8862 } 8863 8864 /** 8865 * <p>Define whether the vertical edges should be faded when this view 8866 * is scrolled vertically.</p> 8867 * 8868 * @param verticalFadingEdgeEnabled true if the vertical edges should 8869 * be faded when the view is scrolled 8870 * vertically 8871 * 8872 * @see #isVerticalFadingEdgeEnabled() 8873 * @attr ref android.R.styleable#View_requiresFadingEdge 8874 */ 8875 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 8876 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 8877 if (verticalFadingEdgeEnabled) { 8878 initScrollCache(); 8879 } 8880 8881 mViewFlags ^= FADING_EDGE_VERTICAL; 8882 } 8883 } 8884 8885 /** 8886 * Returns the strength, or intensity, of the top faded edge. The strength is 8887 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8888 * returns 0.0 or 1.0 but no value in between. 8889 * 8890 * Subclasses should override this method to provide a smoother fade transition 8891 * when scrolling occurs. 8892 * 8893 * @return the intensity of the top fade as a float between 0.0f and 1.0f 8894 */ 8895 protected float getTopFadingEdgeStrength() { 8896 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 8897 } 8898 8899 /** 8900 * Returns the strength, or intensity, of the bottom faded edge. The strength is 8901 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8902 * returns 0.0 or 1.0 but no value in between. 8903 * 8904 * Subclasses should override this method to provide a smoother fade transition 8905 * when scrolling occurs. 8906 * 8907 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 8908 */ 8909 protected float getBottomFadingEdgeStrength() { 8910 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 8911 computeVerticalScrollRange() ? 1.0f : 0.0f; 8912 } 8913 8914 /** 8915 * Returns the strength, or intensity, of the left faded edge. The strength is 8916 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8917 * returns 0.0 or 1.0 but no value in between. 8918 * 8919 * Subclasses should override this method to provide a smoother fade transition 8920 * when scrolling occurs. 8921 * 8922 * @return the intensity of the left fade as a float between 0.0f and 1.0f 8923 */ 8924 protected float getLeftFadingEdgeStrength() { 8925 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 8926 } 8927 8928 /** 8929 * Returns the strength, or intensity, of the right faded edge. The strength is 8930 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8931 * returns 0.0 or 1.0 but no value in between. 8932 * 8933 * Subclasses should override this method to provide a smoother fade transition 8934 * when scrolling occurs. 8935 * 8936 * @return the intensity of the right fade as a float between 0.0f and 1.0f 8937 */ 8938 protected float getRightFadingEdgeStrength() { 8939 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 8940 computeHorizontalScrollRange() ? 1.0f : 0.0f; 8941 } 8942 8943 /** 8944 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 8945 * scrollbar is not drawn by default.</p> 8946 * 8947 * @return true if the horizontal scrollbar should be painted, false 8948 * otherwise 8949 * 8950 * @see #setHorizontalScrollBarEnabled(boolean) 8951 */ 8952 public boolean isHorizontalScrollBarEnabled() { 8953 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 8954 } 8955 8956 /** 8957 * <p>Define whether the horizontal scrollbar should be drawn or not. The 8958 * scrollbar is not drawn by default.</p> 8959 * 8960 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 8961 * be painted 8962 * 8963 * @see #isHorizontalScrollBarEnabled() 8964 */ 8965 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 8966 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 8967 mViewFlags ^= SCROLLBARS_HORIZONTAL; 8968 computeOpaqueFlags(); 8969 resolvePadding(); 8970 } 8971 } 8972 8973 /** 8974 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 8975 * scrollbar is not drawn by default.</p> 8976 * 8977 * @return true if the vertical scrollbar should be painted, false 8978 * otherwise 8979 * 8980 * @see #setVerticalScrollBarEnabled(boolean) 8981 */ 8982 public boolean isVerticalScrollBarEnabled() { 8983 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 8984 } 8985 8986 /** 8987 * <p>Define whether the vertical scrollbar should be drawn or not. The 8988 * scrollbar is not drawn by default.</p> 8989 * 8990 * @param verticalScrollBarEnabled true if the vertical scrollbar should 8991 * be painted 8992 * 8993 * @see #isVerticalScrollBarEnabled() 8994 */ 8995 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 8996 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 8997 mViewFlags ^= SCROLLBARS_VERTICAL; 8998 computeOpaqueFlags(); 8999 resolvePadding(); 9000 } 9001 } 9002 9003 /** 9004 * @hide 9005 */ 9006 protected void recomputePadding() { 9007 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 9008 } 9009 9010 /** 9011 * Define whether scrollbars will fade when the view is not scrolling. 9012 * 9013 * @param fadeScrollbars wheter to enable fading 9014 * 9015 */ 9016 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 9017 initScrollCache(); 9018 final ScrollabilityCache scrollabilityCache = mScrollCache; 9019 scrollabilityCache.fadeScrollBars = fadeScrollbars; 9020 if (fadeScrollbars) { 9021 scrollabilityCache.state = ScrollabilityCache.OFF; 9022 } else { 9023 scrollabilityCache.state = ScrollabilityCache.ON; 9024 } 9025 } 9026 9027 /** 9028 * 9029 * Returns true if scrollbars will fade when this view is not scrolling 9030 * 9031 * @return true if scrollbar fading is enabled 9032 */ 9033 public boolean isScrollbarFadingEnabled() { 9034 return mScrollCache != null && mScrollCache.fadeScrollBars; 9035 } 9036 9037 /** 9038 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 9039 * inset. When inset, they add to the padding of the view. And the scrollbars 9040 * can be drawn inside the padding area or on the edge of the view. For example, 9041 * if a view has a background drawable and you want to draw the scrollbars 9042 * inside the padding specified by the drawable, you can use 9043 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 9044 * appear at the edge of the view, ignoring the padding, then you can use 9045 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 9046 * @param style the style of the scrollbars. Should be one of 9047 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 9048 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 9049 * @see #SCROLLBARS_INSIDE_OVERLAY 9050 * @see #SCROLLBARS_INSIDE_INSET 9051 * @see #SCROLLBARS_OUTSIDE_OVERLAY 9052 * @see #SCROLLBARS_OUTSIDE_INSET 9053 */ 9054 public void setScrollBarStyle(int style) { 9055 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 9056 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 9057 computeOpaqueFlags(); 9058 resolvePadding(); 9059 } 9060 } 9061 9062 /** 9063 * <p>Returns the current scrollbar style.</p> 9064 * @return the current scrollbar style 9065 * @see #SCROLLBARS_INSIDE_OVERLAY 9066 * @see #SCROLLBARS_INSIDE_INSET 9067 * @see #SCROLLBARS_OUTSIDE_OVERLAY 9068 * @see #SCROLLBARS_OUTSIDE_INSET 9069 */ 9070 @ViewDebug.ExportedProperty(mapping = { 9071 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 9072 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 9073 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 9074 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 9075 }) 9076 public int getScrollBarStyle() { 9077 return mViewFlags & SCROLLBARS_STYLE_MASK; 9078 } 9079 9080 /** 9081 * <p>Compute the horizontal range that the horizontal scrollbar 9082 * represents.</p> 9083 * 9084 * <p>The range is expressed in arbitrary units that must be the same as the 9085 * units used by {@link #computeHorizontalScrollExtent()} and 9086 * {@link #computeHorizontalScrollOffset()}.</p> 9087 * 9088 * <p>The default range is the drawing width of this view.</p> 9089 * 9090 * @return the total horizontal range represented by the horizontal 9091 * scrollbar 9092 * 9093 * @see #computeHorizontalScrollExtent() 9094 * @see #computeHorizontalScrollOffset() 9095 * @see android.widget.ScrollBarDrawable 9096 */ 9097 protected int computeHorizontalScrollRange() { 9098 return getWidth(); 9099 } 9100 9101 /** 9102 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 9103 * within the horizontal range. This value is used to compute the position 9104 * of the thumb within the scrollbar's track.</p> 9105 * 9106 * <p>The range is expressed in arbitrary units that must be the same as the 9107 * units used by {@link #computeHorizontalScrollRange()} and 9108 * {@link #computeHorizontalScrollExtent()}.</p> 9109 * 9110 * <p>The default offset is the scroll offset of this view.</p> 9111 * 9112 * @return the horizontal offset of the scrollbar's thumb 9113 * 9114 * @see #computeHorizontalScrollRange() 9115 * @see #computeHorizontalScrollExtent() 9116 * @see android.widget.ScrollBarDrawable 9117 */ 9118 protected int computeHorizontalScrollOffset() { 9119 return mScrollX; 9120 } 9121 9122 /** 9123 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 9124 * within the horizontal range. This value is used to compute the length 9125 * of the thumb within the scrollbar's track.</p> 9126 * 9127 * <p>The range is expressed in arbitrary units that must be the same as the 9128 * units used by {@link #computeHorizontalScrollRange()} and 9129 * {@link #computeHorizontalScrollOffset()}.</p> 9130 * 9131 * <p>The default extent is the drawing width of this view.</p> 9132 * 9133 * @return the horizontal extent of the scrollbar's thumb 9134 * 9135 * @see #computeHorizontalScrollRange() 9136 * @see #computeHorizontalScrollOffset() 9137 * @see android.widget.ScrollBarDrawable 9138 */ 9139 protected int computeHorizontalScrollExtent() { 9140 return getWidth(); 9141 } 9142 9143 /** 9144 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 9145 * 9146 * <p>The range is expressed in arbitrary units that must be the same as the 9147 * units used by {@link #computeVerticalScrollExtent()} and 9148 * {@link #computeVerticalScrollOffset()}.</p> 9149 * 9150 * @return the total vertical range represented by the vertical scrollbar 9151 * 9152 * <p>The default range is the drawing height of this view.</p> 9153 * 9154 * @see #computeVerticalScrollExtent() 9155 * @see #computeVerticalScrollOffset() 9156 * @see android.widget.ScrollBarDrawable 9157 */ 9158 protected int computeVerticalScrollRange() { 9159 return getHeight(); 9160 } 9161 9162 /** 9163 * <p>Compute the vertical offset of the vertical scrollbar's thumb 9164 * within the horizontal range. This value is used to compute the position 9165 * of the thumb within the scrollbar's track.</p> 9166 * 9167 * <p>The range is expressed in arbitrary units that must be the same as the 9168 * units used by {@link #computeVerticalScrollRange()} and 9169 * {@link #computeVerticalScrollExtent()}.</p> 9170 * 9171 * <p>The default offset is the scroll offset of this view.</p> 9172 * 9173 * @return the vertical offset of the scrollbar's thumb 9174 * 9175 * @see #computeVerticalScrollRange() 9176 * @see #computeVerticalScrollExtent() 9177 * @see android.widget.ScrollBarDrawable 9178 */ 9179 protected int computeVerticalScrollOffset() { 9180 return mScrollY; 9181 } 9182 9183 /** 9184 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 9185 * within the vertical range. This value is used to compute the length 9186 * of the thumb within the scrollbar's track.</p> 9187 * 9188 * <p>The range is expressed in arbitrary units that must be the same as the 9189 * units used by {@link #computeVerticalScrollRange()} and 9190 * {@link #computeVerticalScrollOffset()}.</p> 9191 * 9192 * <p>The default extent is the drawing height of this view.</p> 9193 * 9194 * @return the vertical extent of the scrollbar's thumb 9195 * 9196 * @see #computeVerticalScrollRange() 9197 * @see #computeVerticalScrollOffset() 9198 * @see android.widget.ScrollBarDrawable 9199 */ 9200 protected int computeVerticalScrollExtent() { 9201 return getHeight(); 9202 } 9203 9204 /** 9205 * Check if this view can be scrolled horizontally in a certain direction. 9206 * 9207 * @param direction Negative to check scrolling left, positive to check scrolling right. 9208 * @return true if this view can be scrolled in the specified direction, false otherwise. 9209 */ 9210 public boolean canScrollHorizontally(int direction) { 9211 final int offset = computeHorizontalScrollOffset(); 9212 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 9213 if (range == 0) return false; 9214 if (direction < 0) { 9215 return offset > 0; 9216 } else { 9217 return offset < range - 1; 9218 } 9219 } 9220 9221 /** 9222 * Check if this view can be scrolled vertically in a certain direction. 9223 * 9224 * @param direction Negative to check scrolling up, positive to check scrolling down. 9225 * @return true if this view can be scrolled in the specified direction, false otherwise. 9226 */ 9227 public boolean canScrollVertically(int direction) { 9228 final int offset = computeVerticalScrollOffset(); 9229 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 9230 if (range == 0) return false; 9231 if (direction < 0) { 9232 return offset > 0; 9233 } else { 9234 return offset < range - 1; 9235 } 9236 } 9237 9238 /** 9239 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 9240 * scrollbars are painted only if they have been awakened first.</p> 9241 * 9242 * @param canvas the canvas on which to draw the scrollbars 9243 * 9244 * @see #awakenScrollBars(int) 9245 */ 9246 protected final void onDrawScrollBars(Canvas canvas) { 9247 // scrollbars are drawn only when the animation is running 9248 final ScrollabilityCache cache = mScrollCache; 9249 if (cache != null) { 9250 9251 int state = cache.state; 9252 9253 if (state == ScrollabilityCache.OFF) { 9254 return; 9255 } 9256 9257 boolean invalidate = false; 9258 9259 if (state == ScrollabilityCache.FADING) { 9260 // We're fading -- get our fade interpolation 9261 if (cache.interpolatorValues == null) { 9262 cache.interpolatorValues = new float[1]; 9263 } 9264 9265 float[] values = cache.interpolatorValues; 9266 9267 // Stops the animation if we're done 9268 if (cache.scrollBarInterpolator.timeToValues(values) == 9269 Interpolator.Result.FREEZE_END) { 9270 cache.state = ScrollabilityCache.OFF; 9271 } else { 9272 cache.scrollBar.setAlpha(Math.round(values[0])); 9273 } 9274 9275 // This will make the scroll bars inval themselves after 9276 // drawing. We only want this when we're fading so that 9277 // we prevent excessive redraws 9278 invalidate = true; 9279 } else { 9280 // We're just on -- but we may have been fading before so 9281 // reset alpha 9282 cache.scrollBar.setAlpha(255); 9283 } 9284 9285 9286 final int viewFlags = mViewFlags; 9287 9288 final boolean drawHorizontalScrollBar = 9289 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 9290 final boolean drawVerticalScrollBar = 9291 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 9292 && !isVerticalScrollBarHidden(); 9293 9294 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 9295 final int width = mRight - mLeft; 9296 final int height = mBottom - mTop; 9297 9298 final ScrollBarDrawable scrollBar = cache.scrollBar; 9299 9300 final int scrollX = mScrollX; 9301 final int scrollY = mScrollY; 9302 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 9303 9304 int left, top, right, bottom; 9305 9306 if (drawHorizontalScrollBar) { 9307 int size = scrollBar.getSize(false); 9308 if (size <= 0) { 9309 size = cache.scrollBarSize; 9310 } 9311 9312 scrollBar.setParameters(computeHorizontalScrollRange(), 9313 computeHorizontalScrollOffset(), 9314 computeHorizontalScrollExtent(), false); 9315 final int verticalScrollBarGap = drawVerticalScrollBar ? 9316 getVerticalScrollbarWidth() : 0; 9317 top = scrollY + height - size - (mUserPaddingBottom & inside); 9318 left = scrollX + (mPaddingLeft & inside); 9319 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 9320 bottom = top + size; 9321 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 9322 if (invalidate) { 9323 invalidate(left, top, right, bottom); 9324 } 9325 } 9326 9327 if (drawVerticalScrollBar) { 9328 int size = scrollBar.getSize(true); 9329 if (size <= 0) { 9330 size = cache.scrollBarSize; 9331 } 9332 9333 scrollBar.setParameters(computeVerticalScrollRange(), 9334 computeVerticalScrollOffset(), 9335 computeVerticalScrollExtent(), true); 9336 switch (mVerticalScrollbarPosition) { 9337 default: 9338 case SCROLLBAR_POSITION_DEFAULT: 9339 case SCROLLBAR_POSITION_RIGHT: 9340 left = scrollX + width - size - (mUserPaddingRight & inside); 9341 break; 9342 case SCROLLBAR_POSITION_LEFT: 9343 left = scrollX + (mUserPaddingLeft & inside); 9344 break; 9345 } 9346 top = scrollY + (mPaddingTop & inside); 9347 right = left + size; 9348 bottom = scrollY + height - (mUserPaddingBottom & inside); 9349 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 9350 if (invalidate) { 9351 invalidate(left, top, right, bottom); 9352 } 9353 } 9354 } 9355 } 9356 } 9357 9358 /** 9359 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 9360 * FastScroller is visible. 9361 * @return whether to temporarily hide the vertical scrollbar 9362 * @hide 9363 */ 9364 protected boolean isVerticalScrollBarHidden() { 9365 return false; 9366 } 9367 9368 /** 9369 * <p>Draw the horizontal scrollbar if 9370 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 9371 * 9372 * @param canvas the canvas on which to draw the scrollbar 9373 * @param scrollBar the scrollbar's drawable 9374 * 9375 * @see #isHorizontalScrollBarEnabled() 9376 * @see #computeHorizontalScrollRange() 9377 * @see #computeHorizontalScrollExtent() 9378 * @see #computeHorizontalScrollOffset() 9379 * @see android.widget.ScrollBarDrawable 9380 * @hide 9381 */ 9382 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 9383 int l, int t, int r, int b) { 9384 scrollBar.setBounds(l, t, r, b); 9385 scrollBar.draw(canvas); 9386 } 9387 9388 /** 9389 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 9390 * returns true.</p> 9391 * 9392 * @param canvas the canvas on which to draw the scrollbar 9393 * @param scrollBar the scrollbar's drawable 9394 * 9395 * @see #isVerticalScrollBarEnabled() 9396 * @see #computeVerticalScrollRange() 9397 * @see #computeVerticalScrollExtent() 9398 * @see #computeVerticalScrollOffset() 9399 * @see android.widget.ScrollBarDrawable 9400 * @hide 9401 */ 9402 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 9403 int l, int t, int r, int b) { 9404 scrollBar.setBounds(l, t, r, b); 9405 scrollBar.draw(canvas); 9406 } 9407 9408 /** 9409 * Implement this to do your drawing. 9410 * 9411 * @param canvas the canvas on which the background will be drawn 9412 */ 9413 protected void onDraw(Canvas canvas) { 9414 } 9415 9416 /* 9417 * Caller is responsible for calling requestLayout if necessary. 9418 * (This allows addViewInLayout to not request a new layout.) 9419 */ 9420 void assignParent(ViewParent parent) { 9421 if (mParent == null) { 9422 mParent = parent; 9423 } else if (parent == null) { 9424 mParent = null; 9425 } else { 9426 throw new RuntimeException("view " + this + " being added, but" 9427 + " it already has a parent"); 9428 } 9429 } 9430 9431 /** 9432 * This is called when the view is attached to a window. At this point it 9433 * has a Surface and will start drawing. Note that this function is 9434 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 9435 * however it may be called any time before the first onDraw -- including 9436 * before or after {@link #onMeasure(int, int)}. 9437 * 9438 * @see #onDetachedFromWindow() 9439 */ 9440 protected void onAttachedToWindow() { 9441 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 9442 mParent.requestTransparentRegion(this); 9443 } 9444 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 9445 initialAwakenScrollBars(); 9446 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH; 9447 } 9448 jumpDrawablesToCurrentState(); 9449 // Order is important here: LayoutDirection MUST be resolved before Padding 9450 // and TextDirection 9451 resolveLayoutDirectionIfNeeded(); 9452 resolvePadding(); 9453 resolveTextDirection(); 9454 if (isFocused()) { 9455 InputMethodManager imm = InputMethodManager.peekInstance(); 9456 imm.focusIn(this); 9457 } 9458 } 9459 9460 /** 9461 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 9462 * that the parent directionality can and will be resolved before its children. 9463 */ 9464 private void resolveLayoutDirectionIfNeeded() { 9465 // Do not resolve if it is not needed 9466 if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return; 9467 9468 // Clear any previous layout direction resolution 9469 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL; 9470 9471 // Reset also TextDirection as a change into LayoutDirection may impact the selected 9472 // TextDirectionHeuristic 9473 resetResolvedTextDirection(); 9474 9475 // Set resolved depending on layout direction 9476 switch (getLayoutDirection()) { 9477 case LAYOUT_DIRECTION_INHERIT: 9478 // We cannot do the resolution if there is no parent 9479 if (mParent == null) return; 9480 9481 // If this is root view, no need to look at parent's layout dir. 9482 if (mParent instanceof ViewGroup) { 9483 ViewGroup viewGroup = ((ViewGroup) mParent); 9484 9485 // Check if the parent view group can resolve 9486 if (! viewGroup.canResolveLayoutDirection()) { 9487 return; 9488 } 9489 if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 9490 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9491 } 9492 } 9493 break; 9494 case LAYOUT_DIRECTION_RTL: 9495 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9496 break; 9497 case LAYOUT_DIRECTION_LOCALE: 9498 if(isLayoutDirectionRtl(Locale.getDefault())) { 9499 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9500 } 9501 break; 9502 default: 9503 // Nothing to do, LTR by default 9504 } 9505 9506 // Set to resolved 9507 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED; 9508 } 9509 9510 /** 9511 * @hide 9512 */ 9513 protected void resolvePadding() { 9514 // If the user specified the absolute padding (either with android:padding or 9515 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 9516 // use the default padding or the padding from the background drawable 9517 // (stored at this point in mPadding*) 9518 switch (getResolvedLayoutDirection()) { 9519 case LAYOUT_DIRECTION_RTL: 9520 // Start user padding override Right user padding. Otherwise, if Right user 9521 // padding is not defined, use the default Right padding. If Right user padding 9522 // is defined, just use it. 9523 if (mUserPaddingStart >= 0) { 9524 mUserPaddingRight = mUserPaddingStart; 9525 } else if (mUserPaddingRight < 0) { 9526 mUserPaddingRight = mPaddingRight; 9527 } 9528 if (mUserPaddingEnd >= 0) { 9529 mUserPaddingLeft = mUserPaddingEnd; 9530 } else if (mUserPaddingLeft < 0) { 9531 mUserPaddingLeft = mPaddingLeft; 9532 } 9533 break; 9534 case LAYOUT_DIRECTION_LTR: 9535 default: 9536 // Start user padding override Left user padding. Otherwise, if Left user 9537 // padding is not defined, use the default left padding. If Left user padding 9538 // is defined, just use it. 9539 if (mUserPaddingStart >= 0) { 9540 mUserPaddingLeft = mUserPaddingStart; 9541 } else if (mUserPaddingLeft < 0) { 9542 mUserPaddingLeft = mPaddingLeft; 9543 } 9544 if (mUserPaddingEnd >= 0) { 9545 mUserPaddingRight = mUserPaddingEnd; 9546 } else if (mUserPaddingRight < 0) { 9547 mUserPaddingRight = mPaddingRight; 9548 } 9549 } 9550 9551 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 9552 9553 recomputePadding(); 9554 } 9555 9556 /** 9557 * Return true if layout direction resolution can be done 9558 * 9559 * @hide 9560 */ 9561 protected boolean canResolveLayoutDirection() { 9562 switch (getLayoutDirection()) { 9563 case LAYOUT_DIRECTION_INHERIT: 9564 return (mParent != null); 9565 default: 9566 return true; 9567 } 9568 } 9569 9570 /** 9571 * Reset the resolved layout direction. 9572 * 9573 * Subclasses need to override this method to clear cached information that depends on the 9574 * resolved layout direction, or to inform child views that inherit their layout direction. 9575 * Overrides must also call the superclass implementation at the start of their implementation. 9576 * 9577 * @hide 9578 */ 9579 protected void resetResolvedLayoutDirection() { 9580 // Reset the current View resolution 9581 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED; 9582 } 9583 9584 /** 9585 * Check if a Locale is corresponding to a RTL script. 9586 * 9587 * @param locale Locale to check 9588 * @return true if a Locale is corresponding to a RTL script. 9589 * 9590 * @hide 9591 */ 9592 protected static boolean isLayoutDirectionRtl(Locale locale) { 9593 return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE == 9594 LocaleUtil.getLayoutDirectionFromLocale(locale)); 9595 } 9596 9597 /** 9598 * This is called when the view is detached from a window. At this point it 9599 * no longer has a surface for drawing. 9600 * 9601 * @see #onAttachedToWindow() 9602 */ 9603 protected void onDetachedFromWindow() { 9604 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 9605 9606 removeUnsetPressCallback(); 9607 removeLongPressCallback(); 9608 removePerformClickCallback(); 9609 removeSendViewScrolledAccessibilityEventCallback(); 9610 9611 destroyDrawingCache(); 9612 9613 destroyLayer(); 9614 9615 if (mDisplayList != null) { 9616 mDisplayList.invalidate(); 9617 } 9618 9619 if (mAttachInfo != null) { 9620 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this); 9621 } 9622 9623 mCurrentAnimation = null; 9624 9625 resetResolvedLayoutDirection(); 9626 resetResolvedTextDirection(); 9627 } 9628 9629 /** 9630 * @return The number of times this view has been attached to a window 9631 */ 9632 protected int getWindowAttachCount() { 9633 return mWindowAttachCount; 9634 } 9635 9636 /** 9637 * Retrieve a unique token identifying the window this view is attached to. 9638 * @return Return the window's token for use in 9639 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 9640 */ 9641 public IBinder getWindowToken() { 9642 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 9643 } 9644 9645 /** 9646 * Retrieve a unique token identifying the top-level "real" window of 9647 * the window that this view is attached to. That is, this is like 9648 * {@link #getWindowToken}, except if the window this view in is a panel 9649 * window (attached to another containing window), then the token of 9650 * the containing window is returned instead. 9651 * 9652 * @return Returns the associated window token, either 9653 * {@link #getWindowToken()} or the containing window's token. 9654 */ 9655 public IBinder getApplicationWindowToken() { 9656 AttachInfo ai = mAttachInfo; 9657 if (ai != null) { 9658 IBinder appWindowToken = ai.mPanelParentWindowToken; 9659 if (appWindowToken == null) { 9660 appWindowToken = ai.mWindowToken; 9661 } 9662 return appWindowToken; 9663 } 9664 return null; 9665 } 9666 9667 /** 9668 * Retrieve private session object this view hierarchy is using to 9669 * communicate with the window manager. 9670 * @return the session object to communicate with the window manager 9671 */ 9672 /*package*/ IWindowSession getWindowSession() { 9673 return mAttachInfo != null ? mAttachInfo.mSession : null; 9674 } 9675 9676 /** 9677 * @param info the {@link android.view.View.AttachInfo} to associated with 9678 * this view 9679 */ 9680 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 9681 //System.out.println("Attached! " + this); 9682 mAttachInfo = info; 9683 mWindowAttachCount++; 9684 // We will need to evaluate the drawable state at least once. 9685 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 9686 if (mFloatingTreeObserver != null) { 9687 info.mTreeObserver.merge(mFloatingTreeObserver); 9688 mFloatingTreeObserver = null; 9689 } 9690 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 9691 mAttachInfo.mScrollContainers.add(this); 9692 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 9693 } 9694 performCollectViewAttributes(visibility); 9695 onAttachedToWindow(); 9696 9697 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9698 mOnAttachStateChangeListeners; 9699 if (listeners != null && listeners.size() > 0) { 9700 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9701 // perform the dispatching. The iterator is a safe guard against listeners that 9702 // could mutate the list by calling the various add/remove methods. This prevents 9703 // the array from being modified while we iterate it. 9704 for (OnAttachStateChangeListener listener : listeners) { 9705 listener.onViewAttachedToWindow(this); 9706 } 9707 } 9708 9709 int vis = info.mWindowVisibility; 9710 if (vis != GONE) { 9711 onWindowVisibilityChanged(vis); 9712 } 9713 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 9714 // If nobody has evaluated the drawable state yet, then do it now. 9715 refreshDrawableState(); 9716 } 9717 } 9718 9719 void dispatchDetachedFromWindow() { 9720 AttachInfo info = mAttachInfo; 9721 if (info != null) { 9722 int vis = info.mWindowVisibility; 9723 if (vis != GONE) { 9724 onWindowVisibilityChanged(GONE); 9725 } 9726 } 9727 9728 onDetachedFromWindow(); 9729 9730 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9731 mOnAttachStateChangeListeners; 9732 if (listeners != null && listeners.size() > 0) { 9733 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9734 // perform the dispatching. The iterator is a safe guard against listeners that 9735 // could mutate the list by calling the various add/remove methods. This prevents 9736 // the array from being modified while we iterate it. 9737 for (OnAttachStateChangeListener listener : listeners) { 9738 listener.onViewDetachedFromWindow(this); 9739 } 9740 } 9741 9742 if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) { 9743 mAttachInfo.mScrollContainers.remove(this); 9744 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 9745 } 9746 9747 mAttachInfo = null; 9748 } 9749 9750 /** 9751 * Store this view hierarchy's frozen state into the given container. 9752 * 9753 * @param container The SparseArray in which to save the view's state. 9754 * 9755 * @see #restoreHierarchyState(android.util.SparseArray) 9756 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9757 * @see #onSaveInstanceState() 9758 */ 9759 public void saveHierarchyState(SparseArray<Parcelable> container) { 9760 dispatchSaveInstanceState(container); 9761 } 9762 9763 /** 9764 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 9765 * this view and its children. May be overridden to modify how freezing happens to a 9766 * view's children; for example, some views may want to not store state for their children. 9767 * 9768 * @param container The SparseArray in which to save the view's state. 9769 * 9770 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9771 * @see #saveHierarchyState(android.util.SparseArray) 9772 * @see #onSaveInstanceState() 9773 */ 9774 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 9775 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 9776 mPrivateFlags &= ~SAVE_STATE_CALLED; 9777 Parcelable state = onSaveInstanceState(); 9778 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9779 throw new IllegalStateException( 9780 "Derived class did not call super.onSaveInstanceState()"); 9781 } 9782 if (state != null) { 9783 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 9784 // + ": " + state); 9785 container.put(mID, state); 9786 } 9787 } 9788 } 9789 9790 /** 9791 * Hook allowing a view to generate a representation of its internal state 9792 * that can later be used to create a new instance with that same state. 9793 * This state should only contain information that is not persistent or can 9794 * not be reconstructed later. For example, you will never store your 9795 * current position on screen because that will be computed again when a 9796 * new instance of the view is placed in its view hierarchy. 9797 * <p> 9798 * Some examples of things you may store here: the current cursor position 9799 * in a text view (but usually not the text itself since that is stored in a 9800 * content provider or other persistent storage), the currently selected 9801 * item in a list view. 9802 * 9803 * @return Returns a Parcelable object containing the view's current dynamic 9804 * state, or null if there is nothing interesting to save. The 9805 * default implementation returns null. 9806 * @see #onRestoreInstanceState(android.os.Parcelable) 9807 * @see #saveHierarchyState(android.util.SparseArray) 9808 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9809 * @see #setSaveEnabled(boolean) 9810 */ 9811 protected Parcelable onSaveInstanceState() { 9812 mPrivateFlags |= SAVE_STATE_CALLED; 9813 return BaseSavedState.EMPTY_STATE; 9814 } 9815 9816 /** 9817 * Restore this view hierarchy's frozen state from the given container. 9818 * 9819 * @param container The SparseArray which holds previously frozen states. 9820 * 9821 * @see #saveHierarchyState(android.util.SparseArray) 9822 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9823 * @see #onRestoreInstanceState(android.os.Parcelable) 9824 */ 9825 public void restoreHierarchyState(SparseArray<Parcelable> container) { 9826 dispatchRestoreInstanceState(container); 9827 } 9828 9829 /** 9830 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 9831 * state for this view and its children. May be overridden to modify how restoring 9832 * happens to a view's children; for example, some views may want to not store state 9833 * for their children. 9834 * 9835 * @param container The SparseArray which holds previously saved state. 9836 * 9837 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9838 * @see #restoreHierarchyState(android.util.SparseArray) 9839 * @see #onRestoreInstanceState(android.os.Parcelable) 9840 */ 9841 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 9842 if (mID != NO_ID) { 9843 Parcelable state = container.get(mID); 9844 if (state != null) { 9845 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 9846 // + ": " + state); 9847 mPrivateFlags &= ~SAVE_STATE_CALLED; 9848 onRestoreInstanceState(state); 9849 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9850 throw new IllegalStateException( 9851 "Derived class did not call super.onRestoreInstanceState()"); 9852 } 9853 } 9854 } 9855 } 9856 9857 /** 9858 * Hook allowing a view to re-apply a representation of its internal state that had previously 9859 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 9860 * null state. 9861 * 9862 * @param state The frozen state that had previously been returned by 9863 * {@link #onSaveInstanceState}. 9864 * 9865 * @see #onSaveInstanceState() 9866 * @see #restoreHierarchyState(android.util.SparseArray) 9867 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9868 */ 9869 protected void onRestoreInstanceState(Parcelable state) { 9870 mPrivateFlags |= SAVE_STATE_CALLED; 9871 if (state != BaseSavedState.EMPTY_STATE && state != null) { 9872 throw new IllegalArgumentException("Wrong state class, expecting View State but " 9873 + "received " + state.getClass().toString() + " instead. This usually happens " 9874 + "when two views of different type have the same id in the same hierarchy. " 9875 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 9876 + "other views do not use the same id."); 9877 } 9878 } 9879 9880 /** 9881 * <p>Return the time at which the drawing of the view hierarchy started.</p> 9882 * 9883 * @return the drawing start time in milliseconds 9884 */ 9885 public long getDrawingTime() { 9886 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 9887 } 9888 9889 /** 9890 * <p>Enables or disables the duplication of the parent's state into this view. When 9891 * duplication is enabled, this view gets its drawable state from its parent rather 9892 * than from its own internal properties.</p> 9893 * 9894 * <p>Note: in the current implementation, setting this property to true after the 9895 * view was added to a ViewGroup might have no effect at all. This property should 9896 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 9897 * 9898 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 9899 * property is enabled, an exception will be thrown.</p> 9900 * 9901 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 9902 * parent, these states should not be affected by this method.</p> 9903 * 9904 * @param enabled True to enable duplication of the parent's drawable state, false 9905 * to disable it. 9906 * 9907 * @see #getDrawableState() 9908 * @see #isDuplicateParentStateEnabled() 9909 */ 9910 public void setDuplicateParentStateEnabled(boolean enabled) { 9911 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 9912 } 9913 9914 /** 9915 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 9916 * 9917 * @return True if this view's drawable state is duplicated from the parent, 9918 * false otherwise 9919 * 9920 * @see #getDrawableState() 9921 * @see #setDuplicateParentStateEnabled(boolean) 9922 */ 9923 public boolean isDuplicateParentStateEnabled() { 9924 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 9925 } 9926 9927 /** 9928 * <p>Specifies the type of layer backing this view. The layer can be 9929 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 9930 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 9931 * 9932 * <p>A layer is associated with an optional {@link android.graphics.Paint} 9933 * instance that controls how the layer is composed on screen. The following 9934 * properties of the paint are taken into account when composing the layer:</p> 9935 * <ul> 9936 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 9937 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 9938 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 9939 * </ul> 9940 * 9941 * <p>If this view has an alpha value set to < 1.0 by calling 9942 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 9943 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 9944 * equivalent to setting a hardware layer on this view and providing a paint with 9945 * the desired alpha value.<p> 9946 * 9947 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 9948 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 9949 * for more information on when and how to use layers.</p> 9950 * 9951 * @param layerType The ype of layer to use with this view, must be one of 9952 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 9953 * {@link #LAYER_TYPE_HARDWARE} 9954 * @param paint The paint used to compose the layer. This argument is optional 9955 * and can be null. It is ignored when the layer type is 9956 * {@link #LAYER_TYPE_NONE} 9957 * 9958 * @see #getLayerType() 9959 * @see #LAYER_TYPE_NONE 9960 * @see #LAYER_TYPE_SOFTWARE 9961 * @see #LAYER_TYPE_HARDWARE 9962 * @see #setAlpha(float) 9963 * 9964 * @attr ref android.R.styleable#View_layerType 9965 */ 9966 public void setLayerType(int layerType, Paint paint) { 9967 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 9968 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 9969 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 9970 } 9971 9972 if (layerType == mLayerType) { 9973 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 9974 mLayerPaint = paint == null ? new Paint() : paint; 9975 invalidateParentCaches(); 9976 invalidate(true); 9977 } 9978 return; 9979 } 9980 9981 // Destroy any previous software drawing cache if needed 9982 switch (mLayerType) { 9983 case LAYER_TYPE_HARDWARE: 9984 destroyLayer(); 9985 // fall through - unaccelerated views may use software layer mechanism instead 9986 case LAYER_TYPE_SOFTWARE: 9987 destroyDrawingCache(); 9988 break; 9989 default: 9990 break; 9991 } 9992 9993 mLayerType = layerType; 9994 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 9995 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 9996 mLocalDirtyRect = layerDisabled ? null : new Rect(); 9997 9998 invalidateParentCaches(); 9999 invalidate(true); 10000 } 10001 10002 /** 10003 * Indicates what type of layer is currently associated with this view. By default 10004 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 10005 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 10006 * for more information on the different types of layers. 10007 * 10008 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 10009 * {@link #LAYER_TYPE_HARDWARE} 10010 * 10011 * @see #setLayerType(int, android.graphics.Paint) 10012 * @see #buildLayer() 10013 * @see #LAYER_TYPE_NONE 10014 * @see #LAYER_TYPE_SOFTWARE 10015 * @see #LAYER_TYPE_HARDWARE 10016 */ 10017 public int getLayerType() { 10018 return mLayerType; 10019 } 10020 10021 /** 10022 * Forces this view's layer to be created and this view to be rendered 10023 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 10024 * invoking this method will have no effect. 10025 * 10026 * This method can for instance be used to render a view into its layer before 10027 * starting an animation. If this view is complex, rendering into the layer 10028 * before starting the animation will avoid skipping frames. 10029 * 10030 * @throws IllegalStateException If this view is not attached to a window 10031 * 10032 * @see #setLayerType(int, android.graphics.Paint) 10033 */ 10034 public void buildLayer() { 10035 if (mLayerType == LAYER_TYPE_NONE) return; 10036 10037 if (mAttachInfo == null) { 10038 throw new IllegalStateException("This view must be attached to a window first"); 10039 } 10040 10041 switch (mLayerType) { 10042 case LAYER_TYPE_HARDWARE: 10043 getHardwareLayer(); 10044 break; 10045 case LAYER_TYPE_SOFTWARE: 10046 buildDrawingCache(true); 10047 break; 10048 } 10049 } 10050 10051 /** 10052 * <p>Returns a hardware layer that can be used to draw this view again 10053 * without executing its draw method.</p> 10054 * 10055 * @return A HardwareLayer ready to render, or null if an error occurred. 10056 */ 10057 HardwareLayer getHardwareLayer() { 10058 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 10059 !mAttachInfo.mHardwareRenderer.isEnabled()) { 10060 return null; 10061 } 10062 10063 final int width = mRight - mLeft; 10064 final int height = mBottom - mTop; 10065 10066 if (width == 0 || height == 0) { 10067 return null; 10068 } 10069 10070 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 10071 if (mHardwareLayer == null) { 10072 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 10073 width, height, isOpaque()); 10074 mLocalDirtyRect.setEmpty(); 10075 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 10076 mHardwareLayer.resize(width, height); 10077 mLocalDirtyRect.setEmpty(); 10078 } 10079 10080 HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas; 10081 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas); 10082 mAttachInfo.mHardwareCanvas = canvas; 10083 try { 10084 canvas.setViewport(width, height); 10085 canvas.onPreDraw(mLocalDirtyRect); 10086 mLocalDirtyRect.setEmpty(); 10087 10088 final int restoreCount = canvas.save(); 10089 10090 computeScroll(); 10091 canvas.translate(-mScrollX, -mScrollY); 10092 10093 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10094 10095 // Fast path for layouts with no backgrounds 10096 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10097 mPrivateFlags &= ~DIRTY_MASK; 10098 dispatchDraw(canvas); 10099 } else { 10100 draw(canvas); 10101 } 10102 10103 canvas.restoreToCount(restoreCount); 10104 } finally { 10105 canvas.onPostDraw(); 10106 mHardwareLayer.end(currentCanvas); 10107 mAttachInfo.mHardwareCanvas = currentCanvas; 10108 } 10109 } 10110 10111 return mHardwareLayer; 10112 } 10113 10114 boolean destroyLayer() { 10115 if (mHardwareLayer != null) { 10116 mHardwareLayer.destroy(); 10117 mHardwareLayer = null; 10118 return true; 10119 } 10120 return false; 10121 } 10122 10123 /** 10124 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 10125 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 10126 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 10127 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 10128 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 10129 * null.</p> 10130 * 10131 * <p>Enabling the drawing cache is similar to 10132 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 10133 * acceleration is turned off. When hardware acceleration is turned on, enabling the 10134 * drawing cache has no effect on rendering because the system uses a different mechanism 10135 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 10136 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 10137 * for information on how to enable software and hardware layers.</p> 10138 * 10139 * <p>This API can be used to manually generate 10140 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 10141 * {@link #getDrawingCache()}.</p> 10142 * 10143 * @param enabled true to enable the drawing cache, false otherwise 10144 * 10145 * @see #isDrawingCacheEnabled() 10146 * @see #getDrawingCache() 10147 * @see #buildDrawingCache() 10148 * @see #setLayerType(int, android.graphics.Paint) 10149 */ 10150 public void setDrawingCacheEnabled(boolean enabled) { 10151 mCachingFailed = false; 10152 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 10153 } 10154 10155 /** 10156 * <p>Indicates whether the drawing cache is enabled for this view.</p> 10157 * 10158 * @return true if the drawing cache is enabled 10159 * 10160 * @see #setDrawingCacheEnabled(boolean) 10161 * @see #getDrawingCache() 10162 */ 10163 @ViewDebug.ExportedProperty(category = "drawing") 10164 public boolean isDrawingCacheEnabled() { 10165 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 10166 } 10167 10168 /** 10169 * Debugging utility which recursively outputs the dirty state of a view and its 10170 * descendants. 10171 * 10172 * @hide 10173 */ 10174 @SuppressWarnings({"UnusedDeclaration"}) 10175 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 10176 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) + 10177 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" + 10178 (mPrivateFlags & View.DRAWING_CACHE_VALID) + 10179 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")"); 10180 if (clear) { 10181 mPrivateFlags &= clearMask; 10182 } 10183 if (this instanceof ViewGroup) { 10184 ViewGroup parent = (ViewGroup) this; 10185 final int count = parent.getChildCount(); 10186 for (int i = 0; i < count; i++) { 10187 final View child = parent.getChildAt(i); 10188 child.outputDirtyFlags(indent + " ", clear, clearMask); 10189 } 10190 } 10191 } 10192 10193 /** 10194 * This method is used by ViewGroup to cause its children to restore or recreate their 10195 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 10196 * to recreate its own display list, which would happen if it went through the normal 10197 * draw/dispatchDraw mechanisms. 10198 * 10199 * @hide 10200 */ 10201 protected void dispatchGetDisplayList() {} 10202 10203 /** 10204 * A view that is not attached or hardware accelerated cannot create a display list. 10205 * This method checks these conditions and returns the appropriate result. 10206 * 10207 * @return true if view has the ability to create a display list, false otherwise. 10208 * 10209 * @hide 10210 */ 10211 public boolean canHaveDisplayList() { 10212 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 10213 } 10214 10215 /** 10216 * <p>Returns a display list that can be used to draw this view again 10217 * without executing its draw method.</p> 10218 * 10219 * @return A DisplayList ready to replay, or null if caching is not enabled. 10220 * 10221 * @hide 10222 */ 10223 public DisplayList getDisplayList() { 10224 if (!canHaveDisplayList()) { 10225 return null; 10226 } 10227 10228 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || 10229 mDisplayList == null || !mDisplayList.isValid() || 10230 mRecreateDisplayList)) { 10231 // Don't need to recreate the display list, just need to tell our 10232 // children to restore/recreate theirs 10233 if (mDisplayList != null && mDisplayList.isValid() && 10234 !mRecreateDisplayList) { 10235 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10236 mPrivateFlags &= ~DIRTY_MASK; 10237 dispatchGetDisplayList(); 10238 10239 return mDisplayList; 10240 } 10241 10242 // If we got here, we're recreating it. Mark it as such to ensure that 10243 // we copy in child display lists into ours in drawChild() 10244 mRecreateDisplayList = true; 10245 if (mDisplayList == null) { 10246 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(); 10247 // If we're creating a new display list, make sure our parent gets invalidated 10248 // since they will need to recreate their display list to account for this 10249 // new child display list. 10250 invalidateParentCaches(); 10251 } 10252 10253 final HardwareCanvas canvas = mDisplayList.start(); 10254 int restoreCount = 0; 10255 try { 10256 int width = mRight - mLeft; 10257 int height = mBottom - mTop; 10258 10259 canvas.setViewport(width, height); 10260 // The dirty rect should always be null for a display list 10261 canvas.onPreDraw(null); 10262 10263 computeScroll(); 10264 10265 restoreCount = canvas.save(); 10266 canvas.translate(-mScrollX, -mScrollY); 10267 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10268 mPrivateFlags &= ~DIRTY_MASK; 10269 10270 // Fast path for layouts with no backgrounds 10271 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10272 dispatchDraw(canvas); 10273 } else { 10274 draw(canvas); 10275 } 10276 } finally { 10277 canvas.restoreToCount(restoreCount); 10278 canvas.onPostDraw(); 10279 10280 mDisplayList.end(); 10281 } 10282 } else { 10283 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10284 mPrivateFlags &= ~DIRTY_MASK; 10285 } 10286 10287 return mDisplayList; 10288 } 10289 10290 /** 10291 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 10292 * 10293 * @return A non-scaled bitmap representing this view or null if cache is disabled. 10294 * 10295 * @see #getDrawingCache(boolean) 10296 */ 10297 public Bitmap getDrawingCache() { 10298 return getDrawingCache(false); 10299 } 10300 10301 /** 10302 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 10303 * is null when caching is disabled. If caching is enabled and the cache is not ready, 10304 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 10305 * draw from the cache when the cache is enabled. To benefit from the cache, you must 10306 * request the drawing cache by calling this method and draw it on screen if the 10307 * returned bitmap is not null.</p> 10308 * 10309 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10310 * this method will create a bitmap of the same size as this view. Because this bitmap 10311 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10312 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10313 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10314 * size than the view. This implies that your application must be able to handle this 10315 * size.</p> 10316 * 10317 * @param autoScale Indicates whether the generated bitmap should be scaled based on 10318 * the current density of the screen when the application is in compatibility 10319 * mode. 10320 * 10321 * @return A bitmap representing this view or null if cache is disabled. 10322 * 10323 * @see #setDrawingCacheEnabled(boolean) 10324 * @see #isDrawingCacheEnabled() 10325 * @see #buildDrawingCache(boolean) 10326 * @see #destroyDrawingCache() 10327 */ 10328 public Bitmap getDrawingCache(boolean autoScale) { 10329 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 10330 return null; 10331 } 10332 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 10333 buildDrawingCache(autoScale); 10334 } 10335 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 10336 } 10337 10338 /** 10339 * <p>Frees the resources used by the drawing cache. If you call 10340 * {@link #buildDrawingCache()} manually without calling 10341 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10342 * should cleanup the cache with this method afterwards.</p> 10343 * 10344 * @see #setDrawingCacheEnabled(boolean) 10345 * @see #buildDrawingCache() 10346 * @see #getDrawingCache() 10347 */ 10348 public void destroyDrawingCache() { 10349 if (mDrawingCache != null) { 10350 mDrawingCache.recycle(); 10351 mDrawingCache = null; 10352 } 10353 if (mUnscaledDrawingCache != null) { 10354 mUnscaledDrawingCache.recycle(); 10355 mUnscaledDrawingCache = null; 10356 } 10357 } 10358 10359 /** 10360 * Setting a solid background color for the drawing cache's bitmaps will improve 10361 * performance and memory usage. Note, though that this should only be used if this 10362 * view will always be drawn on top of a solid color. 10363 * 10364 * @param color The background color to use for the drawing cache's bitmap 10365 * 10366 * @see #setDrawingCacheEnabled(boolean) 10367 * @see #buildDrawingCache() 10368 * @see #getDrawingCache() 10369 */ 10370 public void setDrawingCacheBackgroundColor(int color) { 10371 if (color != mDrawingCacheBackgroundColor) { 10372 mDrawingCacheBackgroundColor = color; 10373 mPrivateFlags &= ~DRAWING_CACHE_VALID; 10374 } 10375 } 10376 10377 /** 10378 * @see #setDrawingCacheBackgroundColor(int) 10379 * 10380 * @return The background color to used for the drawing cache's bitmap 10381 */ 10382 public int getDrawingCacheBackgroundColor() { 10383 return mDrawingCacheBackgroundColor; 10384 } 10385 10386 /** 10387 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 10388 * 10389 * @see #buildDrawingCache(boolean) 10390 */ 10391 public void buildDrawingCache() { 10392 buildDrawingCache(false); 10393 } 10394 10395 /** 10396 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 10397 * 10398 * <p>If you call {@link #buildDrawingCache()} manually without calling 10399 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10400 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 10401 * 10402 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10403 * this method will create a bitmap of the same size as this view. Because this bitmap 10404 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10405 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10406 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10407 * size than the view. This implies that your application must be able to handle this 10408 * size.</p> 10409 * 10410 * <p>You should avoid calling this method when hardware acceleration is enabled. If 10411 * you do not need the drawing cache bitmap, calling this method will increase memory 10412 * usage and cause the view to be rendered in software once, thus negatively impacting 10413 * performance.</p> 10414 * 10415 * @see #getDrawingCache() 10416 * @see #destroyDrawingCache() 10417 */ 10418 public void buildDrawingCache(boolean autoScale) { 10419 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 10420 mDrawingCache == null : mUnscaledDrawingCache == null)) { 10421 mCachingFailed = false; 10422 10423 if (ViewDebug.TRACE_HIERARCHY) { 10424 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 10425 } 10426 10427 int width = mRight - mLeft; 10428 int height = mBottom - mTop; 10429 10430 final AttachInfo attachInfo = mAttachInfo; 10431 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 10432 10433 if (autoScale && scalingRequired) { 10434 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 10435 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 10436 } 10437 10438 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 10439 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 10440 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 10441 10442 if (width <= 0 || height <= 0 || 10443 // Projected bitmap size in bytes 10444 (width * height * (opaque && !use32BitCache ? 2 : 4) > 10445 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 10446 destroyDrawingCache(); 10447 mCachingFailed = true; 10448 return; 10449 } 10450 10451 boolean clear = true; 10452 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 10453 10454 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 10455 Bitmap.Config quality; 10456 if (!opaque) { 10457 // Never pick ARGB_4444 because it looks awful 10458 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 10459 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 10460 case DRAWING_CACHE_QUALITY_AUTO: 10461 quality = Bitmap.Config.ARGB_8888; 10462 break; 10463 case DRAWING_CACHE_QUALITY_LOW: 10464 quality = Bitmap.Config.ARGB_8888; 10465 break; 10466 case DRAWING_CACHE_QUALITY_HIGH: 10467 quality = Bitmap.Config.ARGB_8888; 10468 break; 10469 default: 10470 quality = Bitmap.Config.ARGB_8888; 10471 break; 10472 } 10473 } else { 10474 // Optimization for translucent windows 10475 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 10476 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 10477 } 10478 10479 // Try to cleanup memory 10480 if (bitmap != null) bitmap.recycle(); 10481 10482 try { 10483 bitmap = Bitmap.createBitmap(width, height, quality); 10484 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 10485 if (autoScale) { 10486 mDrawingCache = bitmap; 10487 } else { 10488 mUnscaledDrawingCache = bitmap; 10489 } 10490 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 10491 } catch (OutOfMemoryError e) { 10492 // If there is not enough memory to create the bitmap cache, just 10493 // ignore the issue as bitmap caches are not required to draw the 10494 // view hierarchy 10495 if (autoScale) { 10496 mDrawingCache = null; 10497 } else { 10498 mUnscaledDrawingCache = null; 10499 } 10500 mCachingFailed = true; 10501 return; 10502 } 10503 10504 clear = drawingCacheBackgroundColor != 0; 10505 } 10506 10507 Canvas canvas; 10508 if (attachInfo != null) { 10509 canvas = attachInfo.mCanvas; 10510 if (canvas == null) { 10511 canvas = new Canvas(); 10512 } 10513 canvas.setBitmap(bitmap); 10514 // Temporarily clobber the cached Canvas in case one of our children 10515 // is also using a drawing cache. Without this, the children would 10516 // steal the canvas by attaching their own bitmap to it and bad, bad 10517 // thing would happen (invisible views, corrupted drawings, etc.) 10518 attachInfo.mCanvas = null; 10519 } else { 10520 // This case should hopefully never or seldom happen 10521 canvas = new Canvas(bitmap); 10522 } 10523 10524 if (clear) { 10525 bitmap.eraseColor(drawingCacheBackgroundColor); 10526 } 10527 10528 computeScroll(); 10529 final int restoreCount = canvas.save(); 10530 10531 if (autoScale && scalingRequired) { 10532 final float scale = attachInfo.mApplicationScale; 10533 canvas.scale(scale, scale); 10534 } 10535 10536 canvas.translate(-mScrollX, -mScrollY); 10537 10538 mPrivateFlags |= DRAWN; 10539 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 10540 mLayerType != LAYER_TYPE_NONE) { 10541 mPrivateFlags |= DRAWING_CACHE_VALID; 10542 } 10543 10544 // Fast path for layouts with no backgrounds 10545 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10546 if (ViewDebug.TRACE_HIERARCHY) { 10547 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 10548 } 10549 mPrivateFlags &= ~DIRTY_MASK; 10550 dispatchDraw(canvas); 10551 } else { 10552 draw(canvas); 10553 } 10554 10555 canvas.restoreToCount(restoreCount); 10556 canvas.setBitmap(null); 10557 10558 if (attachInfo != null) { 10559 // Restore the cached Canvas for our siblings 10560 attachInfo.mCanvas = canvas; 10561 } 10562 } 10563 } 10564 10565 /** 10566 * Create a snapshot of the view into a bitmap. We should probably make 10567 * some form of this public, but should think about the API. 10568 */ 10569 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 10570 int width = mRight - mLeft; 10571 int height = mBottom - mTop; 10572 10573 final AttachInfo attachInfo = mAttachInfo; 10574 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 10575 width = (int) ((width * scale) + 0.5f); 10576 height = (int) ((height * scale) + 0.5f); 10577 10578 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 10579 if (bitmap == null) { 10580 throw new OutOfMemoryError(); 10581 } 10582 10583 Resources resources = getResources(); 10584 if (resources != null) { 10585 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 10586 } 10587 10588 Canvas canvas; 10589 if (attachInfo != null) { 10590 canvas = attachInfo.mCanvas; 10591 if (canvas == null) { 10592 canvas = new Canvas(); 10593 } 10594 canvas.setBitmap(bitmap); 10595 // Temporarily clobber the cached Canvas in case one of our children 10596 // is also using a drawing cache. Without this, the children would 10597 // steal the canvas by attaching their own bitmap to it and bad, bad 10598 // things would happen (invisible views, corrupted drawings, etc.) 10599 attachInfo.mCanvas = null; 10600 } else { 10601 // This case should hopefully never or seldom happen 10602 canvas = new Canvas(bitmap); 10603 } 10604 10605 if ((backgroundColor & 0xff000000) != 0) { 10606 bitmap.eraseColor(backgroundColor); 10607 } 10608 10609 computeScroll(); 10610 final int restoreCount = canvas.save(); 10611 canvas.scale(scale, scale); 10612 canvas.translate(-mScrollX, -mScrollY); 10613 10614 // Temporarily remove the dirty mask 10615 int flags = mPrivateFlags; 10616 mPrivateFlags &= ~DIRTY_MASK; 10617 10618 // Fast path for layouts with no backgrounds 10619 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10620 dispatchDraw(canvas); 10621 } else { 10622 draw(canvas); 10623 } 10624 10625 mPrivateFlags = flags; 10626 10627 canvas.restoreToCount(restoreCount); 10628 canvas.setBitmap(null); 10629 10630 if (attachInfo != null) { 10631 // Restore the cached Canvas for our siblings 10632 attachInfo.mCanvas = canvas; 10633 } 10634 10635 return bitmap; 10636 } 10637 10638 /** 10639 * Indicates whether this View is currently in edit mode. A View is usually 10640 * in edit mode when displayed within a developer tool. For instance, if 10641 * this View is being drawn by a visual user interface builder, this method 10642 * should return true. 10643 * 10644 * Subclasses should check the return value of this method to provide 10645 * different behaviors if their normal behavior might interfere with the 10646 * host environment. For instance: the class spawns a thread in its 10647 * constructor, the drawing code relies on device-specific features, etc. 10648 * 10649 * This method is usually checked in the drawing code of custom widgets. 10650 * 10651 * @return True if this View is in edit mode, false otherwise. 10652 */ 10653 public boolean isInEditMode() { 10654 return false; 10655 } 10656 10657 /** 10658 * If the View draws content inside its padding and enables fading edges, 10659 * it needs to support padding offsets. Padding offsets are added to the 10660 * fading edges to extend the length of the fade so that it covers pixels 10661 * drawn inside the padding. 10662 * 10663 * Subclasses of this class should override this method if they need 10664 * to draw content inside the padding. 10665 * 10666 * @return True if padding offset must be applied, false otherwise. 10667 * 10668 * @see #getLeftPaddingOffset() 10669 * @see #getRightPaddingOffset() 10670 * @see #getTopPaddingOffset() 10671 * @see #getBottomPaddingOffset() 10672 * 10673 * @since CURRENT 10674 */ 10675 protected boolean isPaddingOffsetRequired() { 10676 return false; 10677 } 10678 10679 /** 10680 * Amount by which to extend the left fading region. Called only when 10681 * {@link #isPaddingOffsetRequired()} returns true. 10682 * 10683 * @return The left padding offset in pixels. 10684 * 10685 * @see #isPaddingOffsetRequired() 10686 * 10687 * @since CURRENT 10688 */ 10689 protected int getLeftPaddingOffset() { 10690 return 0; 10691 } 10692 10693 /** 10694 * Amount by which to extend the right fading region. Called only when 10695 * {@link #isPaddingOffsetRequired()} returns true. 10696 * 10697 * @return The right padding offset in pixels. 10698 * 10699 * @see #isPaddingOffsetRequired() 10700 * 10701 * @since CURRENT 10702 */ 10703 protected int getRightPaddingOffset() { 10704 return 0; 10705 } 10706 10707 /** 10708 * Amount by which to extend the top fading region. Called only when 10709 * {@link #isPaddingOffsetRequired()} returns true. 10710 * 10711 * @return The top padding offset in pixels. 10712 * 10713 * @see #isPaddingOffsetRequired() 10714 * 10715 * @since CURRENT 10716 */ 10717 protected int getTopPaddingOffset() { 10718 return 0; 10719 } 10720 10721 /** 10722 * Amount by which to extend the bottom fading region. Called only when 10723 * {@link #isPaddingOffsetRequired()} returns true. 10724 * 10725 * @return The bottom padding offset in pixels. 10726 * 10727 * @see #isPaddingOffsetRequired() 10728 * 10729 * @since CURRENT 10730 */ 10731 protected int getBottomPaddingOffset() { 10732 return 0; 10733 } 10734 10735 /** 10736 * @hide 10737 * @param offsetRequired 10738 */ 10739 protected int getFadeTop(boolean offsetRequired) { 10740 int top = mPaddingTop; 10741 if (offsetRequired) top += getTopPaddingOffset(); 10742 return top; 10743 } 10744 10745 /** 10746 * @hide 10747 * @param offsetRequired 10748 */ 10749 protected int getFadeHeight(boolean offsetRequired) { 10750 int padding = mPaddingTop; 10751 if (offsetRequired) padding += getTopPaddingOffset(); 10752 return mBottom - mTop - mPaddingBottom - padding; 10753 } 10754 10755 /** 10756 * <p>Indicates whether this view is attached to an hardware accelerated 10757 * window or not.</p> 10758 * 10759 * <p>Even if this method returns true, it does not mean that every call 10760 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 10761 * accelerated {@link android.graphics.Canvas}. For instance, if this view 10762 * is drawn onto an offscren {@link android.graphics.Bitmap} and its 10763 * window is hardware accelerated, 10764 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 10765 * return false, and this method will return true.</p> 10766 * 10767 * @return True if the view is attached to a window and the window is 10768 * hardware accelerated; false in any other case. 10769 */ 10770 public boolean isHardwareAccelerated() { 10771 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 10772 } 10773 10774 /** 10775 * Manually render this view (and all of its children) to the given Canvas. 10776 * The view must have already done a full layout before this function is 10777 * called. When implementing a view, implement 10778 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 10779 * If you do need to override this method, call the superclass version. 10780 * 10781 * @param canvas The Canvas to which the View is rendered. 10782 */ 10783 public void draw(Canvas canvas) { 10784 if (ViewDebug.TRACE_HIERARCHY) { 10785 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 10786 } 10787 10788 final int privateFlags = mPrivateFlags; 10789 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 10790 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 10791 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 10792 10793 /* 10794 * Draw traversal performs several drawing steps which must be executed 10795 * in the appropriate order: 10796 * 10797 * 1. Draw the background 10798 * 2. If necessary, save the canvas' layers to prepare for fading 10799 * 3. Draw view's content 10800 * 4. Draw children 10801 * 5. If necessary, draw the fading edges and restore layers 10802 * 6. Draw decorations (scrollbars for instance) 10803 */ 10804 10805 // Step 1, draw the background, if needed 10806 int saveCount; 10807 10808 if (!dirtyOpaque) { 10809 final Drawable background = mBGDrawable; 10810 if (background != null) { 10811 final int scrollX = mScrollX; 10812 final int scrollY = mScrollY; 10813 10814 if (mBackgroundSizeChanged) { 10815 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 10816 mBackgroundSizeChanged = false; 10817 } 10818 10819 if ((scrollX | scrollY) == 0) { 10820 background.draw(canvas); 10821 } else { 10822 canvas.translate(scrollX, scrollY); 10823 background.draw(canvas); 10824 canvas.translate(-scrollX, -scrollY); 10825 } 10826 } 10827 } 10828 10829 // skip step 2 & 5 if possible (common case) 10830 final int viewFlags = mViewFlags; 10831 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 10832 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 10833 if (!verticalEdges && !horizontalEdges) { 10834 // Step 3, draw the content 10835 if (!dirtyOpaque) onDraw(canvas); 10836 10837 // Step 4, draw the children 10838 dispatchDraw(canvas); 10839 10840 // Step 6, draw decorations (scrollbars) 10841 onDrawScrollBars(canvas); 10842 10843 // we're done... 10844 return; 10845 } 10846 10847 /* 10848 * Here we do the full fledged routine... 10849 * (this is an uncommon case where speed matters less, 10850 * this is why we repeat some of the tests that have been 10851 * done above) 10852 */ 10853 10854 boolean drawTop = false; 10855 boolean drawBottom = false; 10856 boolean drawLeft = false; 10857 boolean drawRight = false; 10858 10859 float topFadeStrength = 0.0f; 10860 float bottomFadeStrength = 0.0f; 10861 float leftFadeStrength = 0.0f; 10862 float rightFadeStrength = 0.0f; 10863 10864 // Step 2, save the canvas' layers 10865 int paddingLeft = mPaddingLeft; 10866 10867 final boolean offsetRequired = isPaddingOffsetRequired(); 10868 if (offsetRequired) { 10869 paddingLeft += getLeftPaddingOffset(); 10870 } 10871 10872 int left = mScrollX + paddingLeft; 10873 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 10874 int top = mScrollY + getFadeTop(offsetRequired); 10875 int bottom = top + getFadeHeight(offsetRequired); 10876 10877 if (offsetRequired) { 10878 right += getRightPaddingOffset(); 10879 bottom += getBottomPaddingOffset(); 10880 } 10881 10882 final ScrollabilityCache scrollabilityCache = mScrollCache; 10883 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 10884 int length = (int) fadeHeight; 10885 10886 // clip the fade length if top and bottom fades overlap 10887 // overlapping fades produce odd-looking artifacts 10888 if (verticalEdges && (top + length > bottom - length)) { 10889 length = (bottom - top) / 2; 10890 } 10891 10892 // also clip horizontal fades if necessary 10893 if (horizontalEdges && (left + length > right - length)) { 10894 length = (right - left) / 2; 10895 } 10896 10897 if (verticalEdges) { 10898 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 10899 drawTop = topFadeStrength * fadeHeight > 1.0f; 10900 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 10901 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 10902 } 10903 10904 if (horizontalEdges) { 10905 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 10906 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 10907 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 10908 drawRight = rightFadeStrength * fadeHeight > 1.0f; 10909 } 10910 10911 saveCount = canvas.getSaveCount(); 10912 10913 int solidColor = getSolidColor(); 10914 if (solidColor == 0) { 10915 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 10916 10917 if (drawTop) { 10918 canvas.saveLayer(left, top, right, top + length, null, flags); 10919 } 10920 10921 if (drawBottom) { 10922 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 10923 } 10924 10925 if (drawLeft) { 10926 canvas.saveLayer(left, top, left + length, bottom, null, flags); 10927 } 10928 10929 if (drawRight) { 10930 canvas.saveLayer(right - length, top, right, bottom, null, flags); 10931 } 10932 } else { 10933 scrollabilityCache.setFadeColor(solidColor); 10934 } 10935 10936 // Step 3, draw the content 10937 if (!dirtyOpaque) onDraw(canvas); 10938 10939 // Step 4, draw the children 10940 dispatchDraw(canvas); 10941 10942 // Step 5, draw the fade effect and restore layers 10943 final Paint p = scrollabilityCache.paint; 10944 final Matrix matrix = scrollabilityCache.matrix; 10945 final Shader fade = scrollabilityCache.shader; 10946 10947 if (drawTop) { 10948 matrix.setScale(1, fadeHeight * topFadeStrength); 10949 matrix.postTranslate(left, top); 10950 fade.setLocalMatrix(matrix); 10951 canvas.drawRect(left, top, right, top + length, p); 10952 } 10953 10954 if (drawBottom) { 10955 matrix.setScale(1, fadeHeight * bottomFadeStrength); 10956 matrix.postRotate(180); 10957 matrix.postTranslate(left, bottom); 10958 fade.setLocalMatrix(matrix); 10959 canvas.drawRect(left, bottom - length, right, bottom, p); 10960 } 10961 10962 if (drawLeft) { 10963 matrix.setScale(1, fadeHeight * leftFadeStrength); 10964 matrix.postRotate(-90); 10965 matrix.postTranslate(left, top); 10966 fade.setLocalMatrix(matrix); 10967 canvas.drawRect(left, top, left + length, bottom, p); 10968 } 10969 10970 if (drawRight) { 10971 matrix.setScale(1, fadeHeight * rightFadeStrength); 10972 matrix.postRotate(90); 10973 matrix.postTranslate(right, top); 10974 fade.setLocalMatrix(matrix); 10975 canvas.drawRect(right - length, top, right, bottom, p); 10976 } 10977 10978 canvas.restoreToCount(saveCount); 10979 10980 // Step 6, draw decorations (scrollbars) 10981 onDrawScrollBars(canvas); 10982 } 10983 10984 /** 10985 * Override this if your view is known to always be drawn on top of a solid color background, 10986 * and needs to draw fading edges. Returning a non-zero color enables the view system to 10987 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 10988 * should be set to 0xFF. 10989 * 10990 * @see #setVerticalFadingEdgeEnabled(boolean) 10991 * @see #setHorizontalFadingEdgeEnabled(boolean) 10992 * 10993 * @return The known solid color background for this view, or 0 if the color may vary 10994 */ 10995 @ViewDebug.ExportedProperty(category = "drawing") 10996 public int getSolidColor() { 10997 return 0; 10998 } 10999 11000 /** 11001 * Build a human readable string representation of the specified view flags. 11002 * 11003 * @param flags the view flags to convert to a string 11004 * @return a String representing the supplied flags 11005 */ 11006 private static String printFlags(int flags) { 11007 String output = ""; 11008 int numFlags = 0; 11009 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 11010 output += "TAKES_FOCUS"; 11011 numFlags++; 11012 } 11013 11014 switch (flags & VISIBILITY_MASK) { 11015 case INVISIBLE: 11016 if (numFlags > 0) { 11017 output += " "; 11018 } 11019 output += "INVISIBLE"; 11020 // USELESS HERE numFlags++; 11021 break; 11022 case GONE: 11023 if (numFlags > 0) { 11024 output += " "; 11025 } 11026 output += "GONE"; 11027 // USELESS HERE numFlags++; 11028 break; 11029 default: 11030 break; 11031 } 11032 return output; 11033 } 11034 11035 /** 11036 * Build a human readable string representation of the specified private 11037 * view flags. 11038 * 11039 * @param privateFlags the private view flags to convert to a string 11040 * @return a String representing the supplied flags 11041 */ 11042 private static String printPrivateFlags(int privateFlags) { 11043 String output = ""; 11044 int numFlags = 0; 11045 11046 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 11047 output += "WANTS_FOCUS"; 11048 numFlags++; 11049 } 11050 11051 if ((privateFlags & FOCUSED) == FOCUSED) { 11052 if (numFlags > 0) { 11053 output += " "; 11054 } 11055 output += "FOCUSED"; 11056 numFlags++; 11057 } 11058 11059 if ((privateFlags & SELECTED) == SELECTED) { 11060 if (numFlags > 0) { 11061 output += " "; 11062 } 11063 output += "SELECTED"; 11064 numFlags++; 11065 } 11066 11067 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 11068 if (numFlags > 0) { 11069 output += " "; 11070 } 11071 output += "IS_ROOT_NAMESPACE"; 11072 numFlags++; 11073 } 11074 11075 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 11076 if (numFlags > 0) { 11077 output += " "; 11078 } 11079 output += "HAS_BOUNDS"; 11080 numFlags++; 11081 } 11082 11083 if ((privateFlags & DRAWN) == DRAWN) { 11084 if (numFlags > 0) { 11085 output += " "; 11086 } 11087 output += "DRAWN"; 11088 // USELESS HERE numFlags++; 11089 } 11090 return output; 11091 } 11092 11093 /** 11094 * <p>Indicates whether or not this view's layout will be requested during 11095 * the next hierarchy layout pass.</p> 11096 * 11097 * @return true if the layout will be forced during next layout pass 11098 */ 11099 public boolean isLayoutRequested() { 11100 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 11101 } 11102 11103 /** 11104 * Assign a size and position to a view and all of its 11105 * descendants 11106 * 11107 * <p>This is the second phase of the layout mechanism. 11108 * (The first is measuring). In this phase, each parent calls 11109 * layout on all of its children to position them. 11110 * This is typically done using the child measurements 11111 * that were stored in the measure pass().</p> 11112 * 11113 * <p>Derived classes should not override this method. 11114 * Derived classes with children should override 11115 * onLayout. In that method, they should 11116 * call layout on each of their children.</p> 11117 * 11118 * @param l Left position, relative to parent 11119 * @param t Top position, relative to parent 11120 * @param r Right position, relative to parent 11121 * @param b Bottom position, relative to parent 11122 */ 11123 @SuppressWarnings({"unchecked"}) 11124 public void layout(int l, int t, int r, int b) { 11125 int oldL = mLeft; 11126 int oldT = mTop; 11127 int oldB = mBottom; 11128 int oldR = mRight; 11129 boolean changed = setFrame(l, t, r, b); 11130 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 11131 if (ViewDebug.TRACE_HIERARCHY) { 11132 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 11133 } 11134 11135 onLayout(changed, l, t, r, b); 11136 mPrivateFlags &= ~LAYOUT_REQUIRED; 11137 11138 if (mOnLayoutChangeListeners != null) { 11139 ArrayList<OnLayoutChangeListener> listenersCopy = 11140 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone(); 11141 int numListeners = listenersCopy.size(); 11142 for (int i = 0; i < numListeners; ++i) { 11143 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 11144 } 11145 } 11146 } 11147 mPrivateFlags &= ~FORCE_LAYOUT; 11148 } 11149 11150 /** 11151 * Called from layout when this view should 11152 * assign a size and position to each of its children. 11153 * 11154 * Derived classes with children should override 11155 * this method and call layout on each of 11156 * their children. 11157 * @param changed This is a new size or position for this view 11158 * @param left Left position, relative to parent 11159 * @param top Top position, relative to parent 11160 * @param right Right position, relative to parent 11161 * @param bottom Bottom position, relative to parent 11162 */ 11163 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 11164 } 11165 11166 /** 11167 * Assign a size and position to this view. 11168 * 11169 * This is called from layout. 11170 * 11171 * @param left Left position, relative to parent 11172 * @param top Top position, relative to parent 11173 * @param right Right position, relative to parent 11174 * @param bottom Bottom position, relative to parent 11175 * @return true if the new size and position are different than the 11176 * previous ones 11177 * {@hide} 11178 */ 11179 protected boolean setFrame(int left, int top, int right, int bottom) { 11180 boolean changed = false; 11181 11182 if (DBG) { 11183 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 11184 + right + "," + bottom + ")"); 11185 } 11186 11187 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 11188 changed = true; 11189 11190 // Remember our drawn bit 11191 int drawn = mPrivateFlags & DRAWN; 11192 11193 int oldWidth = mRight - mLeft; 11194 int oldHeight = mBottom - mTop; 11195 int newWidth = right - left; 11196 int newHeight = bottom - top; 11197 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 11198 11199 // Invalidate our old position 11200 invalidate(sizeChanged); 11201 11202 mLeft = left; 11203 mTop = top; 11204 mRight = right; 11205 mBottom = bottom; 11206 11207 mPrivateFlags |= HAS_BOUNDS; 11208 11209 11210 if (sizeChanged) { 11211 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 11212 // A change in dimension means an auto-centered pivot point changes, too 11213 if (mTransformationInfo != null) { 11214 mTransformationInfo.mMatrixDirty = true; 11215 } 11216 } 11217 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 11218 } 11219 11220 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 11221 // If we are visible, force the DRAWN bit to on so that 11222 // this invalidate will go through (at least to our parent). 11223 // This is because someone may have invalidated this view 11224 // before this call to setFrame came in, thereby clearing 11225 // the DRAWN bit. 11226 mPrivateFlags |= DRAWN; 11227 invalidate(sizeChanged); 11228 // parent display list may need to be recreated based on a change in the bounds 11229 // of any child 11230 invalidateParentCaches(); 11231 } 11232 11233 // Reset drawn bit to original value (invalidate turns it off) 11234 mPrivateFlags |= drawn; 11235 11236 mBackgroundSizeChanged = true; 11237 } 11238 return changed; 11239 } 11240 11241 /** 11242 * Finalize inflating a view from XML. This is called as the last phase 11243 * of inflation, after all child views have been added. 11244 * 11245 * <p>Even if the subclass overrides onFinishInflate, they should always be 11246 * sure to call the super method, so that we get called. 11247 */ 11248 protected void onFinishInflate() { 11249 } 11250 11251 /** 11252 * Returns the resources associated with this view. 11253 * 11254 * @return Resources object. 11255 */ 11256 public Resources getResources() { 11257 return mResources; 11258 } 11259 11260 /** 11261 * Invalidates the specified Drawable. 11262 * 11263 * @param drawable the drawable to invalidate 11264 */ 11265 public void invalidateDrawable(Drawable drawable) { 11266 if (verifyDrawable(drawable)) { 11267 final Rect dirty = drawable.getBounds(); 11268 final int scrollX = mScrollX; 11269 final int scrollY = mScrollY; 11270 11271 invalidate(dirty.left + scrollX, dirty.top + scrollY, 11272 dirty.right + scrollX, dirty.bottom + scrollY); 11273 } 11274 } 11275 11276 /** 11277 * Schedules an action on a drawable to occur at a specified time. 11278 * 11279 * @param who the recipient of the action 11280 * @param what the action to run on the drawable 11281 * @param when the time at which the action must occur. Uses the 11282 * {@link SystemClock#uptimeMillis} timebase. 11283 */ 11284 public void scheduleDrawable(Drawable who, Runnable what, long when) { 11285 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 11286 mAttachInfo.mHandler.postAtTime(what, who, when); 11287 } 11288 } 11289 11290 /** 11291 * Cancels a scheduled action on a drawable. 11292 * 11293 * @param who the recipient of the action 11294 * @param what the action to cancel 11295 */ 11296 public void unscheduleDrawable(Drawable who, Runnable what) { 11297 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 11298 mAttachInfo.mHandler.removeCallbacks(what, who); 11299 } 11300 } 11301 11302 /** 11303 * Unschedule any events associated with the given Drawable. This can be 11304 * used when selecting a new Drawable into a view, so that the previous 11305 * one is completely unscheduled. 11306 * 11307 * @param who The Drawable to unschedule. 11308 * 11309 * @see #drawableStateChanged 11310 */ 11311 public void unscheduleDrawable(Drawable who) { 11312 if (mAttachInfo != null) { 11313 mAttachInfo.mHandler.removeCallbacksAndMessages(who); 11314 } 11315 } 11316 11317 /** 11318 * Return the layout direction of a given Drawable. 11319 * 11320 * @param who the Drawable to query 11321 * 11322 * @hide 11323 */ 11324 public int getResolvedLayoutDirection(Drawable who) { 11325 return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT; 11326 } 11327 11328 /** 11329 * If your view subclass is displaying its own Drawable objects, it should 11330 * override this function and return true for any Drawable it is 11331 * displaying. This allows animations for those drawables to be 11332 * scheduled. 11333 * 11334 * <p>Be sure to call through to the super class when overriding this 11335 * function. 11336 * 11337 * @param who The Drawable to verify. Return true if it is one you are 11338 * displaying, else return the result of calling through to the 11339 * super class. 11340 * 11341 * @return boolean If true than the Drawable is being displayed in the 11342 * view; else false and it is not allowed to animate. 11343 * 11344 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 11345 * @see #drawableStateChanged() 11346 */ 11347 protected boolean verifyDrawable(Drawable who) { 11348 return who == mBGDrawable; 11349 } 11350 11351 /** 11352 * This function is called whenever the state of the view changes in such 11353 * a way that it impacts the state of drawables being shown. 11354 * 11355 * <p>Be sure to call through to the superclass when overriding this 11356 * function. 11357 * 11358 * @see Drawable#setState(int[]) 11359 */ 11360 protected void drawableStateChanged() { 11361 Drawable d = mBGDrawable; 11362 if (d != null && d.isStateful()) { 11363 d.setState(getDrawableState()); 11364 } 11365 } 11366 11367 /** 11368 * Call this to force a view to update its drawable state. This will cause 11369 * drawableStateChanged to be called on this view. Views that are interested 11370 * in the new state should call getDrawableState. 11371 * 11372 * @see #drawableStateChanged 11373 * @see #getDrawableState 11374 */ 11375 public void refreshDrawableState() { 11376 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 11377 drawableStateChanged(); 11378 11379 ViewParent parent = mParent; 11380 if (parent != null) { 11381 parent.childDrawableStateChanged(this); 11382 } 11383 } 11384 11385 /** 11386 * Return an array of resource IDs of the drawable states representing the 11387 * current state of the view. 11388 * 11389 * @return The current drawable state 11390 * 11391 * @see Drawable#setState(int[]) 11392 * @see #drawableStateChanged() 11393 * @see #onCreateDrawableState(int) 11394 */ 11395 public final int[] getDrawableState() { 11396 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 11397 return mDrawableState; 11398 } else { 11399 mDrawableState = onCreateDrawableState(0); 11400 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 11401 return mDrawableState; 11402 } 11403 } 11404 11405 /** 11406 * Generate the new {@link android.graphics.drawable.Drawable} state for 11407 * this view. This is called by the view 11408 * system when the cached Drawable state is determined to be invalid. To 11409 * retrieve the current state, you should use {@link #getDrawableState}. 11410 * 11411 * @param extraSpace if non-zero, this is the number of extra entries you 11412 * would like in the returned array in which you can place your own 11413 * states. 11414 * 11415 * @return Returns an array holding the current {@link Drawable} state of 11416 * the view. 11417 * 11418 * @see #mergeDrawableStates(int[], int[]) 11419 */ 11420 protected int[] onCreateDrawableState(int extraSpace) { 11421 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 11422 mParent instanceof View) { 11423 return ((View) mParent).onCreateDrawableState(extraSpace); 11424 } 11425 11426 int[] drawableState; 11427 11428 int privateFlags = mPrivateFlags; 11429 11430 int viewStateIndex = 0; 11431 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 11432 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 11433 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 11434 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 11435 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 11436 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 11437 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 11438 HardwareRenderer.isAvailable()) { 11439 // This is set if HW acceleration is requested, even if the current 11440 // process doesn't allow it. This is just to allow app preview 11441 // windows to better match their app. 11442 viewStateIndex |= VIEW_STATE_ACCELERATED; 11443 } 11444 if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 11445 11446 final int privateFlags2 = mPrivateFlags2; 11447 if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 11448 if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 11449 11450 drawableState = VIEW_STATE_SETS[viewStateIndex]; 11451 11452 //noinspection ConstantIfStatement 11453 if (false) { 11454 Log.i("View", "drawableStateIndex=" + viewStateIndex); 11455 Log.i("View", toString() 11456 + " pressed=" + ((privateFlags & PRESSED) != 0) 11457 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 11458 + " fo=" + hasFocus() 11459 + " sl=" + ((privateFlags & SELECTED) != 0) 11460 + " wf=" + hasWindowFocus() 11461 + ": " + Arrays.toString(drawableState)); 11462 } 11463 11464 if (extraSpace == 0) { 11465 return drawableState; 11466 } 11467 11468 final int[] fullState; 11469 if (drawableState != null) { 11470 fullState = new int[drawableState.length + extraSpace]; 11471 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 11472 } else { 11473 fullState = new int[extraSpace]; 11474 } 11475 11476 return fullState; 11477 } 11478 11479 /** 11480 * Merge your own state values in <var>additionalState</var> into the base 11481 * state values <var>baseState</var> that were returned by 11482 * {@link #onCreateDrawableState(int)}. 11483 * 11484 * @param baseState The base state values returned by 11485 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 11486 * own additional state values. 11487 * 11488 * @param additionalState The additional state values you would like 11489 * added to <var>baseState</var>; this array is not modified. 11490 * 11491 * @return As a convenience, the <var>baseState</var> array you originally 11492 * passed into the function is returned. 11493 * 11494 * @see #onCreateDrawableState(int) 11495 */ 11496 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 11497 final int N = baseState.length; 11498 int i = N - 1; 11499 while (i >= 0 && baseState[i] == 0) { 11500 i--; 11501 } 11502 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 11503 return baseState; 11504 } 11505 11506 /** 11507 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 11508 * on all Drawable objects associated with this view. 11509 */ 11510 public void jumpDrawablesToCurrentState() { 11511 if (mBGDrawable != null) { 11512 mBGDrawable.jumpToCurrentState(); 11513 } 11514 } 11515 11516 /** 11517 * Sets the background color for this view. 11518 * @param color the color of the background 11519 */ 11520 @RemotableViewMethod 11521 public void setBackgroundColor(int color) { 11522 if (mBGDrawable instanceof ColorDrawable) { 11523 ((ColorDrawable) mBGDrawable).setColor(color); 11524 } else { 11525 setBackgroundDrawable(new ColorDrawable(color)); 11526 } 11527 } 11528 11529 /** 11530 * Set the background to a given resource. The resource should refer to 11531 * a Drawable object or 0 to remove the background. 11532 * @param resid The identifier of the resource. 11533 * @attr ref android.R.styleable#View_background 11534 */ 11535 @RemotableViewMethod 11536 public void setBackgroundResource(int resid) { 11537 if (resid != 0 && resid == mBackgroundResource) { 11538 return; 11539 } 11540 11541 Drawable d= null; 11542 if (resid != 0) { 11543 d = mResources.getDrawable(resid); 11544 } 11545 setBackgroundDrawable(d); 11546 11547 mBackgroundResource = resid; 11548 } 11549 11550 /** 11551 * Set the background to a given Drawable, or remove the background. If the 11552 * background has padding, this View's padding is set to the background's 11553 * padding. However, when a background is removed, this View's padding isn't 11554 * touched. If setting the padding is desired, please use 11555 * {@link #setPadding(int, int, int, int)}. 11556 * 11557 * @param d The Drawable to use as the background, or null to remove the 11558 * background 11559 */ 11560 public void setBackgroundDrawable(Drawable d) { 11561 if (d == mBGDrawable) { 11562 return; 11563 } 11564 11565 boolean requestLayout = false; 11566 11567 mBackgroundResource = 0; 11568 11569 /* 11570 * Regardless of whether we're setting a new background or not, we want 11571 * to clear the previous drawable. 11572 */ 11573 if (mBGDrawable != null) { 11574 mBGDrawable.setCallback(null); 11575 unscheduleDrawable(mBGDrawable); 11576 } 11577 11578 if (d != null) { 11579 Rect padding = sThreadLocal.get(); 11580 if (padding == null) { 11581 padding = new Rect(); 11582 sThreadLocal.set(padding); 11583 } 11584 if (d.getPadding(padding)) { 11585 switch (d.getResolvedLayoutDirectionSelf()) { 11586 case LAYOUT_DIRECTION_RTL: 11587 setPadding(padding.right, padding.top, padding.left, padding.bottom); 11588 break; 11589 case LAYOUT_DIRECTION_LTR: 11590 default: 11591 setPadding(padding.left, padding.top, padding.right, padding.bottom); 11592 } 11593 } 11594 11595 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 11596 // if it has a different minimum size, we should layout again 11597 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 11598 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 11599 requestLayout = true; 11600 } 11601 11602 d.setCallback(this); 11603 if (d.isStateful()) { 11604 d.setState(getDrawableState()); 11605 } 11606 d.setVisible(getVisibility() == VISIBLE, false); 11607 mBGDrawable = d; 11608 11609 if ((mPrivateFlags & SKIP_DRAW) != 0) { 11610 mPrivateFlags &= ~SKIP_DRAW; 11611 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 11612 requestLayout = true; 11613 } 11614 } else { 11615 /* Remove the background */ 11616 mBGDrawable = null; 11617 11618 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 11619 /* 11620 * This view ONLY drew the background before and we're removing 11621 * the background, so now it won't draw anything 11622 * (hence we SKIP_DRAW) 11623 */ 11624 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 11625 mPrivateFlags |= SKIP_DRAW; 11626 } 11627 11628 /* 11629 * When the background is set, we try to apply its padding to this 11630 * View. When the background is removed, we don't touch this View's 11631 * padding. This is noted in the Javadocs. Hence, we don't need to 11632 * requestLayout(), the invalidate() below is sufficient. 11633 */ 11634 11635 // The old background's minimum size could have affected this 11636 // View's layout, so let's requestLayout 11637 requestLayout = true; 11638 } 11639 11640 computeOpaqueFlags(); 11641 11642 if (requestLayout) { 11643 requestLayout(); 11644 } 11645 11646 mBackgroundSizeChanged = true; 11647 invalidate(true); 11648 } 11649 11650 /** 11651 * Gets the background drawable 11652 * @return The drawable used as the background for this view, if any. 11653 */ 11654 public Drawable getBackground() { 11655 return mBGDrawable; 11656 } 11657 11658 /** 11659 * Sets the padding. The view may add on the space required to display 11660 * the scrollbars, depending on the style and visibility of the scrollbars. 11661 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 11662 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 11663 * from the values set in this call. 11664 * 11665 * @attr ref android.R.styleable#View_padding 11666 * @attr ref android.R.styleable#View_paddingBottom 11667 * @attr ref android.R.styleable#View_paddingLeft 11668 * @attr ref android.R.styleable#View_paddingRight 11669 * @attr ref android.R.styleable#View_paddingTop 11670 * @param left the left padding in pixels 11671 * @param top the top padding in pixels 11672 * @param right the right padding in pixels 11673 * @param bottom the bottom padding in pixels 11674 */ 11675 public void setPadding(int left, int top, int right, int bottom) { 11676 boolean changed = false; 11677 11678 mUserPaddingRelative = false; 11679 11680 mUserPaddingLeft = left; 11681 mUserPaddingRight = right; 11682 mUserPaddingBottom = bottom; 11683 11684 final int viewFlags = mViewFlags; 11685 11686 // Common case is there are no scroll bars. 11687 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 11688 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 11689 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 11690 ? 0 : getVerticalScrollbarWidth(); 11691 switch (mVerticalScrollbarPosition) { 11692 case SCROLLBAR_POSITION_DEFAULT: 11693 if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 11694 left += offset; 11695 } else { 11696 right += offset; 11697 } 11698 break; 11699 case SCROLLBAR_POSITION_RIGHT: 11700 right += offset; 11701 break; 11702 case SCROLLBAR_POSITION_LEFT: 11703 left += offset; 11704 break; 11705 } 11706 } 11707 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 11708 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 11709 ? 0 : getHorizontalScrollbarHeight(); 11710 } 11711 } 11712 11713 if (mPaddingLeft != left) { 11714 changed = true; 11715 mPaddingLeft = left; 11716 } 11717 if (mPaddingTop != top) { 11718 changed = true; 11719 mPaddingTop = top; 11720 } 11721 if (mPaddingRight != right) { 11722 changed = true; 11723 mPaddingRight = right; 11724 } 11725 if (mPaddingBottom != bottom) { 11726 changed = true; 11727 mPaddingBottom = bottom; 11728 } 11729 11730 if (changed) { 11731 requestLayout(); 11732 } 11733 } 11734 11735 /** 11736 * Sets the relative padding. The view may add on the space required to display 11737 * the scrollbars, depending on the style and visibility of the scrollbars. 11738 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 11739 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 11740 * from the values set in this call. 11741 * 11742 * @attr ref android.R.styleable#View_padding 11743 * @attr ref android.R.styleable#View_paddingBottom 11744 * @attr ref android.R.styleable#View_paddingStart 11745 * @attr ref android.R.styleable#View_paddingEnd 11746 * @attr ref android.R.styleable#View_paddingTop 11747 * @param start the start padding in pixels 11748 * @param top the top padding in pixels 11749 * @param end the end padding in pixels 11750 * @param bottom the bottom padding in pixels 11751 * 11752 * @hide 11753 */ 11754 public void setPaddingRelative(int start, int top, int end, int bottom) { 11755 mUserPaddingRelative = true; 11756 11757 mUserPaddingStart = start; 11758 mUserPaddingEnd = end; 11759 11760 switch(getResolvedLayoutDirection()) { 11761 case LAYOUT_DIRECTION_RTL: 11762 setPadding(end, top, start, bottom); 11763 break; 11764 case LAYOUT_DIRECTION_LTR: 11765 default: 11766 setPadding(start, top, end, bottom); 11767 } 11768 } 11769 11770 /** 11771 * Returns the top padding of this view. 11772 * 11773 * @return the top padding in pixels 11774 */ 11775 public int getPaddingTop() { 11776 return mPaddingTop; 11777 } 11778 11779 /** 11780 * Returns the bottom padding of this view. If there are inset and enabled 11781 * scrollbars, this value may include the space required to display the 11782 * scrollbars as well. 11783 * 11784 * @return the bottom padding in pixels 11785 */ 11786 public int getPaddingBottom() { 11787 return mPaddingBottom; 11788 } 11789 11790 /** 11791 * Returns the left padding of this view. If there are inset and enabled 11792 * scrollbars, this value may include the space required to display the 11793 * scrollbars as well. 11794 * 11795 * @return the left padding in pixels 11796 */ 11797 public int getPaddingLeft() { 11798 return mPaddingLeft; 11799 } 11800 11801 /** 11802 * Returns the start padding of this view. If there are inset and enabled 11803 * scrollbars, this value may include the space required to display the 11804 * scrollbars as well. 11805 * 11806 * @return the start padding in pixels 11807 * 11808 * @hide 11809 */ 11810 public int getPaddingStart() { 11811 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 11812 mPaddingRight : mPaddingLeft; 11813 } 11814 11815 /** 11816 * Returns the right padding of this view. If there are inset and enabled 11817 * scrollbars, this value may include the space required to display the 11818 * scrollbars as well. 11819 * 11820 * @return the right padding in pixels 11821 */ 11822 public int getPaddingRight() { 11823 return mPaddingRight; 11824 } 11825 11826 /** 11827 * Returns the end padding of this view. If there are inset and enabled 11828 * scrollbars, this value may include the space required to display the 11829 * scrollbars as well. 11830 * 11831 * @return the end padding in pixels 11832 * 11833 * @hide 11834 */ 11835 public int getPaddingEnd() { 11836 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 11837 mPaddingLeft : mPaddingRight; 11838 } 11839 11840 /** 11841 * Return if the padding as been set thru relative values 11842 * {@link #setPaddingRelative(int, int, int, int)} or thru 11843 * @attr ref android.R.styleable#View_paddingStart or 11844 * @attr ref android.R.styleable#View_paddingEnd 11845 * 11846 * @return true if the padding is relative or false if it is not. 11847 * 11848 * @hide 11849 */ 11850 public boolean isPaddingRelative() { 11851 return mUserPaddingRelative; 11852 } 11853 11854 /** 11855 * Changes the selection state of this view. A view can be selected or not. 11856 * Note that selection is not the same as focus. Views are typically 11857 * selected in the context of an AdapterView like ListView or GridView; 11858 * the selected view is the view that is highlighted. 11859 * 11860 * @param selected true if the view must be selected, false otherwise 11861 */ 11862 public void setSelected(boolean selected) { 11863 if (((mPrivateFlags & SELECTED) != 0) != selected) { 11864 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 11865 if (!selected) resetPressedState(); 11866 invalidate(true); 11867 refreshDrawableState(); 11868 dispatchSetSelected(selected); 11869 } 11870 } 11871 11872 /** 11873 * Dispatch setSelected to all of this View's children. 11874 * 11875 * @see #setSelected(boolean) 11876 * 11877 * @param selected The new selected state 11878 */ 11879 protected void dispatchSetSelected(boolean selected) { 11880 } 11881 11882 /** 11883 * Indicates the selection state of this view. 11884 * 11885 * @return true if the view is selected, false otherwise 11886 */ 11887 @ViewDebug.ExportedProperty 11888 public boolean isSelected() { 11889 return (mPrivateFlags & SELECTED) != 0; 11890 } 11891 11892 /** 11893 * Changes the activated state of this view. A view can be activated or not. 11894 * Note that activation is not the same as selection. Selection is 11895 * a transient property, representing the view (hierarchy) the user is 11896 * currently interacting with. Activation is a longer-term state that the 11897 * user can move views in and out of. For example, in a list view with 11898 * single or multiple selection enabled, the views in the current selection 11899 * set are activated. (Um, yeah, we are deeply sorry about the terminology 11900 * here.) The activated state is propagated down to children of the view it 11901 * is set on. 11902 * 11903 * @param activated true if the view must be activated, false otherwise 11904 */ 11905 public void setActivated(boolean activated) { 11906 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 11907 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 11908 invalidate(true); 11909 refreshDrawableState(); 11910 dispatchSetActivated(activated); 11911 } 11912 } 11913 11914 /** 11915 * Dispatch setActivated to all of this View's children. 11916 * 11917 * @see #setActivated(boolean) 11918 * 11919 * @param activated The new activated state 11920 */ 11921 protected void dispatchSetActivated(boolean activated) { 11922 } 11923 11924 /** 11925 * Indicates the activation state of this view. 11926 * 11927 * @return true if the view is activated, false otherwise 11928 */ 11929 @ViewDebug.ExportedProperty 11930 public boolean isActivated() { 11931 return (mPrivateFlags & ACTIVATED) != 0; 11932 } 11933 11934 /** 11935 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 11936 * observer can be used to get notifications when global events, like 11937 * layout, happen. 11938 * 11939 * The returned ViewTreeObserver observer is not guaranteed to remain 11940 * valid for the lifetime of this View. If the caller of this method keeps 11941 * a long-lived reference to ViewTreeObserver, it should always check for 11942 * the return value of {@link ViewTreeObserver#isAlive()}. 11943 * 11944 * @return The ViewTreeObserver for this view's hierarchy. 11945 */ 11946 public ViewTreeObserver getViewTreeObserver() { 11947 if (mAttachInfo != null) { 11948 return mAttachInfo.mTreeObserver; 11949 } 11950 if (mFloatingTreeObserver == null) { 11951 mFloatingTreeObserver = new ViewTreeObserver(); 11952 } 11953 return mFloatingTreeObserver; 11954 } 11955 11956 /** 11957 * <p>Finds the topmost view in the current view hierarchy.</p> 11958 * 11959 * @return the topmost view containing this view 11960 */ 11961 public View getRootView() { 11962 if (mAttachInfo != null) { 11963 final View v = mAttachInfo.mRootView; 11964 if (v != null) { 11965 return v; 11966 } 11967 } 11968 11969 View parent = this; 11970 11971 while (parent.mParent != null && parent.mParent instanceof View) { 11972 parent = (View) parent.mParent; 11973 } 11974 11975 return parent; 11976 } 11977 11978 /** 11979 * <p>Computes the coordinates of this view on the screen. The argument 11980 * must be an array of two integers. After the method returns, the array 11981 * contains the x and y location in that order.</p> 11982 * 11983 * @param location an array of two integers in which to hold the coordinates 11984 */ 11985 public void getLocationOnScreen(int[] location) { 11986 getLocationInWindow(location); 11987 11988 final AttachInfo info = mAttachInfo; 11989 if (info != null) { 11990 location[0] += info.mWindowLeft; 11991 location[1] += info.mWindowTop; 11992 } 11993 } 11994 11995 /** 11996 * <p>Computes the coordinates of this view in its window. The argument 11997 * must be an array of two integers. After the method returns, the array 11998 * contains the x and y location in that order.</p> 11999 * 12000 * @param location an array of two integers in which to hold the coordinates 12001 */ 12002 public void getLocationInWindow(int[] location) { 12003 if (location == null || location.length < 2) { 12004 throw new IllegalArgumentException("location must be an array of " 12005 + "two integers"); 12006 } 12007 12008 location[0] = mLeft; 12009 location[1] = mTop; 12010 if (mTransformationInfo != null) { 12011 location[0] += (int) (mTransformationInfo.mTranslationX + 0.5f); 12012 location[1] += (int) (mTransformationInfo.mTranslationY + 0.5f); 12013 } 12014 12015 ViewParent viewParent = mParent; 12016 while (viewParent instanceof View) { 12017 final View view = (View)viewParent; 12018 location[0] += view.mLeft - view.mScrollX; 12019 location[1] += view.mTop - view.mScrollY; 12020 if (view.mTransformationInfo != null) { 12021 location[0] += (int) (view.mTransformationInfo.mTranslationX + 0.5f); 12022 location[1] += (int) (view.mTransformationInfo.mTranslationY + 0.5f); 12023 } 12024 viewParent = view.mParent; 12025 } 12026 12027 if (viewParent instanceof ViewRootImpl) { 12028 // *cough* 12029 final ViewRootImpl vr = (ViewRootImpl)viewParent; 12030 location[1] -= vr.mCurScrollY; 12031 } 12032 } 12033 12034 /** 12035 * {@hide} 12036 * @param id the id of the view to be found 12037 * @return the view of the specified id, null if cannot be found 12038 */ 12039 protected View findViewTraversal(int id) { 12040 if (id == mID) { 12041 return this; 12042 } 12043 return null; 12044 } 12045 12046 /** 12047 * {@hide} 12048 * @param tag the tag of the view to be found 12049 * @return the view of specified tag, null if cannot be found 12050 */ 12051 protected View findViewWithTagTraversal(Object tag) { 12052 if (tag != null && tag.equals(mTag)) { 12053 return this; 12054 } 12055 return null; 12056 } 12057 12058 /** 12059 * {@hide} 12060 * @param predicate The predicate to evaluate. 12061 * @param childToSkip If not null, ignores this child during the recursive traversal. 12062 * @return The first view that matches the predicate or null. 12063 */ 12064 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 12065 if (predicate.apply(this)) { 12066 return this; 12067 } 12068 return null; 12069 } 12070 12071 /** 12072 * Look for a child view with the given id. If this view has the given 12073 * id, return this view. 12074 * 12075 * @param id The id to search for. 12076 * @return The view that has the given id in the hierarchy or null 12077 */ 12078 public final View findViewById(int id) { 12079 if (id < 0) { 12080 return null; 12081 } 12082 return findViewTraversal(id); 12083 } 12084 12085 /** 12086 * Look for a child view with the given tag. If this view has the given 12087 * tag, return this view. 12088 * 12089 * @param tag The tag to search for, using "tag.equals(getTag())". 12090 * @return The View that has the given tag in the hierarchy or null 12091 */ 12092 public final View findViewWithTag(Object tag) { 12093 if (tag == null) { 12094 return null; 12095 } 12096 return findViewWithTagTraversal(tag); 12097 } 12098 12099 /** 12100 * {@hide} 12101 * Look for a child view that matches the specified predicate. 12102 * If this view matches the predicate, return this view. 12103 * 12104 * @param predicate The predicate to evaluate. 12105 * @return The first view that matches the predicate or null. 12106 */ 12107 public final View findViewByPredicate(Predicate<View> predicate) { 12108 return findViewByPredicateTraversal(predicate, null); 12109 } 12110 12111 /** 12112 * {@hide} 12113 * Look for a child view that matches the specified predicate, 12114 * starting with the specified view and its descendents and then 12115 * recusively searching the ancestors and siblings of that view 12116 * until this view is reached. 12117 * 12118 * This method is useful in cases where the predicate does not match 12119 * a single unique view (perhaps multiple views use the same id) 12120 * and we are trying to find the view that is "closest" in scope to the 12121 * starting view. 12122 * 12123 * @param start The view to start from. 12124 * @param predicate The predicate to evaluate. 12125 * @return The first view that matches the predicate or null. 12126 */ 12127 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 12128 View childToSkip = null; 12129 for (;;) { 12130 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 12131 if (view != null || start == this) { 12132 return view; 12133 } 12134 12135 ViewParent parent = start.getParent(); 12136 if (parent == null || !(parent instanceof View)) { 12137 return null; 12138 } 12139 12140 childToSkip = start; 12141 start = (View) parent; 12142 } 12143 } 12144 12145 /** 12146 * Sets the identifier for this view. The identifier does not have to be 12147 * unique in this view's hierarchy. The identifier should be a positive 12148 * number. 12149 * 12150 * @see #NO_ID 12151 * @see #getId() 12152 * @see #findViewById(int) 12153 * 12154 * @param id a number used to identify the view 12155 * 12156 * @attr ref android.R.styleable#View_id 12157 */ 12158 public void setId(int id) { 12159 mID = id; 12160 } 12161 12162 /** 12163 * {@hide} 12164 * 12165 * @param isRoot true if the view belongs to the root namespace, false 12166 * otherwise 12167 */ 12168 public void setIsRootNamespace(boolean isRoot) { 12169 if (isRoot) { 12170 mPrivateFlags |= IS_ROOT_NAMESPACE; 12171 } else { 12172 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 12173 } 12174 } 12175 12176 /** 12177 * {@hide} 12178 * 12179 * @return true if the view belongs to the root namespace, false otherwise 12180 */ 12181 public boolean isRootNamespace() { 12182 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 12183 } 12184 12185 /** 12186 * Returns this view's identifier. 12187 * 12188 * @return a positive integer used to identify the view or {@link #NO_ID} 12189 * if the view has no ID 12190 * 12191 * @see #setId(int) 12192 * @see #findViewById(int) 12193 * @attr ref android.R.styleable#View_id 12194 */ 12195 @ViewDebug.CapturedViewProperty 12196 public int getId() { 12197 return mID; 12198 } 12199 12200 /** 12201 * Returns this view's tag. 12202 * 12203 * @return the Object stored in this view as a tag 12204 * 12205 * @see #setTag(Object) 12206 * @see #getTag(int) 12207 */ 12208 @ViewDebug.ExportedProperty 12209 public Object getTag() { 12210 return mTag; 12211 } 12212 12213 /** 12214 * Sets the tag associated with this view. A tag can be used to mark 12215 * a view in its hierarchy and does not have to be unique within the 12216 * hierarchy. Tags can also be used to store data within a view without 12217 * resorting to another data structure. 12218 * 12219 * @param tag an Object to tag the view with 12220 * 12221 * @see #getTag() 12222 * @see #setTag(int, Object) 12223 */ 12224 public void setTag(final Object tag) { 12225 mTag = tag; 12226 } 12227 12228 /** 12229 * Returns the tag associated with this view and the specified key. 12230 * 12231 * @param key The key identifying the tag 12232 * 12233 * @return the Object stored in this view as a tag 12234 * 12235 * @see #setTag(int, Object) 12236 * @see #getTag() 12237 */ 12238 public Object getTag(int key) { 12239 SparseArray<Object> tags = null; 12240 synchronized (sTagsLock) { 12241 if (sTags != null) { 12242 tags = sTags.get(this); 12243 } 12244 } 12245 12246 if (tags != null) return tags.get(key); 12247 return null; 12248 } 12249 12250 /** 12251 * Sets a tag associated with this view and a key. A tag can be used 12252 * to mark a view in its hierarchy and does not have to be unique within 12253 * the hierarchy. Tags can also be used to store data within a view 12254 * without resorting to another data structure. 12255 * 12256 * The specified key should be an id declared in the resources of the 12257 * application to ensure it is unique (see the <a 12258 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 12259 * Keys identified as belonging to 12260 * the Android framework or not associated with any package will cause 12261 * an {@link IllegalArgumentException} to be thrown. 12262 * 12263 * @param key The key identifying the tag 12264 * @param tag An Object to tag the view with 12265 * 12266 * @throws IllegalArgumentException If they specified key is not valid 12267 * 12268 * @see #setTag(Object) 12269 * @see #getTag(int) 12270 */ 12271 public void setTag(int key, final Object tag) { 12272 // If the package id is 0x00 or 0x01, it's either an undefined package 12273 // or a framework id 12274 if ((key >>> 24) < 2) { 12275 throw new IllegalArgumentException("The key must be an application-specific " 12276 + "resource id."); 12277 } 12278 12279 setTagInternal(this, key, tag); 12280 } 12281 12282 /** 12283 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 12284 * framework id. 12285 * 12286 * @hide 12287 */ 12288 public void setTagInternal(int key, Object tag) { 12289 if ((key >>> 24) != 0x1) { 12290 throw new IllegalArgumentException("The key must be a framework-specific " 12291 + "resource id."); 12292 } 12293 12294 setTagInternal(this, key, tag); 12295 } 12296 12297 private static void setTagInternal(View view, int key, Object tag) { 12298 SparseArray<Object> tags = null; 12299 synchronized (sTagsLock) { 12300 if (sTags == null) { 12301 sTags = new WeakHashMap<View, SparseArray<Object>>(); 12302 } else { 12303 tags = sTags.get(view); 12304 } 12305 } 12306 12307 if (tags == null) { 12308 tags = new SparseArray<Object>(2); 12309 synchronized (sTagsLock) { 12310 sTags.put(view, tags); 12311 } 12312 } 12313 12314 tags.put(key, tag); 12315 } 12316 12317 /** 12318 * @param consistency The type of consistency. See ViewDebug for more information. 12319 * 12320 * @hide 12321 */ 12322 protected boolean dispatchConsistencyCheck(int consistency) { 12323 return onConsistencyCheck(consistency); 12324 } 12325 12326 /** 12327 * Method that subclasses should implement to check their consistency. The type of 12328 * consistency check is indicated by the bit field passed as a parameter. 12329 * 12330 * @param consistency The type of consistency. See ViewDebug for more information. 12331 * 12332 * @throws IllegalStateException if the view is in an inconsistent state. 12333 * 12334 * @hide 12335 */ 12336 protected boolean onConsistencyCheck(int consistency) { 12337 boolean result = true; 12338 12339 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 12340 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 12341 12342 if (checkLayout) { 12343 if (getParent() == null) { 12344 result = false; 12345 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12346 "View " + this + " does not have a parent."); 12347 } 12348 12349 if (mAttachInfo == null) { 12350 result = false; 12351 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12352 "View " + this + " is not attached to a window."); 12353 } 12354 } 12355 12356 if (checkDrawing) { 12357 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 12358 // from their draw() method 12359 12360 if ((mPrivateFlags & DRAWN) != DRAWN && 12361 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 12362 result = false; 12363 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12364 "View " + this + " was invalidated but its drawing cache is valid."); 12365 } 12366 } 12367 12368 return result; 12369 } 12370 12371 /** 12372 * Prints information about this view in the log output, with the tag 12373 * {@link #VIEW_LOG_TAG}. 12374 * 12375 * @hide 12376 */ 12377 public void debug() { 12378 debug(0); 12379 } 12380 12381 /** 12382 * Prints information about this view in the log output, with the tag 12383 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 12384 * indentation defined by the <code>depth</code>. 12385 * 12386 * @param depth the indentation level 12387 * 12388 * @hide 12389 */ 12390 protected void debug(int depth) { 12391 String output = debugIndent(depth - 1); 12392 12393 output += "+ " + this; 12394 int id = getId(); 12395 if (id != -1) { 12396 output += " (id=" + id + ")"; 12397 } 12398 Object tag = getTag(); 12399 if (tag != null) { 12400 output += " (tag=" + tag + ")"; 12401 } 12402 Log.d(VIEW_LOG_TAG, output); 12403 12404 if ((mPrivateFlags & FOCUSED) != 0) { 12405 output = debugIndent(depth) + " FOCUSED"; 12406 Log.d(VIEW_LOG_TAG, output); 12407 } 12408 12409 output = debugIndent(depth); 12410 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 12411 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 12412 + "} "; 12413 Log.d(VIEW_LOG_TAG, output); 12414 12415 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 12416 || mPaddingBottom != 0) { 12417 output = debugIndent(depth); 12418 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 12419 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 12420 Log.d(VIEW_LOG_TAG, output); 12421 } 12422 12423 output = debugIndent(depth); 12424 output += "mMeasureWidth=" + mMeasuredWidth + 12425 " mMeasureHeight=" + mMeasuredHeight; 12426 Log.d(VIEW_LOG_TAG, output); 12427 12428 output = debugIndent(depth); 12429 if (mLayoutParams == null) { 12430 output += "BAD! no layout params"; 12431 } else { 12432 output = mLayoutParams.debug(output); 12433 } 12434 Log.d(VIEW_LOG_TAG, output); 12435 12436 output = debugIndent(depth); 12437 output += "flags={"; 12438 output += View.printFlags(mViewFlags); 12439 output += "}"; 12440 Log.d(VIEW_LOG_TAG, output); 12441 12442 output = debugIndent(depth); 12443 output += "privateFlags={"; 12444 output += View.printPrivateFlags(mPrivateFlags); 12445 output += "}"; 12446 Log.d(VIEW_LOG_TAG, output); 12447 } 12448 12449 /** 12450 * Creates an string of whitespaces used for indentation. 12451 * 12452 * @param depth the indentation level 12453 * @return a String containing (depth * 2 + 3) * 2 white spaces 12454 * 12455 * @hide 12456 */ 12457 protected static String debugIndent(int depth) { 12458 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 12459 for (int i = 0; i < (depth * 2) + 3; i++) { 12460 spaces.append(' ').append(' '); 12461 } 12462 return spaces.toString(); 12463 } 12464 12465 /** 12466 * <p>Return the offset of the widget's text baseline from the widget's top 12467 * boundary. If this widget does not support baseline alignment, this 12468 * method returns -1. </p> 12469 * 12470 * @return the offset of the baseline within the widget's bounds or -1 12471 * if baseline alignment is not supported 12472 */ 12473 @ViewDebug.ExportedProperty(category = "layout") 12474 public int getBaseline() { 12475 return -1; 12476 } 12477 12478 /** 12479 * Call this when something has changed which has invalidated the 12480 * layout of this view. This will schedule a layout pass of the view 12481 * tree. 12482 */ 12483 public void requestLayout() { 12484 if (ViewDebug.TRACE_HIERARCHY) { 12485 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 12486 } 12487 12488 mPrivateFlags |= FORCE_LAYOUT; 12489 mPrivateFlags |= INVALIDATED; 12490 12491 if (mParent != null) { 12492 if (mLayoutParams != null) { 12493 mLayoutParams.resolveWithDirection(getResolvedLayoutDirection()); 12494 } 12495 if (!mParent.isLayoutRequested()) { 12496 mParent.requestLayout(); 12497 } 12498 } 12499 } 12500 12501 /** 12502 * Forces this view to be laid out during the next layout pass. 12503 * This method does not call requestLayout() or forceLayout() 12504 * on the parent. 12505 */ 12506 public void forceLayout() { 12507 mPrivateFlags |= FORCE_LAYOUT; 12508 mPrivateFlags |= INVALIDATED; 12509 } 12510 12511 /** 12512 * <p> 12513 * This is called to find out how big a view should be. The parent 12514 * supplies constraint information in the width and height parameters. 12515 * </p> 12516 * 12517 * <p> 12518 * The actual mesurement work of a view is performed in 12519 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 12520 * {@link #onMeasure(int, int)} can and must be overriden by subclasses. 12521 * </p> 12522 * 12523 * 12524 * @param widthMeasureSpec Horizontal space requirements as imposed by the 12525 * parent 12526 * @param heightMeasureSpec Vertical space requirements as imposed by the 12527 * parent 12528 * 12529 * @see #onMeasure(int, int) 12530 */ 12531 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 12532 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 12533 widthMeasureSpec != mOldWidthMeasureSpec || 12534 heightMeasureSpec != mOldHeightMeasureSpec) { 12535 12536 // first clears the measured dimension flag 12537 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 12538 12539 if (ViewDebug.TRACE_HIERARCHY) { 12540 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 12541 } 12542 12543 // measure ourselves, this should set the measured dimension flag back 12544 onMeasure(widthMeasureSpec, heightMeasureSpec); 12545 12546 // flag not set, setMeasuredDimension() was not invoked, we raise 12547 // an exception to warn the developer 12548 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 12549 throw new IllegalStateException("onMeasure() did not set the" 12550 + " measured dimension by calling" 12551 + " setMeasuredDimension()"); 12552 } 12553 12554 mPrivateFlags |= LAYOUT_REQUIRED; 12555 } 12556 12557 mOldWidthMeasureSpec = widthMeasureSpec; 12558 mOldHeightMeasureSpec = heightMeasureSpec; 12559 } 12560 12561 /** 12562 * <p> 12563 * Measure the view and its content to determine the measured width and the 12564 * measured height. This method is invoked by {@link #measure(int, int)} and 12565 * should be overriden by subclasses to provide accurate and efficient 12566 * measurement of their contents. 12567 * </p> 12568 * 12569 * <p> 12570 * <strong>CONTRACT:</strong> When overriding this method, you 12571 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 12572 * measured width and height of this view. Failure to do so will trigger an 12573 * <code>IllegalStateException</code>, thrown by 12574 * {@link #measure(int, int)}. Calling the superclass' 12575 * {@link #onMeasure(int, int)} is a valid use. 12576 * </p> 12577 * 12578 * <p> 12579 * The base class implementation of measure defaults to the background size, 12580 * unless a larger size is allowed by the MeasureSpec. Subclasses should 12581 * override {@link #onMeasure(int, int)} to provide better measurements of 12582 * their content. 12583 * </p> 12584 * 12585 * <p> 12586 * If this method is overridden, it is the subclass's responsibility to make 12587 * sure the measured height and width are at least the view's minimum height 12588 * and width ({@link #getSuggestedMinimumHeight()} and 12589 * {@link #getSuggestedMinimumWidth()}). 12590 * </p> 12591 * 12592 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 12593 * The requirements are encoded with 12594 * {@link android.view.View.MeasureSpec}. 12595 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 12596 * The requirements are encoded with 12597 * {@link android.view.View.MeasureSpec}. 12598 * 12599 * @see #getMeasuredWidth() 12600 * @see #getMeasuredHeight() 12601 * @see #setMeasuredDimension(int, int) 12602 * @see #getSuggestedMinimumHeight() 12603 * @see #getSuggestedMinimumWidth() 12604 * @see android.view.View.MeasureSpec#getMode(int) 12605 * @see android.view.View.MeasureSpec#getSize(int) 12606 */ 12607 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 12608 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 12609 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 12610 } 12611 12612 /** 12613 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 12614 * measured width and measured height. Failing to do so will trigger an 12615 * exception at measurement time.</p> 12616 * 12617 * @param measuredWidth The measured width of this view. May be a complex 12618 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 12619 * {@link #MEASURED_STATE_TOO_SMALL}. 12620 * @param measuredHeight The measured height of this view. May be a complex 12621 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 12622 * {@link #MEASURED_STATE_TOO_SMALL}. 12623 */ 12624 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 12625 mMeasuredWidth = measuredWidth; 12626 mMeasuredHeight = measuredHeight; 12627 12628 mPrivateFlags |= MEASURED_DIMENSION_SET; 12629 } 12630 12631 /** 12632 * Merge two states as returned by {@link #getMeasuredState()}. 12633 * @param curState The current state as returned from a view or the result 12634 * of combining multiple views. 12635 * @param newState The new view state to combine. 12636 * @return Returns a new integer reflecting the combination of the two 12637 * states. 12638 */ 12639 public static int combineMeasuredStates(int curState, int newState) { 12640 return curState | newState; 12641 } 12642 12643 /** 12644 * Version of {@link #resolveSizeAndState(int, int, int)} 12645 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 12646 */ 12647 public static int resolveSize(int size, int measureSpec) { 12648 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 12649 } 12650 12651 /** 12652 * Utility to reconcile a desired size and state, with constraints imposed 12653 * by a MeasureSpec. Will take the desired size, unless a different size 12654 * is imposed by the constraints. The returned value is a compound integer, 12655 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 12656 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 12657 * size is smaller than the size the view wants to be. 12658 * 12659 * @param size How big the view wants to be 12660 * @param measureSpec Constraints imposed by the parent 12661 * @return Size information bit mask as defined by 12662 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 12663 */ 12664 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 12665 int result = size; 12666 int specMode = MeasureSpec.getMode(measureSpec); 12667 int specSize = MeasureSpec.getSize(measureSpec); 12668 switch (specMode) { 12669 case MeasureSpec.UNSPECIFIED: 12670 result = size; 12671 break; 12672 case MeasureSpec.AT_MOST: 12673 if (specSize < size) { 12674 result = specSize | MEASURED_STATE_TOO_SMALL; 12675 } else { 12676 result = size; 12677 } 12678 break; 12679 case MeasureSpec.EXACTLY: 12680 result = specSize; 12681 break; 12682 } 12683 return result | (childMeasuredState&MEASURED_STATE_MASK); 12684 } 12685 12686 /** 12687 * Utility to return a default size. Uses the supplied size if the 12688 * MeasureSpec imposed no constraints. Will get larger if allowed 12689 * by the MeasureSpec. 12690 * 12691 * @param size Default size for this view 12692 * @param measureSpec Constraints imposed by the parent 12693 * @return The size this view should be. 12694 */ 12695 public static int getDefaultSize(int size, int measureSpec) { 12696 int result = size; 12697 int specMode = MeasureSpec.getMode(measureSpec); 12698 int specSize = MeasureSpec.getSize(measureSpec); 12699 12700 switch (specMode) { 12701 case MeasureSpec.UNSPECIFIED: 12702 result = size; 12703 break; 12704 case MeasureSpec.AT_MOST: 12705 case MeasureSpec.EXACTLY: 12706 result = specSize; 12707 break; 12708 } 12709 return result; 12710 } 12711 12712 /** 12713 * Returns the suggested minimum height that the view should use. This 12714 * returns the maximum of the view's minimum height 12715 * and the background's minimum height 12716 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 12717 * <p> 12718 * When being used in {@link #onMeasure(int, int)}, the caller should still 12719 * ensure the returned height is within the requirements of the parent. 12720 * 12721 * @return The suggested minimum height of the view. 12722 */ 12723 protected int getSuggestedMinimumHeight() { 12724 int suggestedMinHeight = mMinHeight; 12725 12726 if (mBGDrawable != null) { 12727 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 12728 if (suggestedMinHeight < bgMinHeight) { 12729 suggestedMinHeight = bgMinHeight; 12730 } 12731 } 12732 12733 return suggestedMinHeight; 12734 } 12735 12736 /** 12737 * Returns the suggested minimum width that the view should use. This 12738 * returns the maximum of the view's minimum width) 12739 * and the background's minimum width 12740 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 12741 * <p> 12742 * When being used in {@link #onMeasure(int, int)}, the caller should still 12743 * ensure the returned width is within the requirements of the parent. 12744 * 12745 * @return The suggested minimum width of the view. 12746 */ 12747 protected int getSuggestedMinimumWidth() { 12748 int suggestedMinWidth = mMinWidth; 12749 12750 if (mBGDrawable != null) { 12751 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 12752 if (suggestedMinWidth < bgMinWidth) { 12753 suggestedMinWidth = bgMinWidth; 12754 } 12755 } 12756 12757 return suggestedMinWidth; 12758 } 12759 12760 /** 12761 * Sets the minimum height of the view. It is not guaranteed the view will 12762 * be able to achieve this minimum height (for example, if its parent layout 12763 * constrains it with less available height). 12764 * 12765 * @param minHeight The minimum height the view will try to be. 12766 */ 12767 public void setMinimumHeight(int minHeight) { 12768 mMinHeight = minHeight; 12769 } 12770 12771 /** 12772 * Sets the minimum width of the view. It is not guaranteed the view will 12773 * be able to achieve this minimum width (for example, if its parent layout 12774 * constrains it with less available width). 12775 * 12776 * @param minWidth The minimum width the view will try to be. 12777 */ 12778 public void setMinimumWidth(int minWidth) { 12779 mMinWidth = minWidth; 12780 } 12781 12782 /** 12783 * Get the animation currently associated with this view. 12784 * 12785 * @return The animation that is currently playing or 12786 * scheduled to play for this view. 12787 */ 12788 public Animation getAnimation() { 12789 return mCurrentAnimation; 12790 } 12791 12792 /** 12793 * Start the specified animation now. 12794 * 12795 * @param animation the animation to start now 12796 */ 12797 public void startAnimation(Animation animation) { 12798 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 12799 setAnimation(animation); 12800 invalidateParentCaches(); 12801 invalidate(true); 12802 } 12803 12804 /** 12805 * Cancels any animations for this view. 12806 */ 12807 public void clearAnimation() { 12808 if (mCurrentAnimation != null) { 12809 mCurrentAnimation.detach(); 12810 } 12811 mCurrentAnimation = null; 12812 invalidateParentIfNeeded(); 12813 } 12814 12815 /** 12816 * Sets the next animation to play for this view. 12817 * If you want the animation to play immediately, use 12818 * startAnimation. This method provides allows fine-grained 12819 * control over the start time and invalidation, but you 12820 * must make sure that 1) the animation has a start time set, and 12821 * 2) the view will be invalidated when the animation is supposed to 12822 * start. 12823 * 12824 * @param animation The next animation, or null. 12825 */ 12826 public void setAnimation(Animation animation) { 12827 mCurrentAnimation = animation; 12828 if (animation != null) { 12829 animation.reset(); 12830 } 12831 } 12832 12833 /** 12834 * Invoked by a parent ViewGroup to notify the start of the animation 12835 * currently associated with this view. If you override this method, 12836 * always call super.onAnimationStart(); 12837 * 12838 * @see #setAnimation(android.view.animation.Animation) 12839 * @see #getAnimation() 12840 */ 12841 protected void onAnimationStart() { 12842 mPrivateFlags |= ANIMATION_STARTED; 12843 } 12844 12845 /** 12846 * Invoked by a parent ViewGroup to notify the end of the animation 12847 * currently associated with this view. If you override this method, 12848 * always call super.onAnimationEnd(); 12849 * 12850 * @see #setAnimation(android.view.animation.Animation) 12851 * @see #getAnimation() 12852 */ 12853 protected void onAnimationEnd() { 12854 mPrivateFlags &= ~ANIMATION_STARTED; 12855 } 12856 12857 /** 12858 * Invoked if there is a Transform that involves alpha. Subclass that can 12859 * draw themselves with the specified alpha should return true, and then 12860 * respect that alpha when their onDraw() is called. If this returns false 12861 * then the view may be redirected to draw into an offscreen buffer to 12862 * fulfill the request, which will look fine, but may be slower than if the 12863 * subclass handles it internally. The default implementation returns false. 12864 * 12865 * @param alpha The alpha (0..255) to apply to the view's drawing 12866 * @return true if the view can draw with the specified alpha. 12867 */ 12868 protected boolean onSetAlpha(int alpha) { 12869 return false; 12870 } 12871 12872 /** 12873 * This is used by the RootView to perform an optimization when 12874 * the view hierarchy contains one or several SurfaceView. 12875 * SurfaceView is always considered transparent, but its children are not, 12876 * therefore all View objects remove themselves from the global transparent 12877 * region (passed as a parameter to this function). 12878 * 12879 * @param region The transparent region for this ViewAncestor (window). 12880 * 12881 * @return Returns true if the effective visibility of the view at this 12882 * point is opaque, regardless of the transparent region; returns false 12883 * if it is possible for underlying windows to be seen behind the view. 12884 * 12885 * {@hide} 12886 */ 12887 public boolean gatherTransparentRegion(Region region) { 12888 final AttachInfo attachInfo = mAttachInfo; 12889 if (region != null && attachInfo != null) { 12890 final int pflags = mPrivateFlags; 12891 if ((pflags & SKIP_DRAW) == 0) { 12892 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 12893 // remove it from the transparent region. 12894 final int[] location = attachInfo.mTransparentLocation; 12895 getLocationInWindow(location); 12896 region.op(location[0], location[1], location[0] + mRight - mLeft, 12897 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 12898 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 12899 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 12900 // exists, so we remove the background drawable's non-transparent 12901 // parts from this transparent region. 12902 applyDrawableToTransparentRegion(mBGDrawable, region); 12903 } 12904 } 12905 return true; 12906 } 12907 12908 /** 12909 * Play a sound effect for this view. 12910 * 12911 * <p>The framework will play sound effects for some built in actions, such as 12912 * clicking, but you may wish to play these effects in your widget, 12913 * for instance, for internal navigation. 12914 * 12915 * <p>The sound effect will only be played if sound effects are enabled by the user, and 12916 * {@link #isSoundEffectsEnabled()} is true. 12917 * 12918 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 12919 */ 12920 public void playSoundEffect(int soundConstant) { 12921 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 12922 return; 12923 } 12924 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 12925 } 12926 12927 /** 12928 * BZZZTT!!1! 12929 * 12930 * <p>Provide haptic feedback to the user for this view. 12931 * 12932 * <p>The framework will provide haptic feedback for some built in actions, 12933 * such as long presses, but you may wish to provide feedback for your 12934 * own widget. 12935 * 12936 * <p>The feedback will only be performed if 12937 * {@link #isHapticFeedbackEnabled()} is true. 12938 * 12939 * @param feedbackConstant One of the constants defined in 12940 * {@link HapticFeedbackConstants} 12941 */ 12942 public boolean performHapticFeedback(int feedbackConstant) { 12943 return performHapticFeedback(feedbackConstant, 0); 12944 } 12945 12946 /** 12947 * BZZZTT!!1! 12948 * 12949 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 12950 * 12951 * @param feedbackConstant One of the constants defined in 12952 * {@link HapticFeedbackConstants} 12953 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 12954 */ 12955 public boolean performHapticFeedback(int feedbackConstant, int flags) { 12956 if (mAttachInfo == null) { 12957 return false; 12958 } 12959 //noinspection SimplifiableIfStatement 12960 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 12961 && !isHapticFeedbackEnabled()) { 12962 return false; 12963 } 12964 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 12965 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 12966 } 12967 12968 /** 12969 * Request that the visibility of the status bar be changed. 12970 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 12971 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 12972 */ 12973 public void setSystemUiVisibility(int visibility) { 12974 if (visibility != mSystemUiVisibility) { 12975 mSystemUiVisibility = visibility; 12976 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 12977 mParent.recomputeViewAttributes(this); 12978 } 12979 } 12980 } 12981 12982 /** 12983 * Returns the status bar visibility that this view has requested. 12984 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 12985 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 12986 */ 12987 public int getSystemUiVisibility() { 12988 return mSystemUiVisibility; 12989 } 12990 12991 /** 12992 * Set a listener to receive callbacks when the visibility of the system bar changes. 12993 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 12994 */ 12995 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 12996 mOnSystemUiVisibilityChangeListener = l; 12997 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 12998 mParent.recomputeViewAttributes(this); 12999 } 13000 } 13001 13002 /** 13003 */ 13004 public void dispatchSystemUiVisibilityChanged(int visibility) { 13005 if (mOnSystemUiVisibilityChangeListener != null) { 13006 mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 13007 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 13008 } 13009 } 13010 13011 /** 13012 * Creates an image that the system displays during the drag and drop 13013 * operation. This is called a "drag shadow". The default implementation 13014 * for a DragShadowBuilder based on a View returns an image that has exactly the same 13015 * appearance as the given View. The default also positions the center of the drag shadow 13016 * directly under the touch point. If no View is provided (the constructor with no parameters 13017 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 13018 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 13019 * default is an invisible drag shadow. 13020 * <p> 13021 * You are not required to use the View you provide to the constructor as the basis of the 13022 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 13023 * anything you want as the drag shadow. 13024 * </p> 13025 * <p> 13026 * You pass a DragShadowBuilder object to the system when you start the drag. The system 13027 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 13028 * size and position of the drag shadow. It uses this data to construct a 13029 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 13030 * so that your application can draw the shadow image in the Canvas. 13031 * </p> 13032 */ 13033 public static class DragShadowBuilder { 13034 private final WeakReference<View> mView; 13035 13036 /** 13037 * Constructs a shadow image builder based on a View. By default, the resulting drag 13038 * shadow will have the same appearance and dimensions as the View, with the touch point 13039 * over the center of the View. 13040 * @param view A View. Any View in scope can be used. 13041 */ 13042 public DragShadowBuilder(View view) { 13043 mView = new WeakReference<View>(view); 13044 } 13045 13046 /** 13047 * Construct a shadow builder object with no associated View. This 13048 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 13049 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 13050 * to supply the drag shadow's dimensions and appearance without 13051 * reference to any View object. If they are not overridden, then the result is an 13052 * invisible drag shadow. 13053 */ 13054 public DragShadowBuilder() { 13055 mView = new WeakReference<View>(null); 13056 } 13057 13058 /** 13059 * Returns the View object that had been passed to the 13060 * {@link #View.DragShadowBuilder(View)} 13061 * constructor. If that View parameter was {@code null} or if the 13062 * {@link #View.DragShadowBuilder()} 13063 * constructor was used to instantiate the builder object, this method will return 13064 * null. 13065 * 13066 * @return The View object associate with this builder object. 13067 */ 13068 @SuppressWarnings({"JavadocReference"}) 13069 final public View getView() { 13070 return mView.get(); 13071 } 13072 13073 /** 13074 * Provides the metrics for the shadow image. These include the dimensions of 13075 * the shadow image, and the point within that shadow that should 13076 * be centered under the touch location while dragging. 13077 * <p> 13078 * The default implementation sets the dimensions of the shadow to be the 13079 * same as the dimensions of the View itself and centers the shadow under 13080 * the touch point. 13081 * </p> 13082 * 13083 * @param shadowSize A {@link android.graphics.Point} containing the width and height 13084 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 13085 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 13086 * image. 13087 * 13088 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 13089 * shadow image that should be underneath the touch point during the drag and drop 13090 * operation. Your application must set {@link android.graphics.Point#x} to the 13091 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 13092 */ 13093 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 13094 final View view = mView.get(); 13095 if (view != null) { 13096 shadowSize.set(view.getWidth(), view.getHeight()); 13097 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 13098 } else { 13099 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 13100 } 13101 } 13102 13103 /** 13104 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 13105 * based on the dimensions it received from the 13106 * {@link #onProvideShadowMetrics(Point, Point)} callback. 13107 * 13108 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 13109 */ 13110 public void onDrawShadow(Canvas canvas) { 13111 final View view = mView.get(); 13112 if (view != null) { 13113 view.draw(canvas); 13114 } else { 13115 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 13116 } 13117 } 13118 } 13119 13120 /** 13121 * Starts a drag and drop operation. When your application calls this method, it passes a 13122 * {@link android.view.View.DragShadowBuilder} object to the system. The 13123 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 13124 * to get metrics for the drag shadow, and then calls the object's 13125 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 13126 * <p> 13127 * Once the system has the drag shadow, it begins the drag and drop operation by sending 13128 * drag events to all the View objects in your application that are currently visible. It does 13129 * this either by calling the View object's drag listener (an implementation of 13130 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 13131 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 13132 * Both are passed a {@link android.view.DragEvent} object that has a 13133 * {@link android.view.DragEvent#getAction()} value of 13134 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 13135 * </p> 13136 * <p> 13137 * Your application can invoke startDrag() on any attached View object. The View object does not 13138 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 13139 * be related to the View the user selected for dragging. 13140 * </p> 13141 * @param data A {@link android.content.ClipData} object pointing to the data to be 13142 * transferred by the drag and drop operation. 13143 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 13144 * drag shadow. 13145 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 13146 * drop operation. This Object is put into every DragEvent object sent by the system during the 13147 * current drag. 13148 * <p> 13149 * myLocalState is a lightweight mechanism for the sending information from the dragged View 13150 * to the target Views. For example, it can contain flags that differentiate between a 13151 * a copy operation and a move operation. 13152 * </p> 13153 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 13154 * so the parameter should be set to 0. 13155 * @return {@code true} if the method completes successfully, or 13156 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 13157 * do a drag, and so no drag operation is in progress. 13158 */ 13159 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 13160 Object myLocalState, int flags) { 13161 if (ViewDebug.DEBUG_DRAG) { 13162 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 13163 } 13164 boolean okay = false; 13165 13166 Point shadowSize = new Point(); 13167 Point shadowTouchPoint = new Point(); 13168 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 13169 13170 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 13171 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 13172 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 13173 } 13174 13175 if (ViewDebug.DEBUG_DRAG) { 13176 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 13177 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 13178 } 13179 Surface surface = new Surface(); 13180 try { 13181 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 13182 flags, shadowSize.x, shadowSize.y, surface); 13183 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 13184 + " surface=" + surface); 13185 if (token != null) { 13186 Canvas canvas = surface.lockCanvas(null); 13187 try { 13188 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 13189 shadowBuilder.onDrawShadow(canvas); 13190 } finally { 13191 surface.unlockCanvasAndPost(canvas); 13192 } 13193 13194 final ViewRootImpl root = getViewRootImpl(); 13195 13196 // Cache the local state object for delivery with DragEvents 13197 root.setLocalDragState(myLocalState); 13198 13199 // repurpose 'shadowSize' for the last touch point 13200 root.getLastTouchPoint(shadowSize); 13201 13202 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 13203 shadowSize.x, shadowSize.y, 13204 shadowTouchPoint.x, shadowTouchPoint.y, data); 13205 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 13206 13207 // Off and running! Release our local surface instance; the drag 13208 // shadow surface is now managed by the system process. 13209 surface.release(); 13210 } 13211 } catch (Exception e) { 13212 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 13213 surface.destroy(); 13214 } 13215 13216 return okay; 13217 } 13218 13219 /** 13220 * Handles drag events sent by the system following a call to 13221 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 13222 *<p> 13223 * When the system calls this method, it passes a 13224 * {@link android.view.DragEvent} object. A call to 13225 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 13226 * in DragEvent. The method uses these to determine what is happening in the drag and drop 13227 * operation. 13228 * @param event The {@link android.view.DragEvent} sent by the system. 13229 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 13230 * in DragEvent, indicating the type of drag event represented by this object. 13231 * @return {@code true} if the method was successful, otherwise {@code false}. 13232 * <p> 13233 * The method should return {@code true} in response to an action type of 13234 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 13235 * operation. 13236 * </p> 13237 * <p> 13238 * The method should also return {@code true} in response to an action type of 13239 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 13240 * {@code false} if it didn't. 13241 * </p> 13242 */ 13243 public boolean onDragEvent(DragEvent event) { 13244 return false; 13245 } 13246 13247 /** 13248 * Detects if this View is enabled and has a drag event listener. 13249 * If both are true, then it calls the drag event listener with the 13250 * {@link android.view.DragEvent} it received. If the drag event listener returns 13251 * {@code true}, then dispatchDragEvent() returns {@code true}. 13252 * <p> 13253 * For all other cases, the method calls the 13254 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 13255 * method and returns its result. 13256 * </p> 13257 * <p> 13258 * This ensures that a drag event is always consumed, even if the View does not have a drag 13259 * event listener. However, if the View has a listener and the listener returns true, then 13260 * onDragEvent() is not called. 13261 * </p> 13262 */ 13263 public boolean dispatchDragEvent(DragEvent event) { 13264 //noinspection SimplifiableIfStatement 13265 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 13266 && mOnDragListener.onDrag(this, event)) { 13267 return true; 13268 } 13269 return onDragEvent(event); 13270 } 13271 13272 boolean canAcceptDrag() { 13273 return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0; 13274 } 13275 13276 /** 13277 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 13278 * it is ever exposed at all. 13279 * @hide 13280 */ 13281 public void onCloseSystemDialogs(String reason) { 13282 } 13283 13284 /** 13285 * Given a Drawable whose bounds have been set to draw into this view, 13286 * update a Region being computed for 13287 * {@link #gatherTransparentRegion(android.graphics.Region)} so 13288 * that any non-transparent parts of the Drawable are removed from the 13289 * given transparent region. 13290 * 13291 * @param dr The Drawable whose transparency is to be applied to the region. 13292 * @param region A Region holding the current transparency information, 13293 * where any parts of the region that are set are considered to be 13294 * transparent. On return, this region will be modified to have the 13295 * transparency information reduced by the corresponding parts of the 13296 * Drawable that are not transparent. 13297 * {@hide} 13298 */ 13299 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 13300 if (DBG) { 13301 Log.i("View", "Getting transparent region for: " + this); 13302 } 13303 final Region r = dr.getTransparentRegion(); 13304 final Rect db = dr.getBounds(); 13305 final AttachInfo attachInfo = mAttachInfo; 13306 if (r != null && attachInfo != null) { 13307 final int w = getRight()-getLeft(); 13308 final int h = getBottom()-getTop(); 13309 if (db.left > 0) { 13310 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 13311 r.op(0, 0, db.left, h, Region.Op.UNION); 13312 } 13313 if (db.right < w) { 13314 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 13315 r.op(db.right, 0, w, h, Region.Op.UNION); 13316 } 13317 if (db.top > 0) { 13318 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 13319 r.op(0, 0, w, db.top, Region.Op.UNION); 13320 } 13321 if (db.bottom < h) { 13322 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 13323 r.op(0, db.bottom, w, h, Region.Op.UNION); 13324 } 13325 final int[] location = attachInfo.mTransparentLocation; 13326 getLocationInWindow(location); 13327 r.translate(location[0], location[1]); 13328 region.op(r, Region.Op.INTERSECT); 13329 } else { 13330 region.op(db, Region.Op.DIFFERENCE); 13331 } 13332 } 13333 13334 private void checkForLongClick(int delayOffset) { 13335 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 13336 mHasPerformedLongPress = false; 13337 13338 if (mPendingCheckForLongPress == null) { 13339 mPendingCheckForLongPress = new CheckForLongPress(); 13340 } 13341 mPendingCheckForLongPress.rememberWindowAttachCount(); 13342 postDelayed(mPendingCheckForLongPress, 13343 ViewConfiguration.getLongPressTimeout() - delayOffset); 13344 } 13345 } 13346 13347 /** 13348 * Inflate a view from an XML resource. This convenience method wraps the {@link 13349 * LayoutInflater} class, which provides a full range of options for view inflation. 13350 * 13351 * @param context The Context object for your activity or application. 13352 * @param resource The resource ID to inflate 13353 * @param root A view group that will be the parent. Used to properly inflate the 13354 * layout_* parameters. 13355 * @see LayoutInflater 13356 */ 13357 public static View inflate(Context context, int resource, ViewGroup root) { 13358 LayoutInflater factory = LayoutInflater.from(context); 13359 return factory.inflate(resource, root); 13360 } 13361 13362 /** 13363 * Scroll the view with standard behavior for scrolling beyond the normal 13364 * content boundaries. Views that call this method should override 13365 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 13366 * results of an over-scroll operation. 13367 * 13368 * Views can use this method to handle any touch or fling-based scrolling. 13369 * 13370 * @param deltaX Change in X in pixels 13371 * @param deltaY Change in Y in pixels 13372 * @param scrollX Current X scroll value in pixels before applying deltaX 13373 * @param scrollY Current Y scroll value in pixels before applying deltaY 13374 * @param scrollRangeX Maximum content scroll range along the X axis 13375 * @param scrollRangeY Maximum content scroll range along the Y axis 13376 * @param maxOverScrollX Number of pixels to overscroll by in either direction 13377 * along the X axis. 13378 * @param maxOverScrollY Number of pixels to overscroll by in either direction 13379 * along the Y axis. 13380 * @param isTouchEvent true if this scroll operation is the result of a touch event. 13381 * @return true if scrolling was clamped to an over-scroll boundary along either 13382 * axis, false otherwise. 13383 */ 13384 @SuppressWarnings({"UnusedParameters"}) 13385 protected boolean overScrollBy(int deltaX, int deltaY, 13386 int scrollX, int scrollY, 13387 int scrollRangeX, int scrollRangeY, 13388 int maxOverScrollX, int maxOverScrollY, 13389 boolean isTouchEvent) { 13390 final int overScrollMode = mOverScrollMode; 13391 final boolean canScrollHorizontal = 13392 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 13393 final boolean canScrollVertical = 13394 computeVerticalScrollRange() > computeVerticalScrollExtent(); 13395 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 13396 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 13397 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 13398 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 13399 13400 int newScrollX = scrollX + deltaX; 13401 if (!overScrollHorizontal) { 13402 maxOverScrollX = 0; 13403 } 13404 13405 int newScrollY = scrollY + deltaY; 13406 if (!overScrollVertical) { 13407 maxOverScrollY = 0; 13408 } 13409 13410 // Clamp values if at the limits and record 13411 final int left = -maxOverScrollX; 13412 final int right = maxOverScrollX + scrollRangeX; 13413 final int top = -maxOverScrollY; 13414 final int bottom = maxOverScrollY + scrollRangeY; 13415 13416 boolean clampedX = false; 13417 if (newScrollX > right) { 13418 newScrollX = right; 13419 clampedX = true; 13420 } else if (newScrollX < left) { 13421 newScrollX = left; 13422 clampedX = true; 13423 } 13424 13425 boolean clampedY = false; 13426 if (newScrollY > bottom) { 13427 newScrollY = bottom; 13428 clampedY = true; 13429 } else if (newScrollY < top) { 13430 newScrollY = top; 13431 clampedY = true; 13432 } 13433 13434 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 13435 13436 return clampedX || clampedY; 13437 } 13438 13439 /** 13440 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 13441 * respond to the results of an over-scroll operation. 13442 * 13443 * @param scrollX New X scroll value in pixels 13444 * @param scrollY New Y scroll value in pixels 13445 * @param clampedX True if scrollX was clamped to an over-scroll boundary 13446 * @param clampedY True if scrollY was clamped to an over-scroll boundary 13447 */ 13448 protected void onOverScrolled(int scrollX, int scrollY, 13449 boolean clampedX, boolean clampedY) { 13450 // Intentionally empty. 13451 } 13452 13453 /** 13454 * Returns the over-scroll mode for this view. The result will be 13455 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 13456 * (allow over-scrolling only if the view content is larger than the container), 13457 * or {@link #OVER_SCROLL_NEVER}. 13458 * 13459 * @return This view's over-scroll mode. 13460 */ 13461 public int getOverScrollMode() { 13462 return mOverScrollMode; 13463 } 13464 13465 /** 13466 * Set the over-scroll mode for this view. Valid over-scroll modes are 13467 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 13468 * (allow over-scrolling only if the view content is larger than the container), 13469 * or {@link #OVER_SCROLL_NEVER}. 13470 * 13471 * Setting the over-scroll mode of a view will have an effect only if the 13472 * view is capable of scrolling. 13473 * 13474 * @param overScrollMode The new over-scroll mode for this view. 13475 */ 13476 public void setOverScrollMode(int overScrollMode) { 13477 if (overScrollMode != OVER_SCROLL_ALWAYS && 13478 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 13479 overScrollMode != OVER_SCROLL_NEVER) { 13480 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 13481 } 13482 mOverScrollMode = overScrollMode; 13483 } 13484 13485 /** 13486 * Gets a scale factor that determines the distance the view should scroll 13487 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 13488 * @return The vertical scroll scale factor. 13489 * @hide 13490 */ 13491 protected float getVerticalScrollFactor() { 13492 if (mVerticalScrollFactor == 0) { 13493 TypedValue outValue = new TypedValue(); 13494 if (!mContext.getTheme().resolveAttribute( 13495 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 13496 throw new IllegalStateException( 13497 "Expected theme to define listPreferredItemHeight."); 13498 } 13499 mVerticalScrollFactor = outValue.getDimension( 13500 mContext.getResources().getDisplayMetrics()); 13501 } 13502 return mVerticalScrollFactor; 13503 } 13504 13505 /** 13506 * Gets a scale factor that determines the distance the view should scroll 13507 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 13508 * @return The horizontal scroll scale factor. 13509 * @hide 13510 */ 13511 protected float getHorizontalScrollFactor() { 13512 // TODO: Should use something else. 13513 return getVerticalScrollFactor(); 13514 } 13515 13516 /** 13517 * Return the value specifying the text direction or policy that was set with 13518 * {@link #setTextDirection(int)}. 13519 * 13520 * @return the defined text direction. It can be one of: 13521 * 13522 * {@link #TEXT_DIRECTION_INHERIT}, 13523 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13524 * {@link #TEXT_DIRECTION_ANY_RTL}, 13525 * {@link #TEXT_DIRECTION_LTR}, 13526 * {@link #TEXT_DIRECTION_RTL}, 13527 * 13528 * @hide 13529 */ 13530 public int getTextDirection() { 13531 return mTextDirection; 13532 } 13533 13534 /** 13535 * Set the text direction. 13536 * 13537 * @param textDirection the direction to set. Should be one of: 13538 * 13539 * {@link #TEXT_DIRECTION_INHERIT}, 13540 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13541 * {@link #TEXT_DIRECTION_ANY_RTL}, 13542 * {@link #TEXT_DIRECTION_LTR}, 13543 * {@link #TEXT_DIRECTION_RTL}, 13544 * 13545 * @hide 13546 */ 13547 public void setTextDirection(int textDirection) { 13548 if (textDirection != mTextDirection) { 13549 mTextDirection = textDirection; 13550 resetResolvedTextDirection(); 13551 requestLayout(); 13552 } 13553 } 13554 13555 /** 13556 * Return the resolved text direction. 13557 * 13558 * @return the resolved text direction. Return one of: 13559 * 13560 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13561 * {@link #TEXT_DIRECTION_ANY_RTL}, 13562 * {@link #TEXT_DIRECTION_LTR}, 13563 * {@link #TEXT_DIRECTION_RTL}, 13564 * 13565 * @hide 13566 */ 13567 public int getResolvedTextDirection() { 13568 if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) { 13569 resolveTextDirection(); 13570 } 13571 return mResolvedTextDirection; 13572 } 13573 13574 /** 13575 * Resolve the text direction. 13576 * 13577 * @hide 13578 */ 13579 protected void resolveTextDirection() { 13580 if (mTextDirection != TEXT_DIRECTION_INHERIT) { 13581 mResolvedTextDirection = mTextDirection; 13582 return; 13583 } 13584 if (mParent != null && mParent instanceof ViewGroup) { 13585 mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection(); 13586 return; 13587 } 13588 mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG; 13589 } 13590 13591 /** 13592 * Reset resolved text direction. Will be resolved during a call to getResolvedTextDirection(). 13593 * 13594 * @hide 13595 */ 13596 protected void resetResolvedTextDirection() { 13597 mResolvedTextDirection = TEXT_DIRECTION_INHERIT; 13598 } 13599 13600 // 13601 // Properties 13602 // 13603 /** 13604 * A Property wrapper around the <code>alpha</code> functionality handled by the 13605 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 13606 */ 13607 public static Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 13608 @Override 13609 public void setValue(View object, float value) { 13610 object.setAlpha(value); 13611 } 13612 13613 @Override 13614 public Float get(View object) { 13615 return object.getAlpha(); 13616 } 13617 }; 13618 13619 /** 13620 * A Property wrapper around the <code>translationX</code> functionality handled by the 13621 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 13622 */ 13623 public static Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 13624 @Override 13625 public void setValue(View object, float value) { 13626 object.setTranslationX(value); 13627 } 13628 13629 @Override 13630 public Float get(View object) { 13631 return object.getTranslationX(); 13632 } 13633 }; 13634 13635 /** 13636 * A Property wrapper around the <code>translationY</code> functionality handled by the 13637 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 13638 */ 13639 public static Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 13640 @Override 13641 public void setValue(View object, float value) { 13642 object.setTranslationY(value); 13643 } 13644 13645 @Override 13646 public Float get(View object) { 13647 return object.getTranslationY(); 13648 } 13649 }; 13650 13651 /** 13652 * A Property wrapper around the <code>x</code> functionality handled by the 13653 * {@link View#setX(float)} and {@link View#getX()} methods. 13654 */ 13655 public static Property<View, Float> X = new FloatProperty<View>("x") { 13656 @Override 13657 public void setValue(View object, float value) { 13658 object.setX(value); 13659 } 13660 13661 @Override 13662 public Float get(View object) { 13663 return object.getX(); 13664 } 13665 }; 13666 13667 /** 13668 * A Property wrapper around the <code>y</code> functionality handled by the 13669 * {@link View#setY(float)} and {@link View#getY()} methods. 13670 */ 13671 public static Property<View, Float> Y = new FloatProperty<View>("y") { 13672 @Override 13673 public void setValue(View object, float value) { 13674 object.setY(value); 13675 } 13676 13677 @Override 13678 public Float get(View object) { 13679 return object.getY(); 13680 } 13681 }; 13682 13683 /** 13684 * A Property wrapper around the <code>rotation</code> functionality handled by the 13685 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 13686 */ 13687 public static Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 13688 @Override 13689 public void setValue(View object, float value) { 13690 object.setRotation(value); 13691 } 13692 13693 @Override 13694 public Float get(View object) { 13695 return object.getRotation(); 13696 } 13697 }; 13698 13699 /** 13700 * A Property wrapper around the <code>rotationX</code> functionality handled by the 13701 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 13702 */ 13703 public static Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 13704 @Override 13705 public void setValue(View object, float value) { 13706 object.setRotationX(value); 13707 } 13708 13709 @Override 13710 public Float get(View object) { 13711 return object.getRotationX(); 13712 } 13713 }; 13714 13715 /** 13716 * A Property wrapper around the <code>rotationY</code> functionality handled by the 13717 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 13718 */ 13719 public static Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 13720 @Override 13721 public void setValue(View object, float value) { 13722 object.setRotationY(value); 13723 } 13724 13725 @Override 13726 public Float get(View object) { 13727 return object.getRotationY(); 13728 } 13729 }; 13730 13731 /** 13732 * A Property wrapper around the <code>scaleX</code> functionality handled by the 13733 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 13734 */ 13735 public static Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 13736 @Override 13737 public void setValue(View object, float value) { 13738 object.setScaleX(value); 13739 } 13740 13741 @Override 13742 public Float get(View object) { 13743 return object.getScaleX(); 13744 } 13745 }; 13746 13747 /** 13748 * A Property wrapper around the <code>scaleY</code> functionality handled by the 13749 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 13750 */ 13751 public static Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 13752 @Override 13753 public void setValue(View object, float value) { 13754 object.setScaleY(value); 13755 } 13756 13757 @Override 13758 public Float get(View object) { 13759 return object.getScaleY(); 13760 } 13761 }; 13762 13763 /** 13764 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 13765 * Each MeasureSpec represents a requirement for either the width or the height. 13766 * A MeasureSpec is comprised of a size and a mode. There are three possible 13767 * modes: 13768 * <dl> 13769 * <dt>UNSPECIFIED</dt> 13770 * <dd> 13771 * The parent has not imposed any constraint on the child. It can be whatever size 13772 * it wants. 13773 * </dd> 13774 * 13775 * <dt>EXACTLY</dt> 13776 * <dd> 13777 * The parent has determined an exact size for the child. The child is going to be 13778 * given those bounds regardless of how big it wants to be. 13779 * </dd> 13780 * 13781 * <dt>AT_MOST</dt> 13782 * <dd> 13783 * The child can be as large as it wants up to the specified size. 13784 * </dd> 13785 * </dl> 13786 * 13787 * MeasureSpecs are implemented as ints to reduce object allocation. This class 13788 * is provided to pack and unpack the <size, mode> tuple into the int. 13789 */ 13790 public static class MeasureSpec { 13791 private static final int MODE_SHIFT = 30; 13792 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 13793 13794 /** 13795 * Measure specification mode: The parent has not imposed any constraint 13796 * on the child. It can be whatever size it wants. 13797 */ 13798 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 13799 13800 /** 13801 * Measure specification mode: The parent has determined an exact size 13802 * for the child. The child is going to be given those bounds regardless 13803 * of how big it wants to be. 13804 */ 13805 public static final int EXACTLY = 1 << MODE_SHIFT; 13806 13807 /** 13808 * Measure specification mode: The child can be as large as it wants up 13809 * to the specified size. 13810 */ 13811 public static final int AT_MOST = 2 << MODE_SHIFT; 13812 13813 /** 13814 * Creates a measure specification based on the supplied size and mode. 13815 * 13816 * The mode must always be one of the following: 13817 * <ul> 13818 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 13819 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 13820 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 13821 * </ul> 13822 * 13823 * @param size the size of the measure specification 13824 * @param mode the mode of the measure specification 13825 * @return the measure specification based on size and mode 13826 */ 13827 public static int makeMeasureSpec(int size, int mode) { 13828 return size + mode; 13829 } 13830 13831 /** 13832 * Extracts the mode from the supplied measure specification. 13833 * 13834 * @param measureSpec the measure specification to extract the mode from 13835 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 13836 * {@link android.view.View.MeasureSpec#AT_MOST} or 13837 * {@link android.view.View.MeasureSpec#EXACTLY} 13838 */ 13839 public static int getMode(int measureSpec) { 13840 return (measureSpec & MODE_MASK); 13841 } 13842 13843 /** 13844 * Extracts the size from the supplied measure specification. 13845 * 13846 * @param measureSpec the measure specification to extract the size from 13847 * @return the size in pixels defined in the supplied measure specification 13848 */ 13849 public static int getSize(int measureSpec) { 13850 return (measureSpec & ~MODE_MASK); 13851 } 13852 13853 /** 13854 * Returns a String representation of the specified measure 13855 * specification. 13856 * 13857 * @param measureSpec the measure specification to convert to a String 13858 * @return a String with the following format: "MeasureSpec: MODE SIZE" 13859 */ 13860 public static String toString(int measureSpec) { 13861 int mode = getMode(measureSpec); 13862 int size = getSize(measureSpec); 13863 13864 StringBuilder sb = new StringBuilder("MeasureSpec: "); 13865 13866 if (mode == UNSPECIFIED) 13867 sb.append("UNSPECIFIED "); 13868 else if (mode == EXACTLY) 13869 sb.append("EXACTLY "); 13870 else if (mode == AT_MOST) 13871 sb.append("AT_MOST "); 13872 else 13873 sb.append(mode).append(" "); 13874 13875 sb.append(size); 13876 return sb.toString(); 13877 } 13878 } 13879 13880 class CheckForLongPress implements Runnable { 13881 13882 private int mOriginalWindowAttachCount; 13883 13884 public void run() { 13885 if (isPressed() && (mParent != null) 13886 && mOriginalWindowAttachCount == mWindowAttachCount) { 13887 if (performLongClick()) { 13888 mHasPerformedLongPress = true; 13889 } 13890 } 13891 } 13892 13893 public void rememberWindowAttachCount() { 13894 mOriginalWindowAttachCount = mWindowAttachCount; 13895 } 13896 } 13897 13898 private final class CheckForTap implements Runnable { 13899 public void run() { 13900 mPrivateFlags &= ~PREPRESSED; 13901 mPrivateFlags |= PRESSED; 13902 refreshDrawableState(); 13903 checkForLongClick(ViewConfiguration.getTapTimeout()); 13904 } 13905 } 13906 13907 private final class PerformClick implements Runnable { 13908 public void run() { 13909 performClick(); 13910 } 13911 } 13912 13913 /** @hide */ 13914 public void hackTurnOffWindowResizeAnim(boolean off) { 13915 mAttachInfo.mTurnOffWindowResizeAnim = off; 13916 } 13917 13918 /** 13919 * This method returns a ViewPropertyAnimator object, which can be used to animate 13920 * specific properties on this View. 13921 * 13922 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 13923 */ 13924 public ViewPropertyAnimator animate() { 13925 if (mAnimator == null) { 13926 mAnimator = new ViewPropertyAnimator(this); 13927 } 13928 return mAnimator; 13929 } 13930 13931 /** 13932 * Interface definition for a callback to be invoked when a key event is 13933 * dispatched to this view. The callback will be invoked before the key 13934 * event is given to the view. 13935 */ 13936 public interface OnKeyListener { 13937 /** 13938 * Called when a key is dispatched to a view. This allows listeners to 13939 * get a chance to respond before the target view. 13940 * 13941 * @param v The view the key has been dispatched to. 13942 * @param keyCode The code for the physical key that was pressed 13943 * @param event The KeyEvent object containing full information about 13944 * the event. 13945 * @return True if the listener has consumed the event, false otherwise. 13946 */ 13947 boolean onKey(View v, int keyCode, KeyEvent event); 13948 } 13949 13950 /** 13951 * Interface definition for a callback to be invoked when a touch event is 13952 * dispatched to this view. The callback will be invoked before the touch 13953 * event is given to the view. 13954 */ 13955 public interface OnTouchListener { 13956 /** 13957 * Called when a touch event is dispatched to a view. This allows listeners to 13958 * get a chance to respond before the target view. 13959 * 13960 * @param v The view the touch event has been dispatched to. 13961 * @param event The MotionEvent object containing full information about 13962 * the event. 13963 * @return True if the listener has consumed the event, false otherwise. 13964 */ 13965 boolean onTouch(View v, MotionEvent event); 13966 } 13967 13968 /** 13969 * Interface definition for a callback to be invoked when a hover event is 13970 * dispatched to this view. The callback will be invoked before the hover 13971 * event is given to the view. 13972 */ 13973 public interface OnHoverListener { 13974 /** 13975 * Called when a hover event is dispatched to a view. This allows listeners to 13976 * get a chance to respond before the target view. 13977 * 13978 * @param v The view the hover event has been dispatched to. 13979 * @param event The MotionEvent object containing full information about 13980 * the event. 13981 * @return True if the listener has consumed the event, false otherwise. 13982 */ 13983 boolean onHover(View v, MotionEvent event); 13984 } 13985 13986 /** 13987 * Interface definition for a callback to be invoked when a generic motion event is 13988 * dispatched to this view. The callback will be invoked before the generic motion 13989 * event is given to the view. 13990 */ 13991 public interface OnGenericMotionListener { 13992 /** 13993 * Called when a generic motion event is dispatched to a view. This allows listeners to 13994 * get a chance to respond before the target view. 13995 * 13996 * @param v The view the generic motion event has been dispatched to. 13997 * @param event The MotionEvent object containing full information about 13998 * the event. 13999 * @return True if the listener has consumed the event, false otherwise. 14000 */ 14001 boolean onGenericMotion(View v, MotionEvent event); 14002 } 14003 14004 /** 14005 * Interface definition for a callback to be invoked when a view has been clicked and held. 14006 */ 14007 public interface OnLongClickListener { 14008 /** 14009 * Called when a view has been clicked and held. 14010 * 14011 * @param v The view that was clicked and held. 14012 * 14013 * @return true if the callback consumed the long click, false otherwise. 14014 */ 14015 boolean onLongClick(View v); 14016 } 14017 14018 /** 14019 * Interface definition for a callback to be invoked when a drag is being dispatched 14020 * to this view. The callback will be invoked before the hosting view's own 14021 * onDrag(event) method. If the listener wants to fall back to the hosting view's 14022 * onDrag(event) behavior, it should return 'false' from this callback. 14023 */ 14024 public interface OnDragListener { 14025 /** 14026 * Called when a drag event is dispatched to a view. This allows listeners 14027 * to get a chance to override base View behavior. 14028 * 14029 * @param v The View that received the drag event. 14030 * @param event The {@link android.view.DragEvent} object for the drag event. 14031 * @return {@code true} if the drag event was handled successfully, or {@code false} 14032 * if the drag event was not handled. Note that {@code false} will trigger the View 14033 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 14034 */ 14035 boolean onDrag(View v, DragEvent event); 14036 } 14037 14038 /** 14039 * Interface definition for a callback to be invoked when the focus state of 14040 * a view changed. 14041 */ 14042 public interface OnFocusChangeListener { 14043 /** 14044 * Called when the focus state of a view has changed. 14045 * 14046 * @param v The view whose state has changed. 14047 * @param hasFocus The new focus state of v. 14048 */ 14049 void onFocusChange(View v, boolean hasFocus); 14050 } 14051 14052 /** 14053 * Interface definition for a callback to be invoked when a view is clicked. 14054 */ 14055 public interface OnClickListener { 14056 /** 14057 * Called when a view has been clicked. 14058 * 14059 * @param v The view that was clicked. 14060 */ 14061 void onClick(View v); 14062 } 14063 14064 /** 14065 * Interface definition for a callback to be invoked when the context menu 14066 * for this view is being built. 14067 */ 14068 public interface OnCreateContextMenuListener { 14069 /** 14070 * Called when the context menu for this view is being built. It is not 14071 * safe to hold onto the menu after this method returns. 14072 * 14073 * @param menu The context menu that is being built 14074 * @param v The view for which the context menu is being built 14075 * @param menuInfo Extra information about the item for which the 14076 * context menu should be shown. This information will vary 14077 * depending on the class of v. 14078 */ 14079 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 14080 } 14081 14082 /** 14083 * Interface definition for a callback to be invoked when the status bar changes 14084 * visibility. 14085 * 14086 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 14087 */ 14088 public interface OnSystemUiVisibilityChangeListener { 14089 /** 14090 * Called when the status bar changes visibility because of a call to 14091 * {@link View#setSystemUiVisibility(int)}. 14092 * 14093 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 14094 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 14095 */ 14096 public void onSystemUiVisibilityChange(int visibility); 14097 } 14098 14099 /** 14100 * Interface definition for a callback to be invoked when this view is attached 14101 * or detached from its window. 14102 */ 14103 public interface OnAttachStateChangeListener { 14104 /** 14105 * Called when the view is attached to a window. 14106 * @param v The view that was attached 14107 */ 14108 public void onViewAttachedToWindow(View v); 14109 /** 14110 * Called when the view is detached from a window. 14111 * @param v The view that was detached 14112 */ 14113 public void onViewDetachedFromWindow(View v); 14114 } 14115 14116 private final class UnsetPressedState implements Runnable { 14117 public void run() { 14118 setPressed(false); 14119 } 14120 } 14121 14122 /** 14123 * Base class for derived classes that want to save and restore their own 14124 * state in {@link android.view.View#onSaveInstanceState()}. 14125 */ 14126 public static class BaseSavedState extends AbsSavedState { 14127 /** 14128 * Constructor used when reading from a parcel. Reads the state of the superclass. 14129 * 14130 * @param source 14131 */ 14132 public BaseSavedState(Parcel source) { 14133 super(source); 14134 } 14135 14136 /** 14137 * Constructor called by derived classes when creating their SavedState objects 14138 * 14139 * @param superState The state of the superclass of this view 14140 */ 14141 public BaseSavedState(Parcelable superState) { 14142 super(superState); 14143 } 14144 14145 public static final Parcelable.Creator<BaseSavedState> CREATOR = 14146 new Parcelable.Creator<BaseSavedState>() { 14147 public BaseSavedState createFromParcel(Parcel in) { 14148 return new BaseSavedState(in); 14149 } 14150 14151 public BaseSavedState[] newArray(int size) { 14152 return new BaseSavedState[size]; 14153 } 14154 }; 14155 } 14156 14157 /** 14158 * A set of information given to a view when it is attached to its parent 14159 * window. 14160 */ 14161 static class AttachInfo { 14162 interface Callbacks { 14163 void playSoundEffect(int effectId); 14164 boolean performHapticFeedback(int effectId, boolean always); 14165 } 14166 14167 /** 14168 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 14169 * to a Handler. This class contains the target (View) to invalidate and 14170 * the coordinates of the dirty rectangle. 14171 * 14172 * For performance purposes, this class also implements a pool of up to 14173 * POOL_LIMIT objects that get reused. This reduces memory allocations 14174 * whenever possible. 14175 */ 14176 static class InvalidateInfo implements Poolable<InvalidateInfo> { 14177 private static final int POOL_LIMIT = 10; 14178 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 14179 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 14180 public InvalidateInfo newInstance() { 14181 return new InvalidateInfo(); 14182 } 14183 14184 public void onAcquired(InvalidateInfo element) { 14185 } 14186 14187 public void onReleased(InvalidateInfo element) { 14188 element.target = null; 14189 } 14190 }, POOL_LIMIT) 14191 ); 14192 14193 private InvalidateInfo mNext; 14194 private boolean mIsPooled; 14195 14196 View target; 14197 14198 int left; 14199 int top; 14200 int right; 14201 int bottom; 14202 14203 public void setNextPoolable(InvalidateInfo element) { 14204 mNext = element; 14205 } 14206 14207 public InvalidateInfo getNextPoolable() { 14208 return mNext; 14209 } 14210 14211 static InvalidateInfo acquire() { 14212 return sPool.acquire(); 14213 } 14214 14215 void release() { 14216 sPool.release(this); 14217 } 14218 14219 public boolean isPooled() { 14220 return mIsPooled; 14221 } 14222 14223 public void setPooled(boolean isPooled) { 14224 mIsPooled = isPooled; 14225 } 14226 } 14227 14228 final IWindowSession mSession; 14229 14230 final IWindow mWindow; 14231 14232 final IBinder mWindowToken; 14233 14234 final Callbacks mRootCallbacks; 14235 14236 HardwareCanvas mHardwareCanvas; 14237 14238 /** 14239 * The top view of the hierarchy. 14240 */ 14241 View mRootView; 14242 14243 IBinder mPanelParentWindowToken; 14244 Surface mSurface; 14245 14246 boolean mHardwareAccelerated; 14247 boolean mHardwareAccelerationRequested; 14248 HardwareRenderer mHardwareRenderer; 14249 14250 /** 14251 * Scale factor used by the compatibility mode 14252 */ 14253 float mApplicationScale; 14254 14255 /** 14256 * Indicates whether the application is in compatibility mode 14257 */ 14258 boolean mScalingRequired; 14259 14260 /** 14261 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 14262 */ 14263 boolean mTurnOffWindowResizeAnim; 14264 14265 /** 14266 * Left position of this view's window 14267 */ 14268 int mWindowLeft; 14269 14270 /** 14271 * Top position of this view's window 14272 */ 14273 int mWindowTop; 14274 14275 /** 14276 * Indicates whether views need to use 32-bit drawing caches 14277 */ 14278 boolean mUse32BitDrawingCache; 14279 14280 /** 14281 * For windows that are full-screen but using insets to layout inside 14282 * of the screen decorations, these are the current insets for the 14283 * content of the window. 14284 */ 14285 final Rect mContentInsets = new Rect(); 14286 14287 /** 14288 * For windows that are full-screen but using insets to layout inside 14289 * of the screen decorations, these are the current insets for the 14290 * actual visible parts of the window. 14291 */ 14292 final Rect mVisibleInsets = new Rect(); 14293 14294 /** 14295 * The internal insets given by this window. This value is 14296 * supplied by the client (through 14297 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 14298 * be given to the window manager when changed to be used in laying 14299 * out windows behind it. 14300 */ 14301 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 14302 = new ViewTreeObserver.InternalInsetsInfo(); 14303 14304 /** 14305 * All views in the window's hierarchy that serve as scroll containers, 14306 * used to determine if the window can be resized or must be panned 14307 * to adjust for a soft input area. 14308 */ 14309 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 14310 14311 final KeyEvent.DispatcherState mKeyDispatchState 14312 = new KeyEvent.DispatcherState(); 14313 14314 /** 14315 * Indicates whether the view's window currently has the focus. 14316 */ 14317 boolean mHasWindowFocus; 14318 14319 /** 14320 * The current visibility of the window. 14321 */ 14322 int mWindowVisibility; 14323 14324 /** 14325 * Indicates the time at which drawing started to occur. 14326 */ 14327 long mDrawingTime; 14328 14329 /** 14330 * Indicates whether or not ignoring the DIRTY_MASK flags. 14331 */ 14332 boolean mIgnoreDirtyState; 14333 14334 /** 14335 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 14336 * to avoid clearing that flag prematurely. 14337 */ 14338 boolean mSetIgnoreDirtyState = false; 14339 14340 /** 14341 * Indicates whether the view's window is currently in touch mode. 14342 */ 14343 boolean mInTouchMode; 14344 14345 /** 14346 * Indicates that ViewAncestor should trigger a global layout change 14347 * the next time it performs a traversal 14348 */ 14349 boolean mRecomputeGlobalAttributes; 14350 14351 /** 14352 * Set during a traveral if any views want to keep the screen on. 14353 */ 14354 boolean mKeepScreenOn; 14355 14356 /** 14357 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 14358 */ 14359 int mSystemUiVisibility; 14360 14361 /** 14362 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 14363 * attached. 14364 */ 14365 boolean mHasSystemUiListeners; 14366 14367 /** 14368 * Set if the visibility of any views has changed. 14369 */ 14370 boolean mViewVisibilityChanged; 14371 14372 /** 14373 * Set to true if a view has been scrolled. 14374 */ 14375 boolean mViewScrollChanged; 14376 14377 /** 14378 * Global to the view hierarchy used as a temporary for dealing with 14379 * x/y points in the transparent region computations. 14380 */ 14381 final int[] mTransparentLocation = new int[2]; 14382 14383 /** 14384 * Global to the view hierarchy used as a temporary for dealing with 14385 * x/y points in the ViewGroup.invalidateChild implementation. 14386 */ 14387 final int[] mInvalidateChildLocation = new int[2]; 14388 14389 14390 /** 14391 * Global to the view hierarchy used as a temporary for dealing with 14392 * x/y location when view is transformed. 14393 */ 14394 final float[] mTmpTransformLocation = new float[2]; 14395 14396 /** 14397 * The view tree observer used to dispatch global events like 14398 * layout, pre-draw, touch mode change, etc. 14399 */ 14400 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 14401 14402 /** 14403 * A Canvas used by the view hierarchy to perform bitmap caching. 14404 */ 14405 Canvas mCanvas; 14406 14407 /** 14408 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 14409 * handler can be used to pump events in the UI events queue. 14410 */ 14411 final Handler mHandler; 14412 14413 /** 14414 * Identifier for messages requesting the view to be invalidated. 14415 * Such messages should be sent to {@link #mHandler}. 14416 */ 14417 static final int INVALIDATE_MSG = 0x1; 14418 14419 /** 14420 * Identifier for messages requesting the view to invalidate a region. 14421 * Such messages should be sent to {@link #mHandler}. 14422 */ 14423 static final int INVALIDATE_RECT_MSG = 0x2; 14424 14425 /** 14426 * Temporary for use in computing invalidate rectangles while 14427 * calling up the hierarchy. 14428 */ 14429 final Rect mTmpInvalRect = new Rect(); 14430 14431 /** 14432 * Temporary for use in computing hit areas with transformed views 14433 */ 14434 final RectF mTmpTransformRect = new RectF(); 14435 14436 /** 14437 * Temporary list for use in collecting focusable descendents of a view. 14438 */ 14439 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 14440 14441 /** 14442 * The id of the window for accessibility purposes. 14443 */ 14444 int mAccessibilityWindowId = View.NO_ID; 14445 14446 /** 14447 * Creates a new set of attachment information with the specified 14448 * events handler and thread. 14449 * 14450 * @param handler the events handler the view must use 14451 */ 14452 AttachInfo(IWindowSession session, IWindow window, 14453 Handler handler, Callbacks effectPlayer) { 14454 mSession = session; 14455 mWindow = window; 14456 mWindowToken = window.asBinder(); 14457 mHandler = handler; 14458 mRootCallbacks = effectPlayer; 14459 } 14460 } 14461 14462 /** 14463 * <p>ScrollabilityCache holds various fields used by a View when scrolling 14464 * is supported. This avoids keeping too many unused fields in most 14465 * instances of View.</p> 14466 */ 14467 private static class ScrollabilityCache implements Runnable { 14468 14469 /** 14470 * Scrollbars are not visible 14471 */ 14472 public static final int OFF = 0; 14473 14474 /** 14475 * Scrollbars are visible 14476 */ 14477 public static final int ON = 1; 14478 14479 /** 14480 * Scrollbars are fading away 14481 */ 14482 public static final int FADING = 2; 14483 14484 public boolean fadeScrollBars; 14485 14486 public int fadingEdgeLength; 14487 public int scrollBarDefaultDelayBeforeFade; 14488 public int scrollBarFadeDuration; 14489 14490 public int scrollBarSize; 14491 public ScrollBarDrawable scrollBar; 14492 public float[] interpolatorValues; 14493 public View host; 14494 14495 public final Paint paint; 14496 public final Matrix matrix; 14497 public Shader shader; 14498 14499 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 14500 14501 private static final float[] OPAQUE = { 255 }; 14502 private static final float[] TRANSPARENT = { 0.0f }; 14503 14504 /** 14505 * When fading should start. This time moves into the future every time 14506 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 14507 */ 14508 public long fadeStartTime; 14509 14510 14511 /** 14512 * The current state of the scrollbars: ON, OFF, or FADING 14513 */ 14514 public int state = OFF; 14515 14516 private int mLastColor; 14517 14518 public ScrollabilityCache(ViewConfiguration configuration, View host) { 14519 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 14520 scrollBarSize = configuration.getScaledScrollBarSize(); 14521 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 14522 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 14523 14524 paint = new Paint(); 14525 matrix = new Matrix(); 14526 // use use a height of 1, and then wack the matrix each time we 14527 // actually use it. 14528 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 14529 14530 paint.setShader(shader); 14531 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 14532 this.host = host; 14533 } 14534 14535 public void setFadeColor(int color) { 14536 if (color != 0 && color != mLastColor) { 14537 mLastColor = color; 14538 color |= 0xFF000000; 14539 14540 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 14541 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 14542 14543 paint.setShader(shader); 14544 // Restore the default transfer mode (src_over) 14545 paint.setXfermode(null); 14546 } 14547 } 14548 14549 public void run() { 14550 long now = AnimationUtils.currentAnimationTimeMillis(); 14551 if (now >= fadeStartTime) { 14552 14553 // the animation fades the scrollbars out by changing 14554 // the opacity (alpha) from fully opaque to fully 14555 // transparent 14556 int nextFrame = (int) now; 14557 int framesCount = 0; 14558 14559 Interpolator interpolator = scrollBarInterpolator; 14560 14561 // Start opaque 14562 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 14563 14564 // End transparent 14565 nextFrame += scrollBarFadeDuration; 14566 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 14567 14568 state = FADING; 14569 14570 // Kick off the fade animation 14571 host.invalidate(true); 14572 } 14573 } 14574 } 14575 14576 /** 14577 * Resuable callback for sending 14578 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 14579 */ 14580 private class SendViewScrolledAccessibilityEvent implements Runnable { 14581 public volatile boolean mIsPending; 14582 14583 public void run() { 14584 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 14585 mIsPending = false; 14586 } 14587 } 14588 14589 /** 14590 * <p> 14591 * This class represents a delegate that can be registered in a {@link View} 14592 * to enhance accessibility support via composition rather via inheritance. 14593 * It is specifically targeted to widget developers that extend basic View 14594 * classes i.e. classes in package android.view, that would like their 14595 * applications to be backwards compatible. 14596 * </p> 14597 * <p> 14598 * A scenario in which a developer would like to use an accessibility delegate 14599 * is overriding a method introduced in a later API version then the minimal API 14600 * version supported by the application. For example, the method 14601 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 14602 * in API version 4 when the accessibility APIs were first introduced. If a 14603 * developer would like his application to run on API version 4 devices (assuming 14604 * all other APIs used by the application are version 4 or lower) and take advantage 14605 * of this method, instead of overriding the method which would break the application's 14606 * backwards compatibility, he can override the corresponding method in this 14607 * delegate and register the delegate in the target View if the API version of 14608 * the system is high enough i.e. the API version is same or higher to the API 14609 * version that introduced 14610 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 14611 * </p> 14612 * <p> 14613 * Here is an example implementation: 14614 * </p> 14615 * <code><pre><p> 14616 * if (Build.VERSION.SDK_INT >= 14) { 14617 * // If the API version is equal of higher than the version in 14618 * // which onInitializeAccessibilityNodeInfo was introduced we 14619 * // register a delegate with a customized implementation. 14620 * View view = findViewById(R.id.view_id); 14621 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 14622 * public void onInitializeAccessibilityNodeInfo(View host, 14623 * AccessibilityNodeInfo info) { 14624 * // Let the default implementation populate the info. 14625 * super.onInitializeAccessibilityNodeInfo(host, info); 14626 * // Set some other information. 14627 * info.setEnabled(host.isEnabled()); 14628 * } 14629 * }); 14630 * } 14631 * </code></pre></p> 14632 * <p> 14633 * This delegate contains methods that correspond to the accessibility methods 14634 * in View. If a delegate has been specified the implementation in View hands 14635 * off handling to the corresponding method in this delegate. The default 14636 * implementation the delegate methods behaves exactly as the corresponding 14637 * method in View for the case of no accessibility delegate been set. Hence, 14638 * to customize the behavior of a View method, clients can override only the 14639 * corresponding delegate method without altering the behavior of the rest 14640 * accessibility related methods of the host view. 14641 * </p> 14642 */ 14643 public static class AccessibilityDelegate { 14644 14645 /** 14646 * Sends an accessibility event of the given type. If accessibility is not 14647 * enabled this method has no effect. 14648 * <p> 14649 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 14650 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 14651 * been set. 14652 * </p> 14653 * 14654 * @param host The View hosting the delegate. 14655 * @param eventType The type of the event to send. 14656 * 14657 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 14658 */ 14659 public void sendAccessibilityEvent(View host, int eventType) { 14660 host.sendAccessibilityEventInternal(eventType); 14661 } 14662 14663 /** 14664 * Sends an accessibility event. This method behaves exactly as 14665 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 14666 * empty {@link AccessibilityEvent} and does not perform a check whether 14667 * accessibility is enabled. 14668 * <p> 14669 * The default implementation behaves as 14670 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 14671 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 14672 * the case of no accessibility delegate been set. 14673 * </p> 14674 * 14675 * @param host The View hosting the delegate. 14676 * @param event The event to send. 14677 * 14678 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 14679 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 14680 */ 14681 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 14682 host.sendAccessibilityEventUncheckedInternal(event); 14683 } 14684 14685 /** 14686 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 14687 * to its children for adding their text content to the event. 14688 * <p> 14689 * The default implementation behaves as 14690 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 14691 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 14692 * the case of no accessibility delegate been set. 14693 * </p> 14694 * 14695 * @param host The View hosting the delegate. 14696 * @param event The event. 14697 * @return True if the event population was completed. 14698 * 14699 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 14700 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 14701 */ 14702 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 14703 return host.dispatchPopulateAccessibilityEventInternal(event); 14704 } 14705 14706 /** 14707 * Gives a chance to the host View to populate the accessibility event with its 14708 * text content. 14709 * <p> 14710 * The default implementation behaves as 14711 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 14712 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 14713 * the case of no accessibility delegate been set. 14714 * </p> 14715 * 14716 * @param host The View hosting the delegate. 14717 * @param event The accessibility event which to populate. 14718 * 14719 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 14720 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 14721 */ 14722 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 14723 host.onPopulateAccessibilityEventInternal(event); 14724 } 14725 14726 /** 14727 * Initializes an {@link AccessibilityEvent} with information about the 14728 * the host View which is the event source. 14729 * <p> 14730 * The default implementation behaves as 14731 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 14732 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 14733 * the case of no accessibility delegate been set. 14734 * </p> 14735 * 14736 * @param host The View hosting the delegate. 14737 * @param event The event to initialize. 14738 * 14739 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 14740 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 14741 */ 14742 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 14743 host.onInitializeAccessibilityEventInternal(event); 14744 } 14745 14746 /** 14747 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 14748 * <p> 14749 * The default implementation behaves as 14750 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 14751 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 14752 * the case of no accessibility delegate been set. 14753 * </p> 14754 * 14755 * @param host The View hosting the delegate. 14756 * @param info The instance to initialize. 14757 * 14758 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 14759 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 14760 */ 14761 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 14762 host.onInitializeAccessibilityNodeInfoInternal(info); 14763 } 14764 14765 /** 14766 * Called when a child of the host View has requested sending an 14767 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 14768 * to augment the event. 14769 * <p> 14770 * The default implementation behaves as 14771 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 14772 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 14773 * the case of no accessibility delegate been set. 14774 * </p> 14775 * 14776 * @param host The View hosting the delegate. 14777 * @param child The child which requests sending the event. 14778 * @param event The event to be sent. 14779 * @return True if the event should be sent 14780 * 14781 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 14782 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 14783 */ 14784 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 14785 AccessibilityEvent event) { 14786 return host.onRequestSendAccessibilityEventInternal(child, event); 14787 } 14788 } 14789} 14790