View.java revision aff599b4abb10bad6711ff9348f97a56240e0612
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.util.AttributeSet; 49import android.util.FloatProperty; 50import android.util.LocaleUtil; 51import android.util.Log; 52import android.util.Pool; 53import android.util.Poolable; 54import android.util.PoolableManager; 55import android.util.Pools; 56import android.util.Property; 57import android.util.SparseArray; 58import android.util.TypedValue; 59import android.view.ContextMenu.ContextMenuInfo; 60import android.view.accessibility.AccessibilityEvent; 61import android.view.accessibility.AccessibilityEventSource; 62import android.view.accessibility.AccessibilityManager; 63import android.view.accessibility.AccessibilityNodeInfo; 64import android.view.animation.Animation; 65import android.view.animation.AnimationUtils; 66import android.view.inputmethod.EditorInfo; 67import android.view.inputmethod.InputConnection; 68import android.view.inputmethod.InputMethodManager; 69import android.widget.ScrollBarDrawable; 70 71import com.android.internal.R; 72import com.android.internal.util.Predicate; 73import com.android.internal.view.menu.MenuBuilder; 74 75import java.lang.ref.WeakReference; 76import java.lang.reflect.InvocationTargetException; 77import java.lang.reflect.Method; 78import java.util.ArrayList; 79import java.util.Arrays; 80import java.util.Locale; 81import java.util.WeakHashMap; 82import java.util.concurrent.CopyOnWriteArrayList; 83 84/** 85 * <p> 86 * This class represents the basic building block for user interface components. A View 87 * occupies a rectangular area on the screen and is responsible for drawing and 88 * event handling. View is the base class for <em>widgets</em>, which are 89 * used to create interactive UI components (buttons, text fields, etc.). The 90 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 91 * are invisible containers that hold other Views (or other ViewGroups) and define 92 * their layout properties. 93 * </p> 94 * 95 * <div class="special"> 96 * <p>For an introduction to using this class to develop your 97 * application's user interface, read the Developer Guide documentation on 98 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics 99 * include: 100 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a> 101 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a> 102 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a> 103 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a> 104 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a> 105 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a> 106 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a> 107 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>. 108 * </p> 109 * </div> 110 * 111 * <a name="Using"></a> 112 * <h3>Using Views</h3> 113 * <p> 114 * All of the views in a window are arranged in a single tree. You can add views 115 * either from code or by specifying a tree of views in one or more XML layout 116 * files. There are many specialized subclasses of views that act as controls or 117 * are capable of displaying text, images, or other content. 118 * </p> 119 * <p> 120 * Once you have created a tree of views, there are typically a few types of 121 * common operations you may wish to perform: 122 * <ul> 123 * <li><strong>Set properties:</strong> for example setting the text of a 124 * {@link android.widget.TextView}. The available properties and the methods 125 * that set them will vary among the different subclasses of views. Note that 126 * properties that are known at build time can be set in the XML layout 127 * files.</li> 128 * <li><strong>Set focus:</strong> The framework will handled moving focus in 129 * response to user input. To force focus to a specific view, call 130 * {@link #requestFocus}.</li> 131 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 132 * that will be notified when something interesting happens to the view. For 133 * example, all views will let you set a listener to be notified when the view 134 * gains or loses focus. You can register such a listener using 135 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 136 * Other view subclasses offer more specialized listeners. For example, a Button 137 * exposes a listener to notify clients when the button is clicked.</li> 138 * <li><strong>Set visibility:</strong> You can hide or show views using 139 * {@link #setVisibility(int)}.</li> 140 * </ul> 141 * </p> 142 * <p><em> 143 * Note: The Android framework is responsible for measuring, laying out and 144 * drawing views. You should not call methods that perform these actions on 145 * views yourself unless you are actually implementing a 146 * {@link android.view.ViewGroup}. 147 * </em></p> 148 * 149 * <a name="Lifecycle"></a> 150 * <h3>Implementing a Custom View</h3> 151 * 152 * <p> 153 * To implement a custom view, you will usually begin by providing overrides for 154 * some of the standard methods that the framework calls on all views. You do 155 * not need to override all of these methods. In fact, you can start by just 156 * overriding {@link #onDraw(android.graphics.Canvas)}. 157 * <table border="2" width="85%" align="center" cellpadding="5"> 158 * <thead> 159 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 160 * </thead> 161 * 162 * <tbody> 163 * <tr> 164 * <td rowspan="2">Creation</td> 165 * <td>Constructors</td> 166 * <td>There is a form of the constructor that are called when the view 167 * is created from code and a form that is called when the view is 168 * inflated from a layout file. The second form should parse and apply 169 * any attributes defined in the layout file. 170 * </td> 171 * </tr> 172 * <tr> 173 * <td><code>{@link #onFinishInflate()}</code></td> 174 * <td>Called after a view and all of its children has been inflated 175 * from XML.</td> 176 * </tr> 177 * 178 * <tr> 179 * <td rowspan="3">Layout</td> 180 * <td><code>{@link #onMeasure(int, int)}</code></td> 181 * <td>Called to determine the size requirements for this view and all 182 * of its children. 183 * </td> 184 * </tr> 185 * <tr> 186 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 187 * <td>Called when this view should assign a size and position to all 188 * of its children. 189 * </td> 190 * </tr> 191 * <tr> 192 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 193 * <td>Called when the size of this view has changed. 194 * </td> 195 * </tr> 196 * 197 * <tr> 198 * <td>Drawing</td> 199 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 200 * <td>Called when the view should render its content. 201 * </td> 202 * </tr> 203 * 204 * <tr> 205 * <td rowspan="4">Event processing</td> 206 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 207 * <td>Called when a new key event occurs. 208 * </td> 209 * </tr> 210 * <tr> 211 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 212 * <td>Called when a key up event occurs. 213 * </td> 214 * </tr> 215 * <tr> 216 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 217 * <td>Called when a trackball motion event occurs. 218 * </td> 219 * </tr> 220 * <tr> 221 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 222 * <td>Called when a touch screen motion event occurs. 223 * </td> 224 * </tr> 225 * 226 * <tr> 227 * <td rowspan="2">Focus</td> 228 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 229 * <td>Called when the view gains or loses focus. 230 * </td> 231 * </tr> 232 * 233 * <tr> 234 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 235 * <td>Called when the window containing the view gains or loses focus. 236 * </td> 237 * </tr> 238 * 239 * <tr> 240 * <td rowspan="3">Attaching</td> 241 * <td><code>{@link #onAttachedToWindow()}</code></td> 242 * <td>Called when the view is attached to a window. 243 * </td> 244 * </tr> 245 * 246 * <tr> 247 * <td><code>{@link #onDetachedFromWindow}</code></td> 248 * <td>Called when the view is detached from its window. 249 * </td> 250 * </tr> 251 * 252 * <tr> 253 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 254 * <td>Called when the visibility of the window containing the view 255 * has changed. 256 * </td> 257 * </tr> 258 * </tbody> 259 * 260 * </table> 261 * </p> 262 * 263 * <a name="IDs"></a> 264 * <h3>IDs</h3> 265 * Views may have an integer id associated with them. These ids are typically 266 * assigned in the layout XML files, and are used to find specific views within 267 * the view tree. A common pattern is to: 268 * <ul> 269 * <li>Define a Button in the layout file and assign it a unique ID. 270 * <pre> 271 * <Button 272 * android:id="@+id/my_button" 273 * android:layout_width="wrap_content" 274 * android:layout_height="wrap_content" 275 * android:text="@string/my_button_text"/> 276 * </pre></li> 277 * <li>From the onCreate method of an Activity, find the Button 278 * <pre class="prettyprint"> 279 * Button myButton = (Button) findViewById(R.id.my_button); 280 * </pre></li> 281 * </ul> 282 * <p> 283 * View IDs need not be unique throughout the tree, but it is good practice to 284 * ensure that they are at least unique within the part of the tree you are 285 * searching. 286 * </p> 287 * 288 * <a name="Position"></a> 289 * <h3>Position</h3> 290 * <p> 291 * The geometry of a view is that of a rectangle. A view has a location, 292 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 293 * two dimensions, expressed as a width and a height. The unit for location 294 * and dimensions is the pixel. 295 * </p> 296 * 297 * <p> 298 * It is possible to retrieve the location of a view by invoking the methods 299 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 300 * coordinate of the rectangle representing the view. The latter returns the 301 * top, or Y, coordinate of the rectangle representing the view. These methods 302 * both return the location of the view relative to its parent. For instance, 303 * when getLeft() returns 20, that means the view is located 20 pixels to the 304 * right of the left edge of its direct parent. 305 * </p> 306 * 307 * <p> 308 * In addition, several convenience methods are offered to avoid unnecessary 309 * computations, namely {@link #getRight()} and {@link #getBottom()}. 310 * These methods return the coordinates of the right and bottom edges of the 311 * rectangle representing the view. For instance, calling {@link #getRight()} 312 * is similar to the following computation: <code>getLeft() + getWidth()</code> 313 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 314 * </p> 315 * 316 * <a name="SizePaddingMargins"></a> 317 * <h3>Size, padding and margins</h3> 318 * <p> 319 * The size of a view is expressed with a width and a height. A view actually 320 * possess two pairs of width and height values. 321 * </p> 322 * 323 * <p> 324 * The first pair is known as <em>measured width</em> and 325 * <em>measured height</em>. These dimensions define how big a view wants to be 326 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 327 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 328 * and {@link #getMeasuredHeight()}. 329 * </p> 330 * 331 * <p> 332 * The second pair is simply known as <em>width</em> and <em>height</em>, or 333 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 334 * dimensions define the actual size of the view on screen, at drawing time and 335 * after layout. These values may, but do not have to, be different from the 336 * measured width and height. The width and height can be obtained by calling 337 * {@link #getWidth()} and {@link #getHeight()}. 338 * </p> 339 * 340 * <p> 341 * To measure its dimensions, a view takes into account its padding. The padding 342 * is expressed in pixels for the left, top, right and bottom parts of the view. 343 * Padding can be used to offset the content of the view by a specific amount of 344 * pixels. For instance, a left padding of 2 will push the view's content by 345 * 2 pixels to the right of the left edge. Padding can be set using the 346 * {@link #setPadding(int, int, int, int)} method and queried by calling 347 * {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 348 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}. 349 * </p> 350 * 351 * <p> 352 * Even though a view can define a padding, it does not provide any support for 353 * margins. However, view groups provide such a support. Refer to 354 * {@link android.view.ViewGroup} and 355 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 356 * </p> 357 * 358 * <a name="Layout"></a> 359 * <h3>Layout</h3> 360 * <p> 361 * Layout is a two pass process: a measure pass and a layout pass. The measuring 362 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 363 * of the view tree. Each view pushes dimension specifications down the tree 364 * during the recursion. At the end of the measure pass, every view has stored 365 * its measurements. The second pass happens in 366 * {@link #layout(int,int,int,int)} and is also top-down. During 367 * this pass each parent is responsible for positioning all of its children 368 * using the sizes computed in the measure pass. 369 * </p> 370 * 371 * <p> 372 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 373 * {@link #getMeasuredHeight()} values must be set, along with those for all of 374 * that view's descendants. A view's measured width and measured height values 375 * must respect the constraints imposed by the view's parents. This guarantees 376 * that at the end of the measure pass, all parents accept all of their 377 * children's measurements. A parent view may call measure() more than once on 378 * its children. For example, the parent may measure each child once with 379 * unspecified dimensions to find out how big they want to be, then call 380 * measure() on them again with actual numbers if the sum of all the children's 381 * unconstrained sizes is too big or too small. 382 * </p> 383 * 384 * <p> 385 * The measure pass uses two classes to communicate dimensions. The 386 * {@link MeasureSpec} class is used by views to tell their parents how they 387 * want to be measured and positioned. The base LayoutParams class just 388 * describes how big the view wants to be for both width and height. For each 389 * dimension, it can specify one of: 390 * <ul> 391 * <li> an exact number 392 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 393 * (minus padding) 394 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 395 * enclose its content (plus padding). 396 * </ul> 397 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 398 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 399 * an X and Y value. 400 * </p> 401 * 402 * <p> 403 * MeasureSpecs are used to push requirements down the tree from parent to 404 * child. A MeasureSpec can be in one of three modes: 405 * <ul> 406 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 407 * of a child view. For example, a LinearLayout may call measure() on its child 408 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 409 * tall the child view wants to be given a width of 240 pixels. 410 * <li>EXACTLY: This is used by the parent to impose an exact size on the 411 * child. The child must use this size, and guarantee that all of its 412 * descendants will fit within this size. 413 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 414 * child. The child must gurantee that it and all of its descendants will fit 415 * within this size. 416 * </ul> 417 * </p> 418 * 419 * <p> 420 * To intiate a layout, call {@link #requestLayout}. This method is typically 421 * called by a view on itself when it believes that is can no longer fit within 422 * its current bounds. 423 * </p> 424 * 425 * <a name="Drawing"></a> 426 * <h3>Drawing</h3> 427 * <p> 428 * Drawing is handled by walking the tree and rendering each view that 429 * intersects the the invalid region. Because the tree is traversed in-order, 430 * this means that parents will draw before (i.e., behind) their children, with 431 * siblings drawn in the order they appear in the tree. 432 * If you set a background drawable for a View, then the View will draw it for you 433 * before calling back to its <code>onDraw()</code> method. 434 * </p> 435 * 436 * <p> 437 * Note that the framework will not draw views that are not in the invalid region. 438 * </p> 439 * 440 * <p> 441 * To force a view to draw, call {@link #invalidate()}. 442 * </p> 443 * 444 * <a name="EventHandlingThreading"></a> 445 * <h3>Event Handling and Threading</h3> 446 * <p> 447 * The basic cycle of a view is as follows: 448 * <ol> 449 * <li>An event comes in and is dispatched to the appropriate view. The view 450 * handles the event and notifies any listeners.</li> 451 * <li>If in the course of processing the event, the view's bounds may need 452 * to be changed, the view will call {@link #requestLayout()}.</li> 453 * <li>Similarly, if in the course of processing the event the view's appearance 454 * may need to be changed, the view will call {@link #invalidate()}.</li> 455 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 456 * the framework will take care of measuring, laying out, and drawing the tree 457 * as appropriate.</li> 458 * </ol> 459 * </p> 460 * 461 * <p><em>Note: The entire view tree is single threaded. You must always be on 462 * the UI thread when calling any method on any view.</em> 463 * If you are doing work on other threads and want to update the state of a view 464 * from that thread, you should use a {@link Handler}. 465 * </p> 466 * 467 * <a name="FocusHandling"></a> 468 * <h3>Focus Handling</h3> 469 * <p> 470 * The framework will handle routine focus movement in response to user input. 471 * This includes changing the focus as views are removed or hidden, or as new 472 * views become available. Views indicate their willingness to take focus 473 * through the {@link #isFocusable} method. To change whether a view can take 474 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 475 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 476 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 477 * </p> 478 * <p> 479 * Focus movement is based on an algorithm which finds the nearest neighbor in a 480 * given direction. In rare cases, the default algorithm may not match the 481 * intended behavior of the developer. In these situations, you can provide 482 * explicit overrides by using these XML attributes in the layout file: 483 * <pre> 484 * nextFocusDown 485 * nextFocusLeft 486 * nextFocusRight 487 * nextFocusUp 488 * </pre> 489 * </p> 490 * 491 * 492 * <p> 493 * To get a particular view to take focus, call {@link #requestFocus()}. 494 * </p> 495 * 496 * <a name="TouchMode"></a> 497 * <h3>Touch Mode</h3> 498 * <p> 499 * When a user is navigating a user interface via directional keys such as a D-pad, it is 500 * necessary to give focus to actionable items such as buttons so the user can see 501 * what will take input. If the device has touch capabilities, however, and the user 502 * begins interacting with the interface by touching it, it is no longer necessary to 503 * always highlight, or give focus to, a particular view. This motivates a mode 504 * for interaction named 'touch mode'. 505 * </p> 506 * <p> 507 * For a touch capable device, once the user touches the screen, the device 508 * will enter touch mode. From this point onward, only views for which 509 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 510 * Other views that are touchable, like buttons, will not take focus when touched; they will 511 * only fire the on click listeners. 512 * </p> 513 * <p> 514 * Any time a user hits a directional key, such as a D-pad direction, the view device will 515 * exit touch mode, and find a view to take focus, so that the user may resume interacting 516 * with the user interface without touching the screen again. 517 * </p> 518 * <p> 519 * The touch mode state is maintained across {@link android.app.Activity}s. Call 520 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 521 * </p> 522 * 523 * <a name="Scrolling"></a> 524 * <h3>Scrolling</h3> 525 * <p> 526 * The framework provides basic support for views that wish to internally 527 * scroll their content. This includes keeping track of the X and Y scroll 528 * offset as well as mechanisms for drawing scrollbars. See 529 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 530 * {@link #awakenScrollBars()} for more details. 531 * </p> 532 * 533 * <a name="Tags"></a> 534 * <h3>Tags</h3> 535 * <p> 536 * Unlike IDs, tags are not used to identify views. Tags are essentially an 537 * extra piece of information that can be associated with a view. They are most 538 * often used as a convenience to store data related to views in the views 539 * themselves rather than by putting them in a separate structure. 540 * </p> 541 * 542 * <a name="Animation"></a> 543 * <h3>Animation</h3> 544 * <p> 545 * You can attach an {@link Animation} object to a view using 546 * {@link #setAnimation(Animation)} or 547 * {@link #startAnimation(Animation)}. The animation can alter the scale, 548 * rotation, translation and alpha of a view over time. If the animation is 549 * attached to a view that has children, the animation will affect the entire 550 * subtree rooted by that node. When an animation is started, the framework will 551 * take care of redrawing the appropriate views until the animation completes. 552 * </p> 553 * <p> 554 * Starting with Android 3.0, the preferred way of animating views is to use the 555 * {@link android.animation} package APIs. 556 * </p> 557 * 558 * <a name="Security"></a> 559 * <h3>Security</h3> 560 * <p> 561 * Sometimes it is essential that an application be able to verify that an action 562 * is being performed with the full knowledge and consent of the user, such as 563 * granting a permission request, making a purchase or clicking on an advertisement. 564 * Unfortunately, a malicious application could try to spoof the user into 565 * performing these actions, unaware, by concealing the intended purpose of the view. 566 * As a remedy, the framework offers a touch filtering mechanism that can be used to 567 * improve the security of views that provide access to sensitive functionality. 568 * </p><p> 569 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 570 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 571 * will discard touches that are received whenever the view's window is obscured by 572 * another visible window. As a result, the view will not receive touches whenever a 573 * toast, dialog or other window appears above the view's window. 574 * </p><p> 575 * For more fine-grained control over security, consider overriding the 576 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 577 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 578 * </p> 579 * 580 * @attr ref android.R.styleable#View_alpha 581 * @attr ref android.R.styleable#View_background 582 * @attr ref android.R.styleable#View_clickable 583 * @attr ref android.R.styleable#View_contentDescription 584 * @attr ref android.R.styleable#View_drawingCacheQuality 585 * @attr ref android.R.styleable#View_duplicateParentState 586 * @attr ref android.R.styleable#View_id 587 * @attr ref android.R.styleable#View_fadingEdge 588 * @attr ref android.R.styleable#View_fadingEdgeLength 589 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 590 * @attr ref android.R.styleable#View_fitsSystemWindows 591 * @attr ref android.R.styleable#View_isScrollContainer 592 * @attr ref android.R.styleable#View_focusable 593 * @attr ref android.R.styleable#View_focusableInTouchMode 594 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 595 * @attr ref android.R.styleable#View_keepScreenOn 596 * @attr ref android.R.styleable#View_layerType 597 * @attr ref android.R.styleable#View_longClickable 598 * @attr ref android.R.styleable#View_minHeight 599 * @attr ref android.R.styleable#View_minWidth 600 * @attr ref android.R.styleable#View_nextFocusDown 601 * @attr ref android.R.styleable#View_nextFocusLeft 602 * @attr ref android.R.styleable#View_nextFocusRight 603 * @attr ref android.R.styleable#View_nextFocusUp 604 * @attr ref android.R.styleable#View_onClick 605 * @attr ref android.R.styleable#View_padding 606 * @attr ref android.R.styleable#View_paddingBottom 607 * @attr ref android.R.styleable#View_paddingLeft 608 * @attr ref android.R.styleable#View_paddingRight 609 * @attr ref android.R.styleable#View_paddingTop 610 * @attr ref android.R.styleable#View_saveEnabled 611 * @attr ref android.R.styleable#View_rotation 612 * @attr ref android.R.styleable#View_rotationX 613 * @attr ref android.R.styleable#View_rotationY 614 * @attr ref android.R.styleable#View_scaleX 615 * @attr ref android.R.styleable#View_scaleY 616 * @attr ref android.R.styleable#View_scrollX 617 * @attr ref android.R.styleable#View_scrollY 618 * @attr ref android.R.styleable#View_scrollbarSize 619 * @attr ref android.R.styleable#View_scrollbarStyle 620 * @attr ref android.R.styleable#View_scrollbars 621 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 622 * @attr ref android.R.styleable#View_scrollbarFadeDuration 623 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 624 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 625 * @attr ref android.R.styleable#View_scrollbarThumbVertical 626 * @attr ref android.R.styleable#View_scrollbarTrackVertical 627 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 628 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 629 * @attr ref android.R.styleable#View_soundEffectsEnabled 630 * @attr ref android.R.styleable#View_tag 631 * @attr ref android.R.styleable#View_transformPivotX 632 * @attr ref android.R.styleable#View_transformPivotY 633 * @attr ref android.R.styleable#View_translationX 634 * @attr ref android.R.styleable#View_translationY 635 * @attr ref android.R.styleable#View_visibility 636 * 637 * @see android.view.ViewGroup 638 */ 639public class View implements Drawable.Callback2, KeyEvent.Callback, AccessibilityEventSource { 640 private static final boolean DBG = false; 641 642 /** 643 * The logging tag used by this class with android.util.Log. 644 */ 645 protected static final String VIEW_LOG_TAG = "View"; 646 647 /** 648 * Used to mark a View that has no ID. 649 */ 650 public static final int NO_ID = -1; 651 652 /** 653 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 654 * calling setFlags. 655 */ 656 private static final int NOT_FOCUSABLE = 0x00000000; 657 658 /** 659 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 660 * setFlags. 661 */ 662 private static final int FOCUSABLE = 0x00000001; 663 664 /** 665 * Mask for use with setFlags indicating bits used for focus. 666 */ 667 private static final int FOCUSABLE_MASK = 0x00000001; 668 669 /** 670 * This view will adjust its padding to fit sytem windows (e.g. status bar) 671 */ 672 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 673 674 /** 675 * This view is visible. Use with {@link #setVisibility(int)}. 676 */ 677 public static final int VISIBLE = 0x00000000; 678 679 /** 680 * This view is invisible, but it still takes up space for layout purposes. 681 * Use with {@link #setVisibility(int)}. 682 */ 683 public static final int INVISIBLE = 0x00000004; 684 685 /** 686 * This view is invisible, and it doesn't take any space for layout 687 * purposes. Use with {@link #setVisibility(int)}. 688 */ 689 public static final int GONE = 0x00000008; 690 691 /** 692 * Mask for use with setFlags indicating bits used for visibility. 693 * {@hide} 694 */ 695 static final int VISIBILITY_MASK = 0x0000000C; 696 697 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 698 699 /** 700 * This view is enabled. Intrepretation varies by subclass. 701 * Use with ENABLED_MASK when calling setFlags. 702 * {@hide} 703 */ 704 static final int ENABLED = 0x00000000; 705 706 /** 707 * This view is disabled. Intrepretation varies by subclass. 708 * Use with ENABLED_MASK when calling setFlags. 709 * {@hide} 710 */ 711 static final int DISABLED = 0x00000020; 712 713 /** 714 * Mask for use with setFlags indicating bits used for indicating whether 715 * this view is enabled 716 * {@hide} 717 */ 718 static final int ENABLED_MASK = 0x00000020; 719 720 /** 721 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 722 * called and further optimizations will be performed. It is okay to have 723 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 724 * {@hide} 725 */ 726 static final int WILL_NOT_DRAW = 0x00000080; 727 728 /** 729 * Mask for use with setFlags indicating bits used for indicating whether 730 * this view is will draw 731 * {@hide} 732 */ 733 static final int DRAW_MASK = 0x00000080; 734 735 /** 736 * <p>This view doesn't show scrollbars.</p> 737 * {@hide} 738 */ 739 static final int SCROLLBARS_NONE = 0x00000000; 740 741 /** 742 * <p>This view shows horizontal scrollbars.</p> 743 * {@hide} 744 */ 745 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 746 747 /** 748 * <p>This view shows vertical scrollbars.</p> 749 * {@hide} 750 */ 751 static final int SCROLLBARS_VERTICAL = 0x00000200; 752 753 /** 754 * <p>Mask for use with setFlags indicating bits used for indicating which 755 * scrollbars are enabled.</p> 756 * {@hide} 757 */ 758 static final int SCROLLBARS_MASK = 0x00000300; 759 760 /** 761 * Indicates that the view should filter touches when its window is obscured. 762 * Refer to the class comments for more information about this security feature. 763 * {@hide} 764 */ 765 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 766 767 // note flag value 0x00000800 is now available for next flags... 768 769 /** 770 * <p>This view doesn't show fading edges.</p> 771 * {@hide} 772 */ 773 static final int FADING_EDGE_NONE = 0x00000000; 774 775 /** 776 * <p>This view shows horizontal fading edges.</p> 777 * {@hide} 778 */ 779 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 780 781 /** 782 * <p>This view shows vertical fading edges.</p> 783 * {@hide} 784 */ 785 static final int FADING_EDGE_VERTICAL = 0x00002000; 786 787 /** 788 * <p>Mask for use with setFlags indicating bits used for indicating which 789 * fading edges are enabled.</p> 790 * {@hide} 791 */ 792 static final int FADING_EDGE_MASK = 0x00003000; 793 794 /** 795 * <p>Indicates this view can be clicked. When clickable, a View reacts 796 * to clicks by notifying the OnClickListener.<p> 797 * {@hide} 798 */ 799 static final int CLICKABLE = 0x00004000; 800 801 /** 802 * <p>Indicates this view is caching its drawing into a bitmap.</p> 803 * {@hide} 804 */ 805 static final int DRAWING_CACHE_ENABLED = 0x00008000; 806 807 /** 808 * <p>Indicates that no icicle should be saved for this view.<p> 809 * {@hide} 810 */ 811 static final int SAVE_DISABLED = 0x000010000; 812 813 /** 814 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 815 * property.</p> 816 * {@hide} 817 */ 818 static final int SAVE_DISABLED_MASK = 0x000010000; 819 820 /** 821 * <p>Indicates that no drawing cache should ever be created for this view.<p> 822 * {@hide} 823 */ 824 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 825 826 /** 827 * <p>Indicates this view can take / keep focus when int touch mode.</p> 828 * {@hide} 829 */ 830 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 831 832 /** 833 * <p>Enables low quality mode for the drawing cache.</p> 834 */ 835 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 836 837 /** 838 * <p>Enables high quality mode for the drawing cache.</p> 839 */ 840 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 841 842 /** 843 * <p>Enables automatic quality mode for the drawing cache.</p> 844 */ 845 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 846 847 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 848 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 849 }; 850 851 /** 852 * <p>Mask for use with setFlags indicating bits used for the cache 853 * quality property.</p> 854 * {@hide} 855 */ 856 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 857 858 /** 859 * <p> 860 * Indicates this view can be long clicked. When long clickable, a View 861 * reacts to long clicks by notifying the OnLongClickListener or showing a 862 * context menu. 863 * </p> 864 * {@hide} 865 */ 866 static final int LONG_CLICKABLE = 0x00200000; 867 868 /** 869 * <p>Indicates that this view gets its drawable states from its direct parent 870 * and ignores its original internal states.</p> 871 * 872 * @hide 873 */ 874 static final int DUPLICATE_PARENT_STATE = 0x00400000; 875 876 /** 877 * The scrollbar style to display the scrollbars inside the content area, 878 * without increasing the padding. The scrollbars will be overlaid with 879 * translucency on the view's content. 880 */ 881 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 882 883 /** 884 * The scrollbar style to display the scrollbars inside the padded area, 885 * increasing the padding of the view. The scrollbars will not overlap the 886 * content area of the view. 887 */ 888 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 889 890 /** 891 * The scrollbar style to display the scrollbars at the edge of the view, 892 * without increasing the padding. The scrollbars will be overlaid with 893 * translucency. 894 */ 895 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 896 897 /** 898 * The scrollbar style to display the scrollbars at the edge of the view, 899 * increasing the padding of the view. The scrollbars will only overlap the 900 * background, if any. 901 */ 902 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 903 904 /** 905 * Mask to check if the scrollbar style is overlay or inset. 906 * {@hide} 907 */ 908 static final int SCROLLBARS_INSET_MASK = 0x01000000; 909 910 /** 911 * Mask to check if the scrollbar style is inside or outside. 912 * {@hide} 913 */ 914 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 915 916 /** 917 * Mask for scrollbar style. 918 * {@hide} 919 */ 920 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 921 922 /** 923 * View flag indicating that the screen should remain on while the 924 * window containing this view is visible to the user. This effectively 925 * takes care of automatically setting the WindowManager's 926 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 927 */ 928 public static final int KEEP_SCREEN_ON = 0x04000000; 929 930 /** 931 * View flag indicating whether this view should have sound effects enabled 932 * for events such as clicking and touching. 933 */ 934 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 935 936 /** 937 * View flag indicating whether this view should have haptic feedback 938 * enabled for events such as long presses. 939 */ 940 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 941 942 /** 943 * <p>Indicates that the view hierarchy should stop saving state when 944 * it reaches this view. If state saving is initiated immediately at 945 * the view, it will be allowed. 946 * {@hide} 947 */ 948 static final int PARENT_SAVE_DISABLED = 0x20000000; 949 950 /** 951 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 952 * {@hide} 953 */ 954 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 955 956 /** 957 * Horizontal direction of this view is from Left to Right. 958 * Use with {@link #setLayoutDirection}. 959 * {@hide} 960 */ 961 public static final int LAYOUT_DIRECTION_LTR = 0x00000000; 962 963 /** 964 * Horizontal direction of this view is from Right to Left. 965 * Use with {@link #setLayoutDirection}. 966 * {@hide} 967 */ 968 public static final int LAYOUT_DIRECTION_RTL = 0x40000000; 969 970 /** 971 * Horizontal direction of this view is inherited from its parent. 972 * Use with {@link #setLayoutDirection}. 973 * {@hide} 974 */ 975 public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000; 976 977 /** 978 * Horizontal direction of this view is from deduced from the default language 979 * script for the locale. Use with {@link #setLayoutDirection}. 980 * {@hide} 981 */ 982 public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000; 983 984 /** 985 * Mask for use with setFlags indicating bits used for horizontalDirection. 986 * {@hide} 987 */ 988 static final int LAYOUT_DIRECTION_MASK = 0xC0000000; 989 990 /* 991 * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct 992 * flag value. 993 * {@hide} 994 */ 995 private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR, 996 LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE}; 997 998 /** 999 * Default horizontalDirection. 1000 * {@hide} 1001 */ 1002 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1003 1004 /** 1005 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1006 * should add all focusable Views regardless if they are focusable in touch mode. 1007 */ 1008 public static final int FOCUSABLES_ALL = 0x00000000; 1009 1010 /** 1011 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1012 * should add only Views focusable in touch mode. 1013 */ 1014 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1015 1016 /** 1017 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1018 * item. 1019 */ 1020 public static final int FOCUS_BACKWARD = 0x00000001; 1021 1022 /** 1023 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1024 * item. 1025 */ 1026 public static final int FOCUS_FORWARD = 0x00000002; 1027 1028 /** 1029 * Use with {@link #focusSearch(int)}. Move focus to the left. 1030 */ 1031 public static final int FOCUS_LEFT = 0x00000011; 1032 1033 /** 1034 * Use with {@link #focusSearch(int)}. Move focus up. 1035 */ 1036 public static final int FOCUS_UP = 0x00000021; 1037 1038 /** 1039 * Use with {@link #focusSearch(int)}. Move focus to the right. 1040 */ 1041 public static final int FOCUS_RIGHT = 0x00000042; 1042 1043 /** 1044 * Use with {@link #focusSearch(int)}. Move focus down. 1045 */ 1046 public static final int FOCUS_DOWN = 0x00000082; 1047 1048 /** 1049 * Bits of {@link #getMeasuredWidthAndState()} and 1050 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1051 */ 1052 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1053 1054 /** 1055 * Bits of {@link #getMeasuredWidthAndState()} and 1056 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1057 */ 1058 public static final int MEASURED_STATE_MASK = 0xff000000; 1059 1060 /** 1061 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1062 * for functions that combine both width and height into a single int, 1063 * such as {@link #getMeasuredState()} and the childState argument of 1064 * {@link #resolveSizeAndState(int, int, int)}. 1065 */ 1066 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1067 1068 /** 1069 * Bit of {@link #getMeasuredWidthAndState()} and 1070 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1071 * is smaller that the space the view would like to have. 1072 */ 1073 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1074 1075 /** 1076 * Base View state sets 1077 */ 1078 // Singles 1079 /** 1080 * Indicates the view has no states set. States are used with 1081 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1082 * view depending on its state. 1083 * 1084 * @see android.graphics.drawable.Drawable 1085 * @see #getDrawableState() 1086 */ 1087 protected static final int[] EMPTY_STATE_SET; 1088 /** 1089 * Indicates the view is enabled. States are used with 1090 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1091 * view depending on its state. 1092 * 1093 * @see android.graphics.drawable.Drawable 1094 * @see #getDrawableState() 1095 */ 1096 protected static final int[] ENABLED_STATE_SET; 1097 /** 1098 * Indicates the view is focused. States are used with 1099 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1100 * view depending on its state. 1101 * 1102 * @see android.graphics.drawable.Drawable 1103 * @see #getDrawableState() 1104 */ 1105 protected static final int[] FOCUSED_STATE_SET; 1106 /** 1107 * Indicates the view is selected. States are used with 1108 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1109 * view depending on its state. 1110 * 1111 * @see android.graphics.drawable.Drawable 1112 * @see #getDrawableState() 1113 */ 1114 protected static final int[] SELECTED_STATE_SET; 1115 /** 1116 * Indicates the view is pressed. States are used with 1117 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1118 * view depending on its state. 1119 * 1120 * @see android.graphics.drawable.Drawable 1121 * @see #getDrawableState() 1122 * @hide 1123 */ 1124 protected static final int[] PRESSED_STATE_SET; 1125 /** 1126 * Indicates the view's window has focus. States are used with 1127 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1128 * view depending on its state. 1129 * 1130 * @see android.graphics.drawable.Drawable 1131 * @see #getDrawableState() 1132 */ 1133 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1134 // Doubles 1135 /** 1136 * Indicates the view is enabled and has the focus. 1137 * 1138 * @see #ENABLED_STATE_SET 1139 * @see #FOCUSED_STATE_SET 1140 */ 1141 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1142 /** 1143 * Indicates the view is enabled and selected. 1144 * 1145 * @see #ENABLED_STATE_SET 1146 * @see #SELECTED_STATE_SET 1147 */ 1148 protected static final int[] ENABLED_SELECTED_STATE_SET; 1149 /** 1150 * Indicates the view is enabled and that its window has focus. 1151 * 1152 * @see #ENABLED_STATE_SET 1153 * @see #WINDOW_FOCUSED_STATE_SET 1154 */ 1155 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1156 /** 1157 * Indicates the view is focused and selected. 1158 * 1159 * @see #FOCUSED_STATE_SET 1160 * @see #SELECTED_STATE_SET 1161 */ 1162 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1163 /** 1164 * Indicates the view has the focus and that its window has the focus. 1165 * 1166 * @see #FOCUSED_STATE_SET 1167 * @see #WINDOW_FOCUSED_STATE_SET 1168 */ 1169 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1170 /** 1171 * Indicates the view is selected and that its window has the focus. 1172 * 1173 * @see #SELECTED_STATE_SET 1174 * @see #WINDOW_FOCUSED_STATE_SET 1175 */ 1176 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1177 // Triples 1178 /** 1179 * Indicates the view is enabled, focused and selected. 1180 * 1181 * @see #ENABLED_STATE_SET 1182 * @see #FOCUSED_STATE_SET 1183 * @see #SELECTED_STATE_SET 1184 */ 1185 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1186 /** 1187 * Indicates the view is enabled, focused and its window has the focus. 1188 * 1189 * @see #ENABLED_STATE_SET 1190 * @see #FOCUSED_STATE_SET 1191 * @see #WINDOW_FOCUSED_STATE_SET 1192 */ 1193 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1194 /** 1195 * Indicates the view is enabled, selected and its window has the focus. 1196 * 1197 * @see #ENABLED_STATE_SET 1198 * @see #SELECTED_STATE_SET 1199 * @see #WINDOW_FOCUSED_STATE_SET 1200 */ 1201 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1202 /** 1203 * Indicates the view is focused, selected and its window has the focus. 1204 * 1205 * @see #FOCUSED_STATE_SET 1206 * @see #SELECTED_STATE_SET 1207 * @see #WINDOW_FOCUSED_STATE_SET 1208 */ 1209 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1210 /** 1211 * Indicates the view is enabled, focused, selected and its window 1212 * has the focus. 1213 * 1214 * @see #ENABLED_STATE_SET 1215 * @see #FOCUSED_STATE_SET 1216 * @see #SELECTED_STATE_SET 1217 * @see #WINDOW_FOCUSED_STATE_SET 1218 */ 1219 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1220 /** 1221 * Indicates the view is pressed and its window has the focus. 1222 * 1223 * @see #PRESSED_STATE_SET 1224 * @see #WINDOW_FOCUSED_STATE_SET 1225 */ 1226 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1227 /** 1228 * Indicates the view is pressed and selected. 1229 * 1230 * @see #PRESSED_STATE_SET 1231 * @see #SELECTED_STATE_SET 1232 */ 1233 protected static final int[] PRESSED_SELECTED_STATE_SET; 1234 /** 1235 * Indicates the view is pressed, selected and its window has the focus. 1236 * 1237 * @see #PRESSED_STATE_SET 1238 * @see #SELECTED_STATE_SET 1239 * @see #WINDOW_FOCUSED_STATE_SET 1240 */ 1241 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1242 /** 1243 * Indicates the view is pressed and focused. 1244 * 1245 * @see #PRESSED_STATE_SET 1246 * @see #FOCUSED_STATE_SET 1247 */ 1248 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1249 /** 1250 * Indicates the view is pressed, focused and its window has the focus. 1251 * 1252 * @see #PRESSED_STATE_SET 1253 * @see #FOCUSED_STATE_SET 1254 * @see #WINDOW_FOCUSED_STATE_SET 1255 */ 1256 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1257 /** 1258 * Indicates the view is pressed, focused and selected. 1259 * 1260 * @see #PRESSED_STATE_SET 1261 * @see #SELECTED_STATE_SET 1262 * @see #FOCUSED_STATE_SET 1263 */ 1264 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1265 /** 1266 * Indicates the view is pressed, focused, selected and its window has the focus. 1267 * 1268 * @see #PRESSED_STATE_SET 1269 * @see #FOCUSED_STATE_SET 1270 * @see #SELECTED_STATE_SET 1271 * @see #WINDOW_FOCUSED_STATE_SET 1272 */ 1273 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1274 /** 1275 * Indicates the view is pressed and enabled. 1276 * 1277 * @see #PRESSED_STATE_SET 1278 * @see #ENABLED_STATE_SET 1279 */ 1280 protected static final int[] PRESSED_ENABLED_STATE_SET; 1281 /** 1282 * Indicates the view is pressed, enabled and its window has the focus. 1283 * 1284 * @see #PRESSED_STATE_SET 1285 * @see #ENABLED_STATE_SET 1286 * @see #WINDOW_FOCUSED_STATE_SET 1287 */ 1288 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1289 /** 1290 * Indicates the view is pressed, enabled and selected. 1291 * 1292 * @see #PRESSED_STATE_SET 1293 * @see #ENABLED_STATE_SET 1294 * @see #SELECTED_STATE_SET 1295 */ 1296 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1297 /** 1298 * Indicates the view is pressed, enabled, selected and its window has the 1299 * focus. 1300 * 1301 * @see #PRESSED_STATE_SET 1302 * @see #ENABLED_STATE_SET 1303 * @see #SELECTED_STATE_SET 1304 * @see #WINDOW_FOCUSED_STATE_SET 1305 */ 1306 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1307 /** 1308 * Indicates the view is pressed, enabled and focused. 1309 * 1310 * @see #PRESSED_STATE_SET 1311 * @see #ENABLED_STATE_SET 1312 * @see #FOCUSED_STATE_SET 1313 */ 1314 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1315 /** 1316 * Indicates the view is pressed, enabled, focused and its window has the 1317 * focus. 1318 * 1319 * @see #PRESSED_STATE_SET 1320 * @see #ENABLED_STATE_SET 1321 * @see #FOCUSED_STATE_SET 1322 * @see #WINDOW_FOCUSED_STATE_SET 1323 */ 1324 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1325 /** 1326 * Indicates the view is pressed, enabled, focused and selected. 1327 * 1328 * @see #PRESSED_STATE_SET 1329 * @see #ENABLED_STATE_SET 1330 * @see #SELECTED_STATE_SET 1331 * @see #FOCUSED_STATE_SET 1332 */ 1333 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1334 /** 1335 * Indicates the view is pressed, enabled, focused, selected and its window 1336 * has the focus. 1337 * 1338 * @see #PRESSED_STATE_SET 1339 * @see #ENABLED_STATE_SET 1340 * @see #SELECTED_STATE_SET 1341 * @see #FOCUSED_STATE_SET 1342 * @see #WINDOW_FOCUSED_STATE_SET 1343 */ 1344 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1345 1346 /** 1347 * The order here is very important to {@link #getDrawableState()} 1348 */ 1349 private static final int[][] VIEW_STATE_SETS; 1350 1351 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1352 static final int VIEW_STATE_SELECTED = 1 << 1; 1353 static final int VIEW_STATE_FOCUSED = 1 << 2; 1354 static final int VIEW_STATE_ENABLED = 1 << 3; 1355 static final int VIEW_STATE_PRESSED = 1 << 4; 1356 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1357 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1358 static final int VIEW_STATE_HOVERED = 1 << 7; 1359 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1360 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1361 1362 static final int[] VIEW_STATE_IDS = new int[] { 1363 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1364 R.attr.state_selected, VIEW_STATE_SELECTED, 1365 R.attr.state_focused, VIEW_STATE_FOCUSED, 1366 R.attr.state_enabled, VIEW_STATE_ENABLED, 1367 R.attr.state_pressed, VIEW_STATE_PRESSED, 1368 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1369 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1370 R.attr.state_hovered, VIEW_STATE_HOVERED, 1371 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1372 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED, 1373 }; 1374 1375 static { 1376 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1377 throw new IllegalStateException( 1378 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1379 } 1380 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1381 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1382 int viewState = R.styleable.ViewDrawableStates[i]; 1383 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1384 if (VIEW_STATE_IDS[j] == viewState) { 1385 orderedIds[i * 2] = viewState; 1386 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1387 } 1388 } 1389 } 1390 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1391 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1392 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1393 int numBits = Integer.bitCount(i); 1394 int[] set = new int[numBits]; 1395 int pos = 0; 1396 for (int j = 0; j < orderedIds.length; j += 2) { 1397 if ((i & orderedIds[j+1]) != 0) { 1398 set[pos++] = orderedIds[j]; 1399 } 1400 } 1401 VIEW_STATE_SETS[i] = set; 1402 } 1403 1404 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1405 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1406 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1407 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1408 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1409 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1410 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1411 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1412 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1413 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1414 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1415 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1416 | VIEW_STATE_FOCUSED]; 1417 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1418 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1419 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1420 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1421 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1422 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1423 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1424 | VIEW_STATE_ENABLED]; 1425 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1426 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1427 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1428 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1429 | VIEW_STATE_ENABLED]; 1430 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1431 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1432 | VIEW_STATE_ENABLED]; 1433 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1434 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1435 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1436 1437 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1438 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1439 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1440 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1441 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1442 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1443 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1444 | VIEW_STATE_PRESSED]; 1445 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1446 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1447 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1448 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1449 | VIEW_STATE_PRESSED]; 1450 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1451 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1452 | VIEW_STATE_PRESSED]; 1453 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1454 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1455 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1456 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1457 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1458 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1459 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1460 | VIEW_STATE_PRESSED]; 1461 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1462 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1463 | VIEW_STATE_PRESSED]; 1464 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1465 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1466 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1467 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1468 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1469 | VIEW_STATE_PRESSED]; 1470 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1471 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1472 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1473 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1474 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1475 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1476 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1477 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1478 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1479 | VIEW_STATE_PRESSED]; 1480 } 1481 1482 /** 1483 * Temporary Rect currently for use in setBackground(). This will probably 1484 * be extended in the future to hold our own class with more than just 1485 * a Rect. :) 1486 */ 1487 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1488 1489 /** 1490 * Map used to store views' tags. 1491 */ 1492 private static WeakHashMap<View, SparseArray<Object>> sTags; 1493 1494 /** 1495 * Lock used to access sTags. 1496 */ 1497 private static final Object sTagsLock = new Object(); 1498 1499 /** 1500 * The next available accessiiblity id. 1501 */ 1502 private static int sNextAccessibilityViewId; 1503 1504 /** 1505 * The animation currently associated with this view. 1506 * @hide 1507 */ 1508 protected Animation mCurrentAnimation = null; 1509 1510 /** 1511 * Width as measured during measure pass. 1512 * {@hide} 1513 */ 1514 @ViewDebug.ExportedProperty(category = "measurement") 1515 int mMeasuredWidth; 1516 1517 /** 1518 * Height as measured during measure pass. 1519 * {@hide} 1520 */ 1521 @ViewDebug.ExportedProperty(category = "measurement") 1522 int mMeasuredHeight; 1523 1524 /** 1525 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1526 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1527 * its display list. This flag, used only when hw accelerated, allows us to clear the 1528 * flag while retaining this information until it's needed (at getDisplayList() time and 1529 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1530 * 1531 * {@hide} 1532 */ 1533 boolean mRecreateDisplayList = false; 1534 1535 /** 1536 * The view's identifier. 1537 * {@hide} 1538 * 1539 * @see #setId(int) 1540 * @see #getId() 1541 */ 1542 @ViewDebug.ExportedProperty(resolveId = true) 1543 int mID = NO_ID; 1544 1545 /** 1546 * The stable ID of this view for accessibility porposes. 1547 */ 1548 int mAccessibilityViewId = NO_ID; 1549 1550 /** 1551 * The view's tag. 1552 * {@hide} 1553 * 1554 * @see #setTag(Object) 1555 * @see #getTag() 1556 */ 1557 protected Object mTag; 1558 1559 // for mPrivateFlags: 1560 /** {@hide} */ 1561 static final int WANTS_FOCUS = 0x00000001; 1562 /** {@hide} */ 1563 static final int FOCUSED = 0x00000002; 1564 /** {@hide} */ 1565 static final int SELECTED = 0x00000004; 1566 /** {@hide} */ 1567 static final int IS_ROOT_NAMESPACE = 0x00000008; 1568 /** {@hide} */ 1569 static final int HAS_BOUNDS = 0x00000010; 1570 /** {@hide} */ 1571 static final int DRAWN = 0x00000020; 1572 /** 1573 * When this flag is set, this view is running an animation on behalf of its 1574 * children and should therefore not cancel invalidate requests, even if they 1575 * lie outside of this view's bounds. 1576 * 1577 * {@hide} 1578 */ 1579 static final int DRAW_ANIMATION = 0x00000040; 1580 /** {@hide} */ 1581 static final int SKIP_DRAW = 0x00000080; 1582 /** {@hide} */ 1583 static final int ONLY_DRAWS_BACKGROUND = 0x00000100; 1584 /** {@hide} */ 1585 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1586 /** {@hide} */ 1587 static final int DRAWABLE_STATE_DIRTY = 0x00000400; 1588 /** {@hide} */ 1589 static final int MEASURED_DIMENSION_SET = 0x00000800; 1590 /** {@hide} */ 1591 static final int FORCE_LAYOUT = 0x00001000; 1592 /** {@hide} */ 1593 static final int LAYOUT_REQUIRED = 0x00002000; 1594 1595 private static final int PRESSED = 0x00004000; 1596 1597 /** {@hide} */ 1598 static final int DRAWING_CACHE_VALID = 0x00008000; 1599 /** 1600 * Flag used to indicate that this view should be drawn once more (and only once 1601 * more) after its animation has completed. 1602 * {@hide} 1603 */ 1604 static final int ANIMATION_STARTED = 0x00010000; 1605 1606 private static final int SAVE_STATE_CALLED = 0x00020000; 1607 1608 /** 1609 * Indicates that the View returned true when onSetAlpha() was called and that 1610 * the alpha must be restored. 1611 * {@hide} 1612 */ 1613 static final int ALPHA_SET = 0x00040000; 1614 1615 /** 1616 * Set by {@link #setScrollContainer(boolean)}. 1617 */ 1618 static final int SCROLL_CONTAINER = 0x00080000; 1619 1620 /** 1621 * Set by {@link #setScrollContainer(boolean)}. 1622 */ 1623 static final int SCROLL_CONTAINER_ADDED = 0x00100000; 1624 1625 /** 1626 * View flag indicating whether this view was invalidated (fully or partially.) 1627 * 1628 * @hide 1629 */ 1630 static final int DIRTY = 0x00200000; 1631 1632 /** 1633 * View flag indicating whether this view was invalidated by an opaque 1634 * invalidate request. 1635 * 1636 * @hide 1637 */ 1638 static final int DIRTY_OPAQUE = 0x00400000; 1639 1640 /** 1641 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}. 1642 * 1643 * @hide 1644 */ 1645 static final int DIRTY_MASK = 0x00600000; 1646 1647 /** 1648 * Indicates whether the background is opaque. 1649 * 1650 * @hide 1651 */ 1652 static final int OPAQUE_BACKGROUND = 0x00800000; 1653 1654 /** 1655 * Indicates whether the scrollbars are opaque. 1656 * 1657 * @hide 1658 */ 1659 static final int OPAQUE_SCROLLBARS = 0x01000000; 1660 1661 /** 1662 * Indicates whether the view is opaque. 1663 * 1664 * @hide 1665 */ 1666 static final int OPAQUE_MASK = 0x01800000; 1667 1668 /** 1669 * Indicates a prepressed state; 1670 * the short time between ACTION_DOWN and recognizing 1671 * a 'real' press. Prepressed is used to recognize quick taps 1672 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1673 * 1674 * @hide 1675 */ 1676 private static final int PREPRESSED = 0x02000000; 1677 1678 /** 1679 * Indicates whether the view is temporarily detached. 1680 * 1681 * @hide 1682 */ 1683 static final int CANCEL_NEXT_UP_EVENT = 0x04000000; 1684 1685 /** 1686 * Indicates that we should awaken scroll bars once attached 1687 * 1688 * @hide 1689 */ 1690 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1691 1692 /** 1693 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1694 * @hide 1695 */ 1696 private static final int HOVERED = 0x10000000; 1697 1698 /** 1699 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1700 * for transform operations 1701 * 1702 * @hide 1703 */ 1704 private static final int PIVOT_EXPLICITLY_SET = 0x20000000; 1705 1706 /** {@hide} */ 1707 static final int ACTIVATED = 0x40000000; 1708 1709 /** 1710 * Indicates that this view was specifically invalidated, not just dirtied because some 1711 * child view was invalidated. The flag is used to determine when we need to recreate 1712 * a view's display list (as opposed to just returning a reference to its existing 1713 * display list). 1714 * 1715 * @hide 1716 */ 1717 static final int INVALIDATED = 0x80000000; 1718 1719 /* Masks for mPrivateFlags2 */ 1720 1721 /** 1722 * Indicates that this view has reported that it can accept the current drag's content. 1723 * Cleared when the drag operation concludes. 1724 * @hide 1725 */ 1726 static final int DRAG_CAN_ACCEPT = 0x00000001; 1727 1728 /** 1729 * Indicates that this view is currently directly under the drag location in a 1730 * drag-and-drop operation involving content that it can accept. Cleared when 1731 * the drag exits the view, or when the drag operation concludes. 1732 * @hide 1733 */ 1734 static final int DRAG_HOVERED = 0x00000002; 1735 1736 /** 1737 * Indicates whether the view layout direction has been resolved and drawn to the 1738 * right-to-left direction. 1739 * 1740 * @hide 1741 */ 1742 static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004; 1743 1744 /** 1745 * Indicates whether the view layout direction has been resolved. 1746 * 1747 * @hide 1748 */ 1749 static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008; 1750 1751 1752 /* End of masks for mPrivateFlags2 */ 1753 1754 static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED; 1755 1756 /** 1757 * Always allow a user to over-scroll this view, provided it is a 1758 * view that can scroll. 1759 * 1760 * @see #getOverScrollMode() 1761 * @see #setOverScrollMode(int) 1762 */ 1763 public static final int OVER_SCROLL_ALWAYS = 0; 1764 1765 /** 1766 * Allow a user to over-scroll this view only if the content is large 1767 * enough to meaningfully scroll, provided it is a view that can scroll. 1768 * 1769 * @see #getOverScrollMode() 1770 * @see #setOverScrollMode(int) 1771 */ 1772 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 1773 1774 /** 1775 * Never allow a user to over-scroll this view. 1776 * 1777 * @see #getOverScrollMode() 1778 * @see #setOverScrollMode(int) 1779 */ 1780 public static final int OVER_SCROLL_NEVER = 2; 1781 1782 /** 1783 * View has requested the status bar to be visible (the default). 1784 * 1785 * @see #setSystemUiVisibility(int) 1786 */ 1787 public static final int STATUS_BAR_VISIBLE = 0; 1788 1789 /** 1790 * View has requested the status bar to be hidden. 1791 * 1792 * @see #setSystemUiVisibility(int) 1793 */ 1794 public static final int STATUS_BAR_HIDDEN = 0x00000001; 1795 1796 /** 1797 * @hide 1798 * 1799 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1800 * out of the public fields to keep the undefined bits out of the developer's way. 1801 * 1802 * Flag to make the status bar not expandable. Unless you also 1803 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 1804 */ 1805 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 1806 1807 /** 1808 * @hide 1809 * 1810 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1811 * out of the public fields to keep the undefined bits out of the developer's way. 1812 * 1813 * Flag to hide notification icons and scrolling ticker text. 1814 */ 1815 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 1816 1817 /** 1818 * @hide 1819 * 1820 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1821 * out of the public fields to keep the undefined bits out of the developer's way. 1822 * 1823 * Flag to disable incoming notification alerts. This will not block 1824 * icons, but it will block sound, vibrating and other visual or aural notifications. 1825 */ 1826 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 1827 1828 /** 1829 * @hide 1830 * 1831 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1832 * out of the public fields to keep the undefined bits out of the developer's way. 1833 * 1834 * Flag to hide only the scrolling ticker. Note that 1835 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 1836 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 1837 */ 1838 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 1839 1840 /** 1841 * @hide 1842 * 1843 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1844 * out of the public fields to keep the undefined bits out of the developer's way. 1845 * 1846 * Flag to hide the center system info area. 1847 */ 1848 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 1849 1850 /** 1851 * @hide 1852 * 1853 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1854 * out of the public fields to keep the undefined bits out of the developer's way. 1855 * 1856 * Flag to hide only the navigation buttons. Don't use this 1857 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1858 * 1859 * THIS DOES NOT DISABLE THE BACK BUTTON 1860 */ 1861 public static final int STATUS_BAR_DISABLE_NAVIGATION = 0x00200000; 1862 1863 /** 1864 * @hide 1865 * 1866 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1867 * out of the public fields to keep the undefined bits out of the developer's way. 1868 * 1869 * Flag to hide only the back button. Don't use this 1870 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1871 */ 1872 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 1873 1874 /** 1875 * @hide 1876 * 1877 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1878 * out of the public fields to keep the undefined bits out of the developer's way. 1879 * 1880 * Flag to hide only the clock. You might use this if your activity has 1881 * its own clock making the status bar's clock redundant. 1882 */ 1883 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 1884 1885 /** 1886 * @hide 1887 */ 1888 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = STATUS_BAR_HIDDEN; 1889 1890 /** 1891 * Controls the over-scroll mode for this view. 1892 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 1893 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 1894 * and {@link #OVER_SCROLL_NEVER}. 1895 */ 1896 private int mOverScrollMode; 1897 1898 /** 1899 * The parent this view is attached to. 1900 * {@hide} 1901 * 1902 * @see #getParent() 1903 */ 1904 protected ViewParent mParent; 1905 1906 /** 1907 * {@hide} 1908 */ 1909 AttachInfo mAttachInfo; 1910 1911 /** 1912 * {@hide} 1913 */ 1914 @ViewDebug.ExportedProperty(flagMapping = { 1915 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT, 1916 name = "FORCE_LAYOUT"), 1917 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED, 1918 name = "LAYOUT_REQUIRED"), 1919 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID, 1920 name = "DRAWING_CACHE_INVALID", outputIf = false), 1921 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true), 1922 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false), 1923 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 1924 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY") 1925 }) 1926 int mPrivateFlags; 1927 int mPrivateFlags2; 1928 1929 /** 1930 * This view's request for the visibility of the status bar. 1931 * @hide 1932 */ 1933 @ViewDebug.ExportedProperty() 1934 int mSystemUiVisibility; 1935 1936 /** 1937 * Count of how many windows this view has been attached to. 1938 */ 1939 int mWindowAttachCount; 1940 1941 /** 1942 * The layout parameters associated with this view and used by the parent 1943 * {@link android.view.ViewGroup} to determine how this view should be 1944 * laid out. 1945 * {@hide} 1946 */ 1947 protected ViewGroup.LayoutParams mLayoutParams; 1948 1949 /** 1950 * The view flags hold various views states. 1951 * {@hide} 1952 */ 1953 @ViewDebug.ExportedProperty 1954 int mViewFlags; 1955 1956 /** 1957 * The transform matrix for the View. This transform is calculated internally 1958 * based on the rotation, scaleX, and scaleY properties. The identity matrix 1959 * is used by default. Do *not* use this variable directly; instead call 1960 * getMatrix(), which will automatically recalculate the matrix if necessary 1961 * to get the correct matrix based on the latest rotation and scale properties. 1962 */ 1963 private final Matrix mMatrix = new Matrix(); 1964 1965 /** 1966 * The transform matrix for the View. This transform is calculated internally 1967 * based on the rotation, scaleX, and scaleY properties. The identity matrix 1968 * is used by default. Do *not* use this variable directly; instead call 1969 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 1970 * to get the correct matrix based on the latest rotation and scale properties. 1971 */ 1972 private Matrix mInverseMatrix; 1973 1974 /** 1975 * An internal variable that tracks whether we need to recalculate the 1976 * transform matrix, based on whether the rotation or scaleX/Y properties 1977 * have changed since the matrix was last calculated. 1978 */ 1979 boolean mMatrixDirty = false; 1980 1981 /** 1982 * An internal variable that tracks whether we need to recalculate the 1983 * transform matrix, based on whether the rotation or scaleX/Y properties 1984 * have changed since the matrix was last calculated. 1985 */ 1986 private boolean mInverseMatrixDirty = true; 1987 1988 /** 1989 * A variable that tracks whether we need to recalculate the 1990 * transform matrix, based on whether the rotation or scaleX/Y properties 1991 * have changed since the matrix was last calculated. This variable 1992 * is only valid after a call to updateMatrix() or to a function that 1993 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 1994 */ 1995 private boolean mMatrixIsIdentity = true; 1996 1997 /** 1998 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 1999 */ 2000 private Camera mCamera = null; 2001 2002 /** 2003 * This matrix is used when computing the matrix for 3D rotations. 2004 */ 2005 private Matrix matrix3D = null; 2006 2007 /** 2008 * These prev values are used to recalculate a centered pivot point when necessary. The 2009 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2010 * set), so thes values are only used then as well. 2011 */ 2012 private int mPrevWidth = -1; 2013 private int mPrevHeight = -1; 2014 2015 private boolean mLastIsOpaque; 2016 2017 /** 2018 * Convenience value to check for float values that are close enough to zero to be considered 2019 * zero. 2020 */ 2021 private static final float NONZERO_EPSILON = .001f; 2022 2023 /** 2024 * The degrees rotation around the vertical axis through the pivot point. 2025 */ 2026 @ViewDebug.ExportedProperty 2027 float mRotationY = 0f; 2028 2029 /** 2030 * The degrees rotation around the horizontal axis through the pivot point. 2031 */ 2032 @ViewDebug.ExportedProperty 2033 float mRotationX = 0f; 2034 2035 /** 2036 * The degrees rotation around the pivot point. 2037 */ 2038 @ViewDebug.ExportedProperty 2039 float mRotation = 0f; 2040 2041 /** 2042 * The amount of translation of the object away from its left property (post-layout). 2043 */ 2044 @ViewDebug.ExportedProperty 2045 float mTranslationX = 0f; 2046 2047 /** 2048 * The amount of translation of the object away from its top property (post-layout). 2049 */ 2050 @ViewDebug.ExportedProperty 2051 float mTranslationY = 0f; 2052 2053 /** 2054 * The amount of scale in the x direction around the pivot point. A 2055 * value of 1 means no scaling is applied. 2056 */ 2057 @ViewDebug.ExportedProperty 2058 float mScaleX = 1f; 2059 2060 /** 2061 * The amount of scale in the y direction around the pivot point. A 2062 * value of 1 means no scaling is applied. 2063 */ 2064 @ViewDebug.ExportedProperty 2065 float mScaleY = 1f; 2066 2067 /** 2068 * The amount of scale in the x direction around the pivot point. A 2069 * value of 1 means no scaling is applied. 2070 */ 2071 @ViewDebug.ExportedProperty 2072 float mPivotX = 0f; 2073 2074 /** 2075 * The amount of scale in the y direction around the pivot point. A 2076 * value of 1 means no scaling is applied. 2077 */ 2078 @ViewDebug.ExportedProperty 2079 float mPivotY = 0f; 2080 2081 /** 2082 * The opacity of the View. This is a value from 0 to 1, where 0 means 2083 * completely transparent and 1 means completely opaque. 2084 */ 2085 @ViewDebug.ExportedProperty 2086 float mAlpha = 1f; 2087 2088 /** 2089 * The distance in pixels from the left edge of this view's parent 2090 * to the left edge of this view. 2091 * {@hide} 2092 */ 2093 @ViewDebug.ExportedProperty(category = "layout") 2094 protected int mLeft; 2095 /** 2096 * The distance in pixels from the left edge of this view's parent 2097 * to the right edge of this view. 2098 * {@hide} 2099 */ 2100 @ViewDebug.ExportedProperty(category = "layout") 2101 protected int mRight; 2102 /** 2103 * The distance in pixels from the top edge of this view's parent 2104 * to the top edge of this view. 2105 * {@hide} 2106 */ 2107 @ViewDebug.ExportedProperty(category = "layout") 2108 protected int mTop; 2109 /** 2110 * The distance in pixels from the top edge of this view's parent 2111 * to the bottom edge of this view. 2112 * {@hide} 2113 */ 2114 @ViewDebug.ExportedProperty(category = "layout") 2115 protected int mBottom; 2116 2117 /** 2118 * The offset, in pixels, by which the content of this view is scrolled 2119 * horizontally. 2120 * {@hide} 2121 */ 2122 @ViewDebug.ExportedProperty(category = "scrolling") 2123 protected int mScrollX; 2124 /** 2125 * The offset, in pixels, by which the content of this view is scrolled 2126 * vertically. 2127 * {@hide} 2128 */ 2129 @ViewDebug.ExportedProperty(category = "scrolling") 2130 protected int mScrollY; 2131 2132 /** 2133 * The left padding in pixels, that is the distance in pixels between the 2134 * left edge of this view and the left edge of its content. 2135 * {@hide} 2136 */ 2137 @ViewDebug.ExportedProperty(category = "padding") 2138 protected int mPaddingLeft; 2139 /** 2140 * The right padding in pixels, that is the distance in pixels between the 2141 * right edge of this view and the right edge of its content. 2142 * {@hide} 2143 */ 2144 @ViewDebug.ExportedProperty(category = "padding") 2145 protected int mPaddingRight; 2146 /** 2147 * The top padding in pixels, that is the distance in pixels between the 2148 * top edge of this view and the top edge of its content. 2149 * {@hide} 2150 */ 2151 @ViewDebug.ExportedProperty(category = "padding") 2152 protected int mPaddingTop; 2153 /** 2154 * The bottom padding in pixels, that is the distance in pixels between the 2155 * bottom edge of this view and the bottom edge of its content. 2156 * {@hide} 2157 */ 2158 @ViewDebug.ExportedProperty(category = "padding") 2159 protected int mPaddingBottom; 2160 2161 /** 2162 * Briefly describes the view and is primarily used for accessibility support. 2163 */ 2164 private CharSequence mContentDescription; 2165 2166 /** 2167 * Cache the paddingRight set by the user to append to the scrollbar's size. 2168 * 2169 * @hide 2170 */ 2171 @ViewDebug.ExportedProperty(category = "padding") 2172 protected int mUserPaddingRight; 2173 2174 /** 2175 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2176 * 2177 * @hide 2178 */ 2179 @ViewDebug.ExportedProperty(category = "padding") 2180 protected int mUserPaddingBottom; 2181 2182 /** 2183 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2184 * 2185 * @hide 2186 */ 2187 @ViewDebug.ExportedProperty(category = "padding") 2188 protected int mUserPaddingLeft; 2189 2190 /** 2191 * Cache if the user padding is relative. 2192 * 2193 */ 2194 @ViewDebug.ExportedProperty(category = "padding") 2195 boolean mUserPaddingRelative; 2196 2197 /** 2198 * Cache the paddingStart set by the user to append to the scrollbar's size. 2199 * 2200 */ 2201 @ViewDebug.ExportedProperty(category = "padding") 2202 int mUserPaddingStart; 2203 2204 /** 2205 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2206 * 2207 */ 2208 @ViewDebug.ExportedProperty(category = "padding") 2209 int mUserPaddingEnd; 2210 2211 /** 2212 * @hide 2213 */ 2214 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2215 /** 2216 * @hide 2217 */ 2218 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2219 2220 private Resources mResources = null; 2221 2222 private Drawable mBGDrawable; 2223 2224 private int mBackgroundResource; 2225 private boolean mBackgroundSizeChanged; 2226 2227 /** 2228 * Listener used to dispatch focus change events. 2229 * This field should be made private, so it is hidden from the SDK. 2230 * {@hide} 2231 */ 2232 protected OnFocusChangeListener mOnFocusChangeListener; 2233 2234 /** 2235 * Listeners for layout change events. 2236 */ 2237 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2238 2239 /** 2240 * Listeners for attach events. 2241 */ 2242 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2243 2244 /** 2245 * Listener used to dispatch click events. 2246 * This field should be made private, so it is hidden from the SDK. 2247 * {@hide} 2248 */ 2249 protected OnClickListener mOnClickListener; 2250 2251 /** 2252 * Listener used to dispatch long click events. 2253 * This field should be made private, so it is hidden from the SDK. 2254 * {@hide} 2255 */ 2256 protected OnLongClickListener mOnLongClickListener; 2257 2258 /** 2259 * Listener used to build the context menu. 2260 * This field should be made private, so it is hidden from the SDK. 2261 * {@hide} 2262 */ 2263 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2264 2265 private OnKeyListener mOnKeyListener; 2266 2267 private OnTouchListener mOnTouchListener; 2268 2269 private OnHoverListener mOnHoverListener; 2270 2271 private OnGenericMotionListener mOnGenericMotionListener; 2272 2273 private OnDragListener mOnDragListener; 2274 2275 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2276 2277 /** 2278 * The application environment this view lives in. 2279 * This field should be made private, so it is hidden from the SDK. 2280 * {@hide} 2281 */ 2282 protected Context mContext; 2283 2284 private ScrollabilityCache mScrollCache; 2285 2286 private int[] mDrawableState = null; 2287 2288 /** 2289 * Set to true when drawing cache is enabled and cannot be created. 2290 * 2291 * @hide 2292 */ 2293 public boolean mCachingFailed; 2294 2295 private Bitmap mDrawingCache; 2296 private Bitmap mUnscaledDrawingCache; 2297 private DisplayList mDisplayList; 2298 private HardwareLayer mHardwareLayer; 2299 2300 /** 2301 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2302 * the user may specify which view to go to next. 2303 */ 2304 private int mNextFocusLeftId = View.NO_ID; 2305 2306 /** 2307 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2308 * the user may specify which view to go to next. 2309 */ 2310 private int mNextFocusRightId = View.NO_ID; 2311 2312 /** 2313 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2314 * the user may specify which view to go to next. 2315 */ 2316 private int mNextFocusUpId = View.NO_ID; 2317 2318 /** 2319 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2320 * the user may specify which view to go to next. 2321 */ 2322 private int mNextFocusDownId = View.NO_ID; 2323 2324 /** 2325 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 2326 * the user may specify which view to go to next. 2327 */ 2328 int mNextFocusForwardId = View.NO_ID; 2329 2330 private CheckForLongPress mPendingCheckForLongPress; 2331 private CheckForTap mPendingCheckForTap = null; 2332 private PerformClick mPerformClick; 2333 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 2334 2335 private UnsetPressedState mUnsetPressedState; 2336 2337 /** 2338 * Whether the long press's action has been invoked. The tap's action is invoked on the 2339 * up event while a long press is invoked as soon as the long press duration is reached, so 2340 * a long press could be performed before the tap is checked, in which case the tap's action 2341 * should not be invoked. 2342 */ 2343 private boolean mHasPerformedLongPress; 2344 2345 /** 2346 * The minimum height of the view. We'll try our best to have the height 2347 * of this view to at least this amount. 2348 */ 2349 @ViewDebug.ExportedProperty(category = "measurement") 2350 private int mMinHeight; 2351 2352 /** 2353 * The minimum width of the view. We'll try our best to have the width 2354 * of this view to at least this amount. 2355 */ 2356 @ViewDebug.ExportedProperty(category = "measurement") 2357 private int mMinWidth; 2358 2359 /** 2360 * The delegate to handle touch events that are physically in this view 2361 * but should be handled by another view. 2362 */ 2363 private TouchDelegate mTouchDelegate = null; 2364 2365 /** 2366 * Solid color to use as a background when creating the drawing cache. Enables 2367 * the cache to use 16 bit bitmaps instead of 32 bit. 2368 */ 2369 private int mDrawingCacheBackgroundColor = 0; 2370 2371 /** 2372 * Special tree observer used when mAttachInfo is null. 2373 */ 2374 private ViewTreeObserver mFloatingTreeObserver; 2375 2376 /** 2377 * Cache the touch slop from the context that created the view. 2378 */ 2379 private int mTouchSlop; 2380 2381 /** 2382 * Object that handles automatic animation of view properties. 2383 */ 2384 private ViewPropertyAnimator mAnimator = null; 2385 2386 /** 2387 * Flag indicating that a drag can cross window boundaries. When 2388 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 2389 * with this flag set, all visible applications will be able to participate 2390 * in the drag operation and receive the dragged content. 2391 * 2392 * @hide 2393 */ 2394 public static final int DRAG_FLAG_GLOBAL = 1; 2395 2396 /** 2397 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 2398 */ 2399 private float mVerticalScrollFactor; 2400 2401 /** 2402 * Position of the vertical scroll bar. 2403 */ 2404 private int mVerticalScrollbarPosition; 2405 2406 /** 2407 * Position the scroll bar at the default position as determined by the system. 2408 */ 2409 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 2410 2411 /** 2412 * Position the scroll bar along the left edge. 2413 */ 2414 public static final int SCROLLBAR_POSITION_LEFT = 1; 2415 2416 /** 2417 * Position the scroll bar along the right edge. 2418 */ 2419 public static final int SCROLLBAR_POSITION_RIGHT = 2; 2420 2421 /** 2422 * Indicates that the view does not have a layer. 2423 * 2424 * @see #getLayerType() 2425 * @see #setLayerType(int, android.graphics.Paint) 2426 * @see #LAYER_TYPE_SOFTWARE 2427 * @see #LAYER_TYPE_HARDWARE 2428 */ 2429 public static final int LAYER_TYPE_NONE = 0; 2430 2431 /** 2432 * <p>Indicates that the view has a software layer. A software layer is backed 2433 * by a bitmap and causes the view to be rendered using Android's software 2434 * rendering pipeline, even if hardware acceleration is enabled.</p> 2435 * 2436 * <p>Software layers have various usages:</p> 2437 * <p>When the application is not using hardware acceleration, a software layer 2438 * is useful to apply a specific color filter and/or blending mode and/or 2439 * translucency to a view and all its children.</p> 2440 * <p>When the application is using hardware acceleration, a software layer 2441 * is useful to render drawing primitives not supported by the hardware 2442 * accelerated pipeline. It can also be used to cache a complex view tree 2443 * into a texture and reduce the complexity of drawing operations. For instance, 2444 * when animating a complex view tree with a translation, a software layer can 2445 * be used to render the view tree only once.</p> 2446 * <p>Software layers should be avoided when the affected view tree updates 2447 * often. Every update will require to re-render the software layer, which can 2448 * potentially be slow (particularly when hardware acceleration is turned on 2449 * since the layer will have to be uploaded into a hardware texture after every 2450 * update.)</p> 2451 * 2452 * @see #getLayerType() 2453 * @see #setLayerType(int, android.graphics.Paint) 2454 * @see #LAYER_TYPE_NONE 2455 * @see #LAYER_TYPE_HARDWARE 2456 */ 2457 public static final int LAYER_TYPE_SOFTWARE = 1; 2458 2459 /** 2460 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 2461 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 2462 * OpenGL hardware) and causes the view to be rendered using Android's hardware 2463 * rendering pipeline, but only if hardware acceleration is turned on for the 2464 * view hierarchy. When hardware acceleration is turned off, hardware layers 2465 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 2466 * 2467 * <p>A hardware layer is useful to apply a specific color filter and/or 2468 * blending mode and/or translucency to a view and all its children.</p> 2469 * <p>A hardware layer can be used to cache a complex view tree into a 2470 * texture and reduce the complexity of drawing operations. For instance, 2471 * when animating a complex view tree with a translation, a hardware layer can 2472 * be used to render the view tree only once.</p> 2473 * <p>A hardware layer can also be used to increase the rendering quality when 2474 * rotation transformations are applied on a view. It can also be used to 2475 * prevent potential clipping issues when applying 3D transforms on a view.</p> 2476 * 2477 * @see #getLayerType() 2478 * @see #setLayerType(int, android.graphics.Paint) 2479 * @see #LAYER_TYPE_NONE 2480 * @see #LAYER_TYPE_SOFTWARE 2481 */ 2482 public static final int LAYER_TYPE_HARDWARE = 2; 2483 2484 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 2485 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 2486 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 2487 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 2488 }) 2489 int mLayerType = LAYER_TYPE_NONE; 2490 Paint mLayerPaint; 2491 Rect mLocalDirtyRect; 2492 2493 /** 2494 * Set to true when the view is sending hover accessibility events because it 2495 * is the innermost hovered view. 2496 */ 2497 private boolean mSendingHoverAccessibilityEvents; 2498 2499 /** 2500 * Text direction is inherited thru {@link ViewGroup} 2501 * @hide 2502 */ 2503 public static final int TEXT_DIRECTION_INHERIT = 0; 2504 2505 /** 2506 * Text direction is using "first strong algorithm". The first strong directional character 2507 * determines the paragraph direction. If there is no strong directional character, the 2508 * paragraph direction is the view's resolved ayout direction. 2509 * 2510 * @hide 2511 */ 2512 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 2513 2514 /** 2515 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 2516 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 2517 * If there are neither, the paragraph direction is the view's resolved layout direction. 2518 * 2519 * @hide 2520 */ 2521 public static final int TEXT_DIRECTION_ANY_RTL = 2; 2522 2523 /** 2524 * Text direction is the same as the one held by a 60% majority of the characters. If there is 2525 * no majority then the paragraph direction is the resolved layout direction of the View. 2526 * 2527 * @hide 2528 */ 2529 public static final int TEXT_DIRECTION_CHAR_COUNT = 3; 2530 2531 /** 2532 * Text direction is forced to LTR. 2533 * 2534 * @hide 2535 */ 2536 public static final int TEXT_DIRECTION_LTR = 4; 2537 2538 /** 2539 * Text direction is forced to RTL. 2540 * 2541 * @hide 2542 */ 2543 public static final int TEXT_DIRECTION_RTL = 5; 2544 2545 /** 2546 * Default text direction is inherited 2547 */ 2548 protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT; 2549 2550 /** 2551 * Default threshold for "char count" heuristic. 2552 */ 2553 protected static float DEFAULT_TEXT_DIRECTION_CHAR_COUNT_THRESHOLD = 0.6f; 2554 2555 /** 2556 * The text direction that has been defined by {@link #setTextDirection(int)}. 2557 * 2558 * {@hide} 2559 */ 2560 @ViewDebug.ExportedProperty(category = "text", mapping = { 2561 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 2562 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 2563 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 2564 @ViewDebug.IntToString(from = TEXT_DIRECTION_CHAR_COUNT, to = "CHAR_COUNT"), 2565 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 2566 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL") 2567 }) 2568 private int mTextDirection = DEFAULT_TEXT_DIRECTION; 2569 2570 /** 2571 * The resolved text direction. This needs resolution if the value is 2572 * TEXT_DIRECTION_INHERIT. The resolution matches mTextDirection if that is 2573 * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent 2574 * chain of the view. 2575 * 2576 * {@hide} 2577 */ 2578 @ViewDebug.ExportedProperty(category = "text", mapping = { 2579 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 2580 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 2581 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 2582 @ViewDebug.IntToString(from = TEXT_DIRECTION_CHAR_COUNT, to = "CHAR_COUNT"), 2583 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 2584 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL") 2585 }) 2586 private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT; 2587 2588 /** 2589 * Consistency verifier for debugging purposes. 2590 * @hide 2591 */ 2592 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 2593 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 2594 new InputEventConsistencyVerifier(this, 0) : null; 2595 2596 /** 2597 * Simple constructor to use when creating a view from code. 2598 * 2599 * @param context The Context the view is running in, through which it can 2600 * access the current theme, resources, etc. 2601 */ 2602 public View(Context context) { 2603 mContext = context; 2604 mResources = context != null ? context.getResources() : null; 2605 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT; 2606 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 2607 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 2608 mUserPaddingStart = -1; 2609 mUserPaddingEnd = -1; 2610 mUserPaddingRelative = false; 2611 } 2612 2613 /** 2614 * Constructor that is called when inflating a view from XML. This is called 2615 * when a view is being constructed from an XML file, supplying attributes 2616 * that were specified in the XML file. This version uses a default style of 2617 * 0, so the only attribute values applied are those in the Context's Theme 2618 * and the given AttributeSet. 2619 * 2620 * <p> 2621 * The method onFinishInflate() will be called after all children have been 2622 * added. 2623 * 2624 * @param context The Context the view is running in, through which it can 2625 * access the current theme, resources, etc. 2626 * @param attrs The attributes of the XML tag that is inflating the view. 2627 * @see #View(Context, AttributeSet, int) 2628 */ 2629 public View(Context context, AttributeSet attrs) { 2630 this(context, attrs, 0); 2631 } 2632 2633 /** 2634 * Perform inflation from XML and apply a class-specific base style. This 2635 * constructor of View allows subclasses to use their own base style when 2636 * they are inflating. For example, a Button class's constructor would call 2637 * this version of the super class constructor and supply 2638 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 2639 * the theme's button style to modify all of the base view attributes (in 2640 * particular its background) as well as the Button class's attributes. 2641 * 2642 * @param context The Context the view is running in, through which it can 2643 * access the current theme, resources, etc. 2644 * @param attrs The attributes of the XML tag that is inflating the view. 2645 * @param defStyle The default style to apply to this view. If 0, no style 2646 * will be applied (beyond what is included in the theme). This may 2647 * either be an attribute resource, whose value will be retrieved 2648 * from the current theme, or an explicit style resource. 2649 * @see #View(Context, AttributeSet) 2650 */ 2651 public View(Context context, AttributeSet attrs, int defStyle) { 2652 this(context); 2653 2654 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 2655 defStyle, 0); 2656 2657 Drawable background = null; 2658 2659 int leftPadding = -1; 2660 int topPadding = -1; 2661 int rightPadding = -1; 2662 int bottomPadding = -1; 2663 int startPadding = -1; 2664 int endPadding = -1; 2665 2666 int padding = -1; 2667 2668 int viewFlagValues = 0; 2669 int viewFlagMasks = 0; 2670 2671 boolean setScrollContainer = false; 2672 2673 int x = 0; 2674 int y = 0; 2675 2676 float tx = 0; 2677 float ty = 0; 2678 float rotation = 0; 2679 float rotationX = 0; 2680 float rotationY = 0; 2681 float sx = 1f; 2682 float sy = 1f; 2683 boolean transformSet = false; 2684 2685 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 2686 2687 int overScrollMode = mOverScrollMode; 2688 final int N = a.getIndexCount(); 2689 for (int i = 0; i < N; i++) { 2690 int attr = a.getIndex(i); 2691 switch (attr) { 2692 case com.android.internal.R.styleable.View_background: 2693 background = a.getDrawable(attr); 2694 break; 2695 case com.android.internal.R.styleable.View_padding: 2696 padding = a.getDimensionPixelSize(attr, -1); 2697 break; 2698 case com.android.internal.R.styleable.View_paddingLeft: 2699 leftPadding = a.getDimensionPixelSize(attr, -1); 2700 break; 2701 case com.android.internal.R.styleable.View_paddingTop: 2702 topPadding = a.getDimensionPixelSize(attr, -1); 2703 break; 2704 case com.android.internal.R.styleable.View_paddingRight: 2705 rightPadding = a.getDimensionPixelSize(attr, -1); 2706 break; 2707 case com.android.internal.R.styleable.View_paddingBottom: 2708 bottomPadding = a.getDimensionPixelSize(attr, -1); 2709 break; 2710 case com.android.internal.R.styleable.View_paddingStart: 2711 startPadding = a.getDimensionPixelSize(attr, -1); 2712 break; 2713 case com.android.internal.R.styleable.View_paddingEnd: 2714 endPadding = a.getDimensionPixelSize(attr, -1); 2715 break; 2716 case com.android.internal.R.styleable.View_scrollX: 2717 x = a.getDimensionPixelOffset(attr, 0); 2718 break; 2719 case com.android.internal.R.styleable.View_scrollY: 2720 y = a.getDimensionPixelOffset(attr, 0); 2721 break; 2722 case com.android.internal.R.styleable.View_alpha: 2723 setAlpha(a.getFloat(attr, 1f)); 2724 break; 2725 case com.android.internal.R.styleable.View_transformPivotX: 2726 setPivotX(a.getDimensionPixelOffset(attr, 0)); 2727 break; 2728 case com.android.internal.R.styleable.View_transformPivotY: 2729 setPivotY(a.getDimensionPixelOffset(attr, 0)); 2730 break; 2731 case com.android.internal.R.styleable.View_translationX: 2732 tx = a.getDimensionPixelOffset(attr, 0); 2733 transformSet = true; 2734 break; 2735 case com.android.internal.R.styleable.View_translationY: 2736 ty = a.getDimensionPixelOffset(attr, 0); 2737 transformSet = true; 2738 break; 2739 case com.android.internal.R.styleable.View_rotation: 2740 rotation = a.getFloat(attr, 0); 2741 transformSet = true; 2742 break; 2743 case com.android.internal.R.styleable.View_rotationX: 2744 rotationX = a.getFloat(attr, 0); 2745 transformSet = true; 2746 break; 2747 case com.android.internal.R.styleable.View_rotationY: 2748 rotationY = a.getFloat(attr, 0); 2749 transformSet = true; 2750 break; 2751 case com.android.internal.R.styleable.View_scaleX: 2752 sx = a.getFloat(attr, 1f); 2753 transformSet = true; 2754 break; 2755 case com.android.internal.R.styleable.View_scaleY: 2756 sy = a.getFloat(attr, 1f); 2757 transformSet = true; 2758 break; 2759 case com.android.internal.R.styleable.View_id: 2760 mID = a.getResourceId(attr, NO_ID); 2761 break; 2762 case com.android.internal.R.styleable.View_tag: 2763 mTag = a.getText(attr); 2764 break; 2765 case com.android.internal.R.styleable.View_fitsSystemWindows: 2766 if (a.getBoolean(attr, false)) { 2767 viewFlagValues |= FITS_SYSTEM_WINDOWS; 2768 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 2769 } 2770 break; 2771 case com.android.internal.R.styleable.View_focusable: 2772 if (a.getBoolean(attr, false)) { 2773 viewFlagValues |= FOCUSABLE; 2774 viewFlagMasks |= FOCUSABLE_MASK; 2775 } 2776 break; 2777 case com.android.internal.R.styleable.View_focusableInTouchMode: 2778 if (a.getBoolean(attr, false)) { 2779 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 2780 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 2781 } 2782 break; 2783 case com.android.internal.R.styleable.View_clickable: 2784 if (a.getBoolean(attr, false)) { 2785 viewFlagValues |= CLICKABLE; 2786 viewFlagMasks |= CLICKABLE; 2787 } 2788 break; 2789 case com.android.internal.R.styleable.View_longClickable: 2790 if (a.getBoolean(attr, false)) { 2791 viewFlagValues |= LONG_CLICKABLE; 2792 viewFlagMasks |= LONG_CLICKABLE; 2793 } 2794 break; 2795 case com.android.internal.R.styleable.View_saveEnabled: 2796 if (!a.getBoolean(attr, true)) { 2797 viewFlagValues |= SAVE_DISABLED; 2798 viewFlagMasks |= SAVE_DISABLED_MASK; 2799 } 2800 break; 2801 case com.android.internal.R.styleable.View_duplicateParentState: 2802 if (a.getBoolean(attr, false)) { 2803 viewFlagValues |= DUPLICATE_PARENT_STATE; 2804 viewFlagMasks |= DUPLICATE_PARENT_STATE; 2805 } 2806 break; 2807 case com.android.internal.R.styleable.View_visibility: 2808 final int visibility = a.getInt(attr, 0); 2809 if (visibility != 0) { 2810 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 2811 viewFlagMasks |= VISIBILITY_MASK; 2812 } 2813 break; 2814 case com.android.internal.R.styleable.View_layoutDirection: 2815 // Clear any HORIZONTAL_DIRECTION flag already set 2816 viewFlagValues &= ~LAYOUT_DIRECTION_MASK; 2817 // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute 2818 final int layoutDirection = a.getInt(attr, -1); 2819 if (layoutDirection != -1) { 2820 viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection]; 2821 } else { 2822 // Set to default (LAYOUT_DIRECTION_INHERIT) 2823 viewFlagValues |= LAYOUT_DIRECTION_DEFAULT; 2824 } 2825 viewFlagMasks |= LAYOUT_DIRECTION_MASK; 2826 break; 2827 case com.android.internal.R.styleable.View_drawingCacheQuality: 2828 final int cacheQuality = a.getInt(attr, 0); 2829 if (cacheQuality != 0) { 2830 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 2831 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 2832 } 2833 break; 2834 case com.android.internal.R.styleable.View_contentDescription: 2835 mContentDescription = a.getString(attr); 2836 break; 2837 case com.android.internal.R.styleable.View_soundEffectsEnabled: 2838 if (!a.getBoolean(attr, true)) { 2839 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 2840 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 2841 } 2842 break; 2843 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 2844 if (!a.getBoolean(attr, true)) { 2845 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 2846 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 2847 } 2848 break; 2849 case R.styleable.View_scrollbars: 2850 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 2851 if (scrollbars != SCROLLBARS_NONE) { 2852 viewFlagValues |= scrollbars; 2853 viewFlagMasks |= SCROLLBARS_MASK; 2854 initializeScrollbars(a); 2855 } 2856 break; 2857 case R.styleable.View_fadingEdge: 2858 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 2859 if (fadingEdge != FADING_EDGE_NONE) { 2860 viewFlagValues |= fadingEdge; 2861 viewFlagMasks |= FADING_EDGE_MASK; 2862 initializeFadingEdge(a); 2863 } 2864 break; 2865 case R.styleable.View_scrollbarStyle: 2866 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 2867 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 2868 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 2869 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 2870 } 2871 break; 2872 case R.styleable.View_isScrollContainer: 2873 setScrollContainer = true; 2874 if (a.getBoolean(attr, false)) { 2875 setScrollContainer(true); 2876 } 2877 break; 2878 case com.android.internal.R.styleable.View_keepScreenOn: 2879 if (a.getBoolean(attr, false)) { 2880 viewFlagValues |= KEEP_SCREEN_ON; 2881 viewFlagMasks |= KEEP_SCREEN_ON; 2882 } 2883 break; 2884 case R.styleable.View_filterTouchesWhenObscured: 2885 if (a.getBoolean(attr, false)) { 2886 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 2887 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 2888 } 2889 break; 2890 case R.styleable.View_nextFocusLeft: 2891 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 2892 break; 2893 case R.styleable.View_nextFocusRight: 2894 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 2895 break; 2896 case R.styleable.View_nextFocusUp: 2897 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 2898 break; 2899 case R.styleable.View_nextFocusDown: 2900 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 2901 break; 2902 case R.styleable.View_nextFocusForward: 2903 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 2904 break; 2905 case R.styleable.View_minWidth: 2906 mMinWidth = a.getDimensionPixelSize(attr, 0); 2907 break; 2908 case R.styleable.View_minHeight: 2909 mMinHeight = a.getDimensionPixelSize(attr, 0); 2910 break; 2911 case R.styleable.View_onClick: 2912 if (context.isRestricted()) { 2913 throw new IllegalStateException("The android:onClick attribute cannot " 2914 + "be used within a restricted context"); 2915 } 2916 2917 final String handlerName = a.getString(attr); 2918 if (handlerName != null) { 2919 setOnClickListener(new OnClickListener() { 2920 private Method mHandler; 2921 2922 public void onClick(View v) { 2923 if (mHandler == null) { 2924 try { 2925 mHandler = getContext().getClass().getMethod(handlerName, 2926 View.class); 2927 } catch (NoSuchMethodException e) { 2928 int id = getId(); 2929 String idText = id == NO_ID ? "" : " with id '" 2930 + getContext().getResources().getResourceEntryName( 2931 id) + "'"; 2932 throw new IllegalStateException("Could not find a method " + 2933 handlerName + "(View) in the activity " 2934 + getContext().getClass() + " for onClick handler" 2935 + " on view " + View.this.getClass() + idText, e); 2936 } 2937 } 2938 2939 try { 2940 mHandler.invoke(getContext(), View.this); 2941 } catch (IllegalAccessException e) { 2942 throw new IllegalStateException("Could not execute non " 2943 + "public method of the activity", e); 2944 } catch (InvocationTargetException e) { 2945 throw new IllegalStateException("Could not execute " 2946 + "method of the activity", e); 2947 } 2948 } 2949 }); 2950 } 2951 break; 2952 case R.styleable.View_overScrollMode: 2953 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 2954 break; 2955 case R.styleable.View_verticalScrollbarPosition: 2956 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 2957 break; 2958 case R.styleable.View_layerType: 2959 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 2960 break; 2961 case R.styleable.View_textDirection: 2962 mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION); 2963 break; 2964 } 2965 } 2966 2967 setOverScrollMode(overScrollMode); 2968 2969 if (background != null) { 2970 setBackgroundDrawable(background); 2971 } 2972 2973 mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0); 2974 2975 // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved 2976 // layout direction). Those cached values will be used later during padding resolution. 2977 mUserPaddingStart = startPadding; 2978 mUserPaddingEnd = endPadding; 2979 2980 if (padding >= 0) { 2981 leftPadding = padding; 2982 topPadding = padding; 2983 rightPadding = padding; 2984 bottomPadding = padding; 2985 } 2986 2987 // If the user specified the padding (either with android:padding or 2988 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 2989 // use the default padding or the padding from the background drawable 2990 // (stored at this point in mPadding*) 2991 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft, 2992 topPadding >= 0 ? topPadding : mPaddingTop, 2993 rightPadding >= 0 ? rightPadding : mPaddingRight, 2994 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 2995 2996 if (viewFlagMasks != 0) { 2997 setFlags(viewFlagValues, viewFlagMasks); 2998 } 2999 3000 // Needs to be called after mViewFlags is set 3001 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3002 recomputePadding(); 3003 } 3004 3005 if (x != 0 || y != 0) { 3006 scrollTo(x, y); 3007 } 3008 3009 if (transformSet) { 3010 setTranslationX(tx); 3011 setTranslationY(ty); 3012 setRotation(rotation); 3013 setRotationX(rotationX); 3014 setRotationY(rotationY); 3015 setScaleX(sx); 3016 setScaleY(sy); 3017 } 3018 3019 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3020 setScrollContainer(true); 3021 } 3022 3023 computeOpaqueFlags(); 3024 3025 a.recycle(); 3026 } 3027 3028 /** 3029 * Non-public constructor for use in testing 3030 */ 3031 View() { 3032 } 3033 3034 /** 3035 * <p> 3036 * Initializes the fading edges from a given set of styled attributes. This 3037 * method should be called by subclasses that need fading edges and when an 3038 * instance of these subclasses is created programmatically rather than 3039 * being inflated from XML. This method is automatically called when the XML 3040 * is inflated. 3041 * </p> 3042 * 3043 * @param a the styled attributes set to initialize the fading edges from 3044 */ 3045 protected void initializeFadingEdge(TypedArray a) { 3046 initScrollCache(); 3047 3048 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3049 R.styleable.View_fadingEdgeLength, 3050 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3051 } 3052 3053 /** 3054 * Returns the size of the vertical faded edges used to indicate that more 3055 * content in this view is visible. 3056 * 3057 * @return The size in pixels of the vertical faded edge or 0 if vertical 3058 * faded edges are not enabled for this view. 3059 * @attr ref android.R.styleable#View_fadingEdgeLength 3060 */ 3061 public int getVerticalFadingEdgeLength() { 3062 if (isVerticalFadingEdgeEnabled()) { 3063 ScrollabilityCache cache = mScrollCache; 3064 if (cache != null) { 3065 return cache.fadingEdgeLength; 3066 } 3067 } 3068 return 0; 3069 } 3070 3071 /** 3072 * Set the size of the faded edge used to indicate that more content in this 3073 * view is available. Will not change whether the fading edge is enabled; use 3074 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3075 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3076 * for the vertical or horizontal fading edges. 3077 * 3078 * @param length The size in pixels of the faded edge used to indicate that more 3079 * content in this view is visible. 3080 */ 3081 public void setFadingEdgeLength(int length) { 3082 initScrollCache(); 3083 mScrollCache.fadingEdgeLength = length; 3084 } 3085 3086 /** 3087 * Returns the size of the horizontal faded edges used to indicate that more 3088 * content in this view is visible. 3089 * 3090 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3091 * faded edges are not enabled for this view. 3092 * @attr ref android.R.styleable#View_fadingEdgeLength 3093 */ 3094 public int getHorizontalFadingEdgeLength() { 3095 if (isHorizontalFadingEdgeEnabled()) { 3096 ScrollabilityCache cache = mScrollCache; 3097 if (cache != null) { 3098 return cache.fadingEdgeLength; 3099 } 3100 } 3101 return 0; 3102 } 3103 3104 /** 3105 * Returns the width of the vertical scrollbar. 3106 * 3107 * @return The width in pixels of the vertical scrollbar or 0 if there 3108 * is no vertical scrollbar. 3109 */ 3110 public int getVerticalScrollbarWidth() { 3111 ScrollabilityCache cache = mScrollCache; 3112 if (cache != null) { 3113 ScrollBarDrawable scrollBar = cache.scrollBar; 3114 if (scrollBar != null) { 3115 int size = scrollBar.getSize(true); 3116 if (size <= 0) { 3117 size = cache.scrollBarSize; 3118 } 3119 return size; 3120 } 3121 return 0; 3122 } 3123 return 0; 3124 } 3125 3126 /** 3127 * Returns the height of the horizontal scrollbar. 3128 * 3129 * @return The height in pixels of the horizontal scrollbar or 0 if 3130 * there is no horizontal scrollbar. 3131 */ 3132 protected int getHorizontalScrollbarHeight() { 3133 ScrollabilityCache cache = mScrollCache; 3134 if (cache != null) { 3135 ScrollBarDrawable scrollBar = cache.scrollBar; 3136 if (scrollBar != null) { 3137 int size = scrollBar.getSize(false); 3138 if (size <= 0) { 3139 size = cache.scrollBarSize; 3140 } 3141 return size; 3142 } 3143 return 0; 3144 } 3145 return 0; 3146 } 3147 3148 /** 3149 * <p> 3150 * Initializes the scrollbars from a given set of styled attributes. This 3151 * method should be called by subclasses that need scrollbars and when an 3152 * instance of these subclasses is created programmatically rather than 3153 * being inflated from XML. This method is automatically called when the XML 3154 * is inflated. 3155 * </p> 3156 * 3157 * @param a the styled attributes set to initialize the scrollbars from 3158 */ 3159 protected void initializeScrollbars(TypedArray a) { 3160 initScrollCache(); 3161 3162 final ScrollabilityCache scrollabilityCache = mScrollCache; 3163 3164 if (scrollabilityCache.scrollBar == null) { 3165 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 3166 } 3167 3168 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 3169 3170 if (!fadeScrollbars) { 3171 scrollabilityCache.state = ScrollabilityCache.ON; 3172 } 3173 scrollabilityCache.fadeScrollBars = fadeScrollbars; 3174 3175 3176 scrollabilityCache.scrollBarFadeDuration = a.getInt( 3177 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 3178 .getScrollBarFadeDuration()); 3179 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 3180 R.styleable.View_scrollbarDefaultDelayBeforeFade, 3181 ViewConfiguration.getScrollDefaultDelay()); 3182 3183 3184 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 3185 com.android.internal.R.styleable.View_scrollbarSize, 3186 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3187 3188 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3189 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3190 3191 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3192 if (thumb != null) { 3193 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3194 } 3195 3196 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3197 false); 3198 if (alwaysDraw) { 3199 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3200 } 3201 3202 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3203 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3204 3205 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3206 if (thumb != null) { 3207 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3208 } 3209 3210 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3211 false); 3212 if (alwaysDraw) { 3213 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3214 } 3215 3216 // Re-apply user/background padding so that scrollbar(s) get added 3217 resolvePadding(); 3218 } 3219 3220 /** 3221 * <p> 3222 * Initalizes the scrollability cache if necessary. 3223 * </p> 3224 */ 3225 private void initScrollCache() { 3226 if (mScrollCache == null) { 3227 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 3228 } 3229 } 3230 3231 /** 3232 * Set the position of the vertical scroll bar. Should be one of 3233 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 3234 * {@link #SCROLLBAR_POSITION_RIGHT}. 3235 * 3236 * @param position Where the vertical scroll bar should be positioned. 3237 */ 3238 public void setVerticalScrollbarPosition(int position) { 3239 if (mVerticalScrollbarPosition != position) { 3240 mVerticalScrollbarPosition = position; 3241 computeOpaqueFlags(); 3242 resolvePadding(); 3243 } 3244 } 3245 3246 /** 3247 * @return The position where the vertical scroll bar will show, if applicable. 3248 * @see #setVerticalScrollbarPosition(int) 3249 */ 3250 public int getVerticalScrollbarPosition() { 3251 return mVerticalScrollbarPosition; 3252 } 3253 3254 /** 3255 * Register a callback to be invoked when focus of this view changed. 3256 * 3257 * @param l The callback that will run. 3258 */ 3259 public void setOnFocusChangeListener(OnFocusChangeListener l) { 3260 mOnFocusChangeListener = l; 3261 } 3262 3263 /** 3264 * Add a listener that will be called when the bounds of the view change due to 3265 * layout processing. 3266 * 3267 * @param listener The listener that will be called when layout bounds change. 3268 */ 3269 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 3270 if (mOnLayoutChangeListeners == null) { 3271 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 3272 } 3273 mOnLayoutChangeListeners.add(listener); 3274 } 3275 3276 /** 3277 * Remove a listener for layout changes. 3278 * 3279 * @param listener The listener for layout bounds change. 3280 */ 3281 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 3282 if (mOnLayoutChangeListeners == null) { 3283 return; 3284 } 3285 mOnLayoutChangeListeners.remove(listener); 3286 } 3287 3288 /** 3289 * Add a listener for attach state changes. 3290 * 3291 * This listener will be called whenever this view is attached or detached 3292 * from a window. Remove the listener using 3293 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 3294 * 3295 * @param listener Listener to attach 3296 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 3297 */ 3298 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3299 if (mOnAttachStateChangeListeners == null) { 3300 mOnAttachStateChangeListeners = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 3301 } 3302 mOnAttachStateChangeListeners.add(listener); 3303 } 3304 3305 /** 3306 * Remove a listener for attach state changes. The listener will receive no further 3307 * notification of window attach/detach events. 3308 * 3309 * @param listener Listener to remove 3310 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 3311 */ 3312 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3313 if (mOnAttachStateChangeListeners == null) { 3314 return; 3315 } 3316 mOnAttachStateChangeListeners.remove(listener); 3317 } 3318 3319 /** 3320 * Returns the focus-change callback registered for this view. 3321 * 3322 * @return The callback, or null if one is not registered. 3323 */ 3324 public OnFocusChangeListener getOnFocusChangeListener() { 3325 return mOnFocusChangeListener; 3326 } 3327 3328 /** 3329 * Register a callback to be invoked when this view is clicked. If this view is not 3330 * clickable, it becomes clickable. 3331 * 3332 * @param l The callback that will run 3333 * 3334 * @see #setClickable(boolean) 3335 */ 3336 public void setOnClickListener(OnClickListener l) { 3337 if (!isClickable()) { 3338 setClickable(true); 3339 } 3340 mOnClickListener = l; 3341 } 3342 3343 /** 3344 * Register a callback to be invoked when this view is clicked and held. If this view is not 3345 * long clickable, it becomes long clickable. 3346 * 3347 * @param l The callback that will run 3348 * 3349 * @see #setLongClickable(boolean) 3350 */ 3351 public void setOnLongClickListener(OnLongClickListener l) { 3352 if (!isLongClickable()) { 3353 setLongClickable(true); 3354 } 3355 mOnLongClickListener = l; 3356 } 3357 3358 /** 3359 * Register a callback to be invoked when the context menu for this view is 3360 * being built. If this view is not long clickable, it becomes long clickable. 3361 * 3362 * @param l The callback that will run 3363 * 3364 */ 3365 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 3366 if (!isLongClickable()) { 3367 setLongClickable(true); 3368 } 3369 mOnCreateContextMenuListener = l; 3370 } 3371 3372 /** 3373 * Call this view's OnClickListener, if it is defined. 3374 * 3375 * @return True there was an assigned OnClickListener that was called, false 3376 * otherwise is returned. 3377 */ 3378 public boolean performClick() { 3379 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 3380 3381 if (mOnClickListener != null) { 3382 playSoundEffect(SoundEffectConstants.CLICK); 3383 mOnClickListener.onClick(this); 3384 return true; 3385 } 3386 3387 return false; 3388 } 3389 3390 /** 3391 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 3392 * OnLongClickListener did not consume the event. 3393 * 3394 * @return True if one of the above receivers consumed the event, false otherwise. 3395 */ 3396 public boolean performLongClick() { 3397 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 3398 3399 boolean handled = false; 3400 if (mOnLongClickListener != null) { 3401 handled = mOnLongClickListener.onLongClick(View.this); 3402 } 3403 if (!handled) { 3404 handled = showContextMenu(); 3405 } 3406 if (handled) { 3407 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 3408 } 3409 return handled; 3410 } 3411 3412 /** 3413 * Performs button-related actions during a touch down event. 3414 * 3415 * @param event The event. 3416 * @return True if the down was consumed. 3417 * 3418 * @hide 3419 */ 3420 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 3421 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 3422 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 3423 return true; 3424 } 3425 } 3426 return false; 3427 } 3428 3429 /** 3430 * Bring up the context menu for this view. 3431 * 3432 * @return Whether a context menu was displayed. 3433 */ 3434 public boolean showContextMenu() { 3435 return getParent().showContextMenuForChild(this); 3436 } 3437 3438 /** 3439 * Bring up the context menu for this view, referring to the item under the specified point. 3440 * 3441 * @param x The referenced x coordinate. 3442 * @param y The referenced y coordinate. 3443 * @param metaState The keyboard modifiers that were pressed. 3444 * @return Whether a context menu was displayed. 3445 * 3446 * @hide 3447 */ 3448 public boolean showContextMenu(float x, float y, int metaState) { 3449 return showContextMenu(); 3450 } 3451 3452 /** 3453 * Start an action mode. 3454 * 3455 * @param callback Callback that will control the lifecycle of the action mode 3456 * @return The new action mode if it is started, null otherwise 3457 * 3458 * @see ActionMode 3459 */ 3460 public ActionMode startActionMode(ActionMode.Callback callback) { 3461 return getParent().startActionModeForChild(this, callback); 3462 } 3463 3464 /** 3465 * Register a callback to be invoked when a key is pressed in this view. 3466 * @param l the key listener to attach to this view 3467 */ 3468 public void setOnKeyListener(OnKeyListener l) { 3469 mOnKeyListener = l; 3470 } 3471 3472 /** 3473 * Register a callback to be invoked when a touch event is sent to this view. 3474 * @param l the touch listener to attach to this view 3475 */ 3476 public void setOnTouchListener(OnTouchListener l) { 3477 mOnTouchListener = l; 3478 } 3479 3480 /** 3481 * Register a callback to be invoked when a generic motion event is sent to this view. 3482 * @param l the generic motion listener to attach to this view 3483 */ 3484 public void setOnGenericMotionListener(OnGenericMotionListener l) { 3485 mOnGenericMotionListener = l; 3486 } 3487 3488 /** 3489 * Register a callback to be invoked when a hover event is sent to this view. 3490 * @param l the hover listener to attach to this view 3491 */ 3492 public void setOnHoverListener(OnHoverListener l) { 3493 mOnHoverListener = l; 3494 } 3495 3496 /** 3497 * Register a drag event listener callback object for this View. The parameter is 3498 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 3499 * View, the system calls the 3500 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 3501 * @param l An implementation of {@link android.view.View.OnDragListener}. 3502 */ 3503 public void setOnDragListener(OnDragListener l) { 3504 mOnDragListener = l; 3505 } 3506 3507 /** 3508 * Give this view focus. This will cause 3509 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3510 * 3511 * Note: this does not check whether this {@link View} should get focus, it just 3512 * gives it focus no matter what. It should only be called internally by framework 3513 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 3514 * 3515 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 3516 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 3517 * focus moved when requestFocus() is called. It may not always 3518 * apply, in which case use the default View.FOCUS_DOWN. 3519 * @param previouslyFocusedRect The rectangle of the view that had focus 3520 * prior in this View's coordinate system. 3521 */ 3522 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 3523 if (DBG) { 3524 System.out.println(this + " requestFocus()"); 3525 } 3526 3527 if ((mPrivateFlags & FOCUSED) == 0) { 3528 mPrivateFlags |= FOCUSED; 3529 3530 if (mParent != null) { 3531 mParent.requestChildFocus(this, this); 3532 } 3533 3534 onFocusChanged(true, direction, previouslyFocusedRect); 3535 refreshDrawableState(); 3536 } 3537 } 3538 3539 /** 3540 * Request that a rectangle of this view be visible on the screen, 3541 * scrolling if necessary just enough. 3542 * 3543 * <p>A View should call this if it maintains some notion of which part 3544 * of its content is interesting. For example, a text editing view 3545 * should call this when its cursor moves. 3546 * 3547 * @param rectangle The rectangle. 3548 * @return Whether any parent scrolled. 3549 */ 3550 public boolean requestRectangleOnScreen(Rect rectangle) { 3551 return requestRectangleOnScreen(rectangle, false); 3552 } 3553 3554 /** 3555 * Request that a rectangle of this view be visible on the screen, 3556 * scrolling if necessary just enough. 3557 * 3558 * <p>A View should call this if it maintains some notion of which part 3559 * of its content is interesting. For example, a text editing view 3560 * should call this when its cursor moves. 3561 * 3562 * <p>When <code>immediate</code> is set to true, scrolling will not be 3563 * animated. 3564 * 3565 * @param rectangle The rectangle. 3566 * @param immediate True to forbid animated scrolling, false otherwise 3567 * @return Whether any parent scrolled. 3568 */ 3569 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 3570 View child = this; 3571 ViewParent parent = mParent; 3572 boolean scrolled = false; 3573 while (parent != null) { 3574 scrolled |= parent.requestChildRectangleOnScreen(child, 3575 rectangle, immediate); 3576 3577 // offset rect so next call has the rectangle in the 3578 // coordinate system of its direct child. 3579 rectangle.offset(child.getLeft(), child.getTop()); 3580 rectangle.offset(-child.getScrollX(), -child.getScrollY()); 3581 3582 if (!(parent instanceof View)) { 3583 break; 3584 } 3585 3586 child = (View) parent; 3587 parent = child.getParent(); 3588 } 3589 return scrolled; 3590 } 3591 3592 /** 3593 * Called when this view wants to give up focus. This will cause 3594 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3595 */ 3596 public void clearFocus() { 3597 if (DBG) { 3598 System.out.println(this + " clearFocus()"); 3599 } 3600 3601 if ((mPrivateFlags & FOCUSED) != 0) { 3602 mPrivateFlags &= ~FOCUSED; 3603 3604 if (mParent != null) { 3605 mParent.clearChildFocus(this); 3606 } 3607 3608 onFocusChanged(false, 0, null); 3609 refreshDrawableState(); 3610 } 3611 } 3612 3613 /** 3614 * Called to clear the focus of a view that is about to be removed. 3615 * Doesn't call clearChildFocus, which prevents this view from taking 3616 * focus again before it has been removed from the parent 3617 */ 3618 void clearFocusForRemoval() { 3619 if ((mPrivateFlags & FOCUSED) != 0) { 3620 mPrivateFlags &= ~FOCUSED; 3621 3622 onFocusChanged(false, 0, null); 3623 refreshDrawableState(); 3624 } 3625 } 3626 3627 /** 3628 * Called internally by the view system when a new view is getting focus. 3629 * This is what clears the old focus. 3630 */ 3631 void unFocus() { 3632 if (DBG) { 3633 System.out.println(this + " unFocus()"); 3634 } 3635 3636 if ((mPrivateFlags & FOCUSED) != 0) { 3637 mPrivateFlags &= ~FOCUSED; 3638 3639 onFocusChanged(false, 0, null); 3640 refreshDrawableState(); 3641 } 3642 } 3643 3644 /** 3645 * Returns true if this view has focus iteself, or is the ancestor of the 3646 * view that has focus. 3647 * 3648 * @return True if this view has or contains focus, false otherwise. 3649 */ 3650 @ViewDebug.ExportedProperty(category = "focus") 3651 public boolean hasFocus() { 3652 return (mPrivateFlags & FOCUSED) != 0; 3653 } 3654 3655 /** 3656 * Returns true if this view is focusable or if it contains a reachable View 3657 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 3658 * is a View whose parents do not block descendants focus. 3659 * 3660 * Only {@link #VISIBLE} views are considered focusable. 3661 * 3662 * @return True if the view is focusable or if the view contains a focusable 3663 * View, false otherwise. 3664 * 3665 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 3666 */ 3667 public boolean hasFocusable() { 3668 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 3669 } 3670 3671 /** 3672 * Called by the view system when the focus state of this view changes. 3673 * When the focus change event is caused by directional navigation, direction 3674 * and previouslyFocusedRect provide insight into where the focus is coming from. 3675 * When overriding, be sure to call up through to the super class so that 3676 * the standard focus handling will occur. 3677 * 3678 * @param gainFocus True if the View has focus; false otherwise. 3679 * @param direction The direction focus has moved when requestFocus() 3680 * is called to give this view focus. Values are 3681 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 3682 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 3683 * It may not always apply, in which case use the default. 3684 * @param previouslyFocusedRect The rectangle, in this view's coordinate 3685 * system, of the previously focused view. If applicable, this will be 3686 * passed in as finer grained information about where the focus is coming 3687 * from (in addition to direction). Will be <code>null</code> otherwise. 3688 */ 3689 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 3690 if (gainFocus) { 3691 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 3692 } 3693 3694 InputMethodManager imm = InputMethodManager.peekInstance(); 3695 if (!gainFocus) { 3696 if (isPressed()) { 3697 setPressed(false); 3698 } 3699 if (imm != null && mAttachInfo != null 3700 && mAttachInfo.mHasWindowFocus) { 3701 imm.focusOut(this); 3702 } 3703 onFocusLost(); 3704 } else if (imm != null && mAttachInfo != null 3705 && mAttachInfo.mHasWindowFocus) { 3706 imm.focusIn(this); 3707 } 3708 3709 invalidate(true); 3710 if (mOnFocusChangeListener != null) { 3711 mOnFocusChangeListener.onFocusChange(this, gainFocus); 3712 } 3713 3714 if (mAttachInfo != null) { 3715 mAttachInfo.mKeyDispatchState.reset(this); 3716 } 3717 } 3718 3719 /** 3720 * Sends an accessibility event of the given type. If accessiiblity is 3721 * not enabled this method has no effect. The default implementation calls 3722 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 3723 * to populate information about the event source (this View), then calls 3724 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 3725 * populate the text content of the event source including its descendants, 3726 * and last calls 3727 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 3728 * on its parent to resuest sending of the event to interested parties. 3729 * 3730 * @param eventType The type of the event to send. 3731 * 3732 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 3733 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3734 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 3735 */ 3736 public void sendAccessibilityEvent(int eventType) { 3737 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 3738 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 3739 } 3740 } 3741 3742 /** 3743 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 3744 * takes as an argument an empty {@link AccessibilityEvent} and does not 3745 * perfrom a check whether accessibility is enabled. 3746 * 3747 * @param event The event to send. 3748 * 3749 * @see #sendAccessibilityEvent(int) 3750 */ 3751 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 3752 if (!isShown()) { 3753 return; 3754 } 3755 onInitializeAccessibilityEvent(event); 3756 dispatchPopulateAccessibilityEvent(event); 3757 // In the beginning we called #isShown(), so we know that getParent() is not null. 3758 getParent().requestSendAccessibilityEvent(this, event); 3759 } 3760 3761 /** 3762 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 3763 * to its children for adding their text content to the event. Note that the 3764 * event text is populated in a separate dispatch path since we add to the 3765 * event not only the text of the source but also the text of all its descendants. 3766 * </p> 3767 * A typical implementation will call 3768 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 3769 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3770 * on each child. Override this method if custom population of the event text 3771 * content is required. 3772 * 3773 * @param event The event. 3774 * 3775 * @return True if the event population was completed. 3776 */ 3777 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 3778 onPopulateAccessibilityEvent(event); 3779 return false; 3780 } 3781 3782 /** 3783 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3784 * giving a chance to this View to populate the accessibility event with its 3785 * text content. While the implementation is free to modify other event 3786 * attributes this should be performed in 3787 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 3788 * <p> 3789 * Example: Adding formatted date string to an accessibility event in addition 3790 * to the text added by the super implementation. 3791 * </p><p><pre><code> 3792 * public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3793 * super.onPopulateAccessibilityEvent(event); 3794 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 3795 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 3796 * mCurrentDate.getTimeInMillis(), flags); 3797 * event.getText().add(selectedDateUtterance); 3798 * } 3799 * </code></pre></p> 3800 * 3801 * @param event The accessibility event which to populate. 3802 * 3803 * @see #sendAccessibilityEvent(int) 3804 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3805 */ 3806 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3807 } 3808 3809 /** 3810 * Initializes an {@link AccessibilityEvent} with information about the 3811 * the type of the event and this View which is the event source. In other 3812 * words, the source of an accessibility event is the view whose state 3813 * change triggered firing the event. 3814 * <p> 3815 * Example: Setting the password property of an event in addition 3816 * to properties set by the super implementation. 3817 * </p><p><pre><code> 3818 * public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 3819 * super.onInitializeAccessibilityEvent(event); 3820 * event.setPassword(true); 3821 * } 3822 * </code></pre></p> 3823 * @param event The event to initialeze. 3824 * 3825 * @see #sendAccessibilityEvent(int) 3826 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3827 */ 3828 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 3829 event.setSource(this); 3830 event.setClassName(getClass().getName()); 3831 event.setPackageName(getContext().getPackageName()); 3832 event.setEnabled(isEnabled()); 3833 event.setContentDescription(mContentDescription); 3834 3835 final int eventType = event.getEventType(); 3836 switch (eventType) { 3837 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 3838 if (mAttachInfo != null) { 3839 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList; 3840 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, 3841 FOCUSABLES_ALL); 3842 event.setItemCount(focusablesTempList.size()); 3843 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 3844 focusablesTempList.clear(); 3845 } 3846 } break; 3847 case AccessibilityEvent.TYPE_VIEW_SCROLLED: { 3848 event.setScrollX(mScrollX); 3849 event.setScrollY(mScrollY); 3850 event.setItemCount(getHeight()); 3851 } break; 3852 } 3853 } 3854 3855 /** 3856 * Returns an {@link AccessibilityNodeInfo} representing this view from the 3857 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 3858 * This method is responsible for obtaining an accessibility node info from a 3859 * pool of reusable instances and calling 3860 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 3861 * initialize the former. 3862 * <p> 3863 * Note: The client is responsible for recycling the obtained instance by calling 3864 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 3865 * </p> 3866 * @return A populated {@link AccessibilityNodeInfo}. 3867 * 3868 * @see AccessibilityNodeInfo 3869 */ 3870 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 3871 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 3872 onInitializeAccessibilityNodeInfo(info); 3873 return info; 3874 } 3875 3876 /** 3877 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 3878 * The base implementation sets: 3879 * <ul> 3880 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 3881 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 3882 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 3883 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 3884 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 3885 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 3886 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 3887 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 3888 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 3889 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 3890 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 3891 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 3892 * </ul> 3893 * <p> 3894 * Subclasses should override this method, call the super implementation, 3895 * and set additional attributes. 3896 * </p> 3897 * @param info The instance to initialize. 3898 */ 3899 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 3900 Rect bounds = mAttachInfo.mTmpInvalRect; 3901 getDrawingRect(bounds); 3902 info.setBoundsInParent(bounds); 3903 3904 int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation; 3905 getLocationOnScreen(locationOnScreen); 3906 bounds.offset(locationOnScreen[0], locationOnScreen[1]); 3907 info.setBoundsInScreen(bounds); 3908 3909 ViewParent parent = getParent(); 3910 if (parent instanceof View) { 3911 View parentView = (View) parent; 3912 info.setParent(parentView); 3913 } 3914 3915 info.setPackageName(mContext.getPackageName()); 3916 info.setClassName(getClass().getName()); 3917 info.setContentDescription(getContentDescription()); 3918 3919 info.setEnabled(isEnabled()); 3920 info.setClickable(isClickable()); 3921 info.setFocusable(isFocusable()); 3922 info.setFocused(isFocused()); 3923 info.setSelected(isSelected()); 3924 info.setLongClickable(isLongClickable()); 3925 3926 // TODO: These make sense only if we are in an AdapterView but all 3927 // views can be selected. Maybe from accessiiblity perspective 3928 // we should report as selectable view in an AdapterView. 3929 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 3930 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 3931 3932 if (isFocusable()) { 3933 if (isFocused()) { 3934 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 3935 } else { 3936 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 3937 } 3938 } 3939 } 3940 3941 /** 3942 * Gets the unique identifier of this view on the screen for accessibility purposes. 3943 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 3944 * 3945 * @return The view accessibility id. 3946 * 3947 * @hide 3948 */ 3949 public int getAccessibilityViewId() { 3950 if (mAccessibilityViewId == NO_ID) { 3951 mAccessibilityViewId = sNextAccessibilityViewId++; 3952 } 3953 return mAccessibilityViewId; 3954 } 3955 3956 /** 3957 * Gets the unique identifier of the window in which this View reseides. 3958 * 3959 * @return The window accessibility id. 3960 * 3961 * @hide 3962 */ 3963 public int getAccessibilityWindowId() { 3964 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 3965 } 3966 3967 /** 3968 * Gets the {@link View} description. It briefly describes the view and is 3969 * primarily used for accessibility support. Set this property to enable 3970 * better accessibility support for your application. This is especially 3971 * true for views that do not have textual representation (For example, 3972 * ImageButton). 3973 * 3974 * @return The content descriptiopn. 3975 * 3976 * @attr ref android.R.styleable#View_contentDescription 3977 */ 3978 public CharSequence getContentDescription() { 3979 return mContentDescription; 3980 } 3981 3982 /** 3983 * Sets the {@link View} description. It briefly describes the view and is 3984 * primarily used for accessibility support. Set this property to enable 3985 * better accessibility support for your application. This is especially 3986 * true for views that do not have textual representation (For example, 3987 * ImageButton). 3988 * 3989 * @param contentDescription The content description. 3990 * 3991 * @attr ref android.R.styleable#View_contentDescription 3992 */ 3993 public void setContentDescription(CharSequence contentDescription) { 3994 mContentDescription = contentDescription; 3995 } 3996 3997 /** 3998 * Invoked whenever this view loses focus, either by losing window focus or by losing 3999 * focus within its window. This method can be used to clear any state tied to the 4000 * focus. For instance, if a button is held pressed with the trackball and the window 4001 * loses focus, this method can be used to cancel the press. 4002 * 4003 * Subclasses of View overriding this method should always call super.onFocusLost(). 4004 * 4005 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 4006 * @see #onWindowFocusChanged(boolean) 4007 * 4008 * @hide pending API council approval 4009 */ 4010 protected void onFocusLost() { 4011 resetPressedState(); 4012 } 4013 4014 private void resetPressedState() { 4015 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 4016 return; 4017 } 4018 4019 if (isPressed()) { 4020 setPressed(false); 4021 4022 if (!mHasPerformedLongPress) { 4023 removeLongPressCallback(); 4024 } 4025 } 4026 } 4027 4028 /** 4029 * Returns true if this view has focus 4030 * 4031 * @return True if this view has focus, false otherwise. 4032 */ 4033 @ViewDebug.ExportedProperty(category = "focus") 4034 public boolean isFocused() { 4035 return (mPrivateFlags & FOCUSED) != 0; 4036 } 4037 4038 /** 4039 * Find the view in the hierarchy rooted at this view that currently has 4040 * focus. 4041 * 4042 * @return The view that currently has focus, or null if no focused view can 4043 * be found. 4044 */ 4045 public View findFocus() { 4046 return (mPrivateFlags & FOCUSED) != 0 ? this : null; 4047 } 4048 4049 /** 4050 * Change whether this view is one of the set of scrollable containers in 4051 * its window. This will be used to determine whether the window can 4052 * resize or must pan when a soft input area is open -- scrollable 4053 * containers allow the window to use resize mode since the container 4054 * will appropriately shrink. 4055 */ 4056 public void setScrollContainer(boolean isScrollContainer) { 4057 if (isScrollContainer) { 4058 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) { 4059 mAttachInfo.mScrollContainers.add(this); 4060 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 4061 } 4062 mPrivateFlags |= SCROLL_CONTAINER; 4063 } else { 4064 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 4065 mAttachInfo.mScrollContainers.remove(this); 4066 } 4067 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED); 4068 } 4069 } 4070 4071 /** 4072 * Returns the quality of the drawing cache. 4073 * 4074 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4075 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4076 * 4077 * @see #setDrawingCacheQuality(int) 4078 * @see #setDrawingCacheEnabled(boolean) 4079 * @see #isDrawingCacheEnabled() 4080 * 4081 * @attr ref android.R.styleable#View_drawingCacheQuality 4082 */ 4083 public int getDrawingCacheQuality() { 4084 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 4085 } 4086 4087 /** 4088 * Set the drawing cache quality of this view. This value is used only when the 4089 * drawing cache is enabled 4090 * 4091 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4092 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4093 * 4094 * @see #getDrawingCacheQuality() 4095 * @see #setDrawingCacheEnabled(boolean) 4096 * @see #isDrawingCacheEnabled() 4097 * 4098 * @attr ref android.R.styleable#View_drawingCacheQuality 4099 */ 4100 public void setDrawingCacheQuality(int quality) { 4101 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 4102 } 4103 4104 /** 4105 * Returns whether the screen should remain on, corresponding to the current 4106 * value of {@link #KEEP_SCREEN_ON}. 4107 * 4108 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 4109 * 4110 * @see #setKeepScreenOn(boolean) 4111 * 4112 * @attr ref android.R.styleable#View_keepScreenOn 4113 */ 4114 public boolean getKeepScreenOn() { 4115 return (mViewFlags & KEEP_SCREEN_ON) != 0; 4116 } 4117 4118 /** 4119 * Controls whether the screen should remain on, modifying the 4120 * value of {@link #KEEP_SCREEN_ON}. 4121 * 4122 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 4123 * 4124 * @see #getKeepScreenOn() 4125 * 4126 * @attr ref android.R.styleable#View_keepScreenOn 4127 */ 4128 public void setKeepScreenOn(boolean keepScreenOn) { 4129 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 4130 } 4131 4132 /** 4133 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4134 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4135 * 4136 * @attr ref android.R.styleable#View_nextFocusLeft 4137 */ 4138 public int getNextFocusLeftId() { 4139 return mNextFocusLeftId; 4140 } 4141 4142 /** 4143 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4144 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 4145 * decide automatically. 4146 * 4147 * @attr ref android.R.styleable#View_nextFocusLeft 4148 */ 4149 public void setNextFocusLeftId(int nextFocusLeftId) { 4150 mNextFocusLeftId = nextFocusLeftId; 4151 } 4152 4153 /** 4154 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4155 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4156 * 4157 * @attr ref android.R.styleable#View_nextFocusRight 4158 */ 4159 public int getNextFocusRightId() { 4160 return mNextFocusRightId; 4161 } 4162 4163 /** 4164 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4165 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 4166 * decide automatically. 4167 * 4168 * @attr ref android.R.styleable#View_nextFocusRight 4169 */ 4170 public void setNextFocusRightId(int nextFocusRightId) { 4171 mNextFocusRightId = nextFocusRightId; 4172 } 4173 4174 /** 4175 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4176 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4177 * 4178 * @attr ref android.R.styleable#View_nextFocusUp 4179 */ 4180 public int getNextFocusUpId() { 4181 return mNextFocusUpId; 4182 } 4183 4184 /** 4185 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4186 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 4187 * decide automatically. 4188 * 4189 * @attr ref android.R.styleable#View_nextFocusUp 4190 */ 4191 public void setNextFocusUpId(int nextFocusUpId) { 4192 mNextFocusUpId = nextFocusUpId; 4193 } 4194 4195 /** 4196 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4197 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4198 * 4199 * @attr ref android.R.styleable#View_nextFocusDown 4200 */ 4201 public int getNextFocusDownId() { 4202 return mNextFocusDownId; 4203 } 4204 4205 /** 4206 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4207 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 4208 * decide automatically. 4209 * 4210 * @attr ref android.R.styleable#View_nextFocusDown 4211 */ 4212 public void setNextFocusDownId(int nextFocusDownId) { 4213 mNextFocusDownId = nextFocusDownId; 4214 } 4215 4216 /** 4217 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4218 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4219 * 4220 * @attr ref android.R.styleable#View_nextFocusForward 4221 */ 4222 public int getNextFocusForwardId() { 4223 return mNextFocusForwardId; 4224 } 4225 4226 /** 4227 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4228 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 4229 * decide automatically. 4230 * 4231 * @attr ref android.R.styleable#View_nextFocusForward 4232 */ 4233 public void setNextFocusForwardId(int nextFocusForwardId) { 4234 mNextFocusForwardId = nextFocusForwardId; 4235 } 4236 4237 /** 4238 * Returns the visibility of this view and all of its ancestors 4239 * 4240 * @return True if this view and all of its ancestors are {@link #VISIBLE} 4241 */ 4242 public boolean isShown() { 4243 View current = this; 4244 //noinspection ConstantConditions 4245 do { 4246 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 4247 return false; 4248 } 4249 ViewParent parent = current.mParent; 4250 if (parent == null) { 4251 return false; // We are not attached to the view root 4252 } 4253 if (!(parent instanceof View)) { 4254 return true; 4255 } 4256 current = (View) parent; 4257 } while (current != null); 4258 4259 return false; 4260 } 4261 4262 /** 4263 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag 4264 * is set 4265 * 4266 * @param insets Insets for system windows 4267 * 4268 * @return True if this view applied the insets, false otherwise 4269 */ 4270 protected boolean fitSystemWindows(Rect insets) { 4271 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 4272 mPaddingLeft = insets.left; 4273 mPaddingTop = insets.top; 4274 mPaddingRight = insets.right; 4275 mPaddingBottom = insets.bottom; 4276 requestLayout(); 4277 return true; 4278 } 4279 return false; 4280 } 4281 4282 /** 4283 * Returns the visibility status for this view. 4284 * 4285 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4286 * @attr ref android.R.styleable#View_visibility 4287 */ 4288 @ViewDebug.ExportedProperty(mapping = { 4289 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 4290 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 4291 @ViewDebug.IntToString(from = GONE, to = "GONE") 4292 }) 4293 public int getVisibility() { 4294 return mViewFlags & VISIBILITY_MASK; 4295 } 4296 4297 /** 4298 * Set the enabled state of this view. 4299 * 4300 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4301 * @attr ref android.R.styleable#View_visibility 4302 */ 4303 @RemotableViewMethod 4304 public void setVisibility(int visibility) { 4305 setFlags(visibility, VISIBILITY_MASK); 4306 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); 4307 } 4308 4309 /** 4310 * Returns the enabled status for this view. The interpretation of the 4311 * enabled state varies by subclass. 4312 * 4313 * @return True if this view is enabled, false otherwise. 4314 */ 4315 @ViewDebug.ExportedProperty 4316 public boolean isEnabled() { 4317 return (mViewFlags & ENABLED_MASK) == ENABLED; 4318 } 4319 4320 /** 4321 * Set the enabled state of this view. The interpretation of the enabled 4322 * state varies by subclass. 4323 * 4324 * @param enabled True if this view is enabled, false otherwise. 4325 */ 4326 @RemotableViewMethod 4327 public void setEnabled(boolean enabled) { 4328 if (enabled == isEnabled()) return; 4329 4330 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 4331 4332 /* 4333 * The View most likely has to change its appearance, so refresh 4334 * the drawable state. 4335 */ 4336 refreshDrawableState(); 4337 4338 // Invalidate too, since the default behavior for views is to be 4339 // be drawn at 50% alpha rather than to change the drawable. 4340 invalidate(true); 4341 } 4342 4343 /** 4344 * Set whether this view can receive the focus. 4345 * 4346 * Setting this to false will also ensure that this view is not focusable 4347 * in touch mode. 4348 * 4349 * @param focusable If true, this view can receive the focus. 4350 * 4351 * @see #setFocusableInTouchMode(boolean) 4352 * @attr ref android.R.styleable#View_focusable 4353 */ 4354 public void setFocusable(boolean focusable) { 4355 if (!focusable) { 4356 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 4357 } 4358 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 4359 } 4360 4361 /** 4362 * Set whether this view can receive focus while in touch mode. 4363 * 4364 * Setting this to true will also ensure that this view is focusable. 4365 * 4366 * @param focusableInTouchMode If true, this view can receive the focus while 4367 * in touch mode. 4368 * 4369 * @see #setFocusable(boolean) 4370 * @attr ref android.R.styleable#View_focusableInTouchMode 4371 */ 4372 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 4373 // Focusable in touch mode should always be set before the focusable flag 4374 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 4375 // which, in touch mode, will not successfully request focus on this view 4376 // because the focusable in touch mode flag is not set 4377 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 4378 if (focusableInTouchMode) { 4379 setFlags(FOCUSABLE, FOCUSABLE_MASK); 4380 } 4381 } 4382 4383 /** 4384 * Set whether this view should have sound effects enabled for events such as 4385 * clicking and touching. 4386 * 4387 * <p>You may wish to disable sound effects for a view if you already play sounds, 4388 * for instance, a dial key that plays dtmf tones. 4389 * 4390 * @param soundEffectsEnabled whether sound effects are enabled for this view. 4391 * @see #isSoundEffectsEnabled() 4392 * @see #playSoundEffect(int) 4393 * @attr ref android.R.styleable#View_soundEffectsEnabled 4394 */ 4395 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 4396 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 4397 } 4398 4399 /** 4400 * @return whether this view should have sound effects enabled for events such as 4401 * clicking and touching. 4402 * 4403 * @see #setSoundEffectsEnabled(boolean) 4404 * @see #playSoundEffect(int) 4405 * @attr ref android.R.styleable#View_soundEffectsEnabled 4406 */ 4407 @ViewDebug.ExportedProperty 4408 public boolean isSoundEffectsEnabled() { 4409 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 4410 } 4411 4412 /** 4413 * Set whether this view should have haptic feedback for events such as 4414 * long presses. 4415 * 4416 * <p>You may wish to disable haptic feedback if your view already controls 4417 * its own haptic feedback. 4418 * 4419 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 4420 * @see #isHapticFeedbackEnabled() 4421 * @see #performHapticFeedback(int) 4422 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4423 */ 4424 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 4425 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 4426 } 4427 4428 /** 4429 * @return whether this view should have haptic feedback enabled for events 4430 * long presses. 4431 * 4432 * @see #setHapticFeedbackEnabled(boolean) 4433 * @see #performHapticFeedback(int) 4434 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4435 */ 4436 @ViewDebug.ExportedProperty 4437 public boolean isHapticFeedbackEnabled() { 4438 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 4439 } 4440 4441 /** 4442 * Returns the layout direction for this view. 4443 * 4444 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 4445 * {@link #LAYOUT_DIRECTION_RTL}, 4446 * {@link #LAYOUT_DIRECTION_INHERIT} or 4447 * {@link #LAYOUT_DIRECTION_LOCALE}. 4448 * @attr ref android.R.styleable#View_layoutDirection 4449 * 4450 * @hide 4451 */ 4452 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4453 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 4454 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 4455 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 4456 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 4457 }) 4458 public int getLayoutDirection() { 4459 return mViewFlags & LAYOUT_DIRECTION_MASK; 4460 } 4461 4462 /** 4463 * Set the layout direction for this view. This will propagate a reset of layout direction 4464 * resolution to the view's children and resolve layout direction for this view. 4465 * 4466 * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR}, 4467 * {@link #LAYOUT_DIRECTION_RTL}, 4468 * {@link #LAYOUT_DIRECTION_INHERIT} or 4469 * {@link #LAYOUT_DIRECTION_LOCALE}. 4470 * 4471 * @attr ref android.R.styleable#View_layoutDirection 4472 * 4473 * @hide 4474 */ 4475 @RemotableViewMethod 4476 public void setLayoutDirection(int layoutDirection) { 4477 if (getLayoutDirection() != layoutDirection) { 4478 resetResolvedLayoutDirection(); 4479 // Setting the flag will also request a layout. 4480 setFlags(layoutDirection, LAYOUT_DIRECTION_MASK); 4481 } 4482 } 4483 4484 /** 4485 * Returns the resolved layout direction for this view. 4486 * 4487 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 4488 * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL. 4489 * 4490 * @hide 4491 */ 4492 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4493 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 4494 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 4495 }) 4496 public int getResolvedLayoutDirection() { 4497 resolveLayoutDirectionIfNeeded(); 4498 return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ? 4499 LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 4500 } 4501 4502 /** 4503 * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from 4504 * layout attribute and/or the inherited value from the parent.</p> 4505 * 4506 * @return true if the layout is right-to-left. 4507 * 4508 * @hide 4509 */ 4510 @ViewDebug.ExportedProperty(category = "layout") 4511 public boolean isLayoutRtl() { 4512 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 4513 } 4514 4515 /** 4516 * If this view doesn't do any drawing on its own, set this flag to 4517 * allow further optimizations. By default, this flag is not set on 4518 * View, but could be set on some View subclasses such as ViewGroup. 4519 * 4520 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 4521 * you should clear this flag. 4522 * 4523 * @param willNotDraw whether or not this View draw on its own 4524 */ 4525 public void setWillNotDraw(boolean willNotDraw) { 4526 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 4527 } 4528 4529 /** 4530 * Returns whether or not this View draws on its own. 4531 * 4532 * @return true if this view has nothing to draw, false otherwise 4533 */ 4534 @ViewDebug.ExportedProperty(category = "drawing") 4535 public boolean willNotDraw() { 4536 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 4537 } 4538 4539 /** 4540 * When a View's drawing cache is enabled, drawing is redirected to an 4541 * offscreen bitmap. Some views, like an ImageView, must be able to 4542 * bypass this mechanism if they already draw a single bitmap, to avoid 4543 * unnecessary usage of the memory. 4544 * 4545 * @param willNotCacheDrawing true if this view does not cache its 4546 * drawing, false otherwise 4547 */ 4548 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 4549 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 4550 } 4551 4552 /** 4553 * Returns whether or not this View can cache its drawing or not. 4554 * 4555 * @return true if this view does not cache its drawing, false otherwise 4556 */ 4557 @ViewDebug.ExportedProperty(category = "drawing") 4558 public boolean willNotCacheDrawing() { 4559 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 4560 } 4561 4562 /** 4563 * Indicates whether this view reacts to click events or not. 4564 * 4565 * @return true if the view is clickable, false otherwise 4566 * 4567 * @see #setClickable(boolean) 4568 * @attr ref android.R.styleable#View_clickable 4569 */ 4570 @ViewDebug.ExportedProperty 4571 public boolean isClickable() { 4572 return (mViewFlags & CLICKABLE) == CLICKABLE; 4573 } 4574 4575 /** 4576 * Enables or disables click events for this view. When a view 4577 * is clickable it will change its state to "pressed" on every click. 4578 * Subclasses should set the view clickable to visually react to 4579 * user's clicks. 4580 * 4581 * @param clickable true to make the view clickable, false otherwise 4582 * 4583 * @see #isClickable() 4584 * @attr ref android.R.styleable#View_clickable 4585 */ 4586 public void setClickable(boolean clickable) { 4587 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 4588 } 4589 4590 /** 4591 * Indicates whether this view reacts to long click events or not. 4592 * 4593 * @return true if the view is long clickable, false otherwise 4594 * 4595 * @see #setLongClickable(boolean) 4596 * @attr ref android.R.styleable#View_longClickable 4597 */ 4598 public boolean isLongClickable() { 4599 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 4600 } 4601 4602 /** 4603 * Enables or disables long click events for this view. When a view is long 4604 * clickable it reacts to the user holding down the button for a longer 4605 * duration than a tap. This event can either launch the listener or a 4606 * context menu. 4607 * 4608 * @param longClickable true to make the view long clickable, false otherwise 4609 * @see #isLongClickable() 4610 * @attr ref android.R.styleable#View_longClickable 4611 */ 4612 public void setLongClickable(boolean longClickable) { 4613 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 4614 } 4615 4616 /** 4617 * Sets the pressed state for this view. 4618 * 4619 * @see #isClickable() 4620 * @see #setClickable(boolean) 4621 * 4622 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 4623 * the View's internal state from a previously set "pressed" state. 4624 */ 4625 public void setPressed(boolean pressed) { 4626 if (pressed) { 4627 mPrivateFlags |= PRESSED; 4628 } else { 4629 mPrivateFlags &= ~PRESSED; 4630 } 4631 refreshDrawableState(); 4632 dispatchSetPressed(pressed); 4633 } 4634 4635 /** 4636 * Dispatch setPressed to all of this View's children. 4637 * 4638 * @see #setPressed(boolean) 4639 * 4640 * @param pressed The new pressed state 4641 */ 4642 protected void dispatchSetPressed(boolean pressed) { 4643 } 4644 4645 /** 4646 * Indicates whether the view is currently in pressed state. Unless 4647 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 4648 * the pressed state. 4649 * 4650 * @see #setPressed(boolean) 4651 * @see #isClickable() 4652 * @see #setClickable(boolean) 4653 * 4654 * @return true if the view is currently pressed, false otherwise 4655 */ 4656 public boolean isPressed() { 4657 return (mPrivateFlags & PRESSED) == PRESSED; 4658 } 4659 4660 /** 4661 * Indicates whether this view will save its state (that is, 4662 * whether its {@link #onSaveInstanceState} method will be called). 4663 * 4664 * @return Returns true if the view state saving is enabled, else false. 4665 * 4666 * @see #setSaveEnabled(boolean) 4667 * @attr ref android.R.styleable#View_saveEnabled 4668 */ 4669 public boolean isSaveEnabled() { 4670 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 4671 } 4672 4673 /** 4674 * Controls whether the saving of this view's state is 4675 * enabled (that is, whether its {@link #onSaveInstanceState} method 4676 * will be called). Note that even if freezing is enabled, the 4677 * view still must have an id assigned to it (via {@link #setId(int)}) 4678 * for its state to be saved. This flag can only disable the 4679 * saving of this view; any child views may still have their state saved. 4680 * 4681 * @param enabled Set to false to <em>disable</em> state saving, or true 4682 * (the default) to allow it. 4683 * 4684 * @see #isSaveEnabled() 4685 * @see #setId(int) 4686 * @see #onSaveInstanceState() 4687 * @attr ref android.R.styleable#View_saveEnabled 4688 */ 4689 public void setSaveEnabled(boolean enabled) { 4690 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 4691 } 4692 4693 /** 4694 * Gets whether the framework should discard touches when the view's 4695 * window is obscured by another visible window. 4696 * Refer to the {@link View} security documentation for more details. 4697 * 4698 * @return True if touch filtering is enabled. 4699 * 4700 * @see #setFilterTouchesWhenObscured(boolean) 4701 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4702 */ 4703 @ViewDebug.ExportedProperty 4704 public boolean getFilterTouchesWhenObscured() { 4705 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 4706 } 4707 4708 /** 4709 * Sets whether the framework should discard touches when the view's 4710 * window is obscured by another visible window. 4711 * Refer to the {@link View} security documentation for more details. 4712 * 4713 * @param enabled True if touch filtering should be enabled. 4714 * 4715 * @see #getFilterTouchesWhenObscured 4716 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4717 */ 4718 public void setFilterTouchesWhenObscured(boolean enabled) { 4719 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 4720 FILTER_TOUCHES_WHEN_OBSCURED); 4721 } 4722 4723 /** 4724 * Indicates whether the entire hierarchy under this view will save its 4725 * state when a state saving traversal occurs from its parent. The default 4726 * is true; if false, these views will not be saved unless 4727 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4728 * 4729 * @return Returns true if the view state saving from parent is enabled, else false. 4730 * 4731 * @see #setSaveFromParentEnabled(boolean) 4732 */ 4733 public boolean isSaveFromParentEnabled() { 4734 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 4735 } 4736 4737 /** 4738 * Controls whether the entire hierarchy under this view will save its 4739 * state when a state saving traversal occurs from its parent. The default 4740 * is true; if false, these views will not be saved unless 4741 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4742 * 4743 * @param enabled Set to false to <em>disable</em> state saving, or true 4744 * (the default) to allow it. 4745 * 4746 * @see #isSaveFromParentEnabled() 4747 * @see #setId(int) 4748 * @see #onSaveInstanceState() 4749 */ 4750 public void setSaveFromParentEnabled(boolean enabled) { 4751 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 4752 } 4753 4754 4755 /** 4756 * Returns whether this View is able to take focus. 4757 * 4758 * @return True if this view can take focus, or false otherwise. 4759 * @attr ref android.R.styleable#View_focusable 4760 */ 4761 @ViewDebug.ExportedProperty(category = "focus") 4762 public final boolean isFocusable() { 4763 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 4764 } 4765 4766 /** 4767 * When a view is focusable, it may not want to take focus when in touch mode. 4768 * For example, a button would like focus when the user is navigating via a D-pad 4769 * so that the user can click on it, but once the user starts touching the screen, 4770 * the button shouldn't take focus 4771 * @return Whether the view is focusable in touch mode. 4772 * @attr ref android.R.styleable#View_focusableInTouchMode 4773 */ 4774 @ViewDebug.ExportedProperty 4775 public final boolean isFocusableInTouchMode() { 4776 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 4777 } 4778 4779 /** 4780 * Find the nearest view in the specified direction that can take focus. 4781 * This does not actually give focus to that view. 4782 * 4783 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4784 * 4785 * @return The nearest focusable in the specified direction, or null if none 4786 * can be found. 4787 */ 4788 public View focusSearch(int direction) { 4789 if (mParent != null) { 4790 return mParent.focusSearch(this, direction); 4791 } else { 4792 return null; 4793 } 4794 } 4795 4796 /** 4797 * This method is the last chance for the focused view and its ancestors to 4798 * respond to an arrow key. This is called when the focused view did not 4799 * consume the key internally, nor could the view system find a new view in 4800 * the requested direction to give focus to. 4801 * 4802 * @param focused The currently focused view. 4803 * @param direction The direction focus wants to move. One of FOCUS_UP, 4804 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 4805 * @return True if the this view consumed this unhandled move. 4806 */ 4807 public boolean dispatchUnhandledMove(View focused, int direction) { 4808 return false; 4809 } 4810 4811 /** 4812 * If a user manually specified the next view id for a particular direction, 4813 * use the root to look up the view. 4814 * @param root The root view of the hierarchy containing this view. 4815 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 4816 * or FOCUS_BACKWARD. 4817 * @return The user specified next view, or null if there is none. 4818 */ 4819 View findUserSetNextFocus(View root, int direction) { 4820 switch (direction) { 4821 case FOCUS_LEFT: 4822 if (mNextFocusLeftId == View.NO_ID) return null; 4823 return findViewShouldExist(root, mNextFocusLeftId); 4824 case FOCUS_RIGHT: 4825 if (mNextFocusRightId == View.NO_ID) return null; 4826 return findViewShouldExist(root, mNextFocusRightId); 4827 case FOCUS_UP: 4828 if (mNextFocusUpId == View.NO_ID) return null; 4829 return findViewShouldExist(root, mNextFocusUpId); 4830 case FOCUS_DOWN: 4831 if (mNextFocusDownId == View.NO_ID) return null; 4832 return findViewShouldExist(root, mNextFocusDownId); 4833 case FOCUS_FORWARD: 4834 if (mNextFocusForwardId == View.NO_ID) return null; 4835 return findViewShouldExist(root, mNextFocusForwardId); 4836 case FOCUS_BACKWARD: { 4837 final int id = mID; 4838 return root.findViewByPredicate(new Predicate<View>() { 4839 @Override 4840 public boolean apply(View t) { 4841 return t.mNextFocusForwardId == id; 4842 } 4843 }); 4844 } 4845 } 4846 return null; 4847 } 4848 4849 private static View findViewShouldExist(View root, int childViewId) { 4850 View result = root.findViewById(childViewId); 4851 if (result == null) { 4852 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified " 4853 + "by user for id " + childViewId); 4854 } 4855 return result; 4856 } 4857 4858 /** 4859 * Find and return all focusable views that are descendants of this view, 4860 * possibly including this view if it is focusable itself. 4861 * 4862 * @param direction The direction of the focus 4863 * @return A list of focusable views 4864 */ 4865 public ArrayList<View> getFocusables(int direction) { 4866 ArrayList<View> result = new ArrayList<View>(24); 4867 addFocusables(result, direction); 4868 return result; 4869 } 4870 4871 /** 4872 * Add any focusable views that are descendants of this view (possibly 4873 * including this view if it is focusable itself) to views. If we are in touch mode, 4874 * only add views that are also focusable in touch mode. 4875 * 4876 * @param views Focusable views found so far 4877 * @param direction The direction of the focus 4878 */ 4879 public void addFocusables(ArrayList<View> views, int direction) { 4880 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 4881 } 4882 4883 /** 4884 * Adds any focusable views that are descendants of this view (possibly 4885 * including this view if it is focusable itself) to views. This method 4886 * adds all focusable views regardless if we are in touch mode or 4887 * only views focusable in touch mode if we are in touch mode depending on 4888 * the focusable mode paramater. 4889 * 4890 * @param views Focusable views found so far or null if all we are interested is 4891 * the number of focusables. 4892 * @param direction The direction of the focus. 4893 * @param focusableMode The type of focusables to be added. 4894 * 4895 * @see #FOCUSABLES_ALL 4896 * @see #FOCUSABLES_TOUCH_MODE 4897 */ 4898 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 4899 if (!isFocusable()) { 4900 return; 4901 } 4902 4903 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 4904 isInTouchMode() && !isFocusableInTouchMode()) { 4905 return; 4906 } 4907 4908 if (views != null) { 4909 views.add(this); 4910 } 4911 } 4912 4913 /** 4914 * Finds the Views that contain given text. The containment is case insensitive. 4915 * As View's text is considered any text content that View renders. 4916 * 4917 * @param outViews The output list of matching Views. 4918 * @param text The text to match against. 4919 */ 4920 public void findViewsWithText(ArrayList<View> outViews, CharSequence text) { 4921 } 4922 4923 /** 4924 * Find and return all touchable views that are descendants of this view, 4925 * possibly including this view if it is touchable itself. 4926 * 4927 * @return A list of touchable views 4928 */ 4929 public ArrayList<View> getTouchables() { 4930 ArrayList<View> result = new ArrayList<View>(); 4931 addTouchables(result); 4932 return result; 4933 } 4934 4935 /** 4936 * Add any touchable views that are descendants of this view (possibly 4937 * including this view if it is touchable itself) to views. 4938 * 4939 * @param views Touchable views found so far 4940 */ 4941 public void addTouchables(ArrayList<View> views) { 4942 final int viewFlags = mViewFlags; 4943 4944 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 4945 && (viewFlags & ENABLED_MASK) == ENABLED) { 4946 views.add(this); 4947 } 4948 } 4949 4950 /** 4951 * Call this to try to give focus to a specific view or to one of its 4952 * descendants. 4953 * 4954 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 4955 * false), or if it is focusable and it is not focusable in touch mode 4956 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 4957 * 4958 * See also {@link #focusSearch(int)}, which is what you call to say that you 4959 * have focus, and you want your parent to look for the next one. 4960 * 4961 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 4962 * {@link #FOCUS_DOWN} and <code>null</code>. 4963 * 4964 * @return Whether this view or one of its descendants actually took focus. 4965 */ 4966 public final boolean requestFocus() { 4967 return requestFocus(View.FOCUS_DOWN); 4968 } 4969 4970 4971 /** 4972 * Call this to try to give focus to a specific view or to one of its 4973 * descendants and give it a hint about what direction focus is heading. 4974 * 4975 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 4976 * false), or if it is focusable and it is not focusable in touch mode 4977 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 4978 * 4979 * See also {@link #focusSearch(int)}, which is what you call to say that you 4980 * have focus, and you want your parent to look for the next one. 4981 * 4982 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 4983 * <code>null</code> set for the previously focused rectangle. 4984 * 4985 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4986 * @return Whether this view or one of its descendants actually took focus. 4987 */ 4988 public final boolean requestFocus(int direction) { 4989 return requestFocus(direction, null); 4990 } 4991 4992 /** 4993 * Call this to try to give focus to a specific view or to one of its descendants 4994 * and give it hints about the direction and a specific rectangle that the focus 4995 * is coming from. The rectangle can help give larger views a finer grained hint 4996 * about where focus is coming from, and therefore, where to show selection, or 4997 * forward focus change internally. 4998 * 4999 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5000 * false), or if it is focusable and it is not focusable in touch mode 5001 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5002 * 5003 * A View will not take focus if it is not visible. 5004 * 5005 * A View will not take focus if one of its parents has 5006 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 5007 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 5008 * 5009 * See also {@link #focusSearch(int)}, which is what you call to say that you 5010 * have focus, and you want your parent to look for the next one. 5011 * 5012 * You may wish to override this method if your custom {@link View} has an internal 5013 * {@link View} that it wishes to forward the request to. 5014 * 5015 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5016 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 5017 * to give a finer grained hint about where focus is coming from. May be null 5018 * if there is no hint. 5019 * @return Whether this view or one of its descendants actually took focus. 5020 */ 5021 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 5022 // need to be focusable 5023 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 5024 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5025 return false; 5026 } 5027 5028 // need to be focusable in touch mode if in touch mode 5029 if (isInTouchMode() && 5030 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 5031 return false; 5032 } 5033 5034 // need to not have any parents blocking us 5035 if (hasAncestorThatBlocksDescendantFocus()) { 5036 return false; 5037 } 5038 5039 handleFocusGainInternal(direction, previouslyFocusedRect); 5040 return true; 5041 } 5042 5043 /** Gets the ViewAncestor, or null if not attached. */ 5044 /*package*/ ViewRootImpl getViewRootImpl() { 5045 View root = getRootView(); 5046 return root != null ? (ViewRootImpl)root.getParent() : null; 5047 } 5048 5049 /** 5050 * Call this to try to give focus to a specific view or to one of its descendants. This is a 5051 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 5052 * touch mode to request focus when they are touched. 5053 * 5054 * @return Whether this view or one of its descendants actually took focus. 5055 * 5056 * @see #isInTouchMode() 5057 * 5058 */ 5059 public final boolean requestFocusFromTouch() { 5060 // Leave touch mode if we need to 5061 if (isInTouchMode()) { 5062 ViewRootImpl viewRoot = getViewRootImpl(); 5063 if (viewRoot != null) { 5064 viewRoot.ensureTouchMode(false); 5065 } 5066 } 5067 return requestFocus(View.FOCUS_DOWN); 5068 } 5069 5070 /** 5071 * @return Whether any ancestor of this view blocks descendant focus. 5072 */ 5073 private boolean hasAncestorThatBlocksDescendantFocus() { 5074 ViewParent ancestor = mParent; 5075 while (ancestor instanceof ViewGroup) { 5076 final ViewGroup vgAncestor = (ViewGroup) ancestor; 5077 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 5078 return true; 5079 } else { 5080 ancestor = vgAncestor.getParent(); 5081 } 5082 } 5083 return false; 5084 } 5085 5086 /** 5087 * @hide 5088 */ 5089 public void dispatchStartTemporaryDetach() { 5090 onStartTemporaryDetach(); 5091 } 5092 5093 /** 5094 * This is called when a container is going to temporarily detach a child, with 5095 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 5096 * It will either be followed by {@link #onFinishTemporaryDetach()} or 5097 * {@link #onDetachedFromWindow()} when the container is done. 5098 */ 5099 public void onStartTemporaryDetach() { 5100 removeUnsetPressCallback(); 5101 mPrivateFlags |= CANCEL_NEXT_UP_EVENT; 5102 } 5103 5104 /** 5105 * @hide 5106 */ 5107 public void dispatchFinishTemporaryDetach() { 5108 onFinishTemporaryDetach(); 5109 } 5110 5111 /** 5112 * Called after {@link #onStartTemporaryDetach} when the container is done 5113 * changing the view. 5114 */ 5115 public void onFinishTemporaryDetach() { 5116 } 5117 5118 /** 5119 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 5120 * for this view's window. Returns null if the view is not currently attached 5121 * to the window. Normally you will not need to use this directly, but 5122 * just use the standard high-level event callbacks like 5123 * {@link #onKeyDown(int, KeyEvent)}. 5124 */ 5125 public KeyEvent.DispatcherState getKeyDispatcherState() { 5126 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 5127 } 5128 5129 /** 5130 * Dispatch a key event before it is processed by any input method 5131 * associated with the view hierarchy. This can be used to intercept 5132 * key events in special situations before the IME consumes them; a 5133 * typical example would be handling the BACK key to update the application's 5134 * UI instead of allowing the IME to see it and close itself. 5135 * 5136 * @param event The key event to be dispatched. 5137 * @return True if the event was handled, false otherwise. 5138 */ 5139 public boolean dispatchKeyEventPreIme(KeyEvent event) { 5140 return onKeyPreIme(event.getKeyCode(), event); 5141 } 5142 5143 /** 5144 * Dispatch a key event to the next view on the focus path. This path runs 5145 * from the top of the view tree down to the currently focused view. If this 5146 * view has focus, it will dispatch to itself. Otherwise it will dispatch 5147 * the next node down the focus path. This method also fires any key 5148 * listeners. 5149 * 5150 * @param event The key event to be dispatched. 5151 * @return True if the event was handled, false otherwise. 5152 */ 5153 public boolean dispatchKeyEvent(KeyEvent event) { 5154 if (mInputEventConsistencyVerifier != null) { 5155 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 5156 } 5157 5158 // Give any attached key listener a first crack at the event. 5159 //noinspection SimplifiableIfStatement 5160 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5161 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 5162 return true; 5163 } 5164 5165 if (event.dispatch(this, mAttachInfo != null 5166 ? mAttachInfo.mKeyDispatchState : null, this)) { 5167 return true; 5168 } 5169 5170 if (mInputEventConsistencyVerifier != null) { 5171 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5172 } 5173 return false; 5174 } 5175 5176 /** 5177 * Dispatches a key shortcut event. 5178 * 5179 * @param event The key event to be dispatched. 5180 * @return True if the event was handled by the view, false otherwise. 5181 */ 5182 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 5183 return onKeyShortcut(event.getKeyCode(), event); 5184 } 5185 5186 /** 5187 * Pass the touch screen motion event down to the target view, or this 5188 * view if it is the target. 5189 * 5190 * @param event The motion event to be dispatched. 5191 * @return True if the event was handled by the view, false otherwise. 5192 */ 5193 public boolean dispatchTouchEvent(MotionEvent event) { 5194 if (mInputEventConsistencyVerifier != null) { 5195 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 5196 } 5197 5198 if (onFilterTouchEventForSecurity(event)) { 5199 //noinspection SimplifiableIfStatement 5200 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && 5201 mOnTouchListener.onTouch(this, event)) { 5202 return true; 5203 } 5204 5205 if (onTouchEvent(event)) { 5206 return true; 5207 } 5208 } 5209 5210 if (mInputEventConsistencyVerifier != null) { 5211 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5212 } 5213 return false; 5214 } 5215 5216 /** 5217 * Filter the touch event to apply security policies. 5218 * 5219 * @param event The motion event to be filtered. 5220 * @return True if the event should be dispatched, false if the event should be dropped. 5221 * 5222 * @see #getFilterTouchesWhenObscured 5223 */ 5224 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 5225 //noinspection RedundantIfStatement 5226 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 5227 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 5228 // Window is obscured, drop this touch. 5229 return false; 5230 } 5231 return true; 5232 } 5233 5234 /** 5235 * Pass a trackball motion event down to the focused view. 5236 * 5237 * @param event The motion event to be dispatched. 5238 * @return True if the event was handled by the view, false otherwise. 5239 */ 5240 public boolean dispatchTrackballEvent(MotionEvent event) { 5241 if (mInputEventConsistencyVerifier != null) { 5242 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 5243 } 5244 5245 return onTrackballEvent(event); 5246 } 5247 5248 /** 5249 * Dispatch a generic motion event. 5250 * <p> 5251 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5252 * are delivered to the view under the pointer. All other generic motion events are 5253 * delivered to the focused view. Hover events are handled specially and are delivered 5254 * to {@link #onHoverEvent(MotionEvent)}. 5255 * </p> 5256 * 5257 * @param event The motion event to be dispatched. 5258 * @return True if the event was handled by the view, false otherwise. 5259 */ 5260 public boolean dispatchGenericMotionEvent(MotionEvent event) { 5261 if (mInputEventConsistencyVerifier != null) { 5262 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 5263 } 5264 5265 final int source = event.getSource(); 5266 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5267 final int action = event.getAction(); 5268 if (action == MotionEvent.ACTION_HOVER_ENTER 5269 || action == MotionEvent.ACTION_HOVER_MOVE 5270 || action == MotionEvent.ACTION_HOVER_EXIT) { 5271 if (dispatchHoverEvent(event)) { 5272 // For compatibility with existing applications that handled HOVER_MOVE 5273 // events in onGenericMotionEvent, dispatch the event there. The 5274 // onHoverEvent method did not exist at the time. 5275 if (action == MotionEvent.ACTION_HOVER_MOVE) { 5276 dispatchGenericMotionEventInternal(event); 5277 } 5278 return true; 5279 } 5280 } else if (dispatchGenericPointerEvent(event)) { 5281 return true; 5282 } 5283 } else if (dispatchGenericFocusedEvent(event)) { 5284 return true; 5285 } 5286 5287 if (dispatchGenericMotionEventInternal(event)) { 5288 return true; 5289 } 5290 5291 if (mInputEventConsistencyVerifier != null) { 5292 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5293 } 5294 return false; 5295 } 5296 5297 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 5298 //noinspection SimplifiableIfStatement 5299 if (mOnGenericMotionListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5300 && mOnGenericMotionListener.onGenericMotion(this, event)) { 5301 return true; 5302 } 5303 5304 if (onGenericMotionEvent(event)) { 5305 return true; 5306 } 5307 5308 if (mInputEventConsistencyVerifier != null) { 5309 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5310 } 5311 return false; 5312 } 5313 5314 /** 5315 * Dispatch a hover event. 5316 * <p> 5317 * Do not call this method directly. 5318 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5319 * </p> 5320 * 5321 * @param event The motion event to be dispatched. 5322 * @return True if the event was handled by the view, false otherwise. 5323 */ 5324 protected boolean dispatchHoverEvent(MotionEvent event) { 5325 switch (event.getAction()) { 5326 case MotionEvent.ACTION_HOVER_ENTER: 5327 if (!hasHoveredChild() && !mSendingHoverAccessibilityEvents) { 5328 mSendingHoverAccessibilityEvents = true; 5329 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 5330 } 5331 break; 5332 case MotionEvent.ACTION_HOVER_EXIT: 5333 if (mSendingHoverAccessibilityEvents) { 5334 mSendingHoverAccessibilityEvents = false; 5335 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 5336 } 5337 break; 5338 } 5339 5340 //noinspection SimplifiableIfStatement 5341 if (mOnHoverListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5342 && mOnHoverListener.onHover(this, event)) { 5343 return true; 5344 } 5345 5346 return onHoverEvent(event); 5347 } 5348 5349 /** 5350 * Returns true if the view has a child to which it has recently sent 5351 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 5352 * it does not have a hovered child, then it must be the innermost hovered view. 5353 * @hide 5354 */ 5355 protected boolean hasHoveredChild() { 5356 return false; 5357 } 5358 5359 /** 5360 * Dispatch a generic motion event to the view under the first pointer. 5361 * <p> 5362 * Do not call this method directly. 5363 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5364 * </p> 5365 * 5366 * @param event The motion event to be dispatched. 5367 * @return True if the event was handled by the view, false otherwise. 5368 */ 5369 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 5370 return false; 5371 } 5372 5373 /** 5374 * Dispatch a generic motion event to the currently focused view. 5375 * <p> 5376 * Do not call this method directly. 5377 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5378 * </p> 5379 * 5380 * @param event The motion event to be dispatched. 5381 * @return True if the event was handled by the view, false otherwise. 5382 */ 5383 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 5384 return false; 5385 } 5386 5387 /** 5388 * Dispatch a pointer event. 5389 * <p> 5390 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 5391 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 5392 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 5393 * and should not be expected to handle other pointing device features. 5394 * </p> 5395 * 5396 * @param event The motion event to be dispatched. 5397 * @return True if the event was handled by the view, false otherwise. 5398 * @hide 5399 */ 5400 public final boolean dispatchPointerEvent(MotionEvent event) { 5401 if (event.isTouchEvent()) { 5402 return dispatchTouchEvent(event); 5403 } else { 5404 return dispatchGenericMotionEvent(event); 5405 } 5406 } 5407 5408 /** 5409 * Called when the window containing this view gains or loses window focus. 5410 * ViewGroups should override to route to their children. 5411 * 5412 * @param hasFocus True if the window containing this view now has focus, 5413 * false otherwise. 5414 */ 5415 public void dispatchWindowFocusChanged(boolean hasFocus) { 5416 onWindowFocusChanged(hasFocus); 5417 } 5418 5419 /** 5420 * Called when the window containing this view gains or loses focus. Note 5421 * that this is separate from view focus: to receive key events, both 5422 * your view and its window must have focus. If a window is displayed 5423 * on top of yours that takes input focus, then your own window will lose 5424 * focus but the view focus will remain unchanged. 5425 * 5426 * @param hasWindowFocus True if the window containing this view now has 5427 * focus, false otherwise. 5428 */ 5429 public void onWindowFocusChanged(boolean hasWindowFocus) { 5430 InputMethodManager imm = InputMethodManager.peekInstance(); 5431 if (!hasWindowFocus) { 5432 if (isPressed()) { 5433 setPressed(false); 5434 } 5435 if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5436 imm.focusOut(this); 5437 } 5438 removeLongPressCallback(); 5439 removeTapCallback(); 5440 onFocusLost(); 5441 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5442 imm.focusIn(this); 5443 } 5444 refreshDrawableState(); 5445 } 5446 5447 /** 5448 * Returns true if this view is in a window that currently has window focus. 5449 * Note that this is not the same as the view itself having focus. 5450 * 5451 * @return True if this view is in a window that currently has window focus. 5452 */ 5453 public boolean hasWindowFocus() { 5454 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 5455 } 5456 5457 /** 5458 * Dispatch a view visibility change down the view hierarchy. 5459 * ViewGroups should override to route to their children. 5460 * @param changedView The view whose visibility changed. Could be 'this' or 5461 * an ancestor view. 5462 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5463 * {@link #INVISIBLE} or {@link #GONE}. 5464 */ 5465 protected void dispatchVisibilityChanged(View changedView, int visibility) { 5466 onVisibilityChanged(changedView, visibility); 5467 } 5468 5469 /** 5470 * Called when the visibility of the view or an ancestor of the view is changed. 5471 * @param changedView The view whose visibility changed. Could be 'this' or 5472 * an ancestor view. 5473 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5474 * {@link #INVISIBLE} or {@link #GONE}. 5475 */ 5476 protected void onVisibilityChanged(View changedView, int visibility) { 5477 if (visibility == VISIBLE) { 5478 if (mAttachInfo != null) { 5479 initialAwakenScrollBars(); 5480 } else { 5481 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH; 5482 } 5483 } 5484 } 5485 5486 /** 5487 * Dispatch a hint about whether this view is displayed. For instance, when 5488 * a View moves out of the screen, it might receives a display hint indicating 5489 * the view is not displayed. Applications should not <em>rely</em> on this hint 5490 * as there is no guarantee that they will receive one. 5491 * 5492 * @param hint A hint about whether or not this view is displayed: 5493 * {@link #VISIBLE} or {@link #INVISIBLE}. 5494 */ 5495 public void dispatchDisplayHint(int hint) { 5496 onDisplayHint(hint); 5497 } 5498 5499 /** 5500 * Gives this view a hint about whether is displayed or not. For instance, when 5501 * a View moves out of the screen, it might receives a display hint indicating 5502 * the view is not displayed. Applications should not <em>rely</em> on this hint 5503 * as there is no guarantee that they will receive one. 5504 * 5505 * @param hint A hint about whether or not this view is displayed: 5506 * {@link #VISIBLE} or {@link #INVISIBLE}. 5507 */ 5508 protected void onDisplayHint(int hint) { 5509 } 5510 5511 /** 5512 * Dispatch a window visibility change down the view hierarchy. 5513 * ViewGroups should override to route to their children. 5514 * 5515 * @param visibility The new visibility of the window. 5516 * 5517 * @see #onWindowVisibilityChanged(int) 5518 */ 5519 public void dispatchWindowVisibilityChanged(int visibility) { 5520 onWindowVisibilityChanged(visibility); 5521 } 5522 5523 /** 5524 * Called when the window containing has change its visibility 5525 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 5526 * that this tells you whether or not your window is being made visible 5527 * to the window manager; this does <em>not</em> tell you whether or not 5528 * your window is obscured by other windows on the screen, even if it 5529 * is itself visible. 5530 * 5531 * @param visibility The new visibility of the window. 5532 */ 5533 protected void onWindowVisibilityChanged(int visibility) { 5534 if (visibility == VISIBLE) { 5535 initialAwakenScrollBars(); 5536 } 5537 } 5538 5539 /** 5540 * Returns the current visibility of the window this view is attached to 5541 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 5542 * 5543 * @return Returns the current visibility of the view's window. 5544 */ 5545 public int getWindowVisibility() { 5546 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 5547 } 5548 5549 /** 5550 * Retrieve the overall visible display size in which the window this view is 5551 * attached to has been positioned in. This takes into account screen 5552 * decorations above the window, for both cases where the window itself 5553 * is being position inside of them or the window is being placed under 5554 * then and covered insets are used for the window to position its content 5555 * inside. In effect, this tells you the available area where content can 5556 * be placed and remain visible to users. 5557 * 5558 * <p>This function requires an IPC back to the window manager to retrieve 5559 * the requested information, so should not be used in performance critical 5560 * code like drawing. 5561 * 5562 * @param outRect Filled in with the visible display frame. If the view 5563 * is not attached to a window, this is simply the raw display size. 5564 */ 5565 public void getWindowVisibleDisplayFrame(Rect outRect) { 5566 if (mAttachInfo != null) { 5567 try { 5568 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 5569 } catch (RemoteException e) { 5570 return; 5571 } 5572 // XXX This is really broken, and probably all needs to be done 5573 // in the window manager, and we need to know more about whether 5574 // we want the area behind or in front of the IME. 5575 final Rect insets = mAttachInfo.mVisibleInsets; 5576 outRect.left += insets.left; 5577 outRect.top += insets.top; 5578 outRect.right -= insets.right; 5579 outRect.bottom -= insets.bottom; 5580 return; 5581 } 5582 Display d = WindowManagerImpl.getDefault().getDefaultDisplay(); 5583 d.getRectSize(outRect); 5584 } 5585 5586 /** 5587 * Dispatch a notification about a resource configuration change down 5588 * the view hierarchy. 5589 * ViewGroups should override to route to their children. 5590 * 5591 * @param newConfig The new resource configuration. 5592 * 5593 * @see #onConfigurationChanged(android.content.res.Configuration) 5594 */ 5595 public void dispatchConfigurationChanged(Configuration newConfig) { 5596 onConfigurationChanged(newConfig); 5597 } 5598 5599 /** 5600 * Called when the current configuration of the resources being used 5601 * by the application have changed. You can use this to decide when 5602 * to reload resources that can changed based on orientation and other 5603 * configuration characterstics. You only need to use this if you are 5604 * not relying on the normal {@link android.app.Activity} mechanism of 5605 * recreating the activity instance upon a configuration change. 5606 * 5607 * @param newConfig The new resource configuration. 5608 */ 5609 protected void onConfigurationChanged(Configuration newConfig) { 5610 } 5611 5612 /** 5613 * Private function to aggregate all per-view attributes in to the view 5614 * root. 5615 */ 5616 void dispatchCollectViewAttributes(int visibility) { 5617 performCollectViewAttributes(visibility); 5618 } 5619 5620 void performCollectViewAttributes(int visibility) { 5621 if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) { 5622 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 5623 mAttachInfo.mKeepScreenOn = true; 5624 } 5625 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility; 5626 if (mOnSystemUiVisibilityChangeListener != null) { 5627 mAttachInfo.mHasSystemUiListeners = true; 5628 } 5629 } 5630 } 5631 5632 void needGlobalAttributesUpdate(boolean force) { 5633 final AttachInfo ai = mAttachInfo; 5634 if (ai != null) { 5635 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 5636 || ai.mHasSystemUiListeners) { 5637 ai.mRecomputeGlobalAttributes = true; 5638 } 5639 } 5640 } 5641 5642 /** 5643 * Returns whether the device is currently in touch mode. Touch mode is entered 5644 * once the user begins interacting with the device by touch, and affects various 5645 * things like whether focus is always visible to the user. 5646 * 5647 * @return Whether the device is in touch mode. 5648 */ 5649 @ViewDebug.ExportedProperty 5650 public boolean isInTouchMode() { 5651 if (mAttachInfo != null) { 5652 return mAttachInfo.mInTouchMode; 5653 } else { 5654 return ViewRootImpl.isInTouchMode(); 5655 } 5656 } 5657 5658 /** 5659 * Returns the context the view is running in, through which it can 5660 * access the current theme, resources, etc. 5661 * 5662 * @return The view's Context. 5663 */ 5664 @ViewDebug.CapturedViewProperty 5665 public final Context getContext() { 5666 return mContext; 5667 } 5668 5669 /** 5670 * Handle a key event before it is processed by any input method 5671 * associated with the view hierarchy. This can be used to intercept 5672 * key events in special situations before the IME consumes them; a 5673 * typical example would be handling the BACK key to update the application's 5674 * UI instead of allowing the IME to see it and close itself. 5675 * 5676 * @param keyCode The value in event.getKeyCode(). 5677 * @param event Description of the key event. 5678 * @return If you handled the event, return true. If you want to allow the 5679 * event to be handled by the next receiver, return false. 5680 */ 5681 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 5682 return false; 5683 } 5684 5685 /** 5686 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 5687 * KeyEvent.Callback.onKeyDown()}: perform press of the view 5688 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 5689 * is released, if the view is enabled and clickable. 5690 * 5691 * @param keyCode A key code that represents the button pressed, from 5692 * {@link android.view.KeyEvent}. 5693 * @param event The KeyEvent object that defines the button action. 5694 */ 5695 public boolean onKeyDown(int keyCode, KeyEvent event) { 5696 boolean result = false; 5697 5698 switch (keyCode) { 5699 case KeyEvent.KEYCODE_DPAD_CENTER: 5700 case KeyEvent.KEYCODE_ENTER: { 5701 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5702 return true; 5703 } 5704 // Long clickable items don't necessarily have to be clickable 5705 if (((mViewFlags & CLICKABLE) == CLICKABLE || 5706 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 5707 (event.getRepeatCount() == 0)) { 5708 setPressed(true); 5709 checkForLongClick(0); 5710 return true; 5711 } 5712 break; 5713 } 5714 } 5715 return result; 5716 } 5717 5718 /** 5719 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 5720 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 5721 * the event). 5722 */ 5723 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 5724 return false; 5725 } 5726 5727 /** 5728 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 5729 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 5730 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 5731 * {@link KeyEvent#KEYCODE_ENTER} is released. 5732 * 5733 * @param keyCode A key code that represents the button pressed, from 5734 * {@link android.view.KeyEvent}. 5735 * @param event The KeyEvent object that defines the button action. 5736 */ 5737 public boolean onKeyUp(int keyCode, KeyEvent event) { 5738 boolean result = false; 5739 5740 switch (keyCode) { 5741 case KeyEvent.KEYCODE_DPAD_CENTER: 5742 case KeyEvent.KEYCODE_ENTER: { 5743 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5744 return true; 5745 } 5746 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 5747 setPressed(false); 5748 5749 if (!mHasPerformedLongPress) { 5750 // This is a tap, so remove the longpress check 5751 removeLongPressCallback(); 5752 5753 result = performClick(); 5754 } 5755 } 5756 break; 5757 } 5758 } 5759 return result; 5760 } 5761 5762 /** 5763 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 5764 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 5765 * the event). 5766 * 5767 * @param keyCode A key code that represents the button pressed, from 5768 * {@link android.view.KeyEvent}. 5769 * @param repeatCount The number of times the action was made. 5770 * @param event The KeyEvent object that defines the button action. 5771 */ 5772 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 5773 return false; 5774 } 5775 5776 /** 5777 * Called on the focused view when a key shortcut event is not handled. 5778 * Override this method to implement local key shortcuts for the View. 5779 * Key shortcuts can also be implemented by setting the 5780 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 5781 * 5782 * @param keyCode The value in event.getKeyCode(). 5783 * @param event Description of the key event. 5784 * @return If you handled the event, return true. If you want to allow the 5785 * event to be handled by the next receiver, return false. 5786 */ 5787 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 5788 return false; 5789 } 5790 5791 /** 5792 * Check whether the called view is a text editor, in which case it 5793 * would make sense to automatically display a soft input window for 5794 * it. Subclasses should override this if they implement 5795 * {@link #onCreateInputConnection(EditorInfo)} to return true if 5796 * a call on that method would return a non-null InputConnection, and 5797 * they are really a first-class editor that the user would normally 5798 * start typing on when the go into a window containing your view. 5799 * 5800 * <p>The default implementation always returns false. This does 5801 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 5802 * will not be called or the user can not otherwise perform edits on your 5803 * view; it is just a hint to the system that this is not the primary 5804 * purpose of this view. 5805 * 5806 * @return Returns true if this view is a text editor, else false. 5807 */ 5808 public boolean onCheckIsTextEditor() { 5809 return false; 5810 } 5811 5812 /** 5813 * Create a new InputConnection for an InputMethod to interact 5814 * with the view. The default implementation returns null, since it doesn't 5815 * support input methods. You can override this to implement such support. 5816 * This is only needed for views that take focus and text input. 5817 * 5818 * <p>When implementing this, you probably also want to implement 5819 * {@link #onCheckIsTextEditor()} to indicate you will return a 5820 * non-null InputConnection. 5821 * 5822 * @param outAttrs Fill in with attribute information about the connection. 5823 */ 5824 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 5825 return null; 5826 } 5827 5828 /** 5829 * Called by the {@link android.view.inputmethod.InputMethodManager} 5830 * when a view who is not the current 5831 * input connection target is trying to make a call on the manager. The 5832 * default implementation returns false; you can override this to return 5833 * true for certain views if you are performing InputConnection proxying 5834 * to them. 5835 * @param view The View that is making the InputMethodManager call. 5836 * @return Return true to allow the call, false to reject. 5837 */ 5838 public boolean checkInputConnectionProxy(View view) { 5839 return false; 5840 } 5841 5842 /** 5843 * Show the context menu for this view. It is not safe to hold on to the 5844 * menu after returning from this method. 5845 * 5846 * You should normally not overload this method. Overload 5847 * {@link #onCreateContextMenu(ContextMenu)} or define an 5848 * {@link OnCreateContextMenuListener} to add items to the context menu. 5849 * 5850 * @param menu The context menu to populate 5851 */ 5852 public void createContextMenu(ContextMenu menu) { 5853 ContextMenuInfo menuInfo = getContextMenuInfo(); 5854 5855 // Sets the current menu info so all items added to menu will have 5856 // my extra info set. 5857 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 5858 5859 onCreateContextMenu(menu); 5860 if (mOnCreateContextMenuListener != null) { 5861 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 5862 } 5863 5864 // Clear the extra information so subsequent items that aren't mine don't 5865 // have my extra info. 5866 ((MenuBuilder)menu).setCurrentMenuInfo(null); 5867 5868 if (mParent != null) { 5869 mParent.createContextMenu(menu); 5870 } 5871 } 5872 5873 /** 5874 * Views should implement this if they have extra information to associate 5875 * with the context menu. The return result is supplied as a parameter to 5876 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 5877 * callback. 5878 * 5879 * @return Extra information about the item for which the context menu 5880 * should be shown. This information will vary across different 5881 * subclasses of View. 5882 */ 5883 protected ContextMenuInfo getContextMenuInfo() { 5884 return null; 5885 } 5886 5887 /** 5888 * Views should implement this if the view itself is going to add items to 5889 * the context menu. 5890 * 5891 * @param menu the context menu to populate 5892 */ 5893 protected void onCreateContextMenu(ContextMenu menu) { 5894 } 5895 5896 /** 5897 * Implement this method to handle trackball motion events. The 5898 * <em>relative</em> movement of the trackball since the last event 5899 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 5900 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 5901 * that a movement of 1 corresponds to the user pressing one DPAD key (so 5902 * they will often be fractional values, representing the more fine-grained 5903 * movement information available from a trackball). 5904 * 5905 * @param event The motion event. 5906 * @return True if the event was handled, false otherwise. 5907 */ 5908 public boolean onTrackballEvent(MotionEvent event) { 5909 return false; 5910 } 5911 5912 /** 5913 * Implement this method to handle generic motion events. 5914 * <p> 5915 * Generic motion events describe joystick movements, mouse hovers, track pad 5916 * touches, scroll wheel movements and other input events. The 5917 * {@link MotionEvent#getSource() source} of the motion event specifies 5918 * the class of input that was received. Implementations of this method 5919 * must examine the bits in the source before processing the event. 5920 * The following code example shows how this is done. 5921 * </p><p> 5922 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5923 * are delivered to the view under the pointer. All other generic motion events are 5924 * delivered to the focused view. 5925 * </p> 5926 * <code> 5927 * public boolean onGenericMotionEvent(MotionEvent event) { 5928 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 5929 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 5930 * // process the joystick movement... 5931 * return true; 5932 * } 5933 * } 5934 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5935 * switch (event.getAction()) { 5936 * case MotionEvent.ACTION_HOVER_MOVE: 5937 * // process the mouse hover movement... 5938 * return true; 5939 * case MotionEvent.ACTION_SCROLL: 5940 * // process the scroll wheel movement... 5941 * return true; 5942 * } 5943 * } 5944 * return super.onGenericMotionEvent(event); 5945 * } 5946 * </code> 5947 * 5948 * @param event The generic motion event being processed. 5949 * @return True if the event was handled, false otherwise. 5950 */ 5951 public boolean onGenericMotionEvent(MotionEvent event) { 5952 return false; 5953 } 5954 5955 /** 5956 * Implement this method to handle hover events. 5957 * <p> 5958 * This method is called whenever a pointer is hovering into, over, or out of the 5959 * bounds of a view and the view is not currently being touched. 5960 * Hover events are represented as pointer events with action 5961 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 5962 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 5963 * </p> 5964 * <ul> 5965 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 5966 * when the pointer enters the bounds of the view.</li> 5967 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 5968 * when the pointer has already entered the bounds of the view and has moved.</li> 5969 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 5970 * when the pointer has exited the bounds of the view or when the pointer is 5971 * about to go down due to a button click, tap, or similar user action that 5972 * causes the view to be touched.</li> 5973 * </ul> 5974 * <p> 5975 * The view should implement this method to return true to indicate that it is 5976 * handling the hover event, such as by changing its drawable state. 5977 * </p><p> 5978 * The default implementation calls {@link #setHovered} to update the hovered state 5979 * of the view when a hover enter or hover exit event is received, if the view 5980 * is enabled and is clickable. 5981 * </p> 5982 * 5983 * @param event The motion event that describes the hover. 5984 * @return True if the view handled the hover event. 5985 * 5986 * @see #isHovered 5987 * @see #setHovered 5988 * @see #onHoverChanged 5989 */ 5990 public boolean onHoverEvent(MotionEvent event) { 5991 if (isHoverable()) { 5992 switch (event.getAction()) { 5993 case MotionEvent.ACTION_HOVER_ENTER: 5994 setHovered(true); 5995 break; 5996 case MotionEvent.ACTION_HOVER_EXIT: 5997 setHovered(false); 5998 break; 5999 } 6000 return true; 6001 } 6002 return false; 6003 } 6004 6005 /** 6006 * Returns true if the view should handle {@link #onHoverEvent} 6007 * by calling {@link #setHovered} to change its hovered state. 6008 * 6009 * @return True if the view is hoverable. 6010 */ 6011 private boolean isHoverable() { 6012 final int viewFlags = mViewFlags; 6013 //noinspection SimplifiableIfStatement 6014 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6015 return false; 6016 } 6017 6018 return (viewFlags & CLICKABLE) == CLICKABLE 6019 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6020 } 6021 6022 /** 6023 * Returns true if the view is currently hovered. 6024 * 6025 * @return True if the view is currently hovered. 6026 * 6027 * @see #setHovered 6028 * @see #onHoverChanged 6029 */ 6030 @ViewDebug.ExportedProperty 6031 public boolean isHovered() { 6032 return (mPrivateFlags & HOVERED) != 0; 6033 } 6034 6035 /** 6036 * Sets whether the view is currently hovered. 6037 * <p> 6038 * Calling this method also changes the drawable state of the view. This 6039 * enables the view to react to hover by using different drawable resources 6040 * to change its appearance. 6041 * </p><p> 6042 * The {@link #onHoverChanged} method is called when the hovered state changes. 6043 * </p> 6044 * 6045 * @param hovered True if the view is hovered. 6046 * 6047 * @see #isHovered 6048 * @see #onHoverChanged 6049 */ 6050 public void setHovered(boolean hovered) { 6051 if (hovered) { 6052 if ((mPrivateFlags & HOVERED) == 0) { 6053 mPrivateFlags |= HOVERED; 6054 refreshDrawableState(); 6055 onHoverChanged(true); 6056 } 6057 } else { 6058 if ((mPrivateFlags & HOVERED) != 0) { 6059 mPrivateFlags &= ~HOVERED; 6060 refreshDrawableState(); 6061 onHoverChanged(false); 6062 } 6063 } 6064 } 6065 6066 /** 6067 * Implement this method to handle hover state changes. 6068 * <p> 6069 * This method is called whenever the hover state changes as a result of a 6070 * call to {@link #setHovered}. 6071 * </p> 6072 * 6073 * @param hovered The current hover state, as returned by {@link #isHovered}. 6074 * 6075 * @see #isHovered 6076 * @see #setHovered 6077 */ 6078 public void onHoverChanged(boolean hovered) { 6079 } 6080 6081 /** 6082 * Implement this method to handle touch screen motion events. 6083 * 6084 * @param event The motion event. 6085 * @return True if the event was handled, false otherwise. 6086 */ 6087 public boolean onTouchEvent(MotionEvent event) { 6088 final int viewFlags = mViewFlags; 6089 6090 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6091 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) { 6092 mPrivateFlags &= ~PRESSED; 6093 refreshDrawableState(); 6094 } 6095 // A disabled view that is clickable still consumes the touch 6096 // events, it just doesn't respond to them. 6097 return (((viewFlags & CLICKABLE) == CLICKABLE || 6098 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 6099 } 6100 6101 if (mTouchDelegate != null) { 6102 if (mTouchDelegate.onTouchEvent(event)) { 6103 return true; 6104 } 6105 } 6106 6107 if (((viewFlags & CLICKABLE) == CLICKABLE || 6108 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 6109 switch (event.getAction()) { 6110 case MotionEvent.ACTION_UP: 6111 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; 6112 if ((mPrivateFlags & PRESSED) != 0 || prepressed) { 6113 // take focus if we don't have it already and we should in 6114 // touch mode. 6115 boolean focusTaken = false; 6116 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 6117 focusTaken = requestFocus(); 6118 } 6119 6120 if (prepressed) { 6121 // The button is being released before we actually 6122 // showed it as pressed. Make it show the pressed 6123 // state now (before scheduling the click) to ensure 6124 // the user sees it. 6125 mPrivateFlags |= PRESSED; 6126 refreshDrawableState(); 6127 } 6128 6129 if (!mHasPerformedLongPress) { 6130 // This is a tap, so remove the longpress check 6131 removeLongPressCallback(); 6132 6133 // Only perform take click actions if we were in the pressed state 6134 if (!focusTaken) { 6135 // Use a Runnable and post this rather than calling 6136 // performClick directly. This lets other visual state 6137 // of the view update before click actions start. 6138 if (mPerformClick == null) { 6139 mPerformClick = new PerformClick(); 6140 } 6141 if (!post(mPerformClick)) { 6142 performClick(); 6143 } 6144 } 6145 } 6146 6147 if (mUnsetPressedState == null) { 6148 mUnsetPressedState = new UnsetPressedState(); 6149 } 6150 6151 if (prepressed) { 6152 postDelayed(mUnsetPressedState, 6153 ViewConfiguration.getPressedStateDuration()); 6154 } else if (!post(mUnsetPressedState)) { 6155 // If the post failed, unpress right now 6156 mUnsetPressedState.run(); 6157 } 6158 removeTapCallback(); 6159 } 6160 break; 6161 6162 case MotionEvent.ACTION_DOWN: 6163 mHasPerformedLongPress = false; 6164 6165 if (performButtonActionOnTouchDown(event)) { 6166 break; 6167 } 6168 6169 // Walk up the hierarchy to determine if we're inside a scrolling container. 6170 boolean isInScrollingContainer = false; 6171 ViewParent p = getParent(); 6172 while (p != null && p instanceof ViewGroup) { 6173 if (((ViewGroup) p).shouldDelayChildPressedState()) { 6174 isInScrollingContainer = true; 6175 break; 6176 } 6177 p = p.getParent(); 6178 } 6179 6180 // For views inside a scrolling container, delay the pressed feedback for 6181 // a short period in case this is a scroll. 6182 if (isInScrollingContainer) { 6183 mPrivateFlags |= PREPRESSED; 6184 if (mPendingCheckForTap == null) { 6185 mPendingCheckForTap = new CheckForTap(); 6186 } 6187 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 6188 } else { 6189 // Not inside a scrolling container, so show the feedback right away 6190 mPrivateFlags |= PRESSED; 6191 refreshDrawableState(); 6192 checkForLongClick(0); 6193 } 6194 break; 6195 6196 case MotionEvent.ACTION_CANCEL: 6197 mPrivateFlags &= ~PRESSED; 6198 refreshDrawableState(); 6199 removeTapCallback(); 6200 break; 6201 6202 case MotionEvent.ACTION_MOVE: 6203 final int x = (int) event.getX(); 6204 final int y = (int) event.getY(); 6205 6206 // Be lenient about moving outside of buttons 6207 if (!pointInView(x, y, mTouchSlop)) { 6208 // Outside button 6209 removeTapCallback(); 6210 if ((mPrivateFlags & PRESSED) != 0) { 6211 // Remove any future long press/tap checks 6212 removeLongPressCallback(); 6213 6214 // Need to switch from pressed to not pressed 6215 mPrivateFlags &= ~PRESSED; 6216 refreshDrawableState(); 6217 } 6218 } 6219 break; 6220 } 6221 return true; 6222 } 6223 6224 return false; 6225 } 6226 6227 /** 6228 * Remove the longpress detection timer. 6229 */ 6230 private void removeLongPressCallback() { 6231 if (mPendingCheckForLongPress != null) { 6232 removeCallbacks(mPendingCheckForLongPress); 6233 } 6234 } 6235 6236 /** 6237 * Remove the pending click action 6238 */ 6239 private void removePerformClickCallback() { 6240 if (mPerformClick != null) { 6241 removeCallbacks(mPerformClick); 6242 } 6243 } 6244 6245 /** 6246 * Remove the prepress detection timer. 6247 */ 6248 private void removeUnsetPressCallback() { 6249 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) { 6250 setPressed(false); 6251 removeCallbacks(mUnsetPressedState); 6252 } 6253 } 6254 6255 /** 6256 * Remove the tap detection timer. 6257 */ 6258 private void removeTapCallback() { 6259 if (mPendingCheckForTap != null) { 6260 mPrivateFlags &= ~PREPRESSED; 6261 removeCallbacks(mPendingCheckForTap); 6262 } 6263 } 6264 6265 /** 6266 * Cancels a pending long press. Your subclass can use this if you 6267 * want the context menu to come up if the user presses and holds 6268 * at the same place, but you don't want it to come up if they press 6269 * and then move around enough to cause scrolling. 6270 */ 6271 public void cancelLongPress() { 6272 removeLongPressCallback(); 6273 6274 /* 6275 * The prepressed state handled by the tap callback is a display 6276 * construct, but the tap callback will post a long press callback 6277 * less its own timeout. Remove it here. 6278 */ 6279 removeTapCallback(); 6280 } 6281 6282 /** 6283 * Remove the pending callback for sending a 6284 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 6285 */ 6286 private void removeSendViewScrolledAccessibilityEventCallback() { 6287 if (mSendViewScrolledAccessibilityEvent != null) { 6288 removeCallbacks(mSendViewScrolledAccessibilityEvent); 6289 } 6290 } 6291 6292 /** 6293 * Sets the TouchDelegate for this View. 6294 */ 6295 public void setTouchDelegate(TouchDelegate delegate) { 6296 mTouchDelegate = delegate; 6297 } 6298 6299 /** 6300 * Gets the TouchDelegate for this View. 6301 */ 6302 public TouchDelegate getTouchDelegate() { 6303 return mTouchDelegate; 6304 } 6305 6306 /** 6307 * Set flags controlling behavior of this view. 6308 * 6309 * @param flags Constant indicating the value which should be set 6310 * @param mask Constant indicating the bit range that should be changed 6311 */ 6312 void setFlags(int flags, int mask) { 6313 int old = mViewFlags; 6314 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 6315 6316 int changed = mViewFlags ^ old; 6317 if (changed == 0) { 6318 return; 6319 } 6320 int privateFlags = mPrivateFlags; 6321 6322 /* Check if the FOCUSABLE bit has changed */ 6323 if (((changed & FOCUSABLE_MASK) != 0) && 6324 ((privateFlags & HAS_BOUNDS) !=0)) { 6325 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 6326 && ((privateFlags & FOCUSED) != 0)) { 6327 /* Give up focus if we are no longer focusable */ 6328 clearFocus(); 6329 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 6330 && ((privateFlags & FOCUSED) == 0)) { 6331 /* 6332 * Tell the view system that we are now available to take focus 6333 * if no one else already has it. 6334 */ 6335 if (mParent != null) mParent.focusableViewAvailable(this); 6336 } 6337 } 6338 6339 if ((flags & VISIBILITY_MASK) == VISIBLE) { 6340 if ((changed & VISIBILITY_MASK) != 0) { 6341 /* 6342 * If this view is becoming visible, set the DRAWN flag so that 6343 * the next invalidate() will not be skipped. 6344 */ 6345 mPrivateFlags |= DRAWN; 6346 6347 needGlobalAttributesUpdate(true); 6348 6349 // a view becoming visible is worth notifying the parent 6350 // about in case nothing has focus. even if this specific view 6351 // isn't focusable, it may contain something that is, so let 6352 // the root view try to give this focus if nothing else does. 6353 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 6354 mParent.focusableViewAvailable(this); 6355 } 6356 } 6357 } 6358 6359 /* Check if the GONE bit has changed */ 6360 if ((changed & GONE) != 0) { 6361 needGlobalAttributesUpdate(false); 6362 requestLayout(); 6363 invalidate(true); 6364 6365 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 6366 if (hasFocus()) clearFocus(); 6367 destroyDrawingCache(); 6368 } 6369 if (mAttachInfo != null) { 6370 mAttachInfo.mViewVisibilityChanged = true; 6371 } 6372 } 6373 6374 /* Check if the VISIBLE bit has changed */ 6375 if ((changed & INVISIBLE) != 0) { 6376 needGlobalAttributesUpdate(false); 6377 /* 6378 * If this view is becoming invisible, set the DRAWN flag so that 6379 * the next invalidate() will not be skipped. 6380 */ 6381 mPrivateFlags |= DRAWN; 6382 6383 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 6384 // root view becoming invisible shouldn't clear focus 6385 if (getRootView() != this) { 6386 clearFocus(); 6387 } 6388 } 6389 if (mAttachInfo != null) { 6390 mAttachInfo.mViewVisibilityChanged = true; 6391 } 6392 } 6393 6394 if ((changed & VISIBILITY_MASK) != 0) { 6395 if (mParent instanceof ViewGroup) { 6396 ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6397 ((View) mParent).invalidate(true); 6398 } 6399 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6400 } 6401 6402 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 6403 destroyDrawingCache(); 6404 } 6405 6406 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 6407 destroyDrawingCache(); 6408 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6409 invalidateParentCaches(); 6410 } 6411 6412 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 6413 destroyDrawingCache(); 6414 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6415 } 6416 6417 if ((changed & DRAW_MASK) != 0) { 6418 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 6419 if (mBGDrawable != null) { 6420 mPrivateFlags &= ~SKIP_DRAW; 6421 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 6422 } else { 6423 mPrivateFlags |= SKIP_DRAW; 6424 } 6425 } else { 6426 mPrivateFlags &= ~SKIP_DRAW; 6427 } 6428 requestLayout(); 6429 invalidate(true); 6430 } 6431 6432 if ((changed & KEEP_SCREEN_ON) != 0) { 6433 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 6434 mParent.recomputeViewAttributes(this); 6435 } 6436 } 6437 6438 if ((changed & LAYOUT_DIRECTION_MASK) != 0) { 6439 requestLayout(); 6440 } 6441 } 6442 6443 /** 6444 * Change the view's z order in the tree, so it's on top of other sibling 6445 * views 6446 */ 6447 public void bringToFront() { 6448 if (mParent != null) { 6449 mParent.bringChildToFront(this); 6450 } 6451 } 6452 6453 /** 6454 * This is called in response to an internal scroll in this view (i.e., the 6455 * view scrolled its own contents). This is typically as a result of 6456 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 6457 * called. 6458 * 6459 * @param l Current horizontal scroll origin. 6460 * @param t Current vertical scroll origin. 6461 * @param oldl Previous horizontal scroll origin. 6462 * @param oldt Previous vertical scroll origin. 6463 */ 6464 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 6465 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6466 postSendViewScrolledAccessibilityEventCallback(); 6467 } 6468 6469 mBackgroundSizeChanged = true; 6470 6471 final AttachInfo ai = mAttachInfo; 6472 if (ai != null) { 6473 ai.mViewScrollChanged = true; 6474 } 6475 } 6476 6477 /** 6478 * Interface definition for a callback to be invoked when the layout bounds of a view 6479 * changes due to layout processing. 6480 */ 6481 public interface OnLayoutChangeListener { 6482 /** 6483 * Called when the focus state of a view has changed. 6484 * 6485 * @param v The view whose state has changed. 6486 * @param left The new value of the view's left property. 6487 * @param top The new value of the view's top property. 6488 * @param right The new value of the view's right property. 6489 * @param bottom The new value of the view's bottom property. 6490 * @param oldLeft The previous value of the view's left property. 6491 * @param oldTop The previous value of the view's top property. 6492 * @param oldRight The previous value of the view's right property. 6493 * @param oldBottom The previous value of the view's bottom property. 6494 */ 6495 void onLayoutChange(View v, int left, int top, int right, int bottom, 6496 int oldLeft, int oldTop, int oldRight, int oldBottom); 6497 } 6498 6499 /** 6500 * This is called during layout when the size of this view has changed. If 6501 * you were just added to the view hierarchy, you're called with the old 6502 * values of 0. 6503 * 6504 * @param w Current width of this view. 6505 * @param h Current height of this view. 6506 * @param oldw Old width of this view. 6507 * @param oldh Old height of this view. 6508 */ 6509 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 6510 } 6511 6512 /** 6513 * Called by draw to draw the child views. This may be overridden 6514 * by derived classes to gain control just before its children are drawn 6515 * (but after its own view has been drawn). 6516 * @param canvas the canvas on which to draw the view 6517 */ 6518 protected void dispatchDraw(Canvas canvas) { 6519 } 6520 6521 /** 6522 * Gets the parent of this view. Note that the parent is a 6523 * ViewParent and not necessarily a View. 6524 * 6525 * @return Parent of this view. 6526 */ 6527 public final ViewParent getParent() { 6528 return mParent; 6529 } 6530 6531 /** 6532 * Set the horizontal scrolled position of your view. This will cause a call to 6533 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6534 * invalidated. 6535 * @param value the x position to scroll to 6536 */ 6537 public void setScrollX(int value) { 6538 scrollTo(value, mScrollY); 6539 } 6540 6541 /** 6542 * Set the vertical scrolled position of your view. This will cause a call to 6543 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6544 * invalidated. 6545 * @param value the y position to scroll to 6546 */ 6547 public void setScrollY(int value) { 6548 scrollTo(mScrollX, value); 6549 } 6550 6551 /** 6552 * Return the scrolled left position of this view. This is the left edge of 6553 * the displayed part of your view. You do not need to draw any pixels 6554 * farther left, since those are outside of the frame of your view on 6555 * screen. 6556 * 6557 * @return The left edge of the displayed part of your view, in pixels. 6558 */ 6559 public final int getScrollX() { 6560 return mScrollX; 6561 } 6562 6563 /** 6564 * Return the scrolled top position of this view. This is the top edge of 6565 * the displayed part of your view. You do not need to draw any pixels above 6566 * it, since those are outside of the frame of your view on screen. 6567 * 6568 * @return The top edge of the displayed part of your view, in pixels. 6569 */ 6570 public final int getScrollY() { 6571 return mScrollY; 6572 } 6573 6574 /** 6575 * Return the width of the your view. 6576 * 6577 * @return The width of your view, in pixels. 6578 */ 6579 @ViewDebug.ExportedProperty(category = "layout") 6580 public final int getWidth() { 6581 return mRight - mLeft; 6582 } 6583 6584 /** 6585 * Return the height of your view. 6586 * 6587 * @return The height of your view, in pixels. 6588 */ 6589 @ViewDebug.ExportedProperty(category = "layout") 6590 public final int getHeight() { 6591 return mBottom - mTop; 6592 } 6593 6594 /** 6595 * Return the visible drawing bounds of your view. Fills in the output 6596 * rectangle with the values from getScrollX(), getScrollY(), 6597 * getWidth(), and getHeight(). 6598 * 6599 * @param outRect The (scrolled) drawing bounds of the view. 6600 */ 6601 public void getDrawingRect(Rect outRect) { 6602 outRect.left = mScrollX; 6603 outRect.top = mScrollY; 6604 outRect.right = mScrollX + (mRight - mLeft); 6605 outRect.bottom = mScrollY + (mBottom - mTop); 6606 } 6607 6608 /** 6609 * Like {@link #getMeasuredWidthAndState()}, but only returns the 6610 * raw width component (that is the result is masked by 6611 * {@link #MEASURED_SIZE_MASK}). 6612 * 6613 * @return The raw measured width of this view. 6614 */ 6615 public final int getMeasuredWidth() { 6616 return mMeasuredWidth & MEASURED_SIZE_MASK; 6617 } 6618 6619 /** 6620 * Return the full width measurement information for this view as computed 6621 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6622 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6623 * This should be used during measurement and layout calculations only. Use 6624 * {@link #getWidth()} to see how wide a view is after layout. 6625 * 6626 * @return The measured width of this view as a bit mask. 6627 */ 6628 public final int getMeasuredWidthAndState() { 6629 return mMeasuredWidth; 6630 } 6631 6632 /** 6633 * Like {@link #getMeasuredHeightAndState()}, but only returns the 6634 * raw width component (that is the result is masked by 6635 * {@link #MEASURED_SIZE_MASK}). 6636 * 6637 * @return The raw measured height of this view. 6638 */ 6639 public final int getMeasuredHeight() { 6640 return mMeasuredHeight & MEASURED_SIZE_MASK; 6641 } 6642 6643 /** 6644 * Return the full height measurement information for this view as computed 6645 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6646 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6647 * This should be used during measurement and layout calculations only. Use 6648 * {@link #getHeight()} to see how wide a view is after layout. 6649 * 6650 * @return The measured width of this view as a bit mask. 6651 */ 6652 public final int getMeasuredHeightAndState() { 6653 return mMeasuredHeight; 6654 } 6655 6656 /** 6657 * Return only the state bits of {@link #getMeasuredWidthAndState()} 6658 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 6659 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 6660 * and the height component is at the shifted bits 6661 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 6662 */ 6663 public final int getMeasuredState() { 6664 return (mMeasuredWidth&MEASURED_STATE_MASK) 6665 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 6666 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 6667 } 6668 6669 /** 6670 * The transform matrix of this view, which is calculated based on the current 6671 * roation, scale, and pivot properties. 6672 * 6673 * @see #getRotation() 6674 * @see #getScaleX() 6675 * @see #getScaleY() 6676 * @see #getPivotX() 6677 * @see #getPivotY() 6678 * @return The current transform matrix for the view 6679 */ 6680 public Matrix getMatrix() { 6681 updateMatrix(); 6682 return mMatrix; 6683 } 6684 6685 /** 6686 * Utility function to determine if the value is far enough away from zero to be 6687 * considered non-zero. 6688 * @param value A floating point value to check for zero-ness 6689 * @return whether the passed-in value is far enough away from zero to be considered non-zero 6690 */ 6691 private static boolean nonzero(float value) { 6692 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 6693 } 6694 6695 /** 6696 * Returns true if the transform matrix is the identity matrix. 6697 * Recomputes the matrix if necessary. 6698 * 6699 * @return True if the transform matrix is the identity matrix, false otherwise. 6700 */ 6701 final boolean hasIdentityMatrix() { 6702 updateMatrix(); 6703 return mMatrixIsIdentity; 6704 } 6705 6706 /** 6707 * Recomputes the transform matrix if necessary. 6708 */ 6709 private void updateMatrix() { 6710 if (mMatrixDirty) { 6711 // transform-related properties have changed since the last time someone 6712 // asked for the matrix; recalculate it with the current values 6713 6714 // Figure out if we need to update the pivot point 6715 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6716 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) { 6717 mPrevWidth = mRight - mLeft; 6718 mPrevHeight = mBottom - mTop; 6719 mPivotX = mPrevWidth / 2f; 6720 mPivotY = mPrevHeight / 2f; 6721 } 6722 } 6723 mMatrix.reset(); 6724 if (!nonzero(mRotationX) && !nonzero(mRotationY)) { 6725 mMatrix.setTranslate(mTranslationX, mTranslationY); 6726 mMatrix.preRotate(mRotation, mPivotX, mPivotY); 6727 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY); 6728 } else { 6729 if (mCamera == null) { 6730 mCamera = new Camera(); 6731 matrix3D = new Matrix(); 6732 } 6733 mCamera.save(); 6734 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY); 6735 mCamera.rotate(mRotationX, mRotationY, -mRotation); 6736 mCamera.getMatrix(matrix3D); 6737 matrix3D.preTranslate(-mPivotX, -mPivotY); 6738 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY); 6739 mMatrix.postConcat(matrix3D); 6740 mCamera.restore(); 6741 } 6742 mMatrixDirty = false; 6743 mMatrixIsIdentity = mMatrix.isIdentity(); 6744 mInverseMatrixDirty = true; 6745 } 6746 } 6747 6748 /** 6749 * Utility method to retrieve the inverse of the current mMatrix property. 6750 * We cache the matrix to avoid recalculating it when transform properties 6751 * have not changed. 6752 * 6753 * @return The inverse of the current matrix of this view. 6754 */ 6755 final Matrix getInverseMatrix() { 6756 updateMatrix(); 6757 if (mInverseMatrixDirty) { 6758 if (mInverseMatrix == null) { 6759 mInverseMatrix = new Matrix(); 6760 } 6761 mMatrix.invert(mInverseMatrix); 6762 mInverseMatrixDirty = false; 6763 } 6764 return mInverseMatrix; 6765 } 6766 6767 /** 6768 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 6769 * views are drawn) from the camera to this view. The camera's distance 6770 * affects 3D transformations, for instance rotations around the X and Y 6771 * axis. If the rotationX or rotationY properties are changed and this view is 6772 * large (more than half the size of the screen), it is recommended to always 6773 * use a camera distance that's greater than the height (X axis rotation) or 6774 * the width (Y axis rotation) of this view.</p> 6775 * 6776 * <p>The distance of the camera from the view plane can have an affect on the 6777 * perspective distortion of the view when it is rotated around the x or y axis. 6778 * For example, a large distance will result in a large viewing angle, and there 6779 * will not be much perspective distortion of the view as it rotates. A short 6780 * distance may cause much more perspective distortion upon rotation, and can 6781 * also result in some drawing artifacts if the rotated view ends up partially 6782 * behind the camera (which is why the recommendation is to use a distance at 6783 * least as far as the size of the view, if the view is to be rotated.)</p> 6784 * 6785 * <p>The distance is expressed in "depth pixels." The default distance depends 6786 * on the screen density. For instance, on a medium density display, the 6787 * default distance is 1280. On a high density display, the default distance 6788 * is 1920.</p> 6789 * 6790 * <p>If you want to specify a distance that leads to visually consistent 6791 * results across various densities, use the following formula:</p> 6792 * <pre> 6793 * float scale = context.getResources().getDisplayMetrics().density; 6794 * view.setCameraDistance(distance * scale); 6795 * </pre> 6796 * 6797 * <p>The density scale factor of a high density display is 1.5, 6798 * and 1920 = 1280 * 1.5.</p> 6799 * 6800 * @param distance The distance in "depth pixels", if negative the opposite 6801 * value is used 6802 * 6803 * @see #setRotationX(float) 6804 * @see #setRotationY(float) 6805 */ 6806 public void setCameraDistance(float distance) { 6807 invalidateParentCaches(); 6808 invalidate(false); 6809 6810 final float dpi = mResources.getDisplayMetrics().densityDpi; 6811 if (mCamera == null) { 6812 mCamera = new Camera(); 6813 matrix3D = new Matrix(); 6814 } 6815 6816 mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 6817 mMatrixDirty = true; 6818 6819 invalidate(false); 6820 } 6821 6822 /** 6823 * The degrees that the view is rotated around the pivot point. 6824 * 6825 * @see #setRotation(float) 6826 * @see #getPivotX() 6827 * @see #getPivotY() 6828 * 6829 * @return The degrees of rotation. 6830 */ 6831 public float getRotation() { 6832 return mRotation; 6833 } 6834 6835 /** 6836 * Sets the degrees that the view is rotated around the pivot point. Increasing values 6837 * result in clockwise rotation. 6838 * 6839 * @param rotation The degrees of rotation. 6840 * 6841 * @see #getRotation() 6842 * @see #getPivotX() 6843 * @see #getPivotY() 6844 * @see #setRotationX(float) 6845 * @see #setRotationY(float) 6846 * 6847 * @attr ref android.R.styleable#View_rotation 6848 */ 6849 public void setRotation(float rotation) { 6850 if (mRotation != rotation) { 6851 invalidateParentCaches(); 6852 // Double-invalidation is necessary to capture view's old and new areas 6853 invalidate(false); 6854 mRotation = rotation; 6855 mMatrixDirty = true; 6856 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6857 invalidate(false); 6858 } 6859 } 6860 6861 /** 6862 * The degrees that the view is rotated around the vertical axis through the pivot point. 6863 * 6864 * @see #getPivotX() 6865 * @see #getPivotY() 6866 * @see #setRotationY(float) 6867 * 6868 * @return The degrees of Y rotation. 6869 */ 6870 public float getRotationY() { 6871 return mRotationY; 6872 } 6873 6874 /** 6875 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 6876 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 6877 * down the y axis. 6878 * 6879 * When rotating large views, it is recommended to adjust the camera distance 6880 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 6881 * 6882 * @param rotationY The degrees of Y rotation. 6883 * 6884 * @see #getRotationY() 6885 * @see #getPivotX() 6886 * @see #getPivotY() 6887 * @see #setRotation(float) 6888 * @see #setRotationX(float) 6889 * @see #setCameraDistance(float) 6890 * 6891 * @attr ref android.R.styleable#View_rotationY 6892 */ 6893 public void setRotationY(float rotationY) { 6894 if (mRotationY != rotationY) { 6895 invalidateParentCaches(); 6896 // Double-invalidation is necessary to capture view's old and new areas 6897 invalidate(false); 6898 mRotationY = rotationY; 6899 mMatrixDirty = true; 6900 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6901 invalidate(false); 6902 } 6903 } 6904 6905 /** 6906 * The degrees that the view is rotated around the horizontal axis through the pivot point. 6907 * 6908 * @see #getPivotX() 6909 * @see #getPivotY() 6910 * @see #setRotationX(float) 6911 * 6912 * @return The degrees of X rotation. 6913 */ 6914 public float getRotationX() { 6915 return mRotationX; 6916 } 6917 6918 /** 6919 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 6920 * Increasing values result in clockwise rotation from the viewpoint of looking down the 6921 * x axis. 6922 * 6923 * When rotating large views, it is recommended to adjust the camera distance 6924 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 6925 * 6926 * @param rotationX The degrees of X rotation. 6927 * 6928 * @see #getRotationX() 6929 * @see #getPivotX() 6930 * @see #getPivotY() 6931 * @see #setRotation(float) 6932 * @see #setRotationY(float) 6933 * @see #setCameraDistance(float) 6934 * 6935 * @attr ref android.R.styleable#View_rotationX 6936 */ 6937 public void setRotationX(float rotationX) { 6938 if (mRotationX != rotationX) { 6939 invalidateParentCaches(); 6940 // Double-invalidation is necessary to capture view's old and new areas 6941 invalidate(false); 6942 mRotationX = rotationX; 6943 mMatrixDirty = true; 6944 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6945 invalidate(false); 6946 } 6947 } 6948 6949 /** 6950 * The amount that the view is scaled in x around the pivot point, as a proportion of 6951 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 6952 * 6953 * <p>By default, this is 1.0f. 6954 * 6955 * @see #getPivotX() 6956 * @see #getPivotY() 6957 * @return The scaling factor. 6958 */ 6959 public float getScaleX() { 6960 return mScaleX; 6961 } 6962 6963 /** 6964 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 6965 * the view's unscaled width. A value of 1 means that no scaling is applied. 6966 * 6967 * @param scaleX The scaling factor. 6968 * @see #getPivotX() 6969 * @see #getPivotY() 6970 * 6971 * @attr ref android.R.styleable#View_scaleX 6972 */ 6973 public void setScaleX(float scaleX) { 6974 if (mScaleX != scaleX) { 6975 invalidateParentCaches(); 6976 // Double-invalidation is necessary to capture view's old and new areas 6977 invalidate(false); 6978 mScaleX = scaleX; 6979 mMatrixDirty = true; 6980 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6981 invalidate(false); 6982 } 6983 } 6984 6985 /** 6986 * The amount that the view is scaled in y around the pivot point, as a proportion of 6987 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 6988 * 6989 * <p>By default, this is 1.0f. 6990 * 6991 * @see #getPivotX() 6992 * @see #getPivotY() 6993 * @return The scaling factor. 6994 */ 6995 public float getScaleY() { 6996 return mScaleY; 6997 } 6998 6999 /** 7000 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 7001 * the view's unscaled width. A value of 1 means that no scaling is applied. 7002 * 7003 * @param scaleY The scaling factor. 7004 * @see #getPivotX() 7005 * @see #getPivotY() 7006 * 7007 * @attr ref android.R.styleable#View_scaleY 7008 */ 7009 public void setScaleY(float scaleY) { 7010 if (mScaleY != scaleY) { 7011 invalidateParentCaches(); 7012 // Double-invalidation is necessary to capture view's old and new areas 7013 invalidate(false); 7014 mScaleY = scaleY; 7015 mMatrixDirty = true; 7016 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7017 invalidate(false); 7018 } 7019 } 7020 7021 /** 7022 * The x location of the point around which the view is {@link #setRotation(float) rotated} 7023 * and {@link #setScaleX(float) scaled}. 7024 * 7025 * @see #getRotation() 7026 * @see #getScaleX() 7027 * @see #getScaleY() 7028 * @see #getPivotY() 7029 * @return The x location of the pivot point. 7030 */ 7031 public float getPivotX() { 7032 return mPivotX; 7033 } 7034 7035 /** 7036 * Sets the x location of the point around which the view is 7037 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 7038 * By default, the pivot point is centered on the object. 7039 * Setting this property disables this behavior and causes the view to use only the 7040 * explicitly set pivotX and pivotY values. 7041 * 7042 * @param pivotX The x location of the pivot point. 7043 * @see #getRotation() 7044 * @see #getScaleX() 7045 * @see #getScaleY() 7046 * @see #getPivotY() 7047 * 7048 * @attr ref android.R.styleable#View_transformPivotX 7049 */ 7050 public void setPivotX(float pivotX) { 7051 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7052 if (mPivotX != pivotX) { 7053 invalidateParentCaches(); 7054 // Double-invalidation is necessary to capture view's old and new areas 7055 invalidate(false); 7056 mPivotX = pivotX; 7057 mMatrixDirty = true; 7058 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7059 invalidate(false); 7060 } 7061 } 7062 7063 /** 7064 * The y location of the point around which the view is {@link #setRotation(float) rotated} 7065 * and {@link #setScaleY(float) scaled}. 7066 * 7067 * @see #getRotation() 7068 * @see #getScaleX() 7069 * @see #getScaleY() 7070 * @see #getPivotY() 7071 * @return The y location of the pivot point. 7072 */ 7073 public float getPivotY() { 7074 return mPivotY; 7075 } 7076 7077 /** 7078 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 7079 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 7080 * Setting this property disables this behavior and causes the view to use only the 7081 * explicitly set pivotX and pivotY values. 7082 * 7083 * @param pivotY The y location of the pivot point. 7084 * @see #getRotation() 7085 * @see #getScaleX() 7086 * @see #getScaleY() 7087 * @see #getPivotY() 7088 * 7089 * @attr ref android.R.styleable#View_transformPivotY 7090 */ 7091 public void setPivotY(float pivotY) { 7092 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7093 if (mPivotY != pivotY) { 7094 invalidateParentCaches(); 7095 // Double-invalidation is necessary to capture view's old and new areas 7096 invalidate(false); 7097 mPivotY = pivotY; 7098 mMatrixDirty = true; 7099 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7100 invalidate(false); 7101 } 7102 } 7103 7104 /** 7105 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 7106 * completely transparent and 1 means the view is completely opaque. 7107 * 7108 * <p>By default this is 1.0f. 7109 * @return The opacity of the view. 7110 */ 7111 public float getAlpha() { 7112 return mAlpha; 7113 } 7114 7115 /** 7116 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 7117 * completely transparent and 1 means the view is completely opaque.</p> 7118 * 7119 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 7120 * responsible for applying the opacity itself. Otherwise, calling this method is 7121 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 7122 * setting a hardware layer.</p> 7123 * 7124 * @param alpha The opacity of the view. 7125 * 7126 * @see #setLayerType(int, android.graphics.Paint) 7127 * 7128 * @attr ref android.R.styleable#View_alpha 7129 */ 7130 public void setAlpha(float alpha) { 7131 mAlpha = alpha; 7132 invalidateParentCaches(); 7133 if (onSetAlpha((int) (alpha * 255))) { 7134 mPrivateFlags |= ALPHA_SET; 7135 // subclass is handling alpha - don't optimize rendering cache invalidation 7136 invalidate(true); 7137 } else { 7138 mPrivateFlags &= ~ALPHA_SET; 7139 invalidate(false); 7140 } 7141 } 7142 7143 /** 7144 * Faster version of setAlpha() which performs the same steps except there are 7145 * no calls to invalidate(). The caller of this function should perform proper invalidation 7146 * on the parent and this object. The return value indicates whether the subclass handles 7147 * alpha (the return value for onSetAlpha()). 7148 * 7149 * @param alpha The new value for the alpha property 7150 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) 7151 */ 7152 boolean setAlphaNoInvalidation(float alpha) { 7153 mAlpha = alpha; 7154 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 7155 if (subclassHandlesAlpha) { 7156 mPrivateFlags |= ALPHA_SET; 7157 } else { 7158 mPrivateFlags &= ~ALPHA_SET; 7159 } 7160 return subclassHandlesAlpha; 7161 } 7162 7163 /** 7164 * Top position of this view relative to its parent. 7165 * 7166 * @return The top of this view, in pixels. 7167 */ 7168 @ViewDebug.CapturedViewProperty 7169 public final int getTop() { 7170 return mTop; 7171 } 7172 7173 /** 7174 * Sets the top position of this view relative to its parent. This method is meant to be called 7175 * by the layout system and should not generally be called otherwise, because the property 7176 * may be changed at any time by the layout. 7177 * 7178 * @param top The top of this view, in pixels. 7179 */ 7180 public final void setTop(int top) { 7181 if (top != mTop) { 7182 updateMatrix(); 7183 if (mMatrixIsIdentity) { 7184 if (mAttachInfo != null) { 7185 int minTop; 7186 int yLoc; 7187 if (top < mTop) { 7188 minTop = top; 7189 yLoc = top - mTop; 7190 } else { 7191 minTop = mTop; 7192 yLoc = 0; 7193 } 7194 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 7195 } 7196 } else { 7197 // Double-invalidation is necessary to capture view's old and new areas 7198 invalidate(true); 7199 } 7200 7201 int width = mRight - mLeft; 7202 int oldHeight = mBottom - mTop; 7203 7204 mTop = top; 7205 7206 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7207 7208 if (!mMatrixIsIdentity) { 7209 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7210 // A change in dimension means an auto-centered pivot point changes, too 7211 mMatrixDirty = true; 7212 } 7213 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7214 invalidate(true); 7215 } 7216 mBackgroundSizeChanged = true; 7217 invalidateParentIfNeeded(); 7218 } 7219 } 7220 7221 /** 7222 * Bottom position of this view relative to its parent. 7223 * 7224 * @return The bottom of this view, in pixels. 7225 */ 7226 @ViewDebug.CapturedViewProperty 7227 public final int getBottom() { 7228 return mBottom; 7229 } 7230 7231 /** 7232 * True if this view has changed since the last time being drawn. 7233 * 7234 * @return The dirty state of this view. 7235 */ 7236 public boolean isDirty() { 7237 return (mPrivateFlags & DIRTY_MASK) != 0; 7238 } 7239 7240 /** 7241 * Sets the bottom position of this view relative to its parent. This method is meant to be 7242 * called by the layout system and should not generally be called otherwise, because the 7243 * property may be changed at any time by the layout. 7244 * 7245 * @param bottom The bottom of this view, in pixels. 7246 */ 7247 public final void setBottom(int bottom) { 7248 if (bottom != mBottom) { 7249 updateMatrix(); 7250 if (mMatrixIsIdentity) { 7251 if (mAttachInfo != null) { 7252 int maxBottom; 7253 if (bottom < mBottom) { 7254 maxBottom = mBottom; 7255 } else { 7256 maxBottom = bottom; 7257 } 7258 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 7259 } 7260 } else { 7261 // Double-invalidation is necessary to capture view's old and new areas 7262 invalidate(true); 7263 } 7264 7265 int width = mRight - mLeft; 7266 int oldHeight = mBottom - mTop; 7267 7268 mBottom = bottom; 7269 7270 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7271 7272 if (!mMatrixIsIdentity) { 7273 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7274 // A change in dimension means an auto-centered pivot point changes, too 7275 mMatrixDirty = true; 7276 } 7277 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7278 invalidate(true); 7279 } 7280 mBackgroundSizeChanged = true; 7281 invalidateParentIfNeeded(); 7282 } 7283 } 7284 7285 /** 7286 * Left position of this view relative to its parent. 7287 * 7288 * @return The left edge of this view, in pixels. 7289 */ 7290 @ViewDebug.CapturedViewProperty 7291 public final int getLeft() { 7292 return mLeft; 7293 } 7294 7295 /** 7296 * Sets the left position of this view relative to its parent. This method is meant to be called 7297 * by the layout system and should not generally be called otherwise, because the property 7298 * may be changed at any time by the layout. 7299 * 7300 * @param left The bottom of this view, in pixels. 7301 */ 7302 public final void setLeft(int left) { 7303 if (left != mLeft) { 7304 updateMatrix(); 7305 if (mMatrixIsIdentity) { 7306 if (mAttachInfo != null) { 7307 int minLeft; 7308 int xLoc; 7309 if (left < mLeft) { 7310 minLeft = left; 7311 xLoc = left - mLeft; 7312 } else { 7313 minLeft = mLeft; 7314 xLoc = 0; 7315 } 7316 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 7317 } 7318 } else { 7319 // Double-invalidation is necessary to capture view's old and new areas 7320 invalidate(true); 7321 } 7322 7323 int oldWidth = mRight - mLeft; 7324 int height = mBottom - mTop; 7325 7326 mLeft = left; 7327 7328 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7329 7330 if (!mMatrixIsIdentity) { 7331 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7332 // A change in dimension means an auto-centered pivot point changes, too 7333 mMatrixDirty = true; 7334 } 7335 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7336 invalidate(true); 7337 } 7338 mBackgroundSizeChanged = true; 7339 invalidateParentIfNeeded(); 7340 } 7341 } 7342 7343 /** 7344 * Right position of this view relative to its parent. 7345 * 7346 * @return The right edge of this view, in pixels. 7347 */ 7348 @ViewDebug.CapturedViewProperty 7349 public final int getRight() { 7350 return mRight; 7351 } 7352 7353 /** 7354 * Sets the right position of this view relative to its parent. This method is meant to be called 7355 * by the layout system and should not generally be called otherwise, because the property 7356 * may be changed at any time by the layout. 7357 * 7358 * @param right The bottom of this view, in pixels. 7359 */ 7360 public final void setRight(int right) { 7361 if (right != mRight) { 7362 updateMatrix(); 7363 if (mMatrixIsIdentity) { 7364 if (mAttachInfo != null) { 7365 int maxRight; 7366 if (right < mRight) { 7367 maxRight = mRight; 7368 } else { 7369 maxRight = right; 7370 } 7371 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 7372 } 7373 } else { 7374 // Double-invalidation is necessary to capture view's old and new areas 7375 invalidate(true); 7376 } 7377 7378 int oldWidth = mRight - mLeft; 7379 int height = mBottom - mTop; 7380 7381 mRight = right; 7382 7383 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7384 7385 if (!mMatrixIsIdentity) { 7386 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7387 // A change in dimension means an auto-centered pivot point changes, too 7388 mMatrixDirty = true; 7389 } 7390 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7391 invalidate(true); 7392 } 7393 mBackgroundSizeChanged = true; 7394 invalidateParentIfNeeded(); 7395 } 7396 } 7397 7398 /** 7399 * The visual x position of this view, in pixels. This is equivalent to the 7400 * {@link #setTranslationX(float) translationX} property plus the current 7401 * {@link #getLeft() left} property. 7402 * 7403 * @return The visual x position of this view, in pixels. 7404 */ 7405 public float getX() { 7406 return mLeft + mTranslationX; 7407 } 7408 7409 /** 7410 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 7411 * {@link #setTranslationX(float) translationX} property to be the difference between 7412 * the x value passed in and the current {@link #getLeft() left} property. 7413 * 7414 * @param x The visual x position of this view, in pixels. 7415 */ 7416 public void setX(float x) { 7417 setTranslationX(x - mLeft); 7418 } 7419 7420 /** 7421 * The visual y position of this view, in pixels. This is equivalent to the 7422 * {@link #setTranslationY(float) translationY} property plus the current 7423 * {@link #getTop() top} property. 7424 * 7425 * @return The visual y position of this view, in pixels. 7426 */ 7427 public float getY() { 7428 return mTop + mTranslationY; 7429 } 7430 7431 /** 7432 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 7433 * {@link #setTranslationY(float) translationY} property to be the difference between 7434 * the y value passed in and the current {@link #getTop() top} property. 7435 * 7436 * @param y The visual y position of this view, in pixels. 7437 */ 7438 public void setY(float y) { 7439 setTranslationY(y - mTop); 7440 } 7441 7442 7443 /** 7444 * The horizontal location of this view relative to its {@link #getLeft() left} position. 7445 * This position is post-layout, in addition to wherever the object's 7446 * layout placed it. 7447 * 7448 * @return The horizontal position of this view relative to its left position, in pixels. 7449 */ 7450 public float getTranslationX() { 7451 return mTranslationX; 7452 } 7453 7454 /** 7455 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 7456 * This effectively positions the object post-layout, in addition to wherever the object's 7457 * layout placed it. 7458 * 7459 * @param translationX The horizontal position of this view relative to its left position, 7460 * in pixels. 7461 * 7462 * @attr ref android.R.styleable#View_translationX 7463 */ 7464 public void setTranslationX(float translationX) { 7465 if (mTranslationX != translationX) { 7466 invalidateParentCaches(); 7467 // Double-invalidation is necessary to capture view's old and new areas 7468 invalidate(false); 7469 mTranslationX = translationX; 7470 mMatrixDirty = true; 7471 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7472 invalidate(false); 7473 } 7474 } 7475 7476 /** 7477 * The horizontal location of this view relative to its {@link #getTop() top} position. 7478 * This position is post-layout, in addition to wherever the object's 7479 * layout placed it. 7480 * 7481 * @return The vertical position of this view relative to its top position, 7482 * in pixels. 7483 */ 7484 public float getTranslationY() { 7485 return mTranslationY; 7486 } 7487 7488 /** 7489 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 7490 * This effectively positions the object post-layout, in addition to wherever the object's 7491 * layout placed it. 7492 * 7493 * @param translationY The vertical position of this view relative to its top position, 7494 * in pixels. 7495 * 7496 * @attr ref android.R.styleable#View_translationY 7497 */ 7498 public void setTranslationY(float translationY) { 7499 if (mTranslationY != translationY) { 7500 invalidateParentCaches(); 7501 // Double-invalidation is necessary to capture view's old and new areas 7502 invalidate(false); 7503 mTranslationY = translationY; 7504 mMatrixDirty = true; 7505 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7506 invalidate(false); 7507 } 7508 } 7509 7510 /** 7511 * @hide 7512 */ 7513 public void setFastTranslationX(float x) { 7514 mTranslationX = x; 7515 mMatrixDirty = true; 7516 } 7517 7518 /** 7519 * @hide 7520 */ 7521 public void setFastTranslationY(float y) { 7522 mTranslationY = y; 7523 mMatrixDirty = true; 7524 } 7525 7526 /** 7527 * @hide 7528 */ 7529 public void setFastX(float x) { 7530 mTranslationX = x - mLeft; 7531 mMatrixDirty = true; 7532 } 7533 7534 /** 7535 * @hide 7536 */ 7537 public void setFastY(float y) { 7538 mTranslationY = y - mTop; 7539 mMatrixDirty = true; 7540 } 7541 7542 /** 7543 * @hide 7544 */ 7545 public void setFastScaleX(float x) { 7546 mScaleX = x; 7547 mMatrixDirty = true; 7548 } 7549 7550 /** 7551 * @hide 7552 */ 7553 public void setFastScaleY(float y) { 7554 mScaleY = y; 7555 mMatrixDirty = true; 7556 } 7557 7558 /** 7559 * @hide 7560 */ 7561 public void setFastAlpha(float alpha) { 7562 mAlpha = alpha; 7563 } 7564 7565 /** 7566 * @hide 7567 */ 7568 public void setFastRotationY(float y) { 7569 mRotationY = y; 7570 mMatrixDirty = true; 7571 } 7572 7573 /** 7574 * Hit rectangle in parent's coordinates 7575 * 7576 * @param outRect The hit rectangle of the view. 7577 */ 7578 public void getHitRect(Rect outRect) { 7579 updateMatrix(); 7580 if (mMatrixIsIdentity || mAttachInfo == null) { 7581 outRect.set(mLeft, mTop, mRight, mBottom); 7582 } else { 7583 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 7584 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY); 7585 mMatrix.mapRect(tmpRect); 7586 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 7587 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 7588 } 7589 } 7590 7591 /** 7592 * Determines whether the given point, in local coordinates is inside the view. 7593 */ 7594 /*package*/ final boolean pointInView(float localX, float localY) { 7595 return localX >= 0 && localX < (mRight - mLeft) 7596 && localY >= 0 && localY < (mBottom - mTop); 7597 } 7598 7599 /** 7600 * Utility method to determine whether the given point, in local coordinates, 7601 * is inside the view, where the area of the view is expanded by the slop factor. 7602 * This method is called while processing touch-move events to determine if the event 7603 * is still within the view. 7604 */ 7605 private boolean pointInView(float localX, float localY, float slop) { 7606 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 7607 localY < ((mBottom - mTop) + slop); 7608 } 7609 7610 /** 7611 * When a view has focus and the user navigates away from it, the next view is searched for 7612 * starting from the rectangle filled in by this method. 7613 * 7614 * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)}) 7615 * of the view. However, if your view maintains some idea of internal selection, 7616 * such as a cursor, or a selected row or column, you should override this method and 7617 * fill in a more specific rectangle. 7618 * 7619 * @param r The rectangle to fill in, in this view's coordinates. 7620 */ 7621 public void getFocusedRect(Rect r) { 7622 getDrawingRect(r); 7623 } 7624 7625 /** 7626 * If some part of this view is not clipped by any of its parents, then 7627 * return that area in r in global (root) coordinates. To convert r to local 7628 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x, 7629 * -globalOffset.y)) If the view is completely clipped or translated out, 7630 * return false. 7631 * 7632 * @param r If true is returned, r holds the global coordinates of the 7633 * visible portion of this view. 7634 * @param globalOffset If true is returned, globalOffset holds the dx,dy 7635 * between this view and its root. globalOffet may be null. 7636 * @return true if r is non-empty (i.e. part of the view is visible at the 7637 * root level. 7638 */ 7639 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 7640 int width = mRight - mLeft; 7641 int height = mBottom - mTop; 7642 if (width > 0 && height > 0) { 7643 r.set(0, 0, width, height); 7644 if (globalOffset != null) { 7645 globalOffset.set(-mScrollX, -mScrollY); 7646 } 7647 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 7648 } 7649 return false; 7650 } 7651 7652 public final boolean getGlobalVisibleRect(Rect r) { 7653 return getGlobalVisibleRect(r, null); 7654 } 7655 7656 public final boolean getLocalVisibleRect(Rect r) { 7657 Point offset = new Point(); 7658 if (getGlobalVisibleRect(r, offset)) { 7659 r.offset(-offset.x, -offset.y); // make r local 7660 return true; 7661 } 7662 return false; 7663 } 7664 7665 /** 7666 * Offset this view's vertical location by the specified number of pixels. 7667 * 7668 * @param offset the number of pixels to offset the view by 7669 */ 7670 public void offsetTopAndBottom(int offset) { 7671 if (offset != 0) { 7672 updateMatrix(); 7673 if (mMatrixIsIdentity) { 7674 final ViewParent p = mParent; 7675 if (p != null && mAttachInfo != null) { 7676 final Rect r = mAttachInfo.mTmpInvalRect; 7677 int minTop; 7678 int maxBottom; 7679 int yLoc; 7680 if (offset < 0) { 7681 minTop = mTop + offset; 7682 maxBottom = mBottom; 7683 yLoc = offset; 7684 } else { 7685 minTop = mTop; 7686 maxBottom = mBottom + offset; 7687 yLoc = 0; 7688 } 7689 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 7690 p.invalidateChild(this, r); 7691 } 7692 } else { 7693 invalidate(false); 7694 } 7695 7696 mTop += offset; 7697 mBottom += offset; 7698 7699 if (!mMatrixIsIdentity) { 7700 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7701 invalidate(false); 7702 } 7703 invalidateParentIfNeeded(); 7704 } 7705 } 7706 7707 /** 7708 * Offset this view's horizontal location by the specified amount of pixels. 7709 * 7710 * @param offset the numer of pixels to offset the view by 7711 */ 7712 public void offsetLeftAndRight(int offset) { 7713 if (offset != 0) { 7714 updateMatrix(); 7715 if (mMatrixIsIdentity) { 7716 final ViewParent p = mParent; 7717 if (p != null && mAttachInfo != null) { 7718 final Rect r = mAttachInfo.mTmpInvalRect; 7719 int minLeft; 7720 int maxRight; 7721 if (offset < 0) { 7722 minLeft = mLeft + offset; 7723 maxRight = mRight; 7724 } else { 7725 minLeft = mLeft; 7726 maxRight = mRight + offset; 7727 } 7728 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 7729 p.invalidateChild(this, r); 7730 } 7731 } else { 7732 invalidate(false); 7733 } 7734 7735 mLeft += offset; 7736 mRight += offset; 7737 7738 if (!mMatrixIsIdentity) { 7739 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7740 invalidate(false); 7741 } 7742 invalidateParentIfNeeded(); 7743 } 7744 } 7745 7746 /** 7747 * Get the LayoutParams associated with this view. All views should have 7748 * layout parameters. These supply parameters to the <i>parent</i> of this 7749 * view specifying how it should be arranged. There are many subclasses of 7750 * ViewGroup.LayoutParams, and these correspond to the different subclasses 7751 * of ViewGroup that are responsible for arranging their children. 7752 * 7753 * This method may return null if this View is not attached to a parent 7754 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 7755 * was not invoked successfully. When a View is attached to a parent 7756 * ViewGroup, this method must not return null. 7757 * 7758 * @return The LayoutParams associated with this view, or null if no 7759 * parameters have been set yet 7760 */ 7761 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 7762 public ViewGroup.LayoutParams getLayoutParams() { 7763 return mLayoutParams; 7764 } 7765 7766 /** 7767 * Set the layout parameters associated with this view. These supply 7768 * parameters to the <i>parent</i> of this view specifying how it should be 7769 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 7770 * correspond to the different subclasses of ViewGroup that are responsible 7771 * for arranging their children. 7772 * 7773 * @param params The layout parameters for this view, cannot be null 7774 */ 7775 public void setLayoutParams(ViewGroup.LayoutParams params) { 7776 if (params == null) { 7777 throw new NullPointerException("Layout parameters cannot be null"); 7778 } 7779 mLayoutParams = params; 7780 requestLayout(); 7781 } 7782 7783 /** 7784 * Set the scrolled position of your view. This will cause a call to 7785 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7786 * invalidated. 7787 * @param x the x position to scroll to 7788 * @param y the y position to scroll to 7789 */ 7790 public void scrollTo(int x, int y) { 7791 if (mScrollX != x || mScrollY != y) { 7792 int oldX = mScrollX; 7793 int oldY = mScrollY; 7794 mScrollX = x; 7795 mScrollY = y; 7796 invalidateParentCaches(); 7797 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 7798 if (!awakenScrollBars()) { 7799 invalidate(true); 7800 } 7801 } 7802 } 7803 7804 /** 7805 * Move the scrolled position of your view. This will cause a call to 7806 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7807 * invalidated. 7808 * @param x the amount of pixels to scroll by horizontally 7809 * @param y the amount of pixels to scroll by vertically 7810 */ 7811 public void scrollBy(int x, int y) { 7812 scrollTo(mScrollX + x, mScrollY + y); 7813 } 7814 7815 /** 7816 * <p>Trigger the scrollbars to draw. When invoked this method starts an 7817 * animation to fade the scrollbars out after a default delay. If a subclass 7818 * provides animated scrolling, the start delay should equal the duration 7819 * of the scrolling animation.</p> 7820 * 7821 * <p>The animation starts only if at least one of the scrollbars is 7822 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 7823 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 7824 * this method returns true, and false otherwise. If the animation is 7825 * started, this method calls {@link #invalidate()}; in that case the 7826 * caller should not call {@link #invalidate()}.</p> 7827 * 7828 * <p>This method should be invoked every time a subclass directly updates 7829 * the scroll parameters.</p> 7830 * 7831 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 7832 * and {@link #scrollTo(int, int)}.</p> 7833 * 7834 * @return true if the animation is played, false otherwise 7835 * 7836 * @see #awakenScrollBars(int) 7837 * @see #scrollBy(int, int) 7838 * @see #scrollTo(int, int) 7839 * @see #isHorizontalScrollBarEnabled() 7840 * @see #isVerticalScrollBarEnabled() 7841 * @see #setHorizontalScrollBarEnabled(boolean) 7842 * @see #setVerticalScrollBarEnabled(boolean) 7843 */ 7844 protected boolean awakenScrollBars() { 7845 return mScrollCache != null && 7846 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 7847 } 7848 7849 /** 7850 * Trigger the scrollbars to draw. 7851 * This method differs from awakenScrollBars() only in its default duration. 7852 * initialAwakenScrollBars() will show the scroll bars for longer than 7853 * usual to give the user more of a chance to notice them. 7854 * 7855 * @return true if the animation is played, false otherwise. 7856 */ 7857 private boolean initialAwakenScrollBars() { 7858 return mScrollCache != null && 7859 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 7860 } 7861 7862 /** 7863 * <p> 7864 * Trigger the scrollbars to draw. When invoked this method starts an 7865 * animation to fade the scrollbars out after a fixed delay. If a subclass 7866 * provides animated scrolling, the start delay should equal the duration of 7867 * the scrolling animation. 7868 * </p> 7869 * 7870 * <p> 7871 * The animation starts only if at least one of the scrollbars is enabled, 7872 * as specified by {@link #isHorizontalScrollBarEnabled()} and 7873 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 7874 * this method returns true, and false otherwise. If the animation is 7875 * started, this method calls {@link #invalidate()}; in that case the caller 7876 * should not call {@link #invalidate()}. 7877 * </p> 7878 * 7879 * <p> 7880 * This method should be invoked everytime a subclass directly updates the 7881 * scroll parameters. 7882 * </p> 7883 * 7884 * @param startDelay the delay, in milliseconds, after which the animation 7885 * should start; when the delay is 0, the animation starts 7886 * immediately 7887 * @return true if the animation is played, false otherwise 7888 * 7889 * @see #scrollBy(int, int) 7890 * @see #scrollTo(int, int) 7891 * @see #isHorizontalScrollBarEnabled() 7892 * @see #isVerticalScrollBarEnabled() 7893 * @see #setHorizontalScrollBarEnabled(boolean) 7894 * @see #setVerticalScrollBarEnabled(boolean) 7895 */ 7896 protected boolean awakenScrollBars(int startDelay) { 7897 return awakenScrollBars(startDelay, true); 7898 } 7899 7900 /** 7901 * <p> 7902 * Trigger the scrollbars to draw. When invoked this method starts an 7903 * animation to fade the scrollbars out after a fixed delay. If a subclass 7904 * provides animated scrolling, the start delay should equal the duration of 7905 * the scrolling animation. 7906 * </p> 7907 * 7908 * <p> 7909 * The animation starts only if at least one of the scrollbars is enabled, 7910 * as specified by {@link #isHorizontalScrollBarEnabled()} and 7911 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 7912 * this method returns true, and false otherwise. If the animation is 7913 * started, this method calls {@link #invalidate()} if the invalidate parameter 7914 * is set to true; in that case the caller 7915 * should not call {@link #invalidate()}. 7916 * </p> 7917 * 7918 * <p> 7919 * This method should be invoked everytime a subclass directly updates the 7920 * scroll parameters. 7921 * </p> 7922 * 7923 * @param startDelay the delay, in milliseconds, after which the animation 7924 * should start; when the delay is 0, the animation starts 7925 * immediately 7926 * 7927 * @param invalidate Wheter this method should call invalidate 7928 * 7929 * @return true if the animation is played, false otherwise 7930 * 7931 * @see #scrollBy(int, int) 7932 * @see #scrollTo(int, int) 7933 * @see #isHorizontalScrollBarEnabled() 7934 * @see #isVerticalScrollBarEnabled() 7935 * @see #setHorizontalScrollBarEnabled(boolean) 7936 * @see #setVerticalScrollBarEnabled(boolean) 7937 */ 7938 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 7939 final ScrollabilityCache scrollCache = mScrollCache; 7940 7941 if (scrollCache == null || !scrollCache.fadeScrollBars) { 7942 return false; 7943 } 7944 7945 if (scrollCache.scrollBar == null) { 7946 scrollCache.scrollBar = new ScrollBarDrawable(); 7947 } 7948 7949 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 7950 7951 if (invalidate) { 7952 // Invalidate to show the scrollbars 7953 invalidate(true); 7954 } 7955 7956 if (scrollCache.state == ScrollabilityCache.OFF) { 7957 // FIXME: this is copied from WindowManagerService. 7958 // We should get this value from the system when it 7959 // is possible to do so. 7960 final int KEY_REPEAT_FIRST_DELAY = 750; 7961 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 7962 } 7963 7964 // Tell mScrollCache when we should start fading. This may 7965 // extend the fade start time if one was already scheduled 7966 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 7967 scrollCache.fadeStartTime = fadeStartTime; 7968 scrollCache.state = ScrollabilityCache.ON; 7969 7970 // Schedule our fader to run, unscheduling any old ones first 7971 if (mAttachInfo != null) { 7972 mAttachInfo.mHandler.removeCallbacks(scrollCache); 7973 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 7974 } 7975 7976 return true; 7977 } 7978 7979 return false; 7980 } 7981 7982 /** 7983 * Mark the the area defined by dirty as needing to be drawn. If the view is 7984 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 7985 * in the future. This must be called from a UI thread. To call from a non-UI 7986 * thread, call {@link #postInvalidate()}. 7987 * 7988 * WARNING: This method is destructive to dirty. 7989 * @param dirty the rectangle representing the bounds of the dirty region 7990 */ 7991 public void invalidate(Rect dirty) { 7992 if (ViewDebug.TRACE_HIERARCHY) { 7993 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 7994 } 7995 7996 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 7997 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 7998 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 7999 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8000 mPrivateFlags |= INVALIDATED; 8001 final ViewParent p = mParent; 8002 final AttachInfo ai = mAttachInfo; 8003 //noinspection PointlessBooleanExpression,ConstantConditions 8004 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8005 if (p != null && ai != null && ai.mHardwareAccelerated) { 8006 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8007 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8008 p.invalidateChild(this, null); 8009 return; 8010 } 8011 } 8012 if (p != null && ai != null) { 8013 final int scrollX = mScrollX; 8014 final int scrollY = mScrollY; 8015 final Rect r = ai.mTmpInvalRect; 8016 r.set(dirty.left - scrollX, dirty.top - scrollY, 8017 dirty.right - scrollX, dirty.bottom - scrollY); 8018 mParent.invalidateChild(this, r); 8019 } 8020 } 8021 } 8022 8023 /** 8024 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn. 8025 * The coordinates of the dirty rect are relative to the view. 8026 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 8027 * will be called at some point in the future. This must be called from 8028 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 8029 * @param l the left position of the dirty region 8030 * @param t the top position of the dirty region 8031 * @param r the right position of the dirty region 8032 * @param b the bottom position of the dirty region 8033 */ 8034 public void invalidate(int l, int t, int r, int b) { 8035 if (ViewDebug.TRACE_HIERARCHY) { 8036 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8037 } 8038 8039 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8040 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8041 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8042 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8043 mPrivateFlags |= INVALIDATED; 8044 final ViewParent p = mParent; 8045 final AttachInfo ai = mAttachInfo; 8046 //noinspection PointlessBooleanExpression,ConstantConditions 8047 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8048 if (p != null && ai != null && ai.mHardwareAccelerated) { 8049 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8050 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8051 p.invalidateChild(this, null); 8052 return; 8053 } 8054 } 8055 if (p != null && ai != null && l < r && t < b) { 8056 final int scrollX = mScrollX; 8057 final int scrollY = mScrollY; 8058 final Rect tmpr = ai.mTmpInvalRect; 8059 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 8060 p.invalidateChild(this, tmpr); 8061 } 8062 } 8063 } 8064 8065 /** 8066 * Invalidate the whole view. If the view is visible, 8067 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 8068 * the future. This must be called from a UI thread. To call from a non-UI thread, 8069 * call {@link #postInvalidate()}. 8070 */ 8071 public void invalidate() { 8072 invalidate(true); 8073 } 8074 8075 /** 8076 * This is where the invalidate() work actually happens. A full invalidate() 8077 * causes the drawing cache to be invalidated, but this function can be called with 8078 * invalidateCache set to false to skip that invalidation step for cases that do not 8079 * need it (for example, a component that remains at the same dimensions with the same 8080 * content). 8081 * 8082 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 8083 * well. This is usually true for a full invalidate, but may be set to false if the 8084 * View's contents or dimensions have not changed. 8085 */ 8086 void invalidate(boolean invalidateCache) { 8087 if (ViewDebug.TRACE_HIERARCHY) { 8088 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8089 } 8090 8091 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8092 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) || 8093 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) { 8094 mLastIsOpaque = isOpaque(); 8095 mPrivateFlags &= ~DRAWN; 8096 if (invalidateCache) { 8097 mPrivateFlags |= INVALIDATED; 8098 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8099 } 8100 final AttachInfo ai = mAttachInfo; 8101 final ViewParent p = mParent; 8102 //noinspection PointlessBooleanExpression,ConstantConditions 8103 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8104 if (p != null && ai != null && ai.mHardwareAccelerated) { 8105 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8106 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8107 p.invalidateChild(this, null); 8108 return; 8109 } 8110 } 8111 8112 if (p != null && ai != null) { 8113 final Rect r = ai.mTmpInvalRect; 8114 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8115 // Don't call invalidate -- we don't want to internally scroll 8116 // our own bounds 8117 p.invalidateChild(this, r); 8118 } 8119 } 8120 } 8121 8122 /** 8123 * @hide 8124 */ 8125 public void fastInvalidate() { 8126 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8127 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8128 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8129 if (mParent instanceof View) { 8130 ((View) mParent).mPrivateFlags |= INVALIDATED; 8131 } 8132 mPrivateFlags &= ~DRAWN; 8133 mPrivateFlags |= INVALIDATED; 8134 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8135 if (mParent != null && mAttachInfo != null) { 8136 if (mAttachInfo.mHardwareAccelerated) { 8137 mParent.invalidateChild(this, null); 8138 } else { 8139 final Rect r = mAttachInfo.mTmpInvalRect; 8140 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8141 // Don't call invalidate -- we don't want to internally scroll 8142 // our own bounds 8143 mParent.invalidateChild(this, r); 8144 } 8145 } 8146 } 8147 } 8148 8149 /** 8150 * Used to indicate that the parent of this view should clear its caches. This functionality 8151 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8152 * which is necessary when various parent-managed properties of the view change, such as 8153 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 8154 * clears the parent caches and does not causes an invalidate event. 8155 * 8156 * @hide 8157 */ 8158 protected void invalidateParentCaches() { 8159 if (mParent instanceof View) { 8160 ((View) mParent).mPrivateFlags |= INVALIDATED; 8161 } 8162 } 8163 8164 /** 8165 * Used to indicate that the parent of this view should be invalidated. This functionality 8166 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8167 * which is necessary when various parent-managed properties of the view change, such as 8168 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 8169 * an invalidation event to the parent. 8170 * 8171 * @hide 8172 */ 8173 protected void invalidateParentIfNeeded() { 8174 if (isHardwareAccelerated() && mParent instanceof View) { 8175 ((View) mParent).invalidate(true); 8176 } 8177 } 8178 8179 /** 8180 * Indicates whether this View is opaque. An opaque View guarantees that it will 8181 * draw all the pixels overlapping its bounds using a fully opaque color. 8182 * 8183 * Subclasses of View should override this method whenever possible to indicate 8184 * whether an instance is opaque. Opaque Views are treated in a special way by 8185 * the View hierarchy, possibly allowing it to perform optimizations during 8186 * invalidate/draw passes. 8187 * 8188 * @return True if this View is guaranteed to be fully opaque, false otherwise. 8189 */ 8190 @ViewDebug.ExportedProperty(category = "drawing") 8191 public boolean isOpaque() { 8192 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK && 8193 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD); 8194 } 8195 8196 /** 8197 * @hide 8198 */ 8199 protected void computeOpaqueFlags() { 8200 // Opaque if: 8201 // - Has a background 8202 // - Background is opaque 8203 // - Doesn't have scrollbars or scrollbars are inside overlay 8204 8205 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) { 8206 mPrivateFlags |= OPAQUE_BACKGROUND; 8207 } else { 8208 mPrivateFlags &= ~OPAQUE_BACKGROUND; 8209 } 8210 8211 final int flags = mViewFlags; 8212 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 8213 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 8214 mPrivateFlags |= OPAQUE_SCROLLBARS; 8215 } else { 8216 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 8217 } 8218 } 8219 8220 /** 8221 * @hide 8222 */ 8223 protected boolean hasOpaqueScrollbars() { 8224 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 8225 } 8226 8227 /** 8228 * @return A handler associated with the thread running the View. This 8229 * handler can be used to pump events in the UI events queue. 8230 */ 8231 public Handler getHandler() { 8232 if (mAttachInfo != null) { 8233 return mAttachInfo.mHandler; 8234 } 8235 return null; 8236 } 8237 8238 /** 8239 * Causes the Runnable to be added to the message queue. 8240 * The runnable will be run on the user interface thread. 8241 * 8242 * @param action The Runnable that will be executed. 8243 * 8244 * @return Returns true if the Runnable was successfully placed in to the 8245 * message queue. Returns false on failure, usually because the 8246 * looper processing the message queue is exiting. 8247 */ 8248 public boolean post(Runnable action) { 8249 Handler handler; 8250 AttachInfo attachInfo = mAttachInfo; 8251 if (attachInfo != null) { 8252 handler = attachInfo.mHandler; 8253 } else { 8254 // Assume that post will succeed later 8255 ViewRootImpl.getRunQueue().post(action); 8256 return true; 8257 } 8258 8259 return handler.post(action); 8260 } 8261 8262 /** 8263 * Causes the Runnable to be added to the message queue, to be run 8264 * after the specified amount of time elapses. 8265 * The runnable will be run on the user interface thread. 8266 * 8267 * @param action The Runnable that will be executed. 8268 * @param delayMillis The delay (in milliseconds) until the Runnable 8269 * will be executed. 8270 * 8271 * @return true if the Runnable was successfully placed in to the 8272 * message queue. Returns false on failure, usually because the 8273 * looper processing the message queue is exiting. Note that a 8274 * result of true does not mean the Runnable will be processed -- 8275 * if the looper is quit before the delivery time of the message 8276 * occurs then the message will be dropped. 8277 */ 8278 public boolean postDelayed(Runnable action, long delayMillis) { 8279 Handler handler; 8280 AttachInfo attachInfo = mAttachInfo; 8281 if (attachInfo != null) { 8282 handler = attachInfo.mHandler; 8283 } else { 8284 // Assume that post will succeed later 8285 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 8286 return true; 8287 } 8288 8289 return handler.postDelayed(action, delayMillis); 8290 } 8291 8292 /** 8293 * Removes the specified Runnable from the message queue. 8294 * 8295 * @param action The Runnable to remove from the message handling queue 8296 * 8297 * @return true if this view could ask the Handler to remove the Runnable, 8298 * false otherwise. When the returned value is true, the Runnable 8299 * may or may not have been actually removed from the message queue 8300 * (for instance, if the Runnable was not in the queue already.) 8301 */ 8302 public boolean removeCallbacks(Runnable action) { 8303 Handler handler; 8304 AttachInfo attachInfo = mAttachInfo; 8305 if (attachInfo != null) { 8306 handler = attachInfo.mHandler; 8307 } else { 8308 // Assume that post will succeed later 8309 ViewRootImpl.getRunQueue().removeCallbacks(action); 8310 return true; 8311 } 8312 8313 handler.removeCallbacks(action); 8314 return true; 8315 } 8316 8317 /** 8318 * Cause an invalidate to happen on a subsequent cycle through the event loop. 8319 * Use this to invalidate the View from a non-UI thread. 8320 * 8321 * @see #invalidate() 8322 */ 8323 public void postInvalidate() { 8324 postInvalidateDelayed(0); 8325 } 8326 8327 /** 8328 * Cause an invalidate of the specified area to happen on a subsequent cycle 8329 * through the event loop. Use this to invalidate the View from a non-UI thread. 8330 * 8331 * @param left The left coordinate of the rectangle to invalidate. 8332 * @param top The top coordinate of the rectangle to invalidate. 8333 * @param right The right coordinate of the rectangle to invalidate. 8334 * @param bottom The bottom coordinate of the rectangle to invalidate. 8335 * 8336 * @see #invalidate(int, int, int, int) 8337 * @see #invalidate(Rect) 8338 */ 8339 public void postInvalidate(int left, int top, int right, int bottom) { 8340 postInvalidateDelayed(0, left, top, right, bottom); 8341 } 8342 8343 /** 8344 * Cause an invalidate to happen on a subsequent cycle through the event 8345 * loop. Waits for the specified amount of time. 8346 * 8347 * @param delayMilliseconds the duration in milliseconds to delay the 8348 * invalidation by 8349 */ 8350 public void postInvalidateDelayed(long delayMilliseconds) { 8351 // We try only with the AttachInfo because there's no point in invalidating 8352 // if we are not attached to our window 8353 AttachInfo attachInfo = mAttachInfo; 8354 if (attachInfo != null) { 8355 Message msg = Message.obtain(); 8356 msg.what = AttachInfo.INVALIDATE_MSG; 8357 msg.obj = this; 8358 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8359 } 8360 } 8361 8362 /** 8363 * Cause an invalidate of the specified area to happen on a subsequent cycle 8364 * through the event loop. Waits for the specified amount of time. 8365 * 8366 * @param delayMilliseconds the duration in milliseconds to delay the 8367 * invalidation by 8368 * @param left The left coordinate of the rectangle to invalidate. 8369 * @param top The top coordinate of the rectangle to invalidate. 8370 * @param right The right coordinate of the rectangle to invalidate. 8371 * @param bottom The bottom coordinate of the rectangle to invalidate. 8372 */ 8373 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 8374 int right, int bottom) { 8375 8376 // We try only with the AttachInfo because there's no point in invalidating 8377 // if we are not attached to our window 8378 AttachInfo attachInfo = mAttachInfo; 8379 if (attachInfo != null) { 8380 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 8381 info.target = this; 8382 info.left = left; 8383 info.top = top; 8384 info.right = right; 8385 info.bottom = bottom; 8386 8387 final Message msg = Message.obtain(); 8388 msg.what = AttachInfo.INVALIDATE_RECT_MSG; 8389 msg.obj = info; 8390 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8391 } 8392 } 8393 8394 /** 8395 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 8396 * This event is sent at most once every 8397 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 8398 */ 8399 private void postSendViewScrolledAccessibilityEventCallback() { 8400 if (mSendViewScrolledAccessibilityEvent == null) { 8401 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 8402 } 8403 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 8404 mSendViewScrolledAccessibilityEvent.mIsPending = true; 8405 postDelayed(mSendViewScrolledAccessibilityEvent, 8406 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 8407 } 8408 } 8409 8410 /** 8411 * Called by a parent to request that a child update its values for mScrollX 8412 * and mScrollY if necessary. This will typically be done if the child is 8413 * animating a scroll using a {@link android.widget.Scroller Scroller} 8414 * object. 8415 */ 8416 public void computeScroll() { 8417 } 8418 8419 /** 8420 * <p>Indicate whether the horizontal edges are faded when the view is 8421 * scrolled horizontally.</p> 8422 * 8423 * @return true if the horizontal edges should are faded on scroll, false 8424 * otherwise 8425 * 8426 * @see #setHorizontalFadingEdgeEnabled(boolean) 8427 * @attr ref android.R.styleable#View_fadingEdge 8428 */ 8429 public boolean isHorizontalFadingEdgeEnabled() { 8430 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 8431 } 8432 8433 /** 8434 * <p>Define whether the horizontal edges should be faded when this view 8435 * is scrolled horizontally.</p> 8436 * 8437 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 8438 * be faded when the view is scrolled 8439 * horizontally 8440 * 8441 * @see #isHorizontalFadingEdgeEnabled() 8442 * @attr ref android.R.styleable#View_fadingEdge 8443 */ 8444 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 8445 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 8446 if (horizontalFadingEdgeEnabled) { 8447 initScrollCache(); 8448 } 8449 8450 mViewFlags ^= FADING_EDGE_HORIZONTAL; 8451 } 8452 } 8453 8454 /** 8455 * <p>Indicate whether the vertical edges are faded when the view is 8456 * scrolled horizontally.</p> 8457 * 8458 * @return true if the vertical edges should are faded on scroll, false 8459 * otherwise 8460 * 8461 * @see #setVerticalFadingEdgeEnabled(boolean) 8462 * @attr ref android.R.styleable#View_fadingEdge 8463 */ 8464 public boolean isVerticalFadingEdgeEnabled() { 8465 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 8466 } 8467 8468 /** 8469 * <p>Define whether the vertical edges should be faded when this view 8470 * is scrolled vertically.</p> 8471 * 8472 * @param verticalFadingEdgeEnabled true if the vertical edges should 8473 * be faded when the view is scrolled 8474 * vertically 8475 * 8476 * @see #isVerticalFadingEdgeEnabled() 8477 * @attr ref android.R.styleable#View_fadingEdge 8478 */ 8479 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 8480 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 8481 if (verticalFadingEdgeEnabled) { 8482 initScrollCache(); 8483 } 8484 8485 mViewFlags ^= FADING_EDGE_VERTICAL; 8486 } 8487 } 8488 8489 /** 8490 * Returns the strength, or intensity, of the top faded edge. The strength is 8491 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8492 * returns 0.0 or 1.0 but no value in between. 8493 * 8494 * Subclasses should override this method to provide a smoother fade transition 8495 * when scrolling occurs. 8496 * 8497 * @return the intensity of the top fade as a float between 0.0f and 1.0f 8498 */ 8499 protected float getTopFadingEdgeStrength() { 8500 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 8501 } 8502 8503 /** 8504 * Returns the strength, or intensity, of the bottom faded edge. The strength is 8505 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8506 * returns 0.0 or 1.0 but no value in between. 8507 * 8508 * Subclasses should override this method to provide a smoother fade transition 8509 * when scrolling occurs. 8510 * 8511 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 8512 */ 8513 protected float getBottomFadingEdgeStrength() { 8514 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 8515 computeVerticalScrollRange() ? 1.0f : 0.0f; 8516 } 8517 8518 /** 8519 * Returns the strength, or intensity, of the left faded edge. The strength is 8520 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8521 * returns 0.0 or 1.0 but no value in between. 8522 * 8523 * Subclasses should override this method to provide a smoother fade transition 8524 * when scrolling occurs. 8525 * 8526 * @return the intensity of the left fade as a float between 0.0f and 1.0f 8527 */ 8528 protected float getLeftFadingEdgeStrength() { 8529 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 8530 } 8531 8532 /** 8533 * Returns the strength, or intensity, of the right faded edge. The strength is 8534 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8535 * returns 0.0 or 1.0 but no value in between. 8536 * 8537 * Subclasses should override this method to provide a smoother fade transition 8538 * when scrolling occurs. 8539 * 8540 * @return the intensity of the right fade as a float between 0.0f and 1.0f 8541 */ 8542 protected float getRightFadingEdgeStrength() { 8543 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 8544 computeHorizontalScrollRange() ? 1.0f : 0.0f; 8545 } 8546 8547 /** 8548 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 8549 * scrollbar is not drawn by default.</p> 8550 * 8551 * @return true if the horizontal scrollbar should be painted, false 8552 * otherwise 8553 * 8554 * @see #setHorizontalScrollBarEnabled(boolean) 8555 */ 8556 public boolean isHorizontalScrollBarEnabled() { 8557 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 8558 } 8559 8560 /** 8561 * <p>Define whether the horizontal scrollbar should be drawn or not. The 8562 * scrollbar is not drawn by default.</p> 8563 * 8564 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 8565 * be painted 8566 * 8567 * @see #isHorizontalScrollBarEnabled() 8568 */ 8569 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 8570 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 8571 mViewFlags ^= SCROLLBARS_HORIZONTAL; 8572 computeOpaqueFlags(); 8573 resolvePadding(); 8574 } 8575 } 8576 8577 /** 8578 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 8579 * scrollbar is not drawn by default.</p> 8580 * 8581 * @return true if the vertical scrollbar should be painted, false 8582 * otherwise 8583 * 8584 * @see #setVerticalScrollBarEnabled(boolean) 8585 */ 8586 public boolean isVerticalScrollBarEnabled() { 8587 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 8588 } 8589 8590 /** 8591 * <p>Define whether the vertical scrollbar should be drawn or not. The 8592 * scrollbar is not drawn by default.</p> 8593 * 8594 * @param verticalScrollBarEnabled true if the vertical scrollbar should 8595 * be painted 8596 * 8597 * @see #isVerticalScrollBarEnabled() 8598 */ 8599 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 8600 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 8601 mViewFlags ^= SCROLLBARS_VERTICAL; 8602 computeOpaqueFlags(); 8603 resolvePadding(); 8604 } 8605 } 8606 8607 /** 8608 * @hide 8609 */ 8610 protected void recomputePadding() { 8611 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 8612 } 8613 8614 /** 8615 * Define whether scrollbars will fade when the view is not scrolling. 8616 * 8617 * @param fadeScrollbars wheter to enable fading 8618 * 8619 */ 8620 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 8621 initScrollCache(); 8622 final ScrollabilityCache scrollabilityCache = mScrollCache; 8623 scrollabilityCache.fadeScrollBars = fadeScrollbars; 8624 if (fadeScrollbars) { 8625 scrollabilityCache.state = ScrollabilityCache.OFF; 8626 } else { 8627 scrollabilityCache.state = ScrollabilityCache.ON; 8628 } 8629 } 8630 8631 /** 8632 * 8633 * Returns true if scrollbars will fade when this view is not scrolling 8634 * 8635 * @return true if scrollbar fading is enabled 8636 */ 8637 public boolean isScrollbarFadingEnabled() { 8638 return mScrollCache != null && mScrollCache.fadeScrollBars; 8639 } 8640 8641 /** 8642 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 8643 * inset. When inset, they add to the padding of the view. And the scrollbars 8644 * can be drawn inside the padding area or on the edge of the view. For example, 8645 * if a view has a background drawable and you want to draw the scrollbars 8646 * inside the padding specified by the drawable, you can use 8647 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 8648 * appear at the edge of the view, ignoring the padding, then you can use 8649 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 8650 * @param style the style of the scrollbars. Should be one of 8651 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 8652 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 8653 * @see #SCROLLBARS_INSIDE_OVERLAY 8654 * @see #SCROLLBARS_INSIDE_INSET 8655 * @see #SCROLLBARS_OUTSIDE_OVERLAY 8656 * @see #SCROLLBARS_OUTSIDE_INSET 8657 */ 8658 public void setScrollBarStyle(int style) { 8659 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 8660 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 8661 computeOpaqueFlags(); 8662 resolvePadding(); 8663 } 8664 } 8665 8666 /** 8667 * <p>Returns the current scrollbar style.</p> 8668 * @return the current scrollbar style 8669 * @see #SCROLLBARS_INSIDE_OVERLAY 8670 * @see #SCROLLBARS_INSIDE_INSET 8671 * @see #SCROLLBARS_OUTSIDE_OVERLAY 8672 * @see #SCROLLBARS_OUTSIDE_INSET 8673 */ 8674 public int getScrollBarStyle() { 8675 return mViewFlags & SCROLLBARS_STYLE_MASK; 8676 } 8677 8678 /** 8679 * <p>Compute the horizontal range that the horizontal scrollbar 8680 * represents.</p> 8681 * 8682 * <p>The range is expressed in arbitrary units that must be the same as the 8683 * units used by {@link #computeHorizontalScrollExtent()} and 8684 * {@link #computeHorizontalScrollOffset()}.</p> 8685 * 8686 * <p>The default range is the drawing width of this view.</p> 8687 * 8688 * @return the total horizontal range represented by the horizontal 8689 * scrollbar 8690 * 8691 * @see #computeHorizontalScrollExtent() 8692 * @see #computeHorizontalScrollOffset() 8693 * @see android.widget.ScrollBarDrawable 8694 */ 8695 protected int computeHorizontalScrollRange() { 8696 return getWidth(); 8697 } 8698 8699 /** 8700 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 8701 * within the horizontal range. This value is used to compute the position 8702 * of the thumb within the scrollbar's track.</p> 8703 * 8704 * <p>The range is expressed in arbitrary units that must be the same as the 8705 * units used by {@link #computeHorizontalScrollRange()} and 8706 * {@link #computeHorizontalScrollExtent()}.</p> 8707 * 8708 * <p>The default offset is the scroll offset of this view.</p> 8709 * 8710 * @return the horizontal offset of the scrollbar's thumb 8711 * 8712 * @see #computeHorizontalScrollRange() 8713 * @see #computeHorizontalScrollExtent() 8714 * @see android.widget.ScrollBarDrawable 8715 */ 8716 protected int computeHorizontalScrollOffset() { 8717 return mScrollX; 8718 } 8719 8720 /** 8721 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 8722 * within the horizontal range. This value is used to compute the length 8723 * of the thumb within the scrollbar's track.</p> 8724 * 8725 * <p>The range is expressed in arbitrary units that must be the same as the 8726 * units used by {@link #computeHorizontalScrollRange()} and 8727 * {@link #computeHorizontalScrollOffset()}.</p> 8728 * 8729 * <p>The default extent is the drawing width of this view.</p> 8730 * 8731 * @return the horizontal extent of the scrollbar's thumb 8732 * 8733 * @see #computeHorizontalScrollRange() 8734 * @see #computeHorizontalScrollOffset() 8735 * @see android.widget.ScrollBarDrawable 8736 */ 8737 protected int computeHorizontalScrollExtent() { 8738 return getWidth(); 8739 } 8740 8741 /** 8742 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 8743 * 8744 * <p>The range is expressed in arbitrary units that must be the same as the 8745 * units used by {@link #computeVerticalScrollExtent()} and 8746 * {@link #computeVerticalScrollOffset()}.</p> 8747 * 8748 * @return the total vertical range represented by the vertical scrollbar 8749 * 8750 * <p>The default range is the drawing height of this view.</p> 8751 * 8752 * @see #computeVerticalScrollExtent() 8753 * @see #computeVerticalScrollOffset() 8754 * @see android.widget.ScrollBarDrawable 8755 */ 8756 protected int computeVerticalScrollRange() { 8757 return getHeight(); 8758 } 8759 8760 /** 8761 * <p>Compute the vertical offset of the vertical scrollbar's thumb 8762 * within the horizontal range. This value is used to compute the position 8763 * of the thumb within the scrollbar's track.</p> 8764 * 8765 * <p>The range is expressed in arbitrary units that must be the same as the 8766 * units used by {@link #computeVerticalScrollRange()} and 8767 * {@link #computeVerticalScrollExtent()}.</p> 8768 * 8769 * <p>The default offset is the scroll offset of this view.</p> 8770 * 8771 * @return the vertical offset of the scrollbar's thumb 8772 * 8773 * @see #computeVerticalScrollRange() 8774 * @see #computeVerticalScrollExtent() 8775 * @see android.widget.ScrollBarDrawable 8776 */ 8777 protected int computeVerticalScrollOffset() { 8778 return mScrollY; 8779 } 8780 8781 /** 8782 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 8783 * within the vertical range. This value is used to compute the length 8784 * of the thumb within the scrollbar's track.</p> 8785 * 8786 * <p>The range is expressed in arbitrary units that must be the same as the 8787 * units used by {@link #computeVerticalScrollRange()} and 8788 * {@link #computeVerticalScrollOffset()}.</p> 8789 * 8790 * <p>The default extent is the drawing height of this view.</p> 8791 * 8792 * @return the vertical extent of the scrollbar's thumb 8793 * 8794 * @see #computeVerticalScrollRange() 8795 * @see #computeVerticalScrollOffset() 8796 * @see android.widget.ScrollBarDrawable 8797 */ 8798 protected int computeVerticalScrollExtent() { 8799 return getHeight(); 8800 } 8801 8802 /** 8803 * Check if this view can be scrolled horizontally in a certain direction. 8804 * 8805 * @param direction Negative to check scrolling left, positive to check scrolling right. 8806 * @return true if this view can be scrolled in the specified direction, false otherwise. 8807 */ 8808 public boolean canScrollHorizontally(int direction) { 8809 final int offset = computeHorizontalScrollOffset(); 8810 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 8811 if (range == 0) return false; 8812 if (direction < 0) { 8813 return offset > 0; 8814 } else { 8815 return offset < range - 1; 8816 } 8817 } 8818 8819 /** 8820 * Check if this view can be scrolled vertically in a certain direction. 8821 * 8822 * @param direction Negative to check scrolling up, positive to check scrolling down. 8823 * @return true if this view can be scrolled in the specified direction, false otherwise. 8824 */ 8825 public boolean canScrollVertically(int direction) { 8826 final int offset = computeVerticalScrollOffset(); 8827 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 8828 if (range == 0) return false; 8829 if (direction < 0) { 8830 return offset > 0; 8831 } else { 8832 return offset < range - 1; 8833 } 8834 } 8835 8836 /** 8837 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 8838 * scrollbars are painted only if they have been awakened first.</p> 8839 * 8840 * @param canvas the canvas on which to draw the scrollbars 8841 * 8842 * @see #awakenScrollBars(int) 8843 */ 8844 protected final void onDrawScrollBars(Canvas canvas) { 8845 // scrollbars are drawn only when the animation is running 8846 final ScrollabilityCache cache = mScrollCache; 8847 if (cache != null) { 8848 8849 int state = cache.state; 8850 8851 if (state == ScrollabilityCache.OFF) { 8852 return; 8853 } 8854 8855 boolean invalidate = false; 8856 8857 if (state == ScrollabilityCache.FADING) { 8858 // We're fading -- get our fade interpolation 8859 if (cache.interpolatorValues == null) { 8860 cache.interpolatorValues = new float[1]; 8861 } 8862 8863 float[] values = cache.interpolatorValues; 8864 8865 // Stops the animation if we're done 8866 if (cache.scrollBarInterpolator.timeToValues(values) == 8867 Interpolator.Result.FREEZE_END) { 8868 cache.state = ScrollabilityCache.OFF; 8869 } else { 8870 cache.scrollBar.setAlpha(Math.round(values[0])); 8871 } 8872 8873 // This will make the scroll bars inval themselves after 8874 // drawing. We only want this when we're fading so that 8875 // we prevent excessive redraws 8876 invalidate = true; 8877 } else { 8878 // We're just on -- but we may have been fading before so 8879 // reset alpha 8880 cache.scrollBar.setAlpha(255); 8881 } 8882 8883 8884 final int viewFlags = mViewFlags; 8885 8886 final boolean drawHorizontalScrollBar = 8887 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 8888 final boolean drawVerticalScrollBar = 8889 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 8890 && !isVerticalScrollBarHidden(); 8891 8892 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 8893 final int width = mRight - mLeft; 8894 final int height = mBottom - mTop; 8895 8896 final ScrollBarDrawable scrollBar = cache.scrollBar; 8897 8898 final int scrollX = mScrollX; 8899 final int scrollY = mScrollY; 8900 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 8901 8902 int left, top, right, bottom; 8903 8904 if (drawHorizontalScrollBar) { 8905 int size = scrollBar.getSize(false); 8906 if (size <= 0) { 8907 size = cache.scrollBarSize; 8908 } 8909 8910 scrollBar.setParameters(computeHorizontalScrollRange(), 8911 computeHorizontalScrollOffset(), 8912 computeHorizontalScrollExtent(), false); 8913 final int verticalScrollBarGap = drawVerticalScrollBar ? 8914 getVerticalScrollbarWidth() : 0; 8915 top = scrollY + height - size - (mUserPaddingBottom & inside); 8916 left = scrollX + (mPaddingLeft & inside); 8917 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 8918 bottom = top + size; 8919 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 8920 if (invalidate) { 8921 invalidate(left, top, right, bottom); 8922 } 8923 } 8924 8925 if (drawVerticalScrollBar) { 8926 int size = scrollBar.getSize(true); 8927 if (size <= 0) { 8928 size = cache.scrollBarSize; 8929 } 8930 8931 scrollBar.setParameters(computeVerticalScrollRange(), 8932 computeVerticalScrollOffset(), 8933 computeVerticalScrollExtent(), true); 8934 switch (mVerticalScrollbarPosition) { 8935 default: 8936 case SCROLLBAR_POSITION_DEFAULT: 8937 case SCROLLBAR_POSITION_RIGHT: 8938 left = scrollX + width - size - (mUserPaddingRight & inside); 8939 break; 8940 case SCROLLBAR_POSITION_LEFT: 8941 left = scrollX + (mUserPaddingLeft & inside); 8942 break; 8943 } 8944 top = scrollY + (mPaddingTop & inside); 8945 right = left + size; 8946 bottom = scrollY + height - (mUserPaddingBottom & inside); 8947 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 8948 if (invalidate) { 8949 invalidate(left, top, right, bottom); 8950 } 8951 } 8952 } 8953 } 8954 } 8955 8956 /** 8957 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 8958 * FastScroller is visible. 8959 * @return whether to temporarily hide the vertical scrollbar 8960 * @hide 8961 */ 8962 protected boolean isVerticalScrollBarHidden() { 8963 return false; 8964 } 8965 8966 /** 8967 * <p>Draw the horizontal scrollbar if 8968 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 8969 * 8970 * @param canvas the canvas on which to draw the scrollbar 8971 * @param scrollBar the scrollbar's drawable 8972 * 8973 * @see #isHorizontalScrollBarEnabled() 8974 * @see #computeHorizontalScrollRange() 8975 * @see #computeHorizontalScrollExtent() 8976 * @see #computeHorizontalScrollOffset() 8977 * @see android.widget.ScrollBarDrawable 8978 * @hide 8979 */ 8980 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 8981 int l, int t, int r, int b) { 8982 scrollBar.setBounds(l, t, r, b); 8983 scrollBar.draw(canvas); 8984 } 8985 8986 /** 8987 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 8988 * returns true.</p> 8989 * 8990 * @param canvas the canvas on which to draw the scrollbar 8991 * @param scrollBar the scrollbar's drawable 8992 * 8993 * @see #isVerticalScrollBarEnabled() 8994 * @see #computeVerticalScrollRange() 8995 * @see #computeVerticalScrollExtent() 8996 * @see #computeVerticalScrollOffset() 8997 * @see android.widget.ScrollBarDrawable 8998 * @hide 8999 */ 9000 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 9001 int l, int t, int r, int b) { 9002 scrollBar.setBounds(l, t, r, b); 9003 scrollBar.draw(canvas); 9004 } 9005 9006 /** 9007 * Implement this to do your drawing. 9008 * 9009 * @param canvas the canvas on which the background will be drawn 9010 */ 9011 protected void onDraw(Canvas canvas) { 9012 } 9013 9014 /* 9015 * Caller is responsible for calling requestLayout if necessary. 9016 * (This allows addViewInLayout to not request a new layout.) 9017 */ 9018 void assignParent(ViewParent parent) { 9019 if (mParent == null) { 9020 mParent = parent; 9021 } else if (parent == null) { 9022 mParent = null; 9023 } else { 9024 throw new RuntimeException("view " + this + " being added, but" 9025 + " it already has a parent"); 9026 } 9027 } 9028 9029 /** 9030 * This is called when the view is attached to a window. At this point it 9031 * has a Surface and will start drawing. Note that this function is 9032 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 9033 * however it may be called any time before the first onDraw -- including 9034 * before or after {@link #onMeasure(int, int)}. 9035 * 9036 * @see #onDetachedFromWindow() 9037 */ 9038 protected void onAttachedToWindow() { 9039 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 9040 mParent.requestTransparentRegion(this); 9041 } 9042 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 9043 initialAwakenScrollBars(); 9044 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH; 9045 } 9046 jumpDrawablesToCurrentState(); 9047 resolveLayoutDirectionIfNeeded(); 9048 resolvePadding(); 9049 resolveTextDirection(); 9050 if (isFocused()) { 9051 InputMethodManager imm = InputMethodManager.peekInstance(); 9052 imm.focusIn(this); 9053 } 9054 } 9055 9056 /** 9057 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 9058 * that the parent directionality can and will be resolved before its children. 9059 */ 9060 private void resolveLayoutDirectionIfNeeded() { 9061 // Do not resolve if it is not needed 9062 if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return; 9063 9064 // Clear any previous layout direction resolution 9065 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL; 9066 9067 // Set resolved depending on layout direction 9068 switch (getLayoutDirection()) { 9069 case LAYOUT_DIRECTION_INHERIT: 9070 // We cannot do the resolution if there is no parent 9071 if (mParent == null) return; 9072 9073 // If this is root view, no need to look at parent's layout dir. 9074 if (mParent instanceof ViewGroup) { 9075 ViewGroup viewGroup = ((ViewGroup) mParent); 9076 9077 // Check if the parent view group can resolve 9078 if (! viewGroup.canResolveLayoutDirection()) { 9079 return; 9080 } 9081 if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 9082 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9083 } 9084 } 9085 break; 9086 case LAYOUT_DIRECTION_RTL: 9087 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9088 break; 9089 case LAYOUT_DIRECTION_LOCALE: 9090 if(isLayoutDirectionRtl(Locale.getDefault())) { 9091 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9092 } 9093 break; 9094 default: 9095 // Nothing to do, LTR by default 9096 } 9097 9098 // Set to resolved 9099 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED; 9100 } 9101 9102 /** 9103 * @hide 9104 */ 9105 protected void resolvePadding() { 9106 // If the user specified the absolute padding (either with android:padding or 9107 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 9108 // use the default padding or the padding from the background drawable 9109 // (stored at this point in mPadding*) 9110 switch (getResolvedLayoutDirection()) { 9111 case LAYOUT_DIRECTION_RTL: 9112 // Start user padding override Right user padding. Otherwise, if Right user 9113 // padding is not defined, use the default Right padding. If Right user padding 9114 // is defined, just use it. 9115 if (mUserPaddingStart >= 0) { 9116 mUserPaddingRight = mUserPaddingStart; 9117 } else if (mUserPaddingRight < 0) { 9118 mUserPaddingRight = mPaddingRight; 9119 } 9120 if (mUserPaddingEnd >= 0) { 9121 mUserPaddingLeft = mUserPaddingEnd; 9122 } else if (mUserPaddingLeft < 0) { 9123 mUserPaddingLeft = mPaddingLeft; 9124 } 9125 break; 9126 case LAYOUT_DIRECTION_LTR: 9127 default: 9128 // Start user padding override Left user padding. Otherwise, if Left user 9129 // padding is not defined, use the default left padding. If Left user padding 9130 // is defined, just use it. 9131 if (mUserPaddingStart >= 0) { 9132 mUserPaddingLeft = mUserPaddingStart; 9133 } else if (mUserPaddingLeft < 0) { 9134 mUserPaddingLeft = mPaddingLeft; 9135 } 9136 if (mUserPaddingEnd >= 0) { 9137 mUserPaddingRight = mUserPaddingEnd; 9138 } else if (mUserPaddingRight < 0) { 9139 mUserPaddingRight = mPaddingRight; 9140 } 9141 } 9142 9143 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 9144 9145 recomputePadding(); 9146 } 9147 9148 protected boolean canResolveLayoutDirection() { 9149 switch (getLayoutDirection()) { 9150 case LAYOUT_DIRECTION_INHERIT: 9151 return (mParent != null); 9152 default: 9153 return true; 9154 } 9155 } 9156 9157 /** 9158 * Reset the resolved layout direction. 9159 * 9160 * Subclasses need to override this method to clear cached information that depends on the 9161 * resolved layout direction, or to inform child views that inherit their layout direction. 9162 * Overrides must also call the superclass implementation at the start of their implementation. 9163 * 9164 * @hide 9165 */ 9166 protected void resetResolvedLayoutDirection() { 9167 // Reset the current View resolution 9168 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED; 9169 } 9170 9171 /** 9172 * Check if a Locale is corresponding to a RTL script. 9173 * 9174 * @param locale Locale to check 9175 * @return true if a Locale is corresponding to a RTL script. 9176 */ 9177 protected static boolean isLayoutDirectionRtl(Locale locale) { 9178 return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE == 9179 LocaleUtil.getLayoutDirectionFromLocale(locale)); 9180 } 9181 9182 /** 9183 * This is called when the view is detached from a window. At this point it 9184 * no longer has a surface for drawing. 9185 * 9186 * @see #onAttachedToWindow() 9187 */ 9188 protected void onDetachedFromWindow() { 9189 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 9190 9191 removeUnsetPressCallback(); 9192 removeLongPressCallback(); 9193 removePerformClickCallback(); 9194 removeSendViewScrolledAccessibilityEventCallback(); 9195 9196 destroyDrawingCache(); 9197 9198 if (mHardwareLayer != null) { 9199 mHardwareLayer.destroy(); 9200 mHardwareLayer = null; 9201 } 9202 9203 if (mDisplayList != null) { 9204 mDisplayList.invalidate(); 9205 } 9206 9207 if (mAttachInfo != null) { 9208 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this); 9209 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_RECT_MSG, this); 9210 } 9211 9212 mCurrentAnimation = null; 9213 9214 resetResolvedLayoutDirection(); 9215 resetResolvedTextDirection(); 9216 } 9217 9218 /** 9219 * @return The number of times this view has been attached to a window 9220 */ 9221 protected int getWindowAttachCount() { 9222 return mWindowAttachCount; 9223 } 9224 9225 /** 9226 * Retrieve a unique token identifying the window this view is attached to. 9227 * @return Return the window's token for use in 9228 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 9229 */ 9230 public IBinder getWindowToken() { 9231 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 9232 } 9233 9234 /** 9235 * Retrieve a unique token identifying the top-level "real" window of 9236 * the window that this view is attached to. That is, this is like 9237 * {@link #getWindowToken}, except if the window this view in is a panel 9238 * window (attached to another containing window), then the token of 9239 * the containing window is returned instead. 9240 * 9241 * @return Returns the associated window token, either 9242 * {@link #getWindowToken()} or the containing window's token. 9243 */ 9244 public IBinder getApplicationWindowToken() { 9245 AttachInfo ai = mAttachInfo; 9246 if (ai != null) { 9247 IBinder appWindowToken = ai.mPanelParentWindowToken; 9248 if (appWindowToken == null) { 9249 appWindowToken = ai.mWindowToken; 9250 } 9251 return appWindowToken; 9252 } 9253 return null; 9254 } 9255 9256 /** 9257 * Retrieve private session object this view hierarchy is using to 9258 * communicate with the window manager. 9259 * @return the session object to communicate with the window manager 9260 */ 9261 /*package*/ IWindowSession getWindowSession() { 9262 return mAttachInfo != null ? mAttachInfo.mSession : null; 9263 } 9264 9265 /** 9266 * @param info the {@link android.view.View.AttachInfo} to associated with 9267 * this view 9268 */ 9269 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 9270 //System.out.println("Attached! " + this); 9271 mAttachInfo = info; 9272 mWindowAttachCount++; 9273 // We will need to evaluate the drawable state at least once. 9274 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 9275 if (mFloatingTreeObserver != null) { 9276 info.mTreeObserver.merge(mFloatingTreeObserver); 9277 mFloatingTreeObserver = null; 9278 } 9279 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 9280 mAttachInfo.mScrollContainers.add(this); 9281 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 9282 } 9283 performCollectViewAttributes(visibility); 9284 onAttachedToWindow(); 9285 9286 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9287 mOnAttachStateChangeListeners; 9288 if (listeners != null && listeners.size() > 0) { 9289 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9290 // perform the dispatching. The iterator is a safe guard against listeners that 9291 // could mutate the list by calling the various add/remove methods. This prevents 9292 // the array from being modified while we iterate it. 9293 for (OnAttachStateChangeListener listener : listeners) { 9294 listener.onViewAttachedToWindow(this); 9295 } 9296 } 9297 9298 int vis = info.mWindowVisibility; 9299 if (vis != GONE) { 9300 onWindowVisibilityChanged(vis); 9301 } 9302 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 9303 // If nobody has evaluated the drawable state yet, then do it now. 9304 refreshDrawableState(); 9305 } 9306 } 9307 9308 void dispatchDetachedFromWindow() { 9309 AttachInfo info = mAttachInfo; 9310 if (info != null) { 9311 int vis = info.mWindowVisibility; 9312 if (vis != GONE) { 9313 onWindowVisibilityChanged(GONE); 9314 } 9315 } 9316 9317 onDetachedFromWindow(); 9318 9319 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9320 mOnAttachStateChangeListeners; 9321 if (listeners != null && listeners.size() > 0) { 9322 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9323 // perform the dispatching. The iterator is a safe guard against listeners that 9324 // could mutate the list by calling the various add/remove methods. This prevents 9325 // the array from being modified while we iterate it. 9326 for (OnAttachStateChangeListener listener : listeners) { 9327 listener.onViewDetachedFromWindow(this); 9328 } 9329 } 9330 9331 if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) { 9332 mAttachInfo.mScrollContainers.remove(this); 9333 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 9334 } 9335 9336 mAttachInfo = null; 9337 } 9338 9339 /** 9340 * Store this view hierarchy's frozen state into the given container. 9341 * 9342 * @param container The SparseArray in which to save the view's state. 9343 * 9344 * @see #restoreHierarchyState(android.util.SparseArray) 9345 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9346 * @see #onSaveInstanceState() 9347 */ 9348 public void saveHierarchyState(SparseArray<Parcelable> container) { 9349 dispatchSaveInstanceState(container); 9350 } 9351 9352 /** 9353 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 9354 * this view and its children. May be overridden to modify how freezing happens to a 9355 * view's children; for example, some views may want to not store state for their children. 9356 * 9357 * @param container The SparseArray in which to save the view's state. 9358 * 9359 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9360 * @see #saveHierarchyState(android.util.SparseArray) 9361 * @see #onSaveInstanceState() 9362 */ 9363 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 9364 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 9365 mPrivateFlags &= ~SAVE_STATE_CALLED; 9366 Parcelable state = onSaveInstanceState(); 9367 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9368 throw new IllegalStateException( 9369 "Derived class did not call super.onSaveInstanceState()"); 9370 } 9371 if (state != null) { 9372 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 9373 // + ": " + state); 9374 container.put(mID, state); 9375 } 9376 } 9377 } 9378 9379 /** 9380 * Hook allowing a view to generate a representation of its internal state 9381 * that can later be used to create a new instance with that same state. 9382 * This state should only contain information that is not persistent or can 9383 * not be reconstructed later. For example, you will never store your 9384 * current position on screen because that will be computed again when a 9385 * new instance of the view is placed in its view hierarchy. 9386 * <p> 9387 * Some examples of things you may store here: the current cursor position 9388 * in a text view (but usually not the text itself since that is stored in a 9389 * content provider or other persistent storage), the currently selected 9390 * item in a list view. 9391 * 9392 * @return Returns a Parcelable object containing the view's current dynamic 9393 * state, or null if there is nothing interesting to save. The 9394 * default implementation returns null. 9395 * @see #onRestoreInstanceState(android.os.Parcelable) 9396 * @see #saveHierarchyState(android.util.SparseArray) 9397 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9398 * @see #setSaveEnabled(boolean) 9399 */ 9400 protected Parcelable onSaveInstanceState() { 9401 mPrivateFlags |= SAVE_STATE_CALLED; 9402 return BaseSavedState.EMPTY_STATE; 9403 } 9404 9405 /** 9406 * Restore this view hierarchy's frozen state from the given container. 9407 * 9408 * @param container The SparseArray which holds previously frozen states. 9409 * 9410 * @see #saveHierarchyState(android.util.SparseArray) 9411 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9412 * @see #onRestoreInstanceState(android.os.Parcelable) 9413 */ 9414 public void restoreHierarchyState(SparseArray<Parcelable> container) { 9415 dispatchRestoreInstanceState(container); 9416 } 9417 9418 /** 9419 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 9420 * state for this view and its children. May be overridden to modify how restoring 9421 * happens to a view's children; for example, some views may want to not store state 9422 * for their children. 9423 * 9424 * @param container The SparseArray which holds previously saved state. 9425 * 9426 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9427 * @see #restoreHierarchyState(android.util.SparseArray) 9428 * @see #onRestoreInstanceState(android.os.Parcelable) 9429 */ 9430 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 9431 if (mID != NO_ID) { 9432 Parcelable state = container.get(mID); 9433 if (state != null) { 9434 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 9435 // + ": " + state); 9436 mPrivateFlags &= ~SAVE_STATE_CALLED; 9437 onRestoreInstanceState(state); 9438 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9439 throw new IllegalStateException( 9440 "Derived class did not call super.onRestoreInstanceState()"); 9441 } 9442 } 9443 } 9444 } 9445 9446 /** 9447 * Hook allowing a view to re-apply a representation of its internal state that had previously 9448 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 9449 * null state. 9450 * 9451 * @param state The frozen state that had previously been returned by 9452 * {@link #onSaveInstanceState}. 9453 * 9454 * @see #onSaveInstanceState() 9455 * @see #restoreHierarchyState(android.util.SparseArray) 9456 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9457 */ 9458 protected void onRestoreInstanceState(Parcelable state) { 9459 mPrivateFlags |= SAVE_STATE_CALLED; 9460 if (state != BaseSavedState.EMPTY_STATE && state != null) { 9461 throw new IllegalArgumentException("Wrong state class, expecting View State but " 9462 + "received " + state.getClass().toString() + " instead. This usually happens " 9463 + "when two views of different type have the same id in the same hierarchy. " 9464 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 9465 + "other views do not use the same id."); 9466 } 9467 } 9468 9469 /** 9470 * <p>Return the time at which the drawing of the view hierarchy started.</p> 9471 * 9472 * @return the drawing start time in milliseconds 9473 */ 9474 public long getDrawingTime() { 9475 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 9476 } 9477 9478 /** 9479 * <p>Enables or disables the duplication of the parent's state into this view. When 9480 * duplication is enabled, this view gets its drawable state from its parent rather 9481 * than from its own internal properties.</p> 9482 * 9483 * <p>Note: in the current implementation, setting this property to true after the 9484 * view was added to a ViewGroup might have no effect at all. This property should 9485 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 9486 * 9487 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 9488 * property is enabled, an exception will be thrown.</p> 9489 * 9490 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 9491 * parent, these states should not be affected by this method.</p> 9492 * 9493 * @param enabled True to enable duplication of the parent's drawable state, false 9494 * to disable it. 9495 * 9496 * @see #getDrawableState() 9497 * @see #isDuplicateParentStateEnabled() 9498 */ 9499 public void setDuplicateParentStateEnabled(boolean enabled) { 9500 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 9501 } 9502 9503 /** 9504 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 9505 * 9506 * @return True if this view's drawable state is duplicated from the parent, 9507 * false otherwise 9508 * 9509 * @see #getDrawableState() 9510 * @see #setDuplicateParentStateEnabled(boolean) 9511 */ 9512 public boolean isDuplicateParentStateEnabled() { 9513 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 9514 } 9515 9516 /** 9517 * <p>Specifies the type of layer backing this view. The layer can be 9518 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 9519 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 9520 * 9521 * <p>A layer is associated with an optional {@link android.graphics.Paint} 9522 * instance that controls how the layer is composed on screen. The following 9523 * properties of the paint are taken into account when composing the layer:</p> 9524 * <ul> 9525 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 9526 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 9527 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 9528 * </ul> 9529 * 9530 * <p>If this view has an alpha value set to < 1.0 by calling 9531 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 9532 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 9533 * equivalent to setting a hardware layer on this view and providing a paint with 9534 * the desired alpha value.<p> 9535 * 9536 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 9537 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 9538 * for more information on when and how to use layers.</p> 9539 * 9540 * @param layerType The ype of layer to use with this view, must be one of 9541 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 9542 * {@link #LAYER_TYPE_HARDWARE} 9543 * @param paint The paint used to compose the layer. This argument is optional 9544 * and can be null. It is ignored when the layer type is 9545 * {@link #LAYER_TYPE_NONE} 9546 * 9547 * @see #getLayerType() 9548 * @see #LAYER_TYPE_NONE 9549 * @see #LAYER_TYPE_SOFTWARE 9550 * @see #LAYER_TYPE_HARDWARE 9551 * @see #setAlpha(float) 9552 * 9553 * @attr ref android.R.styleable#View_layerType 9554 */ 9555 public void setLayerType(int layerType, Paint paint) { 9556 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 9557 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 9558 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 9559 } 9560 9561 if (layerType == mLayerType) { 9562 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 9563 mLayerPaint = paint == null ? new Paint() : paint; 9564 invalidateParentCaches(); 9565 invalidate(true); 9566 } 9567 return; 9568 } 9569 9570 // Destroy any previous software drawing cache if needed 9571 switch (mLayerType) { 9572 case LAYER_TYPE_HARDWARE: 9573 if (mHardwareLayer != null) { 9574 mHardwareLayer.destroy(); 9575 mHardwareLayer = null; 9576 } 9577 // fall through - unaccelerated views may use software layer mechanism instead 9578 case LAYER_TYPE_SOFTWARE: 9579 if (mDrawingCache != null) { 9580 mDrawingCache.recycle(); 9581 mDrawingCache = null; 9582 } 9583 9584 if (mUnscaledDrawingCache != null) { 9585 mUnscaledDrawingCache.recycle(); 9586 mUnscaledDrawingCache = null; 9587 } 9588 break; 9589 default: 9590 break; 9591 } 9592 9593 mLayerType = layerType; 9594 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 9595 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 9596 mLocalDirtyRect = layerDisabled ? null : new Rect(); 9597 9598 invalidateParentCaches(); 9599 invalidate(true); 9600 } 9601 9602 /** 9603 * Indicates what type of layer is currently associated with this view. By default 9604 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 9605 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 9606 * for more information on the different types of layers. 9607 * 9608 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 9609 * {@link #LAYER_TYPE_HARDWARE} 9610 * 9611 * @see #setLayerType(int, android.graphics.Paint) 9612 * @see #buildLayer() 9613 * @see #LAYER_TYPE_NONE 9614 * @see #LAYER_TYPE_SOFTWARE 9615 * @see #LAYER_TYPE_HARDWARE 9616 */ 9617 public int getLayerType() { 9618 return mLayerType; 9619 } 9620 9621 /** 9622 * Forces this view's layer to be created and this view to be rendered 9623 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 9624 * invoking this method will have no effect. 9625 * 9626 * This method can for instance be used to render a view into its layer before 9627 * starting an animation. If this view is complex, rendering into the layer 9628 * before starting the animation will avoid skipping frames. 9629 * 9630 * @throws IllegalStateException If this view is not attached to a window 9631 * 9632 * @see #setLayerType(int, android.graphics.Paint) 9633 */ 9634 public void buildLayer() { 9635 if (mLayerType == LAYER_TYPE_NONE) return; 9636 9637 if (mAttachInfo == null) { 9638 throw new IllegalStateException("This view must be attached to a window first"); 9639 } 9640 9641 switch (mLayerType) { 9642 case LAYER_TYPE_HARDWARE: 9643 getHardwareLayer(); 9644 break; 9645 case LAYER_TYPE_SOFTWARE: 9646 buildDrawingCache(true); 9647 break; 9648 } 9649 } 9650 9651 /** 9652 * <p>Returns a hardware layer that can be used to draw this view again 9653 * without executing its draw method.</p> 9654 * 9655 * @return A HardwareLayer ready to render, or null if an error occurred. 9656 */ 9657 HardwareLayer getHardwareLayer() { 9658 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) { 9659 return null; 9660 } 9661 9662 final int width = mRight - mLeft; 9663 final int height = mBottom - mTop; 9664 9665 if (width == 0 || height == 0) { 9666 return null; 9667 } 9668 9669 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 9670 if (mHardwareLayer == null) { 9671 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 9672 width, height, isOpaque()); 9673 mLocalDirtyRect.setEmpty(); 9674 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 9675 mHardwareLayer.resize(width, height); 9676 mLocalDirtyRect.setEmpty(); 9677 } 9678 9679 HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas; 9680 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas); 9681 mAttachInfo.mHardwareCanvas = canvas; 9682 try { 9683 canvas.setViewport(width, height); 9684 canvas.onPreDraw(mLocalDirtyRect); 9685 mLocalDirtyRect.setEmpty(); 9686 9687 final int restoreCount = canvas.save(); 9688 9689 computeScroll(); 9690 canvas.translate(-mScrollX, -mScrollY); 9691 9692 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9693 9694 // Fast path for layouts with no backgrounds 9695 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 9696 mPrivateFlags &= ~DIRTY_MASK; 9697 dispatchDraw(canvas); 9698 } else { 9699 draw(canvas); 9700 } 9701 9702 canvas.restoreToCount(restoreCount); 9703 } finally { 9704 canvas.onPostDraw(); 9705 mHardwareLayer.end(currentCanvas); 9706 mAttachInfo.mHardwareCanvas = currentCanvas; 9707 } 9708 } 9709 9710 return mHardwareLayer; 9711 } 9712 9713 /** 9714 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 9715 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 9716 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 9717 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 9718 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 9719 * null.</p> 9720 * 9721 * <p>Enabling the drawing cache is similar to 9722 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 9723 * acceleration is turned off. When hardware acceleration is turned on, enabling the 9724 * drawing cache has no effect on rendering because the system uses a different mechanism 9725 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 9726 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 9727 * for information on how to enable software and hardware layers.</p> 9728 * 9729 * <p>This API can be used to manually generate 9730 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 9731 * {@link #getDrawingCache()}.</p> 9732 * 9733 * @param enabled true to enable the drawing cache, false otherwise 9734 * 9735 * @see #isDrawingCacheEnabled() 9736 * @see #getDrawingCache() 9737 * @see #buildDrawingCache() 9738 * @see #setLayerType(int, android.graphics.Paint) 9739 */ 9740 public void setDrawingCacheEnabled(boolean enabled) { 9741 mCachingFailed = false; 9742 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 9743 } 9744 9745 /** 9746 * <p>Indicates whether the drawing cache is enabled for this view.</p> 9747 * 9748 * @return true if the drawing cache is enabled 9749 * 9750 * @see #setDrawingCacheEnabled(boolean) 9751 * @see #getDrawingCache() 9752 */ 9753 @ViewDebug.ExportedProperty(category = "drawing") 9754 public boolean isDrawingCacheEnabled() { 9755 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 9756 } 9757 9758 /** 9759 * Debugging utility which recursively outputs the dirty state of a view and its 9760 * descendants. 9761 * 9762 * @hide 9763 */ 9764 @SuppressWarnings({"UnusedDeclaration"}) 9765 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 9766 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) + 9767 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" + 9768 (mPrivateFlags & View.DRAWING_CACHE_VALID) + 9769 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")"); 9770 if (clear) { 9771 mPrivateFlags &= clearMask; 9772 } 9773 if (this instanceof ViewGroup) { 9774 ViewGroup parent = (ViewGroup) this; 9775 final int count = parent.getChildCount(); 9776 for (int i = 0; i < count; i++) { 9777 final View child = parent.getChildAt(i); 9778 child.outputDirtyFlags(indent + " ", clear, clearMask); 9779 } 9780 } 9781 } 9782 9783 /** 9784 * This method is used by ViewGroup to cause its children to restore or recreate their 9785 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 9786 * to recreate its own display list, which would happen if it went through the normal 9787 * draw/dispatchDraw mechanisms. 9788 * 9789 * @hide 9790 */ 9791 protected void dispatchGetDisplayList() {} 9792 9793 /** 9794 * A view that is not attached or hardware accelerated cannot create a display list. 9795 * This method checks these conditions and returns the appropriate result. 9796 * 9797 * @return true if view has the ability to create a display list, false otherwise. 9798 * 9799 * @hide 9800 */ 9801 public boolean canHaveDisplayList() { 9802 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 9803 } 9804 9805 /** 9806 * <p>Returns a display list that can be used to draw this view again 9807 * without executing its draw method.</p> 9808 * 9809 * @return A DisplayList ready to replay, or null if caching is not enabled. 9810 * 9811 * @hide 9812 */ 9813 public DisplayList getDisplayList() { 9814 if (!canHaveDisplayList()) { 9815 return null; 9816 } 9817 9818 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || 9819 mDisplayList == null || !mDisplayList.isValid() || 9820 mRecreateDisplayList)) { 9821 // Don't need to recreate the display list, just need to tell our 9822 // children to restore/recreate theirs 9823 if (mDisplayList != null && mDisplayList.isValid() && 9824 !mRecreateDisplayList) { 9825 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9826 mPrivateFlags &= ~DIRTY_MASK; 9827 dispatchGetDisplayList(); 9828 9829 return mDisplayList; 9830 } 9831 9832 // If we got here, we're recreating it. Mark it as such to ensure that 9833 // we copy in child display lists into ours in drawChild() 9834 mRecreateDisplayList = true; 9835 if (mDisplayList == null) { 9836 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(this); 9837 // If we're creating a new display list, make sure our parent gets invalidated 9838 // since they will need to recreate their display list to account for this 9839 // new child display list. 9840 invalidateParentCaches(); 9841 } 9842 9843 final HardwareCanvas canvas = mDisplayList.start(); 9844 try { 9845 int width = mRight - mLeft; 9846 int height = mBottom - mTop; 9847 9848 canvas.setViewport(width, height); 9849 // The dirty rect should always be null for a display list 9850 canvas.onPreDraw(null); 9851 9852 final int restoreCount = canvas.save(); 9853 9854 computeScroll(); 9855 canvas.translate(-mScrollX, -mScrollY); 9856 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9857 mPrivateFlags &= ~DIRTY_MASK; 9858 9859 // Fast path for layouts with no backgrounds 9860 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 9861 dispatchDraw(canvas); 9862 } else { 9863 draw(canvas); 9864 } 9865 9866 canvas.restoreToCount(restoreCount); 9867 } finally { 9868 canvas.onPostDraw(); 9869 9870 mDisplayList.end(); 9871 } 9872 } else { 9873 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9874 mPrivateFlags &= ~DIRTY_MASK; 9875 } 9876 9877 return mDisplayList; 9878 } 9879 9880 /** 9881 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 9882 * 9883 * @return A non-scaled bitmap representing this view or null if cache is disabled. 9884 * 9885 * @see #getDrawingCache(boolean) 9886 */ 9887 public Bitmap getDrawingCache() { 9888 return getDrawingCache(false); 9889 } 9890 9891 /** 9892 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 9893 * is null when caching is disabled. If caching is enabled and the cache is not ready, 9894 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 9895 * draw from the cache when the cache is enabled. To benefit from the cache, you must 9896 * request the drawing cache by calling this method and draw it on screen if the 9897 * returned bitmap is not null.</p> 9898 * 9899 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 9900 * this method will create a bitmap of the same size as this view. Because this bitmap 9901 * will be drawn scaled by the parent ViewGroup, the result on screen might show 9902 * scaling artifacts. To avoid such artifacts, you should call this method by setting 9903 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 9904 * size than the view. This implies that your application must be able to handle this 9905 * size.</p> 9906 * 9907 * @param autoScale Indicates whether the generated bitmap should be scaled based on 9908 * the current density of the screen when the application is in compatibility 9909 * mode. 9910 * 9911 * @return A bitmap representing this view or null if cache is disabled. 9912 * 9913 * @see #setDrawingCacheEnabled(boolean) 9914 * @see #isDrawingCacheEnabled() 9915 * @see #buildDrawingCache(boolean) 9916 * @see #destroyDrawingCache() 9917 */ 9918 public Bitmap getDrawingCache(boolean autoScale) { 9919 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 9920 return null; 9921 } 9922 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 9923 buildDrawingCache(autoScale); 9924 } 9925 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 9926 } 9927 9928 /** 9929 * <p>Frees the resources used by the drawing cache. If you call 9930 * {@link #buildDrawingCache()} manually without calling 9931 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 9932 * should cleanup the cache with this method afterwards.</p> 9933 * 9934 * @see #setDrawingCacheEnabled(boolean) 9935 * @see #buildDrawingCache() 9936 * @see #getDrawingCache() 9937 */ 9938 public void destroyDrawingCache() { 9939 if (mDrawingCache != null) { 9940 mDrawingCache.recycle(); 9941 mDrawingCache = null; 9942 } 9943 if (mUnscaledDrawingCache != null) { 9944 mUnscaledDrawingCache.recycle(); 9945 mUnscaledDrawingCache = null; 9946 } 9947 } 9948 9949 /** 9950 * Setting a solid background color for the drawing cache's bitmaps will improve 9951 * perfromance and memory usage. Note, though that this should only be used if this 9952 * view will always be drawn on top of a solid color. 9953 * 9954 * @param color The background color to use for the drawing cache's bitmap 9955 * 9956 * @see #setDrawingCacheEnabled(boolean) 9957 * @see #buildDrawingCache() 9958 * @see #getDrawingCache() 9959 */ 9960 public void setDrawingCacheBackgroundColor(int color) { 9961 if (color != mDrawingCacheBackgroundColor) { 9962 mDrawingCacheBackgroundColor = color; 9963 mPrivateFlags &= ~DRAWING_CACHE_VALID; 9964 } 9965 } 9966 9967 /** 9968 * @see #setDrawingCacheBackgroundColor(int) 9969 * 9970 * @return The background color to used for the drawing cache's bitmap 9971 */ 9972 public int getDrawingCacheBackgroundColor() { 9973 return mDrawingCacheBackgroundColor; 9974 } 9975 9976 /** 9977 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 9978 * 9979 * @see #buildDrawingCache(boolean) 9980 */ 9981 public void buildDrawingCache() { 9982 buildDrawingCache(false); 9983 } 9984 9985 /** 9986 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 9987 * 9988 * <p>If you call {@link #buildDrawingCache()} manually without calling 9989 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 9990 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 9991 * 9992 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 9993 * this method will create a bitmap of the same size as this view. Because this bitmap 9994 * will be drawn scaled by the parent ViewGroup, the result on screen might show 9995 * scaling artifacts. To avoid such artifacts, you should call this method by setting 9996 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 9997 * size than the view. This implies that your application must be able to handle this 9998 * size.</p> 9999 * 10000 * <p>You should avoid calling this method when hardware acceleration is enabled. If 10001 * you do not need the drawing cache bitmap, calling this method will increase memory 10002 * usage and cause the view to be rendered in software once, thus negatively impacting 10003 * performance.</p> 10004 * 10005 * @see #getDrawingCache() 10006 * @see #destroyDrawingCache() 10007 */ 10008 public void buildDrawingCache(boolean autoScale) { 10009 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 10010 mDrawingCache == null : mUnscaledDrawingCache == null)) { 10011 mCachingFailed = false; 10012 10013 if (ViewDebug.TRACE_HIERARCHY) { 10014 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 10015 } 10016 10017 int width = mRight - mLeft; 10018 int height = mBottom - mTop; 10019 10020 final AttachInfo attachInfo = mAttachInfo; 10021 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 10022 10023 if (autoScale && scalingRequired) { 10024 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 10025 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 10026 } 10027 10028 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 10029 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 10030 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 10031 10032 if (width <= 0 || height <= 0 || 10033 // Projected bitmap size in bytes 10034 (width * height * (opaque && !use32BitCache ? 2 : 4) > 10035 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 10036 destroyDrawingCache(); 10037 mCachingFailed = true; 10038 return; 10039 } 10040 10041 boolean clear = true; 10042 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 10043 10044 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 10045 Bitmap.Config quality; 10046 if (!opaque) { 10047 // Never pick ARGB_4444 because it looks awful 10048 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 10049 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 10050 case DRAWING_CACHE_QUALITY_AUTO: 10051 quality = Bitmap.Config.ARGB_8888; 10052 break; 10053 case DRAWING_CACHE_QUALITY_LOW: 10054 quality = Bitmap.Config.ARGB_8888; 10055 break; 10056 case DRAWING_CACHE_QUALITY_HIGH: 10057 quality = Bitmap.Config.ARGB_8888; 10058 break; 10059 default: 10060 quality = Bitmap.Config.ARGB_8888; 10061 break; 10062 } 10063 } else { 10064 // Optimization for translucent windows 10065 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 10066 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 10067 } 10068 10069 // Try to cleanup memory 10070 if (bitmap != null) bitmap.recycle(); 10071 10072 try { 10073 bitmap = Bitmap.createBitmap(width, height, quality); 10074 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 10075 if (autoScale) { 10076 mDrawingCache = bitmap; 10077 } else { 10078 mUnscaledDrawingCache = bitmap; 10079 } 10080 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 10081 } catch (OutOfMemoryError e) { 10082 // If there is not enough memory to create the bitmap cache, just 10083 // ignore the issue as bitmap caches are not required to draw the 10084 // view hierarchy 10085 if (autoScale) { 10086 mDrawingCache = null; 10087 } else { 10088 mUnscaledDrawingCache = null; 10089 } 10090 mCachingFailed = true; 10091 return; 10092 } 10093 10094 clear = drawingCacheBackgroundColor != 0; 10095 } 10096 10097 Canvas canvas; 10098 if (attachInfo != null) { 10099 canvas = attachInfo.mCanvas; 10100 if (canvas == null) { 10101 canvas = new Canvas(); 10102 } 10103 canvas.setBitmap(bitmap); 10104 // Temporarily clobber the cached Canvas in case one of our children 10105 // is also using a drawing cache. Without this, the children would 10106 // steal the canvas by attaching their own bitmap to it and bad, bad 10107 // thing would happen (invisible views, corrupted drawings, etc.) 10108 attachInfo.mCanvas = null; 10109 } else { 10110 // This case should hopefully never or seldom happen 10111 canvas = new Canvas(bitmap); 10112 } 10113 10114 if (clear) { 10115 bitmap.eraseColor(drawingCacheBackgroundColor); 10116 } 10117 10118 computeScroll(); 10119 final int restoreCount = canvas.save(); 10120 10121 if (autoScale && scalingRequired) { 10122 final float scale = attachInfo.mApplicationScale; 10123 canvas.scale(scale, scale); 10124 } 10125 10126 canvas.translate(-mScrollX, -mScrollY); 10127 10128 mPrivateFlags |= DRAWN; 10129 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 10130 mLayerType != LAYER_TYPE_NONE) { 10131 mPrivateFlags |= DRAWING_CACHE_VALID; 10132 } 10133 10134 // Fast path for layouts with no backgrounds 10135 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10136 if (ViewDebug.TRACE_HIERARCHY) { 10137 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 10138 } 10139 mPrivateFlags &= ~DIRTY_MASK; 10140 dispatchDraw(canvas); 10141 } else { 10142 draw(canvas); 10143 } 10144 10145 canvas.restoreToCount(restoreCount); 10146 10147 if (attachInfo != null) { 10148 // Restore the cached Canvas for our siblings 10149 attachInfo.mCanvas = canvas; 10150 } 10151 } 10152 } 10153 10154 /** 10155 * Create a snapshot of the view into a bitmap. We should probably make 10156 * some form of this public, but should think about the API. 10157 */ 10158 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 10159 int width = mRight - mLeft; 10160 int height = mBottom - mTop; 10161 10162 final AttachInfo attachInfo = mAttachInfo; 10163 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 10164 width = (int) ((width * scale) + 0.5f); 10165 height = (int) ((height * scale) + 0.5f); 10166 10167 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 10168 if (bitmap == null) { 10169 throw new OutOfMemoryError(); 10170 } 10171 10172 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 10173 10174 Canvas canvas; 10175 if (attachInfo != null) { 10176 canvas = attachInfo.mCanvas; 10177 if (canvas == null) { 10178 canvas = new Canvas(); 10179 } 10180 canvas.setBitmap(bitmap); 10181 // Temporarily clobber the cached Canvas in case one of our children 10182 // is also using a drawing cache. Without this, the children would 10183 // steal the canvas by attaching their own bitmap to it and bad, bad 10184 // things would happen (invisible views, corrupted drawings, etc.) 10185 attachInfo.mCanvas = null; 10186 } else { 10187 // This case should hopefully never or seldom happen 10188 canvas = new Canvas(bitmap); 10189 } 10190 10191 if ((backgroundColor & 0xff000000) != 0) { 10192 bitmap.eraseColor(backgroundColor); 10193 } 10194 10195 computeScroll(); 10196 final int restoreCount = canvas.save(); 10197 canvas.scale(scale, scale); 10198 canvas.translate(-mScrollX, -mScrollY); 10199 10200 // Temporarily remove the dirty mask 10201 int flags = mPrivateFlags; 10202 mPrivateFlags &= ~DIRTY_MASK; 10203 10204 // Fast path for layouts with no backgrounds 10205 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10206 dispatchDraw(canvas); 10207 } else { 10208 draw(canvas); 10209 } 10210 10211 mPrivateFlags = flags; 10212 10213 canvas.restoreToCount(restoreCount); 10214 10215 if (attachInfo != null) { 10216 // Restore the cached Canvas for our siblings 10217 attachInfo.mCanvas = canvas; 10218 } 10219 10220 return bitmap; 10221 } 10222 10223 /** 10224 * Indicates whether this View is currently in edit mode. A View is usually 10225 * in edit mode when displayed within a developer tool. For instance, if 10226 * this View is being drawn by a visual user interface builder, this method 10227 * should return true. 10228 * 10229 * Subclasses should check the return value of this method to provide 10230 * different behaviors if their normal behavior might interfere with the 10231 * host environment. For instance: the class spawns a thread in its 10232 * constructor, the drawing code relies on device-specific features, etc. 10233 * 10234 * This method is usually checked in the drawing code of custom widgets. 10235 * 10236 * @return True if this View is in edit mode, false otherwise. 10237 */ 10238 public boolean isInEditMode() { 10239 return false; 10240 } 10241 10242 /** 10243 * If the View draws content inside its padding and enables fading edges, 10244 * it needs to support padding offsets. Padding offsets are added to the 10245 * fading edges to extend the length of the fade so that it covers pixels 10246 * drawn inside the padding. 10247 * 10248 * Subclasses of this class should override this method if they need 10249 * to draw content inside the padding. 10250 * 10251 * @return True if padding offset must be applied, false otherwise. 10252 * 10253 * @see #getLeftPaddingOffset() 10254 * @see #getRightPaddingOffset() 10255 * @see #getTopPaddingOffset() 10256 * @see #getBottomPaddingOffset() 10257 * 10258 * @since CURRENT 10259 */ 10260 protected boolean isPaddingOffsetRequired() { 10261 return false; 10262 } 10263 10264 /** 10265 * Amount by which to extend the left fading region. Called only when 10266 * {@link #isPaddingOffsetRequired()} returns true. 10267 * 10268 * @return The left padding offset in pixels. 10269 * 10270 * @see #isPaddingOffsetRequired() 10271 * 10272 * @since CURRENT 10273 */ 10274 protected int getLeftPaddingOffset() { 10275 return 0; 10276 } 10277 10278 /** 10279 * Amount by which to extend the right fading region. Called only when 10280 * {@link #isPaddingOffsetRequired()} returns true. 10281 * 10282 * @return The right padding offset in pixels. 10283 * 10284 * @see #isPaddingOffsetRequired() 10285 * 10286 * @since CURRENT 10287 */ 10288 protected int getRightPaddingOffset() { 10289 return 0; 10290 } 10291 10292 /** 10293 * Amount by which to extend the top fading region. Called only when 10294 * {@link #isPaddingOffsetRequired()} returns true. 10295 * 10296 * @return The top padding offset in pixels. 10297 * 10298 * @see #isPaddingOffsetRequired() 10299 * 10300 * @since CURRENT 10301 */ 10302 protected int getTopPaddingOffset() { 10303 return 0; 10304 } 10305 10306 /** 10307 * Amount by which to extend the bottom fading region. Called only when 10308 * {@link #isPaddingOffsetRequired()} returns true. 10309 * 10310 * @return The bottom padding offset in pixels. 10311 * 10312 * @see #isPaddingOffsetRequired() 10313 * 10314 * @since CURRENT 10315 */ 10316 protected int getBottomPaddingOffset() { 10317 return 0; 10318 } 10319 10320 /** 10321 * @hide 10322 * @param offsetRequired 10323 */ 10324 protected int getFadeTop(boolean offsetRequired) { 10325 int top = mPaddingTop; 10326 if (offsetRequired) top += getTopPaddingOffset(); 10327 return top; 10328 } 10329 10330 /** 10331 * @hide 10332 * @param offsetRequired 10333 */ 10334 protected int getFadeHeight(boolean offsetRequired) { 10335 int padding = mPaddingTop; 10336 if (offsetRequired) padding += getTopPaddingOffset(); 10337 return mBottom - mTop - mPaddingBottom - padding; 10338 } 10339 10340 /** 10341 * <p>Indicates whether this view is attached to an hardware accelerated 10342 * window or not.</p> 10343 * 10344 * <p>Even if this method returns true, it does not mean that every call 10345 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 10346 * accelerated {@link android.graphics.Canvas}. For instance, if this view 10347 * is drawn onto an offscren {@link android.graphics.Bitmap} and its 10348 * window is hardware accelerated, 10349 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 10350 * return false, and this method will return true.</p> 10351 * 10352 * @return True if the view is attached to a window and the window is 10353 * hardware accelerated; false in any other case. 10354 */ 10355 public boolean isHardwareAccelerated() { 10356 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 10357 } 10358 10359 /** 10360 * Manually render this view (and all of its children) to the given Canvas. 10361 * The view must have already done a full layout before this function is 10362 * called. When implementing a view, implement 10363 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 10364 * If you do need to override this method, call the superclass version. 10365 * 10366 * @param canvas The Canvas to which the View is rendered. 10367 */ 10368 public void draw(Canvas canvas) { 10369 if (ViewDebug.TRACE_HIERARCHY) { 10370 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 10371 } 10372 10373 final int privateFlags = mPrivateFlags; 10374 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 10375 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 10376 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 10377 10378 /* 10379 * Draw traversal performs several drawing steps which must be executed 10380 * in the appropriate order: 10381 * 10382 * 1. Draw the background 10383 * 2. If necessary, save the canvas' layers to prepare for fading 10384 * 3. Draw view's content 10385 * 4. Draw children 10386 * 5. If necessary, draw the fading edges and restore layers 10387 * 6. Draw decorations (scrollbars for instance) 10388 */ 10389 10390 // Step 1, draw the background, if needed 10391 int saveCount; 10392 10393 if (!dirtyOpaque) { 10394 final Drawable background = mBGDrawable; 10395 if (background != null) { 10396 final int scrollX = mScrollX; 10397 final int scrollY = mScrollY; 10398 10399 if (mBackgroundSizeChanged) { 10400 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 10401 mBackgroundSizeChanged = false; 10402 } 10403 10404 if ((scrollX | scrollY) == 0) { 10405 background.draw(canvas); 10406 } else { 10407 canvas.translate(scrollX, scrollY); 10408 background.draw(canvas); 10409 canvas.translate(-scrollX, -scrollY); 10410 } 10411 } 10412 } 10413 10414 // skip step 2 & 5 if possible (common case) 10415 final int viewFlags = mViewFlags; 10416 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 10417 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 10418 if (!verticalEdges && !horizontalEdges) { 10419 // Step 3, draw the content 10420 if (!dirtyOpaque) onDraw(canvas); 10421 10422 // Step 4, draw the children 10423 dispatchDraw(canvas); 10424 10425 // Step 6, draw decorations (scrollbars) 10426 onDrawScrollBars(canvas); 10427 10428 // we're done... 10429 return; 10430 } 10431 10432 /* 10433 * Here we do the full fledged routine... 10434 * (this is an uncommon case where speed matters less, 10435 * this is why we repeat some of the tests that have been 10436 * done above) 10437 */ 10438 10439 boolean drawTop = false; 10440 boolean drawBottom = false; 10441 boolean drawLeft = false; 10442 boolean drawRight = false; 10443 10444 float topFadeStrength = 0.0f; 10445 float bottomFadeStrength = 0.0f; 10446 float leftFadeStrength = 0.0f; 10447 float rightFadeStrength = 0.0f; 10448 10449 // Step 2, save the canvas' layers 10450 int paddingLeft = mPaddingLeft; 10451 10452 final boolean offsetRequired = isPaddingOffsetRequired(); 10453 if (offsetRequired) { 10454 paddingLeft += getLeftPaddingOffset(); 10455 } 10456 10457 int left = mScrollX + paddingLeft; 10458 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 10459 int top = mScrollY + getFadeTop(offsetRequired); 10460 int bottom = top + getFadeHeight(offsetRequired); 10461 10462 if (offsetRequired) { 10463 right += getRightPaddingOffset(); 10464 bottom += getBottomPaddingOffset(); 10465 } 10466 10467 final ScrollabilityCache scrollabilityCache = mScrollCache; 10468 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 10469 int length = (int) fadeHeight; 10470 10471 // clip the fade length if top and bottom fades overlap 10472 // overlapping fades produce odd-looking artifacts 10473 if (verticalEdges && (top + length > bottom - length)) { 10474 length = (bottom - top) / 2; 10475 } 10476 10477 // also clip horizontal fades if necessary 10478 if (horizontalEdges && (left + length > right - length)) { 10479 length = (right - left) / 2; 10480 } 10481 10482 if (verticalEdges) { 10483 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 10484 drawTop = topFadeStrength * fadeHeight > 1.0f; 10485 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 10486 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 10487 } 10488 10489 if (horizontalEdges) { 10490 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 10491 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 10492 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 10493 drawRight = rightFadeStrength * fadeHeight > 1.0f; 10494 } 10495 10496 saveCount = canvas.getSaveCount(); 10497 10498 int solidColor = getSolidColor(); 10499 if (solidColor == 0) { 10500 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 10501 10502 if (drawTop) { 10503 canvas.saveLayer(left, top, right, top + length, null, flags); 10504 } 10505 10506 if (drawBottom) { 10507 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 10508 } 10509 10510 if (drawLeft) { 10511 canvas.saveLayer(left, top, left + length, bottom, null, flags); 10512 } 10513 10514 if (drawRight) { 10515 canvas.saveLayer(right - length, top, right, bottom, null, flags); 10516 } 10517 } else { 10518 scrollabilityCache.setFadeColor(solidColor); 10519 } 10520 10521 // Step 3, draw the content 10522 if (!dirtyOpaque) onDraw(canvas); 10523 10524 // Step 4, draw the children 10525 dispatchDraw(canvas); 10526 10527 // Step 5, draw the fade effect and restore layers 10528 final Paint p = scrollabilityCache.paint; 10529 final Matrix matrix = scrollabilityCache.matrix; 10530 final Shader fade = scrollabilityCache.shader; 10531 10532 if (drawTop) { 10533 matrix.setScale(1, fadeHeight * topFadeStrength); 10534 matrix.postTranslate(left, top); 10535 fade.setLocalMatrix(matrix); 10536 canvas.drawRect(left, top, right, top + length, p); 10537 } 10538 10539 if (drawBottom) { 10540 matrix.setScale(1, fadeHeight * bottomFadeStrength); 10541 matrix.postRotate(180); 10542 matrix.postTranslate(left, bottom); 10543 fade.setLocalMatrix(matrix); 10544 canvas.drawRect(left, bottom - length, right, bottom, p); 10545 } 10546 10547 if (drawLeft) { 10548 matrix.setScale(1, fadeHeight * leftFadeStrength); 10549 matrix.postRotate(-90); 10550 matrix.postTranslate(left, top); 10551 fade.setLocalMatrix(matrix); 10552 canvas.drawRect(left, top, left + length, bottom, p); 10553 } 10554 10555 if (drawRight) { 10556 matrix.setScale(1, fadeHeight * rightFadeStrength); 10557 matrix.postRotate(90); 10558 matrix.postTranslate(right, top); 10559 fade.setLocalMatrix(matrix); 10560 canvas.drawRect(right - length, top, right, bottom, p); 10561 } 10562 10563 canvas.restoreToCount(saveCount); 10564 10565 // Step 6, draw decorations (scrollbars) 10566 onDrawScrollBars(canvas); 10567 } 10568 10569 /** 10570 * Override this if your view is known to always be drawn on top of a solid color background, 10571 * and needs to draw fading edges. Returning a non-zero color enables the view system to 10572 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 10573 * should be set to 0xFF. 10574 * 10575 * @see #setVerticalFadingEdgeEnabled(boolean) 10576 * @see #setHorizontalFadingEdgeEnabled(boolean) 10577 * 10578 * @return The known solid color background for this view, or 0 if the color may vary 10579 */ 10580 @ViewDebug.ExportedProperty(category = "drawing") 10581 public int getSolidColor() { 10582 return 0; 10583 } 10584 10585 /** 10586 * Build a human readable string representation of the specified view flags. 10587 * 10588 * @param flags the view flags to convert to a string 10589 * @return a String representing the supplied flags 10590 */ 10591 private static String printFlags(int flags) { 10592 String output = ""; 10593 int numFlags = 0; 10594 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 10595 output += "TAKES_FOCUS"; 10596 numFlags++; 10597 } 10598 10599 switch (flags & VISIBILITY_MASK) { 10600 case INVISIBLE: 10601 if (numFlags > 0) { 10602 output += " "; 10603 } 10604 output += "INVISIBLE"; 10605 // USELESS HERE numFlags++; 10606 break; 10607 case GONE: 10608 if (numFlags > 0) { 10609 output += " "; 10610 } 10611 output += "GONE"; 10612 // USELESS HERE numFlags++; 10613 break; 10614 default: 10615 break; 10616 } 10617 return output; 10618 } 10619 10620 /** 10621 * Build a human readable string representation of the specified private 10622 * view flags. 10623 * 10624 * @param privateFlags the private view flags to convert to a string 10625 * @return a String representing the supplied flags 10626 */ 10627 private static String printPrivateFlags(int privateFlags) { 10628 String output = ""; 10629 int numFlags = 0; 10630 10631 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 10632 output += "WANTS_FOCUS"; 10633 numFlags++; 10634 } 10635 10636 if ((privateFlags & FOCUSED) == FOCUSED) { 10637 if (numFlags > 0) { 10638 output += " "; 10639 } 10640 output += "FOCUSED"; 10641 numFlags++; 10642 } 10643 10644 if ((privateFlags & SELECTED) == SELECTED) { 10645 if (numFlags > 0) { 10646 output += " "; 10647 } 10648 output += "SELECTED"; 10649 numFlags++; 10650 } 10651 10652 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 10653 if (numFlags > 0) { 10654 output += " "; 10655 } 10656 output += "IS_ROOT_NAMESPACE"; 10657 numFlags++; 10658 } 10659 10660 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 10661 if (numFlags > 0) { 10662 output += " "; 10663 } 10664 output += "HAS_BOUNDS"; 10665 numFlags++; 10666 } 10667 10668 if ((privateFlags & DRAWN) == DRAWN) { 10669 if (numFlags > 0) { 10670 output += " "; 10671 } 10672 output += "DRAWN"; 10673 // USELESS HERE numFlags++; 10674 } 10675 return output; 10676 } 10677 10678 /** 10679 * <p>Indicates whether or not this view's layout will be requested during 10680 * the next hierarchy layout pass.</p> 10681 * 10682 * @return true if the layout will be forced during next layout pass 10683 */ 10684 public boolean isLayoutRequested() { 10685 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 10686 } 10687 10688 /** 10689 * Assign a size and position to a view and all of its 10690 * descendants 10691 * 10692 * <p>This is the second phase of the layout mechanism. 10693 * (The first is measuring). In this phase, each parent calls 10694 * layout on all of its children to position them. 10695 * This is typically done using the child measurements 10696 * that were stored in the measure pass().</p> 10697 * 10698 * <p>Derived classes should not override this method. 10699 * Derived classes with children should override 10700 * onLayout. In that method, they should 10701 * call layout on each of their children.</p> 10702 * 10703 * @param l Left position, relative to parent 10704 * @param t Top position, relative to parent 10705 * @param r Right position, relative to parent 10706 * @param b Bottom position, relative to parent 10707 */ 10708 @SuppressWarnings({"unchecked"}) 10709 public void layout(int l, int t, int r, int b) { 10710 int oldL = mLeft; 10711 int oldT = mTop; 10712 int oldB = mBottom; 10713 int oldR = mRight; 10714 boolean changed = setFrame(l, t, r, b); 10715 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 10716 if (ViewDebug.TRACE_HIERARCHY) { 10717 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 10718 } 10719 10720 onLayout(changed, l, t, r, b); 10721 mPrivateFlags &= ~LAYOUT_REQUIRED; 10722 10723 if (mOnLayoutChangeListeners != null) { 10724 ArrayList<OnLayoutChangeListener> listenersCopy = 10725 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone(); 10726 int numListeners = listenersCopy.size(); 10727 for (int i = 0; i < numListeners; ++i) { 10728 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 10729 } 10730 } 10731 } 10732 mPrivateFlags &= ~FORCE_LAYOUT; 10733 } 10734 10735 /** 10736 * Called from layout when this view should 10737 * assign a size and position to each of its children. 10738 * 10739 * Derived classes with children should override 10740 * this method and call layout on each of 10741 * their children. 10742 * @param changed This is a new size or position for this view 10743 * @param left Left position, relative to parent 10744 * @param top Top position, relative to parent 10745 * @param right Right position, relative to parent 10746 * @param bottom Bottom position, relative to parent 10747 */ 10748 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 10749 } 10750 10751 /** 10752 * Assign a size and position to this view. 10753 * 10754 * This is called from layout. 10755 * 10756 * @param left Left position, relative to parent 10757 * @param top Top position, relative to parent 10758 * @param right Right position, relative to parent 10759 * @param bottom Bottom position, relative to parent 10760 * @return true if the new size and position are different than the 10761 * previous ones 10762 * {@hide} 10763 */ 10764 protected boolean setFrame(int left, int top, int right, int bottom) { 10765 boolean changed = false; 10766 10767 if (DBG) { 10768 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 10769 + right + "," + bottom + ")"); 10770 } 10771 10772 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 10773 changed = true; 10774 10775 // Remember our drawn bit 10776 int drawn = mPrivateFlags & DRAWN; 10777 10778 int oldWidth = mRight - mLeft; 10779 int oldHeight = mBottom - mTop; 10780 int newWidth = right - left; 10781 int newHeight = bottom - top; 10782 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 10783 10784 // Invalidate our old position 10785 invalidate(sizeChanged); 10786 10787 mLeft = left; 10788 mTop = top; 10789 mRight = right; 10790 mBottom = bottom; 10791 10792 mPrivateFlags |= HAS_BOUNDS; 10793 10794 10795 if (sizeChanged) { 10796 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 10797 // A change in dimension means an auto-centered pivot point changes, too 10798 mMatrixDirty = true; 10799 } 10800 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 10801 } 10802 10803 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 10804 // If we are visible, force the DRAWN bit to on so that 10805 // this invalidate will go through (at least to our parent). 10806 // This is because someone may have invalidated this view 10807 // before this call to setFrame came in, thereby clearing 10808 // the DRAWN bit. 10809 mPrivateFlags |= DRAWN; 10810 invalidate(sizeChanged); 10811 // parent display list may need to be recreated based on a change in the bounds 10812 // of any child 10813 invalidateParentCaches(); 10814 } 10815 10816 // Reset drawn bit to original value (invalidate turns it off) 10817 mPrivateFlags |= drawn; 10818 10819 mBackgroundSizeChanged = true; 10820 } 10821 return changed; 10822 } 10823 10824 /** 10825 * Finalize inflating a view from XML. This is called as the last phase 10826 * of inflation, after all child views have been added. 10827 * 10828 * <p>Even if the subclass overrides onFinishInflate, they should always be 10829 * sure to call the super method, so that we get called. 10830 */ 10831 protected void onFinishInflate() { 10832 } 10833 10834 /** 10835 * Returns the resources associated with this view. 10836 * 10837 * @return Resources object. 10838 */ 10839 public Resources getResources() { 10840 return mResources; 10841 } 10842 10843 /** 10844 * Invalidates the specified Drawable. 10845 * 10846 * @param drawable the drawable to invalidate 10847 */ 10848 public void invalidateDrawable(Drawable drawable) { 10849 if (verifyDrawable(drawable)) { 10850 final Rect dirty = drawable.getBounds(); 10851 final int scrollX = mScrollX; 10852 final int scrollY = mScrollY; 10853 10854 invalidate(dirty.left + scrollX, dirty.top + scrollY, 10855 dirty.right + scrollX, dirty.bottom + scrollY); 10856 } 10857 } 10858 10859 /** 10860 * Schedules an action on a drawable to occur at a specified time. 10861 * 10862 * @param who the recipient of the action 10863 * @param what the action to run on the drawable 10864 * @param when the time at which the action must occur. Uses the 10865 * {@link SystemClock#uptimeMillis} timebase. 10866 */ 10867 public void scheduleDrawable(Drawable who, Runnable what, long when) { 10868 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 10869 mAttachInfo.mHandler.postAtTime(what, who, when); 10870 } 10871 } 10872 10873 /** 10874 * Cancels a scheduled action on a drawable. 10875 * 10876 * @param who the recipient of the action 10877 * @param what the action to cancel 10878 */ 10879 public void unscheduleDrawable(Drawable who, Runnable what) { 10880 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 10881 mAttachInfo.mHandler.removeCallbacks(what, who); 10882 } 10883 } 10884 10885 /** 10886 * Unschedule any events associated with the given Drawable. This can be 10887 * used when selecting a new Drawable into a view, so that the previous 10888 * one is completely unscheduled. 10889 * 10890 * @param who The Drawable to unschedule. 10891 * 10892 * @see #drawableStateChanged 10893 */ 10894 public void unscheduleDrawable(Drawable who) { 10895 if (mAttachInfo != null) { 10896 mAttachInfo.mHandler.removeCallbacksAndMessages(who); 10897 } 10898 } 10899 10900 /** 10901 * Return the layout direction of a given Drawable. 10902 * 10903 * @param who the Drawable to query 10904 * 10905 * @hide 10906 */ 10907 public int getResolvedLayoutDirection(Drawable who) { 10908 return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT; 10909 } 10910 10911 /** 10912 * If your view subclass is displaying its own Drawable objects, it should 10913 * override this function and return true for any Drawable it is 10914 * displaying. This allows animations for those drawables to be 10915 * scheduled. 10916 * 10917 * <p>Be sure to call through to the super class when overriding this 10918 * function. 10919 * 10920 * @param who The Drawable to verify. Return true if it is one you are 10921 * displaying, else return the result of calling through to the 10922 * super class. 10923 * 10924 * @return boolean If true than the Drawable is being displayed in the 10925 * view; else false and it is not allowed to animate. 10926 * 10927 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 10928 * @see #drawableStateChanged() 10929 */ 10930 protected boolean verifyDrawable(Drawable who) { 10931 return who == mBGDrawable; 10932 } 10933 10934 /** 10935 * This function is called whenever the state of the view changes in such 10936 * a way that it impacts the state of drawables being shown. 10937 * 10938 * <p>Be sure to call through to the superclass when overriding this 10939 * function. 10940 * 10941 * @see Drawable#setState(int[]) 10942 */ 10943 protected void drawableStateChanged() { 10944 Drawable d = mBGDrawable; 10945 if (d != null && d.isStateful()) { 10946 d.setState(getDrawableState()); 10947 } 10948 } 10949 10950 /** 10951 * Call this to force a view to update its drawable state. This will cause 10952 * drawableStateChanged to be called on this view. Views that are interested 10953 * in the new state should call getDrawableState. 10954 * 10955 * @see #drawableStateChanged 10956 * @see #getDrawableState 10957 */ 10958 public void refreshDrawableState() { 10959 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 10960 drawableStateChanged(); 10961 10962 ViewParent parent = mParent; 10963 if (parent != null) { 10964 parent.childDrawableStateChanged(this); 10965 } 10966 } 10967 10968 /** 10969 * Return an array of resource IDs of the drawable states representing the 10970 * current state of the view. 10971 * 10972 * @return The current drawable state 10973 * 10974 * @see Drawable#setState(int[]) 10975 * @see #drawableStateChanged() 10976 * @see #onCreateDrawableState(int) 10977 */ 10978 public final int[] getDrawableState() { 10979 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 10980 return mDrawableState; 10981 } else { 10982 mDrawableState = onCreateDrawableState(0); 10983 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 10984 return mDrawableState; 10985 } 10986 } 10987 10988 /** 10989 * Generate the new {@link android.graphics.drawable.Drawable} state for 10990 * this view. This is called by the view 10991 * system when the cached Drawable state is determined to be invalid. To 10992 * retrieve the current state, you should use {@link #getDrawableState}. 10993 * 10994 * @param extraSpace if non-zero, this is the number of extra entries you 10995 * would like in the returned array in which you can place your own 10996 * states. 10997 * 10998 * @return Returns an array holding the current {@link Drawable} state of 10999 * the view. 11000 * 11001 * @see #mergeDrawableStates(int[], int[]) 11002 */ 11003 protected int[] onCreateDrawableState(int extraSpace) { 11004 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 11005 mParent instanceof View) { 11006 return ((View) mParent).onCreateDrawableState(extraSpace); 11007 } 11008 11009 int[] drawableState; 11010 11011 int privateFlags = mPrivateFlags; 11012 11013 int viewStateIndex = 0; 11014 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 11015 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 11016 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 11017 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 11018 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 11019 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 11020 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 11021 HardwareRenderer.isAvailable()) { 11022 // This is set if HW acceleration is requested, even if the current 11023 // process doesn't allow it. This is just to allow app preview 11024 // windows to better match their app. 11025 viewStateIndex |= VIEW_STATE_ACCELERATED; 11026 } 11027 if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 11028 11029 final int privateFlags2 = mPrivateFlags2; 11030 if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 11031 if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 11032 11033 drawableState = VIEW_STATE_SETS[viewStateIndex]; 11034 11035 //noinspection ConstantIfStatement 11036 if (false) { 11037 Log.i("View", "drawableStateIndex=" + viewStateIndex); 11038 Log.i("View", toString() 11039 + " pressed=" + ((privateFlags & PRESSED) != 0) 11040 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 11041 + " fo=" + hasFocus() 11042 + " sl=" + ((privateFlags & SELECTED) != 0) 11043 + " wf=" + hasWindowFocus() 11044 + ": " + Arrays.toString(drawableState)); 11045 } 11046 11047 if (extraSpace == 0) { 11048 return drawableState; 11049 } 11050 11051 final int[] fullState; 11052 if (drawableState != null) { 11053 fullState = new int[drawableState.length + extraSpace]; 11054 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 11055 } else { 11056 fullState = new int[extraSpace]; 11057 } 11058 11059 return fullState; 11060 } 11061 11062 /** 11063 * Merge your own state values in <var>additionalState</var> into the base 11064 * state values <var>baseState</var> that were returned by 11065 * {@link #onCreateDrawableState(int)}. 11066 * 11067 * @param baseState The base state values returned by 11068 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 11069 * own additional state values. 11070 * 11071 * @param additionalState The additional state values you would like 11072 * added to <var>baseState</var>; this array is not modified. 11073 * 11074 * @return As a convenience, the <var>baseState</var> array you originally 11075 * passed into the function is returned. 11076 * 11077 * @see #onCreateDrawableState(int) 11078 */ 11079 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 11080 final int N = baseState.length; 11081 int i = N - 1; 11082 while (i >= 0 && baseState[i] == 0) { 11083 i--; 11084 } 11085 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 11086 return baseState; 11087 } 11088 11089 /** 11090 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 11091 * on all Drawable objects associated with this view. 11092 */ 11093 public void jumpDrawablesToCurrentState() { 11094 if (mBGDrawable != null) { 11095 mBGDrawable.jumpToCurrentState(); 11096 } 11097 } 11098 11099 /** 11100 * Sets the background color for this view. 11101 * @param color the color of the background 11102 */ 11103 @RemotableViewMethod 11104 public void setBackgroundColor(int color) { 11105 if (mBGDrawable instanceof ColorDrawable) { 11106 ((ColorDrawable) mBGDrawable).setColor(color); 11107 } else { 11108 setBackgroundDrawable(new ColorDrawable(color)); 11109 } 11110 } 11111 11112 /** 11113 * Set the background to a given resource. The resource should refer to 11114 * a Drawable object or 0 to remove the background. 11115 * @param resid The identifier of the resource. 11116 * @attr ref android.R.styleable#View_background 11117 */ 11118 @RemotableViewMethod 11119 public void setBackgroundResource(int resid) { 11120 if (resid != 0 && resid == mBackgroundResource) { 11121 return; 11122 } 11123 11124 Drawable d= null; 11125 if (resid != 0) { 11126 d = mResources.getDrawable(resid); 11127 } 11128 setBackgroundDrawable(d); 11129 11130 mBackgroundResource = resid; 11131 } 11132 11133 /** 11134 * Set the background to a given Drawable, or remove the background. If the 11135 * background has padding, this View's padding is set to the background's 11136 * padding. However, when a background is removed, this View's padding isn't 11137 * touched. If setting the padding is desired, please use 11138 * {@link #setPadding(int, int, int, int)}. 11139 * 11140 * @param d The Drawable to use as the background, or null to remove the 11141 * background 11142 */ 11143 public void setBackgroundDrawable(Drawable d) { 11144 if (d == mBGDrawable) { 11145 return; 11146 } 11147 11148 boolean requestLayout = false; 11149 11150 mBackgroundResource = 0; 11151 11152 /* 11153 * Regardless of whether we're setting a new background or not, we want 11154 * to clear the previous drawable. 11155 */ 11156 if (mBGDrawable != null) { 11157 mBGDrawable.setCallback(null); 11158 unscheduleDrawable(mBGDrawable); 11159 } 11160 11161 if (d != null) { 11162 Rect padding = sThreadLocal.get(); 11163 if (padding == null) { 11164 padding = new Rect(); 11165 sThreadLocal.set(padding); 11166 } 11167 if (d.getPadding(padding)) { 11168 switch (d.getResolvedLayoutDirectionSelf()) { 11169 case LAYOUT_DIRECTION_RTL: 11170 setPadding(padding.right, padding.top, padding.left, padding.bottom); 11171 break; 11172 case LAYOUT_DIRECTION_LTR: 11173 default: 11174 setPadding(padding.left, padding.top, padding.right, padding.bottom); 11175 } 11176 } 11177 11178 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 11179 // if it has a different minimum size, we should layout again 11180 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 11181 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 11182 requestLayout = true; 11183 } 11184 11185 d.setCallback(this); 11186 if (d.isStateful()) { 11187 d.setState(getDrawableState()); 11188 } 11189 d.setVisible(getVisibility() == VISIBLE, false); 11190 mBGDrawable = d; 11191 11192 if ((mPrivateFlags & SKIP_DRAW) != 0) { 11193 mPrivateFlags &= ~SKIP_DRAW; 11194 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 11195 requestLayout = true; 11196 } 11197 } else { 11198 /* Remove the background */ 11199 mBGDrawable = null; 11200 11201 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 11202 /* 11203 * This view ONLY drew the background before and we're removing 11204 * the background, so now it won't draw anything 11205 * (hence we SKIP_DRAW) 11206 */ 11207 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 11208 mPrivateFlags |= SKIP_DRAW; 11209 } 11210 11211 /* 11212 * When the background is set, we try to apply its padding to this 11213 * View. When the background is removed, we don't touch this View's 11214 * padding. This is noted in the Javadocs. Hence, we don't need to 11215 * requestLayout(), the invalidate() below is sufficient. 11216 */ 11217 11218 // The old background's minimum size could have affected this 11219 // View's layout, so let's requestLayout 11220 requestLayout = true; 11221 } 11222 11223 computeOpaqueFlags(); 11224 11225 if (requestLayout) { 11226 requestLayout(); 11227 } 11228 11229 mBackgroundSizeChanged = true; 11230 invalidate(true); 11231 } 11232 11233 /** 11234 * Gets the background drawable 11235 * @return The drawable used as the background for this view, if any. 11236 */ 11237 public Drawable getBackground() { 11238 return mBGDrawable; 11239 } 11240 11241 /** 11242 * Sets the padding. The view may add on the space required to display 11243 * the scrollbars, depending on the style and visibility of the scrollbars. 11244 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 11245 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 11246 * from the values set in this call. 11247 * 11248 * @attr ref android.R.styleable#View_padding 11249 * @attr ref android.R.styleable#View_paddingBottom 11250 * @attr ref android.R.styleable#View_paddingLeft 11251 * @attr ref android.R.styleable#View_paddingRight 11252 * @attr ref android.R.styleable#View_paddingTop 11253 * @param left the left padding in pixels 11254 * @param top the top padding in pixels 11255 * @param right the right padding in pixels 11256 * @param bottom the bottom padding in pixels 11257 */ 11258 public void setPadding(int left, int top, int right, int bottom) { 11259 boolean changed = false; 11260 11261 mUserPaddingRelative = false; 11262 11263 mUserPaddingLeft = left; 11264 mUserPaddingRight = right; 11265 mUserPaddingBottom = bottom; 11266 11267 final int viewFlags = mViewFlags; 11268 11269 // Common case is there are no scroll bars. 11270 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 11271 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 11272 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 11273 ? 0 : getVerticalScrollbarWidth(); 11274 switch (mVerticalScrollbarPosition) { 11275 case SCROLLBAR_POSITION_DEFAULT: 11276 if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 11277 left += offset; 11278 } else { 11279 right += offset; 11280 } 11281 break; 11282 case SCROLLBAR_POSITION_RIGHT: 11283 right += offset; 11284 break; 11285 case SCROLLBAR_POSITION_LEFT: 11286 left += offset; 11287 break; 11288 } 11289 } 11290 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 11291 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 11292 ? 0 : getHorizontalScrollbarHeight(); 11293 } 11294 } 11295 11296 if (mPaddingLeft != left) { 11297 changed = true; 11298 mPaddingLeft = left; 11299 } 11300 if (mPaddingTop != top) { 11301 changed = true; 11302 mPaddingTop = top; 11303 } 11304 if (mPaddingRight != right) { 11305 changed = true; 11306 mPaddingRight = right; 11307 } 11308 if (mPaddingBottom != bottom) { 11309 changed = true; 11310 mPaddingBottom = bottom; 11311 } 11312 11313 if (changed) { 11314 requestLayout(); 11315 } 11316 } 11317 11318 /** 11319 * Sets the relative padding. The view may add on the space required to display 11320 * the scrollbars, depending on the style and visibility of the scrollbars. 11321 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 11322 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 11323 * from the values set in this call. 11324 * 11325 * @attr ref android.R.styleable#View_padding 11326 * @attr ref android.R.styleable#View_paddingBottom 11327 * @attr ref android.R.styleable#View_paddingStart 11328 * @attr ref android.R.styleable#View_paddingEnd 11329 * @attr ref android.R.styleable#View_paddingTop 11330 * @param start the start padding in pixels 11331 * @param top the top padding in pixels 11332 * @param end the end padding in pixels 11333 * @param bottom the bottom padding in pixels 11334 * 11335 * @hide 11336 */ 11337 public void setPaddingRelative(int start, int top, int end, int bottom) { 11338 mUserPaddingRelative = true; 11339 11340 mUserPaddingStart = start; 11341 mUserPaddingEnd = end; 11342 11343 switch(getResolvedLayoutDirection()) { 11344 case LAYOUT_DIRECTION_RTL: 11345 setPadding(end, top, start, bottom); 11346 break; 11347 case LAYOUT_DIRECTION_LTR: 11348 default: 11349 setPadding(start, top, end, bottom); 11350 } 11351 } 11352 11353 /** 11354 * Returns the top padding of this view. 11355 * 11356 * @return the top padding in pixels 11357 */ 11358 public int getPaddingTop() { 11359 return mPaddingTop; 11360 } 11361 11362 /** 11363 * Returns the bottom padding of this view. If there are inset and enabled 11364 * scrollbars, this value may include the space required to display the 11365 * scrollbars as well. 11366 * 11367 * @return the bottom padding in pixels 11368 */ 11369 public int getPaddingBottom() { 11370 return mPaddingBottom; 11371 } 11372 11373 /** 11374 * Returns the left padding of this view. If there are inset and enabled 11375 * scrollbars, this value may include the space required to display the 11376 * scrollbars as well. 11377 * 11378 * @return the left padding in pixels 11379 */ 11380 public int getPaddingLeft() { 11381 return mPaddingLeft; 11382 } 11383 11384 /** 11385 * Returns the start padding of this view. If there are inset and enabled 11386 * scrollbars, this value may include the space required to display the 11387 * scrollbars as well. 11388 * 11389 * @return the start padding in pixels 11390 * 11391 * @hide 11392 */ 11393 public int getPaddingStart() { 11394 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 11395 mPaddingRight : mPaddingLeft; 11396 } 11397 11398 /** 11399 * Returns the right padding of this view. If there are inset and enabled 11400 * scrollbars, this value may include the space required to display the 11401 * scrollbars as well. 11402 * 11403 * @return the right padding in pixels 11404 */ 11405 public int getPaddingRight() { 11406 return mPaddingRight; 11407 } 11408 11409 /** 11410 * Returns the end padding of this view. If there are inset and enabled 11411 * scrollbars, this value may include the space required to display the 11412 * scrollbars as well. 11413 * 11414 * @return the end padding in pixels 11415 * 11416 * @hide 11417 */ 11418 public int getPaddingEnd() { 11419 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 11420 mPaddingLeft : mPaddingRight; 11421 } 11422 11423 /** 11424 * Return if the padding as been set thru relative values 11425 * {@link #setPaddingRelative(int, int, int, int)} or thru 11426 * @attr ref android.R.styleable#View_paddingStart or 11427 * @attr ref android.R.styleable#View_paddingEnd 11428 * 11429 * @return true if the padding is relative or false if it is not. 11430 * 11431 * @hide 11432 */ 11433 public boolean isPaddingRelative() { 11434 return mUserPaddingRelative; 11435 } 11436 11437 /** 11438 * Changes the selection state of this view. A view can be selected or not. 11439 * Note that selection is not the same as focus. Views are typically 11440 * selected in the context of an AdapterView like ListView or GridView; 11441 * the selected view is the view that is highlighted. 11442 * 11443 * @param selected true if the view must be selected, false otherwise 11444 */ 11445 public void setSelected(boolean selected) { 11446 if (((mPrivateFlags & SELECTED) != 0) != selected) { 11447 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 11448 if (!selected) resetPressedState(); 11449 invalidate(true); 11450 refreshDrawableState(); 11451 dispatchSetSelected(selected); 11452 } 11453 } 11454 11455 /** 11456 * Dispatch setSelected to all of this View's children. 11457 * 11458 * @see #setSelected(boolean) 11459 * 11460 * @param selected The new selected state 11461 */ 11462 protected void dispatchSetSelected(boolean selected) { 11463 } 11464 11465 /** 11466 * Indicates the selection state of this view. 11467 * 11468 * @return true if the view is selected, false otherwise 11469 */ 11470 @ViewDebug.ExportedProperty 11471 public boolean isSelected() { 11472 return (mPrivateFlags & SELECTED) != 0; 11473 } 11474 11475 /** 11476 * Changes the activated state of this view. A view can be activated or not. 11477 * Note that activation is not the same as selection. Selection is 11478 * a transient property, representing the view (hierarchy) the user is 11479 * currently interacting with. Activation is a longer-term state that the 11480 * user can move views in and out of. For example, in a list view with 11481 * single or multiple selection enabled, the views in the current selection 11482 * set are activated. (Um, yeah, we are deeply sorry about the terminology 11483 * here.) The activated state is propagated down to children of the view it 11484 * is set on. 11485 * 11486 * @param activated true if the view must be activated, false otherwise 11487 */ 11488 public void setActivated(boolean activated) { 11489 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 11490 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 11491 invalidate(true); 11492 refreshDrawableState(); 11493 dispatchSetActivated(activated); 11494 } 11495 } 11496 11497 /** 11498 * Dispatch setActivated to all of this View's children. 11499 * 11500 * @see #setActivated(boolean) 11501 * 11502 * @param activated The new activated state 11503 */ 11504 protected void dispatchSetActivated(boolean activated) { 11505 } 11506 11507 /** 11508 * Indicates the activation state of this view. 11509 * 11510 * @return true if the view is activated, false otherwise 11511 */ 11512 @ViewDebug.ExportedProperty 11513 public boolean isActivated() { 11514 return (mPrivateFlags & ACTIVATED) != 0; 11515 } 11516 11517 /** 11518 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 11519 * observer can be used to get notifications when global events, like 11520 * layout, happen. 11521 * 11522 * The returned ViewTreeObserver observer is not guaranteed to remain 11523 * valid for the lifetime of this View. If the caller of this method keeps 11524 * a long-lived reference to ViewTreeObserver, it should always check for 11525 * the return value of {@link ViewTreeObserver#isAlive()}. 11526 * 11527 * @return The ViewTreeObserver for this view's hierarchy. 11528 */ 11529 public ViewTreeObserver getViewTreeObserver() { 11530 if (mAttachInfo != null) { 11531 return mAttachInfo.mTreeObserver; 11532 } 11533 if (mFloatingTreeObserver == null) { 11534 mFloatingTreeObserver = new ViewTreeObserver(); 11535 } 11536 return mFloatingTreeObserver; 11537 } 11538 11539 /** 11540 * <p>Finds the topmost view in the current view hierarchy.</p> 11541 * 11542 * @return the topmost view containing this view 11543 */ 11544 public View getRootView() { 11545 if (mAttachInfo != null) { 11546 final View v = mAttachInfo.mRootView; 11547 if (v != null) { 11548 return v; 11549 } 11550 } 11551 11552 View parent = this; 11553 11554 while (parent.mParent != null && parent.mParent instanceof View) { 11555 parent = (View) parent.mParent; 11556 } 11557 11558 return parent; 11559 } 11560 11561 /** 11562 * <p>Computes the coordinates of this view on the screen. The argument 11563 * must be an array of two integers. After the method returns, the array 11564 * contains the x and y location in that order.</p> 11565 * 11566 * @param location an array of two integers in which to hold the coordinates 11567 */ 11568 public void getLocationOnScreen(int[] location) { 11569 getLocationInWindow(location); 11570 11571 final AttachInfo info = mAttachInfo; 11572 if (info != null) { 11573 location[0] += info.mWindowLeft; 11574 location[1] += info.mWindowTop; 11575 } 11576 } 11577 11578 /** 11579 * <p>Computes the coordinates of this view in its window. The argument 11580 * must be an array of two integers. After the method returns, the array 11581 * contains the x and y location in that order.</p> 11582 * 11583 * @param location an array of two integers in which to hold the coordinates 11584 */ 11585 public void getLocationInWindow(int[] location) { 11586 if (location == null || location.length < 2) { 11587 throw new IllegalArgumentException("location must be an array of " 11588 + "two integers"); 11589 } 11590 11591 location[0] = mLeft + (int) (mTranslationX + 0.5f); 11592 location[1] = mTop + (int) (mTranslationY + 0.5f); 11593 11594 ViewParent viewParent = mParent; 11595 while (viewParent instanceof View) { 11596 final View view = (View)viewParent; 11597 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX; 11598 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY; 11599 viewParent = view.mParent; 11600 } 11601 11602 if (viewParent instanceof ViewRootImpl) { 11603 // *cough* 11604 final ViewRootImpl vr = (ViewRootImpl)viewParent; 11605 location[1] -= vr.mCurScrollY; 11606 } 11607 } 11608 11609 /** 11610 * {@hide} 11611 * @param id the id of the view to be found 11612 * @return the view of the specified id, null if cannot be found 11613 */ 11614 protected View findViewTraversal(int id) { 11615 if (id == mID) { 11616 return this; 11617 } 11618 return null; 11619 } 11620 11621 /** 11622 * {@hide} 11623 * @param tag the tag of the view to be found 11624 * @return the view of specified tag, null if cannot be found 11625 */ 11626 protected View findViewWithTagTraversal(Object tag) { 11627 if (tag != null && tag.equals(mTag)) { 11628 return this; 11629 } 11630 return null; 11631 } 11632 11633 /** 11634 * {@hide} 11635 * @param predicate The predicate to evaluate. 11636 * @return The first view that matches the predicate or null. 11637 */ 11638 protected View findViewByPredicateTraversal(Predicate<View> predicate) { 11639 if (predicate.apply(this)) { 11640 return this; 11641 } 11642 return null; 11643 } 11644 11645 /** 11646 * Look for a child view with the given id. If this view has the given 11647 * id, return this view. 11648 * 11649 * @param id The id to search for. 11650 * @return The view that has the given id in the hierarchy or null 11651 */ 11652 public final View findViewById(int id) { 11653 if (id < 0) { 11654 return null; 11655 } 11656 return findViewTraversal(id); 11657 } 11658 11659 /** 11660 * Look for a child view with the given tag. If this view has the given 11661 * tag, return this view. 11662 * 11663 * @param tag The tag to search for, using "tag.equals(getTag())". 11664 * @return The View that has the given tag in the hierarchy or null 11665 */ 11666 public final View findViewWithTag(Object tag) { 11667 if (tag == null) { 11668 return null; 11669 } 11670 return findViewWithTagTraversal(tag); 11671 } 11672 11673 /** 11674 * {@hide} 11675 * Look for a child view that matches the specified predicate. 11676 * If this view matches the predicate, return this view. 11677 * 11678 * @param predicate The predicate to evaluate. 11679 * @return The first view that matches the predicate or null. 11680 */ 11681 public final View findViewByPredicate(Predicate<View> predicate) { 11682 return findViewByPredicateTraversal(predicate); 11683 } 11684 11685 /** 11686 * Sets the identifier for this view. The identifier does not have to be 11687 * unique in this view's hierarchy. The identifier should be a positive 11688 * number. 11689 * 11690 * @see #NO_ID 11691 * @see #getId() 11692 * @see #findViewById(int) 11693 * 11694 * @param id a number used to identify the view 11695 * 11696 * @attr ref android.R.styleable#View_id 11697 */ 11698 public void setId(int id) { 11699 mID = id; 11700 } 11701 11702 /** 11703 * {@hide} 11704 * 11705 * @param isRoot true if the view belongs to the root namespace, false 11706 * otherwise 11707 */ 11708 public void setIsRootNamespace(boolean isRoot) { 11709 if (isRoot) { 11710 mPrivateFlags |= IS_ROOT_NAMESPACE; 11711 } else { 11712 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 11713 } 11714 } 11715 11716 /** 11717 * {@hide} 11718 * 11719 * @return true if the view belongs to the root namespace, false otherwise 11720 */ 11721 public boolean isRootNamespace() { 11722 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 11723 } 11724 11725 /** 11726 * Returns this view's identifier. 11727 * 11728 * @return a positive integer used to identify the view or {@link #NO_ID} 11729 * if the view has no ID 11730 * 11731 * @see #setId(int) 11732 * @see #findViewById(int) 11733 * @attr ref android.R.styleable#View_id 11734 */ 11735 @ViewDebug.CapturedViewProperty 11736 public int getId() { 11737 return mID; 11738 } 11739 11740 /** 11741 * Returns this view's tag. 11742 * 11743 * @return the Object stored in this view as a tag 11744 * 11745 * @see #setTag(Object) 11746 * @see #getTag(int) 11747 */ 11748 @ViewDebug.ExportedProperty 11749 public Object getTag() { 11750 return mTag; 11751 } 11752 11753 /** 11754 * Sets the tag associated with this view. A tag can be used to mark 11755 * a view in its hierarchy and does not have to be unique within the 11756 * hierarchy. Tags can also be used to store data within a view without 11757 * resorting to another data structure. 11758 * 11759 * @param tag an Object to tag the view with 11760 * 11761 * @see #getTag() 11762 * @see #setTag(int, Object) 11763 */ 11764 public void setTag(final Object tag) { 11765 mTag = tag; 11766 } 11767 11768 /** 11769 * Returns the tag associated with this view and the specified key. 11770 * 11771 * @param key The key identifying the tag 11772 * 11773 * @return the Object stored in this view as a tag 11774 * 11775 * @see #setTag(int, Object) 11776 * @see #getTag() 11777 */ 11778 public Object getTag(int key) { 11779 SparseArray<Object> tags = null; 11780 synchronized (sTagsLock) { 11781 if (sTags != null) { 11782 tags = sTags.get(this); 11783 } 11784 } 11785 11786 if (tags != null) return tags.get(key); 11787 return null; 11788 } 11789 11790 /** 11791 * Sets a tag associated with this view and a key. A tag can be used 11792 * to mark a view in its hierarchy and does not have to be unique within 11793 * the hierarchy. Tags can also be used to store data within a view 11794 * without resorting to another data structure. 11795 * 11796 * The specified key should be an id declared in the resources of the 11797 * application to ensure it is unique (see the <a 11798 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 11799 * Keys identified as belonging to 11800 * the Android framework or not associated with any package will cause 11801 * an {@link IllegalArgumentException} to be thrown. 11802 * 11803 * @param key The key identifying the tag 11804 * @param tag An Object to tag the view with 11805 * 11806 * @throws IllegalArgumentException If they specified key is not valid 11807 * 11808 * @see #setTag(Object) 11809 * @see #getTag(int) 11810 */ 11811 public void setTag(int key, final Object tag) { 11812 // If the package id is 0x00 or 0x01, it's either an undefined package 11813 // or a framework id 11814 if ((key >>> 24) < 2) { 11815 throw new IllegalArgumentException("The key must be an application-specific " 11816 + "resource id."); 11817 } 11818 11819 setTagInternal(this, key, tag); 11820 } 11821 11822 /** 11823 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 11824 * framework id. 11825 * 11826 * @hide 11827 */ 11828 public void setTagInternal(int key, Object tag) { 11829 if ((key >>> 24) != 0x1) { 11830 throw new IllegalArgumentException("The key must be a framework-specific " 11831 + "resource id."); 11832 } 11833 11834 setTagInternal(this, key, tag); 11835 } 11836 11837 private static void setTagInternal(View view, int key, Object tag) { 11838 SparseArray<Object> tags = null; 11839 synchronized (sTagsLock) { 11840 if (sTags == null) { 11841 sTags = new WeakHashMap<View, SparseArray<Object>>(); 11842 } else { 11843 tags = sTags.get(view); 11844 } 11845 } 11846 11847 if (tags == null) { 11848 tags = new SparseArray<Object>(2); 11849 synchronized (sTagsLock) { 11850 sTags.put(view, tags); 11851 } 11852 } 11853 11854 tags.put(key, tag); 11855 } 11856 11857 /** 11858 * @param consistency The type of consistency. See ViewDebug for more information. 11859 * 11860 * @hide 11861 */ 11862 protected boolean dispatchConsistencyCheck(int consistency) { 11863 return onConsistencyCheck(consistency); 11864 } 11865 11866 /** 11867 * Method that subclasses should implement to check their consistency. The type of 11868 * consistency check is indicated by the bit field passed as a parameter. 11869 * 11870 * @param consistency The type of consistency. See ViewDebug for more information. 11871 * 11872 * @throws IllegalStateException if the view is in an inconsistent state. 11873 * 11874 * @hide 11875 */ 11876 protected boolean onConsistencyCheck(int consistency) { 11877 boolean result = true; 11878 11879 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 11880 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 11881 11882 if (checkLayout) { 11883 if (getParent() == null) { 11884 result = false; 11885 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 11886 "View " + this + " does not have a parent."); 11887 } 11888 11889 if (mAttachInfo == null) { 11890 result = false; 11891 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 11892 "View " + this + " is not attached to a window."); 11893 } 11894 } 11895 11896 if (checkDrawing) { 11897 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 11898 // from their draw() method 11899 11900 if ((mPrivateFlags & DRAWN) != DRAWN && 11901 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 11902 result = false; 11903 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 11904 "View " + this + " was invalidated but its drawing cache is valid."); 11905 } 11906 } 11907 11908 return result; 11909 } 11910 11911 /** 11912 * Prints information about this view in the log output, with the tag 11913 * {@link #VIEW_LOG_TAG}. 11914 * 11915 * @hide 11916 */ 11917 public void debug() { 11918 debug(0); 11919 } 11920 11921 /** 11922 * Prints information about this view in the log output, with the tag 11923 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 11924 * indentation defined by the <code>depth</code>. 11925 * 11926 * @param depth the indentation level 11927 * 11928 * @hide 11929 */ 11930 protected void debug(int depth) { 11931 String output = debugIndent(depth - 1); 11932 11933 output += "+ " + this; 11934 int id = getId(); 11935 if (id != -1) { 11936 output += " (id=" + id + ")"; 11937 } 11938 Object tag = getTag(); 11939 if (tag != null) { 11940 output += " (tag=" + tag + ")"; 11941 } 11942 Log.d(VIEW_LOG_TAG, output); 11943 11944 if ((mPrivateFlags & FOCUSED) != 0) { 11945 output = debugIndent(depth) + " FOCUSED"; 11946 Log.d(VIEW_LOG_TAG, output); 11947 } 11948 11949 output = debugIndent(depth); 11950 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 11951 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 11952 + "} "; 11953 Log.d(VIEW_LOG_TAG, output); 11954 11955 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 11956 || mPaddingBottom != 0) { 11957 output = debugIndent(depth); 11958 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 11959 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 11960 Log.d(VIEW_LOG_TAG, output); 11961 } 11962 11963 output = debugIndent(depth); 11964 output += "mMeasureWidth=" + mMeasuredWidth + 11965 " mMeasureHeight=" + mMeasuredHeight; 11966 Log.d(VIEW_LOG_TAG, output); 11967 11968 output = debugIndent(depth); 11969 if (mLayoutParams == null) { 11970 output += "BAD! no layout params"; 11971 } else { 11972 output = mLayoutParams.debug(output); 11973 } 11974 Log.d(VIEW_LOG_TAG, output); 11975 11976 output = debugIndent(depth); 11977 output += "flags={"; 11978 output += View.printFlags(mViewFlags); 11979 output += "}"; 11980 Log.d(VIEW_LOG_TAG, output); 11981 11982 output = debugIndent(depth); 11983 output += "privateFlags={"; 11984 output += View.printPrivateFlags(mPrivateFlags); 11985 output += "}"; 11986 Log.d(VIEW_LOG_TAG, output); 11987 } 11988 11989 /** 11990 * Creates an string of whitespaces used for indentation. 11991 * 11992 * @param depth the indentation level 11993 * @return a String containing (depth * 2 + 3) * 2 white spaces 11994 * 11995 * @hide 11996 */ 11997 protected static String debugIndent(int depth) { 11998 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 11999 for (int i = 0; i < (depth * 2) + 3; i++) { 12000 spaces.append(' ').append(' '); 12001 } 12002 return spaces.toString(); 12003 } 12004 12005 /** 12006 * <p>Return the offset of the widget's text baseline from the widget's top 12007 * boundary. If this widget does not support baseline alignment, this 12008 * method returns -1. </p> 12009 * 12010 * @return the offset of the baseline within the widget's bounds or -1 12011 * if baseline alignment is not supported 12012 */ 12013 @ViewDebug.ExportedProperty(category = "layout") 12014 public int getBaseline() { 12015 return -1; 12016 } 12017 12018 /** 12019 * Call this when something has changed which has invalidated the 12020 * layout of this view. This will schedule a layout pass of the view 12021 * tree. 12022 */ 12023 public void requestLayout() { 12024 if (ViewDebug.TRACE_HIERARCHY) { 12025 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 12026 } 12027 12028 mPrivateFlags |= FORCE_LAYOUT; 12029 mPrivateFlags |= INVALIDATED; 12030 12031 if (mLayoutParams != null && mParent != null) { 12032 mLayoutParams.resolveWithDirection(getResolvedLayoutDirection()); 12033 } 12034 12035 if (mParent != null && !mParent.isLayoutRequested()) { 12036 mParent.requestLayout(); 12037 } 12038 } 12039 12040 /** 12041 * Forces this view to be laid out during the next layout pass. 12042 * This method does not call requestLayout() or forceLayout() 12043 * on the parent. 12044 */ 12045 public void forceLayout() { 12046 mPrivateFlags |= FORCE_LAYOUT; 12047 mPrivateFlags |= INVALIDATED; 12048 } 12049 12050 /** 12051 * <p> 12052 * This is called to find out how big a view should be. The parent 12053 * supplies constraint information in the width and height parameters. 12054 * </p> 12055 * 12056 * <p> 12057 * The actual mesurement work of a view is performed in 12058 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 12059 * {@link #onMeasure(int, int)} can and must be overriden by subclasses. 12060 * </p> 12061 * 12062 * 12063 * @param widthMeasureSpec Horizontal space requirements as imposed by the 12064 * parent 12065 * @param heightMeasureSpec Vertical space requirements as imposed by the 12066 * parent 12067 * 12068 * @see #onMeasure(int, int) 12069 */ 12070 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 12071 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 12072 widthMeasureSpec != mOldWidthMeasureSpec || 12073 heightMeasureSpec != mOldHeightMeasureSpec) { 12074 12075 // first clears the measured dimension flag 12076 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 12077 12078 if (ViewDebug.TRACE_HIERARCHY) { 12079 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 12080 } 12081 12082 // measure ourselves, this should set the measured dimension flag back 12083 onMeasure(widthMeasureSpec, heightMeasureSpec); 12084 12085 // flag not set, setMeasuredDimension() was not invoked, we raise 12086 // an exception to warn the developer 12087 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 12088 throw new IllegalStateException("onMeasure() did not set the" 12089 + " measured dimension by calling" 12090 + " setMeasuredDimension()"); 12091 } 12092 12093 mPrivateFlags |= LAYOUT_REQUIRED; 12094 } 12095 12096 mOldWidthMeasureSpec = widthMeasureSpec; 12097 mOldHeightMeasureSpec = heightMeasureSpec; 12098 } 12099 12100 /** 12101 * <p> 12102 * Measure the view and its content to determine the measured width and the 12103 * measured height. This method is invoked by {@link #measure(int, int)} and 12104 * should be overriden by subclasses to provide accurate and efficient 12105 * measurement of their contents. 12106 * </p> 12107 * 12108 * <p> 12109 * <strong>CONTRACT:</strong> When overriding this method, you 12110 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 12111 * measured width and height of this view. Failure to do so will trigger an 12112 * <code>IllegalStateException</code>, thrown by 12113 * {@link #measure(int, int)}. Calling the superclass' 12114 * {@link #onMeasure(int, int)} is a valid use. 12115 * </p> 12116 * 12117 * <p> 12118 * The base class implementation of measure defaults to the background size, 12119 * unless a larger size is allowed by the MeasureSpec. Subclasses should 12120 * override {@link #onMeasure(int, int)} to provide better measurements of 12121 * their content. 12122 * </p> 12123 * 12124 * <p> 12125 * If this method is overridden, it is the subclass's responsibility to make 12126 * sure the measured height and width are at least the view's minimum height 12127 * and width ({@link #getSuggestedMinimumHeight()} and 12128 * {@link #getSuggestedMinimumWidth()}). 12129 * </p> 12130 * 12131 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 12132 * The requirements are encoded with 12133 * {@link android.view.View.MeasureSpec}. 12134 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 12135 * The requirements are encoded with 12136 * {@link android.view.View.MeasureSpec}. 12137 * 12138 * @see #getMeasuredWidth() 12139 * @see #getMeasuredHeight() 12140 * @see #setMeasuredDimension(int, int) 12141 * @see #getSuggestedMinimumHeight() 12142 * @see #getSuggestedMinimumWidth() 12143 * @see android.view.View.MeasureSpec#getMode(int) 12144 * @see android.view.View.MeasureSpec#getSize(int) 12145 */ 12146 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 12147 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 12148 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 12149 } 12150 12151 /** 12152 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 12153 * measured width and measured height. Failing to do so will trigger an 12154 * exception at measurement time.</p> 12155 * 12156 * @param measuredWidth The measured width of this view. May be a complex 12157 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 12158 * {@link #MEASURED_STATE_TOO_SMALL}. 12159 * @param measuredHeight The measured height of this view. May be a complex 12160 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 12161 * {@link #MEASURED_STATE_TOO_SMALL}. 12162 */ 12163 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 12164 mMeasuredWidth = measuredWidth; 12165 mMeasuredHeight = measuredHeight; 12166 12167 mPrivateFlags |= MEASURED_DIMENSION_SET; 12168 } 12169 12170 /** 12171 * Merge two states as returned by {@link #getMeasuredState()}. 12172 * @param curState The current state as returned from a view or the result 12173 * of combining multiple views. 12174 * @param newState The new view state to combine. 12175 * @return Returns a new integer reflecting the combination of the two 12176 * states. 12177 */ 12178 public static int combineMeasuredStates(int curState, int newState) { 12179 return curState | newState; 12180 } 12181 12182 /** 12183 * Version of {@link #resolveSizeAndState(int, int, int)} 12184 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 12185 */ 12186 public static int resolveSize(int size, int measureSpec) { 12187 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 12188 } 12189 12190 /** 12191 * Utility to reconcile a desired size and state, with constraints imposed 12192 * by a MeasureSpec. Will take the desired size, unless a different size 12193 * is imposed by the constraints. The returned value is a compound integer, 12194 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 12195 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 12196 * size is smaller than the size the view wants to be. 12197 * 12198 * @param size How big the view wants to be 12199 * @param measureSpec Constraints imposed by the parent 12200 * @return Size information bit mask as defined by 12201 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 12202 */ 12203 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 12204 int result = size; 12205 int specMode = MeasureSpec.getMode(measureSpec); 12206 int specSize = MeasureSpec.getSize(measureSpec); 12207 switch (specMode) { 12208 case MeasureSpec.UNSPECIFIED: 12209 result = size; 12210 break; 12211 case MeasureSpec.AT_MOST: 12212 if (specSize < size) { 12213 result = specSize | MEASURED_STATE_TOO_SMALL; 12214 } else { 12215 result = size; 12216 } 12217 break; 12218 case MeasureSpec.EXACTLY: 12219 result = specSize; 12220 break; 12221 } 12222 return result | (childMeasuredState&MEASURED_STATE_MASK); 12223 } 12224 12225 /** 12226 * Utility to return a default size. Uses the supplied size if the 12227 * MeasureSpec imposed no constraints. Will get larger if allowed 12228 * by the MeasureSpec. 12229 * 12230 * @param size Default size for this view 12231 * @param measureSpec Constraints imposed by the parent 12232 * @return The size this view should be. 12233 */ 12234 public static int getDefaultSize(int size, int measureSpec) { 12235 int result = size; 12236 int specMode = MeasureSpec.getMode(measureSpec); 12237 int specSize = MeasureSpec.getSize(measureSpec); 12238 12239 switch (specMode) { 12240 case MeasureSpec.UNSPECIFIED: 12241 result = size; 12242 break; 12243 case MeasureSpec.AT_MOST: 12244 case MeasureSpec.EXACTLY: 12245 result = specSize; 12246 break; 12247 } 12248 return result; 12249 } 12250 12251 /** 12252 * Returns the suggested minimum height that the view should use. This 12253 * returns the maximum of the view's minimum height 12254 * and the background's minimum height 12255 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 12256 * <p> 12257 * When being used in {@link #onMeasure(int, int)}, the caller should still 12258 * ensure the returned height is within the requirements of the parent. 12259 * 12260 * @return The suggested minimum height of the view. 12261 */ 12262 protected int getSuggestedMinimumHeight() { 12263 int suggestedMinHeight = mMinHeight; 12264 12265 if (mBGDrawable != null) { 12266 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 12267 if (suggestedMinHeight < bgMinHeight) { 12268 suggestedMinHeight = bgMinHeight; 12269 } 12270 } 12271 12272 return suggestedMinHeight; 12273 } 12274 12275 /** 12276 * Returns the suggested minimum width that the view should use. This 12277 * returns the maximum of the view's minimum width) 12278 * and the background's minimum width 12279 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 12280 * <p> 12281 * When being used in {@link #onMeasure(int, int)}, the caller should still 12282 * ensure the returned width is within the requirements of the parent. 12283 * 12284 * @return The suggested minimum width of the view. 12285 */ 12286 protected int getSuggestedMinimumWidth() { 12287 int suggestedMinWidth = mMinWidth; 12288 12289 if (mBGDrawable != null) { 12290 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 12291 if (suggestedMinWidth < bgMinWidth) { 12292 suggestedMinWidth = bgMinWidth; 12293 } 12294 } 12295 12296 return suggestedMinWidth; 12297 } 12298 12299 /** 12300 * Sets the minimum height of the view. It is not guaranteed the view will 12301 * be able to achieve this minimum height (for example, if its parent layout 12302 * constrains it with less available height). 12303 * 12304 * @param minHeight The minimum height the view will try to be. 12305 */ 12306 public void setMinimumHeight(int minHeight) { 12307 mMinHeight = minHeight; 12308 } 12309 12310 /** 12311 * Sets the minimum width of the view. It is not guaranteed the view will 12312 * be able to achieve this minimum width (for example, if its parent layout 12313 * constrains it with less available width). 12314 * 12315 * @param minWidth The minimum width the view will try to be. 12316 */ 12317 public void setMinimumWidth(int minWidth) { 12318 mMinWidth = minWidth; 12319 } 12320 12321 /** 12322 * Get the animation currently associated with this view. 12323 * 12324 * @return The animation that is currently playing or 12325 * scheduled to play for this view. 12326 */ 12327 public Animation getAnimation() { 12328 return mCurrentAnimation; 12329 } 12330 12331 /** 12332 * Start the specified animation now. 12333 * 12334 * @param animation the animation to start now 12335 */ 12336 public void startAnimation(Animation animation) { 12337 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 12338 setAnimation(animation); 12339 invalidateParentCaches(); 12340 invalidate(true); 12341 } 12342 12343 /** 12344 * Cancels any animations for this view. 12345 */ 12346 public void clearAnimation() { 12347 if (mCurrentAnimation != null) { 12348 mCurrentAnimation.detach(); 12349 } 12350 mCurrentAnimation = null; 12351 invalidateParentIfNeeded(); 12352 } 12353 12354 /** 12355 * Sets the next animation to play for this view. 12356 * If you want the animation to play immediately, use 12357 * startAnimation. This method provides allows fine-grained 12358 * control over the start time and invalidation, but you 12359 * must make sure that 1) the animation has a start time set, and 12360 * 2) the view will be invalidated when the animation is supposed to 12361 * start. 12362 * 12363 * @param animation The next animation, or null. 12364 */ 12365 public void setAnimation(Animation animation) { 12366 mCurrentAnimation = animation; 12367 if (animation != null) { 12368 animation.reset(); 12369 } 12370 } 12371 12372 /** 12373 * Invoked by a parent ViewGroup to notify the start of the animation 12374 * currently associated with this view. If you override this method, 12375 * always call super.onAnimationStart(); 12376 * 12377 * @see #setAnimation(android.view.animation.Animation) 12378 * @see #getAnimation() 12379 */ 12380 protected void onAnimationStart() { 12381 mPrivateFlags |= ANIMATION_STARTED; 12382 } 12383 12384 /** 12385 * Invoked by a parent ViewGroup to notify the end of the animation 12386 * currently associated with this view. If you override this method, 12387 * always call super.onAnimationEnd(); 12388 * 12389 * @see #setAnimation(android.view.animation.Animation) 12390 * @see #getAnimation() 12391 */ 12392 protected void onAnimationEnd() { 12393 mPrivateFlags &= ~ANIMATION_STARTED; 12394 } 12395 12396 /** 12397 * Invoked if there is a Transform that involves alpha. Subclass that can 12398 * draw themselves with the specified alpha should return true, and then 12399 * respect that alpha when their onDraw() is called. If this returns false 12400 * then the view may be redirected to draw into an offscreen buffer to 12401 * fulfill the request, which will look fine, but may be slower than if the 12402 * subclass handles it internally. The default implementation returns false. 12403 * 12404 * @param alpha The alpha (0..255) to apply to the view's drawing 12405 * @return true if the view can draw with the specified alpha. 12406 */ 12407 protected boolean onSetAlpha(int alpha) { 12408 return false; 12409 } 12410 12411 /** 12412 * This is used by the RootView to perform an optimization when 12413 * the view hierarchy contains one or several SurfaceView. 12414 * SurfaceView is always considered transparent, but its children are not, 12415 * therefore all View objects remove themselves from the global transparent 12416 * region (passed as a parameter to this function). 12417 * 12418 * @param region The transparent region for this ViewAncestor (window). 12419 * 12420 * @return Returns true if the effective visibility of the view at this 12421 * point is opaque, regardless of the transparent region; returns false 12422 * if it is possible for underlying windows to be seen behind the view. 12423 * 12424 * {@hide} 12425 */ 12426 public boolean gatherTransparentRegion(Region region) { 12427 final AttachInfo attachInfo = mAttachInfo; 12428 if (region != null && attachInfo != null) { 12429 final int pflags = mPrivateFlags; 12430 if ((pflags & SKIP_DRAW) == 0) { 12431 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 12432 // remove it from the transparent region. 12433 final int[] location = attachInfo.mTransparentLocation; 12434 getLocationInWindow(location); 12435 region.op(location[0], location[1], location[0] + mRight - mLeft, 12436 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 12437 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 12438 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 12439 // exists, so we remove the background drawable's non-transparent 12440 // parts from this transparent region. 12441 applyDrawableToTransparentRegion(mBGDrawable, region); 12442 } 12443 } 12444 return true; 12445 } 12446 12447 /** 12448 * Play a sound effect for this view. 12449 * 12450 * <p>The framework will play sound effects for some built in actions, such as 12451 * clicking, but you may wish to play these effects in your widget, 12452 * for instance, for internal navigation. 12453 * 12454 * <p>The sound effect will only be played if sound effects are enabled by the user, and 12455 * {@link #isSoundEffectsEnabled()} is true. 12456 * 12457 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 12458 */ 12459 public void playSoundEffect(int soundConstant) { 12460 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 12461 return; 12462 } 12463 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 12464 } 12465 12466 /** 12467 * BZZZTT!!1! 12468 * 12469 * <p>Provide haptic feedback to the user for this view. 12470 * 12471 * <p>The framework will provide haptic feedback for some built in actions, 12472 * such as long presses, but you may wish to provide feedback for your 12473 * own widget. 12474 * 12475 * <p>The feedback will only be performed if 12476 * {@link #isHapticFeedbackEnabled()} is true. 12477 * 12478 * @param feedbackConstant One of the constants defined in 12479 * {@link HapticFeedbackConstants} 12480 */ 12481 public boolean performHapticFeedback(int feedbackConstant) { 12482 return performHapticFeedback(feedbackConstant, 0); 12483 } 12484 12485 /** 12486 * BZZZTT!!1! 12487 * 12488 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 12489 * 12490 * @param feedbackConstant One of the constants defined in 12491 * {@link HapticFeedbackConstants} 12492 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 12493 */ 12494 public boolean performHapticFeedback(int feedbackConstant, int flags) { 12495 if (mAttachInfo == null) { 12496 return false; 12497 } 12498 //noinspection SimplifiableIfStatement 12499 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 12500 && !isHapticFeedbackEnabled()) { 12501 return false; 12502 } 12503 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 12504 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 12505 } 12506 12507 /** 12508 * Request that the visibility of the status bar be changed. 12509 * @param visibility Either {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}. 12510 */ 12511 public void setSystemUiVisibility(int visibility) { 12512 if (visibility != mSystemUiVisibility) { 12513 mSystemUiVisibility = visibility; 12514 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 12515 mParent.recomputeViewAttributes(this); 12516 } 12517 } 12518 } 12519 12520 /** 12521 * Returns the status bar visibility that this view has requested. 12522 * @return Either {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}. 12523 */ 12524 public int getSystemUiVisibility() { 12525 return mSystemUiVisibility; 12526 } 12527 12528 /** 12529 * Set a listener to receive callbacks when the visibility of the system bar changes. 12530 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 12531 */ 12532 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 12533 mOnSystemUiVisibilityChangeListener = l; 12534 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 12535 mParent.recomputeViewAttributes(this); 12536 } 12537 } 12538 12539 /** 12540 */ 12541 public void dispatchSystemUiVisibilityChanged(int visibility) { 12542 if (mOnSystemUiVisibilityChangeListener != null) { 12543 mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 12544 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 12545 } 12546 } 12547 12548 /** 12549 * Creates an image that the system displays during the drag and drop 12550 * operation. This is called a "drag shadow". The default implementation 12551 * for a DragShadowBuilder based on a View returns an image that has exactly the same 12552 * appearance as the given View. The default also positions the center of the drag shadow 12553 * directly under the touch point. If no View is provided (the constructor with no parameters 12554 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 12555 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 12556 * default is an invisible drag shadow. 12557 * <p> 12558 * You are not required to use the View you provide to the constructor as the basis of the 12559 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 12560 * anything you want as the drag shadow. 12561 * </p> 12562 * <p> 12563 * You pass a DragShadowBuilder object to the system when you start the drag. The system 12564 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 12565 * size and position of the drag shadow. It uses this data to construct a 12566 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 12567 * so that your application can draw the shadow image in the Canvas. 12568 * </p> 12569 */ 12570 public static class DragShadowBuilder { 12571 private final WeakReference<View> mView; 12572 12573 /** 12574 * Constructs a shadow image builder based on a View. By default, the resulting drag 12575 * shadow will have the same appearance and dimensions as the View, with the touch point 12576 * over the center of the View. 12577 * @param view A View. Any View in scope can be used. 12578 */ 12579 public DragShadowBuilder(View view) { 12580 mView = new WeakReference<View>(view); 12581 } 12582 12583 /** 12584 * Construct a shadow builder object with no associated View. This 12585 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 12586 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 12587 * to supply the drag shadow's dimensions and appearance without 12588 * reference to any View object. If they are not overridden, then the result is an 12589 * invisible drag shadow. 12590 */ 12591 public DragShadowBuilder() { 12592 mView = new WeakReference<View>(null); 12593 } 12594 12595 /** 12596 * Returns the View object that had been passed to the 12597 * {@link #View.DragShadowBuilder(View)} 12598 * constructor. If that View parameter was {@code null} or if the 12599 * {@link #View.DragShadowBuilder()} 12600 * constructor was used to instantiate the builder object, this method will return 12601 * null. 12602 * 12603 * @return The View object associate with this builder object. 12604 */ 12605 @SuppressWarnings({"JavadocReference"}) 12606 final public View getView() { 12607 return mView.get(); 12608 } 12609 12610 /** 12611 * Provides the metrics for the shadow image. These include the dimensions of 12612 * the shadow image, and the point within that shadow that should 12613 * be centered under the touch location while dragging. 12614 * <p> 12615 * The default implementation sets the dimensions of the shadow to be the 12616 * same as the dimensions of the View itself and centers the shadow under 12617 * the touch point. 12618 * </p> 12619 * 12620 * @param shadowSize A {@link android.graphics.Point} containing the width and height 12621 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 12622 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 12623 * image. 12624 * 12625 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 12626 * shadow image that should be underneath the touch point during the drag and drop 12627 * operation. Your application must set {@link android.graphics.Point#x} to the 12628 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 12629 */ 12630 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 12631 final View view = mView.get(); 12632 if (view != null) { 12633 shadowSize.set(view.getWidth(), view.getHeight()); 12634 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 12635 } else { 12636 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 12637 } 12638 } 12639 12640 /** 12641 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 12642 * based on the dimensions it received from the 12643 * {@link #onProvideShadowMetrics(Point, Point)} callback. 12644 * 12645 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 12646 */ 12647 public void onDrawShadow(Canvas canvas) { 12648 final View view = mView.get(); 12649 if (view != null) { 12650 view.draw(canvas); 12651 } else { 12652 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 12653 } 12654 } 12655 } 12656 12657 /** 12658 * Starts a drag and drop operation. When your application calls this method, it passes a 12659 * {@link android.view.View.DragShadowBuilder} object to the system. The 12660 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 12661 * to get metrics for the drag shadow, and then calls the object's 12662 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 12663 * <p> 12664 * Once the system has the drag shadow, it begins the drag and drop operation by sending 12665 * drag events to all the View objects in your application that are currently visible. It does 12666 * this either by calling the View object's drag listener (an implementation of 12667 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 12668 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 12669 * Both are passed a {@link android.view.DragEvent} object that has a 12670 * {@link android.view.DragEvent#getAction()} value of 12671 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 12672 * </p> 12673 * <p> 12674 * Your application can invoke startDrag() on any attached View object. The View object does not 12675 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 12676 * be related to the View the user selected for dragging. 12677 * </p> 12678 * @param data A {@link android.content.ClipData} object pointing to the data to be 12679 * transferred by the drag and drop operation. 12680 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 12681 * drag shadow. 12682 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 12683 * drop operation. This Object is put into every DragEvent object sent by the system during the 12684 * current drag. 12685 * <p> 12686 * myLocalState is a lightweight mechanism for the sending information from the dragged View 12687 * to the target Views. For example, it can contain flags that differentiate between a 12688 * a copy operation and a move operation. 12689 * </p> 12690 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 12691 * so the parameter should be set to 0. 12692 * @return {@code true} if the method completes successfully, or 12693 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 12694 * do a drag, and so no drag operation is in progress. 12695 */ 12696 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 12697 Object myLocalState, int flags) { 12698 if (ViewDebug.DEBUG_DRAG) { 12699 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 12700 } 12701 boolean okay = false; 12702 12703 Point shadowSize = new Point(); 12704 Point shadowTouchPoint = new Point(); 12705 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 12706 12707 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 12708 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 12709 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 12710 } 12711 12712 if (ViewDebug.DEBUG_DRAG) { 12713 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 12714 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 12715 } 12716 Surface surface = new Surface(); 12717 try { 12718 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 12719 flags, shadowSize.x, shadowSize.y, surface); 12720 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 12721 + " surface=" + surface); 12722 if (token != null) { 12723 Canvas canvas = surface.lockCanvas(null); 12724 try { 12725 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 12726 shadowBuilder.onDrawShadow(canvas); 12727 } finally { 12728 surface.unlockCanvasAndPost(canvas); 12729 } 12730 12731 final ViewRootImpl root = getViewRootImpl(); 12732 12733 // Cache the local state object for delivery with DragEvents 12734 root.setLocalDragState(myLocalState); 12735 12736 // repurpose 'shadowSize' for the last touch point 12737 root.getLastTouchPoint(shadowSize); 12738 12739 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 12740 shadowSize.x, shadowSize.y, 12741 shadowTouchPoint.x, shadowTouchPoint.y, data); 12742 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 12743 } 12744 } catch (Exception e) { 12745 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 12746 surface.destroy(); 12747 } 12748 12749 return okay; 12750 } 12751 12752 /** 12753 * Handles drag events sent by the system following a call to 12754 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 12755 *<p> 12756 * When the system calls this method, it passes a 12757 * {@link android.view.DragEvent} object. A call to 12758 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 12759 * in DragEvent. The method uses these to determine what is happening in the drag and drop 12760 * operation. 12761 * @param event The {@link android.view.DragEvent} sent by the system. 12762 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 12763 * in DragEvent, indicating the type of drag event represented by this object. 12764 * @return {@code true} if the method was successful, otherwise {@code false}. 12765 * <p> 12766 * The method should return {@code true} in response to an action type of 12767 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 12768 * operation. 12769 * </p> 12770 * <p> 12771 * The method should also return {@code true} in response to an action type of 12772 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 12773 * {@code false} if it didn't. 12774 * </p> 12775 */ 12776 public boolean onDragEvent(DragEvent event) { 12777 return false; 12778 } 12779 12780 /** 12781 * Detects if this View is enabled and has a drag event listener. 12782 * If both are true, then it calls the drag event listener with the 12783 * {@link android.view.DragEvent} it received. If the drag event listener returns 12784 * {@code true}, then dispatchDragEvent() returns {@code true}. 12785 * <p> 12786 * For all other cases, the method calls the 12787 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 12788 * method and returns its result. 12789 * </p> 12790 * <p> 12791 * This ensures that a drag event is always consumed, even if the View does not have a drag 12792 * event listener. However, if the View has a listener and the listener returns true, then 12793 * onDragEvent() is not called. 12794 * </p> 12795 */ 12796 public boolean dispatchDragEvent(DragEvent event) { 12797 //noinspection SimplifiableIfStatement 12798 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 12799 && mOnDragListener.onDrag(this, event)) { 12800 return true; 12801 } 12802 return onDragEvent(event); 12803 } 12804 12805 boolean canAcceptDrag() { 12806 return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0; 12807 } 12808 12809 /** 12810 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 12811 * it is ever exposed at all. 12812 * @hide 12813 */ 12814 public void onCloseSystemDialogs(String reason) { 12815 } 12816 12817 /** 12818 * Given a Drawable whose bounds have been set to draw into this view, 12819 * update a Region being computed for 12820 * {@link #gatherTransparentRegion(android.graphics.Region)} so 12821 * that any non-transparent parts of the Drawable are removed from the 12822 * given transparent region. 12823 * 12824 * @param dr The Drawable whose transparency is to be applied to the region. 12825 * @param region A Region holding the current transparency information, 12826 * where any parts of the region that are set are considered to be 12827 * transparent. On return, this region will be modified to have the 12828 * transparency information reduced by the corresponding parts of the 12829 * Drawable that are not transparent. 12830 * {@hide} 12831 */ 12832 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 12833 if (DBG) { 12834 Log.i("View", "Getting transparent region for: " + this); 12835 } 12836 final Region r = dr.getTransparentRegion(); 12837 final Rect db = dr.getBounds(); 12838 final AttachInfo attachInfo = mAttachInfo; 12839 if (r != null && attachInfo != null) { 12840 final int w = getRight()-getLeft(); 12841 final int h = getBottom()-getTop(); 12842 if (db.left > 0) { 12843 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 12844 r.op(0, 0, db.left, h, Region.Op.UNION); 12845 } 12846 if (db.right < w) { 12847 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 12848 r.op(db.right, 0, w, h, Region.Op.UNION); 12849 } 12850 if (db.top > 0) { 12851 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 12852 r.op(0, 0, w, db.top, Region.Op.UNION); 12853 } 12854 if (db.bottom < h) { 12855 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 12856 r.op(0, db.bottom, w, h, Region.Op.UNION); 12857 } 12858 final int[] location = attachInfo.mTransparentLocation; 12859 getLocationInWindow(location); 12860 r.translate(location[0], location[1]); 12861 region.op(r, Region.Op.INTERSECT); 12862 } else { 12863 region.op(db, Region.Op.DIFFERENCE); 12864 } 12865 } 12866 12867 private void checkForLongClick(int delayOffset) { 12868 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 12869 mHasPerformedLongPress = false; 12870 12871 if (mPendingCheckForLongPress == null) { 12872 mPendingCheckForLongPress = new CheckForLongPress(); 12873 } 12874 mPendingCheckForLongPress.rememberWindowAttachCount(); 12875 postDelayed(mPendingCheckForLongPress, 12876 ViewConfiguration.getLongPressTimeout() - delayOffset); 12877 } 12878 } 12879 12880 /** 12881 * Inflate a view from an XML resource. This convenience method wraps the {@link 12882 * LayoutInflater} class, which provides a full range of options for view inflation. 12883 * 12884 * @param context The Context object for your activity or application. 12885 * @param resource The resource ID to inflate 12886 * @param root A view group that will be the parent. Used to properly inflate the 12887 * layout_* parameters. 12888 * @see LayoutInflater 12889 */ 12890 public static View inflate(Context context, int resource, ViewGroup root) { 12891 LayoutInflater factory = LayoutInflater.from(context); 12892 return factory.inflate(resource, root); 12893 } 12894 12895 /** 12896 * Scroll the view with standard behavior for scrolling beyond the normal 12897 * content boundaries. Views that call this method should override 12898 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 12899 * results of an over-scroll operation. 12900 * 12901 * Views can use this method to handle any touch or fling-based scrolling. 12902 * 12903 * @param deltaX Change in X in pixels 12904 * @param deltaY Change in Y in pixels 12905 * @param scrollX Current X scroll value in pixels before applying deltaX 12906 * @param scrollY Current Y scroll value in pixels before applying deltaY 12907 * @param scrollRangeX Maximum content scroll range along the X axis 12908 * @param scrollRangeY Maximum content scroll range along the Y axis 12909 * @param maxOverScrollX Number of pixels to overscroll by in either direction 12910 * along the X axis. 12911 * @param maxOverScrollY Number of pixels to overscroll by in either direction 12912 * along the Y axis. 12913 * @param isTouchEvent true if this scroll operation is the result of a touch event. 12914 * @return true if scrolling was clamped to an over-scroll boundary along either 12915 * axis, false otherwise. 12916 */ 12917 @SuppressWarnings({"UnusedParameters"}) 12918 protected boolean overScrollBy(int deltaX, int deltaY, 12919 int scrollX, int scrollY, 12920 int scrollRangeX, int scrollRangeY, 12921 int maxOverScrollX, int maxOverScrollY, 12922 boolean isTouchEvent) { 12923 final int overScrollMode = mOverScrollMode; 12924 final boolean canScrollHorizontal = 12925 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 12926 final boolean canScrollVertical = 12927 computeVerticalScrollRange() > computeVerticalScrollExtent(); 12928 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 12929 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 12930 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 12931 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 12932 12933 int newScrollX = scrollX + deltaX; 12934 if (!overScrollHorizontal) { 12935 maxOverScrollX = 0; 12936 } 12937 12938 int newScrollY = scrollY + deltaY; 12939 if (!overScrollVertical) { 12940 maxOverScrollY = 0; 12941 } 12942 12943 // Clamp values if at the limits and record 12944 final int left = -maxOverScrollX; 12945 final int right = maxOverScrollX + scrollRangeX; 12946 final int top = -maxOverScrollY; 12947 final int bottom = maxOverScrollY + scrollRangeY; 12948 12949 boolean clampedX = false; 12950 if (newScrollX > right) { 12951 newScrollX = right; 12952 clampedX = true; 12953 } else if (newScrollX < left) { 12954 newScrollX = left; 12955 clampedX = true; 12956 } 12957 12958 boolean clampedY = false; 12959 if (newScrollY > bottom) { 12960 newScrollY = bottom; 12961 clampedY = true; 12962 } else if (newScrollY < top) { 12963 newScrollY = top; 12964 clampedY = true; 12965 } 12966 12967 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 12968 12969 return clampedX || clampedY; 12970 } 12971 12972 /** 12973 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 12974 * respond to the results of an over-scroll operation. 12975 * 12976 * @param scrollX New X scroll value in pixels 12977 * @param scrollY New Y scroll value in pixels 12978 * @param clampedX True if scrollX was clamped to an over-scroll boundary 12979 * @param clampedY True if scrollY was clamped to an over-scroll boundary 12980 */ 12981 protected void onOverScrolled(int scrollX, int scrollY, 12982 boolean clampedX, boolean clampedY) { 12983 // Intentionally empty. 12984 } 12985 12986 /** 12987 * Returns the over-scroll mode for this view. The result will be 12988 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 12989 * (allow over-scrolling only if the view content is larger than the container), 12990 * or {@link #OVER_SCROLL_NEVER}. 12991 * 12992 * @return This view's over-scroll mode. 12993 */ 12994 public int getOverScrollMode() { 12995 return mOverScrollMode; 12996 } 12997 12998 /** 12999 * Set the over-scroll mode for this view. Valid over-scroll modes are 13000 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 13001 * (allow over-scrolling only if the view content is larger than the container), 13002 * or {@link #OVER_SCROLL_NEVER}. 13003 * 13004 * Setting the over-scroll mode of a view will have an effect only if the 13005 * view is capable of scrolling. 13006 * 13007 * @param overScrollMode The new over-scroll mode for this view. 13008 */ 13009 public void setOverScrollMode(int overScrollMode) { 13010 if (overScrollMode != OVER_SCROLL_ALWAYS && 13011 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 13012 overScrollMode != OVER_SCROLL_NEVER) { 13013 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 13014 } 13015 mOverScrollMode = overScrollMode; 13016 } 13017 13018 /** 13019 * Gets a scale factor that determines the distance the view should scroll 13020 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 13021 * @return The vertical scroll scale factor. 13022 * @hide 13023 */ 13024 protected float getVerticalScrollFactor() { 13025 if (mVerticalScrollFactor == 0) { 13026 TypedValue outValue = new TypedValue(); 13027 if (!mContext.getTheme().resolveAttribute( 13028 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 13029 throw new IllegalStateException( 13030 "Expected theme to define listPreferredItemHeight."); 13031 } 13032 mVerticalScrollFactor = outValue.getDimension( 13033 mContext.getResources().getDisplayMetrics()); 13034 } 13035 return mVerticalScrollFactor; 13036 } 13037 13038 /** 13039 * Gets a scale factor that determines the distance the view should scroll 13040 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 13041 * @return The horizontal scroll scale factor. 13042 * @hide 13043 */ 13044 protected float getHorizontalScrollFactor() { 13045 // TODO: Should use something else. 13046 return getVerticalScrollFactor(); 13047 } 13048 13049 /** 13050 * Return the value specifying the text direction or policy that was set with 13051 * {@link #setTextDirection(int)}. 13052 * 13053 * @return the defined text direction. It can be one of: 13054 * 13055 * {@link #TEXT_DIRECTION_INHERIT}, 13056 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13057 * {@link #TEXT_DIRECTION_ANY_RTL}, 13058 * {@link #TEXT_DIRECTION_CHAR_COUNT}, 13059 * {@link #TEXT_DIRECTION_LTR}, 13060 * {@link #TEXT_DIRECTION_RTL}, 13061 * 13062 * @hide 13063 */ 13064 public int getTextDirection() { 13065 return mTextDirection; 13066 } 13067 13068 /** 13069 * Set the text direction. 13070 * 13071 * @param textDirection the direction to set. Should be one of: 13072 * 13073 * {@link #TEXT_DIRECTION_INHERIT}, 13074 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13075 * {@link #TEXT_DIRECTION_ANY_RTL}, 13076 * {@link #TEXT_DIRECTION_CHAR_COUNT}, 13077 * {@link #TEXT_DIRECTION_LTR}, 13078 * {@link #TEXT_DIRECTION_RTL}, 13079 * 13080 * @hide 13081 */ 13082 public void setTextDirection(int textDirection) { 13083 if (textDirection != mTextDirection) { 13084 mTextDirection = textDirection; 13085 resetResolvedTextDirection(); 13086 requestLayout(); 13087 } 13088 } 13089 13090 /** 13091 * Return the resolved text direction. 13092 * 13093 * @return the resolved text direction. Return one of: 13094 * 13095 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13096 * {@link #TEXT_DIRECTION_ANY_RTL}, 13097 * {@link #TEXT_DIRECTION_CHAR_COUNT}, 13098 * {@link #TEXT_DIRECTION_LTR}, 13099 * {@link #TEXT_DIRECTION_RTL}, 13100 * 13101 * @hide 13102 */ 13103 public int getResolvedTextDirection() { 13104 if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) { 13105 resolveTextDirection(); 13106 } 13107 return mResolvedTextDirection; 13108 } 13109 13110 /** 13111 * Resolve the text direction. 13112 */ 13113 protected void resolveTextDirection() { 13114 if (mTextDirection != TEXT_DIRECTION_INHERIT) { 13115 mResolvedTextDirection = mTextDirection; 13116 return; 13117 } 13118 if (mParent != null && mParent instanceof ViewGroup) { 13119 mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection(); 13120 return; 13121 } 13122 mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG; 13123 } 13124 13125 /** 13126 * Reset resolved text direction. Will be resolved during a call to getResolvedTextDirection(). 13127 */ 13128 protected void resetResolvedTextDirection() { 13129 mResolvedTextDirection = TEXT_DIRECTION_INHERIT; 13130 } 13131 13132 // 13133 // Properties 13134 // 13135 /** 13136 * A Property wrapper around the <code>alpha</code> functionality handled by the 13137 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 13138 */ 13139 public static Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 13140 @Override 13141 public void setValue(View object, float value) { 13142 object.setAlpha(value); 13143 } 13144 13145 @Override 13146 public Float get(View object) { 13147 return object.getAlpha(); 13148 } 13149 }; 13150 13151 /** 13152 * A Property wrapper around the <code>translationX</code> functionality handled by the 13153 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 13154 */ 13155 public static Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 13156 @Override 13157 public void setValue(View object, float value) { 13158 object.setTranslationX(value); 13159 } 13160 13161 @Override 13162 public Float get(View object) { 13163 return object.getTranslationX(); 13164 } 13165 }; 13166 13167 /** 13168 * A Property wrapper around the <code>translationY</code> functionality handled by the 13169 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 13170 */ 13171 public static Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 13172 @Override 13173 public void setValue(View object, float value) { 13174 object.setTranslationY(value); 13175 } 13176 13177 @Override 13178 public Float get(View object) { 13179 return object.getTranslationY(); 13180 } 13181 }; 13182 13183 /** 13184 * A Property wrapper around the <code>x</code> functionality handled by the 13185 * {@link View#setX(float)} and {@link View#getX()} methods. 13186 */ 13187 public static Property<View, Float> X = new FloatProperty<View>("x") { 13188 @Override 13189 public void setValue(View object, float value) { 13190 object.setX(value); 13191 } 13192 13193 @Override 13194 public Float get(View object) { 13195 return object.getX(); 13196 } 13197 }; 13198 13199 /** 13200 * A Property wrapper around the <code>y</code> functionality handled by the 13201 * {@link View#setY(float)} and {@link View#getY()} methods. 13202 */ 13203 public static Property<View, Float> Y = new FloatProperty<View>("y") { 13204 @Override 13205 public void setValue(View object, float value) { 13206 object.setY(value); 13207 } 13208 13209 @Override 13210 public Float get(View object) { 13211 return object.getY(); 13212 } 13213 }; 13214 13215 /** 13216 * A Property wrapper around the <code>rotation</code> functionality handled by the 13217 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 13218 */ 13219 public static Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 13220 @Override 13221 public void setValue(View object, float value) { 13222 object.setRotation(value); 13223 } 13224 13225 @Override 13226 public Float get(View object) { 13227 return object.getRotation(); 13228 } 13229 }; 13230 13231 /** 13232 * A Property wrapper around the <code>rotationX</code> functionality handled by the 13233 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 13234 */ 13235 public static Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 13236 @Override 13237 public void setValue(View object, float value) { 13238 object.setRotationX(value); 13239 } 13240 13241 @Override 13242 public Float get(View object) { 13243 return object.getRotationX(); 13244 } 13245 }; 13246 13247 /** 13248 * A Property wrapper around the <code>rotationY</code> functionality handled by the 13249 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 13250 */ 13251 public static Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 13252 @Override 13253 public void setValue(View object, float value) { 13254 object.setRotationY(value); 13255 } 13256 13257 @Override 13258 public Float get(View object) { 13259 return object.getRotationY(); 13260 } 13261 }; 13262 13263 /** 13264 * A Property wrapper around the <code>scaleX</code> functionality handled by the 13265 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 13266 */ 13267 public static Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 13268 @Override 13269 public void setValue(View object, float value) { 13270 object.setScaleX(value); 13271 } 13272 13273 @Override 13274 public Float get(View object) { 13275 return object.getScaleX(); 13276 } 13277 }; 13278 13279 /** 13280 * A Property wrapper around the <code>scaleY</code> functionality handled by the 13281 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 13282 */ 13283 public static Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 13284 @Override 13285 public void setValue(View object, float value) { 13286 object.setScaleY(value); 13287 } 13288 13289 @Override 13290 public Float get(View object) { 13291 return object.getScaleY(); 13292 } 13293 }; 13294 13295 /** 13296 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 13297 * Each MeasureSpec represents a requirement for either the width or the height. 13298 * A MeasureSpec is comprised of a size and a mode. There are three possible 13299 * modes: 13300 * <dl> 13301 * <dt>UNSPECIFIED</dt> 13302 * <dd> 13303 * The parent has not imposed any constraint on the child. It can be whatever size 13304 * it wants. 13305 * </dd> 13306 * 13307 * <dt>EXACTLY</dt> 13308 * <dd> 13309 * The parent has determined an exact size for the child. The child is going to be 13310 * given those bounds regardless of how big it wants to be. 13311 * </dd> 13312 * 13313 * <dt>AT_MOST</dt> 13314 * <dd> 13315 * The child can be as large as it wants up to the specified size. 13316 * </dd> 13317 * </dl> 13318 * 13319 * MeasureSpecs are implemented as ints to reduce object allocation. This class 13320 * is provided to pack and unpack the <size, mode> tuple into the int. 13321 */ 13322 public static class MeasureSpec { 13323 private static final int MODE_SHIFT = 30; 13324 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 13325 13326 /** 13327 * Measure specification mode: The parent has not imposed any constraint 13328 * on the child. It can be whatever size it wants. 13329 */ 13330 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 13331 13332 /** 13333 * Measure specification mode: The parent has determined an exact size 13334 * for the child. The child is going to be given those bounds regardless 13335 * of how big it wants to be. 13336 */ 13337 public static final int EXACTLY = 1 << MODE_SHIFT; 13338 13339 /** 13340 * Measure specification mode: The child can be as large as it wants up 13341 * to the specified size. 13342 */ 13343 public static final int AT_MOST = 2 << MODE_SHIFT; 13344 13345 /** 13346 * Creates a measure specification based on the supplied size and mode. 13347 * 13348 * The mode must always be one of the following: 13349 * <ul> 13350 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 13351 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 13352 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 13353 * </ul> 13354 * 13355 * @param size the size of the measure specification 13356 * @param mode the mode of the measure specification 13357 * @return the measure specification based on size and mode 13358 */ 13359 public static int makeMeasureSpec(int size, int mode) { 13360 return size + mode; 13361 } 13362 13363 /** 13364 * Extracts the mode from the supplied measure specification. 13365 * 13366 * @param measureSpec the measure specification to extract the mode from 13367 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 13368 * {@link android.view.View.MeasureSpec#AT_MOST} or 13369 * {@link android.view.View.MeasureSpec#EXACTLY} 13370 */ 13371 public static int getMode(int measureSpec) { 13372 return (measureSpec & MODE_MASK); 13373 } 13374 13375 /** 13376 * Extracts the size from the supplied measure specification. 13377 * 13378 * @param measureSpec the measure specification to extract the size from 13379 * @return the size in pixels defined in the supplied measure specification 13380 */ 13381 public static int getSize(int measureSpec) { 13382 return (measureSpec & ~MODE_MASK); 13383 } 13384 13385 /** 13386 * Returns a String representation of the specified measure 13387 * specification. 13388 * 13389 * @param measureSpec the measure specification to convert to a String 13390 * @return a String with the following format: "MeasureSpec: MODE SIZE" 13391 */ 13392 public static String toString(int measureSpec) { 13393 int mode = getMode(measureSpec); 13394 int size = getSize(measureSpec); 13395 13396 StringBuilder sb = new StringBuilder("MeasureSpec: "); 13397 13398 if (mode == UNSPECIFIED) 13399 sb.append("UNSPECIFIED "); 13400 else if (mode == EXACTLY) 13401 sb.append("EXACTLY "); 13402 else if (mode == AT_MOST) 13403 sb.append("AT_MOST "); 13404 else 13405 sb.append(mode).append(" "); 13406 13407 sb.append(size); 13408 return sb.toString(); 13409 } 13410 } 13411 13412 class CheckForLongPress implements Runnable { 13413 13414 private int mOriginalWindowAttachCount; 13415 13416 public void run() { 13417 if (isPressed() && (mParent != null) 13418 && mOriginalWindowAttachCount == mWindowAttachCount) { 13419 if (performLongClick()) { 13420 mHasPerformedLongPress = true; 13421 } 13422 } 13423 } 13424 13425 public void rememberWindowAttachCount() { 13426 mOriginalWindowAttachCount = mWindowAttachCount; 13427 } 13428 } 13429 13430 private final class CheckForTap implements Runnable { 13431 public void run() { 13432 mPrivateFlags &= ~PREPRESSED; 13433 mPrivateFlags |= PRESSED; 13434 refreshDrawableState(); 13435 checkForLongClick(ViewConfiguration.getTapTimeout()); 13436 } 13437 } 13438 13439 private final class PerformClick implements Runnable { 13440 public void run() { 13441 performClick(); 13442 } 13443 } 13444 13445 /** @hide */ 13446 public void hackTurnOffWindowResizeAnim(boolean off) { 13447 mAttachInfo.mTurnOffWindowResizeAnim = off; 13448 } 13449 13450 /** 13451 * This method returns a ViewPropertyAnimator object, which can be used to animate 13452 * specific properties on this View. 13453 * 13454 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 13455 */ 13456 public ViewPropertyAnimator animate() { 13457 if (mAnimator == null) { 13458 mAnimator = new ViewPropertyAnimator(this); 13459 } 13460 return mAnimator; 13461 } 13462 13463 /** 13464 * Interface definition for a callback to be invoked when a key event is 13465 * dispatched to this view. The callback will be invoked before the key 13466 * event is given to the view. 13467 */ 13468 public interface OnKeyListener { 13469 /** 13470 * Called when a key is dispatched to a view. This allows listeners to 13471 * get a chance to respond before the target view. 13472 * 13473 * @param v The view the key has been dispatched to. 13474 * @param keyCode The code for the physical key that was pressed 13475 * @param event The KeyEvent object containing full information about 13476 * the event. 13477 * @return True if the listener has consumed the event, false otherwise. 13478 */ 13479 boolean onKey(View v, int keyCode, KeyEvent event); 13480 } 13481 13482 /** 13483 * Interface definition for a callback to be invoked when a touch event is 13484 * dispatched to this view. The callback will be invoked before the touch 13485 * event is given to the view. 13486 */ 13487 public interface OnTouchListener { 13488 /** 13489 * Called when a touch event is dispatched to a view. This allows listeners to 13490 * get a chance to respond before the target view. 13491 * 13492 * @param v The view the touch event has been dispatched to. 13493 * @param event The MotionEvent object containing full information about 13494 * the event. 13495 * @return True if the listener has consumed the event, false otherwise. 13496 */ 13497 boolean onTouch(View v, MotionEvent event); 13498 } 13499 13500 /** 13501 * Interface definition for a callback to be invoked when a hover event is 13502 * dispatched to this view. The callback will be invoked before the hover 13503 * event is given to the view. 13504 */ 13505 public interface OnHoverListener { 13506 /** 13507 * Called when a hover event is dispatched to a view. This allows listeners to 13508 * get a chance to respond before the target view. 13509 * 13510 * @param v The view the hover event has been dispatched to. 13511 * @param event The MotionEvent object containing full information about 13512 * the event. 13513 * @return True if the listener has consumed the event, false otherwise. 13514 */ 13515 boolean onHover(View v, MotionEvent event); 13516 } 13517 13518 /** 13519 * Interface definition for a callback to be invoked when a generic motion event is 13520 * dispatched to this view. The callback will be invoked before the generic motion 13521 * event is given to the view. 13522 */ 13523 public interface OnGenericMotionListener { 13524 /** 13525 * Called when a generic motion event is dispatched to a view. This allows listeners to 13526 * get a chance to respond before the target view. 13527 * 13528 * @param v The view the generic motion event has been dispatched to. 13529 * @param event The MotionEvent object containing full information about 13530 * the event. 13531 * @return True if the listener has consumed the event, false otherwise. 13532 */ 13533 boolean onGenericMotion(View v, MotionEvent event); 13534 } 13535 13536 /** 13537 * Interface definition for a callback to be invoked when a view has been clicked and held. 13538 */ 13539 public interface OnLongClickListener { 13540 /** 13541 * Called when a view has been clicked and held. 13542 * 13543 * @param v The view that was clicked and held. 13544 * 13545 * @return true if the callback consumed the long click, false otherwise. 13546 */ 13547 boolean onLongClick(View v); 13548 } 13549 13550 /** 13551 * Interface definition for a callback to be invoked when a drag is being dispatched 13552 * to this view. The callback will be invoked before the hosting view's own 13553 * onDrag(event) method. If the listener wants to fall back to the hosting view's 13554 * onDrag(event) behavior, it should return 'false' from this callback. 13555 */ 13556 public interface OnDragListener { 13557 /** 13558 * Called when a drag event is dispatched to a view. This allows listeners 13559 * to get a chance to override base View behavior. 13560 * 13561 * @param v The View that received the drag event. 13562 * @param event The {@link android.view.DragEvent} object for the drag event. 13563 * @return {@code true} if the drag event was handled successfully, or {@code false} 13564 * if the drag event was not handled. Note that {@code false} will trigger the View 13565 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 13566 */ 13567 boolean onDrag(View v, DragEvent event); 13568 } 13569 13570 /** 13571 * Interface definition for a callback to be invoked when the focus state of 13572 * a view changed. 13573 */ 13574 public interface OnFocusChangeListener { 13575 /** 13576 * Called when the focus state of a view has changed. 13577 * 13578 * @param v The view whose state has changed. 13579 * @param hasFocus The new focus state of v. 13580 */ 13581 void onFocusChange(View v, boolean hasFocus); 13582 } 13583 13584 /** 13585 * Interface definition for a callback to be invoked when a view is clicked. 13586 */ 13587 public interface OnClickListener { 13588 /** 13589 * Called when a view has been clicked. 13590 * 13591 * @param v The view that was clicked. 13592 */ 13593 void onClick(View v); 13594 } 13595 13596 /** 13597 * Interface definition for a callback to be invoked when the context menu 13598 * for this view is being built. 13599 */ 13600 public interface OnCreateContextMenuListener { 13601 /** 13602 * Called when the context menu for this view is being built. It is not 13603 * safe to hold onto the menu after this method returns. 13604 * 13605 * @param menu The context menu that is being built 13606 * @param v The view for which the context menu is being built 13607 * @param menuInfo Extra information about the item for which the 13608 * context menu should be shown. This information will vary 13609 * depending on the class of v. 13610 */ 13611 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 13612 } 13613 13614 /** 13615 * Interface definition for a callback to be invoked when the status bar changes 13616 * visibility. 13617 * 13618 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 13619 */ 13620 public interface OnSystemUiVisibilityChangeListener { 13621 /** 13622 * Called when the status bar changes visibility because of a call to 13623 * {@link View#setSystemUiVisibility(int)}. 13624 * 13625 * @param visibility {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}. 13626 */ 13627 public void onSystemUiVisibilityChange(int visibility); 13628 } 13629 13630 /** 13631 * Interface definition for a callback to be invoked when this view is attached 13632 * or detached from its window. 13633 */ 13634 public interface OnAttachStateChangeListener { 13635 /** 13636 * Called when the view is attached to a window. 13637 * @param v The view that was attached 13638 */ 13639 public void onViewAttachedToWindow(View v); 13640 /** 13641 * Called when the view is detached from a window. 13642 * @param v The view that was detached 13643 */ 13644 public void onViewDetachedFromWindow(View v); 13645 } 13646 13647 private final class UnsetPressedState implements Runnable { 13648 public void run() { 13649 setPressed(false); 13650 } 13651 } 13652 13653 /** 13654 * Base class for derived classes that want to save and restore their own 13655 * state in {@link android.view.View#onSaveInstanceState()}. 13656 */ 13657 public static class BaseSavedState extends AbsSavedState { 13658 /** 13659 * Constructor used when reading from a parcel. Reads the state of the superclass. 13660 * 13661 * @param source 13662 */ 13663 public BaseSavedState(Parcel source) { 13664 super(source); 13665 } 13666 13667 /** 13668 * Constructor called by derived classes when creating their SavedState objects 13669 * 13670 * @param superState The state of the superclass of this view 13671 */ 13672 public BaseSavedState(Parcelable superState) { 13673 super(superState); 13674 } 13675 13676 public static final Parcelable.Creator<BaseSavedState> CREATOR = 13677 new Parcelable.Creator<BaseSavedState>() { 13678 public BaseSavedState createFromParcel(Parcel in) { 13679 return new BaseSavedState(in); 13680 } 13681 13682 public BaseSavedState[] newArray(int size) { 13683 return new BaseSavedState[size]; 13684 } 13685 }; 13686 } 13687 13688 /** 13689 * A set of information given to a view when it is attached to its parent 13690 * window. 13691 */ 13692 static class AttachInfo { 13693 interface Callbacks { 13694 void playSoundEffect(int effectId); 13695 boolean performHapticFeedback(int effectId, boolean always); 13696 } 13697 13698 /** 13699 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 13700 * to a Handler. This class contains the target (View) to invalidate and 13701 * the coordinates of the dirty rectangle. 13702 * 13703 * For performance purposes, this class also implements a pool of up to 13704 * POOL_LIMIT objects that get reused. This reduces memory allocations 13705 * whenever possible. 13706 */ 13707 static class InvalidateInfo implements Poolable<InvalidateInfo> { 13708 private static final int POOL_LIMIT = 10; 13709 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 13710 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 13711 public InvalidateInfo newInstance() { 13712 return new InvalidateInfo(); 13713 } 13714 13715 public void onAcquired(InvalidateInfo element) { 13716 } 13717 13718 public void onReleased(InvalidateInfo element) { 13719 } 13720 }, POOL_LIMIT) 13721 ); 13722 13723 private InvalidateInfo mNext; 13724 private boolean mIsPooled; 13725 13726 View target; 13727 13728 int left; 13729 int top; 13730 int right; 13731 int bottom; 13732 13733 public void setNextPoolable(InvalidateInfo element) { 13734 mNext = element; 13735 } 13736 13737 public InvalidateInfo getNextPoolable() { 13738 return mNext; 13739 } 13740 13741 static InvalidateInfo acquire() { 13742 return sPool.acquire(); 13743 } 13744 13745 void release() { 13746 sPool.release(this); 13747 } 13748 13749 public boolean isPooled() { 13750 return mIsPooled; 13751 } 13752 13753 public void setPooled(boolean isPooled) { 13754 mIsPooled = isPooled; 13755 } 13756 } 13757 13758 final IWindowSession mSession; 13759 13760 final IWindow mWindow; 13761 13762 final IBinder mWindowToken; 13763 13764 final Callbacks mRootCallbacks; 13765 13766 HardwareCanvas mHardwareCanvas; 13767 13768 /** 13769 * The top view of the hierarchy. 13770 */ 13771 View mRootView; 13772 13773 IBinder mPanelParentWindowToken; 13774 Surface mSurface; 13775 13776 boolean mHardwareAccelerated; 13777 boolean mHardwareAccelerationRequested; 13778 HardwareRenderer mHardwareRenderer; 13779 13780 /** 13781 * Scale factor used by the compatibility mode 13782 */ 13783 float mApplicationScale; 13784 13785 /** 13786 * Indicates whether the application is in compatibility mode 13787 */ 13788 boolean mScalingRequired; 13789 13790 /** 13791 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 13792 */ 13793 boolean mTurnOffWindowResizeAnim; 13794 13795 /** 13796 * Left position of this view's window 13797 */ 13798 int mWindowLeft; 13799 13800 /** 13801 * Top position of this view's window 13802 */ 13803 int mWindowTop; 13804 13805 /** 13806 * Indicates whether views need to use 32-bit drawing caches 13807 */ 13808 boolean mUse32BitDrawingCache; 13809 13810 /** 13811 * For windows that are full-screen but using insets to layout inside 13812 * of the screen decorations, these are the current insets for the 13813 * content of the window. 13814 */ 13815 final Rect mContentInsets = new Rect(); 13816 13817 /** 13818 * For windows that are full-screen but using insets to layout inside 13819 * of the screen decorations, these are the current insets for the 13820 * actual visible parts of the window. 13821 */ 13822 final Rect mVisibleInsets = new Rect(); 13823 13824 /** 13825 * The internal insets given by this window. This value is 13826 * supplied by the client (through 13827 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 13828 * be given to the window manager when changed to be used in laying 13829 * out windows behind it. 13830 */ 13831 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 13832 = new ViewTreeObserver.InternalInsetsInfo(); 13833 13834 /** 13835 * All views in the window's hierarchy that serve as scroll containers, 13836 * used to determine if the window can be resized or must be panned 13837 * to adjust for a soft input area. 13838 */ 13839 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 13840 13841 final KeyEvent.DispatcherState mKeyDispatchState 13842 = new KeyEvent.DispatcherState(); 13843 13844 /** 13845 * Indicates whether the view's window currently has the focus. 13846 */ 13847 boolean mHasWindowFocus; 13848 13849 /** 13850 * The current visibility of the window. 13851 */ 13852 int mWindowVisibility; 13853 13854 /** 13855 * Indicates the time at which drawing started to occur. 13856 */ 13857 long mDrawingTime; 13858 13859 /** 13860 * Indicates whether or not ignoring the DIRTY_MASK flags. 13861 */ 13862 boolean mIgnoreDirtyState; 13863 13864 /** 13865 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 13866 * to avoid clearing that flag prematurely. 13867 */ 13868 boolean mSetIgnoreDirtyState = false; 13869 13870 /** 13871 * Indicates whether the view's window is currently in touch mode. 13872 */ 13873 boolean mInTouchMode; 13874 13875 /** 13876 * Indicates that ViewAncestor should trigger a global layout change 13877 * the next time it performs a traversal 13878 */ 13879 boolean mRecomputeGlobalAttributes; 13880 13881 /** 13882 * Set during a traveral if any views want to keep the screen on. 13883 */ 13884 boolean mKeepScreenOn; 13885 13886 /** 13887 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 13888 */ 13889 int mSystemUiVisibility; 13890 13891 /** 13892 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 13893 * attached. 13894 */ 13895 boolean mHasSystemUiListeners; 13896 13897 /** 13898 * Set if the visibility of any views has changed. 13899 */ 13900 boolean mViewVisibilityChanged; 13901 13902 /** 13903 * Set to true if a view has been scrolled. 13904 */ 13905 boolean mViewScrollChanged; 13906 13907 /** 13908 * Global to the view hierarchy used as a temporary for dealing with 13909 * x/y points in the transparent region computations. 13910 */ 13911 final int[] mTransparentLocation = new int[2]; 13912 13913 /** 13914 * Global to the view hierarchy used as a temporary for dealing with 13915 * x/y points in the ViewGroup.invalidateChild implementation. 13916 */ 13917 final int[] mInvalidateChildLocation = new int[2]; 13918 13919 13920 /** 13921 * Global to the view hierarchy used as a temporary for dealing with 13922 * x/y location when view is transformed. 13923 */ 13924 final float[] mTmpTransformLocation = new float[2]; 13925 13926 /** 13927 * The view tree observer used to dispatch global events like 13928 * layout, pre-draw, touch mode change, etc. 13929 */ 13930 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 13931 13932 /** 13933 * A Canvas used by the view hierarchy to perform bitmap caching. 13934 */ 13935 Canvas mCanvas; 13936 13937 /** 13938 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 13939 * handler can be used to pump events in the UI events queue. 13940 */ 13941 final Handler mHandler; 13942 13943 /** 13944 * Identifier for messages requesting the view to be invalidated. 13945 * Such messages should be sent to {@link #mHandler}. 13946 */ 13947 static final int INVALIDATE_MSG = 0x1; 13948 13949 /** 13950 * Identifier for messages requesting the view to invalidate a region. 13951 * Such messages should be sent to {@link #mHandler}. 13952 */ 13953 static final int INVALIDATE_RECT_MSG = 0x2; 13954 13955 /** 13956 * Temporary for use in computing invalidate rectangles while 13957 * calling up the hierarchy. 13958 */ 13959 final Rect mTmpInvalRect = new Rect(); 13960 13961 /** 13962 * Temporary for use in computing hit areas with transformed views 13963 */ 13964 final RectF mTmpTransformRect = new RectF(); 13965 13966 /** 13967 * Temporary list for use in collecting focusable descendents of a view. 13968 */ 13969 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 13970 13971 /** 13972 * The id of the window for accessibility purposes. 13973 */ 13974 int mAccessibilityWindowId = View.NO_ID; 13975 13976 /** 13977 * Creates a new set of attachment information with the specified 13978 * events handler and thread. 13979 * 13980 * @param handler the events handler the view must use 13981 */ 13982 AttachInfo(IWindowSession session, IWindow window, 13983 Handler handler, Callbacks effectPlayer) { 13984 mSession = session; 13985 mWindow = window; 13986 mWindowToken = window.asBinder(); 13987 mHandler = handler; 13988 mRootCallbacks = effectPlayer; 13989 } 13990 } 13991 13992 /** 13993 * <p>ScrollabilityCache holds various fields used by a View when scrolling 13994 * is supported. This avoids keeping too many unused fields in most 13995 * instances of View.</p> 13996 */ 13997 private static class ScrollabilityCache implements Runnable { 13998 13999 /** 14000 * Scrollbars are not visible 14001 */ 14002 public static final int OFF = 0; 14003 14004 /** 14005 * Scrollbars are visible 14006 */ 14007 public static final int ON = 1; 14008 14009 /** 14010 * Scrollbars are fading away 14011 */ 14012 public static final int FADING = 2; 14013 14014 public boolean fadeScrollBars; 14015 14016 public int fadingEdgeLength; 14017 public int scrollBarDefaultDelayBeforeFade; 14018 public int scrollBarFadeDuration; 14019 14020 public int scrollBarSize; 14021 public ScrollBarDrawable scrollBar; 14022 public float[] interpolatorValues; 14023 public View host; 14024 14025 public final Paint paint; 14026 public final Matrix matrix; 14027 public Shader shader; 14028 14029 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 14030 14031 private static final float[] OPAQUE = { 255 }; 14032 private static final float[] TRANSPARENT = { 0.0f }; 14033 14034 /** 14035 * When fading should start. This time moves into the future every time 14036 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 14037 */ 14038 public long fadeStartTime; 14039 14040 14041 /** 14042 * The current state of the scrollbars: ON, OFF, or FADING 14043 */ 14044 public int state = OFF; 14045 14046 private int mLastColor; 14047 14048 public ScrollabilityCache(ViewConfiguration configuration, View host) { 14049 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 14050 scrollBarSize = configuration.getScaledScrollBarSize(); 14051 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 14052 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 14053 14054 paint = new Paint(); 14055 matrix = new Matrix(); 14056 // use use a height of 1, and then wack the matrix each time we 14057 // actually use it. 14058 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 14059 14060 paint.setShader(shader); 14061 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 14062 this.host = host; 14063 } 14064 14065 public void setFadeColor(int color) { 14066 if (color != 0 && color != mLastColor) { 14067 mLastColor = color; 14068 color |= 0xFF000000; 14069 14070 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 14071 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 14072 14073 paint.setShader(shader); 14074 // Restore the default transfer mode (src_over) 14075 paint.setXfermode(null); 14076 } 14077 } 14078 14079 public void run() { 14080 long now = AnimationUtils.currentAnimationTimeMillis(); 14081 if (now >= fadeStartTime) { 14082 14083 // the animation fades the scrollbars out by changing 14084 // the opacity (alpha) from fully opaque to fully 14085 // transparent 14086 int nextFrame = (int) now; 14087 int framesCount = 0; 14088 14089 Interpolator interpolator = scrollBarInterpolator; 14090 14091 // Start opaque 14092 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 14093 14094 // End transparent 14095 nextFrame += scrollBarFadeDuration; 14096 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 14097 14098 state = FADING; 14099 14100 // Kick off the fade animation 14101 host.invalidate(true); 14102 } 14103 } 14104 } 14105 14106 /** 14107 * Resuable callback for sending 14108 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 14109 */ 14110 private class SendViewScrolledAccessibilityEvent implements Runnable { 14111 public volatile boolean mIsPending; 14112 14113 public void run() { 14114 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 14115 mIsPending = false; 14116 } 14117 } 14118} 14119