View.java revision 4212d3fc736712d6e5fb69d5067ce8d9a83806ef
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.content.ClipData; 20import android.content.Context; 21import android.content.res.Configuration; 22import android.content.res.Resources; 23import android.content.res.TypedArray; 24import android.graphics.Bitmap; 25import android.graphics.Camera; 26import android.graphics.Canvas; 27import android.graphics.Interpolator; 28import android.graphics.LinearGradient; 29import android.graphics.Matrix; 30import android.graphics.Paint; 31import android.graphics.PixelFormat; 32import android.graphics.Point; 33import android.graphics.PorterDuff; 34import android.graphics.PorterDuffXfermode; 35import android.graphics.Rect; 36import android.graphics.RectF; 37import android.graphics.Region; 38import android.graphics.Shader; 39import android.graphics.drawable.ColorDrawable; 40import android.graphics.drawable.Drawable; 41import android.os.Handler; 42import android.os.IBinder; 43import android.os.Message; 44import android.os.Parcel; 45import android.os.Parcelable; 46import android.os.RemoteException; 47import android.os.SystemClock; 48import android.text.TextUtils; 49import android.util.AttributeSet; 50import android.util.FloatProperty; 51import android.util.LocaleUtil; 52import android.util.Log; 53import android.util.Pool; 54import android.util.Poolable; 55import android.util.PoolableManager; 56import android.util.Pools; 57import android.util.Property; 58import android.util.SparseArray; 59import android.util.TypedValue; 60import android.view.ContextMenu.ContextMenuInfo; 61import android.view.accessibility.AccessibilityEvent; 62import android.view.accessibility.AccessibilityEventSource; 63import android.view.accessibility.AccessibilityManager; 64import android.view.accessibility.AccessibilityNodeInfo; 65import android.view.accessibility.AccessibilityNodeProvider; 66import android.view.animation.Animation; 67import android.view.animation.AnimationUtils; 68import android.view.animation.Transformation; 69import android.view.inputmethod.EditorInfo; 70import android.view.inputmethod.InputConnection; 71import android.view.inputmethod.InputMethodManager; 72import android.widget.ScrollBarDrawable; 73 74import static android.os.Build.VERSION_CODES.*; 75 76import com.android.internal.R; 77import com.android.internal.util.Predicate; 78import com.android.internal.view.menu.MenuBuilder; 79 80import java.lang.ref.WeakReference; 81import java.lang.reflect.InvocationTargetException; 82import java.lang.reflect.Method; 83import java.util.ArrayList; 84import java.util.Arrays; 85import java.util.Locale; 86import java.util.concurrent.CopyOnWriteArrayList; 87 88/** 89 * <p> 90 * This class represents the basic building block for user interface components. A View 91 * occupies a rectangular area on the screen and is responsible for drawing and 92 * event handling. View is the base class for <em>widgets</em>, which are 93 * used to create interactive UI components (buttons, text fields, etc.). The 94 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 95 * are invisible containers that hold other Views (or other ViewGroups) and define 96 * their layout properties. 97 * </p> 98 * 99 * <div class="special reference"> 100 * <h3>Developer Guides</h3> 101 * <p>For information about using this class to develop your application's user interface, 102 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 103 * </div> 104 * 105 * <a name="Using"></a> 106 * <h3>Using Views</h3> 107 * <p> 108 * All of the views in a window are arranged in a single tree. You can add views 109 * either from code or by specifying a tree of views in one or more XML layout 110 * files. There are many specialized subclasses of views that act as controls or 111 * are capable of displaying text, images, or other content. 112 * </p> 113 * <p> 114 * Once you have created a tree of views, there are typically a few types of 115 * common operations you may wish to perform: 116 * <ul> 117 * <li><strong>Set properties:</strong> for example setting the text of a 118 * {@link android.widget.TextView}. The available properties and the methods 119 * that set them will vary among the different subclasses of views. Note that 120 * properties that are known at build time can be set in the XML layout 121 * files.</li> 122 * <li><strong>Set focus:</strong> The framework will handled moving focus in 123 * response to user input. To force focus to a specific view, call 124 * {@link #requestFocus}.</li> 125 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 126 * that will be notified when something interesting happens to the view. For 127 * example, all views will let you set a listener to be notified when the view 128 * gains or loses focus. You can register such a listener using 129 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 130 * Other view subclasses offer more specialized listeners. For example, a Button 131 * exposes a listener to notify clients when the button is clicked.</li> 132 * <li><strong>Set visibility:</strong> You can hide or show views using 133 * {@link #setVisibility(int)}.</li> 134 * </ul> 135 * </p> 136 * <p><em> 137 * Note: The Android framework is responsible for measuring, laying out and 138 * drawing views. You should not call methods that perform these actions on 139 * views yourself unless you are actually implementing a 140 * {@link android.view.ViewGroup}. 141 * </em></p> 142 * 143 * <a name="Lifecycle"></a> 144 * <h3>Implementing a Custom View</h3> 145 * 146 * <p> 147 * To implement a custom view, you will usually begin by providing overrides for 148 * some of the standard methods that the framework calls on all views. You do 149 * not need to override all of these methods. In fact, you can start by just 150 * overriding {@link #onDraw(android.graphics.Canvas)}. 151 * <table border="2" width="85%" align="center" cellpadding="5"> 152 * <thead> 153 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 154 * </thead> 155 * 156 * <tbody> 157 * <tr> 158 * <td rowspan="2">Creation</td> 159 * <td>Constructors</td> 160 * <td>There is a form of the constructor that are called when the view 161 * is created from code and a form that is called when the view is 162 * inflated from a layout file. The second form should parse and apply 163 * any attributes defined in the layout file. 164 * </td> 165 * </tr> 166 * <tr> 167 * <td><code>{@link #onFinishInflate()}</code></td> 168 * <td>Called after a view and all of its children has been inflated 169 * from XML.</td> 170 * </tr> 171 * 172 * <tr> 173 * <td rowspan="3">Layout</td> 174 * <td><code>{@link #onMeasure(int, int)}</code></td> 175 * <td>Called to determine the size requirements for this view and all 176 * of its children. 177 * </td> 178 * </tr> 179 * <tr> 180 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 181 * <td>Called when this view should assign a size and position to all 182 * of its children. 183 * </td> 184 * </tr> 185 * <tr> 186 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 187 * <td>Called when the size of this view has changed. 188 * </td> 189 * </tr> 190 * 191 * <tr> 192 * <td>Drawing</td> 193 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 194 * <td>Called when the view should render its content. 195 * </td> 196 * </tr> 197 * 198 * <tr> 199 * <td rowspan="4">Event processing</td> 200 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 201 * <td>Called when a new key event occurs. 202 * </td> 203 * </tr> 204 * <tr> 205 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 206 * <td>Called when a key up event occurs. 207 * </td> 208 * </tr> 209 * <tr> 210 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 211 * <td>Called when a trackball motion event occurs. 212 * </td> 213 * </tr> 214 * <tr> 215 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 216 * <td>Called when a touch screen motion event occurs. 217 * </td> 218 * </tr> 219 * 220 * <tr> 221 * <td rowspan="2">Focus</td> 222 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 223 * <td>Called when the view gains or loses focus. 224 * </td> 225 * </tr> 226 * 227 * <tr> 228 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 229 * <td>Called when the window containing the view gains or loses focus. 230 * </td> 231 * </tr> 232 * 233 * <tr> 234 * <td rowspan="3">Attaching</td> 235 * <td><code>{@link #onAttachedToWindow()}</code></td> 236 * <td>Called when the view is attached to a window. 237 * </td> 238 * </tr> 239 * 240 * <tr> 241 * <td><code>{@link #onDetachedFromWindow}</code></td> 242 * <td>Called when the view is detached from its window. 243 * </td> 244 * </tr> 245 * 246 * <tr> 247 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 248 * <td>Called when the visibility of the window containing the view 249 * has changed. 250 * </td> 251 * </tr> 252 * </tbody> 253 * 254 * </table> 255 * </p> 256 * 257 * <a name="IDs"></a> 258 * <h3>IDs</h3> 259 * Views may have an integer id associated with them. These ids are typically 260 * assigned in the layout XML files, and are used to find specific views within 261 * the view tree. A common pattern is to: 262 * <ul> 263 * <li>Define a Button in the layout file and assign it a unique ID. 264 * <pre> 265 * <Button 266 * android:id="@+id/my_button" 267 * android:layout_width="wrap_content" 268 * android:layout_height="wrap_content" 269 * android:text="@string/my_button_text"/> 270 * </pre></li> 271 * <li>From the onCreate method of an Activity, find the Button 272 * <pre class="prettyprint"> 273 * Button myButton = (Button) findViewById(R.id.my_button); 274 * </pre></li> 275 * </ul> 276 * <p> 277 * View IDs need not be unique throughout the tree, but it is good practice to 278 * ensure that they are at least unique within the part of the tree you are 279 * searching. 280 * </p> 281 * 282 * <a name="Position"></a> 283 * <h3>Position</h3> 284 * <p> 285 * The geometry of a view is that of a rectangle. A view has a location, 286 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 287 * two dimensions, expressed as a width and a height. The unit for location 288 * and dimensions is the pixel. 289 * </p> 290 * 291 * <p> 292 * It is possible to retrieve the location of a view by invoking the methods 293 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 294 * coordinate of the rectangle representing the view. The latter returns the 295 * top, or Y, coordinate of the rectangle representing the view. These methods 296 * both return the location of the view relative to its parent. For instance, 297 * when getLeft() returns 20, that means the view is located 20 pixels to the 298 * right of the left edge of its direct parent. 299 * </p> 300 * 301 * <p> 302 * In addition, several convenience methods are offered to avoid unnecessary 303 * computations, namely {@link #getRight()} and {@link #getBottom()}. 304 * These methods return the coordinates of the right and bottom edges of the 305 * rectangle representing the view. For instance, calling {@link #getRight()} 306 * is similar to the following computation: <code>getLeft() + getWidth()</code> 307 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 308 * </p> 309 * 310 * <a name="SizePaddingMargins"></a> 311 * <h3>Size, padding and margins</h3> 312 * <p> 313 * The size of a view is expressed with a width and a height. A view actually 314 * possess two pairs of width and height values. 315 * </p> 316 * 317 * <p> 318 * The first pair is known as <em>measured width</em> and 319 * <em>measured height</em>. These dimensions define how big a view wants to be 320 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 321 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 322 * and {@link #getMeasuredHeight()}. 323 * </p> 324 * 325 * <p> 326 * The second pair is simply known as <em>width</em> and <em>height</em>, or 327 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 328 * dimensions define the actual size of the view on screen, at drawing time and 329 * after layout. These values may, but do not have to, be different from the 330 * measured width and height. The width and height can be obtained by calling 331 * {@link #getWidth()} and {@link #getHeight()}. 332 * </p> 333 * 334 * <p> 335 * To measure its dimensions, a view takes into account its padding. The padding 336 * is expressed in pixels for the left, top, right and bottom parts of the view. 337 * Padding can be used to offset the content of the view by a specific amount of 338 * pixels. For instance, a left padding of 2 will push the view's content by 339 * 2 pixels to the right of the left edge. Padding can be set using the 340 * {@link #setPadding(int, int, int, int)} method and queried by calling 341 * {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 342 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}. 343 * </p> 344 * 345 * <p> 346 * Even though a view can define a padding, it does not provide any support for 347 * margins. However, view groups provide such a support. Refer to 348 * {@link android.view.ViewGroup} and 349 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 350 * </p> 351 * 352 * <a name="Layout"></a> 353 * <h3>Layout</h3> 354 * <p> 355 * Layout is a two pass process: a measure pass and a layout pass. The measuring 356 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 357 * of the view tree. Each view pushes dimension specifications down the tree 358 * during the recursion. At the end of the measure pass, every view has stored 359 * its measurements. The second pass happens in 360 * {@link #layout(int,int,int,int)} and is also top-down. During 361 * this pass each parent is responsible for positioning all of its children 362 * using the sizes computed in the measure pass. 363 * </p> 364 * 365 * <p> 366 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 367 * {@link #getMeasuredHeight()} values must be set, along with those for all of 368 * that view's descendants. A view's measured width and measured height values 369 * must respect the constraints imposed by the view's parents. This guarantees 370 * that at the end of the measure pass, all parents accept all of their 371 * children's measurements. A parent view may call measure() more than once on 372 * its children. For example, the parent may measure each child once with 373 * unspecified dimensions to find out how big they want to be, then call 374 * measure() on them again with actual numbers if the sum of all the children's 375 * unconstrained sizes is too big or too small. 376 * </p> 377 * 378 * <p> 379 * The measure pass uses two classes to communicate dimensions. The 380 * {@link MeasureSpec} class is used by views to tell their parents how they 381 * want to be measured and positioned. The base LayoutParams class just 382 * describes how big the view wants to be for both width and height. For each 383 * dimension, it can specify one of: 384 * <ul> 385 * <li> an exact number 386 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 387 * (minus padding) 388 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 389 * enclose its content (plus padding). 390 * </ul> 391 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 392 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 393 * an X and Y value. 394 * </p> 395 * 396 * <p> 397 * MeasureSpecs are used to push requirements down the tree from parent to 398 * child. A MeasureSpec can be in one of three modes: 399 * <ul> 400 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 401 * of a child view. For example, a LinearLayout may call measure() on its child 402 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 403 * tall the child view wants to be given a width of 240 pixels. 404 * <li>EXACTLY: This is used by the parent to impose an exact size on the 405 * child. The child must use this size, and guarantee that all of its 406 * descendants will fit within this size. 407 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 408 * child. The child must gurantee that it and all of its descendants will fit 409 * within this size. 410 * </ul> 411 * </p> 412 * 413 * <p> 414 * To intiate a layout, call {@link #requestLayout}. This method is typically 415 * called by a view on itself when it believes that is can no longer fit within 416 * its current bounds. 417 * </p> 418 * 419 * <a name="Drawing"></a> 420 * <h3>Drawing</h3> 421 * <p> 422 * Drawing is handled by walking the tree and rendering each view that 423 * intersects the invalid region. Because the tree is traversed in-order, 424 * this means that parents will draw before (i.e., behind) their children, with 425 * siblings drawn in the order they appear in the tree. 426 * If you set a background drawable for a View, then the View will draw it for you 427 * before calling back to its <code>onDraw()</code> method. 428 * </p> 429 * 430 * <p> 431 * Note that the framework will not draw views that are not in the invalid region. 432 * </p> 433 * 434 * <p> 435 * To force a view to draw, call {@link #invalidate()}. 436 * </p> 437 * 438 * <a name="EventHandlingThreading"></a> 439 * <h3>Event Handling and Threading</h3> 440 * <p> 441 * The basic cycle of a view is as follows: 442 * <ol> 443 * <li>An event comes in and is dispatched to the appropriate view. The view 444 * handles the event and notifies any listeners.</li> 445 * <li>If in the course of processing the event, the view's bounds may need 446 * to be changed, the view will call {@link #requestLayout()}.</li> 447 * <li>Similarly, if in the course of processing the event the view's appearance 448 * may need to be changed, the view will call {@link #invalidate()}.</li> 449 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 450 * the framework will take care of measuring, laying out, and drawing the tree 451 * as appropriate.</li> 452 * </ol> 453 * </p> 454 * 455 * <p><em>Note: The entire view tree is single threaded. You must always be on 456 * the UI thread when calling any method on any view.</em> 457 * If you are doing work on other threads and want to update the state of a view 458 * from that thread, you should use a {@link Handler}. 459 * </p> 460 * 461 * <a name="FocusHandling"></a> 462 * <h3>Focus Handling</h3> 463 * <p> 464 * The framework will handle routine focus movement in response to user input. 465 * This includes changing the focus as views are removed or hidden, or as new 466 * views become available. Views indicate their willingness to take focus 467 * through the {@link #isFocusable} method. To change whether a view can take 468 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 469 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 470 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 471 * </p> 472 * <p> 473 * Focus movement is based on an algorithm which finds the nearest neighbor in a 474 * given direction. In rare cases, the default algorithm may not match the 475 * intended behavior of the developer. In these situations, you can provide 476 * explicit overrides by using these XML attributes in the layout file: 477 * <pre> 478 * nextFocusDown 479 * nextFocusLeft 480 * nextFocusRight 481 * nextFocusUp 482 * </pre> 483 * </p> 484 * 485 * 486 * <p> 487 * To get a particular view to take focus, call {@link #requestFocus()}. 488 * </p> 489 * 490 * <a name="TouchMode"></a> 491 * <h3>Touch Mode</h3> 492 * <p> 493 * When a user is navigating a user interface via directional keys such as a D-pad, it is 494 * necessary to give focus to actionable items such as buttons so the user can see 495 * what will take input. If the device has touch capabilities, however, and the user 496 * begins interacting with the interface by touching it, it is no longer necessary to 497 * always highlight, or give focus to, a particular view. This motivates a mode 498 * for interaction named 'touch mode'. 499 * </p> 500 * <p> 501 * For a touch capable device, once the user touches the screen, the device 502 * will enter touch mode. From this point onward, only views for which 503 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 504 * Other views that are touchable, like buttons, will not take focus when touched; they will 505 * only fire the on click listeners. 506 * </p> 507 * <p> 508 * Any time a user hits a directional key, such as a D-pad direction, the view device will 509 * exit touch mode, and find a view to take focus, so that the user may resume interacting 510 * with the user interface without touching the screen again. 511 * </p> 512 * <p> 513 * The touch mode state is maintained across {@link android.app.Activity}s. Call 514 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 515 * </p> 516 * 517 * <a name="Scrolling"></a> 518 * <h3>Scrolling</h3> 519 * <p> 520 * The framework provides basic support for views that wish to internally 521 * scroll their content. This includes keeping track of the X and Y scroll 522 * offset as well as mechanisms for drawing scrollbars. See 523 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 524 * {@link #awakenScrollBars()} for more details. 525 * </p> 526 * 527 * <a name="Tags"></a> 528 * <h3>Tags</h3> 529 * <p> 530 * Unlike IDs, tags are not used to identify views. Tags are essentially an 531 * extra piece of information that can be associated with a view. They are most 532 * often used as a convenience to store data related to views in the views 533 * themselves rather than by putting them in a separate structure. 534 * </p> 535 * 536 * <a name="Animation"></a> 537 * <h3>Animation</h3> 538 * <p> 539 * You can attach an {@link Animation} object to a view using 540 * {@link #setAnimation(Animation)} or 541 * {@link #startAnimation(Animation)}. The animation can alter the scale, 542 * rotation, translation and alpha of a view over time. If the animation is 543 * attached to a view that has children, the animation will affect the entire 544 * subtree rooted by that node. When an animation is started, the framework will 545 * take care of redrawing the appropriate views until the animation completes. 546 * </p> 547 * <p> 548 * Starting with Android 3.0, the preferred way of animating views is to use the 549 * {@link android.animation} package APIs. 550 * </p> 551 * 552 * <a name="Security"></a> 553 * <h3>Security</h3> 554 * <p> 555 * Sometimes it is essential that an application be able to verify that an action 556 * is being performed with the full knowledge and consent of the user, such as 557 * granting a permission request, making a purchase or clicking on an advertisement. 558 * Unfortunately, a malicious application could try to spoof the user into 559 * performing these actions, unaware, by concealing the intended purpose of the view. 560 * As a remedy, the framework offers a touch filtering mechanism that can be used to 561 * improve the security of views that provide access to sensitive functionality. 562 * </p><p> 563 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 564 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 565 * will discard touches that are received whenever the view's window is obscured by 566 * another visible window. As a result, the view will not receive touches whenever a 567 * toast, dialog or other window appears above the view's window. 568 * </p><p> 569 * For more fine-grained control over security, consider overriding the 570 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 571 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 572 * </p> 573 * 574 * @attr ref android.R.styleable#View_alpha 575 * @attr ref android.R.styleable#View_background 576 * @attr ref android.R.styleable#View_clickable 577 * @attr ref android.R.styleable#View_contentDescription 578 * @attr ref android.R.styleable#View_drawingCacheQuality 579 * @attr ref android.R.styleable#View_duplicateParentState 580 * @attr ref android.R.styleable#View_id 581 * @attr ref android.R.styleable#View_requiresFadingEdge 582 * @attr ref android.R.styleable#View_fadingEdgeLength 583 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 584 * @attr ref android.R.styleable#View_fitsSystemWindows 585 * @attr ref android.R.styleable#View_isScrollContainer 586 * @attr ref android.R.styleable#View_focusable 587 * @attr ref android.R.styleable#View_focusableInTouchMode 588 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 589 * @attr ref android.R.styleable#View_keepScreenOn 590 * @attr ref android.R.styleable#View_layerType 591 * @attr ref android.R.styleable#View_longClickable 592 * @attr ref android.R.styleable#View_minHeight 593 * @attr ref android.R.styleable#View_minWidth 594 * @attr ref android.R.styleable#View_nextFocusDown 595 * @attr ref android.R.styleable#View_nextFocusLeft 596 * @attr ref android.R.styleable#View_nextFocusRight 597 * @attr ref android.R.styleable#View_nextFocusUp 598 * @attr ref android.R.styleable#View_onClick 599 * @attr ref android.R.styleable#View_padding 600 * @attr ref android.R.styleable#View_paddingBottom 601 * @attr ref android.R.styleable#View_paddingLeft 602 * @attr ref android.R.styleable#View_paddingRight 603 * @attr ref android.R.styleable#View_paddingTop 604 * @attr ref android.R.styleable#View_saveEnabled 605 * @attr ref android.R.styleable#View_rotation 606 * @attr ref android.R.styleable#View_rotationX 607 * @attr ref android.R.styleable#View_rotationY 608 * @attr ref android.R.styleable#View_scaleX 609 * @attr ref android.R.styleable#View_scaleY 610 * @attr ref android.R.styleable#View_scrollX 611 * @attr ref android.R.styleable#View_scrollY 612 * @attr ref android.R.styleable#View_scrollbarSize 613 * @attr ref android.R.styleable#View_scrollbarStyle 614 * @attr ref android.R.styleable#View_scrollbars 615 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 616 * @attr ref android.R.styleable#View_scrollbarFadeDuration 617 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 618 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 619 * @attr ref android.R.styleable#View_scrollbarThumbVertical 620 * @attr ref android.R.styleable#View_scrollbarTrackVertical 621 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 622 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 623 * @attr ref android.R.styleable#View_soundEffectsEnabled 624 * @attr ref android.R.styleable#View_tag 625 * @attr ref android.R.styleable#View_transformPivotX 626 * @attr ref android.R.styleable#View_transformPivotY 627 * @attr ref android.R.styleable#View_translationX 628 * @attr ref android.R.styleable#View_translationY 629 * @attr ref android.R.styleable#View_visibility 630 * 631 * @see android.view.ViewGroup 632 */ 633public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback, 634 AccessibilityEventSource { 635 private static final boolean DBG = false; 636 637 /** 638 * The logging tag used by this class with android.util.Log. 639 */ 640 protected static final String VIEW_LOG_TAG = "View"; 641 642 /** 643 * Used to mark a View that has no ID. 644 */ 645 public static final int NO_ID = -1; 646 647 /** 648 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 649 * calling setFlags. 650 */ 651 private static final int NOT_FOCUSABLE = 0x00000000; 652 653 /** 654 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 655 * setFlags. 656 */ 657 private static final int FOCUSABLE = 0x00000001; 658 659 /** 660 * Mask for use with setFlags indicating bits used for focus. 661 */ 662 private static final int FOCUSABLE_MASK = 0x00000001; 663 664 /** 665 * This view will adjust its padding to fit sytem windows (e.g. status bar) 666 */ 667 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 668 669 /** 670 * This view is visible. 671 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 672 * android:visibility}. 673 */ 674 public static final int VISIBLE = 0x00000000; 675 676 /** 677 * This view is invisible, but it still takes up space for layout purposes. 678 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 679 * android:visibility}. 680 */ 681 public static final int INVISIBLE = 0x00000004; 682 683 /** 684 * This view is invisible, and it doesn't take any space for layout 685 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 686 * android:visibility}. 687 */ 688 public static final int GONE = 0x00000008; 689 690 /** 691 * Mask for use with setFlags indicating bits used for visibility. 692 * {@hide} 693 */ 694 static final int VISIBILITY_MASK = 0x0000000C; 695 696 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 697 698 /** 699 * This view is enabled. Intrepretation varies by subclass. 700 * Use with ENABLED_MASK when calling setFlags. 701 * {@hide} 702 */ 703 static final int ENABLED = 0x00000000; 704 705 /** 706 * This view is disabled. Intrepretation varies by subclass. 707 * Use with ENABLED_MASK when calling setFlags. 708 * {@hide} 709 */ 710 static final int DISABLED = 0x00000020; 711 712 /** 713 * Mask for use with setFlags indicating bits used for indicating whether 714 * this view is enabled 715 * {@hide} 716 */ 717 static final int ENABLED_MASK = 0x00000020; 718 719 /** 720 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 721 * called and further optimizations will be performed. It is okay to have 722 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 723 * {@hide} 724 */ 725 static final int WILL_NOT_DRAW = 0x00000080; 726 727 /** 728 * Mask for use with setFlags indicating bits used for indicating whether 729 * this view is will draw 730 * {@hide} 731 */ 732 static final int DRAW_MASK = 0x00000080; 733 734 /** 735 * <p>This view doesn't show scrollbars.</p> 736 * {@hide} 737 */ 738 static final int SCROLLBARS_NONE = 0x00000000; 739 740 /** 741 * <p>This view shows horizontal scrollbars.</p> 742 * {@hide} 743 */ 744 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 745 746 /** 747 * <p>This view shows vertical scrollbars.</p> 748 * {@hide} 749 */ 750 static final int SCROLLBARS_VERTICAL = 0x00000200; 751 752 /** 753 * <p>Mask for use with setFlags indicating bits used for indicating which 754 * scrollbars are enabled.</p> 755 * {@hide} 756 */ 757 static final int SCROLLBARS_MASK = 0x00000300; 758 759 /** 760 * Indicates that the view should filter touches when its window is obscured. 761 * Refer to the class comments for more information about this security feature. 762 * {@hide} 763 */ 764 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 765 766 // note flag value 0x00000800 is now available for next flags... 767 768 /** 769 * <p>This view doesn't show fading edges.</p> 770 * {@hide} 771 */ 772 static final int FADING_EDGE_NONE = 0x00000000; 773 774 /** 775 * <p>This view shows horizontal fading edges.</p> 776 * {@hide} 777 */ 778 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 779 780 /** 781 * <p>This view shows vertical fading edges.</p> 782 * {@hide} 783 */ 784 static final int FADING_EDGE_VERTICAL = 0x00002000; 785 786 /** 787 * <p>Mask for use with setFlags indicating bits used for indicating which 788 * fading edges are enabled.</p> 789 * {@hide} 790 */ 791 static final int FADING_EDGE_MASK = 0x00003000; 792 793 /** 794 * <p>Indicates this view can be clicked. When clickable, a View reacts 795 * to clicks by notifying the OnClickListener.<p> 796 * {@hide} 797 */ 798 static final int CLICKABLE = 0x00004000; 799 800 /** 801 * <p>Indicates this view is caching its drawing into a bitmap.</p> 802 * {@hide} 803 */ 804 static final int DRAWING_CACHE_ENABLED = 0x00008000; 805 806 /** 807 * <p>Indicates that no icicle should be saved for this view.<p> 808 * {@hide} 809 */ 810 static final int SAVE_DISABLED = 0x000010000; 811 812 /** 813 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 814 * property.</p> 815 * {@hide} 816 */ 817 static final int SAVE_DISABLED_MASK = 0x000010000; 818 819 /** 820 * <p>Indicates that no drawing cache should ever be created for this view.<p> 821 * {@hide} 822 */ 823 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 824 825 /** 826 * <p>Indicates this view can take / keep focus when int touch mode.</p> 827 * {@hide} 828 */ 829 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 830 831 /** 832 * <p>Enables low quality mode for the drawing cache.</p> 833 */ 834 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 835 836 /** 837 * <p>Enables high quality mode for the drawing cache.</p> 838 */ 839 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 840 841 /** 842 * <p>Enables automatic quality mode for the drawing cache.</p> 843 */ 844 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 845 846 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 847 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 848 }; 849 850 /** 851 * <p>Mask for use with setFlags indicating bits used for the cache 852 * quality property.</p> 853 * {@hide} 854 */ 855 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 856 857 /** 858 * <p> 859 * Indicates this view can be long clicked. When long clickable, a View 860 * reacts to long clicks by notifying the OnLongClickListener or showing a 861 * context menu. 862 * </p> 863 * {@hide} 864 */ 865 static final int LONG_CLICKABLE = 0x00200000; 866 867 /** 868 * <p>Indicates that this view gets its drawable states from its direct parent 869 * and ignores its original internal states.</p> 870 * 871 * @hide 872 */ 873 static final int DUPLICATE_PARENT_STATE = 0x00400000; 874 875 /** 876 * The scrollbar style to display the scrollbars inside the content area, 877 * without increasing the padding. The scrollbars will be overlaid with 878 * translucency on the view's content. 879 */ 880 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 881 882 /** 883 * The scrollbar style to display the scrollbars inside the padded area, 884 * increasing the padding of the view. The scrollbars will not overlap the 885 * content area of the view. 886 */ 887 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 888 889 /** 890 * The scrollbar style to display the scrollbars at the edge of the view, 891 * without increasing the padding. The scrollbars will be overlaid with 892 * translucency. 893 */ 894 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 895 896 /** 897 * The scrollbar style to display the scrollbars at the edge of the view, 898 * increasing the padding of the view. The scrollbars will only overlap the 899 * background, if any. 900 */ 901 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 902 903 /** 904 * Mask to check if the scrollbar style is overlay or inset. 905 * {@hide} 906 */ 907 static final int SCROLLBARS_INSET_MASK = 0x01000000; 908 909 /** 910 * Mask to check if the scrollbar style is inside or outside. 911 * {@hide} 912 */ 913 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 914 915 /** 916 * Mask for scrollbar style. 917 * {@hide} 918 */ 919 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 920 921 /** 922 * View flag indicating that the screen should remain on while the 923 * window containing this view is visible to the user. This effectively 924 * takes care of automatically setting the WindowManager's 925 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 926 */ 927 public static final int KEEP_SCREEN_ON = 0x04000000; 928 929 /** 930 * View flag indicating whether this view should have sound effects enabled 931 * for events such as clicking and touching. 932 */ 933 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 934 935 /** 936 * View flag indicating whether this view should have haptic feedback 937 * enabled for events such as long presses. 938 */ 939 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 940 941 /** 942 * <p>Indicates that the view hierarchy should stop saving state when 943 * it reaches this view. If state saving is initiated immediately at 944 * the view, it will be allowed. 945 * {@hide} 946 */ 947 static final int PARENT_SAVE_DISABLED = 0x20000000; 948 949 /** 950 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 951 * {@hide} 952 */ 953 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 954 955 /** 956 * Horizontal direction of this view is from Left to Right. 957 * Use with {@link #setLayoutDirection}. 958 * {@hide} 959 */ 960 public static final int LAYOUT_DIRECTION_LTR = 0x00000000; 961 962 /** 963 * Horizontal direction of this view is from Right to Left. 964 * Use with {@link #setLayoutDirection}. 965 * {@hide} 966 */ 967 public static final int LAYOUT_DIRECTION_RTL = 0x40000000; 968 969 /** 970 * Horizontal direction of this view is inherited from its parent. 971 * Use with {@link #setLayoutDirection}. 972 * {@hide} 973 */ 974 public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000; 975 976 /** 977 * Horizontal direction of this view is from deduced from the default language 978 * script for the locale. Use with {@link #setLayoutDirection}. 979 * {@hide} 980 */ 981 public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000; 982 983 /** 984 * Mask for use with setFlags indicating bits used for horizontalDirection. 985 * {@hide} 986 */ 987 static final int LAYOUT_DIRECTION_MASK = 0xC0000000; 988 989 /* 990 * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct 991 * flag value. 992 * {@hide} 993 */ 994 private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR, 995 LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE}; 996 997 /** 998 * Default horizontalDirection. 999 * {@hide} 1000 */ 1001 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1002 1003 /** 1004 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1005 * should add all focusable Views regardless if they are focusable in touch mode. 1006 */ 1007 public static final int FOCUSABLES_ALL = 0x00000000; 1008 1009 /** 1010 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1011 * should add only Views focusable in touch mode. 1012 */ 1013 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1014 1015 /** 1016 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1017 * item. 1018 */ 1019 public static final int FOCUS_BACKWARD = 0x00000001; 1020 1021 /** 1022 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1023 * item. 1024 */ 1025 public static final int FOCUS_FORWARD = 0x00000002; 1026 1027 /** 1028 * Use with {@link #focusSearch(int)}. Move focus to the left. 1029 */ 1030 public static final int FOCUS_LEFT = 0x00000011; 1031 1032 /** 1033 * Use with {@link #focusSearch(int)}. Move focus up. 1034 */ 1035 public static final int FOCUS_UP = 0x00000021; 1036 1037 /** 1038 * Use with {@link #focusSearch(int)}. Move focus to the right. 1039 */ 1040 public static final int FOCUS_RIGHT = 0x00000042; 1041 1042 /** 1043 * Use with {@link #focusSearch(int)}. Move focus down. 1044 */ 1045 public static final int FOCUS_DOWN = 0x00000082; 1046 1047 /** 1048 * Bits of {@link #getMeasuredWidthAndState()} and 1049 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1050 */ 1051 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1052 1053 /** 1054 * Bits of {@link #getMeasuredWidthAndState()} and 1055 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1056 */ 1057 public static final int MEASURED_STATE_MASK = 0xff000000; 1058 1059 /** 1060 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1061 * for functions that combine both width and height into a single int, 1062 * such as {@link #getMeasuredState()} and the childState argument of 1063 * {@link #resolveSizeAndState(int, int, int)}. 1064 */ 1065 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1066 1067 /** 1068 * Bit of {@link #getMeasuredWidthAndState()} and 1069 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1070 * is smaller that the space the view would like to have. 1071 */ 1072 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1073 1074 /** 1075 * Base View state sets 1076 */ 1077 // Singles 1078 /** 1079 * Indicates the view has no states set. States are used with 1080 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1081 * view depending on its state. 1082 * 1083 * @see android.graphics.drawable.Drawable 1084 * @see #getDrawableState() 1085 */ 1086 protected static final int[] EMPTY_STATE_SET; 1087 /** 1088 * Indicates the view is enabled. States are used with 1089 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1090 * view depending on its state. 1091 * 1092 * @see android.graphics.drawable.Drawable 1093 * @see #getDrawableState() 1094 */ 1095 protected static final int[] ENABLED_STATE_SET; 1096 /** 1097 * Indicates the view is focused. States are used with 1098 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1099 * view depending on its state. 1100 * 1101 * @see android.graphics.drawable.Drawable 1102 * @see #getDrawableState() 1103 */ 1104 protected static final int[] FOCUSED_STATE_SET; 1105 /** 1106 * Indicates the view is selected. States are used with 1107 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1108 * view depending on its state. 1109 * 1110 * @see android.graphics.drawable.Drawable 1111 * @see #getDrawableState() 1112 */ 1113 protected static final int[] SELECTED_STATE_SET; 1114 /** 1115 * Indicates the view is pressed. States are used with 1116 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1117 * view depending on its state. 1118 * 1119 * @see android.graphics.drawable.Drawable 1120 * @see #getDrawableState() 1121 * @hide 1122 */ 1123 protected static final int[] PRESSED_STATE_SET; 1124 /** 1125 * Indicates the view's window has focus. States are used with 1126 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1127 * view depending on its state. 1128 * 1129 * @see android.graphics.drawable.Drawable 1130 * @see #getDrawableState() 1131 */ 1132 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1133 // Doubles 1134 /** 1135 * Indicates the view is enabled and has the focus. 1136 * 1137 * @see #ENABLED_STATE_SET 1138 * @see #FOCUSED_STATE_SET 1139 */ 1140 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1141 /** 1142 * Indicates the view is enabled and selected. 1143 * 1144 * @see #ENABLED_STATE_SET 1145 * @see #SELECTED_STATE_SET 1146 */ 1147 protected static final int[] ENABLED_SELECTED_STATE_SET; 1148 /** 1149 * Indicates the view is enabled and that its window has focus. 1150 * 1151 * @see #ENABLED_STATE_SET 1152 * @see #WINDOW_FOCUSED_STATE_SET 1153 */ 1154 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1155 /** 1156 * Indicates the view is focused and selected. 1157 * 1158 * @see #FOCUSED_STATE_SET 1159 * @see #SELECTED_STATE_SET 1160 */ 1161 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1162 /** 1163 * Indicates the view has the focus and that its window has the focus. 1164 * 1165 * @see #FOCUSED_STATE_SET 1166 * @see #WINDOW_FOCUSED_STATE_SET 1167 */ 1168 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1169 /** 1170 * Indicates the view is selected and that its window has the focus. 1171 * 1172 * @see #SELECTED_STATE_SET 1173 * @see #WINDOW_FOCUSED_STATE_SET 1174 */ 1175 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1176 // Triples 1177 /** 1178 * Indicates the view is enabled, focused and selected. 1179 * 1180 * @see #ENABLED_STATE_SET 1181 * @see #FOCUSED_STATE_SET 1182 * @see #SELECTED_STATE_SET 1183 */ 1184 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1185 /** 1186 * Indicates the view is enabled, focused and its window has the focus. 1187 * 1188 * @see #ENABLED_STATE_SET 1189 * @see #FOCUSED_STATE_SET 1190 * @see #WINDOW_FOCUSED_STATE_SET 1191 */ 1192 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1193 /** 1194 * Indicates the view is enabled, selected and its window has the focus. 1195 * 1196 * @see #ENABLED_STATE_SET 1197 * @see #SELECTED_STATE_SET 1198 * @see #WINDOW_FOCUSED_STATE_SET 1199 */ 1200 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1201 /** 1202 * Indicates the view is focused, selected and its window has the focus. 1203 * 1204 * @see #FOCUSED_STATE_SET 1205 * @see #SELECTED_STATE_SET 1206 * @see #WINDOW_FOCUSED_STATE_SET 1207 */ 1208 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1209 /** 1210 * Indicates the view is enabled, focused, selected and its window 1211 * has the focus. 1212 * 1213 * @see #ENABLED_STATE_SET 1214 * @see #FOCUSED_STATE_SET 1215 * @see #SELECTED_STATE_SET 1216 * @see #WINDOW_FOCUSED_STATE_SET 1217 */ 1218 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1219 /** 1220 * Indicates the view is pressed and its window has the focus. 1221 * 1222 * @see #PRESSED_STATE_SET 1223 * @see #WINDOW_FOCUSED_STATE_SET 1224 */ 1225 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1226 /** 1227 * Indicates the view is pressed and selected. 1228 * 1229 * @see #PRESSED_STATE_SET 1230 * @see #SELECTED_STATE_SET 1231 */ 1232 protected static final int[] PRESSED_SELECTED_STATE_SET; 1233 /** 1234 * Indicates the view is pressed, selected and its window has the focus. 1235 * 1236 * @see #PRESSED_STATE_SET 1237 * @see #SELECTED_STATE_SET 1238 * @see #WINDOW_FOCUSED_STATE_SET 1239 */ 1240 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1241 /** 1242 * Indicates the view is pressed and focused. 1243 * 1244 * @see #PRESSED_STATE_SET 1245 * @see #FOCUSED_STATE_SET 1246 */ 1247 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1248 /** 1249 * Indicates the view is pressed, focused and its window has the focus. 1250 * 1251 * @see #PRESSED_STATE_SET 1252 * @see #FOCUSED_STATE_SET 1253 * @see #WINDOW_FOCUSED_STATE_SET 1254 */ 1255 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1256 /** 1257 * Indicates the view is pressed, focused and selected. 1258 * 1259 * @see #PRESSED_STATE_SET 1260 * @see #SELECTED_STATE_SET 1261 * @see #FOCUSED_STATE_SET 1262 */ 1263 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1264 /** 1265 * Indicates the view is pressed, focused, selected and its window has the focus. 1266 * 1267 * @see #PRESSED_STATE_SET 1268 * @see #FOCUSED_STATE_SET 1269 * @see #SELECTED_STATE_SET 1270 * @see #WINDOW_FOCUSED_STATE_SET 1271 */ 1272 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1273 /** 1274 * Indicates the view is pressed and enabled. 1275 * 1276 * @see #PRESSED_STATE_SET 1277 * @see #ENABLED_STATE_SET 1278 */ 1279 protected static final int[] PRESSED_ENABLED_STATE_SET; 1280 /** 1281 * Indicates the view is pressed, enabled and its window has the focus. 1282 * 1283 * @see #PRESSED_STATE_SET 1284 * @see #ENABLED_STATE_SET 1285 * @see #WINDOW_FOCUSED_STATE_SET 1286 */ 1287 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1288 /** 1289 * Indicates the view is pressed, enabled and selected. 1290 * 1291 * @see #PRESSED_STATE_SET 1292 * @see #ENABLED_STATE_SET 1293 * @see #SELECTED_STATE_SET 1294 */ 1295 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1296 /** 1297 * Indicates the view is pressed, enabled, selected and its window has the 1298 * focus. 1299 * 1300 * @see #PRESSED_STATE_SET 1301 * @see #ENABLED_STATE_SET 1302 * @see #SELECTED_STATE_SET 1303 * @see #WINDOW_FOCUSED_STATE_SET 1304 */ 1305 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1306 /** 1307 * Indicates the view is pressed, enabled and focused. 1308 * 1309 * @see #PRESSED_STATE_SET 1310 * @see #ENABLED_STATE_SET 1311 * @see #FOCUSED_STATE_SET 1312 */ 1313 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1314 /** 1315 * Indicates the view is pressed, enabled, focused and its window has the 1316 * focus. 1317 * 1318 * @see #PRESSED_STATE_SET 1319 * @see #ENABLED_STATE_SET 1320 * @see #FOCUSED_STATE_SET 1321 * @see #WINDOW_FOCUSED_STATE_SET 1322 */ 1323 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1324 /** 1325 * Indicates the view is pressed, enabled, focused and selected. 1326 * 1327 * @see #PRESSED_STATE_SET 1328 * @see #ENABLED_STATE_SET 1329 * @see #SELECTED_STATE_SET 1330 * @see #FOCUSED_STATE_SET 1331 */ 1332 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1333 /** 1334 * Indicates the view is pressed, enabled, focused, selected and its window 1335 * has the focus. 1336 * 1337 * @see #PRESSED_STATE_SET 1338 * @see #ENABLED_STATE_SET 1339 * @see #SELECTED_STATE_SET 1340 * @see #FOCUSED_STATE_SET 1341 * @see #WINDOW_FOCUSED_STATE_SET 1342 */ 1343 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1344 1345 /** 1346 * The order here is very important to {@link #getDrawableState()} 1347 */ 1348 private static final int[][] VIEW_STATE_SETS; 1349 1350 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1351 static final int VIEW_STATE_SELECTED = 1 << 1; 1352 static final int VIEW_STATE_FOCUSED = 1 << 2; 1353 static final int VIEW_STATE_ENABLED = 1 << 3; 1354 static final int VIEW_STATE_PRESSED = 1 << 4; 1355 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1356 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1357 static final int VIEW_STATE_HOVERED = 1 << 7; 1358 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1359 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1360 1361 static final int[] VIEW_STATE_IDS = new int[] { 1362 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1363 R.attr.state_selected, VIEW_STATE_SELECTED, 1364 R.attr.state_focused, VIEW_STATE_FOCUSED, 1365 R.attr.state_enabled, VIEW_STATE_ENABLED, 1366 R.attr.state_pressed, VIEW_STATE_PRESSED, 1367 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1368 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1369 R.attr.state_hovered, VIEW_STATE_HOVERED, 1370 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1371 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED, 1372 }; 1373 1374 static { 1375 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1376 throw new IllegalStateException( 1377 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1378 } 1379 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1380 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1381 int viewState = R.styleable.ViewDrawableStates[i]; 1382 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1383 if (VIEW_STATE_IDS[j] == viewState) { 1384 orderedIds[i * 2] = viewState; 1385 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1386 } 1387 } 1388 } 1389 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1390 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1391 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1392 int numBits = Integer.bitCount(i); 1393 int[] set = new int[numBits]; 1394 int pos = 0; 1395 for (int j = 0; j < orderedIds.length; j += 2) { 1396 if ((i & orderedIds[j+1]) != 0) { 1397 set[pos++] = orderedIds[j]; 1398 } 1399 } 1400 VIEW_STATE_SETS[i] = set; 1401 } 1402 1403 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1404 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1405 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1406 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1407 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1408 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1409 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1410 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1411 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1412 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1413 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1414 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1415 | VIEW_STATE_FOCUSED]; 1416 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1417 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1418 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1419 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1420 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1421 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1422 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1423 | VIEW_STATE_ENABLED]; 1424 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1425 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1426 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1427 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1428 | VIEW_STATE_ENABLED]; 1429 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1430 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1431 | VIEW_STATE_ENABLED]; 1432 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1433 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1434 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1435 1436 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1437 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1438 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1439 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1440 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1441 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1442 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1443 | VIEW_STATE_PRESSED]; 1444 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1445 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1446 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1447 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1448 | VIEW_STATE_PRESSED]; 1449 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1450 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1451 | VIEW_STATE_PRESSED]; 1452 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1453 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1454 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1455 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1456 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1457 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1458 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1459 | VIEW_STATE_PRESSED]; 1460 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1461 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1462 | VIEW_STATE_PRESSED]; 1463 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1464 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1465 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1466 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1467 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1468 | VIEW_STATE_PRESSED]; 1469 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1470 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1471 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1472 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1473 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1474 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1475 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1476 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1477 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1478 | VIEW_STATE_PRESSED]; 1479 } 1480 1481 /** 1482 * Accessibility event types that are dispatched for text population. 1483 */ 1484 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1485 AccessibilityEvent.TYPE_VIEW_CLICKED 1486 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1487 | AccessibilityEvent.TYPE_VIEW_SELECTED 1488 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1489 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1490 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1491 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1492 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1493 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED; 1494 1495 /** 1496 * Temporary Rect currently for use in setBackground(). This will probably 1497 * be extended in the future to hold our own class with more than just 1498 * a Rect. :) 1499 */ 1500 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1501 1502 /** 1503 * Map used to store views' tags. 1504 */ 1505 private SparseArray<Object> mKeyedTags; 1506 1507 /** 1508 * The next available accessiiblity id. 1509 */ 1510 private static int sNextAccessibilityViewId; 1511 1512 /** 1513 * The animation currently associated with this view. 1514 * @hide 1515 */ 1516 protected Animation mCurrentAnimation = null; 1517 1518 /** 1519 * Width as measured during measure pass. 1520 * {@hide} 1521 */ 1522 @ViewDebug.ExportedProperty(category = "measurement") 1523 int mMeasuredWidth; 1524 1525 /** 1526 * Height as measured during measure pass. 1527 * {@hide} 1528 */ 1529 @ViewDebug.ExportedProperty(category = "measurement") 1530 int mMeasuredHeight; 1531 1532 /** 1533 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1534 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1535 * its display list. This flag, used only when hw accelerated, allows us to clear the 1536 * flag while retaining this information until it's needed (at getDisplayList() time and 1537 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1538 * 1539 * {@hide} 1540 */ 1541 boolean mRecreateDisplayList = false; 1542 1543 /** 1544 * The view's identifier. 1545 * {@hide} 1546 * 1547 * @see #setId(int) 1548 * @see #getId() 1549 */ 1550 @ViewDebug.ExportedProperty(resolveId = true) 1551 int mID = NO_ID; 1552 1553 /** 1554 * The stable ID of this view for accessibility purposes. 1555 */ 1556 int mAccessibilityViewId = NO_ID; 1557 1558 /** 1559 * The view's tag. 1560 * {@hide} 1561 * 1562 * @see #setTag(Object) 1563 * @see #getTag() 1564 */ 1565 protected Object mTag; 1566 1567 // for mPrivateFlags: 1568 /** {@hide} */ 1569 static final int WANTS_FOCUS = 0x00000001; 1570 /** {@hide} */ 1571 static final int FOCUSED = 0x00000002; 1572 /** {@hide} */ 1573 static final int SELECTED = 0x00000004; 1574 /** {@hide} */ 1575 static final int IS_ROOT_NAMESPACE = 0x00000008; 1576 /** {@hide} */ 1577 static final int HAS_BOUNDS = 0x00000010; 1578 /** {@hide} */ 1579 static final int DRAWN = 0x00000020; 1580 /** 1581 * When this flag is set, this view is running an animation on behalf of its 1582 * children and should therefore not cancel invalidate requests, even if they 1583 * lie outside of this view's bounds. 1584 * 1585 * {@hide} 1586 */ 1587 static final int DRAW_ANIMATION = 0x00000040; 1588 /** {@hide} */ 1589 static final int SKIP_DRAW = 0x00000080; 1590 /** {@hide} */ 1591 static final int ONLY_DRAWS_BACKGROUND = 0x00000100; 1592 /** {@hide} */ 1593 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1594 /** {@hide} */ 1595 static final int DRAWABLE_STATE_DIRTY = 0x00000400; 1596 /** {@hide} */ 1597 static final int MEASURED_DIMENSION_SET = 0x00000800; 1598 /** {@hide} */ 1599 static final int FORCE_LAYOUT = 0x00001000; 1600 /** {@hide} */ 1601 static final int LAYOUT_REQUIRED = 0x00002000; 1602 1603 private static final int PRESSED = 0x00004000; 1604 1605 /** {@hide} */ 1606 static final int DRAWING_CACHE_VALID = 0x00008000; 1607 /** 1608 * Flag used to indicate that this view should be drawn once more (and only once 1609 * more) after its animation has completed. 1610 * {@hide} 1611 */ 1612 static final int ANIMATION_STARTED = 0x00010000; 1613 1614 private static final int SAVE_STATE_CALLED = 0x00020000; 1615 1616 /** 1617 * Indicates that the View returned true when onSetAlpha() was called and that 1618 * the alpha must be restored. 1619 * {@hide} 1620 */ 1621 static final int ALPHA_SET = 0x00040000; 1622 1623 /** 1624 * Set by {@link #setScrollContainer(boolean)}. 1625 */ 1626 static final int SCROLL_CONTAINER = 0x00080000; 1627 1628 /** 1629 * Set by {@link #setScrollContainer(boolean)}. 1630 */ 1631 static final int SCROLL_CONTAINER_ADDED = 0x00100000; 1632 1633 /** 1634 * View flag indicating whether this view was invalidated (fully or partially.) 1635 * 1636 * @hide 1637 */ 1638 static final int DIRTY = 0x00200000; 1639 1640 /** 1641 * View flag indicating whether this view was invalidated by an opaque 1642 * invalidate request. 1643 * 1644 * @hide 1645 */ 1646 static final int DIRTY_OPAQUE = 0x00400000; 1647 1648 /** 1649 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}. 1650 * 1651 * @hide 1652 */ 1653 static final int DIRTY_MASK = 0x00600000; 1654 1655 /** 1656 * Indicates whether the background is opaque. 1657 * 1658 * @hide 1659 */ 1660 static final int OPAQUE_BACKGROUND = 0x00800000; 1661 1662 /** 1663 * Indicates whether the scrollbars are opaque. 1664 * 1665 * @hide 1666 */ 1667 static final int OPAQUE_SCROLLBARS = 0x01000000; 1668 1669 /** 1670 * Indicates whether the view is opaque. 1671 * 1672 * @hide 1673 */ 1674 static final int OPAQUE_MASK = 0x01800000; 1675 1676 /** 1677 * Indicates a prepressed state; 1678 * the short time between ACTION_DOWN and recognizing 1679 * a 'real' press. Prepressed is used to recognize quick taps 1680 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1681 * 1682 * @hide 1683 */ 1684 private static final int PREPRESSED = 0x02000000; 1685 1686 /** 1687 * Indicates whether the view is temporarily detached. 1688 * 1689 * @hide 1690 */ 1691 static final int CANCEL_NEXT_UP_EVENT = 0x04000000; 1692 1693 /** 1694 * Indicates that we should awaken scroll bars once attached 1695 * 1696 * @hide 1697 */ 1698 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1699 1700 /** 1701 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1702 * @hide 1703 */ 1704 private static final int HOVERED = 0x10000000; 1705 1706 /** 1707 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1708 * for transform operations 1709 * 1710 * @hide 1711 */ 1712 private static final int PIVOT_EXPLICITLY_SET = 0x20000000; 1713 1714 /** {@hide} */ 1715 static final int ACTIVATED = 0x40000000; 1716 1717 /** 1718 * Indicates that this view was specifically invalidated, not just dirtied because some 1719 * child view was invalidated. The flag is used to determine when we need to recreate 1720 * a view's display list (as opposed to just returning a reference to its existing 1721 * display list). 1722 * 1723 * @hide 1724 */ 1725 static final int INVALIDATED = 0x80000000; 1726 1727 /* Masks for mPrivateFlags2 */ 1728 1729 /** 1730 * Indicates that this view has reported that it can accept the current drag's content. 1731 * Cleared when the drag operation concludes. 1732 * @hide 1733 */ 1734 static final int DRAG_CAN_ACCEPT = 0x00000001; 1735 1736 /** 1737 * Indicates that this view is currently directly under the drag location in a 1738 * drag-and-drop operation involving content that it can accept. Cleared when 1739 * the drag exits the view, or when the drag operation concludes. 1740 * @hide 1741 */ 1742 static final int DRAG_HOVERED = 0x00000002; 1743 1744 /** 1745 * Indicates whether the view layout direction has been resolved and drawn to the 1746 * right-to-left direction. 1747 * 1748 * @hide 1749 */ 1750 static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004; 1751 1752 /** 1753 * Indicates whether the view layout direction has been resolved. 1754 * 1755 * @hide 1756 */ 1757 static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008; 1758 1759 1760 /* End of masks for mPrivateFlags2 */ 1761 1762 static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED; 1763 1764 /** 1765 * Always allow a user to over-scroll this view, provided it is a 1766 * view that can scroll. 1767 * 1768 * @see #getOverScrollMode() 1769 * @see #setOverScrollMode(int) 1770 */ 1771 public static final int OVER_SCROLL_ALWAYS = 0; 1772 1773 /** 1774 * Allow a user to over-scroll this view only if the content is large 1775 * enough to meaningfully scroll, provided it is a view that can scroll. 1776 * 1777 * @see #getOverScrollMode() 1778 * @see #setOverScrollMode(int) 1779 */ 1780 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 1781 1782 /** 1783 * Never allow a user to over-scroll this view. 1784 * 1785 * @see #getOverScrollMode() 1786 * @see #setOverScrollMode(int) 1787 */ 1788 public static final int OVER_SCROLL_NEVER = 2; 1789 1790 /** 1791 * View has requested the system UI (status bar) to be visible (the default). 1792 * 1793 * @see #setSystemUiVisibility(int) 1794 */ 1795 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 1796 1797 /** 1798 * View has requested the system UI to enter an unobtrusive "low profile" mode. 1799 * 1800 * This is for use in games, book readers, video players, or any other "immersive" application 1801 * where the usual system chrome is deemed too distracting. 1802 * 1803 * In low profile mode, the status bar and/or navigation icons may dim. 1804 * 1805 * @see #setSystemUiVisibility(int) 1806 */ 1807 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 1808 1809 /** 1810 * View has requested that the system navigation be temporarily hidden. 1811 * 1812 * This is an even less obtrusive state than that called for by 1813 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 1814 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 1815 * those to disappear. This is useful (in conjunction with the 1816 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 1817 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 1818 * window flags) for displaying content using every last pixel on the display. 1819 * 1820 * There is a limitation: because navigation controls are so important, the least user 1821 * interaction will cause them to reappear immediately. 1822 * 1823 * @see #setSystemUiVisibility(int) 1824 */ 1825 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 1826 1827 /** 1828 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 1829 */ 1830 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 1831 1832 /** 1833 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 1834 */ 1835 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 1836 1837 /** 1838 * @hide 1839 * 1840 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1841 * out of the public fields to keep the undefined bits out of the developer's way. 1842 * 1843 * Flag to make the status bar not expandable. Unless you also 1844 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 1845 */ 1846 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 1847 1848 /** 1849 * @hide 1850 * 1851 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1852 * out of the public fields to keep the undefined bits out of the developer's way. 1853 * 1854 * Flag to hide notification icons and scrolling ticker text. 1855 */ 1856 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 1857 1858 /** 1859 * @hide 1860 * 1861 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1862 * out of the public fields to keep the undefined bits out of the developer's way. 1863 * 1864 * Flag to disable incoming notification alerts. This will not block 1865 * icons, but it will block sound, vibrating and other visual or aural notifications. 1866 */ 1867 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 1868 1869 /** 1870 * @hide 1871 * 1872 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1873 * out of the public fields to keep the undefined bits out of the developer's way. 1874 * 1875 * Flag to hide only the scrolling ticker. Note that 1876 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 1877 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 1878 */ 1879 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 1880 1881 /** 1882 * @hide 1883 * 1884 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1885 * out of the public fields to keep the undefined bits out of the developer's way. 1886 * 1887 * Flag to hide the center system info area. 1888 */ 1889 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 1890 1891 /** 1892 * @hide 1893 * 1894 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1895 * out of the public fields to keep the undefined bits out of the developer's way. 1896 * 1897 * Flag to hide only the home button. Don't use this 1898 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1899 */ 1900 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 1901 1902 /** 1903 * @hide 1904 * 1905 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1906 * out of the public fields to keep the undefined bits out of the developer's way. 1907 * 1908 * Flag to hide only the back button. Don't use this 1909 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1910 */ 1911 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 1912 1913 /** 1914 * @hide 1915 * 1916 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1917 * out of the public fields to keep the undefined bits out of the developer's way. 1918 * 1919 * Flag to hide only the clock. You might use this if your activity has 1920 * its own clock making the status bar's clock redundant. 1921 */ 1922 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 1923 1924 /** 1925 * @hide 1926 * 1927 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1928 * out of the public fields to keep the undefined bits out of the developer's way. 1929 * 1930 * Flag to hide only the recent apps button. Don't use this 1931 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1932 */ 1933 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 1934 1935 /** 1936 * @hide 1937 * 1938 * NOTE: This flag may only be used in subtreeSystemUiVisibility, etc. etc. 1939 * 1940 * This hides HOME and RECENT and is provided for compatibility with interim implementations. 1941 */ 1942 @Deprecated 1943 public static final int STATUS_BAR_DISABLE_NAVIGATION = 1944 STATUS_BAR_DISABLE_HOME | STATUS_BAR_DISABLE_RECENT; 1945 1946 /** 1947 * @hide 1948 */ 1949 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 1950 1951 /** 1952 * These are the system UI flags that can be cleared by events outside 1953 * of an application. Currently this is just the ability to tap on the 1954 * screen while hiding the navigation bar to have it return. 1955 * @hide 1956 */ 1957 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 1958 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION; 1959 1960 /** 1961 * Find views that render the specified text. 1962 * 1963 * @see #findViewsWithText(ArrayList, CharSequence, int) 1964 */ 1965 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 1966 1967 /** 1968 * Find find views that contain the specified content description. 1969 * 1970 * @see #findViewsWithText(ArrayList, CharSequence, int) 1971 */ 1972 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 1973 1974 /** 1975 * Find views that contain {@link AccessibilityNodeProvider}. Such 1976 * a View is a root of virtual view hierarchy and may contain the searched 1977 * text. If this flag is set Views with providers are automatically 1978 * added and it is a responsibility of the client to call the APIs of 1979 * the provider to determine whether the virtual tree rooted at this View 1980 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 1981 * represeting the virtual views with this text. 1982 * 1983 * @see #findViewsWithText(ArrayList, CharSequence, int) 1984 * 1985 * @hide 1986 */ 1987 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 1988 1989 /** 1990 * Controls the over-scroll mode for this view. 1991 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 1992 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 1993 * and {@link #OVER_SCROLL_NEVER}. 1994 */ 1995 private int mOverScrollMode; 1996 1997 /** 1998 * The parent this view is attached to. 1999 * {@hide} 2000 * 2001 * @see #getParent() 2002 */ 2003 protected ViewParent mParent; 2004 2005 /** 2006 * {@hide} 2007 */ 2008 AttachInfo mAttachInfo; 2009 2010 /** 2011 * {@hide} 2012 */ 2013 @ViewDebug.ExportedProperty(flagMapping = { 2014 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT, 2015 name = "FORCE_LAYOUT"), 2016 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED, 2017 name = "LAYOUT_REQUIRED"), 2018 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID, 2019 name = "DRAWING_CACHE_INVALID", outputIf = false), 2020 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true), 2021 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false), 2022 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2023 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY") 2024 }) 2025 int mPrivateFlags; 2026 int mPrivateFlags2; 2027 2028 /** 2029 * This view's request for the visibility of the status bar. 2030 * @hide 2031 */ 2032 @ViewDebug.ExportedProperty(flagMapping = { 2033 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2034 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2035 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2036 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2037 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2038 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2039 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2040 equals = SYSTEM_UI_FLAG_VISIBLE, 2041 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2042 }) 2043 int mSystemUiVisibility; 2044 2045 /** 2046 * Count of how many windows this view has been attached to. 2047 */ 2048 int mWindowAttachCount; 2049 2050 /** 2051 * The layout parameters associated with this view and used by the parent 2052 * {@link android.view.ViewGroup} to determine how this view should be 2053 * laid out. 2054 * {@hide} 2055 */ 2056 protected ViewGroup.LayoutParams mLayoutParams; 2057 2058 /** 2059 * The view flags hold various views states. 2060 * {@hide} 2061 */ 2062 @ViewDebug.ExportedProperty 2063 int mViewFlags; 2064 2065 static class TransformationInfo { 2066 /** 2067 * The transform matrix for the View. This transform is calculated internally 2068 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2069 * is used by default. Do *not* use this variable directly; instead call 2070 * getMatrix(), which will automatically recalculate the matrix if necessary 2071 * to get the correct matrix based on the latest rotation and scale properties. 2072 */ 2073 private final Matrix mMatrix = new Matrix(); 2074 2075 /** 2076 * The transform matrix for the View. This transform is calculated internally 2077 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2078 * is used by default. Do *not* use this variable directly; instead call 2079 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2080 * to get the correct matrix based on the latest rotation and scale properties. 2081 */ 2082 private Matrix mInverseMatrix; 2083 2084 /** 2085 * An internal variable that tracks whether we need to recalculate the 2086 * transform matrix, based on whether the rotation or scaleX/Y properties 2087 * have changed since the matrix was last calculated. 2088 */ 2089 boolean mMatrixDirty = false; 2090 2091 /** 2092 * An internal variable that tracks whether we need to recalculate the 2093 * transform matrix, based on whether the rotation or scaleX/Y properties 2094 * have changed since the matrix was last calculated. 2095 */ 2096 private boolean mInverseMatrixDirty = true; 2097 2098 /** 2099 * A variable that tracks whether we need to recalculate the 2100 * transform matrix, based on whether the rotation or scaleX/Y properties 2101 * have changed since the matrix was last calculated. This variable 2102 * is only valid after a call to updateMatrix() or to a function that 2103 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2104 */ 2105 private boolean mMatrixIsIdentity = true; 2106 2107 /** 2108 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2109 */ 2110 private Camera mCamera = null; 2111 2112 /** 2113 * This matrix is used when computing the matrix for 3D rotations. 2114 */ 2115 private Matrix matrix3D = null; 2116 2117 /** 2118 * These prev values are used to recalculate a centered pivot point when necessary. The 2119 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2120 * set), so thes values are only used then as well. 2121 */ 2122 private int mPrevWidth = -1; 2123 private int mPrevHeight = -1; 2124 2125 /** 2126 * The degrees rotation around the vertical axis through the pivot point. 2127 */ 2128 @ViewDebug.ExportedProperty 2129 float mRotationY = 0f; 2130 2131 /** 2132 * The degrees rotation around the horizontal axis through the pivot point. 2133 */ 2134 @ViewDebug.ExportedProperty 2135 float mRotationX = 0f; 2136 2137 /** 2138 * The degrees rotation around the pivot point. 2139 */ 2140 @ViewDebug.ExportedProperty 2141 float mRotation = 0f; 2142 2143 /** 2144 * The amount of translation of the object away from its left property (post-layout). 2145 */ 2146 @ViewDebug.ExportedProperty 2147 float mTranslationX = 0f; 2148 2149 /** 2150 * The amount of translation of the object away from its top property (post-layout). 2151 */ 2152 @ViewDebug.ExportedProperty 2153 float mTranslationY = 0f; 2154 2155 /** 2156 * The amount of scale in the x direction around the pivot point. A 2157 * value of 1 means no scaling is applied. 2158 */ 2159 @ViewDebug.ExportedProperty 2160 float mScaleX = 1f; 2161 2162 /** 2163 * The amount of scale in the y direction around the pivot point. A 2164 * value of 1 means no scaling is applied. 2165 */ 2166 @ViewDebug.ExportedProperty 2167 float mScaleY = 1f; 2168 2169 /** 2170 * The x location of the point around which the view is rotated and scaled. 2171 */ 2172 @ViewDebug.ExportedProperty 2173 float mPivotX = 0f; 2174 2175 /** 2176 * The y location of the point around which the view is rotated and scaled. 2177 */ 2178 @ViewDebug.ExportedProperty 2179 float mPivotY = 0f; 2180 2181 /** 2182 * The opacity of the View. This is a value from 0 to 1, where 0 means 2183 * completely transparent and 1 means completely opaque. 2184 */ 2185 @ViewDebug.ExportedProperty 2186 float mAlpha = 1f; 2187 } 2188 2189 TransformationInfo mTransformationInfo; 2190 2191 private boolean mLastIsOpaque; 2192 2193 /** 2194 * Convenience value to check for float values that are close enough to zero to be considered 2195 * zero. 2196 */ 2197 private static final float NONZERO_EPSILON = .001f; 2198 2199 /** 2200 * The distance in pixels from the left edge of this view's parent 2201 * to the left edge of this view. 2202 * {@hide} 2203 */ 2204 @ViewDebug.ExportedProperty(category = "layout") 2205 protected int mLeft; 2206 /** 2207 * The distance in pixels from the left edge of this view's parent 2208 * to the right edge of this view. 2209 * {@hide} 2210 */ 2211 @ViewDebug.ExportedProperty(category = "layout") 2212 protected int mRight; 2213 /** 2214 * The distance in pixels from the top edge of this view's parent 2215 * to the top edge of this view. 2216 * {@hide} 2217 */ 2218 @ViewDebug.ExportedProperty(category = "layout") 2219 protected int mTop; 2220 /** 2221 * The distance in pixels from the top edge of this view's parent 2222 * to the bottom edge of this view. 2223 * {@hide} 2224 */ 2225 @ViewDebug.ExportedProperty(category = "layout") 2226 protected int mBottom; 2227 2228 /** 2229 * The offset, in pixels, by which the content of this view is scrolled 2230 * horizontally. 2231 * {@hide} 2232 */ 2233 @ViewDebug.ExportedProperty(category = "scrolling") 2234 protected int mScrollX; 2235 /** 2236 * The offset, in pixels, by which the content of this view is scrolled 2237 * vertically. 2238 * {@hide} 2239 */ 2240 @ViewDebug.ExportedProperty(category = "scrolling") 2241 protected int mScrollY; 2242 2243 /** 2244 * The left padding in pixels, that is the distance in pixels between the 2245 * left edge of this view and the left edge of its content. 2246 * {@hide} 2247 */ 2248 @ViewDebug.ExportedProperty(category = "padding") 2249 protected int mPaddingLeft; 2250 /** 2251 * The right padding in pixels, that is the distance in pixels between the 2252 * right edge of this view and the right edge of its content. 2253 * {@hide} 2254 */ 2255 @ViewDebug.ExportedProperty(category = "padding") 2256 protected int mPaddingRight; 2257 /** 2258 * The top padding in pixels, that is the distance in pixels between the 2259 * top edge of this view and the top edge of its content. 2260 * {@hide} 2261 */ 2262 @ViewDebug.ExportedProperty(category = "padding") 2263 protected int mPaddingTop; 2264 /** 2265 * The bottom padding in pixels, that is the distance in pixels between the 2266 * bottom edge of this view and the bottom edge of its content. 2267 * {@hide} 2268 */ 2269 @ViewDebug.ExportedProperty(category = "padding") 2270 protected int mPaddingBottom; 2271 2272 /** 2273 * Briefly describes the view and is primarily used for accessibility support. 2274 */ 2275 private CharSequence mContentDescription; 2276 2277 /** 2278 * Cache the paddingRight set by the user to append to the scrollbar's size. 2279 * 2280 * @hide 2281 */ 2282 @ViewDebug.ExportedProperty(category = "padding") 2283 protected int mUserPaddingRight; 2284 2285 /** 2286 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2287 * 2288 * @hide 2289 */ 2290 @ViewDebug.ExportedProperty(category = "padding") 2291 protected int mUserPaddingBottom; 2292 2293 /** 2294 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2295 * 2296 * @hide 2297 */ 2298 @ViewDebug.ExportedProperty(category = "padding") 2299 protected int mUserPaddingLeft; 2300 2301 /** 2302 * Cache if the user padding is relative. 2303 * 2304 */ 2305 @ViewDebug.ExportedProperty(category = "padding") 2306 boolean mUserPaddingRelative; 2307 2308 /** 2309 * Cache the paddingStart set by the user to append to the scrollbar's size. 2310 * 2311 */ 2312 @ViewDebug.ExportedProperty(category = "padding") 2313 int mUserPaddingStart; 2314 2315 /** 2316 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2317 * 2318 */ 2319 @ViewDebug.ExportedProperty(category = "padding") 2320 int mUserPaddingEnd; 2321 2322 /** 2323 * @hide 2324 */ 2325 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2326 /** 2327 * @hide 2328 */ 2329 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2330 2331 private Drawable mBGDrawable; 2332 2333 private int mBackgroundResource; 2334 private boolean mBackgroundSizeChanged; 2335 2336 static class ListenerInfo { 2337 /** 2338 * Listener used to dispatch focus change events. 2339 * This field should be made private, so it is hidden from the SDK. 2340 * {@hide} 2341 */ 2342 protected OnFocusChangeListener mOnFocusChangeListener; 2343 2344 /** 2345 * Listeners for layout change events. 2346 */ 2347 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2348 2349 /** 2350 * Listeners for attach events. 2351 */ 2352 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2353 2354 /** 2355 * Listener used to dispatch click events. 2356 * This field should be made private, so it is hidden from the SDK. 2357 * {@hide} 2358 */ 2359 public OnClickListener mOnClickListener; 2360 2361 /** 2362 * Listener used to dispatch long click events. 2363 * This field should be made private, so it is hidden from the SDK. 2364 * {@hide} 2365 */ 2366 protected OnLongClickListener mOnLongClickListener; 2367 2368 /** 2369 * Listener used to build the context menu. 2370 * This field should be made private, so it is hidden from the SDK. 2371 * {@hide} 2372 */ 2373 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2374 2375 private OnKeyListener mOnKeyListener; 2376 2377 private OnTouchListener mOnTouchListener; 2378 2379 private OnHoverListener mOnHoverListener; 2380 2381 private OnGenericMotionListener mOnGenericMotionListener; 2382 2383 private OnDragListener mOnDragListener; 2384 2385 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2386 } 2387 2388 ListenerInfo mListenerInfo; 2389 2390 /** 2391 * The application environment this view lives in. 2392 * This field should be made private, so it is hidden from the SDK. 2393 * {@hide} 2394 */ 2395 protected Context mContext; 2396 2397 private final Resources mResources; 2398 2399 private ScrollabilityCache mScrollCache; 2400 2401 private int[] mDrawableState = null; 2402 2403 /** 2404 * Set to true when drawing cache is enabled and cannot be created. 2405 * 2406 * @hide 2407 */ 2408 public boolean mCachingFailed; 2409 2410 private Bitmap mDrawingCache; 2411 private Bitmap mUnscaledDrawingCache; 2412 private HardwareLayer mHardwareLayer; 2413 DisplayList mDisplayList; 2414 2415 /** 2416 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2417 * the user may specify which view to go to next. 2418 */ 2419 private int mNextFocusLeftId = View.NO_ID; 2420 2421 /** 2422 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2423 * the user may specify which view to go to next. 2424 */ 2425 private int mNextFocusRightId = View.NO_ID; 2426 2427 /** 2428 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2429 * the user may specify which view to go to next. 2430 */ 2431 private int mNextFocusUpId = View.NO_ID; 2432 2433 /** 2434 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2435 * the user may specify which view to go to next. 2436 */ 2437 private int mNextFocusDownId = View.NO_ID; 2438 2439 /** 2440 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 2441 * the user may specify which view to go to next. 2442 */ 2443 int mNextFocusForwardId = View.NO_ID; 2444 2445 private CheckForLongPress mPendingCheckForLongPress; 2446 private CheckForTap mPendingCheckForTap = null; 2447 private PerformClick mPerformClick; 2448 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 2449 2450 private UnsetPressedState mUnsetPressedState; 2451 2452 /** 2453 * Whether the long press's action has been invoked. The tap's action is invoked on the 2454 * up event while a long press is invoked as soon as the long press duration is reached, so 2455 * a long press could be performed before the tap is checked, in which case the tap's action 2456 * should not be invoked. 2457 */ 2458 private boolean mHasPerformedLongPress; 2459 2460 /** 2461 * The minimum height of the view. We'll try our best to have the height 2462 * of this view to at least this amount. 2463 */ 2464 @ViewDebug.ExportedProperty(category = "measurement") 2465 private int mMinHeight; 2466 2467 /** 2468 * The minimum width of the view. We'll try our best to have the width 2469 * of this view to at least this amount. 2470 */ 2471 @ViewDebug.ExportedProperty(category = "measurement") 2472 private int mMinWidth; 2473 2474 /** 2475 * The delegate to handle touch events that are physically in this view 2476 * but should be handled by another view. 2477 */ 2478 private TouchDelegate mTouchDelegate = null; 2479 2480 /** 2481 * Solid color to use as a background when creating the drawing cache. Enables 2482 * the cache to use 16 bit bitmaps instead of 32 bit. 2483 */ 2484 private int mDrawingCacheBackgroundColor = 0; 2485 2486 /** 2487 * Special tree observer used when mAttachInfo is null. 2488 */ 2489 private ViewTreeObserver mFloatingTreeObserver; 2490 2491 /** 2492 * Cache the touch slop from the context that created the view. 2493 */ 2494 private int mTouchSlop; 2495 2496 /** 2497 * Object that handles automatic animation of view properties. 2498 */ 2499 private ViewPropertyAnimator mAnimator = null; 2500 2501 /** 2502 * Flag indicating that a drag can cross window boundaries. When 2503 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 2504 * with this flag set, all visible applications will be able to participate 2505 * in the drag operation and receive the dragged content. 2506 * 2507 * @hide 2508 */ 2509 public static final int DRAG_FLAG_GLOBAL = 1; 2510 2511 /** 2512 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 2513 */ 2514 private float mVerticalScrollFactor; 2515 2516 /** 2517 * Position of the vertical scroll bar. 2518 */ 2519 private int mVerticalScrollbarPosition; 2520 2521 /** 2522 * Position the scroll bar at the default position as determined by the system. 2523 */ 2524 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 2525 2526 /** 2527 * Position the scroll bar along the left edge. 2528 */ 2529 public static final int SCROLLBAR_POSITION_LEFT = 1; 2530 2531 /** 2532 * Position the scroll bar along the right edge. 2533 */ 2534 public static final int SCROLLBAR_POSITION_RIGHT = 2; 2535 2536 /** 2537 * Indicates that the view does not have a layer. 2538 * 2539 * @see #getLayerType() 2540 * @see #setLayerType(int, android.graphics.Paint) 2541 * @see #LAYER_TYPE_SOFTWARE 2542 * @see #LAYER_TYPE_HARDWARE 2543 */ 2544 public static final int LAYER_TYPE_NONE = 0; 2545 2546 /** 2547 * <p>Indicates that the view has a software layer. A software layer is backed 2548 * by a bitmap and causes the view to be rendered using Android's software 2549 * rendering pipeline, even if hardware acceleration is enabled.</p> 2550 * 2551 * <p>Software layers have various usages:</p> 2552 * <p>When the application is not using hardware acceleration, a software layer 2553 * is useful to apply a specific color filter and/or blending mode and/or 2554 * translucency to a view and all its children.</p> 2555 * <p>When the application is using hardware acceleration, a software layer 2556 * is useful to render drawing primitives not supported by the hardware 2557 * accelerated pipeline. It can also be used to cache a complex view tree 2558 * into a texture and reduce the complexity of drawing operations. For instance, 2559 * when animating a complex view tree with a translation, a software layer can 2560 * be used to render the view tree only once.</p> 2561 * <p>Software layers should be avoided when the affected view tree updates 2562 * often. Every update will require to re-render the software layer, which can 2563 * potentially be slow (particularly when hardware acceleration is turned on 2564 * since the layer will have to be uploaded into a hardware texture after every 2565 * update.)</p> 2566 * 2567 * @see #getLayerType() 2568 * @see #setLayerType(int, android.graphics.Paint) 2569 * @see #LAYER_TYPE_NONE 2570 * @see #LAYER_TYPE_HARDWARE 2571 */ 2572 public static final int LAYER_TYPE_SOFTWARE = 1; 2573 2574 /** 2575 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 2576 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 2577 * OpenGL hardware) and causes the view to be rendered using Android's hardware 2578 * rendering pipeline, but only if hardware acceleration is turned on for the 2579 * view hierarchy. When hardware acceleration is turned off, hardware layers 2580 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 2581 * 2582 * <p>A hardware layer is useful to apply a specific color filter and/or 2583 * blending mode and/or translucency to a view and all its children.</p> 2584 * <p>A hardware layer can be used to cache a complex view tree into a 2585 * texture and reduce the complexity of drawing operations. For instance, 2586 * when animating a complex view tree with a translation, a hardware layer can 2587 * be used to render the view tree only once.</p> 2588 * <p>A hardware layer can also be used to increase the rendering quality when 2589 * rotation transformations are applied on a view. It can also be used to 2590 * prevent potential clipping issues when applying 3D transforms on a view.</p> 2591 * 2592 * @see #getLayerType() 2593 * @see #setLayerType(int, android.graphics.Paint) 2594 * @see #LAYER_TYPE_NONE 2595 * @see #LAYER_TYPE_SOFTWARE 2596 */ 2597 public static final int LAYER_TYPE_HARDWARE = 2; 2598 2599 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 2600 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 2601 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 2602 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 2603 }) 2604 int mLayerType = LAYER_TYPE_NONE; 2605 Paint mLayerPaint; 2606 Rect mLocalDirtyRect; 2607 2608 /** 2609 * Set to true when the view is sending hover accessibility events because it 2610 * is the innermost hovered view. 2611 */ 2612 private boolean mSendingHoverAccessibilityEvents; 2613 2614 /** 2615 * Delegate for injecting accessiblity functionality. 2616 */ 2617 AccessibilityDelegate mAccessibilityDelegate; 2618 2619 /** 2620 * Text direction is inherited thru {@link ViewGroup} 2621 * @hide 2622 */ 2623 public static final int TEXT_DIRECTION_INHERIT = 0; 2624 2625 /** 2626 * Text direction is using "first strong algorithm". The first strong directional character 2627 * determines the paragraph direction. If there is no strong directional character, the 2628 * paragraph direction is the view's resolved layout direction. 2629 * 2630 * @hide 2631 */ 2632 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 2633 2634 /** 2635 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 2636 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 2637 * If there are neither, the paragraph direction is the view's resolved layout direction. 2638 * 2639 * @hide 2640 */ 2641 public static final int TEXT_DIRECTION_ANY_RTL = 2; 2642 2643 /** 2644 * Text direction is forced to LTR. 2645 * 2646 * @hide 2647 */ 2648 public static final int TEXT_DIRECTION_LTR = 3; 2649 2650 /** 2651 * Text direction is forced to RTL. 2652 * 2653 * @hide 2654 */ 2655 public static final int TEXT_DIRECTION_RTL = 4; 2656 2657 /** 2658 * Text direction is coming from the system Locale. 2659 * 2660 * @hide 2661 */ 2662 public static final int TEXT_DIRECTION_LOCALE = 5; 2663 2664 /** 2665 * Default text direction is inherited 2666 * 2667 * @hide 2668 */ 2669 protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT; 2670 2671 /** 2672 * The text direction that has been defined by {@link #setTextDirection(int)}. 2673 * 2674 * {@hide} 2675 */ 2676 @ViewDebug.ExportedProperty(category = "text", mapping = { 2677 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 2678 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 2679 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 2680 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 2681 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 2682 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 2683 }) 2684 private int mTextDirection = DEFAULT_TEXT_DIRECTION; 2685 2686 /** 2687 * The resolved text direction. This needs resolution if the value is 2688 * TEXT_DIRECTION_INHERIT. The resolution matches mTextDirection if it is 2689 * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent 2690 * chain of the view. 2691 * 2692 * {@hide} 2693 */ 2694 @ViewDebug.ExportedProperty(category = "text", mapping = { 2695 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 2696 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 2697 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 2698 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 2699 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 2700 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 2701 }) 2702 private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT; 2703 2704 /** 2705 * Consistency verifier for debugging purposes. 2706 * @hide 2707 */ 2708 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 2709 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 2710 new InputEventConsistencyVerifier(this, 0) : null; 2711 2712 /** 2713 * Simple constructor to use when creating a view from code. 2714 * 2715 * @param context The Context the view is running in, through which it can 2716 * access the current theme, resources, etc. 2717 */ 2718 public View(Context context) { 2719 mContext = context; 2720 mResources = context != null ? context.getResources() : null; 2721 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT; 2722 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 2723 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 2724 mUserPaddingStart = -1; 2725 mUserPaddingEnd = -1; 2726 mUserPaddingRelative = false; 2727 } 2728 2729 /** 2730 * Constructor that is called when inflating a view from XML. This is called 2731 * when a view is being constructed from an XML file, supplying attributes 2732 * that were specified in the XML file. This version uses a default style of 2733 * 0, so the only attribute values applied are those in the Context's Theme 2734 * and the given AttributeSet. 2735 * 2736 * <p> 2737 * The method onFinishInflate() will be called after all children have been 2738 * added. 2739 * 2740 * @param context The Context the view is running in, through which it can 2741 * access the current theme, resources, etc. 2742 * @param attrs The attributes of the XML tag that is inflating the view. 2743 * @see #View(Context, AttributeSet, int) 2744 */ 2745 public View(Context context, AttributeSet attrs) { 2746 this(context, attrs, 0); 2747 } 2748 2749 /** 2750 * Perform inflation from XML and apply a class-specific base style. This 2751 * constructor of View allows subclasses to use their own base style when 2752 * they are inflating. For example, a Button class's constructor would call 2753 * this version of the super class constructor and supply 2754 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 2755 * the theme's button style to modify all of the base view attributes (in 2756 * particular its background) as well as the Button class's attributes. 2757 * 2758 * @param context The Context the view is running in, through which it can 2759 * access the current theme, resources, etc. 2760 * @param attrs The attributes of the XML tag that is inflating the view. 2761 * @param defStyle The default style to apply to this view. If 0, no style 2762 * will be applied (beyond what is included in the theme). This may 2763 * either be an attribute resource, whose value will be retrieved 2764 * from the current theme, or an explicit style resource. 2765 * @see #View(Context, AttributeSet) 2766 */ 2767 public View(Context context, AttributeSet attrs, int defStyle) { 2768 this(context); 2769 2770 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 2771 defStyle, 0); 2772 2773 Drawable background = null; 2774 2775 int leftPadding = -1; 2776 int topPadding = -1; 2777 int rightPadding = -1; 2778 int bottomPadding = -1; 2779 int startPadding = -1; 2780 int endPadding = -1; 2781 2782 int padding = -1; 2783 2784 int viewFlagValues = 0; 2785 int viewFlagMasks = 0; 2786 2787 boolean setScrollContainer = false; 2788 2789 int x = 0; 2790 int y = 0; 2791 2792 float tx = 0; 2793 float ty = 0; 2794 float rotation = 0; 2795 float rotationX = 0; 2796 float rotationY = 0; 2797 float sx = 1f; 2798 float sy = 1f; 2799 boolean transformSet = false; 2800 2801 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 2802 2803 int overScrollMode = mOverScrollMode; 2804 final int N = a.getIndexCount(); 2805 for (int i = 0; i < N; i++) { 2806 int attr = a.getIndex(i); 2807 switch (attr) { 2808 case com.android.internal.R.styleable.View_background: 2809 background = a.getDrawable(attr); 2810 break; 2811 case com.android.internal.R.styleable.View_padding: 2812 padding = a.getDimensionPixelSize(attr, -1); 2813 break; 2814 case com.android.internal.R.styleable.View_paddingLeft: 2815 leftPadding = a.getDimensionPixelSize(attr, -1); 2816 break; 2817 case com.android.internal.R.styleable.View_paddingTop: 2818 topPadding = a.getDimensionPixelSize(attr, -1); 2819 break; 2820 case com.android.internal.R.styleable.View_paddingRight: 2821 rightPadding = a.getDimensionPixelSize(attr, -1); 2822 break; 2823 case com.android.internal.R.styleable.View_paddingBottom: 2824 bottomPadding = a.getDimensionPixelSize(attr, -1); 2825 break; 2826 case com.android.internal.R.styleable.View_paddingStart: 2827 startPadding = a.getDimensionPixelSize(attr, -1); 2828 break; 2829 case com.android.internal.R.styleable.View_paddingEnd: 2830 endPadding = a.getDimensionPixelSize(attr, -1); 2831 break; 2832 case com.android.internal.R.styleable.View_scrollX: 2833 x = a.getDimensionPixelOffset(attr, 0); 2834 break; 2835 case com.android.internal.R.styleable.View_scrollY: 2836 y = a.getDimensionPixelOffset(attr, 0); 2837 break; 2838 case com.android.internal.R.styleable.View_alpha: 2839 setAlpha(a.getFloat(attr, 1f)); 2840 break; 2841 case com.android.internal.R.styleable.View_transformPivotX: 2842 setPivotX(a.getDimensionPixelOffset(attr, 0)); 2843 break; 2844 case com.android.internal.R.styleable.View_transformPivotY: 2845 setPivotY(a.getDimensionPixelOffset(attr, 0)); 2846 break; 2847 case com.android.internal.R.styleable.View_translationX: 2848 tx = a.getDimensionPixelOffset(attr, 0); 2849 transformSet = true; 2850 break; 2851 case com.android.internal.R.styleable.View_translationY: 2852 ty = a.getDimensionPixelOffset(attr, 0); 2853 transformSet = true; 2854 break; 2855 case com.android.internal.R.styleable.View_rotation: 2856 rotation = a.getFloat(attr, 0); 2857 transformSet = true; 2858 break; 2859 case com.android.internal.R.styleable.View_rotationX: 2860 rotationX = a.getFloat(attr, 0); 2861 transformSet = true; 2862 break; 2863 case com.android.internal.R.styleable.View_rotationY: 2864 rotationY = a.getFloat(attr, 0); 2865 transformSet = true; 2866 break; 2867 case com.android.internal.R.styleable.View_scaleX: 2868 sx = a.getFloat(attr, 1f); 2869 transformSet = true; 2870 break; 2871 case com.android.internal.R.styleable.View_scaleY: 2872 sy = a.getFloat(attr, 1f); 2873 transformSet = true; 2874 break; 2875 case com.android.internal.R.styleable.View_id: 2876 mID = a.getResourceId(attr, NO_ID); 2877 break; 2878 case com.android.internal.R.styleable.View_tag: 2879 mTag = a.getText(attr); 2880 break; 2881 case com.android.internal.R.styleable.View_fitsSystemWindows: 2882 if (a.getBoolean(attr, false)) { 2883 viewFlagValues |= FITS_SYSTEM_WINDOWS; 2884 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 2885 } 2886 break; 2887 case com.android.internal.R.styleable.View_focusable: 2888 if (a.getBoolean(attr, false)) { 2889 viewFlagValues |= FOCUSABLE; 2890 viewFlagMasks |= FOCUSABLE_MASK; 2891 } 2892 break; 2893 case com.android.internal.R.styleable.View_focusableInTouchMode: 2894 if (a.getBoolean(attr, false)) { 2895 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 2896 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 2897 } 2898 break; 2899 case com.android.internal.R.styleable.View_clickable: 2900 if (a.getBoolean(attr, false)) { 2901 viewFlagValues |= CLICKABLE; 2902 viewFlagMasks |= CLICKABLE; 2903 } 2904 break; 2905 case com.android.internal.R.styleable.View_longClickable: 2906 if (a.getBoolean(attr, false)) { 2907 viewFlagValues |= LONG_CLICKABLE; 2908 viewFlagMasks |= LONG_CLICKABLE; 2909 } 2910 break; 2911 case com.android.internal.R.styleable.View_saveEnabled: 2912 if (!a.getBoolean(attr, true)) { 2913 viewFlagValues |= SAVE_DISABLED; 2914 viewFlagMasks |= SAVE_DISABLED_MASK; 2915 } 2916 break; 2917 case com.android.internal.R.styleable.View_duplicateParentState: 2918 if (a.getBoolean(attr, false)) { 2919 viewFlagValues |= DUPLICATE_PARENT_STATE; 2920 viewFlagMasks |= DUPLICATE_PARENT_STATE; 2921 } 2922 break; 2923 case com.android.internal.R.styleable.View_visibility: 2924 final int visibility = a.getInt(attr, 0); 2925 if (visibility != 0) { 2926 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 2927 viewFlagMasks |= VISIBILITY_MASK; 2928 } 2929 break; 2930 case com.android.internal.R.styleable.View_layoutDirection: 2931 // Clear any HORIZONTAL_DIRECTION flag already set 2932 viewFlagValues &= ~LAYOUT_DIRECTION_MASK; 2933 // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute 2934 final int layoutDirection = a.getInt(attr, -1); 2935 if (layoutDirection != -1) { 2936 viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection]; 2937 } else { 2938 // Set to default (LAYOUT_DIRECTION_INHERIT) 2939 viewFlagValues |= LAYOUT_DIRECTION_DEFAULT; 2940 } 2941 viewFlagMasks |= LAYOUT_DIRECTION_MASK; 2942 break; 2943 case com.android.internal.R.styleable.View_drawingCacheQuality: 2944 final int cacheQuality = a.getInt(attr, 0); 2945 if (cacheQuality != 0) { 2946 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 2947 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 2948 } 2949 break; 2950 case com.android.internal.R.styleable.View_contentDescription: 2951 mContentDescription = a.getString(attr); 2952 break; 2953 case com.android.internal.R.styleable.View_soundEffectsEnabled: 2954 if (!a.getBoolean(attr, true)) { 2955 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 2956 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 2957 } 2958 break; 2959 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 2960 if (!a.getBoolean(attr, true)) { 2961 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 2962 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 2963 } 2964 break; 2965 case R.styleable.View_scrollbars: 2966 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 2967 if (scrollbars != SCROLLBARS_NONE) { 2968 viewFlagValues |= scrollbars; 2969 viewFlagMasks |= SCROLLBARS_MASK; 2970 initializeScrollbars(a); 2971 } 2972 break; 2973 //noinspection deprecation 2974 case R.styleable.View_fadingEdge: 2975 if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) { 2976 // Ignore the attribute starting with ICS 2977 break; 2978 } 2979 // With builds < ICS, fall through and apply fading edges 2980 case R.styleable.View_requiresFadingEdge: 2981 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 2982 if (fadingEdge != FADING_EDGE_NONE) { 2983 viewFlagValues |= fadingEdge; 2984 viewFlagMasks |= FADING_EDGE_MASK; 2985 initializeFadingEdge(a); 2986 } 2987 break; 2988 case R.styleable.View_scrollbarStyle: 2989 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 2990 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 2991 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 2992 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 2993 } 2994 break; 2995 case R.styleable.View_isScrollContainer: 2996 setScrollContainer = true; 2997 if (a.getBoolean(attr, false)) { 2998 setScrollContainer(true); 2999 } 3000 break; 3001 case com.android.internal.R.styleable.View_keepScreenOn: 3002 if (a.getBoolean(attr, false)) { 3003 viewFlagValues |= KEEP_SCREEN_ON; 3004 viewFlagMasks |= KEEP_SCREEN_ON; 3005 } 3006 break; 3007 case R.styleable.View_filterTouchesWhenObscured: 3008 if (a.getBoolean(attr, false)) { 3009 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3010 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3011 } 3012 break; 3013 case R.styleable.View_nextFocusLeft: 3014 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3015 break; 3016 case R.styleable.View_nextFocusRight: 3017 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3018 break; 3019 case R.styleable.View_nextFocusUp: 3020 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3021 break; 3022 case R.styleable.View_nextFocusDown: 3023 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3024 break; 3025 case R.styleable.View_nextFocusForward: 3026 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3027 break; 3028 case R.styleable.View_minWidth: 3029 mMinWidth = a.getDimensionPixelSize(attr, 0); 3030 break; 3031 case R.styleable.View_minHeight: 3032 mMinHeight = a.getDimensionPixelSize(attr, 0); 3033 break; 3034 case R.styleable.View_onClick: 3035 if (context.isRestricted()) { 3036 throw new IllegalStateException("The android:onClick attribute cannot " 3037 + "be used within a restricted context"); 3038 } 3039 3040 final String handlerName = a.getString(attr); 3041 if (handlerName != null) { 3042 setOnClickListener(new OnClickListener() { 3043 private Method mHandler; 3044 3045 public void onClick(View v) { 3046 if (mHandler == null) { 3047 try { 3048 mHandler = getContext().getClass().getMethod(handlerName, 3049 View.class); 3050 } catch (NoSuchMethodException e) { 3051 int id = getId(); 3052 String idText = id == NO_ID ? "" : " with id '" 3053 + getContext().getResources().getResourceEntryName( 3054 id) + "'"; 3055 throw new IllegalStateException("Could not find a method " + 3056 handlerName + "(View) in the activity " 3057 + getContext().getClass() + " for onClick handler" 3058 + " on view " + View.this.getClass() + idText, e); 3059 } 3060 } 3061 3062 try { 3063 mHandler.invoke(getContext(), View.this); 3064 } catch (IllegalAccessException e) { 3065 throw new IllegalStateException("Could not execute non " 3066 + "public method of the activity", e); 3067 } catch (InvocationTargetException e) { 3068 throw new IllegalStateException("Could not execute " 3069 + "method of the activity", e); 3070 } 3071 } 3072 }); 3073 } 3074 break; 3075 case R.styleable.View_overScrollMode: 3076 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3077 break; 3078 case R.styleable.View_verticalScrollbarPosition: 3079 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3080 break; 3081 case R.styleable.View_layerType: 3082 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3083 break; 3084 case R.styleable.View_textDirection: 3085 mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION); 3086 break; 3087 } 3088 } 3089 3090 a.recycle(); 3091 3092 setOverScrollMode(overScrollMode); 3093 3094 if (background != null) { 3095 setBackgroundDrawable(background); 3096 } 3097 3098 mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0); 3099 3100 // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved 3101 // layout direction). Those cached values will be used later during padding resolution. 3102 mUserPaddingStart = startPadding; 3103 mUserPaddingEnd = endPadding; 3104 3105 if (padding >= 0) { 3106 leftPadding = padding; 3107 topPadding = padding; 3108 rightPadding = padding; 3109 bottomPadding = padding; 3110 } 3111 3112 // If the user specified the padding (either with android:padding or 3113 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 3114 // use the default padding or the padding from the background drawable 3115 // (stored at this point in mPadding*) 3116 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft, 3117 topPadding >= 0 ? topPadding : mPaddingTop, 3118 rightPadding >= 0 ? rightPadding : mPaddingRight, 3119 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3120 3121 if (viewFlagMasks != 0) { 3122 setFlags(viewFlagValues, viewFlagMasks); 3123 } 3124 3125 // Needs to be called after mViewFlags is set 3126 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3127 recomputePadding(); 3128 } 3129 3130 if (x != 0 || y != 0) { 3131 scrollTo(x, y); 3132 } 3133 3134 if (transformSet) { 3135 setTranslationX(tx); 3136 setTranslationY(ty); 3137 setRotation(rotation); 3138 setRotationX(rotationX); 3139 setRotationY(rotationY); 3140 setScaleX(sx); 3141 setScaleY(sy); 3142 } 3143 3144 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3145 setScrollContainer(true); 3146 } 3147 3148 computeOpaqueFlags(); 3149 } 3150 3151 /** 3152 * Non-public constructor for use in testing 3153 */ 3154 View() { 3155 mResources = null; 3156 } 3157 3158 /** 3159 * <p> 3160 * Initializes the fading edges from a given set of styled attributes. This 3161 * method should be called by subclasses that need fading edges and when an 3162 * instance of these subclasses is created programmatically rather than 3163 * being inflated from XML. This method is automatically called when the XML 3164 * is inflated. 3165 * </p> 3166 * 3167 * @param a the styled attributes set to initialize the fading edges from 3168 */ 3169 protected void initializeFadingEdge(TypedArray a) { 3170 initScrollCache(); 3171 3172 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3173 R.styleable.View_fadingEdgeLength, 3174 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3175 } 3176 3177 /** 3178 * Returns the size of the vertical faded edges used to indicate that more 3179 * content in this view is visible. 3180 * 3181 * @return The size in pixels of the vertical faded edge or 0 if vertical 3182 * faded edges are not enabled for this view. 3183 * @attr ref android.R.styleable#View_fadingEdgeLength 3184 */ 3185 public int getVerticalFadingEdgeLength() { 3186 if (isVerticalFadingEdgeEnabled()) { 3187 ScrollabilityCache cache = mScrollCache; 3188 if (cache != null) { 3189 return cache.fadingEdgeLength; 3190 } 3191 } 3192 return 0; 3193 } 3194 3195 /** 3196 * Set the size of the faded edge used to indicate that more content in this 3197 * view is available. Will not change whether the fading edge is enabled; use 3198 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3199 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3200 * for the vertical or horizontal fading edges. 3201 * 3202 * @param length The size in pixels of the faded edge used to indicate that more 3203 * content in this view is visible. 3204 */ 3205 public void setFadingEdgeLength(int length) { 3206 initScrollCache(); 3207 mScrollCache.fadingEdgeLength = length; 3208 } 3209 3210 /** 3211 * Returns the size of the horizontal faded edges used to indicate that more 3212 * content in this view is visible. 3213 * 3214 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3215 * faded edges are not enabled for this view. 3216 * @attr ref android.R.styleable#View_fadingEdgeLength 3217 */ 3218 public int getHorizontalFadingEdgeLength() { 3219 if (isHorizontalFadingEdgeEnabled()) { 3220 ScrollabilityCache cache = mScrollCache; 3221 if (cache != null) { 3222 return cache.fadingEdgeLength; 3223 } 3224 } 3225 return 0; 3226 } 3227 3228 /** 3229 * Returns the width of the vertical scrollbar. 3230 * 3231 * @return The width in pixels of the vertical scrollbar or 0 if there 3232 * is no vertical scrollbar. 3233 */ 3234 public int getVerticalScrollbarWidth() { 3235 ScrollabilityCache cache = mScrollCache; 3236 if (cache != null) { 3237 ScrollBarDrawable scrollBar = cache.scrollBar; 3238 if (scrollBar != null) { 3239 int size = scrollBar.getSize(true); 3240 if (size <= 0) { 3241 size = cache.scrollBarSize; 3242 } 3243 return size; 3244 } 3245 return 0; 3246 } 3247 return 0; 3248 } 3249 3250 /** 3251 * Returns the height of the horizontal scrollbar. 3252 * 3253 * @return The height in pixels of the horizontal scrollbar or 0 if 3254 * there is no horizontal scrollbar. 3255 */ 3256 protected int getHorizontalScrollbarHeight() { 3257 ScrollabilityCache cache = mScrollCache; 3258 if (cache != null) { 3259 ScrollBarDrawable scrollBar = cache.scrollBar; 3260 if (scrollBar != null) { 3261 int size = scrollBar.getSize(false); 3262 if (size <= 0) { 3263 size = cache.scrollBarSize; 3264 } 3265 return size; 3266 } 3267 return 0; 3268 } 3269 return 0; 3270 } 3271 3272 /** 3273 * <p> 3274 * Initializes the scrollbars from a given set of styled attributes. This 3275 * method should be called by subclasses that need scrollbars and when an 3276 * instance of these subclasses is created programmatically rather than 3277 * being inflated from XML. This method is automatically called when the XML 3278 * is inflated. 3279 * </p> 3280 * 3281 * @param a the styled attributes set to initialize the scrollbars from 3282 */ 3283 protected void initializeScrollbars(TypedArray a) { 3284 initScrollCache(); 3285 3286 final ScrollabilityCache scrollabilityCache = mScrollCache; 3287 3288 if (scrollabilityCache.scrollBar == null) { 3289 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 3290 } 3291 3292 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 3293 3294 if (!fadeScrollbars) { 3295 scrollabilityCache.state = ScrollabilityCache.ON; 3296 } 3297 scrollabilityCache.fadeScrollBars = fadeScrollbars; 3298 3299 3300 scrollabilityCache.scrollBarFadeDuration = a.getInt( 3301 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 3302 .getScrollBarFadeDuration()); 3303 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 3304 R.styleable.View_scrollbarDefaultDelayBeforeFade, 3305 ViewConfiguration.getScrollDefaultDelay()); 3306 3307 3308 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 3309 com.android.internal.R.styleable.View_scrollbarSize, 3310 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3311 3312 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3313 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3314 3315 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3316 if (thumb != null) { 3317 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3318 } 3319 3320 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3321 false); 3322 if (alwaysDraw) { 3323 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3324 } 3325 3326 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3327 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3328 3329 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3330 if (thumb != null) { 3331 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3332 } 3333 3334 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3335 false); 3336 if (alwaysDraw) { 3337 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3338 } 3339 3340 // Re-apply user/background padding so that scrollbar(s) get added 3341 resolvePadding(); 3342 } 3343 3344 /** 3345 * <p> 3346 * Initalizes the scrollability cache if necessary. 3347 * </p> 3348 */ 3349 private void initScrollCache() { 3350 if (mScrollCache == null) { 3351 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 3352 } 3353 } 3354 3355 /** 3356 * Set the position of the vertical scroll bar. Should be one of 3357 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 3358 * {@link #SCROLLBAR_POSITION_RIGHT}. 3359 * 3360 * @param position Where the vertical scroll bar should be positioned. 3361 */ 3362 public void setVerticalScrollbarPosition(int position) { 3363 if (mVerticalScrollbarPosition != position) { 3364 mVerticalScrollbarPosition = position; 3365 computeOpaqueFlags(); 3366 resolvePadding(); 3367 } 3368 } 3369 3370 /** 3371 * @return The position where the vertical scroll bar will show, if applicable. 3372 * @see #setVerticalScrollbarPosition(int) 3373 */ 3374 public int getVerticalScrollbarPosition() { 3375 return mVerticalScrollbarPosition; 3376 } 3377 3378 ListenerInfo getListenerInfo() { 3379 if (mListenerInfo != null) { 3380 return mListenerInfo; 3381 } 3382 mListenerInfo = new ListenerInfo(); 3383 return mListenerInfo; 3384 } 3385 3386 /** 3387 * Register a callback to be invoked when focus of this view changed. 3388 * 3389 * @param l The callback that will run. 3390 */ 3391 public void setOnFocusChangeListener(OnFocusChangeListener l) { 3392 getListenerInfo().mOnFocusChangeListener = l; 3393 } 3394 3395 /** 3396 * Add a listener that will be called when the bounds of the view change due to 3397 * layout processing. 3398 * 3399 * @param listener The listener that will be called when layout bounds change. 3400 */ 3401 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 3402 ListenerInfo li = getListenerInfo(); 3403 if (li.mOnLayoutChangeListeners == null) { 3404 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 3405 } 3406 if (!li.mOnLayoutChangeListeners.contains(listener)) { 3407 li.mOnLayoutChangeListeners.add(listener); 3408 } 3409 } 3410 3411 /** 3412 * Remove a listener for layout changes. 3413 * 3414 * @param listener The listener for layout bounds change. 3415 */ 3416 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 3417 ListenerInfo li = mListenerInfo; 3418 if (li == null || li.mOnLayoutChangeListeners == null) { 3419 return; 3420 } 3421 li.mOnLayoutChangeListeners.remove(listener); 3422 } 3423 3424 /** 3425 * Add a listener for attach state changes. 3426 * 3427 * This listener will be called whenever this view is attached or detached 3428 * from a window. Remove the listener using 3429 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 3430 * 3431 * @param listener Listener to attach 3432 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 3433 */ 3434 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3435 ListenerInfo li = getListenerInfo(); 3436 if (li.mOnAttachStateChangeListeners == null) { 3437 li.mOnAttachStateChangeListeners 3438 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 3439 } 3440 li.mOnAttachStateChangeListeners.add(listener); 3441 } 3442 3443 /** 3444 * Remove a listener for attach state changes. The listener will receive no further 3445 * notification of window attach/detach events. 3446 * 3447 * @param listener Listener to remove 3448 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 3449 */ 3450 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3451 ListenerInfo li = mListenerInfo; 3452 if (li == null || li.mOnAttachStateChangeListeners == null) { 3453 return; 3454 } 3455 li.mOnAttachStateChangeListeners.remove(listener); 3456 } 3457 3458 /** 3459 * Returns the focus-change callback registered for this view. 3460 * 3461 * @return The callback, or null if one is not registered. 3462 */ 3463 public OnFocusChangeListener getOnFocusChangeListener() { 3464 ListenerInfo li = mListenerInfo; 3465 return li != null ? li.mOnFocusChangeListener : null; 3466 } 3467 3468 /** 3469 * Register a callback to be invoked when this view is clicked. If this view is not 3470 * clickable, it becomes clickable. 3471 * 3472 * @param l The callback that will run 3473 * 3474 * @see #setClickable(boolean) 3475 */ 3476 public void setOnClickListener(OnClickListener l) { 3477 if (!isClickable()) { 3478 setClickable(true); 3479 } 3480 getListenerInfo().mOnClickListener = l; 3481 } 3482 3483 /** 3484 * Return whether this view has an attached OnClickListener. Returns 3485 * true if there is a listener, false if there is none. 3486 */ 3487 public boolean hasOnClickListeners() { 3488 ListenerInfo li = mListenerInfo; 3489 return (li != null && li.mOnClickListener != null); 3490 } 3491 3492 /** 3493 * Register a callback to be invoked when this view is clicked and held. If this view is not 3494 * long clickable, it becomes long clickable. 3495 * 3496 * @param l The callback that will run 3497 * 3498 * @see #setLongClickable(boolean) 3499 */ 3500 public void setOnLongClickListener(OnLongClickListener l) { 3501 if (!isLongClickable()) { 3502 setLongClickable(true); 3503 } 3504 getListenerInfo().mOnLongClickListener = l; 3505 } 3506 3507 /** 3508 * Register a callback to be invoked when the context menu for this view is 3509 * being built. If this view is not long clickable, it becomes long clickable. 3510 * 3511 * @param l The callback that will run 3512 * 3513 */ 3514 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 3515 if (!isLongClickable()) { 3516 setLongClickable(true); 3517 } 3518 getListenerInfo().mOnCreateContextMenuListener = l; 3519 } 3520 3521 /** 3522 * Call this view's OnClickListener, if it is defined. Performs all normal 3523 * actions associated with clicking: reporting accessibility event, playing 3524 * a sound, etc. 3525 * 3526 * @return True there was an assigned OnClickListener that was called, false 3527 * otherwise is returned. 3528 */ 3529 public boolean performClick() { 3530 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 3531 3532 ListenerInfo li = mListenerInfo; 3533 if (li != null && li.mOnClickListener != null) { 3534 playSoundEffect(SoundEffectConstants.CLICK); 3535 li.mOnClickListener.onClick(this); 3536 return true; 3537 } 3538 3539 return false; 3540 } 3541 3542 /** 3543 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 3544 * this only calls the listener, and does not do any associated clicking 3545 * actions like reporting an accessibility event. 3546 * 3547 * @return True there was an assigned OnClickListener that was called, false 3548 * otherwise is returned. 3549 */ 3550 public boolean callOnClick() { 3551 ListenerInfo li = mListenerInfo; 3552 if (li != null && li.mOnClickListener != null) { 3553 li.mOnClickListener.onClick(this); 3554 return true; 3555 } 3556 return false; 3557 } 3558 3559 /** 3560 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 3561 * OnLongClickListener did not consume the event. 3562 * 3563 * @return True if one of the above receivers consumed the event, false otherwise. 3564 */ 3565 public boolean performLongClick() { 3566 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 3567 3568 boolean handled = false; 3569 ListenerInfo li = mListenerInfo; 3570 if (li != null && li.mOnLongClickListener != null) { 3571 handled = li.mOnLongClickListener.onLongClick(View.this); 3572 } 3573 if (!handled) { 3574 handled = showContextMenu(); 3575 } 3576 if (handled) { 3577 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 3578 } 3579 return handled; 3580 } 3581 3582 /** 3583 * Performs button-related actions during a touch down event. 3584 * 3585 * @param event The event. 3586 * @return True if the down was consumed. 3587 * 3588 * @hide 3589 */ 3590 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 3591 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 3592 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 3593 return true; 3594 } 3595 } 3596 return false; 3597 } 3598 3599 /** 3600 * Bring up the context menu for this view. 3601 * 3602 * @return Whether a context menu was displayed. 3603 */ 3604 public boolean showContextMenu() { 3605 return getParent().showContextMenuForChild(this); 3606 } 3607 3608 /** 3609 * Bring up the context menu for this view, referring to the item under the specified point. 3610 * 3611 * @param x The referenced x coordinate. 3612 * @param y The referenced y coordinate. 3613 * @param metaState The keyboard modifiers that were pressed. 3614 * @return Whether a context menu was displayed. 3615 * 3616 * @hide 3617 */ 3618 public boolean showContextMenu(float x, float y, int metaState) { 3619 return showContextMenu(); 3620 } 3621 3622 /** 3623 * Start an action mode. 3624 * 3625 * @param callback Callback that will control the lifecycle of the action mode 3626 * @return The new action mode if it is started, null otherwise 3627 * 3628 * @see ActionMode 3629 */ 3630 public ActionMode startActionMode(ActionMode.Callback callback) { 3631 return getParent().startActionModeForChild(this, callback); 3632 } 3633 3634 /** 3635 * Register a callback to be invoked when a key is pressed in this view. 3636 * @param l the key listener to attach to this view 3637 */ 3638 public void setOnKeyListener(OnKeyListener l) { 3639 getListenerInfo().mOnKeyListener = l; 3640 } 3641 3642 /** 3643 * Register a callback to be invoked when a touch event is sent to this view. 3644 * @param l the touch listener to attach to this view 3645 */ 3646 public void setOnTouchListener(OnTouchListener l) { 3647 getListenerInfo().mOnTouchListener = l; 3648 } 3649 3650 /** 3651 * Register a callback to be invoked when a generic motion event is sent to this view. 3652 * @param l the generic motion listener to attach to this view 3653 */ 3654 public void setOnGenericMotionListener(OnGenericMotionListener l) { 3655 getListenerInfo().mOnGenericMotionListener = l; 3656 } 3657 3658 /** 3659 * Register a callback to be invoked when a hover event is sent to this view. 3660 * @param l the hover listener to attach to this view 3661 */ 3662 public void setOnHoverListener(OnHoverListener l) { 3663 getListenerInfo().mOnHoverListener = l; 3664 } 3665 3666 /** 3667 * Register a drag event listener callback object for this View. The parameter is 3668 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 3669 * View, the system calls the 3670 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 3671 * @param l An implementation of {@link android.view.View.OnDragListener}. 3672 */ 3673 public void setOnDragListener(OnDragListener l) { 3674 getListenerInfo().mOnDragListener = l; 3675 } 3676 3677 /** 3678 * Give this view focus. This will cause 3679 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3680 * 3681 * Note: this does not check whether this {@link View} should get focus, it just 3682 * gives it focus no matter what. It should only be called internally by framework 3683 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 3684 * 3685 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 3686 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 3687 * focus moved when requestFocus() is called. It may not always 3688 * apply, in which case use the default View.FOCUS_DOWN. 3689 * @param previouslyFocusedRect The rectangle of the view that had focus 3690 * prior in this View's coordinate system. 3691 */ 3692 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 3693 if (DBG) { 3694 System.out.println(this + " requestFocus()"); 3695 } 3696 3697 if ((mPrivateFlags & FOCUSED) == 0) { 3698 mPrivateFlags |= FOCUSED; 3699 3700 if (mParent != null) { 3701 mParent.requestChildFocus(this, this); 3702 } 3703 3704 onFocusChanged(true, direction, previouslyFocusedRect); 3705 refreshDrawableState(); 3706 } 3707 } 3708 3709 /** 3710 * Request that a rectangle of this view be visible on the screen, 3711 * scrolling if necessary just enough. 3712 * 3713 * <p>A View should call this if it maintains some notion of which part 3714 * of its content is interesting. For example, a text editing view 3715 * should call this when its cursor moves. 3716 * 3717 * @param rectangle The rectangle. 3718 * @return Whether any parent scrolled. 3719 */ 3720 public boolean requestRectangleOnScreen(Rect rectangle) { 3721 return requestRectangleOnScreen(rectangle, false); 3722 } 3723 3724 /** 3725 * Request that a rectangle of this view be visible on the screen, 3726 * scrolling if necessary just enough. 3727 * 3728 * <p>A View should call this if it maintains some notion of which part 3729 * of its content is interesting. For example, a text editing view 3730 * should call this when its cursor moves. 3731 * 3732 * <p>When <code>immediate</code> is set to true, scrolling will not be 3733 * animated. 3734 * 3735 * @param rectangle The rectangle. 3736 * @param immediate True to forbid animated scrolling, false otherwise 3737 * @return Whether any parent scrolled. 3738 */ 3739 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 3740 View child = this; 3741 ViewParent parent = mParent; 3742 boolean scrolled = false; 3743 while (parent != null) { 3744 scrolled |= parent.requestChildRectangleOnScreen(child, 3745 rectangle, immediate); 3746 3747 // offset rect so next call has the rectangle in the 3748 // coordinate system of its direct child. 3749 rectangle.offset(child.getLeft(), child.getTop()); 3750 rectangle.offset(-child.getScrollX(), -child.getScrollY()); 3751 3752 if (!(parent instanceof View)) { 3753 break; 3754 } 3755 3756 child = (View) parent; 3757 parent = child.getParent(); 3758 } 3759 return scrolled; 3760 } 3761 3762 /** 3763 * Called when this view wants to give up focus. If focus is cleared 3764 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 3765 * <p> 3766 * <strong>Note:</strong> When a View clears focus the framework is trying 3767 * to give focus to the first focusable View from the top. Hence, if this 3768 * View is the first from the top that can take focus, then its focus will 3769 * not be cleared nor will the focus change callback be invoked. 3770 * </p> 3771 */ 3772 public void clearFocus() { 3773 if (DBG) { 3774 System.out.println(this + " clearFocus()"); 3775 } 3776 3777 if ((mPrivateFlags & FOCUSED) != 0) { 3778 // If this is the first focusable do not clear focus since the we 3779 // try to give it focus every time a view clears its focus. Hence, 3780 // the view that would gain focus already has it. 3781 View firstFocusable = getFirstFocusable(); 3782 if (firstFocusable == this) { 3783 return; 3784 } 3785 3786 mPrivateFlags &= ~FOCUSED; 3787 3788 if (mParent != null) { 3789 mParent.clearChildFocus(this); 3790 } 3791 3792 onFocusChanged(false, 0, null); 3793 refreshDrawableState(); 3794 3795 // The view cleared focus and invoked the callbacks, so now is the 3796 // time to give focus to the the first focusable to ensure that the 3797 // gain focus is announced after clear focus. 3798 if (firstFocusable != null) { 3799 firstFocusable.requestFocus(FOCUS_FORWARD); 3800 } 3801 } 3802 } 3803 3804 private View getFirstFocusable() { 3805 ViewRootImpl viewRoot = getViewRootImpl(); 3806 if (viewRoot != null) { 3807 return viewRoot.focusSearch(null, FOCUS_FORWARD); 3808 } 3809 return null; 3810 } 3811 3812 /** 3813 * Called to clear the focus of a view that is about to be removed. 3814 * Doesn't call clearChildFocus, which prevents this view from taking 3815 * focus again before it has been removed from the parent 3816 */ 3817 void clearFocusForRemoval() { 3818 if ((mPrivateFlags & FOCUSED) != 0) { 3819 mPrivateFlags &= ~FOCUSED; 3820 3821 onFocusChanged(false, 0, null); 3822 refreshDrawableState(); 3823 } 3824 } 3825 3826 /** 3827 * Called internally by the view system when a new view is getting focus. 3828 * This is what clears the old focus. 3829 */ 3830 void unFocus() { 3831 if (DBG) { 3832 System.out.println(this + " unFocus()"); 3833 } 3834 3835 if ((mPrivateFlags & FOCUSED) != 0) { 3836 mPrivateFlags &= ~FOCUSED; 3837 3838 onFocusChanged(false, 0, null); 3839 refreshDrawableState(); 3840 } 3841 } 3842 3843 /** 3844 * Returns true if this view has focus iteself, or is the ancestor of the 3845 * view that has focus. 3846 * 3847 * @return True if this view has or contains focus, false otherwise. 3848 */ 3849 @ViewDebug.ExportedProperty(category = "focus") 3850 public boolean hasFocus() { 3851 return (mPrivateFlags & FOCUSED) != 0; 3852 } 3853 3854 /** 3855 * Returns true if this view is focusable or if it contains a reachable View 3856 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 3857 * is a View whose parents do not block descendants focus. 3858 * 3859 * Only {@link #VISIBLE} views are considered focusable. 3860 * 3861 * @return True if the view is focusable or if the view contains a focusable 3862 * View, false otherwise. 3863 * 3864 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 3865 */ 3866 public boolean hasFocusable() { 3867 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 3868 } 3869 3870 /** 3871 * Called by the view system when the focus state of this view changes. 3872 * When the focus change event is caused by directional navigation, direction 3873 * and previouslyFocusedRect provide insight into where the focus is coming from. 3874 * When overriding, be sure to call up through to the super class so that 3875 * the standard focus handling will occur. 3876 * 3877 * @param gainFocus True if the View has focus; false otherwise. 3878 * @param direction The direction focus has moved when requestFocus() 3879 * is called to give this view focus. Values are 3880 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 3881 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 3882 * It may not always apply, in which case use the default. 3883 * @param previouslyFocusedRect The rectangle, in this view's coordinate 3884 * system, of the previously focused view. If applicable, this will be 3885 * passed in as finer grained information about where the focus is coming 3886 * from (in addition to direction). Will be <code>null</code> otherwise. 3887 */ 3888 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 3889 if (gainFocus) { 3890 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 3891 } 3892 3893 InputMethodManager imm = InputMethodManager.peekInstance(); 3894 if (!gainFocus) { 3895 if (isPressed()) { 3896 setPressed(false); 3897 } 3898 if (imm != null && mAttachInfo != null 3899 && mAttachInfo.mHasWindowFocus) { 3900 imm.focusOut(this); 3901 } 3902 onFocusLost(); 3903 } else if (imm != null && mAttachInfo != null 3904 && mAttachInfo.mHasWindowFocus) { 3905 imm.focusIn(this); 3906 } 3907 3908 invalidate(true); 3909 ListenerInfo li = mListenerInfo; 3910 if (li != null && li.mOnFocusChangeListener != null) { 3911 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 3912 } 3913 3914 if (mAttachInfo != null) { 3915 mAttachInfo.mKeyDispatchState.reset(this); 3916 } 3917 } 3918 3919 /** 3920 * Sends an accessibility event of the given type. If accessiiblity is 3921 * not enabled this method has no effect. The default implementation calls 3922 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 3923 * to populate information about the event source (this View), then calls 3924 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 3925 * populate the text content of the event source including its descendants, 3926 * and last calls 3927 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 3928 * on its parent to resuest sending of the event to interested parties. 3929 * <p> 3930 * If an {@link AccessibilityDelegate} has been specified via calling 3931 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3932 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 3933 * responsible for handling this call. 3934 * </p> 3935 * 3936 * @param eventType The type of the event to send, as defined by several types from 3937 * {@link android.view.accessibility.AccessibilityEvent}, such as 3938 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 3939 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 3940 * 3941 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 3942 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3943 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 3944 * @see AccessibilityDelegate 3945 */ 3946 public void sendAccessibilityEvent(int eventType) { 3947 if (mAccessibilityDelegate != null) { 3948 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 3949 } else { 3950 sendAccessibilityEventInternal(eventType); 3951 } 3952 } 3953 3954 /** 3955 * @see #sendAccessibilityEvent(int) 3956 * 3957 * Note: Called from the default {@link AccessibilityDelegate}. 3958 */ 3959 void sendAccessibilityEventInternal(int eventType) { 3960 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 3961 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 3962 } 3963 } 3964 3965 /** 3966 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 3967 * takes as an argument an empty {@link AccessibilityEvent} and does not 3968 * perform a check whether accessibility is enabled. 3969 * <p> 3970 * If an {@link AccessibilityDelegate} has been specified via calling 3971 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3972 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 3973 * is responsible for handling this call. 3974 * </p> 3975 * 3976 * @param event The event to send. 3977 * 3978 * @see #sendAccessibilityEvent(int) 3979 */ 3980 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 3981 if (mAccessibilityDelegate != null) { 3982 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 3983 } else { 3984 sendAccessibilityEventUncheckedInternal(event); 3985 } 3986 } 3987 3988 /** 3989 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 3990 * 3991 * Note: Called from the default {@link AccessibilityDelegate}. 3992 */ 3993 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 3994 if (!isShown()) { 3995 return; 3996 } 3997 onInitializeAccessibilityEvent(event); 3998 // Only a subset of accessibility events populates text content. 3999 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 4000 dispatchPopulateAccessibilityEvent(event); 4001 } 4002 // In the beginning we called #isShown(), so we know that getParent() is not null. 4003 getParent().requestSendAccessibilityEvent(this, event); 4004 } 4005 4006 /** 4007 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 4008 * to its children for adding their text content to the event. Note that the 4009 * event text is populated in a separate dispatch path since we add to the 4010 * event not only the text of the source but also the text of all its descendants. 4011 * A typical implementation will call 4012 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 4013 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4014 * on each child. Override this method if custom population of the event text 4015 * content is required. 4016 * <p> 4017 * If an {@link AccessibilityDelegate} has been specified via calling 4018 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4019 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 4020 * is responsible for handling this call. 4021 * </p> 4022 * <p> 4023 * <em>Note:</em> Accessibility events of certain types are not dispatched for 4024 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 4025 * </p> 4026 * 4027 * @param event The event. 4028 * 4029 * @return True if the event population was completed. 4030 */ 4031 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 4032 if (mAccessibilityDelegate != null) { 4033 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 4034 } else { 4035 return dispatchPopulateAccessibilityEventInternal(event); 4036 } 4037 } 4038 4039 /** 4040 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4041 * 4042 * Note: Called from the default {@link AccessibilityDelegate}. 4043 */ 4044 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4045 onPopulateAccessibilityEvent(event); 4046 return false; 4047 } 4048 4049 /** 4050 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4051 * giving a chance to this View to populate the accessibility event with its 4052 * text content. While this method is free to modify event 4053 * attributes other than text content, doing so should normally be performed in 4054 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 4055 * <p> 4056 * Example: Adding formatted date string to an accessibility event in addition 4057 * to the text added by the super implementation: 4058 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4059 * super.onPopulateAccessibilityEvent(event); 4060 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 4061 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 4062 * mCurrentDate.getTimeInMillis(), flags); 4063 * event.getText().add(selectedDateUtterance); 4064 * }</pre> 4065 * <p> 4066 * If an {@link AccessibilityDelegate} has been specified via calling 4067 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4068 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 4069 * is responsible for handling this call. 4070 * </p> 4071 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4072 * information to the event, in case the default implementation has basic information to add. 4073 * </p> 4074 * 4075 * @param event The accessibility event which to populate. 4076 * 4077 * @see #sendAccessibilityEvent(int) 4078 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4079 */ 4080 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4081 if (mAccessibilityDelegate != null) { 4082 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 4083 } else { 4084 onPopulateAccessibilityEventInternal(event); 4085 } 4086 } 4087 4088 /** 4089 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 4090 * 4091 * Note: Called from the default {@link AccessibilityDelegate}. 4092 */ 4093 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4094 4095 } 4096 4097 /** 4098 * Initializes an {@link AccessibilityEvent} with information about 4099 * this View which is the event source. In other words, the source of 4100 * an accessibility event is the view whose state change triggered firing 4101 * the event. 4102 * <p> 4103 * Example: Setting the password property of an event in addition 4104 * to properties set by the super implementation: 4105 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4106 * super.onInitializeAccessibilityEvent(event); 4107 * event.setPassword(true); 4108 * }</pre> 4109 * <p> 4110 * If an {@link AccessibilityDelegate} has been specified via calling 4111 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4112 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 4113 * is responsible for handling this call. 4114 * </p> 4115 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4116 * information to the event, in case the default implementation has basic information to add. 4117 * </p> 4118 * @param event The event to initialize. 4119 * 4120 * @see #sendAccessibilityEvent(int) 4121 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4122 */ 4123 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4124 if (mAccessibilityDelegate != null) { 4125 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 4126 } else { 4127 onInitializeAccessibilityEventInternal(event); 4128 } 4129 } 4130 4131 /** 4132 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4133 * 4134 * Note: Called from the default {@link AccessibilityDelegate}. 4135 */ 4136 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 4137 event.setSource(this); 4138 event.setClassName(View.class.getName()); 4139 event.setPackageName(getContext().getPackageName()); 4140 event.setEnabled(isEnabled()); 4141 event.setContentDescription(mContentDescription); 4142 4143 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) { 4144 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList; 4145 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, 4146 FOCUSABLES_ALL); 4147 event.setItemCount(focusablesTempList.size()); 4148 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 4149 focusablesTempList.clear(); 4150 } 4151 } 4152 4153 /** 4154 * Returns an {@link AccessibilityNodeInfo} representing this view from the 4155 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 4156 * This method is responsible for obtaining an accessibility node info from a 4157 * pool of reusable instances and calling 4158 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 4159 * initialize the former. 4160 * <p> 4161 * Note: The client is responsible for recycling the obtained instance by calling 4162 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 4163 * </p> 4164 * 4165 * @return A populated {@link AccessibilityNodeInfo}. 4166 * 4167 * @see AccessibilityNodeInfo 4168 */ 4169 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 4170 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 4171 if (provider != null) { 4172 return provider.createAccessibilityNodeInfo(View.NO_ID); 4173 } else { 4174 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 4175 onInitializeAccessibilityNodeInfo(info); 4176 return info; 4177 } 4178 } 4179 4180 /** 4181 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 4182 * The base implementation sets: 4183 * <ul> 4184 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 4185 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 4186 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 4187 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 4188 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 4189 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 4190 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 4191 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 4192 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 4193 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 4194 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 4195 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 4196 * </ul> 4197 * <p> 4198 * Subclasses should override this method, call the super implementation, 4199 * and set additional attributes. 4200 * </p> 4201 * <p> 4202 * If an {@link AccessibilityDelegate} has been specified via calling 4203 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4204 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 4205 * is responsible for handling this call. 4206 * </p> 4207 * 4208 * @param info The instance to initialize. 4209 */ 4210 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 4211 if (mAccessibilityDelegate != null) { 4212 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 4213 } else { 4214 onInitializeAccessibilityNodeInfoInternal(info); 4215 } 4216 } 4217 4218 /** 4219 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 4220 * 4221 * Note: Called from the default {@link AccessibilityDelegate}. 4222 */ 4223 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 4224 Rect bounds = mAttachInfo.mTmpInvalRect; 4225 getDrawingRect(bounds); 4226 info.setBoundsInParent(bounds); 4227 4228 int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation; 4229 getLocationOnScreen(locationOnScreen); 4230 bounds.offsetTo(0, 0); 4231 bounds.offset(locationOnScreen[0], locationOnScreen[1]); 4232 info.setBoundsInScreen(bounds); 4233 4234 if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { 4235 ViewParent parent = getParent(); 4236 if (parent instanceof View) { 4237 View parentView = (View) parent; 4238 info.setParent(parentView); 4239 } 4240 } 4241 4242 info.setPackageName(mContext.getPackageName()); 4243 info.setClassName(View.class.getName()); 4244 info.setContentDescription(getContentDescription()); 4245 4246 info.setEnabled(isEnabled()); 4247 info.setClickable(isClickable()); 4248 info.setFocusable(isFocusable()); 4249 info.setFocused(isFocused()); 4250 info.setSelected(isSelected()); 4251 info.setLongClickable(isLongClickable()); 4252 4253 // TODO: These make sense only if we are in an AdapterView but all 4254 // views can be selected. Maybe from accessiiblity perspective 4255 // we should report as selectable view in an AdapterView. 4256 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 4257 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 4258 4259 if (isFocusable()) { 4260 if (isFocused()) { 4261 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 4262 } else { 4263 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 4264 } 4265 } 4266 } 4267 4268 /** 4269 * Sets a delegate for implementing accessibility support via compositon as 4270 * opposed to inheritance. The delegate's primary use is for implementing 4271 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 4272 * 4273 * @param delegate The delegate instance. 4274 * 4275 * @see AccessibilityDelegate 4276 */ 4277 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 4278 mAccessibilityDelegate = delegate; 4279 } 4280 4281 /** 4282 * Gets the provider for managing a virtual view hierarchy rooted at this View 4283 * and reported to {@link android.accessibilityservice.AccessibilityService}s 4284 * that explore the window content. 4285 * <p> 4286 * If this method returns an instance, this instance is responsible for managing 4287 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 4288 * View including the one representing the View itself. Similarly the returned 4289 * instance is responsible for performing accessibility actions on any virtual 4290 * view or the root view itself. 4291 * </p> 4292 * <p> 4293 * If an {@link AccessibilityDelegate} has been specified via calling 4294 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4295 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 4296 * is responsible for handling this call. 4297 * </p> 4298 * 4299 * @return The provider. 4300 * 4301 * @see AccessibilityNodeProvider 4302 */ 4303 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 4304 if (mAccessibilityDelegate != null) { 4305 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 4306 } else { 4307 return null; 4308 } 4309 } 4310 4311 /** 4312 * Gets the unique identifier of this view on the screen for accessibility purposes. 4313 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 4314 * 4315 * @return The view accessibility id. 4316 * 4317 * @hide 4318 */ 4319 public int getAccessibilityViewId() { 4320 if (mAccessibilityViewId == NO_ID) { 4321 mAccessibilityViewId = sNextAccessibilityViewId++; 4322 } 4323 return mAccessibilityViewId; 4324 } 4325 4326 /** 4327 * Gets the unique identifier of the window in which this View reseides. 4328 * 4329 * @return The window accessibility id. 4330 * 4331 * @hide 4332 */ 4333 public int getAccessibilityWindowId() { 4334 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 4335 } 4336 4337 /** 4338 * Gets the {@link View} description. It briefly describes the view and is 4339 * primarily used for accessibility support. Set this property to enable 4340 * better accessibility support for your application. This is especially 4341 * true for views that do not have textual representation (For example, 4342 * ImageButton). 4343 * 4344 * @return The content descriptiopn. 4345 * 4346 * @attr ref android.R.styleable#View_contentDescription 4347 */ 4348 public CharSequence getContentDescription() { 4349 return mContentDescription; 4350 } 4351 4352 /** 4353 * Sets the {@link View} description. It briefly describes the view and is 4354 * primarily used for accessibility support. Set this property to enable 4355 * better accessibility support for your application. This is especially 4356 * true for views that do not have textual representation (For example, 4357 * ImageButton). 4358 * 4359 * @param contentDescription The content description. 4360 * 4361 * @attr ref android.R.styleable#View_contentDescription 4362 */ 4363 @RemotableViewMethod 4364 public void setContentDescription(CharSequence contentDescription) { 4365 mContentDescription = contentDescription; 4366 } 4367 4368 /** 4369 * Invoked whenever this view loses focus, either by losing window focus or by losing 4370 * focus within its window. This method can be used to clear any state tied to the 4371 * focus. For instance, if a button is held pressed with the trackball and the window 4372 * loses focus, this method can be used to cancel the press. 4373 * 4374 * Subclasses of View overriding this method should always call super.onFocusLost(). 4375 * 4376 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 4377 * @see #onWindowFocusChanged(boolean) 4378 * 4379 * @hide pending API council approval 4380 */ 4381 protected void onFocusLost() { 4382 resetPressedState(); 4383 } 4384 4385 private void resetPressedState() { 4386 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 4387 return; 4388 } 4389 4390 if (isPressed()) { 4391 setPressed(false); 4392 4393 if (!mHasPerformedLongPress) { 4394 removeLongPressCallback(); 4395 } 4396 } 4397 } 4398 4399 /** 4400 * Returns true if this view has focus 4401 * 4402 * @return True if this view has focus, false otherwise. 4403 */ 4404 @ViewDebug.ExportedProperty(category = "focus") 4405 public boolean isFocused() { 4406 return (mPrivateFlags & FOCUSED) != 0; 4407 } 4408 4409 /** 4410 * Find the view in the hierarchy rooted at this view that currently has 4411 * focus. 4412 * 4413 * @return The view that currently has focus, or null if no focused view can 4414 * be found. 4415 */ 4416 public View findFocus() { 4417 return (mPrivateFlags & FOCUSED) != 0 ? this : null; 4418 } 4419 4420 /** 4421 * Change whether this view is one of the set of scrollable containers in 4422 * its window. This will be used to determine whether the window can 4423 * resize or must pan when a soft input area is open -- scrollable 4424 * containers allow the window to use resize mode since the container 4425 * will appropriately shrink. 4426 */ 4427 public void setScrollContainer(boolean isScrollContainer) { 4428 if (isScrollContainer) { 4429 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) { 4430 mAttachInfo.mScrollContainers.add(this); 4431 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 4432 } 4433 mPrivateFlags |= SCROLL_CONTAINER; 4434 } else { 4435 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 4436 mAttachInfo.mScrollContainers.remove(this); 4437 } 4438 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED); 4439 } 4440 } 4441 4442 /** 4443 * Returns the quality of the drawing cache. 4444 * 4445 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4446 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4447 * 4448 * @see #setDrawingCacheQuality(int) 4449 * @see #setDrawingCacheEnabled(boolean) 4450 * @see #isDrawingCacheEnabled() 4451 * 4452 * @attr ref android.R.styleable#View_drawingCacheQuality 4453 */ 4454 public int getDrawingCacheQuality() { 4455 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 4456 } 4457 4458 /** 4459 * Set the drawing cache quality of this view. This value is used only when the 4460 * drawing cache is enabled 4461 * 4462 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4463 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4464 * 4465 * @see #getDrawingCacheQuality() 4466 * @see #setDrawingCacheEnabled(boolean) 4467 * @see #isDrawingCacheEnabled() 4468 * 4469 * @attr ref android.R.styleable#View_drawingCacheQuality 4470 */ 4471 public void setDrawingCacheQuality(int quality) { 4472 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 4473 } 4474 4475 /** 4476 * Returns whether the screen should remain on, corresponding to the current 4477 * value of {@link #KEEP_SCREEN_ON}. 4478 * 4479 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 4480 * 4481 * @see #setKeepScreenOn(boolean) 4482 * 4483 * @attr ref android.R.styleable#View_keepScreenOn 4484 */ 4485 public boolean getKeepScreenOn() { 4486 return (mViewFlags & KEEP_SCREEN_ON) != 0; 4487 } 4488 4489 /** 4490 * Controls whether the screen should remain on, modifying the 4491 * value of {@link #KEEP_SCREEN_ON}. 4492 * 4493 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 4494 * 4495 * @see #getKeepScreenOn() 4496 * 4497 * @attr ref android.R.styleable#View_keepScreenOn 4498 */ 4499 public void setKeepScreenOn(boolean keepScreenOn) { 4500 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 4501 } 4502 4503 /** 4504 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4505 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4506 * 4507 * @attr ref android.R.styleable#View_nextFocusLeft 4508 */ 4509 public int getNextFocusLeftId() { 4510 return mNextFocusLeftId; 4511 } 4512 4513 /** 4514 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4515 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 4516 * decide automatically. 4517 * 4518 * @attr ref android.R.styleable#View_nextFocusLeft 4519 */ 4520 public void setNextFocusLeftId(int nextFocusLeftId) { 4521 mNextFocusLeftId = nextFocusLeftId; 4522 } 4523 4524 /** 4525 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4526 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4527 * 4528 * @attr ref android.R.styleable#View_nextFocusRight 4529 */ 4530 public int getNextFocusRightId() { 4531 return mNextFocusRightId; 4532 } 4533 4534 /** 4535 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4536 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 4537 * decide automatically. 4538 * 4539 * @attr ref android.R.styleable#View_nextFocusRight 4540 */ 4541 public void setNextFocusRightId(int nextFocusRightId) { 4542 mNextFocusRightId = nextFocusRightId; 4543 } 4544 4545 /** 4546 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4547 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4548 * 4549 * @attr ref android.R.styleable#View_nextFocusUp 4550 */ 4551 public int getNextFocusUpId() { 4552 return mNextFocusUpId; 4553 } 4554 4555 /** 4556 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4557 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 4558 * decide automatically. 4559 * 4560 * @attr ref android.R.styleable#View_nextFocusUp 4561 */ 4562 public void setNextFocusUpId(int nextFocusUpId) { 4563 mNextFocusUpId = nextFocusUpId; 4564 } 4565 4566 /** 4567 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4568 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4569 * 4570 * @attr ref android.R.styleable#View_nextFocusDown 4571 */ 4572 public int getNextFocusDownId() { 4573 return mNextFocusDownId; 4574 } 4575 4576 /** 4577 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4578 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 4579 * decide automatically. 4580 * 4581 * @attr ref android.R.styleable#View_nextFocusDown 4582 */ 4583 public void setNextFocusDownId(int nextFocusDownId) { 4584 mNextFocusDownId = nextFocusDownId; 4585 } 4586 4587 /** 4588 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4589 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4590 * 4591 * @attr ref android.R.styleable#View_nextFocusForward 4592 */ 4593 public int getNextFocusForwardId() { 4594 return mNextFocusForwardId; 4595 } 4596 4597 /** 4598 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4599 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 4600 * decide automatically. 4601 * 4602 * @attr ref android.R.styleable#View_nextFocusForward 4603 */ 4604 public void setNextFocusForwardId(int nextFocusForwardId) { 4605 mNextFocusForwardId = nextFocusForwardId; 4606 } 4607 4608 /** 4609 * Returns the visibility of this view and all of its ancestors 4610 * 4611 * @return True if this view and all of its ancestors are {@link #VISIBLE} 4612 */ 4613 public boolean isShown() { 4614 View current = this; 4615 //noinspection ConstantConditions 4616 do { 4617 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 4618 return false; 4619 } 4620 ViewParent parent = current.mParent; 4621 if (parent == null) { 4622 return false; // We are not attached to the view root 4623 } 4624 if (!(parent instanceof View)) { 4625 return true; 4626 } 4627 current = (View) parent; 4628 } while (current != null); 4629 4630 return false; 4631 } 4632 4633 /** 4634 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag 4635 * is set 4636 * 4637 * @param insets Insets for system windows 4638 * 4639 * @return True if this view applied the insets, false otherwise 4640 */ 4641 protected boolean fitSystemWindows(Rect insets) { 4642 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 4643 mPaddingLeft = insets.left; 4644 mPaddingTop = insets.top; 4645 mPaddingRight = insets.right; 4646 mPaddingBottom = insets.bottom; 4647 requestLayout(); 4648 return true; 4649 } 4650 return false; 4651 } 4652 4653 /** 4654 * Set whether or not this view should account for system screen decorations 4655 * such as the status bar and inset its content. This allows this view to be 4656 * positioned in absolute screen coordinates and remain visible to the user. 4657 * 4658 * <p>This should only be used by top-level window decor views. 4659 * 4660 * @param fitSystemWindows true to inset content for system screen decorations, false for 4661 * default behavior. 4662 * 4663 * @attr ref android.R.styleable#View_fitsSystemWindows 4664 */ 4665 public void setFitsSystemWindows(boolean fitSystemWindows) { 4666 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 4667 } 4668 4669 /** 4670 * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view 4671 * will account for system screen decorations such as the status bar and inset its 4672 * content. This allows the view to be positioned in absolute screen coordinates 4673 * and remain visible to the user. 4674 * 4675 * @return true if this view will adjust its content bounds for system screen decorations. 4676 * 4677 * @attr ref android.R.styleable#View_fitsSystemWindows 4678 */ 4679 public boolean fitsSystemWindows() { 4680 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 4681 } 4682 4683 /** 4684 * Returns the visibility status for this view. 4685 * 4686 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4687 * @attr ref android.R.styleable#View_visibility 4688 */ 4689 @ViewDebug.ExportedProperty(mapping = { 4690 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 4691 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 4692 @ViewDebug.IntToString(from = GONE, to = "GONE") 4693 }) 4694 public int getVisibility() { 4695 return mViewFlags & VISIBILITY_MASK; 4696 } 4697 4698 /** 4699 * Set the enabled state of this view. 4700 * 4701 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4702 * @attr ref android.R.styleable#View_visibility 4703 */ 4704 @RemotableViewMethod 4705 public void setVisibility(int visibility) { 4706 setFlags(visibility, VISIBILITY_MASK); 4707 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); 4708 } 4709 4710 /** 4711 * Returns the enabled status for this view. The interpretation of the 4712 * enabled state varies by subclass. 4713 * 4714 * @return True if this view is enabled, false otherwise. 4715 */ 4716 @ViewDebug.ExportedProperty 4717 public boolean isEnabled() { 4718 return (mViewFlags & ENABLED_MASK) == ENABLED; 4719 } 4720 4721 /** 4722 * Set the enabled state of this view. The interpretation of the enabled 4723 * state varies by subclass. 4724 * 4725 * @param enabled True if this view is enabled, false otherwise. 4726 */ 4727 @RemotableViewMethod 4728 public void setEnabled(boolean enabled) { 4729 if (enabled == isEnabled()) return; 4730 4731 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 4732 4733 /* 4734 * The View most likely has to change its appearance, so refresh 4735 * the drawable state. 4736 */ 4737 refreshDrawableState(); 4738 4739 // Invalidate too, since the default behavior for views is to be 4740 // be drawn at 50% alpha rather than to change the drawable. 4741 invalidate(true); 4742 } 4743 4744 /** 4745 * Set whether this view can receive the focus. 4746 * 4747 * Setting this to false will also ensure that this view is not focusable 4748 * in touch mode. 4749 * 4750 * @param focusable If true, this view can receive the focus. 4751 * 4752 * @see #setFocusableInTouchMode(boolean) 4753 * @attr ref android.R.styleable#View_focusable 4754 */ 4755 public void setFocusable(boolean focusable) { 4756 if (!focusable) { 4757 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 4758 } 4759 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 4760 } 4761 4762 /** 4763 * Set whether this view can receive focus while in touch mode. 4764 * 4765 * Setting this to true will also ensure that this view is focusable. 4766 * 4767 * @param focusableInTouchMode If true, this view can receive the focus while 4768 * in touch mode. 4769 * 4770 * @see #setFocusable(boolean) 4771 * @attr ref android.R.styleable#View_focusableInTouchMode 4772 */ 4773 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 4774 // Focusable in touch mode should always be set before the focusable flag 4775 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 4776 // which, in touch mode, will not successfully request focus on this view 4777 // because the focusable in touch mode flag is not set 4778 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 4779 if (focusableInTouchMode) { 4780 setFlags(FOCUSABLE, FOCUSABLE_MASK); 4781 } 4782 } 4783 4784 /** 4785 * Set whether this view should have sound effects enabled for events such as 4786 * clicking and touching. 4787 * 4788 * <p>You may wish to disable sound effects for a view if you already play sounds, 4789 * for instance, a dial key that plays dtmf tones. 4790 * 4791 * @param soundEffectsEnabled whether sound effects are enabled for this view. 4792 * @see #isSoundEffectsEnabled() 4793 * @see #playSoundEffect(int) 4794 * @attr ref android.R.styleable#View_soundEffectsEnabled 4795 */ 4796 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 4797 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 4798 } 4799 4800 /** 4801 * @return whether this view should have sound effects enabled for events such as 4802 * clicking and touching. 4803 * 4804 * @see #setSoundEffectsEnabled(boolean) 4805 * @see #playSoundEffect(int) 4806 * @attr ref android.R.styleable#View_soundEffectsEnabled 4807 */ 4808 @ViewDebug.ExportedProperty 4809 public boolean isSoundEffectsEnabled() { 4810 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 4811 } 4812 4813 /** 4814 * Set whether this view should have haptic feedback for events such as 4815 * long presses. 4816 * 4817 * <p>You may wish to disable haptic feedback if your view already controls 4818 * its own haptic feedback. 4819 * 4820 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 4821 * @see #isHapticFeedbackEnabled() 4822 * @see #performHapticFeedback(int) 4823 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4824 */ 4825 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 4826 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 4827 } 4828 4829 /** 4830 * @return whether this view should have haptic feedback enabled for events 4831 * long presses. 4832 * 4833 * @see #setHapticFeedbackEnabled(boolean) 4834 * @see #performHapticFeedback(int) 4835 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4836 */ 4837 @ViewDebug.ExportedProperty 4838 public boolean isHapticFeedbackEnabled() { 4839 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 4840 } 4841 4842 /** 4843 * Returns the layout direction for this view. 4844 * 4845 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 4846 * {@link #LAYOUT_DIRECTION_RTL}, 4847 * {@link #LAYOUT_DIRECTION_INHERIT} or 4848 * {@link #LAYOUT_DIRECTION_LOCALE}. 4849 * @attr ref android.R.styleable#View_layoutDirection 4850 * 4851 * @hide 4852 */ 4853 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4854 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 4855 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 4856 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 4857 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 4858 }) 4859 public int getLayoutDirection() { 4860 return mViewFlags & LAYOUT_DIRECTION_MASK; 4861 } 4862 4863 /** 4864 * Set the layout direction for this view. This will propagate a reset of layout direction 4865 * resolution to the view's children and resolve layout direction for this view. 4866 * 4867 * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR}, 4868 * {@link #LAYOUT_DIRECTION_RTL}, 4869 * {@link #LAYOUT_DIRECTION_INHERIT} or 4870 * {@link #LAYOUT_DIRECTION_LOCALE}. 4871 * 4872 * @attr ref android.R.styleable#View_layoutDirection 4873 * 4874 * @hide 4875 */ 4876 @RemotableViewMethod 4877 public void setLayoutDirection(int layoutDirection) { 4878 if (getLayoutDirection() != layoutDirection) { 4879 resetResolvedLayoutDirection(); 4880 // Setting the flag will also request a layout. 4881 setFlags(layoutDirection, LAYOUT_DIRECTION_MASK); 4882 } 4883 } 4884 4885 /** 4886 * Returns the resolved layout direction for this view. 4887 * 4888 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 4889 * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL. 4890 * 4891 * @hide 4892 */ 4893 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4894 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 4895 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 4896 }) 4897 public int getResolvedLayoutDirection() { 4898 resolveLayoutDirectionIfNeeded(); 4899 return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ? 4900 LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 4901 } 4902 4903 /** 4904 * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from 4905 * layout attribute and/or the inherited value from the parent.</p> 4906 * 4907 * @return true if the layout is right-to-left. 4908 * 4909 * @hide 4910 */ 4911 @ViewDebug.ExportedProperty(category = "layout") 4912 public boolean isLayoutRtl() { 4913 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 4914 } 4915 4916 /** 4917 * If this view doesn't do any drawing on its own, set this flag to 4918 * allow further optimizations. By default, this flag is not set on 4919 * View, but could be set on some View subclasses such as ViewGroup. 4920 * 4921 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 4922 * you should clear this flag. 4923 * 4924 * @param willNotDraw whether or not this View draw on its own 4925 */ 4926 public void setWillNotDraw(boolean willNotDraw) { 4927 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 4928 } 4929 4930 /** 4931 * Returns whether or not this View draws on its own. 4932 * 4933 * @return true if this view has nothing to draw, false otherwise 4934 */ 4935 @ViewDebug.ExportedProperty(category = "drawing") 4936 public boolean willNotDraw() { 4937 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 4938 } 4939 4940 /** 4941 * When a View's drawing cache is enabled, drawing is redirected to an 4942 * offscreen bitmap. Some views, like an ImageView, must be able to 4943 * bypass this mechanism if they already draw a single bitmap, to avoid 4944 * unnecessary usage of the memory. 4945 * 4946 * @param willNotCacheDrawing true if this view does not cache its 4947 * drawing, false otherwise 4948 */ 4949 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 4950 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 4951 } 4952 4953 /** 4954 * Returns whether or not this View can cache its drawing or not. 4955 * 4956 * @return true if this view does not cache its drawing, false otherwise 4957 */ 4958 @ViewDebug.ExportedProperty(category = "drawing") 4959 public boolean willNotCacheDrawing() { 4960 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 4961 } 4962 4963 /** 4964 * Indicates whether this view reacts to click events or not. 4965 * 4966 * @return true if the view is clickable, false otherwise 4967 * 4968 * @see #setClickable(boolean) 4969 * @attr ref android.R.styleable#View_clickable 4970 */ 4971 @ViewDebug.ExportedProperty 4972 public boolean isClickable() { 4973 return (mViewFlags & CLICKABLE) == CLICKABLE; 4974 } 4975 4976 /** 4977 * Enables or disables click events for this view. When a view 4978 * is clickable it will change its state to "pressed" on every click. 4979 * Subclasses should set the view clickable to visually react to 4980 * user's clicks. 4981 * 4982 * @param clickable true to make the view clickable, false otherwise 4983 * 4984 * @see #isClickable() 4985 * @attr ref android.R.styleable#View_clickable 4986 */ 4987 public void setClickable(boolean clickable) { 4988 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 4989 } 4990 4991 /** 4992 * Indicates whether this view reacts to long click events or not. 4993 * 4994 * @return true if the view is long clickable, false otherwise 4995 * 4996 * @see #setLongClickable(boolean) 4997 * @attr ref android.R.styleable#View_longClickable 4998 */ 4999 public boolean isLongClickable() { 5000 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 5001 } 5002 5003 /** 5004 * Enables or disables long click events for this view. When a view is long 5005 * clickable it reacts to the user holding down the button for a longer 5006 * duration than a tap. This event can either launch the listener or a 5007 * context menu. 5008 * 5009 * @param longClickable true to make the view long clickable, false otherwise 5010 * @see #isLongClickable() 5011 * @attr ref android.R.styleable#View_longClickable 5012 */ 5013 public void setLongClickable(boolean longClickable) { 5014 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 5015 } 5016 5017 /** 5018 * Sets the pressed state for this view. 5019 * 5020 * @see #isClickable() 5021 * @see #setClickable(boolean) 5022 * 5023 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 5024 * the View's internal state from a previously set "pressed" state. 5025 */ 5026 public void setPressed(boolean pressed) { 5027 if (pressed) { 5028 mPrivateFlags |= PRESSED; 5029 } else { 5030 mPrivateFlags &= ~PRESSED; 5031 } 5032 refreshDrawableState(); 5033 dispatchSetPressed(pressed); 5034 } 5035 5036 /** 5037 * Dispatch setPressed to all of this View's children. 5038 * 5039 * @see #setPressed(boolean) 5040 * 5041 * @param pressed The new pressed state 5042 */ 5043 protected void dispatchSetPressed(boolean pressed) { 5044 } 5045 5046 /** 5047 * Indicates whether the view is currently in pressed state. Unless 5048 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 5049 * the pressed state. 5050 * 5051 * @see #setPressed(boolean) 5052 * @see #isClickable() 5053 * @see #setClickable(boolean) 5054 * 5055 * @return true if the view is currently pressed, false otherwise 5056 */ 5057 public boolean isPressed() { 5058 return (mPrivateFlags & PRESSED) == PRESSED; 5059 } 5060 5061 /** 5062 * Indicates whether this view will save its state (that is, 5063 * whether its {@link #onSaveInstanceState} method will be called). 5064 * 5065 * @return Returns true if the view state saving is enabled, else false. 5066 * 5067 * @see #setSaveEnabled(boolean) 5068 * @attr ref android.R.styleable#View_saveEnabled 5069 */ 5070 public boolean isSaveEnabled() { 5071 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 5072 } 5073 5074 /** 5075 * Controls whether the saving of this view's state is 5076 * enabled (that is, whether its {@link #onSaveInstanceState} method 5077 * will be called). Note that even if freezing is enabled, the 5078 * view still must have an id assigned to it (via {@link #setId(int)}) 5079 * for its state to be saved. This flag can only disable the 5080 * saving of this view; any child views may still have their state saved. 5081 * 5082 * @param enabled Set to false to <em>disable</em> state saving, or true 5083 * (the default) to allow it. 5084 * 5085 * @see #isSaveEnabled() 5086 * @see #setId(int) 5087 * @see #onSaveInstanceState() 5088 * @attr ref android.R.styleable#View_saveEnabled 5089 */ 5090 public void setSaveEnabled(boolean enabled) { 5091 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 5092 } 5093 5094 /** 5095 * Gets whether the framework should discard touches when the view's 5096 * window is obscured by another visible window. 5097 * Refer to the {@link View} security documentation for more details. 5098 * 5099 * @return True if touch filtering is enabled. 5100 * 5101 * @see #setFilterTouchesWhenObscured(boolean) 5102 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 5103 */ 5104 @ViewDebug.ExportedProperty 5105 public boolean getFilterTouchesWhenObscured() { 5106 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 5107 } 5108 5109 /** 5110 * Sets whether the framework should discard touches when the view's 5111 * window is obscured by another visible window. 5112 * Refer to the {@link View} security documentation for more details. 5113 * 5114 * @param enabled True if touch filtering should be enabled. 5115 * 5116 * @see #getFilterTouchesWhenObscured 5117 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 5118 */ 5119 public void setFilterTouchesWhenObscured(boolean enabled) { 5120 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 5121 FILTER_TOUCHES_WHEN_OBSCURED); 5122 } 5123 5124 /** 5125 * Indicates whether the entire hierarchy under this view will save its 5126 * state when a state saving traversal occurs from its parent. The default 5127 * is true; if false, these views will not be saved unless 5128 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 5129 * 5130 * @return Returns true if the view state saving from parent is enabled, else false. 5131 * 5132 * @see #setSaveFromParentEnabled(boolean) 5133 */ 5134 public boolean isSaveFromParentEnabled() { 5135 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 5136 } 5137 5138 /** 5139 * Controls whether the entire hierarchy under this view will save its 5140 * state when a state saving traversal occurs from its parent. The default 5141 * is true; if false, these views will not be saved unless 5142 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 5143 * 5144 * @param enabled Set to false to <em>disable</em> state saving, or true 5145 * (the default) to allow it. 5146 * 5147 * @see #isSaveFromParentEnabled() 5148 * @see #setId(int) 5149 * @see #onSaveInstanceState() 5150 */ 5151 public void setSaveFromParentEnabled(boolean enabled) { 5152 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 5153 } 5154 5155 5156 /** 5157 * Returns whether this View is able to take focus. 5158 * 5159 * @return True if this view can take focus, or false otherwise. 5160 * @attr ref android.R.styleable#View_focusable 5161 */ 5162 @ViewDebug.ExportedProperty(category = "focus") 5163 public final boolean isFocusable() { 5164 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 5165 } 5166 5167 /** 5168 * When a view is focusable, it may not want to take focus when in touch mode. 5169 * For example, a button would like focus when the user is navigating via a D-pad 5170 * so that the user can click on it, but once the user starts touching the screen, 5171 * the button shouldn't take focus 5172 * @return Whether the view is focusable in touch mode. 5173 * @attr ref android.R.styleable#View_focusableInTouchMode 5174 */ 5175 @ViewDebug.ExportedProperty 5176 public final boolean isFocusableInTouchMode() { 5177 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 5178 } 5179 5180 /** 5181 * Find the nearest view in the specified direction that can take focus. 5182 * This does not actually give focus to that view. 5183 * 5184 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5185 * 5186 * @return The nearest focusable in the specified direction, or null if none 5187 * can be found. 5188 */ 5189 public View focusSearch(int direction) { 5190 if (mParent != null) { 5191 return mParent.focusSearch(this, direction); 5192 } else { 5193 return null; 5194 } 5195 } 5196 5197 /** 5198 * This method is the last chance for the focused view and its ancestors to 5199 * respond to an arrow key. This is called when the focused view did not 5200 * consume the key internally, nor could the view system find a new view in 5201 * the requested direction to give focus to. 5202 * 5203 * @param focused The currently focused view. 5204 * @param direction The direction focus wants to move. One of FOCUS_UP, 5205 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 5206 * @return True if the this view consumed this unhandled move. 5207 */ 5208 public boolean dispatchUnhandledMove(View focused, int direction) { 5209 return false; 5210 } 5211 5212 /** 5213 * If a user manually specified the next view id for a particular direction, 5214 * use the root to look up the view. 5215 * @param root The root view of the hierarchy containing this view. 5216 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 5217 * or FOCUS_BACKWARD. 5218 * @return The user specified next view, or null if there is none. 5219 */ 5220 View findUserSetNextFocus(View root, int direction) { 5221 switch (direction) { 5222 case FOCUS_LEFT: 5223 if (mNextFocusLeftId == View.NO_ID) return null; 5224 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 5225 case FOCUS_RIGHT: 5226 if (mNextFocusRightId == View.NO_ID) return null; 5227 return findViewInsideOutShouldExist(root, mNextFocusRightId); 5228 case FOCUS_UP: 5229 if (mNextFocusUpId == View.NO_ID) return null; 5230 return findViewInsideOutShouldExist(root, mNextFocusUpId); 5231 case FOCUS_DOWN: 5232 if (mNextFocusDownId == View.NO_ID) return null; 5233 return findViewInsideOutShouldExist(root, mNextFocusDownId); 5234 case FOCUS_FORWARD: 5235 if (mNextFocusForwardId == View.NO_ID) return null; 5236 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 5237 case FOCUS_BACKWARD: { 5238 final int id = mID; 5239 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5240 @Override 5241 public boolean apply(View t) { 5242 return t.mNextFocusForwardId == id; 5243 } 5244 }); 5245 } 5246 } 5247 return null; 5248 } 5249 5250 private View findViewInsideOutShouldExist(View root, final int childViewId) { 5251 View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5252 @Override 5253 public boolean apply(View t) { 5254 return t.mID == childViewId; 5255 } 5256 }); 5257 5258 if (result == null) { 5259 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified " 5260 + "by user for id " + childViewId); 5261 } 5262 return result; 5263 } 5264 5265 /** 5266 * Find and return all focusable views that are descendants of this view, 5267 * possibly including this view if it is focusable itself. 5268 * 5269 * @param direction The direction of the focus 5270 * @return A list of focusable views 5271 */ 5272 public ArrayList<View> getFocusables(int direction) { 5273 ArrayList<View> result = new ArrayList<View>(24); 5274 addFocusables(result, direction); 5275 return result; 5276 } 5277 5278 /** 5279 * Add any focusable views that are descendants of this view (possibly 5280 * including this view if it is focusable itself) to views. If we are in touch mode, 5281 * only add views that are also focusable in touch mode. 5282 * 5283 * @param views Focusable views found so far 5284 * @param direction The direction of the focus 5285 */ 5286 public void addFocusables(ArrayList<View> views, int direction) { 5287 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 5288 } 5289 5290 /** 5291 * Adds any focusable views that are descendants of this view (possibly 5292 * including this view if it is focusable itself) to views. This method 5293 * adds all focusable views regardless if we are in touch mode or 5294 * only views focusable in touch mode if we are in touch mode depending on 5295 * the focusable mode paramater. 5296 * 5297 * @param views Focusable views found so far or null if all we are interested is 5298 * the number of focusables. 5299 * @param direction The direction of the focus. 5300 * @param focusableMode The type of focusables to be added. 5301 * 5302 * @see #FOCUSABLES_ALL 5303 * @see #FOCUSABLES_TOUCH_MODE 5304 */ 5305 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 5306 if (!isFocusable()) { 5307 return; 5308 } 5309 5310 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 5311 isInTouchMode() && !isFocusableInTouchMode()) { 5312 return; 5313 } 5314 5315 if (views != null) { 5316 views.add(this); 5317 } 5318 } 5319 5320 /** 5321 * Finds the Views that contain given text. The containment is case insensitive. 5322 * The search is performed by either the text that the View renders or the content 5323 * description that describes the view for accessibility purposes and the view does 5324 * not render or both. Clients can specify how the search is to be performed via 5325 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 5326 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 5327 * 5328 * @param outViews The output list of matching Views. 5329 * @param searched The text to match against. 5330 * 5331 * @see #FIND_VIEWS_WITH_TEXT 5332 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 5333 * @see #setContentDescription(CharSequence) 5334 */ 5335 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 5336 if (getAccessibilityNodeProvider() != null) { 5337 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 5338 outViews.add(this); 5339 } 5340 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 5341 && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) { 5342 String searchedLowerCase = searched.toString().toLowerCase(); 5343 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 5344 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 5345 outViews.add(this); 5346 } 5347 } 5348 } 5349 5350 /** 5351 * Find and return all touchable views that are descendants of this view, 5352 * possibly including this view if it is touchable itself. 5353 * 5354 * @return A list of touchable views 5355 */ 5356 public ArrayList<View> getTouchables() { 5357 ArrayList<View> result = new ArrayList<View>(); 5358 addTouchables(result); 5359 return result; 5360 } 5361 5362 /** 5363 * Add any touchable views that are descendants of this view (possibly 5364 * including this view if it is touchable itself) to views. 5365 * 5366 * @param views Touchable views found so far 5367 */ 5368 public void addTouchables(ArrayList<View> views) { 5369 final int viewFlags = mViewFlags; 5370 5371 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 5372 && (viewFlags & ENABLED_MASK) == ENABLED) { 5373 views.add(this); 5374 } 5375 } 5376 5377 /** 5378 * Call this to try to give focus to a specific view or to one of its 5379 * descendants. 5380 * 5381 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5382 * false), or if it is focusable and it is not focusable in touch mode 5383 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5384 * 5385 * See also {@link #focusSearch(int)}, which is what you call to say that you 5386 * have focus, and you want your parent to look for the next one. 5387 * 5388 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 5389 * {@link #FOCUS_DOWN} and <code>null</code>. 5390 * 5391 * @return Whether this view or one of its descendants actually took focus. 5392 */ 5393 public final boolean requestFocus() { 5394 return requestFocus(View.FOCUS_DOWN); 5395 } 5396 5397 5398 /** 5399 * Call this to try to give focus to a specific view or to one of its 5400 * descendants and give it a hint about what direction focus is heading. 5401 * 5402 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5403 * false), or if it is focusable and it is not focusable in touch mode 5404 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5405 * 5406 * See also {@link #focusSearch(int)}, which is what you call to say that you 5407 * have focus, and you want your parent to look for the next one. 5408 * 5409 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 5410 * <code>null</code> set for the previously focused rectangle. 5411 * 5412 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5413 * @return Whether this view or one of its descendants actually took focus. 5414 */ 5415 public final boolean requestFocus(int direction) { 5416 return requestFocus(direction, null); 5417 } 5418 5419 /** 5420 * Call this to try to give focus to a specific view or to one of its descendants 5421 * and give it hints about the direction and a specific rectangle that the focus 5422 * is coming from. The rectangle can help give larger views a finer grained hint 5423 * about where focus is coming from, and therefore, where to show selection, or 5424 * forward focus change internally. 5425 * 5426 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5427 * false), or if it is focusable and it is not focusable in touch mode 5428 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5429 * 5430 * A View will not take focus if it is not visible. 5431 * 5432 * A View will not take focus if one of its parents has 5433 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 5434 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 5435 * 5436 * See also {@link #focusSearch(int)}, which is what you call to say that you 5437 * have focus, and you want your parent to look for the next one. 5438 * 5439 * You may wish to override this method if your custom {@link View} has an internal 5440 * {@link View} that it wishes to forward the request to. 5441 * 5442 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5443 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 5444 * to give a finer grained hint about where focus is coming from. May be null 5445 * if there is no hint. 5446 * @return Whether this view or one of its descendants actually took focus. 5447 */ 5448 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 5449 // need to be focusable 5450 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 5451 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5452 return false; 5453 } 5454 5455 // need to be focusable in touch mode if in touch mode 5456 if (isInTouchMode() && 5457 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 5458 return false; 5459 } 5460 5461 // need to not have any parents blocking us 5462 if (hasAncestorThatBlocksDescendantFocus()) { 5463 return false; 5464 } 5465 5466 handleFocusGainInternal(direction, previouslyFocusedRect); 5467 return true; 5468 } 5469 5470 /** Gets the ViewAncestor, or null if not attached. */ 5471 /*package*/ ViewRootImpl getViewRootImpl() { 5472 View root = getRootView(); 5473 return root != null ? (ViewRootImpl)root.getParent() : null; 5474 } 5475 5476 /** 5477 * Call this to try to give focus to a specific view or to one of its descendants. This is a 5478 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 5479 * touch mode to request focus when they are touched. 5480 * 5481 * @return Whether this view or one of its descendants actually took focus. 5482 * 5483 * @see #isInTouchMode() 5484 * 5485 */ 5486 public final boolean requestFocusFromTouch() { 5487 // Leave touch mode if we need to 5488 if (isInTouchMode()) { 5489 ViewRootImpl viewRoot = getViewRootImpl(); 5490 if (viewRoot != null) { 5491 viewRoot.ensureTouchMode(false); 5492 } 5493 } 5494 return requestFocus(View.FOCUS_DOWN); 5495 } 5496 5497 /** 5498 * @return Whether any ancestor of this view blocks descendant focus. 5499 */ 5500 private boolean hasAncestorThatBlocksDescendantFocus() { 5501 ViewParent ancestor = mParent; 5502 while (ancestor instanceof ViewGroup) { 5503 final ViewGroup vgAncestor = (ViewGroup) ancestor; 5504 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 5505 return true; 5506 } else { 5507 ancestor = vgAncestor.getParent(); 5508 } 5509 } 5510 return false; 5511 } 5512 5513 /** 5514 * @hide 5515 */ 5516 public void dispatchStartTemporaryDetach() { 5517 onStartTemporaryDetach(); 5518 } 5519 5520 /** 5521 * This is called when a container is going to temporarily detach a child, with 5522 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 5523 * It will either be followed by {@link #onFinishTemporaryDetach()} or 5524 * {@link #onDetachedFromWindow()} when the container is done. 5525 */ 5526 public void onStartTemporaryDetach() { 5527 removeUnsetPressCallback(); 5528 mPrivateFlags |= CANCEL_NEXT_UP_EVENT; 5529 } 5530 5531 /** 5532 * @hide 5533 */ 5534 public void dispatchFinishTemporaryDetach() { 5535 onFinishTemporaryDetach(); 5536 } 5537 5538 /** 5539 * Called after {@link #onStartTemporaryDetach} when the container is done 5540 * changing the view. 5541 */ 5542 public void onFinishTemporaryDetach() { 5543 } 5544 5545 /** 5546 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 5547 * for this view's window. Returns null if the view is not currently attached 5548 * to the window. Normally you will not need to use this directly, but 5549 * just use the standard high-level event callbacks like 5550 * {@link #onKeyDown(int, KeyEvent)}. 5551 */ 5552 public KeyEvent.DispatcherState getKeyDispatcherState() { 5553 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 5554 } 5555 5556 /** 5557 * Dispatch a key event before it is processed by any input method 5558 * associated with the view hierarchy. This can be used to intercept 5559 * key events in special situations before the IME consumes them; a 5560 * typical example would be handling the BACK key to update the application's 5561 * UI instead of allowing the IME to see it and close itself. 5562 * 5563 * @param event The key event to be dispatched. 5564 * @return True if the event was handled, false otherwise. 5565 */ 5566 public boolean dispatchKeyEventPreIme(KeyEvent event) { 5567 return onKeyPreIme(event.getKeyCode(), event); 5568 } 5569 5570 /** 5571 * Dispatch a key event to the next view on the focus path. This path runs 5572 * from the top of the view tree down to the currently focused view. If this 5573 * view has focus, it will dispatch to itself. Otherwise it will dispatch 5574 * the next node down the focus path. This method also fires any key 5575 * listeners. 5576 * 5577 * @param event The key event to be dispatched. 5578 * @return True if the event was handled, false otherwise. 5579 */ 5580 public boolean dispatchKeyEvent(KeyEvent event) { 5581 if (mInputEventConsistencyVerifier != null) { 5582 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 5583 } 5584 5585 // Give any attached key listener a first crack at the event. 5586 //noinspection SimplifiableIfStatement 5587 ListenerInfo li = mListenerInfo; 5588 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5589 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 5590 return true; 5591 } 5592 5593 if (event.dispatch(this, mAttachInfo != null 5594 ? mAttachInfo.mKeyDispatchState : null, this)) { 5595 return true; 5596 } 5597 5598 if (mInputEventConsistencyVerifier != null) { 5599 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5600 } 5601 return false; 5602 } 5603 5604 /** 5605 * Dispatches a key shortcut event. 5606 * 5607 * @param event The key event to be dispatched. 5608 * @return True if the event was handled by the view, false otherwise. 5609 */ 5610 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 5611 return onKeyShortcut(event.getKeyCode(), event); 5612 } 5613 5614 /** 5615 * Pass the touch screen motion event down to the target view, or this 5616 * view if it is the target. 5617 * 5618 * @param event The motion event to be dispatched. 5619 * @return True if the event was handled by the view, false otherwise. 5620 */ 5621 public boolean dispatchTouchEvent(MotionEvent event) { 5622 if (mInputEventConsistencyVerifier != null) { 5623 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 5624 } 5625 5626 if (onFilterTouchEventForSecurity(event)) { 5627 //noinspection SimplifiableIfStatement 5628 ListenerInfo li = mListenerInfo; 5629 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5630 && li.mOnTouchListener.onTouch(this, event)) { 5631 return true; 5632 } 5633 5634 if (onTouchEvent(event)) { 5635 return true; 5636 } 5637 } 5638 5639 if (mInputEventConsistencyVerifier != null) { 5640 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5641 } 5642 return false; 5643 } 5644 5645 /** 5646 * Filter the touch event to apply security policies. 5647 * 5648 * @param event The motion event to be filtered. 5649 * @return True if the event should be dispatched, false if the event should be dropped. 5650 * 5651 * @see #getFilterTouchesWhenObscured 5652 */ 5653 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 5654 //noinspection RedundantIfStatement 5655 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 5656 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 5657 // Window is obscured, drop this touch. 5658 return false; 5659 } 5660 return true; 5661 } 5662 5663 /** 5664 * Pass a trackball motion event down to the focused view. 5665 * 5666 * @param event The motion event to be dispatched. 5667 * @return True if the event was handled by the view, false otherwise. 5668 */ 5669 public boolean dispatchTrackballEvent(MotionEvent event) { 5670 if (mInputEventConsistencyVerifier != null) { 5671 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 5672 } 5673 5674 return onTrackballEvent(event); 5675 } 5676 5677 /** 5678 * Dispatch a generic motion event. 5679 * <p> 5680 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5681 * are delivered to the view under the pointer. All other generic motion events are 5682 * delivered to the focused view. Hover events are handled specially and are delivered 5683 * to {@link #onHoverEvent(MotionEvent)}. 5684 * </p> 5685 * 5686 * @param event The motion event to be dispatched. 5687 * @return True if the event was handled by the view, false otherwise. 5688 */ 5689 public boolean dispatchGenericMotionEvent(MotionEvent event) { 5690 if (mInputEventConsistencyVerifier != null) { 5691 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 5692 } 5693 5694 final int source = event.getSource(); 5695 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5696 final int action = event.getAction(); 5697 if (action == MotionEvent.ACTION_HOVER_ENTER 5698 || action == MotionEvent.ACTION_HOVER_MOVE 5699 || action == MotionEvent.ACTION_HOVER_EXIT) { 5700 if (dispatchHoverEvent(event)) { 5701 return true; 5702 } 5703 } else if (dispatchGenericPointerEvent(event)) { 5704 return true; 5705 } 5706 } else if (dispatchGenericFocusedEvent(event)) { 5707 return true; 5708 } 5709 5710 if (dispatchGenericMotionEventInternal(event)) { 5711 return true; 5712 } 5713 5714 if (mInputEventConsistencyVerifier != null) { 5715 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5716 } 5717 return false; 5718 } 5719 5720 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 5721 //noinspection SimplifiableIfStatement 5722 ListenerInfo li = mListenerInfo; 5723 if (li != null && li.mOnGenericMotionListener != null 5724 && (mViewFlags & ENABLED_MASK) == ENABLED 5725 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 5726 return true; 5727 } 5728 5729 if (onGenericMotionEvent(event)) { 5730 return true; 5731 } 5732 5733 if (mInputEventConsistencyVerifier != null) { 5734 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5735 } 5736 return false; 5737 } 5738 5739 /** 5740 * Dispatch a hover event. 5741 * <p> 5742 * Do not call this method directly. 5743 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5744 * </p> 5745 * 5746 * @param event The motion event to be dispatched. 5747 * @return True if the event was handled by the view, false otherwise. 5748 */ 5749 protected boolean dispatchHoverEvent(MotionEvent event) { 5750 //noinspection SimplifiableIfStatement 5751 ListenerInfo li = mListenerInfo; 5752 if (li != null && li.mOnHoverListener != null 5753 && (mViewFlags & ENABLED_MASK) == ENABLED 5754 && li.mOnHoverListener.onHover(this, event)) { 5755 return true; 5756 } 5757 5758 return onHoverEvent(event); 5759 } 5760 5761 /** 5762 * Returns true if the view has a child to which it has recently sent 5763 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 5764 * it does not have a hovered child, then it must be the innermost hovered view. 5765 * @hide 5766 */ 5767 protected boolean hasHoveredChild() { 5768 return false; 5769 } 5770 5771 /** 5772 * Dispatch a generic motion event to the view under the first pointer. 5773 * <p> 5774 * Do not call this method directly. 5775 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5776 * </p> 5777 * 5778 * @param event The motion event to be dispatched. 5779 * @return True if the event was handled by the view, false otherwise. 5780 */ 5781 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 5782 return false; 5783 } 5784 5785 /** 5786 * Dispatch a generic motion event to the currently focused view. 5787 * <p> 5788 * Do not call this method directly. 5789 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5790 * </p> 5791 * 5792 * @param event The motion event to be dispatched. 5793 * @return True if the event was handled by the view, false otherwise. 5794 */ 5795 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 5796 return false; 5797 } 5798 5799 /** 5800 * Dispatch a pointer event. 5801 * <p> 5802 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 5803 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 5804 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 5805 * and should not be expected to handle other pointing device features. 5806 * </p> 5807 * 5808 * @param event The motion event to be dispatched. 5809 * @return True if the event was handled by the view, false otherwise. 5810 * @hide 5811 */ 5812 public final boolean dispatchPointerEvent(MotionEvent event) { 5813 if (event.isTouchEvent()) { 5814 return dispatchTouchEvent(event); 5815 } else { 5816 return dispatchGenericMotionEvent(event); 5817 } 5818 } 5819 5820 /** 5821 * Called when the window containing this view gains or loses window focus. 5822 * ViewGroups should override to route to their children. 5823 * 5824 * @param hasFocus True if the window containing this view now has focus, 5825 * false otherwise. 5826 */ 5827 public void dispatchWindowFocusChanged(boolean hasFocus) { 5828 onWindowFocusChanged(hasFocus); 5829 } 5830 5831 /** 5832 * Called when the window containing this view gains or loses focus. Note 5833 * that this is separate from view focus: to receive key events, both 5834 * your view and its window must have focus. If a window is displayed 5835 * on top of yours that takes input focus, then your own window will lose 5836 * focus but the view focus will remain unchanged. 5837 * 5838 * @param hasWindowFocus True if the window containing this view now has 5839 * focus, false otherwise. 5840 */ 5841 public void onWindowFocusChanged(boolean hasWindowFocus) { 5842 InputMethodManager imm = InputMethodManager.peekInstance(); 5843 if (!hasWindowFocus) { 5844 if (isPressed()) { 5845 setPressed(false); 5846 } 5847 if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5848 imm.focusOut(this); 5849 } 5850 removeLongPressCallback(); 5851 removeTapCallback(); 5852 onFocusLost(); 5853 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5854 imm.focusIn(this); 5855 } 5856 refreshDrawableState(); 5857 } 5858 5859 /** 5860 * Returns true if this view is in a window that currently has window focus. 5861 * Note that this is not the same as the view itself having focus. 5862 * 5863 * @return True if this view is in a window that currently has window focus. 5864 */ 5865 public boolean hasWindowFocus() { 5866 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 5867 } 5868 5869 /** 5870 * Dispatch a view visibility change down the view hierarchy. 5871 * ViewGroups should override to route to their children. 5872 * @param changedView The view whose visibility changed. Could be 'this' or 5873 * an ancestor view. 5874 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5875 * {@link #INVISIBLE} or {@link #GONE}. 5876 */ 5877 protected void dispatchVisibilityChanged(View changedView, int visibility) { 5878 onVisibilityChanged(changedView, visibility); 5879 } 5880 5881 /** 5882 * Called when the visibility of the view or an ancestor of the view is changed. 5883 * @param changedView The view whose visibility changed. Could be 'this' or 5884 * an ancestor view. 5885 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5886 * {@link #INVISIBLE} or {@link #GONE}. 5887 */ 5888 protected void onVisibilityChanged(View changedView, int visibility) { 5889 if (visibility == VISIBLE) { 5890 if (mAttachInfo != null) { 5891 initialAwakenScrollBars(); 5892 } else { 5893 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH; 5894 } 5895 } 5896 } 5897 5898 /** 5899 * Dispatch a hint about whether this view is displayed. For instance, when 5900 * a View moves out of the screen, it might receives a display hint indicating 5901 * the view is not displayed. Applications should not <em>rely</em> on this hint 5902 * as there is no guarantee that they will receive one. 5903 * 5904 * @param hint A hint about whether or not this view is displayed: 5905 * {@link #VISIBLE} or {@link #INVISIBLE}. 5906 */ 5907 public void dispatchDisplayHint(int hint) { 5908 onDisplayHint(hint); 5909 } 5910 5911 /** 5912 * Gives this view a hint about whether is displayed or not. For instance, when 5913 * a View moves out of the screen, it might receives a display hint indicating 5914 * the view is not displayed. Applications should not <em>rely</em> on this hint 5915 * as there is no guarantee that they will receive one. 5916 * 5917 * @param hint A hint about whether or not this view is displayed: 5918 * {@link #VISIBLE} or {@link #INVISIBLE}. 5919 */ 5920 protected void onDisplayHint(int hint) { 5921 } 5922 5923 /** 5924 * Dispatch a window visibility change down the view hierarchy. 5925 * ViewGroups should override to route to their children. 5926 * 5927 * @param visibility The new visibility of the window. 5928 * 5929 * @see #onWindowVisibilityChanged(int) 5930 */ 5931 public void dispatchWindowVisibilityChanged(int visibility) { 5932 onWindowVisibilityChanged(visibility); 5933 } 5934 5935 /** 5936 * Called when the window containing has change its visibility 5937 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 5938 * that this tells you whether or not your window is being made visible 5939 * to the window manager; this does <em>not</em> tell you whether or not 5940 * your window is obscured by other windows on the screen, even if it 5941 * is itself visible. 5942 * 5943 * @param visibility The new visibility of the window. 5944 */ 5945 protected void onWindowVisibilityChanged(int visibility) { 5946 if (visibility == VISIBLE) { 5947 initialAwakenScrollBars(); 5948 } 5949 } 5950 5951 /** 5952 * Returns the current visibility of the window this view is attached to 5953 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 5954 * 5955 * @return Returns the current visibility of the view's window. 5956 */ 5957 public int getWindowVisibility() { 5958 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 5959 } 5960 5961 /** 5962 * Retrieve the overall visible display size in which the window this view is 5963 * attached to has been positioned in. This takes into account screen 5964 * decorations above the window, for both cases where the window itself 5965 * is being position inside of them or the window is being placed under 5966 * then and covered insets are used for the window to position its content 5967 * inside. In effect, this tells you the available area where content can 5968 * be placed and remain visible to users. 5969 * 5970 * <p>This function requires an IPC back to the window manager to retrieve 5971 * the requested information, so should not be used in performance critical 5972 * code like drawing. 5973 * 5974 * @param outRect Filled in with the visible display frame. If the view 5975 * is not attached to a window, this is simply the raw display size. 5976 */ 5977 public void getWindowVisibleDisplayFrame(Rect outRect) { 5978 if (mAttachInfo != null) { 5979 try { 5980 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 5981 } catch (RemoteException e) { 5982 return; 5983 } 5984 // XXX This is really broken, and probably all needs to be done 5985 // in the window manager, and we need to know more about whether 5986 // we want the area behind or in front of the IME. 5987 final Rect insets = mAttachInfo.mVisibleInsets; 5988 outRect.left += insets.left; 5989 outRect.top += insets.top; 5990 outRect.right -= insets.right; 5991 outRect.bottom -= insets.bottom; 5992 return; 5993 } 5994 Display d = WindowManagerImpl.getDefault().getDefaultDisplay(); 5995 d.getRectSize(outRect); 5996 } 5997 5998 /** 5999 * Dispatch a notification about a resource configuration change down 6000 * the view hierarchy. 6001 * ViewGroups should override to route to their children. 6002 * 6003 * @param newConfig The new resource configuration. 6004 * 6005 * @see #onConfigurationChanged(android.content.res.Configuration) 6006 */ 6007 public void dispatchConfigurationChanged(Configuration newConfig) { 6008 onConfigurationChanged(newConfig); 6009 } 6010 6011 /** 6012 * Called when the current configuration of the resources being used 6013 * by the application have changed. You can use this to decide when 6014 * to reload resources that can changed based on orientation and other 6015 * configuration characterstics. You only need to use this if you are 6016 * not relying on the normal {@link android.app.Activity} mechanism of 6017 * recreating the activity instance upon a configuration change. 6018 * 6019 * @param newConfig The new resource configuration. 6020 */ 6021 protected void onConfigurationChanged(Configuration newConfig) { 6022 } 6023 6024 /** 6025 * Private function to aggregate all per-view attributes in to the view 6026 * root. 6027 */ 6028 void dispatchCollectViewAttributes(int visibility) { 6029 performCollectViewAttributes(visibility); 6030 } 6031 6032 void performCollectViewAttributes(int visibility) { 6033 if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) { 6034 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 6035 mAttachInfo.mKeepScreenOn = true; 6036 } 6037 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility; 6038 ListenerInfo li = mListenerInfo; 6039 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 6040 mAttachInfo.mHasSystemUiListeners = true; 6041 } 6042 } 6043 } 6044 6045 void needGlobalAttributesUpdate(boolean force) { 6046 final AttachInfo ai = mAttachInfo; 6047 if (ai != null) { 6048 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 6049 || ai.mHasSystemUiListeners) { 6050 ai.mRecomputeGlobalAttributes = true; 6051 } 6052 } 6053 } 6054 6055 /** 6056 * Returns whether the device is currently in touch mode. Touch mode is entered 6057 * once the user begins interacting with the device by touch, and affects various 6058 * things like whether focus is always visible to the user. 6059 * 6060 * @return Whether the device is in touch mode. 6061 */ 6062 @ViewDebug.ExportedProperty 6063 public boolean isInTouchMode() { 6064 if (mAttachInfo != null) { 6065 return mAttachInfo.mInTouchMode; 6066 } else { 6067 return ViewRootImpl.isInTouchMode(); 6068 } 6069 } 6070 6071 /** 6072 * Returns the context the view is running in, through which it can 6073 * access the current theme, resources, etc. 6074 * 6075 * @return The view's Context. 6076 */ 6077 @ViewDebug.CapturedViewProperty 6078 public final Context getContext() { 6079 return mContext; 6080 } 6081 6082 /** 6083 * Handle a key event before it is processed by any input method 6084 * associated with the view hierarchy. This can be used to intercept 6085 * key events in special situations before the IME consumes them; a 6086 * typical example would be handling the BACK key to update the application's 6087 * UI instead of allowing the IME to see it and close itself. 6088 * 6089 * @param keyCode The value in event.getKeyCode(). 6090 * @param event Description of the key event. 6091 * @return If you handled the event, return true. If you want to allow the 6092 * event to be handled by the next receiver, return false. 6093 */ 6094 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 6095 return false; 6096 } 6097 6098 /** 6099 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 6100 * KeyEvent.Callback.onKeyDown()}: perform press of the view 6101 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 6102 * is released, if the view is enabled and clickable. 6103 * 6104 * @param keyCode A key code that represents the button pressed, from 6105 * {@link android.view.KeyEvent}. 6106 * @param event The KeyEvent object that defines the button action. 6107 */ 6108 public boolean onKeyDown(int keyCode, KeyEvent event) { 6109 boolean result = false; 6110 6111 switch (keyCode) { 6112 case KeyEvent.KEYCODE_DPAD_CENTER: 6113 case KeyEvent.KEYCODE_ENTER: { 6114 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6115 return true; 6116 } 6117 // Long clickable items don't necessarily have to be clickable 6118 if (((mViewFlags & CLICKABLE) == CLICKABLE || 6119 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 6120 (event.getRepeatCount() == 0)) { 6121 setPressed(true); 6122 checkForLongClick(0); 6123 return true; 6124 } 6125 break; 6126 } 6127 } 6128 return result; 6129 } 6130 6131 /** 6132 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 6133 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 6134 * the event). 6135 */ 6136 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 6137 return false; 6138 } 6139 6140 /** 6141 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 6142 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 6143 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 6144 * {@link KeyEvent#KEYCODE_ENTER} is released. 6145 * 6146 * @param keyCode A key code that represents the button pressed, from 6147 * {@link android.view.KeyEvent}. 6148 * @param event The KeyEvent object that defines the button action. 6149 */ 6150 public boolean onKeyUp(int keyCode, KeyEvent event) { 6151 boolean result = false; 6152 6153 switch (keyCode) { 6154 case KeyEvent.KEYCODE_DPAD_CENTER: 6155 case KeyEvent.KEYCODE_ENTER: { 6156 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6157 return true; 6158 } 6159 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 6160 setPressed(false); 6161 6162 if (!mHasPerformedLongPress) { 6163 // This is a tap, so remove the longpress check 6164 removeLongPressCallback(); 6165 6166 result = performClick(); 6167 } 6168 } 6169 break; 6170 } 6171 } 6172 return result; 6173 } 6174 6175 /** 6176 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 6177 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 6178 * the event). 6179 * 6180 * @param keyCode A key code that represents the button pressed, from 6181 * {@link android.view.KeyEvent}. 6182 * @param repeatCount The number of times the action was made. 6183 * @param event The KeyEvent object that defines the button action. 6184 */ 6185 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 6186 return false; 6187 } 6188 6189 /** 6190 * Called on the focused view when a key shortcut event is not handled. 6191 * Override this method to implement local key shortcuts for the View. 6192 * Key shortcuts can also be implemented by setting the 6193 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 6194 * 6195 * @param keyCode The value in event.getKeyCode(). 6196 * @param event Description of the key event. 6197 * @return If you handled the event, return true. If you want to allow the 6198 * event to be handled by the next receiver, return false. 6199 */ 6200 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 6201 return false; 6202 } 6203 6204 /** 6205 * Check whether the called view is a text editor, in which case it 6206 * would make sense to automatically display a soft input window for 6207 * it. Subclasses should override this if they implement 6208 * {@link #onCreateInputConnection(EditorInfo)} to return true if 6209 * a call on that method would return a non-null InputConnection, and 6210 * they are really a first-class editor that the user would normally 6211 * start typing on when the go into a window containing your view. 6212 * 6213 * <p>The default implementation always returns false. This does 6214 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 6215 * will not be called or the user can not otherwise perform edits on your 6216 * view; it is just a hint to the system that this is not the primary 6217 * purpose of this view. 6218 * 6219 * @return Returns true if this view is a text editor, else false. 6220 */ 6221 public boolean onCheckIsTextEditor() { 6222 return false; 6223 } 6224 6225 /** 6226 * Create a new InputConnection for an InputMethod to interact 6227 * with the view. The default implementation returns null, since it doesn't 6228 * support input methods. You can override this to implement such support. 6229 * This is only needed for views that take focus and text input. 6230 * 6231 * <p>When implementing this, you probably also want to implement 6232 * {@link #onCheckIsTextEditor()} to indicate you will return a 6233 * non-null InputConnection. 6234 * 6235 * @param outAttrs Fill in with attribute information about the connection. 6236 */ 6237 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 6238 return null; 6239 } 6240 6241 /** 6242 * Called by the {@link android.view.inputmethod.InputMethodManager} 6243 * when a view who is not the current 6244 * input connection target is trying to make a call on the manager. The 6245 * default implementation returns false; you can override this to return 6246 * true for certain views if you are performing InputConnection proxying 6247 * to them. 6248 * @param view The View that is making the InputMethodManager call. 6249 * @return Return true to allow the call, false to reject. 6250 */ 6251 public boolean checkInputConnectionProxy(View view) { 6252 return false; 6253 } 6254 6255 /** 6256 * Show the context menu for this view. It is not safe to hold on to the 6257 * menu after returning from this method. 6258 * 6259 * You should normally not overload this method. Overload 6260 * {@link #onCreateContextMenu(ContextMenu)} or define an 6261 * {@link OnCreateContextMenuListener} to add items to the context menu. 6262 * 6263 * @param menu The context menu to populate 6264 */ 6265 public void createContextMenu(ContextMenu menu) { 6266 ContextMenuInfo menuInfo = getContextMenuInfo(); 6267 6268 // Sets the current menu info so all items added to menu will have 6269 // my extra info set. 6270 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 6271 6272 onCreateContextMenu(menu); 6273 ListenerInfo li = mListenerInfo; 6274 if (li != null && li.mOnCreateContextMenuListener != null) { 6275 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 6276 } 6277 6278 // Clear the extra information so subsequent items that aren't mine don't 6279 // have my extra info. 6280 ((MenuBuilder)menu).setCurrentMenuInfo(null); 6281 6282 if (mParent != null) { 6283 mParent.createContextMenu(menu); 6284 } 6285 } 6286 6287 /** 6288 * Views should implement this if they have extra information to associate 6289 * with the context menu. The return result is supplied as a parameter to 6290 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 6291 * callback. 6292 * 6293 * @return Extra information about the item for which the context menu 6294 * should be shown. This information will vary across different 6295 * subclasses of View. 6296 */ 6297 protected ContextMenuInfo getContextMenuInfo() { 6298 return null; 6299 } 6300 6301 /** 6302 * Views should implement this if the view itself is going to add items to 6303 * the context menu. 6304 * 6305 * @param menu the context menu to populate 6306 */ 6307 protected void onCreateContextMenu(ContextMenu menu) { 6308 } 6309 6310 /** 6311 * Implement this method to handle trackball motion events. The 6312 * <em>relative</em> movement of the trackball since the last event 6313 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 6314 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 6315 * that a movement of 1 corresponds to the user pressing one DPAD key (so 6316 * they will often be fractional values, representing the more fine-grained 6317 * movement information available from a trackball). 6318 * 6319 * @param event The motion event. 6320 * @return True if the event was handled, false otherwise. 6321 */ 6322 public boolean onTrackballEvent(MotionEvent event) { 6323 return false; 6324 } 6325 6326 /** 6327 * Implement this method to handle generic motion events. 6328 * <p> 6329 * Generic motion events describe joystick movements, mouse hovers, track pad 6330 * touches, scroll wheel movements and other input events. The 6331 * {@link MotionEvent#getSource() source} of the motion event specifies 6332 * the class of input that was received. Implementations of this method 6333 * must examine the bits in the source before processing the event. 6334 * The following code example shows how this is done. 6335 * </p><p> 6336 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 6337 * are delivered to the view under the pointer. All other generic motion events are 6338 * delivered to the focused view. 6339 * </p> 6340 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 6341 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 6342 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 6343 * // process the joystick movement... 6344 * return true; 6345 * } 6346 * } 6347 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 6348 * switch (event.getAction()) { 6349 * case MotionEvent.ACTION_HOVER_MOVE: 6350 * // process the mouse hover movement... 6351 * return true; 6352 * case MotionEvent.ACTION_SCROLL: 6353 * // process the scroll wheel movement... 6354 * return true; 6355 * } 6356 * } 6357 * return super.onGenericMotionEvent(event); 6358 * }</pre> 6359 * 6360 * @param event The generic motion event being processed. 6361 * @return True if the event was handled, false otherwise. 6362 */ 6363 public boolean onGenericMotionEvent(MotionEvent event) { 6364 return false; 6365 } 6366 6367 /** 6368 * Implement this method to handle hover events. 6369 * <p> 6370 * This method is called whenever a pointer is hovering into, over, or out of the 6371 * bounds of a view and the view is not currently being touched. 6372 * Hover events are represented as pointer events with action 6373 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 6374 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 6375 * </p> 6376 * <ul> 6377 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 6378 * when the pointer enters the bounds of the view.</li> 6379 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 6380 * when the pointer has already entered the bounds of the view and has moved.</li> 6381 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 6382 * when the pointer has exited the bounds of the view or when the pointer is 6383 * about to go down due to a button click, tap, or similar user action that 6384 * causes the view to be touched.</li> 6385 * </ul> 6386 * <p> 6387 * The view should implement this method to return true to indicate that it is 6388 * handling the hover event, such as by changing its drawable state. 6389 * </p><p> 6390 * The default implementation calls {@link #setHovered} to update the hovered state 6391 * of the view when a hover enter or hover exit event is received, if the view 6392 * is enabled and is clickable. The default implementation also sends hover 6393 * accessibility events. 6394 * </p> 6395 * 6396 * @param event The motion event that describes the hover. 6397 * @return True if the view handled the hover event. 6398 * 6399 * @see #isHovered 6400 * @see #setHovered 6401 * @see #onHoverChanged 6402 */ 6403 public boolean onHoverEvent(MotionEvent event) { 6404 // The root view may receive hover (or touch) events that are outside the bounds of 6405 // the window. This code ensures that we only send accessibility events for 6406 // hovers that are actually within the bounds of the root view. 6407 final int action = event.getAction(); 6408 if (!mSendingHoverAccessibilityEvents) { 6409 if ((action == MotionEvent.ACTION_HOVER_ENTER 6410 || action == MotionEvent.ACTION_HOVER_MOVE) 6411 && !hasHoveredChild() 6412 && pointInView(event.getX(), event.getY())) { 6413 mSendingHoverAccessibilityEvents = true; 6414 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 6415 } 6416 } else { 6417 if (action == MotionEvent.ACTION_HOVER_EXIT 6418 || (action == MotionEvent.ACTION_HOVER_MOVE 6419 && !pointInView(event.getX(), event.getY()))) { 6420 mSendingHoverAccessibilityEvents = false; 6421 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 6422 } 6423 } 6424 6425 if (isHoverable()) { 6426 switch (action) { 6427 case MotionEvent.ACTION_HOVER_ENTER: 6428 setHovered(true); 6429 break; 6430 case MotionEvent.ACTION_HOVER_EXIT: 6431 setHovered(false); 6432 break; 6433 } 6434 6435 // Dispatch the event to onGenericMotionEvent before returning true. 6436 // This is to provide compatibility with existing applications that 6437 // handled HOVER_MOVE events in onGenericMotionEvent and that would 6438 // break because of the new default handling for hoverable views 6439 // in onHoverEvent. 6440 // Note that onGenericMotionEvent will be called by default when 6441 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 6442 dispatchGenericMotionEventInternal(event); 6443 return true; 6444 } 6445 return false; 6446 } 6447 6448 /** 6449 * Returns true if the view should handle {@link #onHoverEvent} 6450 * by calling {@link #setHovered} to change its hovered state. 6451 * 6452 * @return True if the view is hoverable. 6453 */ 6454 private boolean isHoverable() { 6455 final int viewFlags = mViewFlags; 6456 //noinspection SimplifiableIfStatement 6457 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6458 return false; 6459 } 6460 6461 return (viewFlags & CLICKABLE) == CLICKABLE 6462 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6463 } 6464 6465 /** 6466 * Returns true if the view is currently hovered. 6467 * 6468 * @return True if the view is currently hovered. 6469 * 6470 * @see #setHovered 6471 * @see #onHoverChanged 6472 */ 6473 @ViewDebug.ExportedProperty 6474 public boolean isHovered() { 6475 return (mPrivateFlags & HOVERED) != 0; 6476 } 6477 6478 /** 6479 * Sets whether the view is currently hovered. 6480 * <p> 6481 * Calling this method also changes the drawable state of the view. This 6482 * enables the view to react to hover by using different drawable resources 6483 * to change its appearance. 6484 * </p><p> 6485 * The {@link #onHoverChanged} method is called when the hovered state changes. 6486 * </p> 6487 * 6488 * @param hovered True if the view is hovered. 6489 * 6490 * @see #isHovered 6491 * @see #onHoverChanged 6492 */ 6493 public void setHovered(boolean hovered) { 6494 if (hovered) { 6495 if ((mPrivateFlags & HOVERED) == 0) { 6496 mPrivateFlags |= HOVERED; 6497 refreshDrawableState(); 6498 onHoverChanged(true); 6499 } 6500 } else { 6501 if ((mPrivateFlags & HOVERED) != 0) { 6502 mPrivateFlags &= ~HOVERED; 6503 refreshDrawableState(); 6504 onHoverChanged(false); 6505 } 6506 } 6507 } 6508 6509 /** 6510 * Implement this method to handle hover state changes. 6511 * <p> 6512 * This method is called whenever the hover state changes as a result of a 6513 * call to {@link #setHovered}. 6514 * </p> 6515 * 6516 * @param hovered The current hover state, as returned by {@link #isHovered}. 6517 * 6518 * @see #isHovered 6519 * @see #setHovered 6520 */ 6521 public void onHoverChanged(boolean hovered) { 6522 } 6523 6524 /** 6525 * Implement this method to handle touch screen motion events. 6526 * 6527 * @param event The motion event. 6528 * @return True if the event was handled, false otherwise. 6529 */ 6530 public boolean onTouchEvent(MotionEvent event) { 6531 final int viewFlags = mViewFlags; 6532 6533 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6534 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) { 6535 mPrivateFlags &= ~PRESSED; 6536 refreshDrawableState(); 6537 } 6538 // A disabled view that is clickable still consumes the touch 6539 // events, it just doesn't respond to them. 6540 return (((viewFlags & CLICKABLE) == CLICKABLE || 6541 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 6542 } 6543 6544 if (mTouchDelegate != null) { 6545 if (mTouchDelegate.onTouchEvent(event)) { 6546 return true; 6547 } 6548 } 6549 6550 if (((viewFlags & CLICKABLE) == CLICKABLE || 6551 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 6552 switch (event.getAction()) { 6553 case MotionEvent.ACTION_UP: 6554 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; 6555 if ((mPrivateFlags & PRESSED) != 0 || prepressed) { 6556 // take focus if we don't have it already and we should in 6557 // touch mode. 6558 boolean focusTaken = false; 6559 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 6560 focusTaken = requestFocus(); 6561 } 6562 6563 if (prepressed) { 6564 // The button is being released before we actually 6565 // showed it as pressed. Make it show the pressed 6566 // state now (before scheduling the click) to ensure 6567 // the user sees it. 6568 mPrivateFlags |= PRESSED; 6569 refreshDrawableState(); 6570 } 6571 6572 if (!mHasPerformedLongPress) { 6573 // This is a tap, so remove the longpress check 6574 removeLongPressCallback(); 6575 6576 // Only perform take click actions if we were in the pressed state 6577 if (!focusTaken) { 6578 // Use a Runnable and post this rather than calling 6579 // performClick directly. This lets other visual state 6580 // of the view update before click actions start. 6581 if (mPerformClick == null) { 6582 mPerformClick = new PerformClick(); 6583 } 6584 if (!post(mPerformClick)) { 6585 performClick(); 6586 } 6587 } 6588 } 6589 6590 if (mUnsetPressedState == null) { 6591 mUnsetPressedState = new UnsetPressedState(); 6592 } 6593 6594 if (prepressed) { 6595 postDelayed(mUnsetPressedState, 6596 ViewConfiguration.getPressedStateDuration()); 6597 } else if (!post(mUnsetPressedState)) { 6598 // If the post failed, unpress right now 6599 mUnsetPressedState.run(); 6600 } 6601 removeTapCallback(); 6602 } 6603 break; 6604 6605 case MotionEvent.ACTION_DOWN: 6606 mHasPerformedLongPress = false; 6607 6608 if (performButtonActionOnTouchDown(event)) { 6609 break; 6610 } 6611 6612 // Walk up the hierarchy to determine if we're inside a scrolling container. 6613 boolean isInScrollingContainer = isInScrollingContainer(); 6614 6615 // For views inside a scrolling container, delay the pressed feedback for 6616 // a short period in case this is a scroll. 6617 if (isInScrollingContainer) { 6618 mPrivateFlags |= PREPRESSED; 6619 if (mPendingCheckForTap == null) { 6620 mPendingCheckForTap = new CheckForTap(); 6621 } 6622 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 6623 } else { 6624 // Not inside a scrolling container, so show the feedback right away 6625 mPrivateFlags |= PRESSED; 6626 refreshDrawableState(); 6627 checkForLongClick(0); 6628 } 6629 break; 6630 6631 case MotionEvent.ACTION_CANCEL: 6632 mPrivateFlags &= ~PRESSED; 6633 refreshDrawableState(); 6634 removeTapCallback(); 6635 break; 6636 6637 case MotionEvent.ACTION_MOVE: 6638 final int x = (int) event.getX(); 6639 final int y = (int) event.getY(); 6640 6641 // Be lenient about moving outside of buttons 6642 if (!pointInView(x, y, mTouchSlop)) { 6643 // Outside button 6644 removeTapCallback(); 6645 if ((mPrivateFlags & PRESSED) != 0) { 6646 // Remove any future long press/tap checks 6647 removeLongPressCallback(); 6648 6649 // Need to switch from pressed to not pressed 6650 mPrivateFlags &= ~PRESSED; 6651 refreshDrawableState(); 6652 } 6653 } 6654 break; 6655 } 6656 return true; 6657 } 6658 6659 return false; 6660 } 6661 6662 /** 6663 * @hide 6664 */ 6665 public boolean isInScrollingContainer() { 6666 ViewParent p = getParent(); 6667 while (p != null && p instanceof ViewGroup) { 6668 if (((ViewGroup) p).shouldDelayChildPressedState()) { 6669 return true; 6670 } 6671 p = p.getParent(); 6672 } 6673 return false; 6674 } 6675 6676 /** 6677 * Remove the longpress detection timer. 6678 */ 6679 private void removeLongPressCallback() { 6680 if (mPendingCheckForLongPress != null) { 6681 removeCallbacks(mPendingCheckForLongPress); 6682 } 6683 } 6684 6685 /** 6686 * Remove the pending click action 6687 */ 6688 private void removePerformClickCallback() { 6689 if (mPerformClick != null) { 6690 removeCallbacks(mPerformClick); 6691 } 6692 } 6693 6694 /** 6695 * Remove the prepress detection timer. 6696 */ 6697 private void removeUnsetPressCallback() { 6698 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) { 6699 setPressed(false); 6700 removeCallbacks(mUnsetPressedState); 6701 } 6702 } 6703 6704 /** 6705 * Remove the tap detection timer. 6706 */ 6707 private void removeTapCallback() { 6708 if (mPendingCheckForTap != null) { 6709 mPrivateFlags &= ~PREPRESSED; 6710 removeCallbacks(mPendingCheckForTap); 6711 } 6712 } 6713 6714 /** 6715 * Cancels a pending long press. Your subclass can use this if you 6716 * want the context menu to come up if the user presses and holds 6717 * at the same place, but you don't want it to come up if they press 6718 * and then move around enough to cause scrolling. 6719 */ 6720 public void cancelLongPress() { 6721 removeLongPressCallback(); 6722 6723 /* 6724 * The prepressed state handled by the tap callback is a display 6725 * construct, but the tap callback will post a long press callback 6726 * less its own timeout. Remove it here. 6727 */ 6728 removeTapCallback(); 6729 } 6730 6731 /** 6732 * Remove the pending callback for sending a 6733 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 6734 */ 6735 private void removeSendViewScrolledAccessibilityEventCallback() { 6736 if (mSendViewScrolledAccessibilityEvent != null) { 6737 removeCallbacks(mSendViewScrolledAccessibilityEvent); 6738 } 6739 } 6740 6741 /** 6742 * Sets the TouchDelegate for this View. 6743 */ 6744 public void setTouchDelegate(TouchDelegate delegate) { 6745 mTouchDelegate = delegate; 6746 } 6747 6748 /** 6749 * Gets the TouchDelegate for this View. 6750 */ 6751 public TouchDelegate getTouchDelegate() { 6752 return mTouchDelegate; 6753 } 6754 6755 /** 6756 * Set flags controlling behavior of this view. 6757 * 6758 * @param flags Constant indicating the value which should be set 6759 * @param mask Constant indicating the bit range that should be changed 6760 */ 6761 void setFlags(int flags, int mask) { 6762 int old = mViewFlags; 6763 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 6764 6765 int changed = mViewFlags ^ old; 6766 if (changed == 0) { 6767 return; 6768 } 6769 int privateFlags = mPrivateFlags; 6770 6771 /* Check if the FOCUSABLE bit has changed */ 6772 if (((changed & FOCUSABLE_MASK) != 0) && 6773 ((privateFlags & HAS_BOUNDS) !=0)) { 6774 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 6775 && ((privateFlags & FOCUSED) != 0)) { 6776 /* Give up focus if we are no longer focusable */ 6777 clearFocus(); 6778 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 6779 && ((privateFlags & FOCUSED) == 0)) { 6780 /* 6781 * Tell the view system that we are now available to take focus 6782 * if no one else already has it. 6783 */ 6784 if (mParent != null) mParent.focusableViewAvailable(this); 6785 } 6786 } 6787 6788 if ((flags & VISIBILITY_MASK) == VISIBLE) { 6789 if ((changed & VISIBILITY_MASK) != 0) { 6790 /* 6791 * If this view is becoming visible, invalidate it in case it changed while 6792 * it was not visible. Marking it drawn ensures that the invalidation will 6793 * go through. 6794 */ 6795 mPrivateFlags |= DRAWN; 6796 invalidate(true); 6797 6798 needGlobalAttributesUpdate(true); 6799 6800 // a view becoming visible is worth notifying the parent 6801 // about in case nothing has focus. even if this specific view 6802 // isn't focusable, it may contain something that is, so let 6803 // the root view try to give this focus if nothing else does. 6804 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 6805 mParent.focusableViewAvailable(this); 6806 } 6807 } 6808 } 6809 6810 /* Check if the GONE bit has changed */ 6811 if ((changed & GONE) != 0) { 6812 needGlobalAttributesUpdate(false); 6813 requestLayout(); 6814 6815 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 6816 if (hasFocus()) clearFocus(); 6817 destroyDrawingCache(); 6818 if (mParent instanceof View) { 6819 // GONE views noop invalidation, so invalidate the parent 6820 ((View) mParent).invalidate(true); 6821 } 6822 // Mark the view drawn to ensure that it gets invalidated properly the next 6823 // time it is visible and gets invalidated 6824 mPrivateFlags |= DRAWN; 6825 } 6826 if (mAttachInfo != null) { 6827 mAttachInfo.mViewVisibilityChanged = true; 6828 } 6829 } 6830 6831 /* Check if the VISIBLE bit has changed */ 6832 if ((changed & INVISIBLE) != 0) { 6833 needGlobalAttributesUpdate(false); 6834 /* 6835 * If this view is becoming invisible, set the DRAWN flag so that 6836 * the next invalidate() will not be skipped. 6837 */ 6838 mPrivateFlags |= DRAWN; 6839 6840 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 6841 // root view becoming invisible shouldn't clear focus 6842 if (getRootView() != this) { 6843 clearFocus(); 6844 } 6845 } 6846 if (mAttachInfo != null) { 6847 mAttachInfo.mViewVisibilityChanged = true; 6848 } 6849 } 6850 6851 if ((changed & VISIBILITY_MASK) != 0) { 6852 if (mParent instanceof ViewGroup) { 6853 ((ViewGroup) mParent).onChildVisibilityChanged(this, (changed & VISIBILITY_MASK), 6854 (flags & VISIBILITY_MASK)); 6855 ((View) mParent).invalidate(true); 6856 } else if (mParent != null) { 6857 mParent.invalidateChild(this, null); 6858 } 6859 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6860 } 6861 6862 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 6863 destroyDrawingCache(); 6864 } 6865 6866 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 6867 destroyDrawingCache(); 6868 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6869 invalidateParentCaches(); 6870 } 6871 6872 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 6873 destroyDrawingCache(); 6874 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6875 } 6876 6877 if ((changed & DRAW_MASK) != 0) { 6878 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 6879 if (mBGDrawable != null) { 6880 mPrivateFlags &= ~SKIP_DRAW; 6881 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 6882 } else { 6883 mPrivateFlags |= SKIP_DRAW; 6884 } 6885 } else { 6886 mPrivateFlags &= ~SKIP_DRAW; 6887 } 6888 requestLayout(); 6889 invalidate(true); 6890 } 6891 6892 if ((changed & KEEP_SCREEN_ON) != 0) { 6893 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 6894 mParent.recomputeViewAttributes(this); 6895 } 6896 } 6897 6898 if ((changed & LAYOUT_DIRECTION_MASK) != 0) { 6899 requestLayout(); 6900 } 6901 } 6902 6903 /** 6904 * Change the view's z order in the tree, so it's on top of other sibling 6905 * views 6906 */ 6907 public void bringToFront() { 6908 if (mParent != null) { 6909 mParent.bringChildToFront(this); 6910 } 6911 } 6912 6913 /** 6914 * This is called in response to an internal scroll in this view (i.e., the 6915 * view scrolled its own contents). This is typically as a result of 6916 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 6917 * called. 6918 * 6919 * @param l Current horizontal scroll origin. 6920 * @param t Current vertical scroll origin. 6921 * @param oldl Previous horizontal scroll origin. 6922 * @param oldt Previous vertical scroll origin. 6923 */ 6924 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 6925 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6926 postSendViewScrolledAccessibilityEventCallback(); 6927 } 6928 6929 mBackgroundSizeChanged = true; 6930 6931 final AttachInfo ai = mAttachInfo; 6932 if (ai != null) { 6933 ai.mViewScrollChanged = true; 6934 } 6935 } 6936 6937 /** 6938 * Interface definition for a callback to be invoked when the layout bounds of a view 6939 * changes due to layout processing. 6940 */ 6941 public interface OnLayoutChangeListener { 6942 /** 6943 * Called when the focus state of a view has changed. 6944 * 6945 * @param v The view whose state has changed. 6946 * @param left The new value of the view's left property. 6947 * @param top The new value of the view's top property. 6948 * @param right The new value of the view's right property. 6949 * @param bottom The new value of the view's bottom property. 6950 * @param oldLeft The previous value of the view's left property. 6951 * @param oldTop The previous value of the view's top property. 6952 * @param oldRight The previous value of the view's right property. 6953 * @param oldBottom The previous value of the view's bottom property. 6954 */ 6955 void onLayoutChange(View v, int left, int top, int right, int bottom, 6956 int oldLeft, int oldTop, int oldRight, int oldBottom); 6957 } 6958 6959 /** 6960 * This is called during layout when the size of this view has changed. If 6961 * you were just added to the view hierarchy, you're called with the old 6962 * values of 0. 6963 * 6964 * @param w Current width of this view. 6965 * @param h Current height of this view. 6966 * @param oldw Old width of this view. 6967 * @param oldh Old height of this view. 6968 */ 6969 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 6970 } 6971 6972 /** 6973 * Called by draw to draw the child views. This may be overridden 6974 * by derived classes to gain control just before its children are drawn 6975 * (but after its own view has been drawn). 6976 * @param canvas the canvas on which to draw the view 6977 */ 6978 protected void dispatchDraw(Canvas canvas) { 6979 } 6980 6981 /** 6982 * Gets the parent of this view. Note that the parent is a 6983 * ViewParent and not necessarily a View. 6984 * 6985 * @return Parent of this view. 6986 */ 6987 public final ViewParent getParent() { 6988 return mParent; 6989 } 6990 6991 /** 6992 * Set the horizontal scrolled position of your view. This will cause a call to 6993 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6994 * invalidated. 6995 * @param value the x position to scroll to 6996 */ 6997 public void setScrollX(int value) { 6998 scrollTo(value, mScrollY); 6999 } 7000 7001 /** 7002 * Set the vertical scrolled position of your view. This will cause a call to 7003 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7004 * invalidated. 7005 * @param value the y position to scroll to 7006 */ 7007 public void setScrollY(int value) { 7008 scrollTo(mScrollX, value); 7009 } 7010 7011 /** 7012 * Return the scrolled left position of this view. This is the left edge of 7013 * the displayed part of your view. You do not need to draw any pixels 7014 * farther left, since those are outside of the frame of your view on 7015 * screen. 7016 * 7017 * @return The left edge of the displayed part of your view, in pixels. 7018 */ 7019 public final int getScrollX() { 7020 return mScrollX; 7021 } 7022 7023 /** 7024 * Return the scrolled top position of this view. This is the top edge of 7025 * the displayed part of your view. You do not need to draw any pixels above 7026 * it, since those are outside of the frame of your view on screen. 7027 * 7028 * @return The top edge of the displayed part of your view, in pixels. 7029 */ 7030 public final int getScrollY() { 7031 return mScrollY; 7032 } 7033 7034 /** 7035 * Return the width of the your view. 7036 * 7037 * @return The width of your view, in pixels. 7038 */ 7039 @ViewDebug.ExportedProperty(category = "layout") 7040 public final int getWidth() { 7041 return mRight - mLeft; 7042 } 7043 7044 /** 7045 * Return the height of your view. 7046 * 7047 * @return The height of your view, in pixels. 7048 */ 7049 @ViewDebug.ExportedProperty(category = "layout") 7050 public final int getHeight() { 7051 return mBottom - mTop; 7052 } 7053 7054 /** 7055 * Return the visible drawing bounds of your view. Fills in the output 7056 * rectangle with the values from getScrollX(), getScrollY(), 7057 * getWidth(), and getHeight(). 7058 * 7059 * @param outRect The (scrolled) drawing bounds of the view. 7060 */ 7061 public void getDrawingRect(Rect outRect) { 7062 outRect.left = mScrollX; 7063 outRect.top = mScrollY; 7064 outRect.right = mScrollX + (mRight - mLeft); 7065 outRect.bottom = mScrollY + (mBottom - mTop); 7066 } 7067 7068 /** 7069 * Like {@link #getMeasuredWidthAndState()}, but only returns the 7070 * raw width component (that is the result is masked by 7071 * {@link #MEASURED_SIZE_MASK}). 7072 * 7073 * @return The raw measured width of this view. 7074 */ 7075 public final int getMeasuredWidth() { 7076 return mMeasuredWidth & MEASURED_SIZE_MASK; 7077 } 7078 7079 /** 7080 * Return the full width measurement information for this view as computed 7081 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 7082 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 7083 * This should be used during measurement and layout calculations only. Use 7084 * {@link #getWidth()} to see how wide a view is after layout. 7085 * 7086 * @return The measured width of this view as a bit mask. 7087 */ 7088 public final int getMeasuredWidthAndState() { 7089 return mMeasuredWidth; 7090 } 7091 7092 /** 7093 * Like {@link #getMeasuredHeightAndState()}, but only returns the 7094 * raw width component (that is the result is masked by 7095 * {@link #MEASURED_SIZE_MASK}). 7096 * 7097 * @return The raw measured height of this view. 7098 */ 7099 public final int getMeasuredHeight() { 7100 return mMeasuredHeight & MEASURED_SIZE_MASK; 7101 } 7102 7103 /** 7104 * Return the full height measurement information for this view as computed 7105 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 7106 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 7107 * This should be used during measurement and layout calculations only. Use 7108 * {@link #getHeight()} to see how wide a view is after layout. 7109 * 7110 * @return The measured width of this view as a bit mask. 7111 */ 7112 public final int getMeasuredHeightAndState() { 7113 return mMeasuredHeight; 7114 } 7115 7116 /** 7117 * Return only the state bits of {@link #getMeasuredWidthAndState()} 7118 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 7119 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 7120 * and the height component is at the shifted bits 7121 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 7122 */ 7123 public final int getMeasuredState() { 7124 return (mMeasuredWidth&MEASURED_STATE_MASK) 7125 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 7126 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 7127 } 7128 7129 /** 7130 * The transform matrix of this view, which is calculated based on the current 7131 * roation, scale, and pivot properties. 7132 * 7133 * @see #getRotation() 7134 * @see #getScaleX() 7135 * @see #getScaleY() 7136 * @see #getPivotX() 7137 * @see #getPivotY() 7138 * @return The current transform matrix for the view 7139 */ 7140 public Matrix getMatrix() { 7141 if (mTransformationInfo != null) { 7142 updateMatrix(); 7143 return mTransformationInfo.mMatrix; 7144 } 7145 return Matrix.IDENTITY_MATRIX; 7146 } 7147 7148 /** 7149 * Utility function to determine if the value is far enough away from zero to be 7150 * considered non-zero. 7151 * @param value A floating point value to check for zero-ness 7152 * @return whether the passed-in value is far enough away from zero to be considered non-zero 7153 */ 7154 private static boolean nonzero(float value) { 7155 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 7156 } 7157 7158 /** 7159 * Returns true if the transform matrix is the identity matrix. 7160 * Recomputes the matrix if necessary. 7161 * 7162 * @return True if the transform matrix is the identity matrix, false otherwise. 7163 */ 7164 final boolean hasIdentityMatrix() { 7165 if (mTransformationInfo != null) { 7166 updateMatrix(); 7167 return mTransformationInfo.mMatrixIsIdentity; 7168 } 7169 return true; 7170 } 7171 7172 void ensureTransformationInfo() { 7173 if (mTransformationInfo == null) { 7174 mTransformationInfo = new TransformationInfo(); 7175 } 7176 } 7177 7178 /** 7179 * Recomputes the transform matrix if necessary. 7180 */ 7181 private void updateMatrix() { 7182 final TransformationInfo info = mTransformationInfo; 7183 if (info == null) { 7184 return; 7185 } 7186 if (info.mMatrixDirty) { 7187 // transform-related properties have changed since the last time someone 7188 // asked for the matrix; recalculate it with the current values 7189 7190 // Figure out if we need to update the pivot point 7191 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7192 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 7193 info.mPrevWidth = mRight - mLeft; 7194 info.mPrevHeight = mBottom - mTop; 7195 info.mPivotX = info.mPrevWidth / 2f; 7196 info.mPivotY = info.mPrevHeight / 2f; 7197 } 7198 } 7199 info.mMatrix.reset(); 7200 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 7201 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 7202 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 7203 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 7204 } else { 7205 if (info.mCamera == null) { 7206 info.mCamera = new Camera(); 7207 info.matrix3D = new Matrix(); 7208 } 7209 info.mCamera.save(); 7210 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 7211 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 7212 info.mCamera.getMatrix(info.matrix3D); 7213 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 7214 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 7215 info.mPivotY + info.mTranslationY); 7216 info.mMatrix.postConcat(info.matrix3D); 7217 info.mCamera.restore(); 7218 } 7219 info.mMatrixDirty = false; 7220 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 7221 info.mInverseMatrixDirty = true; 7222 } 7223 } 7224 7225 /** 7226 * Utility method to retrieve the inverse of the current mMatrix property. 7227 * We cache the matrix to avoid recalculating it when transform properties 7228 * have not changed. 7229 * 7230 * @return The inverse of the current matrix of this view. 7231 */ 7232 final Matrix getInverseMatrix() { 7233 final TransformationInfo info = mTransformationInfo; 7234 if (info != null) { 7235 updateMatrix(); 7236 if (info.mInverseMatrixDirty) { 7237 if (info.mInverseMatrix == null) { 7238 info.mInverseMatrix = new Matrix(); 7239 } 7240 info.mMatrix.invert(info.mInverseMatrix); 7241 info.mInverseMatrixDirty = false; 7242 } 7243 return info.mInverseMatrix; 7244 } 7245 return Matrix.IDENTITY_MATRIX; 7246 } 7247 7248 /** 7249 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 7250 * views are drawn) from the camera to this view. The camera's distance 7251 * affects 3D transformations, for instance rotations around the X and Y 7252 * axis. If the rotationX or rotationY properties are changed and this view is 7253 * large (more than half the size of the screen), it is recommended to always 7254 * use a camera distance that's greater than the height (X axis rotation) or 7255 * the width (Y axis rotation) of this view.</p> 7256 * 7257 * <p>The distance of the camera from the view plane can have an affect on the 7258 * perspective distortion of the view when it is rotated around the x or y axis. 7259 * For example, a large distance will result in a large viewing angle, and there 7260 * will not be much perspective distortion of the view as it rotates. A short 7261 * distance may cause much more perspective distortion upon rotation, and can 7262 * also result in some drawing artifacts if the rotated view ends up partially 7263 * behind the camera (which is why the recommendation is to use a distance at 7264 * least as far as the size of the view, if the view is to be rotated.)</p> 7265 * 7266 * <p>The distance is expressed in "depth pixels." The default distance depends 7267 * on the screen density. For instance, on a medium density display, the 7268 * default distance is 1280. On a high density display, the default distance 7269 * is 1920.</p> 7270 * 7271 * <p>If you want to specify a distance that leads to visually consistent 7272 * results across various densities, use the following formula:</p> 7273 * <pre> 7274 * float scale = context.getResources().getDisplayMetrics().density; 7275 * view.setCameraDistance(distance * scale); 7276 * </pre> 7277 * 7278 * <p>The density scale factor of a high density display is 1.5, 7279 * and 1920 = 1280 * 1.5.</p> 7280 * 7281 * @param distance The distance in "depth pixels", if negative the opposite 7282 * value is used 7283 * 7284 * @see #setRotationX(float) 7285 * @see #setRotationY(float) 7286 */ 7287 public void setCameraDistance(float distance) { 7288 invalidateParentCaches(); 7289 invalidate(false); 7290 7291 ensureTransformationInfo(); 7292 final float dpi = mResources.getDisplayMetrics().densityDpi; 7293 final TransformationInfo info = mTransformationInfo; 7294 if (info.mCamera == null) { 7295 info.mCamera = new Camera(); 7296 info.matrix3D = new Matrix(); 7297 } 7298 7299 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 7300 info.mMatrixDirty = true; 7301 7302 invalidate(false); 7303 } 7304 7305 /** 7306 * The degrees that the view is rotated around the pivot point. 7307 * 7308 * @see #setRotation(float) 7309 * @see #getPivotX() 7310 * @see #getPivotY() 7311 * 7312 * @return The degrees of rotation. 7313 */ 7314 @ViewDebug.ExportedProperty(category = "drawing") 7315 public float getRotation() { 7316 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 7317 } 7318 7319 /** 7320 * Sets the degrees that the view is rotated around the pivot point. Increasing values 7321 * result in clockwise rotation. 7322 * 7323 * @param rotation The degrees of rotation. 7324 * 7325 * @see #getRotation() 7326 * @see #getPivotX() 7327 * @see #getPivotY() 7328 * @see #setRotationX(float) 7329 * @see #setRotationY(float) 7330 * 7331 * @attr ref android.R.styleable#View_rotation 7332 */ 7333 public void setRotation(float rotation) { 7334 ensureTransformationInfo(); 7335 final TransformationInfo info = mTransformationInfo; 7336 if (info.mRotation != rotation) { 7337 invalidateParentCaches(); 7338 // Double-invalidation is necessary to capture view's old and new areas 7339 invalidate(false); 7340 info.mRotation = rotation; 7341 info.mMatrixDirty = true; 7342 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7343 invalidate(false); 7344 } 7345 } 7346 7347 /** 7348 * The degrees that the view is rotated around the vertical axis through the pivot point. 7349 * 7350 * @see #getPivotX() 7351 * @see #getPivotY() 7352 * @see #setRotationY(float) 7353 * 7354 * @return The degrees of Y rotation. 7355 */ 7356 @ViewDebug.ExportedProperty(category = "drawing") 7357 public float getRotationY() { 7358 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 7359 } 7360 7361 /** 7362 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 7363 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 7364 * down the y axis. 7365 * 7366 * When rotating large views, it is recommended to adjust the camera distance 7367 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 7368 * 7369 * @param rotationY The degrees of Y rotation. 7370 * 7371 * @see #getRotationY() 7372 * @see #getPivotX() 7373 * @see #getPivotY() 7374 * @see #setRotation(float) 7375 * @see #setRotationX(float) 7376 * @see #setCameraDistance(float) 7377 * 7378 * @attr ref android.R.styleable#View_rotationY 7379 */ 7380 public void setRotationY(float rotationY) { 7381 ensureTransformationInfo(); 7382 final TransformationInfo info = mTransformationInfo; 7383 if (info.mRotationY != rotationY) { 7384 invalidateParentCaches(); 7385 // Double-invalidation is necessary to capture view's old and new areas 7386 invalidate(false); 7387 info.mRotationY = rotationY; 7388 info.mMatrixDirty = true; 7389 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7390 invalidate(false); 7391 } 7392 } 7393 7394 /** 7395 * The degrees that the view is rotated around the horizontal axis through the pivot point. 7396 * 7397 * @see #getPivotX() 7398 * @see #getPivotY() 7399 * @see #setRotationX(float) 7400 * 7401 * @return The degrees of X rotation. 7402 */ 7403 @ViewDebug.ExportedProperty(category = "drawing") 7404 public float getRotationX() { 7405 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 7406 } 7407 7408 /** 7409 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 7410 * Increasing values result in clockwise rotation from the viewpoint of looking down the 7411 * x axis. 7412 * 7413 * When rotating large views, it is recommended to adjust the camera distance 7414 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 7415 * 7416 * @param rotationX The degrees of X rotation. 7417 * 7418 * @see #getRotationX() 7419 * @see #getPivotX() 7420 * @see #getPivotY() 7421 * @see #setRotation(float) 7422 * @see #setRotationY(float) 7423 * @see #setCameraDistance(float) 7424 * 7425 * @attr ref android.R.styleable#View_rotationX 7426 */ 7427 public void setRotationX(float rotationX) { 7428 ensureTransformationInfo(); 7429 final TransformationInfo info = mTransformationInfo; 7430 if (info.mRotationX != rotationX) { 7431 invalidateParentCaches(); 7432 // Double-invalidation is necessary to capture view's old and new areas 7433 invalidate(false); 7434 info.mRotationX = rotationX; 7435 info.mMatrixDirty = true; 7436 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7437 invalidate(false); 7438 } 7439 } 7440 7441 /** 7442 * The amount that the view is scaled in x around the pivot point, as a proportion of 7443 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 7444 * 7445 * <p>By default, this is 1.0f. 7446 * 7447 * @see #getPivotX() 7448 * @see #getPivotY() 7449 * @return The scaling factor. 7450 */ 7451 @ViewDebug.ExportedProperty(category = "drawing") 7452 public float getScaleX() { 7453 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 7454 } 7455 7456 /** 7457 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 7458 * the view's unscaled width. A value of 1 means that no scaling is applied. 7459 * 7460 * @param scaleX The scaling factor. 7461 * @see #getPivotX() 7462 * @see #getPivotY() 7463 * 7464 * @attr ref android.R.styleable#View_scaleX 7465 */ 7466 public void setScaleX(float scaleX) { 7467 ensureTransformationInfo(); 7468 final TransformationInfo info = mTransformationInfo; 7469 if (info.mScaleX != scaleX) { 7470 invalidateParentCaches(); 7471 // Double-invalidation is necessary to capture view's old and new areas 7472 invalidate(false); 7473 info.mScaleX = scaleX; 7474 info.mMatrixDirty = true; 7475 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7476 invalidate(false); 7477 } 7478 } 7479 7480 /** 7481 * The amount that the view is scaled in y around the pivot point, as a proportion of 7482 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 7483 * 7484 * <p>By default, this is 1.0f. 7485 * 7486 * @see #getPivotX() 7487 * @see #getPivotY() 7488 * @return The scaling factor. 7489 */ 7490 @ViewDebug.ExportedProperty(category = "drawing") 7491 public float getScaleY() { 7492 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 7493 } 7494 7495 /** 7496 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 7497 * the view's unscaled width. A value of 1 means that no scaling is applied. 7498 * 7499 * @param scaleY The scaling factor. 7500 * @see #getPivotX() 7501 * @see #getPivotY() 7502 * 7503 * @attr ref android.R.styleable#View_scaleY 7504 */ 7505 public void setScaleY(float scaleY) { 7506 ensureTransformationInfo(); 7507 final TransformationInfo info = mTransformationInfo; 7508 if (info.mScaleY != scaleY) { 7509 invalidateParentCaches(); 7510 // Double-invalidation is necessary to capture view's old and new areas 7511 invalidate(false); 7512 info.mScaleY = scaleY; 7513 info.mMatrixDirty = true; 7514 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7515 invalidate(false); 7516 } 7517 } 7518 7519 /** 7520 * The x location of the point around which the view is {@link #setRotation(float) rotated} 7521 * and {@link #setScaleX(float) scaled}. 7522 * 7523 * @see #getRotation() 7524 * @see #getScaleX() 7525 * @see #getScaleY() 7526 * @see #getPivotY() 7527 * @return The x location of the pivot point. 7528 */ 7529 @ViewDebug.ExportedProperty(category = "drawing") 7530 public float getPivotX() { 7531 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 7532 } 7533 7534 /** 7535 * Sets the x location of the point around which the view is 7536 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 7537 * By default, the pivot point is centered on the object. 7538 * Setting this property disables this behavior and causes the view to use only the 7539 * explicitly set pivotX and pivotY values. 7540 * 7541 * @param pivotX The x location of the pivot point. 7542 * @see #getRotation() 7543 * @see #getScaleX() 7544 * @see #getScaleY() 7545 * @see #getPivotY() 7546 * 7547 * @attr ref android.R.styleable#View_transformPivotX 7548 */ 7549 public void setPivotX(float pivotX) { 7550 ensureTransformationInfo(); 7551 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7552 final TransformationInfo info = mTransformationInfo; 7553 if (info.mPivotX != pivotX) { 7554 invalidateParentCaches(); 7555 // Double-invalidation is necessary to capture view's old and new areas 7556 invalidate(false); 7557 info.mPivotX = pivotX; 7558 info.mMatrixDirty = true; 7559 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7560 invalidate(false); 7561 } 7562 } 7563 7564 /** 7565 * The y location of the point around which the view is {@link #setRotation(float) rotated} 7566 * and {@link #setScaleY(float) scaled}. 7567 * 7568 * @see #getRotation() 7569 * @see #getScaleX() 7570 * @see #getScaleY() 7571 * @see #getPivotY() 7572 * @return The y location of the pivot point. 7573 */ 7574 @ViewDebug.ExportedProperty(category = "drawing") 7575 public float getPivotY() { 7576 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 7577 } 7578 7579 /** 7580 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 7581 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 7582 * Setting this property disables this behavior and causes the view to use only the 7583 * explicitly set pivotX and pivotY values. 7584 * 7585 * @param pivotY The y location of the pivot point. 7586 * @see #getRotation() 7587 * @see #getScaleX() 7588 * @see #getScaleY() 7589 * @see #getPivotY() 7590 * 7591 * @attr ref android.R.styleable#View_transformPivotY 7592 */ 7593 public void setPivotY(float pivotY) { 7594 ensureTransformationInfo(); 7595 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7596 final TransformationInfo info = mTransformationInfo; 7597 if (info.mPivotY != pivotY) { 7598 invalidateParentCaches(); 7599 // Double-invalidation is necessary to capture view's old and new areas 7600 invalidate(false); 7601 info.mPivotY = pivotY; 7602 info.mMatrixDirty = true; 7603 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7604 invalidate(false); 7605 } 7606 } 7607 7608 /** 7609 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 7610 * completely transparent and 1 means the view is completely opaque. 7611 * 7612 * <p>By default this is 1.0f. 7613 * @return The opacity of the view. 7614 */ 7615 @ViewDebug.ExportedProperty(category = "drawing") 7616 public float getAlpha() { 7617 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 7618 } 7619 7620 /** 7621 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 7622 * completely transparent and 1 means the view is completely opaque.</p> 7623 * 7624 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 7625 * responsible for applying the opacity itself. Otherwise, calling this method is 7626 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 7627 * setting a hardware layer.</p> 7628 * 7629 * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have 7630 * performance implications. It is generally best to use the alpha property sparingly and 7631 * transiently, as in the case of fading animations.</p> 7632 * 7633 * @param alpha The opacity of the view. 7634 * 7635 * @see #setLayerType(int, android.graphics.Paint) 7636 * 7637 * @attr ref android.R.styleable#View_alpha 7638 */ 7639 public void setAlpha(float alpha) { 7640 ensureTransformationInfo(); 7641 if (mTransformationInfo.mAlpha != alpha) { 7642 mTransformationInfo.mAlpha = alpha; 7643 invalidateParentCaches(); 7644 if (onSetAlpha((int) (alpha * 255))) { 7645 mPrivateFlags |= ALPHA_SET; 7646 // subclass is handling alpha - don't optimize rendering cache invalidation 7647 invalidate(true); 7648 } else { 7649 mPrivateFlags &= ~ALPHA_SET; 7650 invalidate(false); 7651 } 7652 } 7653 } 7654 7655 /** 7656 * Faster version of setAlpha() which performs the same steps except there are 7657 * no calls to invalidate(). The caller of this function should perform proper invalidation 7658 * on the parent and this object. The return value indicates whether the subclass handles 7659 * alpha (the return value for onSetAlpha()). 7660 * 7661 * @param alpha The new value for the alpha property 7662 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 7663 * the new value for the alpha property is different from the old value 7664 */ 7665 boolean setAlphaNoInvalidation(float alpha) { 7666 ensureTransformationInfo(); 7667 if (mTransformationInfo.mAlpha != alpha) { 7668 mTransformationInfo.mAlpha = alpha; 7669 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 7670 if (subclassHandlesAlpha) { 7671 mPrivateFlags |= ALPHA_SET; 7672 return true; 7673 } else { 7674 mPrivateFlags &= ~ALPHA_SET; 7675 } 7676 } 7677 return false; 7678 } 7679 7680 /** 7681 * Top position of this view relative to its parent. 7682 * 7683 * @return The top of this view, in pixels. 7684 */ 7685 @ViewDebug.CapturedViewProperty 7686 public final int getTop() { 7687 return mTop; 7688 } 7689 7690 /** 7691 * Sets the top position of this view relative to its parent. This method is meant to be called 7692 * by the layout system and should not generally be called otherwise, because the property 7693 * may be changed at any time by the layout. 7694 * 7695 * @param top The top of this view, in pixels. 7696 */ 7697 public final void setTop(int top) { 7698 if (top != mTop) { 7699 updateMatrix(); 7700 final boolean matrixIsIdentity = mTransformationInfo == null 7701 || mTransformationInfo.mMatrixIsIdentity; 7702 if (matrixIsIdentity) { 7703 if (mAttachInfo != null) { 7704 int minTop; 7705 int yLoc; 7706 if (top < mTop) { 7707 minTop = top; 7708 yLoc = top - mTop; 7709 } else { 7710 minTop = mTop; 7711 yLoc = 0; 7712 } 7713 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 7714 } 7715 } else { 7716 // Double-invalidation is necessary to capture view's old and new areas 7717 invalidate(true); 7718 } 7719 7720 int width = mRight - mLeft; 7721 int oldHeight = mBottom - mTop; 7722 7723 mTop = top; 7724 7725 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7726 7727 if (!matrixIsIdentity) { 7728 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7729 // A change in dimension means an auto-centered pivot point changes, too 7730 mTransformationInfo.mMatrixDirty = true; 7731 } 7732 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7733 invalidate(true); 7734 } 7735 mBackgroundSizeChanged = true; 7736 invalidateParentIfNeeded(); 7737 } 7738 } 7739 7740 /** 7741 * Bottom position of this view relative to its parent. 7742 * 7743 * @return The bottom of this view, in pixels. 7744 */ 7745 @ViewDebug.CapturedViewProperty 7746 public final int getBottom() { 7747 return mBottom; 7748 } 7749 7750 /** 7751 * True if this view has changed since the last time being drawn. 7752 * 7753 * @return The dirty state of this view. 7754 */ 7755 public boolean isDirty() { 7756 return (mPrivateFlags & DIRTY_MASK) != 0; 7757 } 7758 7759 /** 7760 * Sets the bottom position of this view relative to its parent. This method is meant to be 7761 * called by the layout system and should not generally be called otherwise, because the 7762 * property may be changed at any time by the layout. 7763 * 7764 * @param bottom The bottom of this view, in pixels. 7765 */ 7766 public final void setBottom(int bottom) { 7767 if (bottom != mBottom) { 7768 updateMatrix(); 7769 final boolean matrixIsIdentity = mTransformationInfo == null 7770 || mTransformationInfo.mMatrixIsIdentity; 7771 if (matrixIsIdentity) { 7772 if (mAttachInfo != null) { 7773 int maxBottom; 7774 if (bottom < mBottom) { 7775 maxBottom = mBottom; 7776 } else { 7777 maxBottom = bottom; 7778 } 7779 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 7780 } 7781 } else { 7782 // Double-invalidation is necessary to capture view's old and new areas 7783 invalidate(true); 7784 } 7785 7786 int width = mRight - mLeft; 7787 int oldHeight = mBottom - mTop; 7788 7789 mBottom = bottom; 7790 7791 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7792 7793 if (!matrixIsIdentity) { 7794 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7795 // A change in dimension means an auto-centered pivot point changes, too 7796 mTransformationInfo.mMatrixDirty = true; 7797 } 7798 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7799 invalidate(true); 7800 } 7801 mBackgroundSizeChanged = true; 7802 invalidateParentIfNeeded(); 7803 } 7804 } 7805 7806 /** 7807 * Left position of this view relative to its parent. 7808 * 7809 * @return The left edge of this view, in pixels. 7810 */ 7811 @ViewDebug.CapturedViewProperty 7812 public final int getLeft() { 7813 return mLeft; 7814 } 7815 7816 /** 7817 * Sets the left position of this view relative to its parent. This method is meant to be called 7818 * by the layout system and should not generally be called otherwise, because the property 7819 * may be changed at any time by the layout. 7820 * 7821 * @param left The bottom of this view, in pixels. 7822 */ 7823 public final void setLeft(int left) { 7824 if (left != mLeft) { 7825 updateMatrix(); 7826 final boolean matrixIsIdentity = mTransformationInfo == null 7827 || mTransformationInfo.mMatrixIsIdentity; 7828 if (matrixIsIdentity) { 7829 if (mAttachInfo != null) { 7830 int minLeft; 7831 int xLoc; 7832 if (left < mLeft) { 7833 minLeft = left; 7834 xLoc = left - mLeft; 7835 } else { 7836 minLeft = mLeft; 7837 xLoc = 0; 7838 } 7839 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 7840 } 7841 } else { 7842 // Double-invalidation is necessary to capture view's old and new areas 7843 invalidate(true); 7844 } 7845 7846 int oldWidth = mRight - mLeft; 7847 int height = mBottom - mTop; 7848 7849 mLeft = left; 7850 7851 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7852 7853 if (!matrixIsIdentity) { 7854 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7855 // A change in dimension means an auto-centered pivot point changes, too 7856 mTransformationInfo.mMatrixDirty = true; 7857 } 7858 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7859 invalidate(true); 7860 } 7861 mBackgroundSizeChanged = true; 7862 invalidateParentIfNeeded(); 7863 } 7864 } 7865 7866 /** 7867 * Right position of this view relative to its parent. 7868 * 7869 * @return The right edge of this view, in pixels. 7870 */ 7871 @ViewDebug.CapturedViewProperty 7872 public final int getRight() { 7873 return mRight; 7874 } 7875 7876 /** 7877 * Sets the right position of this view relative to its parent. This method is meant to be called 7878 * by the layout system and should not generally be called otherwise, because the property 7879 * may be changed at any time by the layout. 7880 * 7881 * @param right The bottom of this view, in pixels. 7882 */ 7883 public final void setRight(int right) { 7884 if (right != mRight) { 7885 updateMatrix(); 7886 final boolean matrixIsIdentity = mTransformationInfo == null 7887 || mTransformationInfo.mMatrixIsIdentity; 7888 if (matrixIsIdentity) { 7889 if (mAttachInfo != null) { 7890 int maxRight; 7891 if (right < mRight) { 7892 maxRight = mRight; 7893 } else { 7894 maxRight = right; 7895 } 7896 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 7897 } 7898 } else { 7899 // Double-invalidation is necessary to capture view's old and new areas 7900 invalidate(true); 7901 } 7902 7903 int oldWidth = mRight - mLeft; 7904 int height = mBottom - mTop; 7905 7906 mRight = right; 7907 7908 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7909 7910 if (!matrixIsIdentity) { 7911 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7912 // A change in dimension means an auto-centered pivot point changes, too 7913 mTransformationInfo.mMatrixDirty = true; 7914 } 7915 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7916 invalidate(true); 7917 } 7918 mBackgroundSizeChanged = true; 7919 invalidateParentIfNeeded(); 7920 } 7921 } 7922 7923 /** 7924 * The visual x position of this view, in pixels. This is equivalent to the 7925 * {@link #setTranslationX(float) translationX} property plus the current 7926 * {@link #getLeft() left} property. 7927 * 7928 * @return The visual x position of this view, in pixels. 7929 */ 7930 @ViewDebug.ExportedProperty(category = "drawing") 7931 public float getX() { 7932 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 7933 } 7934 7935 /** 7936 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 7937 * {@link #setTranslationX(float) translationX} property to be the difference between 7938 * the x value passed in and the current {@link #getLeft() left} property. 7939 * 7940 * @param x The visual x position of this view, in pixels. 7941 */ 7942 public void setX(float x) { 7943 setTranslationX(x - mLeft); 7944 } 7945 7946 /** 7947 * The visual y position of this view, in pixels. This is equivalent to the 7948 * {@link #setTranslationY(float) translationY} property plus the current 7949 * {@link #getTop() top} property. 7950 * 7951 * @return The visual y position of this view, in pixels. 7952 */ 7953 @ViewDebug.ExportedProperty(category = "drawing") 7954 public float getY() { 7955 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 7956 } 7957 7958 /** 7959 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 7960 * {@link #setTranslationY(float) translationY} property to be the difference between 7961 * the y value passed in and the current {@link #getTop() top} property. 7962 * 7963 * @param y The visual y position of this view, in pixels. 7964 */ 7965 public void setY(float y) { 7966 setTranslationY(y - mTop); 7967 } 7968 7969 7970 /** 7971 * The horizontal location of this view relative to its {@link #getLeft() left} position. 7972 * This position is post-layout, in addition to wherever the object's 7973 * layout placed it. 7974 * 7975 * @return The horizontal position of this view relative to its left position, in pixels. 7976 */ 7977 @ViewDebug.ExportedProperty(category = "drawing") 7978 public float getTranslationX() { 7979 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 7980 } 7981 7982 /** 7983 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 7984 * This effectively positions the object post-layout, in addition to wherever the object's 7985 * layout placed it. 7986 * 7987 * @param translationX The horizontal position of this view relative to its left position, 7988 * in pixels. 7989 * 7990 * @attr ref android.R.styleable#View_translationX 7991 */ 7992 public void setTranslationX(float translationX) { 7993 ensureTransformationInfo(); 7994 final TransformationInfo info = mTransformationInfo; 7995 if (info.mTranslationX != translationX) { 7996 invalidateParentCaches(); 7997 // Double-invalidation is necessary to capture view's old and new areas 7998 invalidate(false); 7999 info.mTranslationX = translationX; 8000 info.mMatrixDirty = true; 8001 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8002 invalidate(false); 8003 } 8004 } 8005 8006 /** 8007 * The horizontal location of this view relative to its {@link #getTop() top} position. 8008 * This position is post-layout, in addition to wherever the object's 8009 * layout placed it. 8010 * 8011 * @return The vertical position of this view relative to its top position, 8012 * in pixels. 8013 */ 8014 @ViewDebug.ExportedProperty(category = "drawing") 8015 public float getTranslationY() { 8016 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 8017 } 8018 8019 /** 8020 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 8021 * This effectively positions the object post-layout, in addition to wherever the object's 8022 * layout placed it. 8023 * 8024 * @param translationY The vertical position of this view relative to its top position, 8025 * in pixels. 8026 * 8027 * @attr ref android.R.styleable#View_translationY 8028 */ 8029 public void setTranslationY(float translationY) { 8030 ensureTransformationInfo(); 8031 final TransformationInfo info = mTransformationInfo; 8032 if (info.mTranslationY != translationY) { 8033 invalidateParentCaches(); 8034 // Double-invalidation is necessary to capture view's old and new areas 8035 invalidate(false); 8036 info.mTranslationY = translationY; 8037 info.mMatrixDirty = true; 8038 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8039 invalidate(false); 8040 } 8041 } 8042 8043 /** 8044 * Hit rectangle in parent's coordinates 8045 * 8046 * @param outRect The hit rectangle of the view. 8047 */ 8048 public void getHitRect(Rect outRect) { 8049 updateMatrix(); 8050 final TransformationInfo info = mTransformationInfo; 8051 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 8052 outRect.set(mLeft, mTop, mRight, mBottom); 8053 } else { 8054 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 8055 tmpRect.set(-info.mPivotX, -info.mPivotY, 8056 getWidth() - info.mPivotX, getHeight() - info.mPivotY); 8057 info.mMatrix.mapRect(tmpRect); 8058 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 8059 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 8060 } 8061 } 8062 8063 /** 8064 * Determines whether the given point, in local coordinates is inside the view. 8065 */ 8066 /*package*/ final boolean pointInView(float localX, float localY) { 8067 return localX >= 0 && localX < (mRight - mLeft) 8068 && localY >= 0 && localY < (mBottom - mTop); 8069 } 8070 8071 /** 8072 * Utility method to determine whether the given point, in local coordinates, 8073 * is inside the view, where the area of the view is expanded by the slop factor. 8074 * This method is called while processing touch-move events to determine if the event 8075 * is still within the view. 8076 */ 8077 private boolean pointInView(float localX, float localY, float slop) { 8078 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 8079 localY < ((mBottom - mTop) + slop); 8080 } 8081 8082 /** 8083 * When a view has focus and the user navigates away from it, the next view is searched for 8084 * starting from the rectangle filled in by this method. 8085 * 8086 * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)}) 8087 * of the view. However, if your view maintains some idea of internal selection, 8088 * such as a cursor, or a selected row or column, you should override this method and 8089 * fill in a more specific rectangle. 8090 * 8091 * @param r The rectangle to fill in, in this view's coordinates. 8092 */ 8093 public void getFocusedRect(Rect r) { 8094 getDrawingRect(r); 8095 } 8096 8097 /** 8098 * If some part of this view is not clipped by any of its parents, then 8099 * return that area in r in global (root) coordinates. To convert r to local 8100 * coordinates (without taking possible View rotations into account), offset 8101 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 8102 * If the view is completely clipped or translated out, return false. 8103 * 8104 * @param r If true is returned, r holds the global coordinates of the 8105 * visible portion of this view. 8106 * @param globalOffset If true is returned, globalOffset holds the dx,dy 8107 * between this view and its root. globalOffet may be null. 8108 * @return true if r is non-empty (i.e. part of the view is visible at the 8109 * root level. 8110 */ 8111 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 8112 int width = mRight - mLeft; 8113 int height = mBottom - mTop; 8114 if (width > 0 && height > 0) { 8115 r.set(0, 0, width, height); 8116 if (globalOffset != null) { 8117 globalOffset.set(-mScrollX, -mScrollY); 8118 } 8119 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 8120 } 8121 return false; 8122 } 8123 8124 public final boolean getGlobalVisibleRect(Rect r) { 8125 return getGlobalVisibleRect(r, null); 8126 } 8127 8128 public final boolean getLocalVisibleRect(Rect r) { 8129 Point offset = new Point(); 8130 if (getGlobalVisibleRect(r, offset)) { 8131 r.offset(-offset.x, -offset.y); // make r local 8132 return true; 8133 } 8134 return false; 8135 } 8136 8137 /** 8138 * Offset this view's vertical location by the specified number of pixels. 8139 * 8140 * @param offset the number of pixels to offset the view by 8141 */ 8142 public void offsetTopAndBottom(int offset) { 8143 if (offset != 0) { 8144 updateMatrix(); 8145 final boolean matrixIsIdentity = mTransformationInfo == null 8146 || mTransformationInfo.mMatrixIsIdentity; 8147 if (matrixIsIdentity) { 8148 final ViewParent p = mParent; 8149 if (p != null && mAttachInfo != null) { 8150 final Rect r = mAttachInfo.mTmpInvalRect; 8151 int minTop; 8152 int maxBottom; 8153 int yLoc; 8154 if (offset < 0) { 8155 minTop = mTop + offset; 8156 maxBottom = mBottom; 8157 yLoc = offset; 8158 } else { 8159 minTop = mTop; 8160 maxBottom = mBottom + offset; 8161 yLoc = 0; 8162 } 8163 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 8164 p.invalidateChild(this, r); 8165 } 8166 } else { 8167 invalidate(false); 8168 } 8169 8170 mTop += offset; 8171 mBottom += offset; 8172 8173 if (!matrixIsIdentity) { 8174 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8175 invalidate(false); 8176 } 8177 invalidateParentIfNeeded(); 8178 } 8179 } 8180 8181 /** 8182 * Offset this view's horizontal location by the specified amount of pixels. 8183 * 8184 * @param offset the numer of pixels to offset the view by 8185 */ 8186 public void offsetLeftAndRight(int offset) { 8187 if (offset != 0) { 8188 updateMatrix(); 8189 final boolean matrixIsIdentity = mTransformationInfo == null 8190 || mTransformationInfo.mMatrixIsIdentity; 8191 if (matrixIsIdentity) { 8192 final ViewParent p = mParent; 8193 if (p != null && mAttachInfo != null) { 8194 final Rect r = mAttachInfo.mTmpInvalRect; 8195 int minLeft; 8196 int maxRight; 8197 if (offset < 0) { 8198 minLeft = mLeft + offset; 8199 maxRight = mRight; 8200 } else { 8201 minLeft = mLeft; 8202 maxRight = mRight + offset; 8203 } 8204 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 8205 p.invalidateChild(this, r); 8206 } 8207 } else { 8208 invalidate(false); 8209 } 8210 8211 mLeft += offset; 8212 mRight += offset; 8213 8214 if (!matrixIsIdentity) { 8215 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8216 invalidate(false); 8217 } 8218 invalidateParentIfNeeded(); 8219 } 8220 } 8221 8222 /** 8223 * Get the LayoutParams associated with this view. All views should have 8224 * layout parameters. These supply parameters to the <i>parent</i> of this 8225 * view specifying how it should be arranged. There are many subclasses of 8226 * ViewGroup.LayoutParams, and these correspond to the different subclasses 8227 * of ViewGroup that are responsible for arranging their children. 8228 * 8229 * This method may return null if this View is not attached to a parent 8230 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 8231 * was not invoked successfully. When a View is attached to a parent 8232 * ViewGroup, this method must not return null. 8233 * 8234 * @return The LayoutParams associated with this view, or null if no 8235 * parameters have been set yet 8236 */ 8237 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 8238 public ViewGroup.LayoutParams getLayoutParams() { 8239 return mLayoutParams; 8240 } 8241 8242 /** 8243 * Set the layout parameters associated with this view. These supply 8244 * parameters to the <i>parent</i> of this view specifying how it should be 8245 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 8246 * correspond to the different subclasses of ViewGroup that are responsible 8247 * for arranging their children. 8248 * 8249 * @param params The layout parameters for this view, cannot be null 8250 */ 8251 public void setLayoutParams(ViewGroup.LayoutParams params) { 8252 if (params == null) { 8253 throw new NullPointerException("Layout parameters cannot be null"); 8254 } 8255 mLayoutParams = params; 8256 if (mParent instanceof ViewGroup) { 8257 ((ViewGroup) mParent).onSetLayoutParams(this, params); 8258 } 8259 requestLayout(); 8260 } 8261 8262 /** 8263 * Set the scrolled position of your view. This will cause a call to 8264 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8265 * invalidated. 8266 * @param x the x position to scroll to 8267 * @param y the y position to scroll to 8268 */ 8269 public void scrollTo(int x, int y) { 8270 if (mScrollX != x || mScrollY != y) { 8271 int oldX = mScrollX; 8272 int oldY = mScrollY; 8273 mScrollX = x; 8274 mScrollY = y; 8275 invalidateParentCaches(); 8276 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 8277 if (!awakenScrollBars()) { 8278 invalidate(true); 8279 } 8280 } 8281 } 8282 8283 /** 8284 * Move the scrolled position of your view. This will cause a call to 8285 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8286 * invalidated. 8287 * @param x the amount of pixels to scroll by horizontally 8288 * @param y the amount of pixels to scroll by vertically 8289 */ 8290 public void scrollBy(int x, int y) { 8291 scrollTo(mScrollX + x, mScrollY + y); 8292 } 8293 8294 /** 8295 * <p>Trigger the scrollbars to draw. When invoked this method starts an 8296 * animation to fade the scrollbars out after a default delay. If a subclass 8297 * provides animated scrolling, the start delay should equal the duration 8298 * of the scrolling animation.</p> 8299 * 8300 * <p>The animation starts only if at least one of the scrollbars is 8301 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 8302 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8303 * this method returns true, and false otherwise. If the animation is 8304 * started, this method calls {@link #invalidate()}; in that case the 8305 * caller should not call {@link #invalidate()}.</p> 8306 * 8307 * <p>This method should be invoked every time a subclass directly updates 8308 * the scroll parameters.</p> 8309 * 8310 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 8311 * and {@link #scrollTo(int, int)}.</p> 8312 * 8313 * @return true if the animation is played, false otherwise 8314 * 8315 * @see #awakenScrollBars(int) 8316 * @see #scrollBy(int, int) 8317 * @see #scrollTo(int, int) 8318 * @see #isHorizontalScrollBarEnabled() 8319 * @see #isVerticalScrollBarEnabled() 8320 * @see #setHorizontalScrollBarEnabled(boolean) 8321 * @see #setVerticalScrollBarEnabled(boolean) 8322 */ 8323 protected boolean awakenScrollBars() { 8324 return mScrollCache != null && 8325 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 8326 } 8327 8328 /** 8329 * Trigger the scrollbars to draw. 8330 * This method differs from awakenScrollBars() only in its default duration. 8331 * initialAwakenScrollBars() will show the scroll bars for longer than 8332 * usual to give the user more of a chance to notice them. 8333 * 8334 * @return true if the animation is played, false otherwise. 8335 */ 8336 private boolean initialAwakenScrollBars() { 8337 return mScrollCache != null && 8338 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 8339 } 8340 8341 /** 8342 * <p> 8343 * Trigger the scrollbars to draw. When invoked this method starts an 8344 * animation to fade the scrollbars out after a fixed delay. If a subclass 8345 * provides animated scrolling, the start delay should equal the duration of 8346 * the scrolling animation. 8347 * </p> 8348 * 8349 * <p> 8350 * The animation starts only if at least one of the scrollbars is enabled, 8351 * as specified by {@link #isHorizontalScrollBarEnabled()} and 8352 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8353 * this method returns true, and false otherwise. If the animation is 8354 * started, this method calls {@link #invalidate()}; in that case the caller 8355 * should not call {@link #invalidate()}. 8356 * </p> 8357 * 8358 * <p> 8359 * This method should be invoked everytime a subclass directly updates the 8360 * scroll parameters. 8361 * </p> 8362 * 8363 * @param startDelay the delay, in milliseconds, after which the animation 8364 * should start; when the delay is 0, the animation starts 8365 * immediately 8366 * @return true if the animation is played, false otherwise 8367 * 8368 * @see #scrollBy(int, int) 8369 * @see #scrollTo(int, int) 8370 * @see #isHorizontalScrollBarEnabled() 8371 * @see #isVerticalScrollBarEnabled() 8372 * @see #setHorizontalScrollBarEnabled(boolean) 8373 * @see #setVerticalScrollBarEnabled(boolean) 8374 */ 8375 protected boolean awakenScrollBars(int startDelay) { 8376 return awakenScrollBars(startDelay, true); 8377 } 8378 8379 /** 8380 * <p> 8381 * Trigger the scrollbars to draw. When invoked this method starts an 8382 * animation to fade the scrollbars out after a fixed delay. If a subclass 8383 * provides animated scrolling, the start delay should equal the duration of 8384 * the scrolling animation. 8385 * </p> 8386 * 8387 * <p> 8388 * The animation starts only if at least one of the scrollbars is enabled, 8389 * as specified by {@link #isHorizontalScrollBarEnabled()} and 8390 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8391 * this method returns true, and false otherwise. If the animation is 8392 * started, this method calls {@link #invalidate()} if the invalidate parameter 8393 * is set to true; in that case the caller 8394 * should not call {@link #invalidate()}. 8395 * </p> 8396 * 8397 * <p> 8398 * This method should be invoked everytime a subclass directly updates the 8399 * scroll parameters. 8400 * </p> 8401 * 8402 * @param startDelay the delay, in milliseconds, after which the animation 8403 * should start; when the delay is 0, the animation starts 8404 * immediately 8405 * 8406 * @param invalidate Wheter this method should call invalidate 8407 * 8408 * @return true if the animation is played, false otherwise 8409 * 8410 * @see #scrollBy(int, int) 8411 * @see #scrollTo(int, int) 8412 * @see #isHorizontalScrollBarEnabled() 8413 * @see #isVerticalScrollBarEnabled() 8414 * @see #setHorizontalScrollBarEnabled(boolean) 8415 * @see #setVerticalScrollBarEnabled(boolean) 8416 */ 8417 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 8418 final ScrollabilityCache scrollCache = mScrollCache; 8419 8420 if (scrollCache == null || !scrollCache.fadeScrollBars) { 8421 return false; 8422 } 8423 8424 if (scrollCache.scrollBar == null) { 8425 scrollCache.scrollBar = new ScrollBarDrawable(); 8426 } 8427 8428 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 8429 8430 if (invalidate) { 8431 // Invalidate to show the scrollbars 8432 invalidate(true); 8433 } 8434 8435 if (scrollCache.state == ScrollabilityCache.OFF) { 8436 // FIXME: this is copied from WindowManagerService. 8437 // We should get this value from the system when it 8438 // is possible to do so. 8439 final int KEY_REPEAT_FIRST_DELAY = 750; 8440 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 8441 } 8442 8443 // Tell mScrollCache when we should start fading. This may 8444 // extend the fade start time if one was already scheduled 8445 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 8446 scrollCache.fadeStartTime = fadeStartTime; 8447 scrollCache.state = ScrollabilityCache.ON; 8448 8449 // Schedule our fader to run, unscheduling any old ones first 8450 if (mAttachInfo != null) { 8451 mAttachInfo.mHandler.removeCallbacks(scrollCache); 8452 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 8453 } 8454 8455 return true; 8456 } 8457 8458 return false; 8459 } 8460 8461 /** 8462 * Do not invalidate views which are not visible and which are not running an animation. They 8463 * will not get drawn and they should not set dirty flags as if they will be drawn 8464 */ 8465 private boolean skipInvalidate() { 8466 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 8467 (!(mParent instanceof ViewGroup) || 8468 !((ViewGroup) mParent).isViewTransitioning(this)); 8469 } 8470 /** 8471 * Mark the area defined by dirty as needing to be drawn. If the view is 8472 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 8473 * in the future. This must be called from a UI thread. To call from a non-UI 8474 * thread, call {@link #postInvalidate()}. 8475 * 8476 * WARNING: This method is destructive to dirty. 8477 * @param dirty the rectangle representing the bounds of the dirty region 8478 */ 8479 public void invalidate(Rect dirty) { 8480 if (ViewDebug.TRACE_HIERARCHY) { 8481 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8482 } 8483 8484 if (skipInvalidate()) { 8485 return; 8486 } 8487 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8488 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8489 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8490 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8491 mPrivateFlags |= INVALIDATED; 8492 mPrivateFlags |= DIRTY; 8493 final ViewParent p = mParent; 8494 final AttachInfo ai = mAttachInfo; 8495 //noinspection PointlessBooleanExpression,ConstantConditions 8496 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8497 if (p != null && ai != null && ai.mHardwareAccelerated) { 8498 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8499 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8500 p.invalidateChild(this, null); 8501 return; 8502 } 8503 } 8504 if (p != null && ai != null) { 8505 final int scrollX = mScrollX; 8506 final int scrollY = mScrollY; 8507 final Rect r = ai.mTmpInvalRect; 8508 r.set(dirty.left - scrollX, dirty.top - scrollY, 8509 dirty.right - scrollX, dirty.bottom - scrollY); 8510 mParent.invalidateChild(this, r); 8511 } 8512 } 8513 } 8514 8515 /** 8516 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 8517 * The coordinates of the dirty rect are relative to the view. 8518 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 8519 * will be called at some point in the future. This must be called from 8520 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 8521 * @param l the left position of the dirty region 8522 * @param t the top position of the dirty region 8523 * @param r the right position of the dirty region 8524 * @param b the bottom position of the dirty region 8525 */ 8526 public void invalidate(int l, int t, int r, int b) { 8527 if (ViewDebug.TRACE_HIERARCHY) { 8528 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8529 } 8530 8531 if (skipInvalidate()) { 8532 return; 8533 } 8534 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8535 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8536 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8537 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8538 mPrivateFlags |= INVALIDATED; 8539 mPrivateFlags |= DIRTY; 8540 final ViewParent p = mParent; 8541 final AttachInfo ai = mAttachInfo; 8542 //noinspection PointlessBooleanExpression,ConstantConditions 8543 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8544 if (p != null && ai != null && ai.mHardwareAccelerated) { 8545 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8546 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8547 p.invalidateChild(this, null); 8548 return; 8549 } 8550 } 8551 if (p != null && ai != null && l < r && t < b) { 8552 final int scrollX = mScrollX; 8553 final int scrollY = mScrollY; 8554 final Rect tmpr = ai.mTmpInvalRect; 8555 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 8556 p.invalidateChild(this, tmpr); 8557 } 8558 } 8559 } 8560 8561 /** 8562 * Invalidate the whole view. If the view is visible, 8563 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 8564 * the future. This must be called from a UI thread. To call from a non-UI thread, 8565 * call {@link #postInvalidate()}. 8566 */ 8567 public void invalidate() { 8568 invalidate(true); 8569 } 8570 8571 /** 8572 * This is where the invalidate() work actually happens. A full invalidate() 8573 * causes the drawing cache to be invalidated, but this function can be called with 8574 * invalidateCache set to false to skip that invalidation step for cases that do not 8575 * need it (for example, a component that remains at the same dimensions with the same 8576 * content). 8577 * 8578 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 8579 * well. This is usually true for a full invalidate, but may be set to false if the 8580 * View's contents or dimensions have not changed. 8581 */ 8582 void invalidate(boolean invalidateCache) { 8583 if (ViewDebug.TRACE_HIERARCHY) { 8584 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8585 } 8586 8587 if (skipInvalidate()) { 8588 return; 8589 } 8590 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8591 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) || 8592 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) { 8593 mLastIsOpaque = isOpaque(); 8594 mPrivateFlags &= ~DRAWN; 8595 mPrivateFlags |= DIRTY; 8596 if (invalidateCache) { 8597 mPrivateFlags |= INVALIDATED; 8598 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8599 } 8600 final AttachInfo ai = mAttachInfo; 8601 final ViewParent p = mParent; 8602 //noinspection PointlessBooleanExpression,ConstantConditions 8603 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8604 if (p != null && ai != null && ai.mHardwareAccelerated) { 8605 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8606 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8607 p.invalidateChild(this, null); 8608 return; 8609 } 8610 } 8611 8612 if (p != null && ai != null) { 8613 final Rect r = ai.mTmpInvalRect; 8614 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8615 // Don't call invalidate -- we don't want to internally scroll 8616 // our own bounds 8617 p.invalidateChild(this, r); 8618 } 8619 } 8620 } 8621 8622 /** 8623 * Used to indicate that the parent of this view should clear its caches. This functionality 8624 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8625 * which is necessary when various parent-managed properties of the view change, such as 8626 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 8627 * clears the parent caches and does not causes an invalidate event. 8628 * 8629 * @hide 8630 */ 8631 protected void invalidateParentCaches() { 8632 if (mParent instanceof View) { 8633 ((View) mParent).mPrivateFlags |= INVALIDATED; 8634 } 8635 } 8636 8637 /** 8638 * Used to indicate that the parent of this view should be invalidated. This functionality 8639 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8640 * which is necessary when various parent-managed properties of the view change, such as 8641 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 8642 * an invalidation event to the parent. 8643 * 8644 * @hide 8645 */ 8646 protected void invalidateParentIfNeeded() { 8647 if (isHardwareAccelerated() && mParent instanceof View) { 8648 ((View) mParent).invalidate(true); 8649 } 8650 } 8651 8652 /** 8653 * Indicates whether this View is opaque. An opaque View guarantees that it will 8654 * draw all the pixels overlapping its bounds using a fully opaque color. 8655 * 8656 * Subclasses of View should override this method whenever possible to indicate 8657 * whether an instance is opaque. Opaque Views are treated in a special way by 8658 * the View hierarchy, possibly allowing it to perform optimizations during 8659 * invalidate/draw passes. 8660 * 8661 * @return True if this View is guaranteed to be fully opaque, false otherwise. 8662 */ 8663 @ViewDebug.ExportedProperty(category = "drawing") 8664 public boolean isOpaque() { 8665 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK && 8666 ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1) 8667 >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD); 8668 } 8669 8670 /** 8671 * @hide 8672 */ 8673 protected void computeOpaqueFlags() { 8674 // Opaque if: 8675 // - Has a background 8676 // - Background is opaque 8677 // - Doesn't have scrollbars or scrollbars are inside overlay 8678 8679 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) { 8680 mPrivateFlags |= OPAQUE_BACKGROUND; 8681 } else { 8682 mPrivateFlags &= ~OPAQUE_BACKGROUND; 8683 } 8684 8685 final int flags = mViewFlags; 8686 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 8687 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 8688 mPrivateFlags |= OPAQUE_SCROLLBARS; 8689 } else { 8690 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 8691 } 8692 } 8693 8694 /** 8695 * @hide 8696 */ 8697 protected boolean hasOpaqueScrollbars() { 8698 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 8699 } 8700 8701 /** 8702 * @return A handler associated with the thread running the View. This 8703 * handler can be used to pump events in the UI events queue. 8704 */ 8705 public Handler getHandler() { 8706 if (mAttachInfo != null) { 8707 return mAttachInfo.mHandler; 8708 } 8709 return null; 8710 } 8711 8712 /** 8713 * <p>Causes the Runnable to be added to the message queue. 8714 * The runnable will be run on the user interface thread.</p> 8715 * 8716 * <p>This method can be invoked from outside of the UI thread 8717 * only when this View is attached to a window.</p> 8718 * 8719 * @param action The Runnable that will be executed. 8720 * 8721 * @return Returns true if the Runnable was successfully placed in to the 8722 * message queue. Returns false on failure, usually because the 8723 * looper processing the message queue is exiting. 8724 */ 8725 public boolean post(Runnable action) { 8726 Handler handler; 8727 AttachInfo attachInfo = mAttachInfo; 8728 if (attachInfo != null) { 8729 handler = attachInfo.mHandler; 8730 } else { 8731 // Assume that post will succeed later 8732 ViewRootImpl.getRunQueue().post(action); 8733 return true; 8734 } 8735 8736 return handler.post(action); 8737 } 8738 8739 /** 8740 * <p>Causes the Runnable to be added to the message queue, to be run 8741 * after the specified amount of time elapses. 8742 * The runnable will be run on the user interface thread.</p> 8743 * 8744 * <p>This method can be invoked from outside of the UI thread 8745 * only when this View is attached to a window.</p> 8746 * 8747 * @param action The Runnable that will be executed. 8748 * @param delayMillis The delay (in milliseconds) until the Runnable 8749 * will be executed. 8750 * 8751 * @return true if the Runnable was successfully placed in to the 8752 * message queue. Returns false on failure, usually because the 8753 * looper processing the message queue is exiting. Note that a 8754 * result of true does not mean the Runnable will be processed -- 8755 * if the looper is quit before the delivery time of the message 8756 * occurs then the message will be dropped. 8757 */ 8758 public boolean postDelayed(Runnable action, long delayMillis) { 8759 Handler handler; 8760 AttachInfo attachInfo = mAttachInfo; 8761 if (attachInfo != null) { 8762 handler = attachInfo.mHandler; 8763 } else { 8764 // Assume that post will succeed later 8765 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 8766 return true; 8767 } 8768 8769 return handler.postDelayed(action, delayMillis); 8770 } 8771 8772 /** 8773 * <p>Removes the specified Runnable from the message queue.</p> 8774 * 8775 * <p>This method can be invoked from outside of the UI thread 8776 * only when this View is attached to a window.</p> 8777 * 8778 * @param action The Runnable to remove from the message handling queue 8779 * 8780 * @return true if this view could ask the Handler to remove the Runnable, 8781 * false otherwise. When the returned value is true, the Runnable 8782 * may or may not have been actually removed from the message queue 8783 * (for instance, if the Runnable was not in the queue already.) 8784 */ 8785 public boolean removeCallbacks(Runnable action) { 8786 Handler handler; 8787 AttachInfo attachInfo = mAttachInfo; 8788 if (attachInfo != null) { 8789 handler = attachInfo.mHandler; 8790 } else { 8791 // Assume that post will succeed later 8792 ViewRootImpl.getRunQueue().removeCallbacks(action); 8793 return true; 8794 } 8795 8796 handler.removeCallbacks(action); 8797 return true; 8798 } 8799 8800 /** 8801 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 8802 * Use this to invalidate the View from a non-UI thread.</p> 8803 * 8804 * <p>This method can be invoked from outside of the UI thread 8805 * only when this View is attached to a window.</p> 8806 * 8807 * @see #invalidate() 8808 */ 8809 public void postInvalidate() { 8810 postInvalidateDelayed(0); 8811 } 8812 8813 /** 8814 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 8815 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 8816 * 8817 * <p>This method can be invoked from outside of the UI thread 8818 * only when this View is attached to a window.</p> 8819 * 8820 * @param left The left coordinate of the rectangle to invalidate. 8821 * @param top The top coordinate of the rectangle to invalidate. 8822 * @param right The right coordinate of the rectangle to invalidate. 8823 * @param bottom The bottom coordinate of the rectangle to invalidate. 8824 * 8825 * @see #invalidate(int, int, int, int) 8826 * @see #invalidate(Rect) 8827 */ 8828 public void postInvalidate(int left, int top, int right, int bottom) { 8829 postInvalidateDelayed(0, left, top, right, bottom); 8830 } 8831 8832 /** 8833 * <p>Cause an invalidate to happen on a subsequent cycle through the event 8834 * loop. Waits for the specified amount of time.</p> 8835 * 8836 * <p>This method can be invoked from outside of the UI thread 8837 * only when this View is attached to a window.</p> 8838 * 8839 * @param delayMilliseconds the duration in milliseconds to delay the 8840 * invalidation by 8841 */ 8842 public void postInvalidateDelayed(long delayMilliseconds) { 8843 // We try only with the AttachInfo because there's no point in invalidating 8844 // if we are not attached to our window 8845 AttachInfo attachInfo = mAttachInfo; 8846 if (attachInfo != null) { 8847 Message msg = Message.obtain(); 8848 msg.what = AttachInfo.INVALIDATE_MSG; 8849 msg.obj = this; 8850 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8851 } 8852 } 8853 8854 /** 8855 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 8856 * through the event loop. Waits for the specified amount of time.</p> 8857 * 8858 * <p>This method can be invoked from outside of the UI thread 8859 * only when this View is attached to a window.</p> 8860 * 8861 * @param delayMilliseconds the duration in milliseconds to delay the 8862 * invalidation by 8863 * @param left The left coordinate of the rectangle to invalidate. 8864 * @param top The top coordinate of the rectangle to invalidate. 8865 * @param right The right coordinate of the rectangle to invalidate. 8866 * @param bottom The bottom coordinate of the rectangle to invalidate. 8867 */ 8868 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 8869 int right, int bottom) { 8870 8871 // We try only with the AttachInfo because there's no point in invalidating 8872 // if we are not attached to our window 8873 AttachInfo attachInfo = mAttachInfo; 8874 if (attachInfo != null) { 8875 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 8876 info.target = this; 8877 info.left = left; 8878 info.top = top; 8879 info.right = right; 8880 info.bottom = bottom; 8881 8882 final Message msg = Message.obtain(); 8883 msg.what = AttachInfo.INVALIDATE_RECT_MSG; 8884 msg.obj = info; 8885 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8886 } 8887 } 8888 8889 /** 8890 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 8891 * This event is sent at most once every 8892 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 8893 */ 8894 private void postSendViewScrolledAccessibilityEventCallback() { 8895 if (mSendViewScrolledAccessibilityEvent == null) { 8896 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 8897 } 8898 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 8899 mSendViewScrolledAccessibilityEvent.mIsPending = true; 8900 postDelayed(mSendViewScrolledAccessibilityEvent, 8901 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 8902 } 8903 } 8904 8905 /** 8906 * Called by a parent to request that a child update its values for mScrollX 8907 * and mScrollY if necessary. This will typically be done if the child is 8908 * animating a scroll using a {@link android.widget.Scroller Scroller} 8909 * object. 8910 */ 8911 public void computeScroll() { 8912 } 8913 8914 /** 8915 * <p>Indicate whether the horizontal edges are faded when the view is 8916 * scrolled horizontally.</p> 8917 * 8918 * @return true if the horizontal edges should are faded on scroll, false 8919 * otherwise 8920 * 8921 * @see #setHorizontalFadingEdgeEnabled(boolean) 8922 * @attr ref android.R.styleable#View_requiresFadingEdge 8923 */ 8924 public boolean isHorizontalFadingEdgeEnabled() { 8925 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 8926 } 8927 8928 /** 8929 * <p>Define whether the horizontal edges should be faded when this view 8930 * is scrolled horizontally.</p> 8931 * 8932 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 8933 * be faded when the view is scrolled 8934 * horizontally 8935 * 8936 * @see #isHorizontalFadingEdgeEnabled() 8937 * @attr ref android.R.styleable#View_requiresFadingEdge 8938 */ 8939 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 8940 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 8941 if (horizontalFadingEdgeEnabled) { 8942 initScrollCache(); 8943 } 8944 8945 mViewFlags ^= FADING_EDGE_HORIZONTAL; 8946 } 8947 } 8948 8949 /** 8950 * <p>Indicate whether the vertical edges are faded when the view is 8951 * scrolled horizontally.</p> 8952 * 8953 * @return true if the vertical edges should are faded on scroll, false 8954 * otherwise 8955 * 8956 * @see #setVerticalFadingEdgeEnabled(boolean) 8957 * @attr ref android.R.styleable#View_requiresFadingEdge 8958 */ 8959 public boolean isVerticalFadingEdgeEnabled() { 8960 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 8961 } 8962 8963 /** 8964 * <p>Define whether the vertical edges should be faded when this view 8965 * is scrolled vertically.</p> 8966 * 8967 * @param verticalFadingEdgeEnabled true if the vertical edges should 8968 * be faded when the view is scrolled 8969 * vertically 8970 * 8971 * @see #isVerticalFadingEdgeEnabled() 8972 * @attr ref android.R.styleable#View_requiresFadingEdge 8973 */ 8974 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 8975 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 8976 if (verticalFadingEdgeEnabled) { 8977 initScrollCache(); 8978 } 8979 8980 mViewFlags ^= FADING_EDGE_VERTICAL; 8981 } 8982 } 8983 8984 /** 8985 * Returns the strength, or intensity, of the top faded edge. The strength is 8986 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8987 * returns 0.0 or 1.0 but no value in between. 8988 * 8989 * Subclasses should override this method to provide a smoother fade transition 8990 * when scrolling occurs. 8991 * 8992 * @return the intensity of the top fade as a float between 0.0f and 1.0f 8993 */ 8994 protected float getTopFadingEdgeStrength() { 8995 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 8996 } 8997 8998 /** 8999 * Returns the strength, or intensity, of the bottom faded edge. The strength is 9000 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 9001 * returns 0.0 or 1.0 but no value in between. 9002 * 9003 * Subclasses should override this method to provide a smoother fade transition 9004 * when scrolling occurs. 9005 * 9006 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 9007 */ 9008 protected float getBottomFadingEdgeStrength() { 9009 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 9010 computeVerticalScrollRange() ? 1.0f : 0.0f; 9011 } 9012 9013 /** 9014 * Returns the strength, or intensity, of the left faded edge. The strength is 9015 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 9016 * returns 0.0 or 1.0 but no value in between. 9017 * 9018 * Subclasses should override this method to provide a smoother fade transition 9019 * when scrolling occurs. 9020 * 9021 * @return the intensity of the left fade as a float between 0.0f and 1.0f 9022 */ 9023 protected float getLeftFadingEdgeStrength() { 9024 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 9025 } 9026 9027 /** 9028 * Returns the strength, or intensity, of the right faded edge. The strength is 9029 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 9030 * returns 0.0 or 1.0 but no value in between. 9031 * 9032 * Subclasses should override this method to provide a smoother fade transition 9033 * when scrolling occurs. 9034 * 9035 * @return the intensity of the right fade as a float between 0.0f and 1.0f 9036 */ 9037 protected float getRightFadingEdgeStrength() { 9038 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 9039 computeHorizontalScrollRange() ? 1.0f : 0.0f; 9040 } 9041 9042 /** 9043 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 9044 * scrollbar is not drawn by default.</p> 9045 * 9046 * @return true if the horizontal scrollbar should be painted, false 9047 * otherwise 9048 * 9049 * @see #setHorizontalScrollBarEnabled(boolean) 9050 */ 9051 public boolean isHorizontalScrollBarEnabled() { 9052 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 9053 } 9054 9055 /** 9056 * <p>Define whether the horizontal scrollbar should be drawn or not. The 9057 * scrollbar is not drawn by default.</p> 9058 * 9059 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 9060 * be painted 9061 * 9062 * @see #isHorizontalScrollBarEnabled() 9063 */ 9064 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 9065 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 9066 mViewFlags ^= SCROLLBARS_HORIZONTAL; 9067 computeOpaqueFlags(); 9068 resolvePadding(); 9069 } 9070 } 9071 9072 /** 9073 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 9074 * scrollbar is not drawn by default.</p> 9075 * 9076 * @return true if the vertical scrollbar should be painted, false 9077 * otherwise 9078 * 9079 * @see #setVerticalScrollBarEnabled(boolean) 9080 */ 9081 public boolean isVerticalScrollBarEnabled() { 9082 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 9083 } 9084 9085 /** 9086 * <p>Define whether the vertical scrollbar should be drawn or not. The 9087 * scrollbar is not drawn by default.</p> 9088 * 9089 * @param verticalScrollBarEnabled true if the vertical scrollbar should 9090 * be painted 9091 * 9092 * @see #isVerticalScrollBarEnabled() 9093 */ 9094 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 9095 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 9096 mViewFlags ^= SCROLLBARS_VERTICAL; 9097 computeOpaqueFlags(); 9098 resolvePadding(); 9099 } 9100 } 9101 9102 /** 9103 * @hide 9104 */ 9105 protected void recomputePadding() { 9106 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 9107 } 9108 9109 /** 9110 * Define whether scrollbars will fade when the view is not scrolling. 9111 * 9112 * @param fadeScrollbars wheter to enable fading 9113 * 9114 */ 9115 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 9116 initScrollCache(); 9117 final ScrollabilityCache scrollabilityCache = mScrollCache; 9118 scrollabilityCache.fadeScrollBars = fadeScrollbars; 9119 if (fadeScrollbars) { 9120 scrollabilityCache.state = ScrollabilityCache.OFF; 9121 } else { 9122 scrollabilityCache.state = ScrollabilityCache.ON; 9123 } 9124 } 9125 9126 /** 9127 * 9128 * Returns true if scrollbars will fade when this view is not scrolling 9129 * 9130 * @return true if scrollbar fading is enabled 9131 */ 9132 public boolean isScrollbarFadingEnabled() { 9133 return mScrollCache != null && mScrollCache.fadeScrollBars; 9134 } 9135 9136 /** 9137 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 9138 * inset. When inset, they add to the padding of the view. And the scrollbars 9139 * can be drawn inside the padding area or on the edge of the view. For example, 9140 * if a view has a background drawable and you want to draw the scrollbars 9141 * inside the padding specified by the drawable, you can use 9142 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 9143 * appear at the edge of the view, ignoring the padding, then you can use 9144 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 9145 * @param style the style of the scrollbars. Should be one of 9146 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 9147 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 9148 * @see #SCROLLBARS_INSIDE_OVERLAY 9149 * @see #SCROLLBARS_INSIDE_INSET 9150 * @see #SCROLLBARS_OUTSIDE_OVERLAY 9151 * @see #SCROLLBARS_OUTSIDE_INSET 9152 */ 9153 public void setScrollBarStyle(int style) { 9154 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 9155 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 9156 computeOpaqueFlags(); 9157 resolvePadding(); 9158 } 9159 } 9160 9161 /** 9162 * <p>Returns the current scrollbar style.</p> 9163 * @return the current scrollbar style 9164 * @see #SCROLLBARS_INSIDE_OVERLAY 9165 * @see #SCROLLBARS_INSIDE_INSET 9166 * @see #SCROLLBARS_OUTSIDE_OVERLAY 9167 * @see #SCROLLBARS_OUTSIDE_INSET 9168 */ 9169 @ViewDebug.ExportedProperty(mapping = { 9170 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 9171 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 9172 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 9173 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 9174 }) 9175 public int getScrollBarStyle() { 9176 return mViewFlags & SCROLLBARS_STYLE_MASK; 9177 } 9178 9179 /** 9180 * <p>Compute the horizontal range that the horizontal scrollbar 9181 * represents.</p> 9182 * 9183 * <p>The range is expressed in arbitrary units that must be the same as the 9184 * units used by {@link #computeHorizontalScrollExtent()} and 9185 * {@link #computeHorizontalScrollOffset()}.</p> 9186 * 9187 * <p>The default range is the drawing width of this view.</p> 9188 * 9189 * @return the total horizontal range represented by the horizontal 9190 * scrollbar 9191 * 9192 * @see #computeHorizontalScrollExtent() 9193 * @see #computeHorizontalScrollOffset() 9194 * @see android.widget.ScrollBarDrawable 9195 */ 9196 protected int computeHorizontalScrollRange() { 9197 return getWidth(); 9198 } 9199 9200 /** 9201 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 9202 * within the horizontal range. This value is used to compute the position 9203 * of the thumb within the scrollbar's track.</p> 9204 * 9205 * <p>The range is expressed in arbitrary units that must be the same as the 9206 * units used by {@link #computeHorizontalScrollRange()} and 9207 * {@link #computeHorizontalScrollExtent()}.</p> 9208 * 9209 * <p>The default offset is the scroll offset of this view.</p> 9210 * 9211 * @return the horizontal offset of the scrollbar's thumb 9212 * 9213 * @see #computeHorizontalScrollRange() 9214 * @see #computeHorizontalScrollExtent() 9215 * @see android.widget.ScrollBarDrawable 9216 */ 9217 protected int computeHorizontalScrollOffset() { 9218 return mScrollX; 9219 } 9220 9221 /** 9222 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 9223 * within the horizontal range. This value is used to compute the length 9224 * of the thumb within the scrollbar's track.</p> 9225 * 9226 * <p>The range is expressed in arbitrary units that must be the same as the 9227 * units used by {@link #computeHorizontalScrollRange()} and 9228 * {@link #computeHorizontalScrollOffset()}.</p> 9229 * 9230 * <p>The default extent is the drawing width of this view.</p> 9231 * 9232 * @return the horizontal extent of the scrollbar's thumb 9233 * 9234 * @see #computeHorizontalScrollRange() 9235 * @see #computeHorizontalScrollOffset() 9236 * @see android.widget.ScrollBarDrawable 9237 */ 9238 protected int computeHorizontalScrollExtent() { 9239 return getWidth(); 9240 } 9241 9242 /** 9243 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 9244 * 9245 * <p>The range is expressed in arbitrary units that must be the same as the 9246 * units used by {@link #computeVerticalScrollExtent()} and 9247 * {@link #computeVerticalScrollOffset()}.</p> 9248 * 9249 * @return the total vertical range represented by the vertical scrollbar 9250 * 9251 * <p>The default range is the drawing height of this view.</p> 9252 * 9253 * @see #computeVerticalScrollExtent() 9254 * @see #computeVerticalScrollOffset() 9255 * @see android.widget.ScrollBarDrawable 9256 */ 9257 protected int computeVerticalScrollRange() { 9258 return getHeight(); 9259 } 9260 9261 /** 9262 * <p>Compute the vertical offset of the vertical scrollbar's thumb 9263 * within the horizontal range. This value is used to compute the position 9264 * of the thumb within the scrollbar's track.</p> 9265 * 9266 * <p>The range is expressed in arbitrary units that must be the same as the 9267 * units used by {@link #computeVerticalScrollRange()} and 9268 * {@link #computeVerticalScrollExtent()}.</p> 9269 * 9270 * <p>The default offset is the scroll offset of this view.</p> 9271 * 9272 * @return the vertical offset of the scrollbar's thumb 9273 * 9274 * @see #computeVerticalScrollRange() 9275 * @see #computeVerticalScrollExtent() 9276 * @see android.widget.ScrollBarDrawable 9277 */ 9278 protected int computeVerticalScrollOffset() { 9279 return mScrollY; 9280 } 9281 9282 /** 9283 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 9284 * within the vertical range. This value is used to compute the length 9285 * of the thumb within the scrollbar's track.</p> 9286 * 9287 * <p>The range is expressed in arbitrary units that must be the same as the 9288 * units used by {@link #computeVerticalScrollRange()} and 9289 * {@link #computeVerticalScrollOffset()}.</p> 9290 * 9291 * <p>The default extent is the drawing height of this view.</p> 9292 * 9293 * @return the vertical extent of the scrollbar's thumb 9294 * 9295 * @see #computeVerticalScrollRange() 9296 * @see #computeVerticalScrollOffset() 9297 * @see android.widget.ScrollBarDrawable 9298 */ 9299 protected int computeVerticalScrollExtent() { 9300 return getHeight(); 9301 } 9302 9303 /** 9304 * Check if this view can be scrolled horizontally in a certain direction. 9305 * 9306 * @param direction Negative to check scrolling left, positive to check scrolling right. 9307 * @return true if this view can be scrolled in the specified direction, false otherwise. 9308 */ 9309 public boolean canScrollHorizontally(int direction) { 9310 final int offset = computeHorizontalScrollOffset(); 9311 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 9312 if (range == 0) return false; 9313 if (direction < 0) { 9314 return offset > 0; 9315 } else { 9316 return offset < range - 1; 9317 } 9318 } 9319 9320 /** 9321 * Check if this view can be scrolled vertically in a certain direction. 9322 * 9323 * @param direction Negative to check scrolling up, positive to check scrolling down. 9324 * @return true if this view can be scrolled in the specified direction, false otherwise. 9325 */ 9326 public boolean canScrollVertically(int direction) { 9327 final int offset = computeVerticalScrollOffset(); 9328 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 9329 if (range == 0) return false; 9330 if (direction < 0) { 9331 return offset > 0; 9332 } else { 9333 return offset < range - 1; 9334 } 9335 } 9336 9337 /** 9338 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 9339 * scrollbars are painted only if they have been awakened first.</p> 9340 * 9341 * @param canvas the canvas on which to draw the scrollbars 9342 * 9343 * @see #awakenScrollBars(int) 9344 */ 9345 protected final void onDrawScrollBars(Canvas canvas) { 9346 // scrollbars are drawn only when the animation is running 9347 final ScrollabilityCache cache = mScrollCache; 9348 if (cache != null) { 9349 9350 int state = cache.state; 9351 9352 if (state == ScrollabilityCache.OFF) { 9353 return; 9354 } 9355 9356 boolean invalidate = false; 9357 9358 if (state == ScrollabilityCache.FADING) { 9359 // We're fading -- get our fade interpolation 9360 if (cache.interpolatorValues == null) { 9361 cache.interpolatorValues = new float[1]; 9362 } 9363 9364 float[] values = cache.interpolatorValues; 9365 9366 // Stops the animation if we're done 9367 if (cache.scrollBarInterpolator.timeToValues(values) == 9368 Interpolator.Result.FREEZE_END) { 9369 cache.state = ScrollabilityCache.OFF; 9370 } else { 9371 cache.scrollBar.setAlpha(Math.round(values[0])); 9372 } 9373 9374 // This will make the scroll bars inval themselves after 9375 // drawing. We only want this when we're fading so that 9376 // we prevent excessive redraws 9377 invalidate = true; 9378 } else { 9379 // We're just on -- but we may have been fading before so 9380 // reset alpha 9381 cache.scrollBar.setAlpha(255); 9382 } 9383 9384 9385 final int viewFlags = mViewFlags; 9386 9387 final boolean drawHorizontalScrollBar = 9388 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 9389 final boolean drawVerticalScrollBar = 9390 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 9391 && !isVerticalScrollBarHidden(); 9392 9393 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 9394 final int width = mRight - mLeft; 9395 final int height = mBottom - mTop; 9396 9397 final ScrollBarDrawable scrollBar = cache.scrollBar; 9398 9399 final int scrollX = mScrollX; 9400 final int scrollY = mScrollY; 9401 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 9402 9403 int left, top, right, bottom; 9404 9405 if (drawHorizontalScrollBar) { 9406 int size = scrollBar.getSize(false); 9407 if (size <= 0) { 9408 size = cache.scrollBarSize; 9409 } 9410 9411 scrollBar.setParameters(computeHorizontalScrollRange(), 9412 computeHorizontalScrollOffset(), 9413 computeHorizontalScrollExtent(), false); 9414 final int verticalScrollBarGap = drawVerticalScrollBar ? 9415 getVerticalScrollbarWidth() : 0; 9416 top = scrollY + height - size - (mUserPaddingBottom & inside); 9417 left = scrollX + (mPaddingLeft & inside); 9418 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 9419 bottom = top + size; 9420 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 9421 if (invalidate) { 9422 invalidate(left, top, right, bottom); 9423 } 9424 } 9425 9426 if (drawVerticalScrollBar) { 9427 int size = scrollBar.getSize(true); 9428 if (size <= 0) { 9429 size = cache.scrollBarSize; 9430 } 9431 9432 scrollBar.setParameters(computeVerticalScrollRange(), 9433 computeVerticalScrollOffset(), 9434 computeVerticalScrollExtent(), true); 9435 switch (mVerticalScrollbarPosition) { 9436 default: 9437 case SCROLLBAR_POSITION_DEFAULT: 9438 case SCROLLBAR_POSITION_RIGHT: 9439 left = scrollX + width - size - (mUserPaddingRight & inside); 9440 break; 9441 case SCROLLBAR_POSITION_LEFT: 9442 left = scrollX + (mUserPaddingLeft & inside); 9443 break; 9444 } 9445 top = scrollY + (mPaddingTop & inside); 9446 right = left + size; 9447 bottom = scrollY + height - (mUserPaddingBottom & inside); 9448 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 9449 if (invalidate) { 9450 invalidate(left, top, right, bottom); 9451 } 9452 } 9453 } 9454 } 9455 } 9456 9457 /** 9458 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 9459 * FastScroller is visible. 9460 * @return whether to temporarily hide the vertical scrollbar 9461 * @hide 9462 */ 9463 protected boolean isVerticalScrollBarHidden() { 9464 return false; 9465 } 9466 9467 /** 9468 * <p>Draw the horizontal scrollbar if 9469 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 9470 * 9471 * @param canvas the canvas on which to draw the scrollbar 9472 * @param scrollBar the scrollbar's drawable 9473 * 9474 * @see #isHorizontalScrollBarEnabled() 9475 * @see #computeHorizontalScrollRange() 9476 * @see #computeHorizontalScrollExtent() 9477 * @see #computeHorizontalScrollOffset() 9478 * @see android.widget.ScrollBarDrawable 9479 * @hide 9480 */ 9481 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 9482 int l, int t, int r, int b) { 9483 scrollBar.setBounds(l, t, r, b); 9484 scrollBar.draw(canvas); 9485 } 9486 9487 /** 9488 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 9489 * returns true.</p> 9490 * 9491 * @param canvas the canvas on which to draw the scrollbar 9492 * @param scrollBar the scrollbar's drawable 9493 * 9494 * @see #isVerticalScrollBarEnabled() 9495 * @see #computeVerticalScrollRange() 9496 * @see #computeVerticalScrollExtent() 9497 * @see #computeVerticalScrollOffset() 9498 * @see android.widget.ScrollBarDrawable 9499 * @hide 9500 */ 9501 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 9502 int l, int t, int r, int b) { 9503 scrollBar.setBounds(l, t, r, b); 9504 scrollBar.draw(canvas); 9505 } 9506 9507 /** 9508 * Implement this to do your drawing. 9509 * 9510 * @param canvas the canvas on which the background will be drawn 9511 */ 9512 protected void onDraw(Canvas canvas) { 9513 } 9514 9515 /* 9516 * Caller is responsible for calling requestLayout if necessary. 9517 * (This allows addViewInLayout to not request a new layout.) 9518 */ 9519 void assignParent(ViewParent parent) { 9520 if (mParent == null) { 9521 mParent = parent; 9522 } else if (parent == null) { 9523 mParent = null; 9524 } else { 9525 throw new RuntimeException("view " + this + " being added, but" 9526 + " it already has a parent"); 9527 } 9528 } 9529 9530 /** 9531 * This is called when the view is attached to a window. At this point it 9532 * has a Surface and will start drawing. Note that this function is 9533 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 9534 * however it may be called any time before the first onDraw -- including 9535 * before or after {@link #onMeasure(int, int)}. 9536 * 9537 * @see #onDetachedFromWindow() 9538 */ 9539 protected void onAttachedToWindow() { 9540 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 9541 mParent.requestTransparentRegion(this); 9542 } 9543 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 9544 initialAwakenScrollBars(); 9545 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH; 9546 } 9547 jumpDrawablesToCurrentState(); 9548 // Order is important here: LayoutDirection MUST be resolved before Padding 9549 // and TextDirection 9550 resolveLayoutDirectionIfNeeded(); 9551 resolvePadding(); 9552 resolveTextDirection(); 9553 if (isFocused()) { 9554 InputMethodManager imm = InputMethodManager.peekInstance(); 9555 imm.focusIn(this); 9556 } 9557 } 9558 9559 /** 9560 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 9561 * that the parent directionality can and will be resolved before its children. 9562 */ 9563 private void resolveLayoutDirectionIfNeeded() { 9564 // Do not resolve if it is not needed 9565 if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return; 9566 9567 // Clear any previous layout direction resolution 9568 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL; 9569 9570 // Reset also TextDirection as a change into LayoutDirection may impact the selected 9571 // TextDirectionHeuristic 9572 resetResolvedTextDirection(); 9573 9574 // Set resolved depending on layout direction 9575 switch (getLayoutDirection()) { 9576 case LAYOUT_DIRECTION_INHERIT: 9577 // We cannot do the resolution if there is no parent 9578 if (mParent == null) return; 9579 9580 // If this is root view, no need to look at parent's layout dir. 9581 if (mParent instanceof ViewGroup) { 9582 ViewGroup viewGroup = ((ViewGroup) mParent); 9583 9584 // Check if the parent view group can resolve 9585 if (! viewGroup.canResolveLayoutDirection()) { 9586 return; 9587 } 9588 if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 9589 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9590 } 9591 } 9592 break; 9593 case LAYOUT_DIRECTION_RTL: 9594 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9595 break; 9596 case LAYOUT_DIRECTION_LOCALE: 9597 if(isLayoutDirectionRtl(Locale.getDefault())) { 9598 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9599 } 9600 break; 9601 default: 9602 // Nothing to do, LTR by default 9603 } 9604 9605 // Set to resolved 9606 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED; 9607 } 9608 9609 /** 9610 * @hide 9611 */ 9612 protected void resolvePadding() { 9613 // If the user specified the absolute padding (either with android:padding or 9614 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 9615 // use the default padding or the padding from the background drawable 9616 // (stored at this point in mPadding*) 9617 switch (getResolvedLayoutDirection()) { 9618 case LAYOUT_DIRECTION_RTL: 9619 // Start user padding override Right user padding. Otherwise, if Right user 9620 // padding is not defined, use the default Right padding. If Right user padding 9621 // is defined, just use it. 9622 if (mUserPaddingStart >= 0) { 9623 mUserPaddingRight = mUserPaddingStart; 9624 } else if (mUserPaddingRight < 0) { 9625 mUserPaddingRight = mPaddingRight; 9626 } 9627 if (mUserPaddingEnd >= 0) { 9628 mUserPaddingLeft = mUserPaddingEnd; 9629 } else if (mUserPaddingLeft < 0) { 9630 mUserPaddingLeft = mPaddingLeft; 9631 } 9632 break; 9633 case LAYOUT_DIRECTION_LTR: 9634 default: 9635 // Start user padding override Left user padding. Otherwise, if Left user 9636 // padding is not defined, use the default left padding. If Left user padding 9637 // is defined, just use it. 9638 if (mUserPaddingStart >= 0) { 9639 mUserPaddingLeft = mUserPaddingStart; 9640 } else if (mUserPaddingLeft < 0) { 9641 mUserPaddingLeft = mPaddingLeft; 9642 } 9643 if (mUserPaddingEnd >= 0) { 9644 mUserPaddingRight = mUserPaddingEnd; 9645 } else if (mUserPaddingRight < 0) { 9646 mUserPaddingRight = mPaddingRight; 9647 } 9648 } 9649 9650 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 9651 9652 recomputePadding(); 9653 } 9654 9655 /** 9656 * Return true if layout direction resolution can be done 9657 * 9658 * @hide 9659 */ 9660 protected boolean canResolveLayoutDirection() { 9661 switch (getLayoutDirection()) { 9662 case LAYOUT_DIRECTION_INHERIT: 9663 return (mParent != null); 9664 default: 9665 return true; 9666 } 9667 } 9668 9669 /** 9670 * Reset the resolved layout direction. 9671 * 9672 * Subclasses need to override this method to clear cached information that depends on the 9673 * resolved layout direction, or to inform child views that inherit their layout direction. 9674 * Overrides must also call the superclass implementation at the start of their implementation. 9675 * 9676 * @hide 9677 */ 9678 protected void resetResolvedLayoutDirection() { 9679 // Reset the current View resolution 9680 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED; 9681 } 9682 9683 /** 9684 * Check if a Locale is corresponding to a RTL script. 9685 * 9686 * @param locale Locale to check 9687 * @return true if a Locale is corresponding to a RTL script. 9688 * 9689 * @hide 9690 */ 9691 protected static boolean isLayoutDirectionRtl(Locale locale) { 9692 return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE == 9693 LocaleUtil.getLayoutDirectionFromLocale(locale)); 9694 } 9695 9696 /** 9697 * This is called when the view is detached from a window. At this point it 9698 * no longer has a surface for drawing. 9699 * 9700 * @see #onAttachedToWindow() 9701 */ 9702 protected void onDetachedFromWindow() { 9703 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 9704 9705 removeUnsetPressCallback(); 9706 removeLongPressCallback(); 9707 removePerformClickCallback(); 9708 removeSendViewScrolledAccessibilityEventCallback(); 9709 9710 destroyDrawingCache(); 9711 9712 destroyLayer(); 9713 9714 if (mDisplayList != null) { 9715 mDisplayList.invalidate(); 9716 } 9717 9718 if (mAttachInfo != null) { 9719 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this); 9720 } 9721 9722 mCurrentAnimation = null; 9723 9724 resetResolvedLayoutDirection(); 9725 resetResolvedTextDirection(); 9726 } 9727 9728 /** 9729 * @return The number of times this view has been attached to a window 9730 */ 9731 protected int getWindowAttachCount() { 9732 return mWindowAttachCount; 9733 } 9734 9735 /** 9736 * Retrieve a unique token identifying the window this view is attached to. 9737 * @return Return the window's token for use in 9738 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 9739 */ 9740 public IBinder getWindowToken() { 9741 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 9742 } 9743 9744 /** 9745 * Retrieve a unique token identifying the top-level "real" window of 9746 * the window that this view is attached to. That is, this is like 9747 * {@link #getWindowToken}, except if the window this view in is a panel 9748 * window (attached to another containing window), then the token of 9749 * the containing window is returned instead. 9750 * 9751 * @return Returns the associated window token, either 9752 * {@link #getWindowToken()} or the containing window's token. 9753 */ 9754 public IBinder getApplicationWindowToken() { 9755 AttachInfo ai = mAttachInfo; 9756 if (ai != null) { 9757 IBinder appWindowToken = ai.mPanelParentWindowToken; 9758 if (appWindowToken == null) { 9759 appWindowToken = ai.mWindowToken; 9760 } 9761 return appWindowToken; 9762 } 9763 return null; 9764 } 9765 9766 /** 9767 * Retrieve private session object this view hierarchy is using to 9768 * communicate with the window manager. 9769 * @return the session object to communicate with the window manager 9770 */ 9771 /*package*/ IWindowSession getWindowSession() { 9772 return mAttachInfo != null ? mAttachInfo.mSession : null; 9773 } 9774 9775 /** 9776 * @param info the {@link android.view.View.AttachInfo} to associated with 9777 * this view 9778 */ 9779 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 9780 //System.out.println("Attached! " + this); 9781 mAttachInfo = info; 9782 mWindowAttachCount++; 9783 // We will need to evaluate the drawable state at least once. 9784 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 9785 if (mFloatingTreeObserver != null) { 9786 info.mTreeObserver.merge(mFloatingTreeObserver); 9787 mFloatingTreeObserver = null; 9788 } 9789 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 9790 mAttachInfo.mScrollContainers.add(this); 9791 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 9792 } 9793 performCollectViewAttributes(visibility); 9794 onAttachedToWindow(); 9795 9796 ListenerInfo li = mListenerInfo; 9797 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9798 li != null ? li.mOnAttachStateChangeListeners : null; 9799 if (listeners != null && listeners.size() > 0) { 9800 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9801 // perform the dispatching. The iterator is a safe guard against listeners that 9802 // could mutate the list by calling the various add/remove methods. This prevents 9803 // the array from being modified while we iterate it. 9804 for (OnAttachStateChangeListener listener : listeners) { 9805 listener.onViewAttachedToWindow(this); 9806 } 9807 } 9808 9809 int vis = info.mWindowVisibility; 9810 if (vis != GONE) { 9811 onWindowVisibilityChanged(vis); 9812 } 9813 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 9814 // If nobody has evaluated the drawable state yet, then do it now. 9815 refreshDrawableState(); 9816 } 9817 } 9818 9819 void dispatchDetachedFromWindow() { 9820 AttachInfo info = mAttachInfo; 9821 if (info != null) { 9822 int vis = info.mWindowVisibility; 9823 if (vis != GONE) { 9824 onWindowVisibilityChanged(GONE); 9825 } 9826 } 9827 9828 onDetachedFromWindow(); 9829 9830 ListenerInfo li = mListenerInfo; 9831 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9832 li != null ? li.mOnAttachStateChangeListeners : null; 9833 if (listeners != null && listeners.size() > 0) { 9834 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9835 // perform the dispatching. The iterator is a safe guard against listeners that 9836 // could mutate the list by calling the various add/remove methods. This prevents 9837 // the array from being modified while we iterate it. 9838 for (OnAttachStateChangeListener listener : listeners) { 9839 listener.onViewDetachedFromWindow(this); 9840 } 9841 } 9842 9843 if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) { 9844 mAttachInfo.mScrollContainers.remove(this); 9845 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 9846 } 9847 9848 mAttachInfo = null; 9849 } 9850 9851 /** 9852 * Store this view hierarchy's frozen state into the given container. 9853 * 9854 * @param container The SparseArray in which to save the view's state. 9855 * 9856 * @see #restoreHierarchyState(android.util.SparseArray) 9857 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9858 * @see #onSaveInstanceState() 9859 */ 9860 public void saveHierarchyState(SparseArray<Parcelable> container) { 9861 dispatchSaveInstanceState(container); 9862 } 9863 9864 /** 9865 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 9866 * this view and its children. May be overridden to modify how freezing happens to a 9867 * view's children; for example, some views may want to not store state for their children. 9868 * 9869 * @param container The SparseArray in which to save the view's state. 9870 * 9871 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9872 * @see #saveHierarchyState(android.util.SparseArray) 9873 * @see #onSaveInstanceState() 9874 */ 9875 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 9876 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 9877 mPrivateFlags &= ~SAVE_STATE_CALLED; 9878 Parcelable state = onSaveInstanceState(); 9879 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9880 throw new IllegalStateException( 9881 "Derived class did not call super.onSaveInstanceState()"); 9882 } 9883 if (state != null) { 9884 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 9885 // + ": " + state); 9886 container.put(mID, state); 9887 } 9888 } 9889 } 9890 9891 /** 9892 * Hook allowing a view to generate a representation of its internal state 9893 * that can later be used to create a new instance with that same state. 9894 * This state should only contain information that is not persistent or can 9895 * not be reconstructed later. For example, you will never store your 9896 * current position on screen because that will be computed again when a 9897 * new instance of the view is placed in its view hierarchy. 9898 * <p> 9899 * Some examples of things you may store here: the current cursor position 9900 * in a text view (but usually not the text itself since that is stored in a 9901 * content provider or other persistent storage), the currently selected 9902 * item in a list view. 9903 * 9904 * @return Returns a Parcelable object containing the view's current dynamic 9905 * state, or null if there is nothing interesting to save. The 9906 * default implementation returns null. 9907 * @see #onRestoreInstanceState(android.os.Parcelable) 9908 * @see #saveHierarchyState(android.util.SparseArray) 9909 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9910 * @see #setSaveEnabled(boolean) 9911 */ 9912 protected Parcelable onSaveInstanceState() { 9913 mPrivateFlags |= SAVE_STATE_CALLED; 9914 return BaseSavedState.EMPTY_STATE; 9915 } 9916 9917 /** 9918 * Restore this view hierarchy's frozen state from the given container. 9919 * 9920 * @param container The SparseArray which holds previously frozen states. 9921 * 9922 * @see #saveHierarchyState(android.util.SparseArray) 9923 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9924 * @see #onRestoreInstanceState(android.os.Parcelable) 9925 */ 9926 public void restoreHierarchyState(SparseArray<Parcelable> container) { 9927 dispatchRestoreInstanceState(container); 9928 } 9929 9930 /** 9931 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 9932 * state for this view and its children. May be overridden to modify how restoring 9933 * happens to a view's children; for example, some views may want to not store state 9934 * for their children. 9935 * 9936 * @param container The SparseArray which holds previously saved state. 9937 * 9938 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9939 * @see #restoreHierarchyState(android.util.SparseArray) 9940 * @see #onRestoreInstanceState(android.os.Parcelable) 9941 */ 9942 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 9943 if (mID != NO_ID) { 9944 Parcelable state = container.get(mID); 9945 if (state != null) { 9946 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 9947 // + ": " + state); 9948 mPrivateFlags &= ~SAVE_STATE_CALLED; 9949 onRestoreInstanceState(state); 9950 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9951 throw new IllegalStateException( 9952 "Derived class did not call super.onRestoreInstanceState()"); 9953 } 9954 } 9955 } 9956 } 9957 9958 /** 9959 * Hook allowing a view to re-apply a representation of its internal state that had previously 9960 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 9961 * null state. 9962 * 9963 * @param state The frozen state that had previously been returned by 9964 * {@link #onSaveInstanceState}. 9965 * 9966 * @see #onSaveInstanceState() 9967 * @see #restoreHierarchyState(android.util.SparseArray) 9968 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9969 */ 9970 protected void onRestoreInstanceState(Parcelable state) { 9971 mPrivateFlags |= SAVE_STATE_CALLED; 9972 if (state != BaseSavedState.EMPTY_STATE && state != null) { 9973 throw new IllegalArgumentException("Wrong state class, expecting View State but " 9974 + "received " + state.getClass().toString() + " instead. This usually happens " 9975 + "when two views of different type have the same id in the same hierarchy. " 9976 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 9977 + "other views do not use the same id."); 9978 } 9979 } 9980 9981 /** 9982 * <p>Return the time at which the drawing of the view hierarchy started.</p> 9983 * 9984 * @return the drawing start time in milliseconds 9985 */ 9986 public long getDrawingTime() { 9987 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 9988 } 9989 9990 /** 9991 * <p>Enables or disables the duplication of the parent's state into this view. When 9992 * duplication is enabled, this view gets its drawable state from its parent rather 9993 * than from its own internal properties.</p> 9994 * 9995 * <p>Note: in the current implementation, setting this property to true after the 9996 * view was added to a ViewGroup might have no effect at all. This property should 9997 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 9998 * 9999 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 10000 * property is enabled, an exception will be thrown.</p> 10001 * 10002 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 10003 * parent, these states should not be affected by this method.</p> 10004 * 10005 * @param enabled True to enable duplication of the parent's drawable state, false 10006 * to disable it. 10007 * 10008 * @see #getDrawableState() 10009 * @see #isDuplicateParentStateEnabled() 10010 */ 10011 public void setDuplicateParentStateEnabled(boolean enabled) { 10012 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 10013 } 10014 10015 /** 10016 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 10017 * 10018 * @return True if this view's drawable state is duplicated from the parent, 10019 * false otherwise 10020 * 10021 * @see #getDrawableState() 10022 * @see #setDuplicateParentStateEnabled(boolean) 10023 */ 10024 public boolean isDuplicateParentStateEnabled() { 10025 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 10026 } 10027 10028 /** 10029 * <p>Specifies the type of layer backing this view. The layer can be 10030 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 10031 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 10032 * 10033 * <p>A layer is associated with an optional {@link android.graphics.Paint} 10034 * instance that controls how the layer is composed on screen. The following 10035 * properties of the paint are taken into account when composing the layer:</p> 10036 * <ul> 10037 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 10038 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 10039 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 10040 * </ul> 10041 * 10042 * <p>If this view has an alpha value set to < 1.0 by calling 10043 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 10044 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 10045 * equivalent to setting a hardware layer on this view and providing a paint with 10046 * the desired alpha value.<p> 10047 * 10048 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 10049 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 10050 * for more information on when and how to use layers.</p> 10051 * 10052 * @param layerType The ype of layer to use with this view, must be one of 10053 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 10054 * {@link #LAYER_TYPE_HARDWARE} 10055 * @param paint The paint used to compose the layer. This argument is optional 10056 * and can be null. It is ignored when the layer type is 10057 * {@link #LAYER_TYPE_NONE} 10058 * 10059 * @see #getLayerType() 10060 * @see #LAYER_TYPE_NONE 10061 * @see #LAYER_TYPE_SOFTWARE 10062 * @see #LAYER_TYPE_HARDWARE 10063 * @see #setAlpha(float) 10064 * 10065 * @attr ref android.R.styleable#View_layerType 10066 */ 10067 public void setLayerType(int layerType, Paint paint) { 10068 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 10069 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 10070 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 10071 } 10072 10073 if (layerType == mLayerType) { 10074 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 10075 mLayerPaint = paint == null ? new Paint() : paint; 10076 invalidateParentCaches(); 10077 invalidate(true); 10078 } 10079 return; 10080 } 10081 10082 // Destroy any previous software drawing cache if needed 10083 switch (mLayerType) { 10084 case LAYER_TYPE_HARDWARE: 10085 destroyLayer(); 10086 // fall through - non-accelerated views may use software layer mechanism instead 10087 case LAYER_TYPE_SOFTWARE: 10088 destroyDrawingCache(); 10089 break; 10090 default: 10091 break; 10092 } 10093 10094 mLayerType = layerType; 10095 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 10096 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 10097 mLocalDirtyRect = layerDisabled ? null : new Rect(); 10098 10099 invalidateParentCaches(); 10100 invalidate(true); 10101 } 10102 10103 /** 10104 * Indicates whether this view has a static layer. A view with layer type 10105 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 10106 * dynamic. 10107 */ 10108 boolean hasStaticLayer() { 10109 return mLayerType == LAYER_TYPE_NONE; 10110 } 10111 10112 /** 10113 * Indicates what type of layer is currently associated with this view. By default 10114 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 10115 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 10116 * for more information on the different types of layers. 10117 * 10118 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 10119 * {@link #LAYER_TYPE_HARDWARE} 10120 * 10121 * @see #setLayerType(int, android.graphics.Paint) 10122 * @see #buildLayer() 10123 * @see #LAYER_TYPE_NONE 10124 * @see #LAYER_TYPE_SOFTWARE 10125 * @see #LAYER_TYPE_HARDWARE 10126 */ 10127 public int getLayerType() { 10128 return mLayerType; 10129 } 10130 10131 /** 10132 * Forces this view's layer to be created and this view to be rendered 10133 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 10134 * invoking this method will have no effect. 10135 * 10136 * This method can for instance be used to render a view into its layer before 10137 * starting an animation. If this view is complex, rendering into the layer 10138 * before starting the animation will avoid skipping frames. 10139 * 10140 * @throws IllegalStateException If this view is not attached to a window 10141 * 10142 * @see #setLayerType(int, android.graphics.Paint) 10143 */ 10144 public void buildLayer() { 10145 if (mLayerType == LAYER_TYPE_NONE) return; 10146 10147 if (mAttachInfo == null) { 10148 throw new IllegalStateException("This view must be attached to a window first"); 10149 } 10150 10151 switch (mLayerType) { 10152 case LAYER_TYPE_HARDWARE: 10153 if (mAttachInfo.mHardwareRenderer != null && 10154 mAttachInfo.mHardwareRenderer.isEnabled() && 10155 mAttachInfo.mHardwareRenderer.validate()) { 10156 getHardwareLayer(); 10157 } 10158 break; 10159 case LAYER_TYPE_SOFTWARE: 10160 buildDrawingCache(true); 10161 break; 10162 } 10163 } 10164 10165 // Make sure the HardwareRenderer.validate() was invoked before calling this method 10166 void flushLayer() { 10167 if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) { 10168 mHardwareLayer.flush(); 10169 } 10170 } 10171 10172 /** 10173 * <p>Returns a hardware layer that can be used to draw this view again 10174 * without executing its draw method.</p> 10175 * 10176 * @return A HardwareLayer ready to render, or null if an error occurred. 10177 */ 10178 HardwareLayer getHardwareLayer() { 10179 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 10180 !mAttachInfo.mHardwareRenderer.isEnabled()) { 10181 return null; 10182 } 10183 10184 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 10185 10186 final int width = mRight - mLeft; 10187 final int height = mBottom - mTop; 10188 10189 if (width == 0 || height == 0) { 10190 return null; 10191 } 10192 10193 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 10194 if (mHardwareLayer == null) { 10195 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 10196 width, height, isOpaque()); 10197 mLocalDirtyRect.setEmpty(); 10198 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 10199 mHardwareLayer.resize(width, height); 10200 mLocalDirtyRect.setEmpty(); 10201 } 10202 10203 // The layer is not valid if the underlying GPU resources cannot be allocated 10204 if (!mHardwareLayer.isValid()) { 10205 return null; 10206 } 10207 10208 HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas; 10209 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas); 10210 10211 // Make sure all the GPU resources have been properly allocated 10212 if (canvas == null) { 10213 mHardwareLayer.end(currentCanvas); 10214 return null; 10215 } 10216 10217 mAttachInfo.mHardwareCanvas = canvas; 10218 try { 10219 canvas.setViewport(width, height); 10220 canvas.onPreDraw(mLocalDirtyRect); 10221 mLocalDirtyRect.setEmpty(); 10222 10223 final int restoreCount = canvas.save(); 10224 10225 computeScroll(); 10226 canvas.translate(-mScrollX, -mScrollY); 10227 10228 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10229 10230 // Fast path for layouts with no backgrounds 10231 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10232 mPrivateFlags &= ~DIRTY_MASK; 10233 dispatchDraw(canvas); 10234 } else { 10235 draw(canvas); 10236 } 10237 10238 canvas.restoreToCount(restoreCount); 10239 } finally { 10240 canvas.onPostDraw(); 10241 mHardwareLayer.end(currentCanvas); 10242 mAttachInfo.mHardwareCanvas = currentCanvas; 10243 } 10244 } 10245 10246 return mHardwareLayer; 10247 } 10248 10249 /** 10250 * Destroys this View's hardware layer if possible. 10251 * 10252 * @return True if the layer was destroyed, false otherwise. 10253 * 10254 * @see #setLayerType(int, android.graphics.Paint) 10255 * @see #LAYER_TYPE_HARDWARE 10256 */ 10257 boolean destroyLayer() { 10258 if (mHardwareLayer != null) { 10259 AttachInfo info = mAttachInfo; 10260 if (info != null && info.mHardwareRenderer != null && 10261 info.mHardwareRenderer.isEnabled() && info.mHardwareRenderer.validate()) { 10262 mHardwareLayer.destroy(); 10263 mHardwareLayer = null; 10264 10265 invalidate(true); 10266 invalidateParentCaches(); 10267 } 10268 return true; 10269 } 10270 return false; 10271 } 10272 10273 /** 10274 * Destroys all hardware rendering resources. This method is invoked 10275 * when the system needs to reclaim resources. Upon execution of this 10276 * method, you should free any OpenGL resources created by the view. 10277 * 10278 * Note: you <strong>must</strong> call 10279 * <code>super.destroyHardwareResources()</code> when overriding 10280 * this method. 10281 * 10282 * @hide 10283 */ 10284 protected void destroyHardwareResources() { 10285 destroyLayer(); 10286 } 10287 10288 /** 10289 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 10290 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 10291 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 10292 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 10293 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 10294 * null.</p> 10295 * 10296 * <p>Enabling the drawing cache is similar to 10297 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 10298 * acceleration is turned off. When hardware acceleration is turned on, enabling the 10299 * drawing cache has no effect on rendering because the system uses a different mechanism 10300 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 10301 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 10302 * for information on how to enable software and hardware layers.</p> 10303 * 10304 * <p>This API can be used to manually generate 10305 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 10306 * {@link #getDrawingCache()}.</p> 10307 * 10308 * @param enabled true to enable the drawing cache, false otherwise 10309 * 10310 * @see #isDrawingCacheEnabled() 10311 * @see #getDrawingCache() 10312 * @see #buildDrawingCache() 10313 * @see #setLayerType(int, android.graphics.Paint) 10314 */ 10315 public void setDrawingCacheEnabled(boolean enabled) { 10316 mCachingFailed = false; 10317 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 10318 } 10319 10320 /** 10321 * <p>Indicates whether the drawing cache is enabled for this view.</p> 10322 * 10323 * @return true if the drawing cache is enabled 10324 * 10325 * @see #setDrawingCacheEnabled(boolean) 10326 * @see #getDrawingCache() 10327 */ 10328 @ViewDebug.ExportedProperty(category = "drawing") 10329 public boolean isDrawingCacheEnabled() { 10330 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 10331 } 10332 10333 /** 10334 * Debugging utility which recursively outputs the dirty state of a view and its 10335 * descendants. 10336 * 10337 * @hide 10338 */ 10339 @SuppressWarnings({"UnusedDeclaration"}) 10340 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 10341 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) + 10342 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" + 10343 (mPrivateFlags & View.DRAWING_CACHE_VALID) + 10344 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")"); 10345 if (clear) { 10346 mPrivateFlags &= clearMask; 10347 } 10348 if (this instanceof ViewGroup) { 10349 ViewGroup parent = (ViewGroup) this; 10350 final int count = parent.getChildCount(); 10351 for (int i = 0; i < count; i++) { 10352 final View child = parent.getChildAt(i); 10353 child.outputDirtyFlags(indent + " ", clear, clearMask); 10354 } 10355 } 10356 } 10357 10358 /** 10359 * This method is used by ViewGroup to cause its children to restore or recreate their 10360 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 10361 * to recreate its own display list, which would happen if it went through the normal 10362 * draw/dispatchDraw mechanisms. 10363 * 10364 * @hide 10365 */ 10366 protected void dispatchGetDisplayList() {} 10367 10368 /** 10369 * A view that is not attached or hardware accelerated cannot create a display list. 10370 * This method checks these conditions and returns the appropriate result. 10371 * 10372 * @return true if view has the ability to create a display list, false otherwise. 10373 * 10374 * @hide 10375 */ 10376 public boolean canHaveDisplayList() { 10377 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 10378 } 10379 10380 /** 10381 * @return The HardwareRenderer associated with that view or null if hardware rendering 10382 * is not supported or this this has not been attached to a window. 10383 * 10384 * @hide 10385 */ 10386 public HardwareRenderer getHardwareRenderer() { 10387 if (mAttachInfo != null) { 10388 return mAttachInfo.mHardwareRenderer; 10389 } 10390 return null; 10391 } 10392 10393 /** 10394 * <p>Returns a display list that can be used to draw this view again 10395 * without executing its draw method.</p> 10396 * 10397 * @return A DisplayList ready to replay, or null if caching is not enabled. 10398 * 10399 * @hide 10400 */ 10401 public DisplayList getDisplayList() { 10402 if (!canHaveDisplayList()) { 10403 return null; 10404 } 10405 10406 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || 10407 mDisplayList == null || !mDisplayList.isValid() || 10408 mRecreateDisplayList)) { 10409 // Don't need to recreate the display list, just need to tell our 10410 // children to restore/recreate theirs 10411 if (mDisplayList != null && mDisplayList.isValid() && 10412 !mRecreateDisplayList) { 10413 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10414 mPrivateFlags &= ~DIRTY_MASK; 10415 dispatchGetDisplayList(); 10416 10417 return mDisplayList; 10418 } 10419 10420 // If we got here, we're recreating it. Mark it as such to ensure that 10421 // we copy in child display lists into ours in drawChild() 10422 mRecreateDisplayList = true; 10423 if (mDisplayList == null) { 10424 final String name = getClass().getSimpleName(); 10425 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(name); 10426 // If we're creating a new display list, make sure our parent gets invalidated 10427 // since they will need to recreate their display list to account for this 10428 // new child display list. 10429 invalidateParentCaches(); 10430 } 10431 10432 final HardwareCanvas canvas = mDisplayList.start(); 10433 int restoreCount = 0; 10434 try { 10435 int width = mRight - mLeft; 10436 int height = mBottom - mTop; 10437 10438 canvas.setViewport(width, height); 10439 // The dirty rect should always be null for a display list 10440 canvas.onPreDraw(null); 10441 10442 computeScroll(); 10443 10444 restoreCount = canvas.save(); 10445 canvas.translate(-mScrollX, -mScrollY); 10446 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10447 mPrivateFlags &= ~DIRTY_MASK; 10448 10449 // Fast path for layouts with no backgrounds 10450 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10451 dispatchDraw(canvas); 10452 } else { 10453 draw(canvas); 10454 } 10455 } finally { 10456 canvas.restoreToCount(restoreCount); 10457 canvas.onPostDraw(); 10458 10459 mDisplayList.end(); 10460 } 10461 } else { 10462 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10463 mPrivateFlags &= ~DIRTY_MASK; 10464 } 10465 10466 return mDisplayList; 10467 } 10468 10469 /** 10470 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 10471 * 10472 * @return A non-scaled bitmap representing this view or null if cache is disabled. 10473 * 10474 * @see #getDrawingCache(boolean) 10475 */ 10476 public Bitmap getDrawingCache() { 10477 return getDrawingCache(false); 10478 } 10479 10480 /** 10481 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 10482 * is null when caching is disabled. If caching is enabled and the cache is not ready, 10483 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 10484 * draw from the cache when the cache is enabled. To benefit from the cache, you must 10485 * request the drawing cache by calling this method and draw it on screen if the 10486 * returned bitmap is not null.</p> 10487 * 10488 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10489 * this method will create a bitmap of the same size as this view. Because this bitmap 10490 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10491 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10492 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10493 * size than the view. This implies that your application must be able to handle this 10494 * size.</p> 10495 * 10496 * @param autoScale Indicates whether the generated bitmap should be scaled based on 10497 * the current density of the screen when the application is in compatibility 10498 * mode. 10499 * 10500 * @return A bitmap representing this view or null if cache is disabled. 10501 * 10502 * @see #setDrawingCacheEnabled(boolean) 10503 * @see #isDrawingCacheEnabled() 10504 * @see #buildDrawingCache(boolean) 10505 * @see #destroyDrawingCache() 10506 */ 10507 public Bitmap getDrawingCache(boolean autoScale) { 10508 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 10509 return null; 10510 } 10511 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 10512 buildDrawingCache(autoScale); 10513 } 10514 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 10515 } 10516 10517 /** 10518 * <p>Frees the resources used by the drawing cache. If you call 10519 * {@link #buildDrawingCache()} manually without calling 10520 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10521 * should cleanup the cache with this method afterwards.</p> 10522 * 10523 * @see #setDrawingCacheEnabled(boolean) 10524 * @see #buildDrawingCache() 10525 * @see #getDrawingCache() 10526 */ 10527 public void destroyDrawingCache() { 10528 if (mDrawingCache != null) { 10529 mDrawingCache.recycle(); 10530 mDrawingCache = null; 10531 } 10532 if (mUnscaledDrawingCache != null) { 10533 mUnscaledDrawingCache.recycle(); 10534 mUnscaledDrawingCache = null; 10535 } 10536 } 10537 10538 /** 10539 * Setting a solid background color for the drawing cache's bitmaps will improve 10540 * performance and memory usage. Note, though that this should only be used if this 10541 * view will always be drawn on top of a solid color. 10542 * 10543 * @param color The background color to use for the drawing cache's bitmap 10544 * 10545 * @see #setDrawingCacheEnabled(boolean) 10546 * @see #buildDrawingCache() 10547 * @see #getDrawingCache() 10548 */ 10549 public void setDrawingCacheBackgroundColor(int color) { 10550 if (color != mDrawingCacheBackgroundColor) { 10551 mDrawingCacheBackgroundColor = color; 10552 mPrivateFlags &= ~DRAWING_CACHE_VALID; 10553 } 10554 } 10555 10556 /** 10557 * @see #setDrawingCacheBackgroundColor(int) 10558 * 10559 * @return The background color to used for the drawing cache's bitmap 10560 */ 10561 public int getDrawingCacheBackgroundColor() { 10562 return mDrawingCacheBackgroundColor; 10563 } 10564 10565 /** 10566 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 10567 * 10568 * @see #buildDrawingCache(boolean) 10569 */ 10570 public void buildDrawingCache() { 10571 buildDrawingCache(false); 10572 } 10573 10574 /** 10575 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 10576 * 10577 * <p>If you call {@link #buildDrawingCache()} manually without calling 10578 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10579 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 10580 * 10581 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10582 * this method will create a bitmap of the same size as this view. Because this bitmap 10583 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10584 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10585 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10586 * size than the view. This implies that your application must be able to handle this 10587 * size.</p> 10588 * 10589 * <p>You should avoid calling this method when hardware acceleration is enabled. If 10590 * you do not need the drawing cache bitmap, calling this method will increase memory 10591 * usage and cause the view to be rendered in software once, thus negatively impacting 10592 * performance.</p> 10593 * 10594 * @see #getDrawingCache() 10595 * @see #destroyDrawingCache() 10596 */ 10597 public void buildDrawingCache(boolean autoScale) { 10598 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 10599 mDrawingCache == null : mUnscaledDrawingCache == null)) { 10600 mCachingFailed = false; 10601 10602 if (ViewDebug.TRACE_HIERARCHY) { 10603 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 10604 } 10605 10606 int width = mRight - mLeft; 10607 int height = mBottom - mTop; 10608 10609 final AttachInfo attachInfo = mAttachInfo; 10610 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 10611 10612 if (autoScale && scalingRequired) { 10613 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 10614 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 10615 } 10616 10617 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 10618 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 10619 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 10620 10621 if (width <= 0 || height <= 0 || 10622 // Projected bitmap size in bytes 10623 (width * height * (opaque && !use32BitCache ? 2 : 4) > 10624 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 10625 destroyDrawingCache(); 10626 mCachingFailed = true; 10627 return; 10628 } 10629 10630 boolean clear = true; 10631 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 10632 10633 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 10634 Bitmap.Config quality; 10635 if (!opaque) { 10636 // Never pick ARGB_4444 because it looks awful 10637 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 10638 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 10639 case DRAWING_CACHE_QUALITY_AUTO: 10640 quality = Bitmap.Config.ARGB_8888; 10641 break; 10642 case DRAWING_CACHE_QUALITY_LOW: 10643 quality = Bitmap.Config.ARGB_8888; 10644 break; 10645 case DRAWING_CACHE_QUALITY_HIGH: 10646 quality = Bitmap.Config.ARGB_8888; 10647 break; 10648 default: 10649 quality = Bitmap.Config.ARGB_8888; 10650 break; 10651 } 10652 } else { 10653 // Optimization for translucent windows 10654 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 10655 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 10656 } 10657 10658 // Try to cleanup memory 10659 if (bitmap != null) bitmap.recycle(); 10660 10661 try { 10662 bitmap = Bitmap.createBitmap(width, height, quality); 10663 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 10664 if (autoScale) { 10665 mDrawingCache = bitmap; 10666 } else { 10667 mUnscaledDrawingCache = bitmap; 10668 } 10669 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 10670 } catch (OutOfMemoryError e) { 10671 // If there is not enough memory to create the bitmap cache, just 10672 // ignore the issue as bitmap caches are not required to draw the 10673 // view hierarchy 10674 if (autoScale) { 10675 mDrawingCache = null; 10676 } else { 10677 mUnscaledDrawingCache = null; 10678 } 10679 mCachingFailed = true; 10680 return; 10681 } 10682 10683 clear = drawingCacheBackgroundColor != 0; 10684 } 10685 10686 Canvas canvas; 10687 if (attachInfo != null) { 10688 canvas = attachInfo.mCanvas; 10689 if (canvas == null) { 10690 canvas = new Canvas(); 10691 } 10692 canvas.setBitmap(bitmap); 10693 // Temporarily clobber the cached Canvas in case one of our children 10694 // is also using a drawing cache. Without this, the children would 10695 // steal the canvas by attaching their own bitmap to it and bad, bad 10696 // thing would happen (invisible views, corrupted drawings, etc.) 10697 attachInfo.mCanvas = null; 10698 } else { 10699 // This case should hopefully never or seldom happen 10700 canvas = new Canvas(bitmap); 10701 } 10702 10703 if (clear) { 10704 bitmap.eraseColor(drawingCacheBackgroundColor); 10705 } 10706 10707 computeScroll(); 10708 final int restoreCount = canvas.save(); 10709 10710 if (autoScale && scalingRequired) { 10711 final float scale = attachInfo.mApplicationScale; 10712 canvas.scale(scale, scale); 10713 } 10714 10715 canvas.translate(-mScrollX, -mScrollY); 10716 10717 mPrivateFlags |= DRAWN; 10718 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 10719 mLayerType != LAYER_TYPE_NONE) { 10720 mPrivateFlags |= DRAWING_CACHE_VALID; 10721 } 10722 10723 // Fast path for layouts with no backgrounds 10724 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10725 if (ViewDebug.TRACE_HIERARCHY) { 10726 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 10727 } 10728 mPrivateFlags &= ~DIRTY_MASK; 10729 dispatchDraw(canvas); 10730 } else { 10731 draw(canvas); 10732 } 10733 10734 canvas.restoreToCount(restoreCount); 10735 canvas.setBitmap(null); 10736 10737 if (attachInfo != null) { 10738 // Restore the cached Canvas for our siblings 10739 attachInfo.mCanvas = canvas; 10740 } 10741 } 10742 } 10743 10744 /** 10745 * Create a snapshot of the view into a bitmap. We should probably make 10746 * some form of this public, but should think about the API. 10747 */ 10748 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 10749 int width = mRight - mLeft; 10750 int height = mBottom - mTop; 10751 10752 final AttachInfo attachInfo = mAttachInfo; 10753 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 10754 width = (int) ((width * scale) + 0.5f); 10755 height = (int) ((height * scale) + 0.5f); 10756 10757 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 10758 if (bitmap == null) { 10759 throw new OutOfMemoryError(); 10760 } 10761 10762 Resources resources = getResources(); 10763 if (resources != null) { 10764 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 10765 } 10766 10767 Canvas canvas; 10768 if (attachInfo != null) { 10769 canvas = attachInfo.mCanvas; 10770 if (canvas == null) { 10771 canvas = new Canvas(); 10772 } 10773 canvas.setBitmap(bitmap); 10774 // Temporarily clobber the cached Canvas in case one of our children 10775 // is also using a drawing cache. Without this, the children would 10776 // steal the canvas by attaching their own bitmap to it and bad, bad 10777 // things would happen (invisible views, corrupted drawings, etc.) 10778 attachInfo.mCanvas = null; 10779 } else { 10780 // This case should hopefully never or seldom happen 10781 canvas = new Canvas(bitmap); 10782 } 10783 10784 if ((backgroundColor & 0xff000000) != 0) { 10785 bitmap.eraseColor(backgroundColor); 10786 } 10787 10788 computeScroll(); 10789 final int restoreCount = canvas.save(); 10790 canvas.scale(scale, scale); 10791 canvas.translate(-mScrollX, -mScrollY); 10792 10793 // Temporarily remove the dirty mask 10794 int flags = mPrivateFlags; 10795 mPrivateFlags &= ~DIRTY_MASK; 10796 10797 // Fast path for layouts with no backgrounds 10798 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10799 dispatchDraw(canvas); 10800 } else { 10801 draw(canvas); 10802 } 10803 10804 mPrivateFlags = flags; 10805 10806 canvas.restoreToCount(restoreCount); 10807 canvas.setBitmap(null); 10808 10809 if (attachInfo != null) { 10810 // Restore the cached Canvas for our siblings 10811 attachInfo.mCanvas = canvas; 10812 } 10813 10814 return bitmap; 10815 } 10816 10817 /** 10818 * Indicates whether this View is currently in edit mode. A View is usually 10819 * in edit mode when displayed within a developer tool. For instance, if 10820 * this View is being drawn by a visual user interface builder, this method 10821 * should return true. 10822 * 10823 * Subclasses should check the return value of this method to provide 10824 * different behaviors if their normal behavior might interfere with the 10825 * host environment. For instance: the class spawns a thread in its 10826 * constructor, the drawing code relies on device-specific features, etc. 10827 * 10828 * This method is usually checked in the drawing code of custom widgets. 10829 * 10830 * @return True if this View is in edit mode, false otherwise. 10831 */ 10832 public boolean isInEditMode() { 10833 return false; 10834 } 10835 10836 /** 10837 * If the View draws content inside its padding and enables fading edges, 10838 * it needs to support padding offsets. Padding offsets are added to the 10839 * fading edges to extend the length of the fade so that it covers pixels 10840 * drawn inside the padding. 10841 * 10842 * Subclasses of this class should override this method if they need 10843 * to draw content inside the padding. 10844 * 10845 * @return True if padding offset must be applied, false otherwise. 10846 * 10847 * @see #getLeftPaddingOffset() 10848 * @see #getRightPaddingOffset() 10849 * @see #getTopPaddingOffset() 10850 * @see #getBottomPaddingOffset() 10851 * 10852 * @since CURRENT 10853 */ 10854 protected boolean isPaddingOffsetRequired() { 10855 return false; 10856 } 10857 10858 /** 10859 * Amount by which to extend the left fading region. Called only when 10860 * {@link #isPaddingOffsetRequired()} returns true. 10861 * 10862 * @return The left padding offset in pixels. 10863 * 10864 * @see #isPaddingOffsetRequired() 10865 * 10866 * @since CURRENT 10867 */ 10868 protected int getLeftPaddingOffset() { 10869 return 0; 10870 } 10871 10872 /** 10873 * Amount by which to extend the right fading region. Called only when 10874 * {@link #isPaddingOffsetRequired()} returns true. 10875 * 10876 * @return The right padding offset in pixels. 10877 * 10878 * @see #isPaddingOffsetRequired() 10879 * 10880 * @since CURRENT 10881 */ 10882 protected int getRightPaddingOffset() { 10883 return 0; 10884 } 10885 10886 /** 10887 * Amount by which to extend the top fading region. Called only when 10888 * {@link #isPaddingOffsetRequired()} returns true. 10889 * 10890 * @return The top padding offset in pixels. 10891 * 10892 * @see #isPaddingOffsetRequired() 10893 * 10894 * @since CURRENT 10895 */ 10896 protected int getTopPaddingOffset() { 10897 return 0; 10898 } 10899 10900 /** 10901 * Amount by which to extend the bottom fading region. Called only when 10902 * {@link #isPaddingOffsetRequired()} returns true. 10903 * 10904 * @return The bottom padding offset in pixels. 10905 * 10906 * @see #isPaddingOffsetRequired() 10907 * 10908 * @since CURRENT 10909 */ 10910 protected int getBottomPaddingOffset() { 10911 return 0; 10912 } 10913 10914 /** 10915 * @hide 10916 * @param offsetRequired 10917 */ 10918 protected int getFadeTop(boolean offsetRequired) { 10919 int top = mPaddingTop; 10920 if (offsetRequired) top += getTopPaddingOffset(); 10921 return top; 10922 } 10923 10924 /** 10925 * @hide 10926 * @param offsetRequired 10927 */ 10928 protected int getFadeHeight(boolean offsetRequired) { 10929 int padding = mPaddingTop; 10930 if (offsetRequired) padding += getTopPaddingOffset(); 10931 return mBottom - mTop - mPaddingBottom - padding; 10932 } 10933 10934 /** 10935 * <p>Indicates whether this view is attached to an hardware accelerated 10936 * window or not.</p> 10937 * 10938 * <p>Even if this method returns true, it does not mean that every call 10939 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 10940 * accelerated {@link android.graphics.Canvas}. For instance, if this view 10941 * is drawn onto an offscren {@link android.graphics.Bitmap} and its 10942 * window is hardware accelerated, 10943 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 10944 * return false, and this method will return true.</p> 10945 * 10946 * @return True if the view is attached to a window and the window is 10947 * hardware accelerated; false in any other case. 10948 */ 10949 public boolean isHardwareAccelerated() { 10950 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 10951 } 10952 10953 /** 10954 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 10955 * This draw() method is an implementation detail and is not intended to be overridden or 10956 * to be called from anywhere else other than ViewGroup.drawChild(). 10957 */ 10958 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 10959 boolean more = false; 10960 10961 final int cl = mLeft; 10962 final int ct = mTop; 10963 final int cr = mRight; 10964 final int cb = mBottom; 10965 10966 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 10967 10968 final int flags = parent.mGroupFlags; 10969 10970 if ((flags & parent.FLAG_CLEAR_TRANSFORMATION) == parent.FLAG_CLEAR_TRANSFORMATION) { 10971 parent.mChildTransformation.clear(); 10972 parent.mGroupFlags &= ~parent.FLAG_CLEAR_TRANSFORMATION; 10973 } 10974 10975 Transformation transformToApply = null; 10976 Transformation invalidationTransform; 10977 final Animation a = getAnimation(); 10978 boolean concatMatrix = false; 10979 10980 boolean scalingRequired = false; 10981 boolean caching; 10982 int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE; 10983 10984 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 10985 if ((flags & parent.FLAG_CHILDREN_DRAWN_WITH_CACHE) == parent.FLAG_CHILDREN_DRAWN_WITH_CACHE || 10986 (flags & parent.FLAG_ALWAYS_DRAWN_WITH_CACHE) == parent.FLAG_ALWAYS_DRAWN_WITH_CACHE) { 10987 caching = true; 10988 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 10989 } else { 10990 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 10991 } 10992 10993 if (a != null) { 10994 final boolean initialized = a.isInitialized(); 10995 if (!initialized) { 10996 a.initialize(cr - cl, cb - ct, getWidth(), getHeight()); 10997 a.initializeInvalidateRegion(0, 0, cr - cl, cb - ct); 10998 onAnimationStart(); 10999 } 11000 11001 more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f); 11002 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 11003 if (parent.mInvalidationTransformation == null) { 11004 parent.mInvalidationTransformation = new Transformation(); 11005 } 11006 invalidationTransform = parent.mInvalidationTransformation; 11007 a.getTransformation(drawingTime, invalidationTransform, 1f); 11008 } else { 11009 invalidationTransform = parent.mChildTransformation; 11010 } 11011 transformToApply = parent.mChildTransformation; 11012 11013 concatMatrix = a.willChangeTransformationMatrix(); 11014 11015 if (more) { 11016 if (!a.willChangeBounds()) { 11017 if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) == 11018 parent.FLAG_OPTIMIZE_INVALIDATE) { 11019 parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED; 11020 } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) { 11021 // The child need to draw an animation, potentially offscreen, so 11022 // make sure we do not cancel invalidate requests 11023 parent.mPrivateFlags |= DRAW_ANIMATION; 11024 invalidate(cl, ct, cr, cb); 11025 } 11026 } else { 11027 if (parent.mInvalidateRegion == null) { 11028 parent.mInvalidateRegion = new RectF(); 11029 } 11030 final RectF region = parent.mInvalidateRegion; 11031 a.getInvalidateRegion(0, 0, cr - cl, cb - ct, region, invalidationTransform); 11032 11033 // The child need to draw an animation, potentially offscreen, so 11034 // make sure we do not cancel invalidate requests 11035 parent.mPrivateFlags |= DRAW_ANIMATION; 11036 11037 final int left = cl + (int) region.left; 11038 final int top = ct + (int) region.top; 11039 invalidate(left, top, left + (int) (region.width() + .5f), 11040 top + (int) (region.height() + .5f)); 11041 } 11042 } 11043 } else if ((flags & parent.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) == 11044 parent.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) { 11045 final boolean hasTransform = parent.getChildStaticTransformation(this, parent.mChildTransformation); 11046 if (hasTransform) { 11047 final int transformType = parent.mChildTransformation.getTransformationType(); 11048 transformToApply = transformType != Transformation.TYPE_IDENTITY ? 11049 parent.mChildTransformation : null; 11050 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 11051 } 11052 } 11053 11054 concatMatrix |= !childHasIdentityMatrix; 11055 11056 // Sets the flag as early as possible to allow draw() implementations 11057 // to call invalidate() successfully when doing animations 11058 mPrivateFlags |= DRAWN; 11059 11060 if (!concatMatrix && canvas.quickReject(cl, ct, cr, cb, Canvas.EdgeType.BW) && 11061 (mPrivateFlags & DRAW_ANIMATION) == 0) { 11062 return more; 11063 } 11064 11065 if (hardwareAccelerated) { 11066 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 11067 // retain the flag's value temporarily in the mRecreateDisplayList flag 11068 mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED; 11069 mPrivateFlags &= ~INVALIDATED; 11070 } 11071 11072 computeScroll(); 11073 11074 final int sx = mScrollX; 11075 final int sy = mScrollY; 11076 11077 DisplayList displayList = null; 11078 Bitmap cache = null; 11079 boolean hasDisplayList = false; 11080 if (caching) { 11081 if (!hardwareAccelerated) { 11082 if (layerType != LAYER_TYPE_NONE) { 11083 layerType = LAYER_TYPE_SOFTWARE; 11084 buildDrawingCache(true); 11085 } 11086 cache = getDrawingCache(true); 11087 } else { 11088 switch (layerType) { 11089 case LAYER_TYPE_SOFTWARE: 11090 buildDrawingCache(true); 11091 cache = getDrawingCache(true); 11092 break; 11093 case LAYER_TYPE_NONE: 11094 // Delay getting the display list until animation-driven alpha values are 11095 // set up and possibly passed on to the view 11096 hasDisplayList = canHaveDisplayList(); 11097 break; 11098 } 11099 } 11100 } 11101 11102 final boolean hasNoCache = cache == null || hasDisplayList; 11103 final boolean offsetForScroll = cache == null && !hasDisplayList && 11104 layerType != LAYER_TYPE_HARDWARE; 11105 11106 final int restoreTo = canvas.save(); 11107 if (offsetForScroll) { 11108 canvas.translate(cl - sx, ct - sy); 11109 } else { 11110 canvas.translate(cl, ct); 11111 if (scalingRequired) { 11112 // mAttachInfo cannot be null, otherwise scalingRequired == false 11113 final float scale = 1.0f / mAttachInfo.mApplicationScale; 11114 canvas.scale(scale, scale); 11115 } 11116 } 11117 11118 float alpha = getAlpha(); 11119 if (transformToApply != null || alpha < 1.0f || !hasIdentityMatrix()) { 11120 if (transformToApply != null || !childHasIdentityMatrix) { 11121 int transX = 0; 11122 int transY = 0; 11123 11124 if (offsetForScroll) { 11125 transX = -sx; 11126 transY = -sy; 11127 } 11128 11129 if (transformToApply != null) { 11130 if (concatMatrix) { 11131 // Undo the scroll translation, apply the transformation matrix, 11132 // then redo the scroll translate to get the correct result. 11133 canvas.translate(-transX, -transY); 11134 canvas.concat(transformToApply.getMatrix()); 11135 canvas.translate(transX, transY); 11136 parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION; 11137 } 11138 11139 float transformAlpha = transformToApply.getAlpha(); 11140 if (transformAlpha < 1.0f) { 11141 alpha *= transformToApply.getAlpha(); 11142 parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION; 11143 } 11144 } 11145 11146 if (!childHasIdentityMatrix) { 11147 canvas.translate(-transX, -transY); 11148 canvas.concat(getMatrix()); 11149 canvas.translate(transX, transY); 11150 } 11151 } 11152 11153 if (alpha < 1.0f) { 11154 parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION; 11155 if (hasNoCache) { 11156 final int multipliedAlpha = (int) (255 * alpha); 11157 if (!onSetAlpha(multipliedAlpha)) { 11158 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 11159 if ((flags & parent.FLAG_CLIP_CHILDREN) == parent.FLAG_CLIP_CHILDREN || 11160 layerType != LAYER_TYPE_NONE) { 11161 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 11162 } 11163 if (layerType == LAYER_TYPE_NONE) { 11164 final int scrollX = hasDisplayList ? 0 : sx; 11165 final int scrollY = hasDisplayList ? 0 : sy; 11166 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + cr - cl, 11167 scrollY + cb - ct, multipliedAlpha, layerFlags); 11168 } 11169 } else { 11170 // Alpha is handled by the child directly, clobber the layer's alpha 11171 mPrivateFlags |= ALPHA_SET; 11172 } 11173 } 11174 } 11175 } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) { 11176 onSetAlpha(255); 11177 mPrivateFlags &= ~ALPHA_SET; 11178 } 11179 11180 if ((flags & parent.FLAG_CLIP_CHILDREN) == parent.FLAG_CLIP_CHILDREN) { 11181 if (offsetForScroll) { 11182 canvas.clipRect(sx, sy, sx + (cr - cl), sy + (cb - ct)); 11183 } else { 11184 if (!scalingRequired || cache == null) { 11185 canvas.clipRect(0, 0, cr - cl, cb - ct); 11186 } else { 11187 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 11188 } 11189 } 11190 } 11191 11192 if (hasDisplayList) { 11193 displayList = getDisplayList(); 11194 if (!displayList.isValid()) { 11195 // Uncommon, but possible. If a view is removed from the hierarchy during the call 11196 // to getDisplayList(), the display list will be marked invalid and we should not 11197 // try to use it again. 11198 displayList = null; 11199 hasDisplayList = false; 11200 } 11201 } 11202 11203 if (hasNoCache) { 11204 boolean layerRendered = false; 11205 if (layerType == LAYER_TYPE_HARDWARE) { 11206 final HardwareLayer layer = getHardwareLayer(); 11207 if (layer != null && layer.isValid()) { 11208 mLayerPaint.setAlpha((int) (alpha * 255)); 11209 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 11210 layerRendered = true; 11211 } else { 11212 final int scrollX = hasDisplayList ? 0 : sx; 11213 final int scrollY = hasDisplayList ? 0 : sy; 11214 canvas.saveLayer(scrollX, scrollY, 11215 scrollX + cr - cl, scrollY + cb - ct, mLayerPaint, 11216 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 11217 } 11218 } 11219 11220 if (!layerRendered) { 11221 if (!hasDisplayList) { 11222 // Fast path for layouts with no backgrounds 11223 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 11224 if (ViewDebug.TRACE_HIERARCHY) { 11225 ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW); 11226 } 11227 mPrivateFlags &= ~DIRTY_MASK; 11228 dispatchDraw(canvas); 11229 } else { 11230 draw(canvas); 11231 } 11232 } else { 11233 mPrivateFlags &= ~DIRTY_MASK; 11234 ((HardwareCanvas) canvas).drawDisplayList(displayList, cr - cl, cb - ct, null); 11235 } 11236 } 11237 } else if (cache != null) { 11238 mPrivateFlags &= ~DIRTY_MASK; 11239 Paint cachePaint; 11240 11241 if (layerType == LAYER_TYPE_NONE) { 11242 cachePaint = parent.mCachePaint; 11243 if (cachePaint == null) { 11244 cachePaint = new Paint(); 11245 cachePaint.setDither(false); 11246 parent.mCachePaint = cachePaint; 11247 } 11248 if (alpha < 1.0f) { 11249 cachePaint.setAlpha((int) (alpha * 255)); 11250 parent.mGroupFlags |= parent.FLAG_ALPHA_LOWER_THAN_ONE; 11251 } else if ((flags & parent.FLAG_ALPHA_LOWER_THAN_ONE) == parent.FLAG_ALPHA_LOWER_THAN_ONE) { 11252 cachePaint.setAlpha(255); 11253 parent.mGroupFlags &= ~parent.FLAG_ALPHA_LOWER_THAN_ONE; 11254 } 11255 } else { 11256 cachePaint = mLayerPaint; 11257 cachePaint.setAlpha((int) (alpha * 255)); 11258 } 11259 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 11260 } 11261 11262 canvas.restoreToCount(restoreTo); 11263 11264 if (a != null && !more) { 11265 if (!hardwareAccelerated && !a.getFillAfter()) { 11266 onSetAlpha(255); 11267 } 11268 parent.finishAnimatingView(this, a); 11269 } 11270 11271 if (more && hardwareAccelerated) { 11272 // invalidation is the trigger to recreate display lists, so if we're using 11273 // display lists to render, force an invalidate to allow the animation to 11274 // continue drawing another frame 11275 parent.invalidate(true); 11276 if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) { 11277 // alpha animations should cause the child to recreate its display list 11278 invalidate(true); 11279 } 11280 } 11281 11282 mRecreateDisplayList = false; 11283 11284 return more; 11285 } 11286 11287 /** 11288 * Manually render this view (and all of its children) to the given Canvas. 11289 * The view must have already done a full layout before this function is 11290 * called. When implementing a view, implement 11291 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 11292 * If you do need to override this method, call the superclass version. 11293 * 11294 * @param canvas The Canvas to which the View is rendered. 11295 */ 11296 public void draw(Canvas canvas) { 11297 if (ViewDebug.TRACE_HIERARCHY) { 11298 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 11299 } 11300 11301 final int privateFlags = mPrivateFlags; 11302 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 11303 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 11304 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 11305 11306 /* 11307 * Draw traversal performs several drawing steps which must be executed 11308 * in the appropriate order: 11309 * 11310 * 1. Draw the background 11311 * 2. If necessary, save the canvas' layers to prepare for fading 11312 * 3. Draw view's content 11313 * 4. Draw children 11314 * 5. If necessary, draw the fading edges and restore layers 11315 * 6. Draw decorations (scrollbars for instance) 11316 */ 11317 11318 // Step 1, draw the background, if needed 11319 int saveCount; 11320 11321 if (!dirtyOpaque) { 11322 final Drawable background = mBGDrawable; 11323 if (background != null) { 11324 final int scrollX = mScrollX; 11325 final int scrollY = mScrollY; 11326 11327 if (mBackgroundSizeChanged) { 11328 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 11329 mBackgroundSizeChanged = false; 11330 } 11331 11332 if ((scrollX | scrollY) == 0) { 11333 background.draw(canvas); 11334 } else { 11335 canvas.translate(scrollX, scrollY); 11336 background.draw(canvas); 11337 canvas.translate(-scrollX, -scrollY); 11338 } 11339 } 11340 } 11341 11342 // skip step 2 & 5 if possible (common case) 11343 final int viewFlags = mViewFlags; 11344 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 11345 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 11346 if (!verticalEdges && !horizontalEdges) { 11347 // Step 3, draw the content 11348 if (!dirtyOpaque) onDraw(canvas); 11349 11350 // Step 4, draw the children 11351 dispatchDraw(canvas); 11352 11353 // Step 6, draw decorations (scrollbars) 11354 onDrawScrollBars(canvas); 11355 11356 // we're done... 11357 return; 11358 } 11359 11360 /* 11361 * Here we do the full fledged routine... 11362 * (this is an uncommon case where speed matters less, 11363 * this is why we repeat some of the tests that have been 11364 * done above) 11365 */ 11366 11367 boolean drawTop = false; 11368 boolean drawBottom = false; 11369 boolean drawLeft = false; 11370 boolean drawRight = false; 11371 11372 float topFadeStrength = 0.0f; 11373 float bottomFadeStrength = 0.0f; 11374 float leftFadeStrength = 0.0f; 11375 float rightFadeStrength = 0.0f; 11376 11377 // Step 2, save the canvas' layers 11378 int paddingLeft = mPaddingLeft; 11379 11380 final boolean offsetRequired = isPaddingOffsetRequired(); 11381 if (offsetRequired) { 11382 paddingLeft += getLeftPaddingOffset(); 11383 } 11384 11385 int left = mScrollX + paddingLeft; 11386 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 11387 int top = mScrollY + getFadeTop(offsetRequired); 11388 int bottom = top + getFadeHeight(offsetRequired); 11389 11390 if (offsetRequired) { 11391 right += getRightPaddingOffset(); 11392 bottom += getBottomPaddingOffset(); 11393 } 11394 11395 final ScrollabilityCache scrollabilityCache = mScrollCache; 11396 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 11397 int length = (int) fadeHeight; 11398 11399 // clip the fade length if top and bottom fades overlap 11400 // overlapping fades produce odd-looking artifacts 11401 if (verticalEdges && (top + length > bottom - length)) { 11402 length = (bottom - top) / 2; 11403 } 11404 11405 // also clip horizontal fades if necessary 11406 if (horizontalEdges && (left + length > right - length)) { 11407 length = (right - left) / 2; 11408 } 11409 11410 if (verticalEdges) { 11411 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 11412 drawTop = topFadeStrength * fadeHeight > 1.0f; 11413 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 11414 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 11415 } 11416 11417 if (horizontalEdges) { 11418 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 11419 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 11420 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 11421 drawRight = rightFadeStrength * fadeHeight > 1.0f; 11422 } 11423 11424 saveCount = canvas.getSaveCount(); 11425 11426 int solidColor = getSolidColor(); 11427 if (solidColor == 0) { 11428 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 11429 11430 if (drawTop) { 11431 canvas.saveLayer(left, top, right, top + length, null, flags); 11432 } 11433 11434 if (drawBottom) { 11435 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 11436 } 11437 11438 if (drawLeft) { 11439 canvas.saveLayer(left, top, left + length, bottom, null, flags); 11440 } 11441 11442 if (drawRight) { 11443 canvas.saveLayer(right - length, top, right, bottom, null, flags); 11444 } 11445 } else { 11446 scrollabilityCache.setFadeColor(solidColor); 11447 } 11448 11449 // Step 3, draw the content 11450 if (!dirtyOpaque) onDraw(canvas); 11451 11452 // Step 4, draw the children 11453 dispatchDraw(canvas); 11454 11455 // Step 5, draw the fade effect and restore layers 11456 final Paint p = scrollabilityCache.paint; 11457 final Matrix matrix = scrollabilityCache.matrix; 11458 final Shader fade = scrollabilityCache.shader; 11459 11460 if (drawTop) { 11461 matrix.setScale(1, fadeHeight * topFadeStrength); 11462 matrix.postTranslate(left, top); 11463 fade.setLocalMatrix(matrix); 11464 canvas.drawRect(left, top, right, top + length, p); 11465 } 11466 11467 if (drawBottom) { 11468 matrix.setScale(1, fadeHeight * bottomFadeStrength); 11469 matrix.postRotate(180); 11470 matrix.postTranslate(left, bottom); 11471 fade.setLocalMatrix(matrix); 11472 canvas.drawRect(left, bottom - length, right, bottom, p); 11473 } 11474 11475 if (drawLeft) { 11476 matrix.setScale(1, fadeHeight * leftFadeStrength); 11477 matrix.postRotate(-90); 11478 matrix.postTranslate(left, top); 11479 fade.setLocalMatrix(matrix); 11480 canvas.drawRect(left, top, left + length, bottom, p); 11481 } 11482 11483 if (drawRight) { 11484 matrix.setScale(1, fadeHeight * rightFadeStrength); 11485 matrix.postRotate(90); 11486 matrix.postTranslate(right, top); 11487 fade.setLocalMatrix(matrix); 11488 canvas.drawRect(right - length, top, right, bottom, p); 11489 } 11490 11491 canvas.restoreToCount(saveCount); 11492 11493 // Step 6, draw decorations (scrollbars) 11494 onDrawScrollBars(canvas); 11495 } 11496 11497 /** 11498 * Override this if your view is known to always be drawn on top of a solid color background, 11499 * and needs to draw fading edges. Returning a non-zero color enables the view system to 11500 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 11501 * should be set to 0xFF. 11502 * 11503 * @see #setVerticalFadingEdgeEnabled(boolean) 11504 * @see #setHorizontalFadingEdgeEnabled(boolean) 11505 * 11506 * @return The known solid color background for this view, or 0 if the color may vary 11507 */ 11508 @ViewDebug.ExportedProperty(category = "drawing") 11509 public int getSolidColor() { 11510 return 0; 11511 } 11512 11513 /** 11514 * Build a human readable string representation of the specified view flags. 11515 * 11516 * @param flags the view flags to convert to a string 11517 * @return a String representing the supplied flags 11518 */ 11519 private static String printFlags(int flags) { 11520 String output = ""; 11521 int numFlags = 0; 11522 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 11523 output += "TAKES_FOCUS"; 11524 numFlags++; 11525 } 11526 11527 switch (flags & VISIBILITY_MASK) { 11528 case INVISIBLE: 11529 if (numFlags > 0) { 11530 output += " "; 11531 } 11532 output += "INVISIBLE"; 11533 // USELESS HERE numFlags++; 11534 break; 11535 case GONE: 11536 if (numFlags > 0) { 11537 output += " "; 11538 } 11539 output += "GONE"; 11540 // USELESS HERE numFlags++; 11541 break; 11542 default: 11543 break; 11544 } 11545 return output; 11546 } 11547 11548 /** 11549 * Build a human readable string representation of the specified private 11550 * view flags. 11551 * 11552 * @param privateFlags the private view flags to convert to a string 11553 * @return a String representing the supplied flags 11554 */ 11555 private static String printPrivateFlags(int privateFlags) { 11556 String output = ""; 11557 int numFlags = 0; 11558 11559 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 11560 output += "WANTS_FOCUS"; 11561 numFlags++; 11562 } 11563 11564 if ((privateFlags & FOCUSED) == FOCUSED) { 11565 if (numFlags > 0) { 11566 output += " "; 11567 } 11568 output += "FOCUSED"; 11569 numFlags++; 11570 } 11571 11572 if ((privateFlags & SELECTED) == SELECTED) { 11573 if (numFlags > 0) { 11574 output += " "; 11575 } 11576 output += "SELECTED"; 11577 numFlags++; 11578 } 11579 11580 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 11581 if (numFlags > 0) { 11582 output += " "; 11583 } 11584 output += "IS_ROOT_NAMESPACE"; 11585 numFlags++; 11586 } 11587 11588 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 11589 if (numFlags > 0) { 11590 output += " "; 11591 } 11592 output += "HAS_BOUNDS"; 11593 numFlags++; 11594 } 11595 11596 if ((privateFlags & DRAWN) == DRAWN) { 11597 if (numFlags > 0) { 11598 output += " "; 11599 } 11600 output += "DRAWN"; 11601 // USELESS HERE numFlags++; 11602 } 11603 return output; 11604 } 11605 11606 /** 11607 * <p>Indicates whether or not this view's layout will be requested during 11608 * the next hierarchy layout pass.</p> 11609 * 11610 * @return true if the layout will be forced during next layout pass 11611 */ 11612 public boolean isLayoutRequested() { 11613 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 11614 } 11615 11616 /** 11617 * Assign a size and position to a view and all of its 11618 * descendants 11619 * 11620 * <p>This is the second phase of the layout mechanism. 11621 * (The first is measuring). In this phase, each parent calls 11622 * layout on all of its children to position them. 11623 * This is typically done using the child measurements 11624 * that were stored in the measure pass().</p> 11625 * 11626 * <p>Derived classes should not override this method. 11627 * Derived classes with children should override 11628 * onLayout. In that method, they should 11629 * call layout on each of their children.</p> 11630 * 11631 * @param l Left position, relative to parent 11632 * @param t Top position, relative to parent 11633 * @param r Right position, relative to parent 11634 * @param b Bottom position, relative to parent 11635 */ 11636 @SuppressWarnings({"unchecked"}) 11637 public void layout(int l, int t, int r, int b) { 11638 int oldL = mLeft; 11639 int oldT = mTop; 11640 int oldB = mBottom; 11641 int oldR = mRight; 11642 boolean changed = setFrame(l, t, r, b); 11643 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 11644 if (ViewDebug.TRACE_HIERARCHY) { 11645 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 11646 } 11647 11648 onLayout(changed, l, t, r, b); 11649 mPrivateFlags &= ~LAYOUT_REQUIRED; 11650 11651 ListenerInfo li = mListenerInfo; 11652 if (li != null && li.mOnLayoutChangeListeners != null) { 11653 ArrayList<OnLayoutChangeListener> listenersCopy = 11654 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 11655 int numListeners = listenersCopy.size(); 11656 for (int i = 0; i < numListeners; ++i) { 11657 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 11658 } 11659 } 11660 } 11661 mPrivateFlags &= ~FORCE_LAYOUT; 11662 } 11663 11664 /** 11665 * Called from layout when this view should 11666 * assign a size and position to each of its children. 11667 * 11668 * Derived classes with children should override 11669 * this method and call layout on each of 11670 * their children. 11671 * @param changed This is a new size or position for this view 11672 * @param left Left position, relative to parent 11673 * @param top Top position, relative to parent 11674 * @param right Right position, relative to parent 11675 * @param bottom Bottom position, relative to parent 11676 */ 11677 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 11678 } 11679 11680 /** 11681 * Assign a size and position to this view. 11682 * 11683 * This is called from layout. 11684 * 11685 * @param left Left position, relative to parent 11686 * @param top Top position, relative to parent 11687 * @param right Right position, relative to parent 11688 * @param bottom Bottom position, relative to parent 11689 * @return true if the new size and position are different than the 11690 * previous ones 11691 * {@hide} 11692 */ 11693 protected boolean setFrame(int left, int top, int right, int bottom) { 11694 boolean changed = false; 11695 11696 if (DBG) { 11697 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 11698 + right + "," + bottom + ")"); 11699 } 11700 11701 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 11702 changed = true; 11703 11704 // Remember our drawn bit 11705 int drawn = mPrivateFlags & DRAWN; 11706 11707 int oldWidth = mRight - mLeft; 11708 int oldHeight = mBottom - mTop; 11709 int newWidth = right - left; 11710 int newHeight = bottom - top; 11711 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 11712 11713 // Invalidate our old position 11714 invalidate(sizeChanged); 11715 11716 mLeft = left; 11717 mTop = top; 11718 mRight = right; 11719 mBottom = bottom; 11720 11721 mPrivateFlags |= HAS_BOUNDS; 11722 11723 11724 if (sizeChanged) { 11725 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 11726 // A change in dimension means an auto-centered pivot point changes, too 11727 if (mTransformationInfo != null) { 11728 mTransformationInfo.mMatrixDirty = true; 11729 } 11730 } 11731 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 11732 } 11733 11734 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 11735 // If we are visible, force the DRAWN bit to on so that 11736 // this invalidate will go through (at least to our parent). 11737 // This is because someone may have invalidated this view 11738 // before this call to setFrame came in, thereby clearing 11739 // the DRAWN bit. 11740 mPrivateFlags |= DRAWN; 11741 invalidate(sizeChanged); 11742 // parent display list may need to be recreated based on a change in the bounds 11743 // of any child 11744 invalidateParentCaches(); 11745 } 11746 11747 // Reset drawn bit to original value (invalidate turns it off) 11748 mPrivateFlags |= drawn; 11749 11750 mBackgroundSizeChanged = true; 11751 } 11752 return changed; 11753 } 11754 11755 /** 11756 * Finalize inflating a view from XML. This is called as the last phase 11757 * of inflation, after all child views have been added. 11758 * 11759 * <p>Even if the subclass overrides onFinishInflate, they should always be 11760 * sure to call the super method, so that we get called. 11761 */ 11762 protected void onFinishInflate() { 11763 } 11764 11765 /** 11766 * Returns the resources associated with this view. 11767 * 11768 * @return Resources object. 11769 */ 11770 public Resources getResources() { 11771 return mResources; 11772 } 11773 11774 /** 11775 * Invalidates the specified Drawable. 11776 * 11777 * @param drawable the drawable to invalidate 11778 */ 11779 public void invalidateDrawable(Drawable drawable) { 11780 if (verifyDrawable(drawable)) { 11781 final Rect dirty = drawable.getBounds(); 11782 final int scrollX = mScrollX; 11783 final int scrollY = mScrollY; 11784 11785 invalidate(dirty.left + scrollX, dirty.top + scrollY, 11786 dirty.right + scrollX, dirty.bottom + scrollY); 11787 } 11788 } 11789 11790 /** 11791 * Schedules an action on a drawable to occur at a specified time. 11792 * 11793 * @param who the recipient of the action 11794 * @param what the action to run on the drawable 11795 * @param when the time at which the action must occur. Uses the 11796 * {@link SystemClock#uptimeMillis} timebase. 11797 */ 11798 public void scheduleDrawable(Drawable who, Runnable what, long when) { 11799 if (verifyDrawable(who) && what != null) { 11800 if (mAttachInfo != null) { 11801 mAttachInfo.mHandler.postAtTime(what, who, when); 11802 } else { 11803 ViewRootImpl.getRunQueue().postDelayed(what, when - SystemClock.uptimeMillis()); 11804 } 11805 } 11806 } 11807 11808 /** 11809 * Cancels a scheduled action on a drawable. 11810 * 11811 * @param who the recipient of the action 11812 * @param what the action to cancel 11813 */ 11814 public void unscheduleDrawable(Drawable who, Runnable what) { 11815 if (verifyDrawable(who) && what != null) { 11816 if (mAttachInfo != null) { 11817 mAttachInfo.mHandler.removeCallbacks(what, who); 11818 } else { 11819 ViewRootImpl.getRunQueue().removeCallbacks(what); 11820 } 11821 } 11822 } 11823 11824 /** 11825 * Unschedule any events associated with the given Drawable. This can be 11826 * used when selecting a new Drawable into a view, so that the previous 11827 * one is completely unscheduled. 11828 * 11829 * @param who The Drawable to unschedule. 11830 * 11831 * @see #drawableStateChanged 11832 */ 11833 public void unscheduleDrawable(Drawable who) { 11834 if (mAttachInfo != null) { 11835 mAttachInfo.mHandler.removeCallbacksAndMessages(who); 11836 } 11837 } 11838 11839 /** 11840 * Return the layout direction of a given Drawable. 11841 * 11842 * @param who the Drawable to query 11843 * 11844 * @hide 11845 */ 11846 public int getResolvedLayoutDirection(Drawable who) { 11847 return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT; 11848 } 11849 11850 /** 11851 * If your view subclass is displaying its own Drawable objects, it should 11852 * override this function and return true for any Drawable it is 11853 * displaying. This allows animations for those drawables to be 11854 * scheduled. 11855 * 11856 * <p>Be sure to call through to the super class when overriding this 11857 * function. 11858 * 11859 * @param who The Drawable to verify. Return true if it is one you are 11860 * displaying, else return the result of calling through to the 11861 * super class. 11862 * 11863 * @return boolean If true than the Drawable is being displayed in the 11864 * view; else false and it is not allowed to animate. 11865 * 11866 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 11867 * @see #drawableStateChanged() 11868 */ 11869 protected boolean verifyDrawable(Drawable who) { 11870 return who == mBGDrawable; 11871 } 11872 11873 /** 11874 * This function is called whenever the state of the view changes in such 11875 * a way that it impacts the state of drawables being shown. 11876 * 11877 * <p>Be sure to call through to the superclass when overriding this 11878 * function. 11879 * 11880 * @see Drawable#setState(int[]) 11881 */ 11882 protected void drawableStateChanged() { 11883 Drawable d = mBGDrawable; 11884 if (d != null && d.isStateful()) { 11885 d.setState(getDrawableState()); 11886 } 11887 } 11888 11889 /** 11890 * Call this to force a view to update its drawable state. This will cause 11891 * drawableStateChanged to be called on this view. Views that are interested 11892 * in the new state should call getDrawableState. 11893 * 11894 * @see #drawableStateChanged 11895 * @see #getDrawableState 11896 */ 11897 public void refreshDrawableState() { 11898 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 11899 drawableStateChanged(); 11900 11901 ViewParent parent = mParent; 11902 if (parent != null) { 11903 parent.childDrawableStateChanged(this); 11904 } 11905 } 11906 11907 /** 11908 * Return an array of resource IDs of the drawable states representing the 11909 * current state of the view. 11910 * 11911 * @return The current drawable state 11912 * 11913 * @see Drawable#setState(int[]) 11914 * @see #drawableStateChanged() 11915 * @see #onCreateDrawableState(int) 11916 */ 11917 public final int[] getDrawableState() { 11918 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 11919 return mDrawableState; 11920 } else { 11921 mDrawableState = onCreateDrawableState(0); 11922 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 11923 return mDrawableState; 11924 } 11925 } 11926 11927 /** 11928 * Generate the new {@link android.graphics.drawable.Drawable} state for 11929 * this view. This is called by the view 11930 * system when the cached Drawable state is determined to be invalid. To 11931 * retrieve the current state, you should use {@link #getDrawableState}. 11932 * 11933 * @param extraSpace if non-zero, this is the number of extra entries you 11934 * would like in the returned array in which you can place your own 11935 * states. 11936 * 11937 * @return Returns an array holding the current {@link Drawable} state of 11938 * the view. 11939 * 11940 * @see #mergeDrawableStates(int[], int[]) 11941 */ 11942 protected int[] onCreateDrawableState(int extraSpace) { 11943 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 11944 mParent instanceof View) { 11945 return ((View) mParent).onCreateDrawableState(extraSpace); 11946 } 11947 11948 int[] drawableState; 11949 11950 int privateFlags = mPrivateFlags; 11951 11952 int viewStateIndex = 0; 11953 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 11954 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 11955 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 11956 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 11957 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 11958 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 11959 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 11960 HardwareRenderer.isAvailable()) { 11961 // This is set if HW acceleration is requested, even if the current 11962 // process doesn't allow it. This is just to allow app preview 11963 // windows to better match their app. 11964 viewStateIndex |= VIEW_STATE_ACCELERATED; 11965 } 11966 if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 11967 11968 final int privateFlags2 = mPrivateFlags2; 11969 if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 11970 if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 11971 11972 drawableState = VIEW_STATE_SETS[viewStateIndex]; 11973 11974 //noinspection ConstantIfStatement 11975 if (false) { 11976 Log.i("View", "drawableStateIndex=" + viewStateIndex); 11977 Log.i("View", toString() 11978 + " pressed=" + ((privateFlags & PRESSED) != 0) 11979 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 11980 + " fo=" + hasFocus() 11981 + " sl=" + ((privateFlags & SELECTED) != 0) 11982 + " wf=" + hasWindowFocus() 11983 + ": " + Arrays.toString(drawableState)); 11984 } 11985 11986 if (extraSpace == 0) { 11987 return drawableState; 11988 } 11989 11990 final int[] fullState; 11991 if (drawableState != null) { 11992 fullState = new int[drawableState.length + extraSpace]; 11993 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 11994 } else { 11995 fullState = new int[extraSpace]; 11996 } 11997 11998 return fullState; 11999 } 12000 12001 /** 12002 * Merge your own state values in <var>additionalState</var> into the base 12003 * state values <var>baseState</var> that were returned by 12004 * {@link #onCreateDrawableState(int)}. 12005 * 12006 * @param baseState The base state values returned by 12007 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 12008 * own additional state values. 12009 * 12010 * @param additionalState The additional state values you would like 12011 * added to <var>baseState</var>; this array is not modified. 12012 * 12013 * @return As a convenience, the <var>baseState</var> array you originally 12014 * passed into the function is returned. 12015 * 12016 * @see #onCreateDrawableState(int) 12017 */ 12018 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 12019 final int N = baseState.length; 12020 int i = N - 1; 12021 while (i >= 0 && baseState[i] == 0) { 12022 i--; 12023 } 12024 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 12025 return baseState; 12026 } 12027 12028 /** 12029 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 12030 * on all Drawable objects associated with this view. 12031 */ 12032 public void jumpDrawablesToCurrentState() { 12033 if (mBGDrawable != null) { 12034 mBGDrawable.jumpToCurrentState(); 12035 } 12036 } 12037 12038 /** 12039 * Sets the background color for this view. 12040 * @param color the color of the background 12041 */ 12042 @RemotableViewMethod 12043 public void setBackgroundColor(int color) { 12044 if (mBGDrawable instanceof ColorDrawable) { 12045 ((ColorDrawable) mBGDrawable).setColor(color); 12046 } else { 12047 setBackgroundDrawable(new ColorDrawable(color)); 12048 } 12049 } 12050 12051 /** 12052 * Set the background to a given resource. The resource should refer to 12053 * a Drawable object or 0 to remove the background. 12054 * @param resid The identifier of the resource. 12055 * @attr ref android.R.styleable#View_background 12056 */ 12057 @RemotableViewMethod 12058 public void setBackgroundResource(int resid) { 12059 if (resid != 0 && resid == mBackgroundResource) { 12060 return; 12061 } 12062 12063 Drawable d= null; 12064 if (resid != 0) { 12065 d = mResources.getDrawable(resid); 12066 } 12067 setBackgroundDrawable(d); 12068 12069 mBackgroundResource = resid; 12070 } 12071 12072 /** 12073 * Set the background to a given Drawable, or remove the background. If the 12074 * background has padding, this View's padding is set to the background's 12075 * padding. However, when a background is removed, this View's padding isn't 12076 * touched. If setting the padding is desired, please use 12077 * {@link #setPadding(int, int, int, int)}. 12078 * 12079 * @param d The Drawable to use as the background, or null to remove the 12080 * background 12081 */ 12082 public void setBackgroundDrawable(Drawable d) { 12083 if (d == mBGDrawable) { 12084 return; 12085 } 12086 12087 boolean requestLayout = false; 12088 12089 mBackgroundResource = 0; 12090 12091 /* 12092 * Regardless of whether we're setting a new background or not, we want 12093 * to clear the previous drawable. 12094 */ 12095 if (mBGDrawable != null) { 12096 mBGDrawable.setCallback(null); 12097 unscheduleDrawable(mBGDrawable); 12098 } 12099 12100 if (d != null) { 12101 Rect padding = sThreadLocal.get(); 12102 if (padding == null) { 12103 padding = new Rect(); 12104 sThreadLocal.set(padding); 12105 } 12106 if (d.getPadding(padding)) { 12107 switch (d.getResolvedLayoutDirectionSelf()) { 12108 case LAYOUT_DIRECTION_RTL: 12109 setPadding(padding.right, padding.top, padding.left, padding.bottom); 12110 break; 12111 case LAYOUT_DIRECTION_LTR: 12112 default: 12113 setPadding(padding.left, padding.top, padding.right, padding.bottom); 12114 } 12115 } 12116 12117 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 12118 // if it has a different minimum size, we should layout again 12119 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 12120 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 12121 requestLayout = true; 12122 } 12123 12124 d.setCallback(this); 12125 if (d.isStateful()) { 12126 d.setState(getDrawableState()); 12127 } 12128 d.setVisible(getVisibility() == VISIBLE, false); 12129 mBGDrawable = d; 12130 12131 if ((mPrivateFlags & SKIP_DRAW) != 0) { 12132 mPrivateFlags &= ~SKIP_DRAW; 12133 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 12134 requestLayout = true; 12135 } 12136 } else { 12137 /* Remove the background */ 12138 mBGDrawable = null; 12139 12140 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 12141 /* 12142 * This view ONLY drew the background before and we're removing 12143 * the background, so now it won't draw anything 12144 * (hence we SKIP_DRAW) 12145 */ 12146 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 12147 mPrivateFlags |= SKIP_DRAW; 12148 } 12149 12150 /* 12151 * When the background is set, we try to apply its padding to this 12152 * View. When the background is removed, we don't touch this View's 12153 * padding. This is noted in the Javadocs. Hence, we don't need to 12154 * requestLayout(), the invalidate() below is sufficient. 12155 */ 12156 12157 // The old background's minimum size could have affected this 12158 // View's layout, so let's requestLayout 12159 requestLayout = true; 12160 } 12161 12162 computeOpaqueFlags(); 12163 12164 if (requestLayout) { 12165 requestLayout(); 12166 } 12167 12168 mBackgroundSizeChanged = true; 12169 invalidate(true); 12170 } 12171 12172 /** 12173 * Gets the background drawable 12174 * @return The drawable used as the background for this view, if any. 12175 */ 12176 public Drawable getBackground() { 12177 return mBGDrawable; 12178 } 12179 12180 /** 12181 * Sets the padding. The view may add on the space required to display 12182 * the scrollbars, depending on the style and visibility of the scrollbars. 12183 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 12184 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 12185 * from the values set in this call. 12186 * 12187 * @attr ref android.R.styleable#View_padding 12188 * @attr ref android.R.styleable#View_paddingBottom 12189 * @attr ref android.R.styleable#View_paddingLeft 12190 * @attr ref android.R.styleable#View_paddingRight 12191 * @attr ref android.R.styleable#View_paddingTop 12192 * @param left the left padding in pixels 12193 * @param top the top padding in pixels 12194 * @param right the right padding in pixels 12195 * @param bottom the bottom padding in pixels 12196 */ 12197 public void setPadding(int left, int top, int right, int bottom) { 12198 boolean changed = false; 12199 12200 mUserPaddingRelative = false; 12201 12202 mUserPaddingLeft = left; 12203 mUserPaddingRight = right; 12204 mUserPaddingBottom = bottom; 12205 12206 final int viewFlags = mViewFlags; 12207 12208 // Common case is there are no scroll bars. 12209 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 12210 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 12211 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 12212 ? 0 : getVerticalScrollbarWidth(); 12213 switch (mVerticalScrollbarPosition) { 12214 case SCROLLBAR_POSITION_DEFAULT: 12215 if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12216 left += offset; 12217 } else { 12218 right += offset; 12219 } 12220 break; 12221 case SCROLLBAR_POSITION_RIGHT: 12222 right += offset; 12223 break; 12224 case SCROLLBAR_POSITION_LEFT: 12225 left += offset; 12226 break; 12227 } 12228 } 12229 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 12230 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 12231 ? 0 : getHorizontalScrollbarHeight(); 12232 } 12233 } 12234 12235 if (mPaddingLeft != left) { 12236 changed = true; 12237 mPaddingLeft = left; 12238 } 12239 if (mPaddingTop != top) { 12240 changed = true; 12241 mPaddingTop = top; 12242 } 12243 if (mPaddingRight != right) { 12244 changed = true; 12245 mPaddingRight = right; 12246 } 12247 if (mPaddingBottom != bottom) { 12248 changed = true; 12249 mPaddingBottom = bottom; 12250 } 12251 12252 if (changed) { 12253 requestLayout(); 12254 } 12255 } 12256 12257 /** 12258 * Sets the relative padding. The view may add on the space required to display 12259 * the scrollbars, depending on the style and visibility of the scrollbars. 12260 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 12261 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 12262 * from the values set in this call. 12263 * 12264 * @attr ref android.R.styleable#View_padding 12265 * @attr ref android.R.styleable#View_paddingBottom 12266 * @attr ref android.R.styleable#View_paddingStart 12267 * @attr ref android.R.styleable#View_paddingEnd 12268 * @attr ref android.R.styleable#View_paddingTop 12269 * @param start the start padding in pixels 12270 * @param top the top padding in pixels 12271 * @param end the end padding in pixels 12272 * @param bottom the bottom padding in pixels 12273 * 12274 * @hide 12275 */ 12276 public void setPaddingRelative(int start, int top, int end, int bottom) { 12277 mUserPaddingRelative = true; 12278 12279 mUserPaddingStart = start; 12280 mUserPaddingEnd = end; 12281 12282 switch(getResolvedLayoutDirection()) { 12283 case LAYOUT_DIRECTION_RTL: 12284 setPadding(end, top, start, bottom); 12285 break; 12286 case LAYOUT_DIRECTION_LTR: 12287 default: 12288 setPadding(start, top, end, bottom); 12289 } 12290 } 12291 12292 /** 12293 * Returns the top padding of this view. 12294 * 12295 * @return the top padding in pixels 12296 */ 12297 public int getPaddingTop() { 12298 return mPaddingTop; 12299 } 12300 12301 /** 12302 * Returns the bottom padding of this view. If there are inset and enabled 12303 * scrollbars, this value may include the space required to display the 12304 * scrollbars as well. 12305 * 12306 * @return the bottom padding in pixels 12307 */ 12308 public int getPaddingBottom() { 12309 return mPaddingBottom; 12310 } 12311 12312 /** 12313 * Returns the left padding of this view. If there are inset and enabled 12314 * scrollbars, this value may include the space required to display the 12315 * scrollbars as well. 12316 * 12317 * @return the left padding in pixels 12318 */ 12319 public int getPaddingLeft() { 12320 return mPaddingLeft; 12321 } 12322 12323 /** 12324 * Returns the start padding of this view. If there are inset and enabled 12325 * scrollbars, this value may include the space required to display the 12326 * scrollbars as well. 12327 * 12328 * @return the start padding in pixels 12329 * 12330 * @hide 12331 */ 12332 public int getPaddingStart() { 12333 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 12334 mPaddingRight : mPaddingLeft; 12335 } 12336 12337 /** 12338 * Returns the right padding of this view. If there are inset and enabled 12339 * scrollbars, this value may include the space required to display the 12340 * scrollbars as well. 12341 * 12342 * @return the right padding in pixels 12343 */ 12344 public int getPaddingRight() { 12345 return mPaddingRight; 12346 } 12347 12348 /** 12349 * Returns the end padding of this view. If there are inset and enabled 12350 * scrollbars, this value may include the space required to display the 12351 * scrollbars as well. 12352 * 12353 * @return the end padding in pixels 12354 * 12355 * @hide 12356 */ 12357 public int getPaddingEnd() { 12358 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 12359 mPaddingLeft : mPaddingRight; 12360 } 12361 12362 /** 12363 * Return if the padding as been set thru relative values 12364 * {@link #setPaddingRelative(int, int, int, int)} or thru 12365 * @attr ref android.R.styleable#View_paddingStart or 12366 * @attr ref android.R.styleable#View_paddingEnd 12367 * 12368 * @return true if the padding is relative or false if it is not. 12369 * 12370 * @hide 12371 */ 12372 public boolean isPaddingRelative() { 12373 return mUserPaddingRelative; 12374 } 12375 12376 /** 12377 * Changes the selection state of this view. A view can be selected or not. 12378 * Note that selection is not the same as focus. Views are typically 12379 * selected in the context of an AdapterView like ListView or GridView; 12380 * the selected view is the view that is highlighted. 12381 * 12382 * @param selected true if the view must be selected, false otherwise 12383 */ 12384 public void setSelected(boolean selected) { 12385 if (((mPrivateFlags & SELECTED) != 0) != selected) { 12386 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 12387 if (!selected) resetPressedState(); 12388 invalidate(true); 12389 refreshDrawableState(); 12390 dispatchSetSelected(selected); 12391 } 12392 } 12393 12394 /** 12395 * Dispatch setSelected to all of this View's children. 12396 * 12397 * @see #setSelected(boolean) 12398 * 12399 * @param selected The new selected state 12400 */ 12401 protected void dispatchSetSelected(boolean selected) { 12402 } 12403 12404 /** 12405 * Indicates the selection state of this view. 12406 * 12407 * @return true if the view is selected, false otherwise 12408 */ 12409 @ViewDebug.ExportedProperty 12410 public boolean isSelected() { 12411 return (mPrivateFlags & SELECTED) != 0; 12412 } 12413 12414 /** 12415 * Changes the activated state of this view. A view can be activated or not. 12416 * Note that activation is not the same as selection. Selection is 12417 * a transient property, representing the view (hierarchy) the user is 12418 * currently interacting with. Activation is a longer-term state that the 12419 * user can move views in and out of. For example, in a list view with 12420 * single or multiple selection enabled, the views in the current selection 12421 * set are activated. (Um, yeah, we are deeply sorry about the terminology 12422 * here.) The activated state is propagated down to children of the view it 12423 * is set on. 12424 * 12425 * @param activated true if the view must be activated, false otherwise 12426 */ 12427 public void setActivated(boolean activated) { 12428 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 12429 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 12430 invalidate(true); 12431 refreshDrawableState(); 12432 dispatchSetActivated(activated); 12433 } 12434 } 12435 12436 /** 12437 * Dispatch setActivated to all of this View's children. 12438 * 12439 * @see #setActivated(boolean) 12440 * 12441 * @param activated The new activated state 12442 */ 12443 protected void dispatchSetActivated(boolean activated) { 12444 } 12445 12446 /** 12447 * Indicates the activation state of this view. 12448 * 12449 * @return true if the view is activated, false otherwise 12450 */ 12451 @ViewDebug.ExportedProperty 12452 public boolean isActivated() { 12453 return (mPrivateFlags & ACTIVATED) != 0; 12454 } 12455 12456 /** 12457 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 12458 * observer can be used to get notifications when global events, like 12459 * layout, happen. 12460 * 12461 * The returned ViewTreeObserver observer is not guaranteed to remain 12462 * valid for the lifetime of this View. If the caller of this method keeps 12463 * a long-lived reference to ViewTreeObserver, it should always check for 12464 * the return value of {@link ViewTreeObserver#isAlive()}. 12465 * 12466 * @return The ViewTreeObserver for this view's hierarchy. 12467 */ 12468 public ViewTreeObserver getViewTreeObserver() { 12469 if (mAttachInfo != null) { 12470 return mAttachInfo.mTreeObserver; 12471 } 12472 if (mFloatingTreeObserver == null) { 12473 mFloatingTreeObserver = new ViewTreeObserver(); 12474 } 12475 return mFloatingTreeObserver; 12476 } 12477 12478 /** 12479 * <p>Finds the topmost view in the current view hierarchy.</p> 12480 * 12481 * @return the topmost view containing this view 12482 */ 12483 public View getRootView() { 12484 if (mAttachInfo != null) { 12485 final View v = mAttachInfo.mRootView; 12486 if (v != null) { 12487 return v; 12488 } 12489 } 12490 12491 View parent = this; 12492 12493 while (parent.mParent != null && parent.mParent instanceof View) { 12494 parent = (View) parent.mParent; 12495 } 12496 12497 return parent; 12498 } 12499 12500 /** 12501 * <p>Computes the coordinates of this view on the screen. The argument 12502 * must be an array of two integers. After the method returns, the array 12503 * contains the x and y location in that order.</p> 12504 * 12505 * @param location an array of two integers in which to hold the coordinates 12506 */ 12507 public void getLocationOnScreen(int[] location) { 12508 getLocationInWindow(location); 12509 12510 final AttachInfo info = mAttachInfo; 12511 if (info != null) { 12512 location[0] += info.mWindowLeft; 12513 location[1] += info.mWindowTop; 12514 } 12515 } 12516 12517 /** 12518 * <p>Computes the coordinates of this view in its window. The argument 12519 * must be an array of two integers. After the method returns, the array 12520 * contains the x and y location in that order.</p> 12521 * 12522 * @param location an array of two integers in which to hold the coordinates 12523 */ 12524 public void getLocationInWindow(int[] location) { 12525 if (location == null || location.length < 2) { 12526 throw new IllegalArgumentException("location must be an array of two integers"); 12527 } 12528 12529 if (mAttachInfo == null) { 12530 // When the view is not attached to a window, this method does not make sense 12531 location[0] = location[1] = 0; 12532 return; 12533 } 12534 12535 float[] position = mAttachInfo.mTmpTransformLocation; 12536 position[0] = position[1] = 0.0f; 12537 12538 if (!hasIdentityMatrix()) { 12539 getMatrix().mapPoints(position); 12540 } 12541 12542 position[0] += mLeft; 12543 position[1] += mTop; 12544 12545 ViewParent viewParent = mParent; 12546 while (viewParent instanceof View) { 12547 final View view = (View) viewParent; 12548 12549 position[0] -= view.mScrollX; 12550 position[1] -= view.mScrollY; 12551 12552 if (!view.hasIdentityMatrix()) { 12553 view.getMatrix().mapPoints(position); 12554 } 12555 12556 position[0] += view.mLeft; 12557 position[1] += view.mTop; 12558 12559 viewParent = view.mParent; 12560 } 12561 12562 if (viewParent instanceof ViewRootImpl) { 12563 // *cough* 12564 final ViewRootImpl vr = (ViewRootImpl) viewParent; 12565 position[1] -= vr.mCurScrollY; 12566 } 12567 12568 location[0] = (int) (position[0] + 0.5f); 12569 location[1] = (int) (position[1] + 0.5f); 12570 } 12571 12572 /** 12573 * {@hide} 12574 * @param id the id of the view to be found 12575 * @return the view of the specified id, null if cannot be found 12576 */ 12577 protected View findViewTraversal(int id) { 12578 if (id == mID) { 12579 return this; 12580 } 12581 return null; 12582 } 12583 12584 /** 12585 * {@hide} 12586 * @param tag the tag of the view to be found 12587 * @return the view of specified tag, null if cannot be found 12588 */ 12589 protected View findViewWithTagTraversal(Object tag) { 12590 if (tag != null && tag.equals(mTag)) { 12591 return this; 12592 } 12593 return null; 12594 } 12595 12596 /** 12597 * {@hide} 12598 * @param predicate The predicate to evaluate. 12599 * @param childToSkip If not null, ignores this child during the recursive traversal. 12600 * @return The first view that matches the predicate or null. 12601 */ 12602 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 12603 if (predicate.apply(this)) { 12604 return this; 12605 } 12606 return null; 12607 } 12608 12609 /** 12610 * Look for a child view with the given id. If this view has the given 12611 * id, return this view. 12612 * 12613 * @param id The id to search for. 12614 * @return The view that has the given id in the hierarchy or null 12615 */ 12616 public final View findViewById(int id) { 12617 if (id < 0) { 12618 return null; 12619 } 12620 return findViewTraversal(id); 12621 } 12622 12623 /** 12624 * Finds a view by its unuque and stable accessibility id. 12625 * 12626 * @param accessibilityId The searched accessibility id. 12627 * @return The found view. 12628 */ 12629 final View findViewByAccessibilityId(int accessibilityId) { 12630 if (accessibilityId < 0) { 12631 return null; 12632 } 12633 return findViewByAccessibilityIdTraversal(accessibilityId); 12634 } 12635 12636 /** 12637 * Performs the traversal to find a view by its unuque and stable accessibility id. 12638 * 12639 * <strong>Note:</strong>This method does not stop at the root namespace 12640 * boundary since the user can touch the screen at an arbitrary location 12641 * potentially crossing the root namespace bounday which will send an 12642 * accessibility event to accessibility services and they should be able 12643 * to obtain the event source. Also accessibility ids are guaranteed to be 12644 * unique in the window. 12645 * 12646 * @param accessibilityId The accessibility id. 12647 * @return The found view. 12648 */ 12649 View findViewByAccessibilityIdTraversal(int accessibilityId) { 12650 if (getAccessibilityViewId() == accessibilityId) { 12651 return this; 12652 } 12653 return null; 12654 } 12655 12656 /** 12657 * Look for a child view with the given tag. If this view has the given 12658 * tag, return this view. 12659 * 12660 * @param tag The tag to search for, using "tag.equals(getTag())". 12661 * @return The View that has the given tag in the hierarchy or null 12662 */ 12663 public final View findViewWithTag(Object tag) { 12664 if (tag == null) { 12665 return null; 12666 } 12667 return findViewWithTagTraversal(tag); 12668 } 12669 12670 /** 12671 * {@hide} 12672 * Look for a child view that matches the specified predicate. 12673 * If this view matches the predicate, return this view. 12674 * 12675 * @param predicate The predicate to evaluate. 12676 * @return The first view that matches the predicate or null. 12677 */ 12678 public final View findViewByPredicate(Predicate<View> predicate) { 12679 return findViewByPredicateTraversal(predicate, null); 12680 } 12681 12682 /** 12683 * {@hide} 12684 * Look for a child view that matches the specified predicate, 12685 * starting with the specified view and its descendents and then 12686 * recusively searching the ancestors and siblings of that view 12687 * until this view is reached. 12688 * 12689 * This method is useful in cases where the predicate does not match 12690 * a single unique view (perhaps multiple views use the same id) 12691 * and we are trying to find the view that is "closest" in scope to the 12692 * starting view. 12693 * 12694 * @param start The view to start from. 12695 * @param predicate The predicate to evaluate. 12696 * @return The first view that matches the predicate or null. 12697 */ 12698 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 12699 View childToSkip = null; 12700 for (;;) { 12701 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 12702 if (view != null || start == this) { 12703 return view; 12704 } 12705 12706 ViewParent parent = start.getParent(); 12707 if (parent == null || !(parent instanceof View)) { 12708 return null; 12709 } 12710 12711 childToSkip = start; 12712 start = (View) parent; 12713 } 12714 } 12715 12716 /** 12717 * Sets the identifier for this view. The identifier does not have to be 12718 * unique in this view's hierarchy. The identifier should be a positive 12719 * number. 12720 * 12721 * @see #NO_ID 12722 * @see #getId() 12723 * @see #findViewById(int) 12724 * 12725 * @param id a number used to identify the view 12726 * 12727 * @attr ref android.R.styleable#View_id 12728 */ 12729 public void setId(int id) { 12730 mID = id; 12731 } 12732 12733 /** 12734 * {@hide} 12735 * 12736 * @param isRoot true if the view belongs to the root namespace, false 12737 * otherwise 12738 */ 12739 public void setIsRootNamespace(boolean isRoot) { 12740 if (isRoot) { 12741 mPrivateFlags |= IS_ROOT_NAMESPACE; 12742 } else { 12743 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 12744 } 12745 } 12746 12747 /** 12748 * {@hide} 12749 * 12750 * @return true if the view belongs to the root namespace, false otherwise 12751 */ 12752 public boolean isRootNamespace() { 12753 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 12754 } 12755 12756 /** 12757 * Returns this view's identifier. 12758 * 12759 * @return a positive integer used to identify the view or {@link #NO_ID} 12760 * if the view has no ID 12761 * 12762 * @see #setId(int) 12763 * @see #findViewById(int) 12764 * @attr ref android.R.styleable#View_id 12765 */ 12766 @ViewDebug.CapturedViewProperty 12767 public int getId() { 12768 return mID; 12769 } 12770 12771 /** 12772 * Returns this view's tag. 12773 * 12774 * @return the Object stored in this view as a tag 12775 * 12776 * @see #setTag(Object) 12777 * @see #getTag(int) 12778 */ 12779 @ViewDebug.ExportedProperty 12780 public Object getTag() { 12781 return mTag; 12782 } 12783 12784 /** 12785 * Sets the tag associated with this view. A tag can be used to mark 12786 * a view in its hierarchy and does not have to be unique within the 12787 * hierarchy. Tags can also be used to store data within a view without 12788 * resorting to another data structure. 12789 * 12790 * @param tag an Object to tag the view with 12791 * 12792 * @see #getTag() 12793 * @see #setTag(int, Object) 12794 */ 12795 public void setTag(final Object tag) { 12796 mTag = tag; 12797 } 12798 12799 /** 12800 * Returns the tag associated with this view and the specified key. 12801 * 12802 * @param key The key identifying the tag 12803 * 12804 * @return the Object stored in this view as a tag 12805 * 12806 * @see #setTag(int, Object) 12807 * @see #getTag() 12808 */ 12809 public Object getTag(int key) { 12810 if (mKeyedTags != null) return mKeyedTags.get(key); 12811 return null; 12812 } 12813 12814 /** 12815 * Sets a tag associated with this view and a key. A tag can be used 12816 * to mark a view in its hierarchy and does not have to be unique within 12817 * the hierarchy. Tags can also be used to store data within a view 12818 * without resorting to another data structure. 12819 * 12820 * The specified key should be an id declared in the resources of the 12821 * application to ensure it is unique (see the <a 12822 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 12823 * Keys identified as belonging to 12824 * the Android framework or not associated with any package will cause 12825 * an {@link IllegalArgumentException} to be thrown. 12826 * 12827 * @param key The key identifying the tag 12828 * @param tag An Object to tag the view with 12829 * 12830 * @throws IllegalArgumentException If they specified key is not valid 12831 * 12832 * @see #setTag(Object) 12833 * @see #getTag(int) 12834 */ 12835 public void setTag(int key, final Object tag) { 12836 // If the package id is 0x00 or 0x01, it's either an undefined package 12837 // or a framework id 12838 if ((key >>> 24) < 2) { 12839 throw new IllegalArgumentException("The key must be an application-specific " 12840 + "resource id."); 12841 } 12842 12843 setKeyedTag(key, tag); 12844 } 12845 12846 /** 12847 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 12848 * framework id. 12849 * 12850 * @hide 12851 */ 12852 public void setTagInternal(int key, Object tag) { 12853 if ((key >>> 24) != 0x1) { 12854 throw new IllegalArgumentException("The key must be a framework-specific " 12855 + "resource id."); 12856 } 12857 12858 setKeyedTag(key, tag); 12859 } 12860 12861 private void setKeyedTag(int key, Object tag) { 12862 if (mKeyedTags == null) { 12863 mKeyedTags = new SparseArray<Object>(); 12864 } 12865 12866 mKeyedTags.put(key, tag); 12867 } 12868 12869 /** 12870 * @param consistency The type of consistency. See ViewDebug for more information. 12871 * 12872 * @hide 12873 */ 12874 protected boolean dispatchConsistencyCheck(int consistency) { 12875 return onConsistencyCheck(consistency); 12876 } 12877 12878 /** 12879 * Method that subclasses should implement to check their consistency. The type of 12880 * consistency check is indicated by the bit field passed as a parameter. 12881 * 12882 * @param consistency The type of consistency. See ViewDebug for more information. 12883 * 12884 * @throws IllegalStateException if the view is in an inconsistent state. 12885 * 12886 * @hide 12887 */ 12888 protected boolean onConsistencyCheck(int consistency) { 12889 boolean result = true; 12890 12891 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 12892 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 12893 12894 if (checkLayout) { 12895 if (getParent() == null) { 12896 result = false; 12897 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12898 "View " + this + " does not have a parent."); 12899 } 12900 12901 if (mAttachInfo == null) { 12902 result = false; 12903 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12904 "View " + this + " is not attached to a window."); 12905 } 12906 } 12907 12908 if (checkDrawing) { 12909 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 12910 // from their draw() method 12911 12912 if ((mPrivateFlags & DRAWN) != DRAWN && 12913 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 12914 result = false; 12915 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12916 "View " + this + " was invalidated but its drawing cache is valid."); 12917 } 12918 } 12919 12920 return result; 12921 } 12922 12923 /** 12924 * Prints information about this view in the log output, with the tag 12925 * {@link #VIEW_LOG_TAG}. 12926 * 12927 * @hide 12928 */ 12929 public void debug() { 12930 debug(0); 12931 } 12932 12933 /** 12934 * Prints information about this view in the log output, with the tag 12935 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 12936 * indentation defined by the <code>depth</code>. 12937 * 12938 * @param depth the indentation level 12939 * 12940 * @hide 12941 */ 12942 protected void debug(int depth) { 12943 String output = debugIndent(depth - 1); 12944 12945 output += "+ " + this; 12946 int id = getId(); 12947 if (id != -1) { 12948 output += " (id=" + id + ")"; 12949 } 12950 Object tag = getTag(); 12951 if (tag != null) { 12952 output += " (tag=" + tag + ")"; 12953 } 12954 Log.d(VIEW_LOG_TAG, output); 12955 12956 if ((mPrivateFlags & FOCUSED) != 0) { 12957 output = debugIndent(depth) + " FOCUSED"; 12958 Log.d(VIEW_LOG_TAG, output); 12959 } 12960 12961 output = debugIndent(depth); 12962 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 12963 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 12964 + "} "; 12965 Log.d(VIEW_LOG_TAG, output); 12966 12967 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 12968 || mPaddingBottom != 0) { 12969 output = debugIndent(depth); 12970 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 12971 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 12972 Log.d(VIEW_LOG_TAG, output); 12973 } 12974 12975 output = debugIndent(depth); 12976 output += "mMeasureWidth=" + mMeasuredWidth + 12977 " mMeasureHeight=" + mMeasuredHeight; 12978 Log.d(VIEW_LOG_TAG, output); 12979 12980 output = debugIndent(depth); 12981 if (mLayoutParams == null) { 12982 output += "BAD! no layout params"; 12983 } else { 12984 output = mLayoutParams.debug(output); 12985 } 12986 Log.d(VIEW_LOG_TAG, output); 12987 12988 output = debugIndent(depth); 12989 output += "flags={"; 12990 output += View.printFlags(mViewFlags); 12991 output += "}"; 12992 Log.d(VIEW_LOG_TAG, output); 12993 12994 output = debugIndent(depth); 12995 output += "privateFlags={"; 12996 output += View.printPrivateFlags(mPrivateFlags); 12997 output += "}"; 12998 Log.d(VIEW_LOG_TAG, output); 12999 } 13000 13001 /** 13002 * Creates an string of whitespaces used for indentation. 13003 * 13004 * @param depth the indentation level 13005 * @return a String containing (depth * 2 + 3) * 2 white spaces 13006 * 13007 * @hide 13008 */ 13009 protected static String debugIndent(int depth) { 13010 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 13011 for (int i = 0; i < (depth * 2) + 3; i++) { 13012 spaces.append(' ').append(' '); 13013 } 13014 return spaces.toString(); 13015 } 13016 13017 /** 13018 * <p>Return the offset of the widget's text baseline from the widget's top 13019 * boundary. If this widget does not support baseline alignment, this 13020 * method returns -1. </p> 13021 * 13022 * @return the offset of the baseline within the widget's bounds or -1 13023 * if baseline alignment is not supported 13024 */ 13025 @ViewDebug.ExportedProperty(category = "layout") 13026 public int getBaseline() { 13027 return -1; 13028 } 13029 13030 /** 13031 * Call this when something has changed which has invalidated the 13032 * layout of this view. This will schedule a layout pass of the view 13033 * tree. 13034 */ 13035 public void requestLayout() { 13036 if (ViewDebug.TRACE_HIERARCHY) { 13037 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 13038 } 13039 13040 if (getAccessibilityNodeProvider() != null) { 13041 throw new IllegalStateException("Views with AccessibilityNodeProvider" 13042 + " can't have children."); 13043 } 13044 13045 mPrivateFlags |= FORCE_LAYOUT; 13046 mPrivateFlags |= INVALIDATED; 13047 13048 if (mParent != null) { 13049 if (mLayoutParams != null) { 13050 mLayoutParams.resolveWithDirection(getResolvedLayoutDirection()); 13051 } 13052 if (!mParent.isLayoutRequested()) { 13053 mParent.requestLayout(); 13054 } 13055 } 13056 } 13057 13058 /** 13059 * Forces this view to be laid out during the next layout pass. 13060 * This method does not call requestLayout() or forceLayout() 13061 * on the parent. 13062 */ 13063 public void forceLayout() { 13064 mPrivateFlags |= FORCE_LAYOUT; 13065 mPrivateFlags |= INVALIDATED; 13066 } 13067 13068 /** 13069 * <p> 13070 * This is called to find out how big a view should be. The parent 13071 * supplies constraint information in the width and height parameters. 13072 * </p> 13073 * 13074 * <p> 13075 * The actual measurement work of a view is performed in 13076 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 13077 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 13078 * </p> 13079 * 13080 * 13081 * @param widthMeasureSpec Horizontal space requirements as imposed by the 13082 * parent 13083 * @param heightMeasureSpec Vertical space requirements as imposed by the 13084 * parent 13085 * 13086 * @see #onMeasure(int, int) 13087 */ 13088 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 13089 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 13090 widthMeasureSpec != mOldWidthMeasureSpec || 13091 heightMeasureSpec != mOldHeightMeasureSpec) { 13092 13093 // first clears the measured dimension flag 13094 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 13095 13096 if (ViewDebug.TRACE_HIERARCHY) { 13097 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 13098 } 13099 13100 // measure ourselves, this should set the measured dimension flag back 13101 onMeasure(widthMeasureSpec, heightMeasureSpec); 13102 13103 // flag not set, setMeasuredDimension() was not invoked, we raise 13104 // an exception to warn the developer 13105 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 13106 throw new IllegalStateException("onMeasure() did not set the" 13107 + " measured dimension by calling" 13108 + " setMeasuredDimension()"); 13109 } 13110 13111 mPrivateFlags |= LAYOUT_REQUIRED; 13112 } 13113 13114 mOldWidthMeasureSpec = widthMeasureSpec; 13115 mOldHeightMeasureSpec = heightMeasureSpec; 13116 } 13117 13118 /** 13119 * <p> 13120 * Measure the view and its content to determine the measured width and the 13121 * measured height. This method is invoked by {@link #measure(int, int)} and 13122 * should be overriden by subclasses to provide accurate and efficient 13123 * measurement of their contents. 13124 * </p> 13125 * 13126 * <p> 13127 * <strong>CONTRACT:</strong> When overriding this method, you 13128 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 13129 * measured width and height of this view. Failure to do so will trigger an 13130 * <code>IllegalStateException</code>, thrown by 13131 * {@link #measure(int, int)}. Calling the superclass' 13132 * {@link #onMeasure(int, int)} is a valid use. 13133 * </p> 13134 * 13135 * <p> 13136 * The base class implementation of measure defaults to the background size, 13137 * unless a larger size is allowed by the MeasureSpec. Subclasses should 13138 * override {@link #onMeasure(int, int)} to provide better measurements of 13139 * their content. 13140 * </p> 13141 * 13142 * <p> 13143 * If this method is overridden, it is the subclass's responsibility to make 13144 * sure the measured height and width are at least the view's minimum height 13145 * and width ({@link #getSuggestedMinimumHeight()} and 13146 * {@link #getSuggestedMinimumWidth()}). 13147 * </p> 13148 * 13149 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 13150 * The requirements are encoded with 13151 * {@link android.view.View.MeasureSpec}. 13152 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 13153 * The requirements are encoded with 13154 * {@link android.view.View.MeasureSpec}. 13155 * 13156 * @see #getMeasuredWidth() 13157 * @see #getMeasuredHeight() 13158 * @see #setMeasuredDimension(int, int) 13159 * @see #getSuggestedMinimumHeight() 13160 * @see #getSuggestedMinimumWidth() 13161 * @see android.view.View.MeasureSpec#getMode(int) 13162 * @see android.view.View.MeasureSpec#getSize(int) 13163 */ 13164 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 13165 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 13166 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 13167 } 13168 13169 /** 13170 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 13171 * measured width and measured height. Failing to do so will trigger an 13172 * exception at measurement time.</p> 13173 * 13174 * @param measuredWidth The measured width of this view. May be a complex 13175 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 13176 * {@link #MEASURED_STATE_TOO_SMALL}. 13177 * @param measuredHeight The measured height of this view. May be a complex 13178 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 13179 * {@link #MEASURED_STATE_TOO_SMALL}. 13180 */ 13181 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 13182 mMeasuredWidth = measuredWidth; 13183 mMeasuredHeight = measuredHeight; 13184 13185 mPrivateFlags |= MEASURED_DIMENSION_SET; 13186 } 13187 13188 /** 13189 * Merge two states as returned by {@link #getMeasuredState()}. 13190 * @param curState The current state as returned from a view or the result 13191 * of combining multiple views. 13192 * @param newState The new view state to combine. 13193 * @return Returns a new integer reflecting the combination of the two 13194 * states. 13195 */ 13196 public static int combineMeasuredStates(int curState, int newState) { 13197 return curState | newState; 13198 } 13199 13200 /** 13201 * Version of {@link #resolveSizeAndState(int, int, int)} 13202 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 13203 */ 13204 public static int resolveSize(int size, int measureSpec) { 13205 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 13206 } 13207 13208 /** 13209 * Utility to reconcile a desired size and state, with constraints imposed 13210 * by a MeasureSpec. Will take the desired size, unless a different size 13211 * is imposed by the constraints. The returned value is a compound integer, 13212 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 13213 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 13214 * size is smaller than the size the view wants to be. 13215 * 13216 * @param size How big the view wants to be 13217 * @param measureSpec Constraints imposed by the parent 13218 * @return Size information bit mask as defined by 13219 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 13220 */ 13221 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 13222 int result = size; 13223 int specMode = MeasureSpec.getMode(measureSpec); 13224 int specSize = MeasureSpec.getSize(measureSpec); 13225 switch (specMode) { 13226 case MeasureSpec.UNSPECIFIED: 13227 result = size; 13228 break; 13229 case MeasureSpec.AT_MOST: 13230 if (specSize < size) { 13231 result = specSize | MEASURED_STATE_TOO_SMALL; 13232 } else { 13233 result = size; 13234 } 13235 break; 13236 case MeasureSpec.EXACTLY: 13237 result = specSize; 13238 break; 13239 } 13240 return result | (childMeasuredState&MEASURED_STATE_MASK); 13241 } 13242 13243 /** 13244 * Utility to return a default size. Uses the supplied size if the 13245 * MeasureSpec imposed no constraints. Will get larger if allowed 13246 * by the MeasureSpec. 13247 * 13248 * @param size Default size for this view 13249 * @param measureSpec Constraints imposed by the parent 13250 * @return The size this view should be. 13251 */ 13252 public static int getDefaultSize(int size, int measureSpec) { 13253 int result = size; 13254 int specMode = MeasureSpec.getMode(measureSpec); 13255 int specSize = MeasureSpec.getSize(measureSpec); 13256 13257 switch (specMode) { 13258 case MeasureSpec.UNSPECIFIED: 13259 result = size; 13260 break; 13261 case MeasureSpec.AT_MOST: 13262 case MeasureSpec.EXACTLY: 13263 result = specSize; 13264 break; 13265 } 13266 return result; 13267 } 13268 13269 /** 13270 * Returns the suggested minimum height that the view should use. This 13271 * returns the maximum of the view's minimum height 13272 * and the background's minimum height 13273 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 13274 * <p> 13275 * When being used in {@link #onMeasure(int, int)}, the caller should still 13276 * ensure the returned height is within the requirements of the parent. 13277 * 13278 * @return The suggested minimum height of the view. 13279 */ 13280 protected int getSuggestedMinimumHeight() { 13281 int suggestedMinHeight = mMinHeight; 13282 13283 if (mBGDrawable != null) { 13284 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 13285 if (suggestedMinHeight < bgMinHeight) { 13286 suggestedMinHeight = bgMinHeight; 13287 } 13288 } 13289 13290 return suggestedMinHeight; 13291 } 13292 13293 /** 13294 * Returns the suggested minimum width that the view should use. This 13295 * returns the maximum of the view's minimum width) 13296 * and the background's minimum width 13297 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 13298 * <p> 13299 * When being used in {@link #onMeasure(int, int)}, the caller should still 13300 * ensure the returned width is within the requirements of the parent. 13301 * 13302 * @return The suggested minimum width of the view. 13303 */ 13304 protected int getSuggestedMinimumWidth() { 13305 int suggestedMinWidth = mMinWidth; 13306 13307 if (mBGDrawable != null) { 13308 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 13309 if (suggestedMinWidth < bgMinWidth) { 13310 suggestedMinWidth = bgMinWidth; 13311 } 13312 } 13313 13314 return suggestedMinWidth; 13315 } 13316 13317 /** 13318 * Sets the minimum height of the view. It is not guaranteed the view will 13319 * be able to achieve this minimum height (for example, if its parent layout 13320 * constrains it with less available height). 13321 * 13322 * @param minHeight The minimum height the view will try to be. 13323 */ 13324 public void setMinimumHeight(int minHeight) { 13325 mMinHeight = minHeight; 13326 } 13327 13328 /** 13329 * Sets the minimum width of the view. It is not guaranteed the view will 13330 * be able to achieve this minimum width (for example, if its parent layout 13331 * constrains it with less available width). 13332 * 13333 * @param minWidth The minimum width the view will try to be. 13334 */ 13335 public void setMinimumWidth(int minWidth) { 13336 mMinWidth = minWidth; 13337 } 13338 13339 /** 13340 * Get the animation currently associated with this view. 13341 * 13342 * @return The animation that is currently playing or 13343 * scheduled to play for this view. 13344 */ 13345 public Animation getAnimation() { 13346 return mCurrentAnimation; 13347 } 13348 13349 /** 13350 * Start the specified animation now. 13351 * 13352 * @param animation the animation to start now 13353 */ 13354 public void startAnimation(Animation animation) { 13355 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 13356 setAnimation(animation); 13357 invalidateParentCaches(); 13358 invalidate(true); 13359 } 13360 13361 /** 13362 * Cancels any animations for this view. 13363 */ 13364 public void clearAnimation() { 13365 if (mCurrentAnimation != null) { 13366 mCurrentAnimation.detach(); 13367 } 13368 mCurrentAnimation = null; 13369 invalidateParentIfNeeded(); 13370 } 13371 13372 /** 13373 * Sets the next animation to play for this view. 13374 * If you want the animation to play immediately, use 13375 * startAnimation. This method provides allows fine-grained 13376 * control over the start time and invalidation, but you 13377 * must make sure that 1) the animation has a start time set, and 13378 * 2) the view will be invalidated when the animation is supposed to 13379 * start. 13380 * 13381 * @param animation The next animation, or null. 13382 */ 13383 public void setAnimation(Animation animation) { 13384 mCurrentAnimation = animation; 13385 if (animation != null) { 13386 animation.reset(); 13387 } 13388 } 13389 13390 /** 13391 * Invoked by a parent ViewGroup to notify the start of the animation 13392 * currently associated with this view. If you override this method, 13393 * always call super.onAnimationStart(); 13394 * 13395 * @see #setAnimation(android.view.animation.Animation) 13396 * @see #getAnimation() 13397 */ 13398 protected void onAnimationStart() { 13399 mPrivateFlags |= ANIMATION_STARTED; 13400 } 13401 13402 /** 13403 * Invoked by a parent ViewGroup to notify the end of the animation 13404 * currently associated with this view. If you override this method, 13405 * always call super.onAnimationEnd(); 13406 * 13407 * @see #setAnimation(android.view.animation.Animation) 13408 * @see #getAnimation() 13409 */ 13410 protected void onAnimationEnd() { 13411 mPrivateFlags &= ~ANIMATION_STARTED; 13412 } 13413 13414 /** 13415 * Invoked if there is a Transform that involves alpha. Subclass that can 13416 * draw themselves with the specified alpha should return true, and then 13417 * respect that alpha when their onDraw() is called. If this returns false 13418 * then the view may be redirected to draw into an offscreen buffer to 13419 * fulfill the request, which will look fine, but may be slower than if the 13420 * subclass handles it internally. The default implementation returns false. 13421 * 13422 * @param alpha The alpha (0..255) to apply to the view's drawing 13423 * @return true if the view can draw with the specified alpha. 13424 */ 13425 protected boolean onSetAlpha(int alpha) { 13426 return false; 13427 } 13428 13429 /** 13430 * This is used by the RootView to perform an optimization when 13431 * the view hierarchy contains one or several SurfaceView. 13432 * SurfaceView is always considered transparent, but its children are not, 13433 * therefore all View objects remove themselves from the global transparent 13434 * region (passed as a parameter to this function). 13435 * 13436 * @param region The transparent region for this ViewAncestor (window). 13437 * 13438 * @return Returns true if the effective visibility of the view at this 13439 * point is opaque, regardless of the transparent region; returns false 13440 * if it is possible for underlying windows to be seen behind the view. 13441 * 13442 * {@hide} 13443 */ 13444 public boolean gatherTransparentRegion(Region region) { 13445 final AttachInfo attachInfo = mAttachInfo; 13446 if (region != null && attachInfo != null) { 13447 final int pflags = mPrivateFlags; 13448 if ((pflags & SKIP_DRAW) == 0) { 13449 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 13450 // remove it from the transparent region. 13451 final int[] location = attachInfo.mTransparentLocation; 13452 getLocationInWindow(location); 13453 region.op(location[0], location[1], location[0] + mRight - mLeft, 13454 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 13455 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 13456 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 13457 // exists, so we remove the background drawable's non-transparent 13458 // parts from this transparent region. 13459 applyDrawableToTransparentRegion(mBGDrawable, region); 13460 } 13461 } 13462 return true; 13463 } 13464 13465 /** 13466 * Play a sound effect for this view. 13467 * 13468 * <p>The framework will play sound effects for some built in actions, such as 13469 * clicking, but you may wish to play these effects in your widget, 13470 * for instance, for internal navigation. 13471 * 13472 * <p>The sound effect will only be played if sound effects are enabled by the user, and 13473 * {@link #isSoundEffectsEnabled()} is true. 13474 * 13475 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 13476 */ 13477 public void playSoundEffect(int soundConstant) { 13478 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 13479 return; 13480 } 13481 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 13482 } 13483 13484 /** 13485 * BZZZTT!!1! 13486 * 13487 * <p>Provide haptic feedback to the user for this view. 13488 * 13489 * <p>The framework will provide haptic feedback for some built in actions, 13490 * such as long presses, but you may wish to provide feedback for your 13491 * own widget. 13492 * 13493 * <p>The feedback will only be performed if 13494 * {@link #isHapticFeedbackEnabled()} is true. 13495 * 13496 * @param feedbackConstant One of the constants defined in 13497 * {@link HapticFeedbackConstants} 13498 */ 13499 public boolean performHapticFeedback(int feedbackConstant) { 13500 return performHapticFeedback(feedbackConstant, 0); 13501 } 13502 13503 /** 13504 * BZZZTT!!1! 13505 * 13506 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 13507 * 13508 * @param feedbackConstant One of the constants defined in 13509 * {@link HapticFeedbackConstants} 13510 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 13511 */ 13512 public boolean performHapticFeedback(int feedbackConstant, int flags) { 13513 if (mAttachInfo == null) { 13514 return false; 13515 } 13516 //noinspection SimplifiableIfStatement 13517 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 13518 && !isHapticFeedbackEnabled()) { 13519 return false; 13520 } 13521 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 13522 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 13523 } 13524 13525 /** 13526 * Request that the visibility of the status bar be changed. 13527 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 13528 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 13529 */ 13530 public void setSystemUiVisibility(int visibility) { 13531 if (visibility != mSystemUiVisibility) { 13532 mSystemUiVisibility = visibility; 13533 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 13534 mParent.recomputeViewAttributes(this); 13535 } 13536 } 13537 } 13538 13539 /** 13540 * Returns the status bar visibility that this view has requested. 13541 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 13542 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 13543 */ 13544 public int getSystemUiVisibility() { 13545 return mSystemUiVisibility; 13546 } 13547 13548 /** 13549 * Set a listener to receive callbacks when the visibility of the system bar changes. 13550 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 13551 */ 13552 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 13553 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 13554 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 13555 mParent.recomputeViewAttributes(this); 13556 } 13557 } 13558 13559 /** 13560 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 13561 * the view hierarchy. 13562 */ 13563 public void dispatchSystemUiVisibilityChanged(int visibility) { 13564 ListenerInfo li = mListenerInfo; 13565 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 13566 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 13567 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 13568 } 13569 } 13570 13571 void updateLocalSystemUiVisibility(int localValue, int localChanges) { 13572 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 13573 if (val != mSystemUiVisibility) { 13574 setSystemUiVisibility(val); 13575 } 13576 } 13577 13578 /** 13579 * Creates an image that the system displays during the drag and drop 13580 * operation. This is called a "drag shadow". The default implementation 13581 * for a DragShadowBuilder based on a View returns an image that has exactly the same 13582 * appearance as the given View. The default also positions the center of the drag shadow 13583 * directly under the touch point. If no View is provided (the constructor with no parameters 13584 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 13585 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 13586 * default is an invisible drag shadow. 13587 * <p> 13588 * You are not required to use the View you provide to the constructor as the basis of the 13589 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 13590 * anything you want as the drag shadow. 13591 * </p> 13592 * <p> 13593 * You pass a DragShadowBuilder object to the system when you start the drag. The system 13594 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 13595 * size and position of the drag shadow. It uses this data to construct a 13596 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 13597 * so that your application can draw the shadow image in the Canvas. 13598 * </p> 13599 * 13600 * <div class="special reference"> 13601 * <h3>Developer Guides</h3> 13602 * <p>For a guide to implementing drag and drop features, read the 13603 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 13604 * </div> 13605 */ 13606 public static class DragShadowBuilder { 13607 private final WeakReference<View> mView; 13608 13609 /** 13610 * Constructs a shadow image builder based on a View. By default, the resulting drag 13611 * shadow will have the same appearance and dimensions as the View, with the touch point 13612 * over the center of the View. 13613 * @param view A View. Any View in scope can be used. 13614 */ 13615 public DragShadowBuilder(View view) { 13616 mView = new WeakReference<View>(view); 13617 } 13618 13619 /** 13620 * Construct a shadow builder object with no associated View. This 13621 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 13622 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 13623 * to supply the drag shadow's dimensions and appearance without 13624 * reference to any View object. If they are not overridden, then the result is an 13625 * invisible drag shadow. 13626 */ 13627 public DragShadowBuilder() { 13628 mView = new WeakReference<View>(null); 13629 } 13630 13631 /** 13632 * Returns the View object that had been passed to the 13633 * {@link #View.DragShadowBuilder(View)} 13634 * constructor. If that View parameter was {@code null} or if the 13635 * {@link #View.DragShadowBuilder()} 13636 * constructor was used to instantiate the builder object, this method will return 13637 * null. 13638 * 13639 * @return The View object associate with this builder object. 13640 */ 13641 @SuppressWarnings({"JavadocReference"}) 13642 final public View getView() { 13643 return mView.get(); 13644 } 13645 13646 /** 13647 * Provides the metrics for the shadow image. These include the dimensions of 13648 * the shadow image, and the point within that shadow that should 13649 * be centered under the touch location while dragging. 13650 * <p> 13651 * The default implementation sets the dimensions of the shadow to be the 13652 * same as the dimensions of the View itself and centers the shadow under 13653 * the touch point. 13654 * </p> 13655 * 13656 * @param shadowSize A {@link android.graphics.Point} containing the width and height 13657 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 13658 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 13659 * image. 13660 * 13661 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 13662 * shadow image that should be underneath the touch point during the drag and drop 13663 * operation. Your application must set {@link android.graphics.Point#x} to the 13664 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 13665 */ 13666 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 13667 final View view = mView.get(); 13668 if (view != null) { 13669 shadowSize.set(view.getWidth(), view.getHeight()); 13670 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 13671 } else { 13672 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 13673 } 13674 } 13675 13676 /** 13677 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 13678 * based on the dimensions it received from the 13679 * {@link #onProvideShadowMetrics(Point, Point)} callback. 13680 * 13681 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 13682 */ 13683 public void onDrawShadow(Canvas canvas) { 13684 final View view = mView.get(); 13685 if (view != null) { 13686 view.draw(canvas); 13687 } else { 13688 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 13689 } 13690 } 13691 } 13692 13693 /** 13694 * Starts a drag and drop operation. When your application calls this method, it passes a 13695 * {@link android.view.View.DragShadowBuilder} object to the system. The 13696 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 13697 * to get metrics for the drag shadow, and then calls the object's 13698 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 13699 * <p> 13700 * Once the system has the drag shadow, it begins the drag and drop operation by sending 13701 * drag events to all the View objects in your application that are currently visible. It does 13702 * this either by calling the View object's drag listener (an implementation of 13703 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 13704 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 13705 * Both are passed a {@link android.view.DragEvent} object that has a 13706 * {@link android.view.DragEvent#getAction()} value of 13707 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 13708 * </p> 13709 * <p> 13710 * Your application can invoke startDrag() on any attached View object. The View object does not 13711 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 13712 * be related to the View the user selected for dragging. 13713 * </p> 13714 * @param data A {@link android.content.ClipData} object pointing to the data to be 13715 * transferred by the drag and drop operation. 13716 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 13717 * drag shadow. 13718 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 13719 * drop operation. This Object is put into every DragEvent object sent by the system during the 13720 * current drag. 13721 * <p> 13722 * myLocalState is a lightweight mechanism for the sending information from the dragged View 13723 * to the target Views. For example, it can contain flags that differentiate between a 13724 * a copy operation and a move operation. 13725 * </p> 13726 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 13727 * so the parameter should be set to 0. 13728 * @return {@code true} if the method completes successfully, or 13729 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 13730 * do a drag, and so no drag operation is in progress. 13731 */ 13732 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 13733 Object myLocalState, int flags) { 13734 if (ViewDebug.DEBUG_DRAG) { 13735 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 13736 } 13737 boolean okay = false; 13738 13739 Point shadowSize = new Point(); 13740 Point shadowTouchPoint = new Point(); 13741 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 13742 13743 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 13744 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 13745 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 13746 } 13747 13748 if (ViewDebug.DEBUG_DRAG) { 13749 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 13750 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 13751 } 13752 Surface surface = new Surface(); 13753 try { 13754 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 13755 flags, shadowSize.x, shadowSize.y, surface); 13756 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 13757 + " surface=" + surface); 13758 if (token != null) { 13759 Canvas canvas = surface.lockCanvas(null); 13760 try { 13761 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 13762 shadowBuilder.onDrawShadow(canvas); 13763 } finally { 13764 surface.unlockCanvasAndPost(canvas); 13765 } 13766 13767 final ViewRootImpl root = getViewRootImpl(); 13768 13769 // Cache the local state object for delivery with DragEvents 13770 root.setLocalDragState(myLocalState); 13771 13772 // repurpose 'shadowSize' for the last touch point 13773 root.getLastTouchPoint(shadowSize); 13774 13775 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 13776 shadowSize.x, shadowSize.y, 13777 shadowTouchPoint.x, shadowTouchPoint.y, data); 13778 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 13779 13780 // Off and running! Release our local surface instance; the drag 13781 // shadow surface is now managed by the system process. 13782 surface.release(); 13783 } 13784 } catch (Exception e) { 13785 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 13786 surface.destroy(); 13787 } 13788 13789 return okay; 13790 } 13791 13792 /** 13793 * Handles drag events sent by the system following a call to 13794 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 13795 *<p> 13796 * When the system calls this method, it passes a 13797 * {@link android.view.DragEvent} object. A call to 13798 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 13799 * in DragEvent. The method uses these to determine what is happening in the drag and drop 13800 * operation. 13801 * @param event The {@link android.view.DragEvent} sent by the system. 13802 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 13803 * in DragEvent, indicating the type of drag event represented by this object. 13804 * @return {@code true} if the method was successful, otherwise {@code false}. 13805 * <p> 13806 * The method should return {@code true} in response to an action type of 13807 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 13808 * operation. 13809 * </p> 13810 * <p> 13811 * The method should also return {@code true} in response to an action type of 13812 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 13813 * {@code false} if it didn't. 13814 * </p> 13815 */ 13816 public boolean onDragEvent(DragEvent event) { 13817 return false; 13818 } 13819 13820 /** 13821 * Detects if this View is enabled and has a drag event listener. 13822 * If both are true, then it calls the drag event listener with the 13823 * {@link android.view.DragEvent} it received. If the drag event listener returns 13824 * {@code true}, then dispatchDragEvent() returns {@code true}. 13825 * <p> 13826 * For all other cases, the method calls the 13827 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 13828 * method and returns its result. 13829 * </p> 13830 * <p> 13831 * This ensures that a drag event is always consumed, even if the View does not have a drag 13832 * event listener. However, if the View has a listener and the listener returns true, then 13833 * onDragEvent() is not called. 13834 * </p> 13835 */ 13836 public boolean dispatchDragEvent(DragEvent event) { 13837 //noinspection SimplifiableIfStatement 13838 ListenerInfo li = mListenerInfo; 13839 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 13840 && li.mOnDragListener.onDrag(this, event)) { 13841 return true; 13842 } 13843 return onDragEvent(event); 13844 } 13845 13846 boolean canAcceptDrag() { 13847 return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0; 13848 } 13849 13850 /** 13851 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 13852 * it is ever exposed at all. 13853 * @hide 13854 */ 13855 public void onCloseSystemDialogs(String reason) { 13856 } 13857 13858 /** 13859 * Given a Drawable whose bounds have been set to draw into this view, 13860 * update a Region being computed for 13861 * {@link #gatherTransparentRegion(android.graphics.Region)} so 13862 * that any non-transparent parts of the Drawable are removed from the 13863 * given transparent region. 13864 * 13865 * @param dr The Drawable whose transparency is to be applied to the region. 13866 * @param region A Region holding the current transparency information, 13867 * where any parts of the region that are set are considered to be 13868 * transparent. On return, this region will be modified to have the 13869 * transparency information reduced by the corresponding parts of the 13870 * Drawable that are not transparent. 13871 * {@hide} 13872 */ 13873 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 13874 if (DBG) { 13875 Log.i("View", "Getting transparent region for: " + this); 13876 } 13877 final Region r = dr.getTransparentRegion(); 13878 final Rect db = dr.getBounds(); 13879 final AttachInfo attachInfo = mAttachInfo; 13880 if (r != null && attachInfo != null) { 13881 final int w = getRight()-getLeft(); 13882 final int h = getBottom()-getTop(); 13883 if (db.left > 0) { 13884 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 13885 r.op(0, 0, db.left, h, Region.Op.UNION); 13886 } 13887 if (db.right < w) { 13888 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 13889 r.op(db.right, 0, w, h, Region.Op.UNION); 13890 } 13891 if (db.top > 0) { 13892 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 13893 r.op(0, 0, w, db.top, Region.Op.UNION); 13894 } 13895 if (db.bottom < h) { 13896 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 13897 r.op(0, db.bottom, w, h, Region.Op.UNION); 13898 } 13899 final int[] location = attachInfo.mTransparentLocation; 13900 getLocationInWindow(location); 13901 r.translate(location[0], location[1]); 13902 region.op(r, Region.Op.INTERSECT); 13903 } else { 13904 region.op(db, Region.Op.DIFFERENCE); 13905 } 13906 } 13907 13908 private void checkForLongClick(int delayOffset) { 13909 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 13910 mHasPerformedLongPress = false; 13911 13912 if (mPendingCheckForLongPress == null) { 13913 mPendingCheckForLongPress = new CheckForLongPress(); 13914 } 13915 mPendingCheckForLongPress.rememberWindowAttachCount(); 13916 postDelayed(mPendingCheckForLongPress, 13917 ViewConfiguration.getLongPressTimeout() - delayOffset); 13918 } 13919 } 13920 13921 /** 13922 * Inflate a view from an XML resource. This convenience method wraps the {@link 13923 * LayoutInflater} class, which provides a full range of options for view inflation. 13924 * 13925 * @param context The Context object for your activity or application. 13926 * @param resource The resource ID to inflate 13927 * @param root A view group that will be the parent. Used to properly inflate the 13928 * layout_* parameters. 13929 * @see LayoutInflater 13930 */ 13931 public static View inflate(Context context, int resource, ViewGroup root) { 13932 LayoutInflater factory = LayoutInflater.from(context); 13933 return factory.inflate(resource, root); 13934 } 13935 13936 /** 13937 * Scroll the view with standard behavior for scrolling beyond the normal 13938 * content boundaries. Views that call this method should override 13939 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 13940 * results of an over-scroll operation. 13941 * 13942 * Views can use this method to handle any touch or fling-based scrolling. 13943 * 13944 * @param deltaX Change in X in pixels 13945 * @param deltaY Change in Y in pixels 13946 * @param scrollX Current X scroll value in pixels before applying deltaX 13947 * @param scrollY Current Y scroll value in pixels before applying deltaY 13948 * @param scrollRangeX Maximum content scroll range along the X axis 13949 * @param scrollRangeY Maximum content scroll range along the Y axis 13950 * @param maxOverScrollX Number of pixels to overscroll by in either direction 13951 * along the X axis. 13952 * @param maxOverScrollY Number of pixels to overscroll by in either direction 13953 * along the Y axis. 13954 * @param isTouchEvent true if this scroll operation is the result of a touch event. 13955 * @return true if scrolling was clamped to an over-scroll boundary along either 13956 * axis, false otherwise. 13957 */ 13958 @SuppressWarnings({"UnusedParameters"}) 13959 protected boolean overScrollBy(int deltaX, int deltaY, 13960 int scrollX, int scrollY, 13961 int scrollRangeX, int scrollRangeY, 13962 int maxOverScrollX, int maxOverScrollY, 13963 boolean isTouchEvent) { 13964 final int overScrollMode = mOverScrollMode; 13965 final boolean canScrollHorizontal = 13966 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 13967 final boolean canScrollVertical = 13968 computeVerticalScrollRange() > computeVerticalScrollExtent(); 13969 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 13970 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 13971 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 13972 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 13973 13974 int newScrollX = scrollX + deltaX; 13975 if (!overScrollHorizontal) { 13976 maxOverScrollX = 0; 13977 } 13978 13979 int newScrollY = scrollY + deltaY; 13980 if (!overScrollVertical) { 13981 maxOverScrollY = 0; 13982 } 13983 13984 // Clamp values if at the limits and record 13985 final int left = -maxOverScrollX; 13986 final int right = maxOverScrollX + scrollRangeX; 13987 final int top = -maxOverScrollY; 13988 final int bottom = maxOverScrollY + scrollRangeY; 13989 13990 boolean clampedX = false; 13991 if (newScrollX > right) { 13992 newScrollX = right; 13993 clampedX = true; 13994 } else if (newScrollX < left) { 13995 newScrollX = left; 13996 clampedX = true; 13997 } 13998 13999 boolean clampedY = false; 14000 if (newScrollY > bottom) { 14001 newScrollY = bottom; 14002 clampedY = true; 14003 } else if (newScrollY < top) { 14004 newScrollY = top; 14005 clampedY = true; 14006 } 14007 14008 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 14009 14010 return clampedX || clampedY; 14011 } 14012 14013 /** 14014 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 14015 * respond to the results of an over-scroll operation. 14016 * 14017 * @param scrollX New X scroll value in pixels 14018 * @param scrollY New Y scroll value in pixels 14019 * @param clampedX True if scrollX was clamped to an over-scroll boundary 14020 * @param clampedY True if scrollY was clamped to an over-scroll boundary 14021 */ 14022 protected void onOverScrolled(int scrollX, int scrollY, 14023 boolean clampedX, boolean clampedY) { 14024 // Intentionally empty. 14025 } 14026 14027 /** 14028 * Returns the over-scroll mode for this view. The result will be 14029 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 14030 * (allow over-scrolling only if the view content is larger than the container), 14031 * or {@link #OVER_SCROLL_NEVER}. 14032 * 14033 * @return This view's over-scroll mode. 14034 */ 14035 public int getOverScrollMode() { 14036 return mOverScrollMode; 14037 } 14038 14039 /** 14040 * Set the over-scroll mode for this view. Valid over-scroll modes are 14041 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 14042 * (allow over-scrolling only if the view content is larger than the container), 14043 * or {@link #OVER_SCROLL_NEVER}. 14044 * 14045 * Setting the over-scroll mode of a view will have an effect only if the 14046 * view is capable of scrolling. 14047 * 14048 * @param overScrollMode The new over-scroll mode for this view. 14049 */ 14050 public void setOverScrollMode(int overScrollMode) { 14051 if (overScrollMode != OVER_SCROLL_ALWAYS && 14052 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 14053 overScrollMode != OVER_SCROLL_NEVER) { 14054 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 14055 } 14056 mOverScrollMode = overScrollMode; 14057 } 14058 14059 /** 14060 * Gets a scale factor that determines the distance the view should scroll 14061 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 14062 * @return The vertical scroll scale factor. 14063 * @hide 14064 */ 14065 protected float getVerticalScrollFactor() { 14066 if (mVerticalScrollFactor == 0) { 14067 TypedValue outValue = new TypedValue(); 14068 if (!mContext.getTheme().resolveAttribute( 14069 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 14070 throw new IllegalStateException( 14071 "Expected theme to define listPreferredItemHeight."); 14072 } 14073 mVerticalScrollFactor = outValue.getDimension( 14074 mContext.getResources().getDisplayMetrics()); 14075 } 14076 return mVerticalScrollFactor; 14077 } 14078 14079 /** 14080 * Gets a scale factor that determines the distance the view should scroll 14081 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 14082 * @return The horizontal scroll scale factor. 14083 * @hide 14084 */ 14085 protected float getHorizontalScrollFactor() { 14086 // TODO: Should use something else. 14087 return getVerticalScrollFactor(); 14088 } 14089 14090 /** 14091 * Return the value specifying the text direction or policy that was set with 14092 * {@link #setTextDirection(int)}. 14093 * 14094 * @return the defined text direction. It can be one of: 14095 * 14096 * {@link #TEXT_DIRECTION_INHERIT}, 14097 * {@link #TEXT_DIRECTION_FIRST_STRONG} 14098 * {@link #TEXT_DIRECTION_ANY_RTL}, 14099 * {@link #TEXT_DIRECTION_LTR}, 14100 * {@link #TEXT_DIRECTION_RTL}, 14101 * {@link #TEXT_DIRECTION_LOCALE}, 14102 * 14103 * @hide 14104 */ 14105 public int getTextDirection() { 14106 return mTextDirection; 14107 } 14108 14109 /** 14110 * Set the text direction. 14111 * 14112 * @param textDirection the direction to set. Should be one of: 14113 * 14114 * {@link #TEXT_DIRECTION_INHERIT}, 14115 * {@link #TEXT_DIRECTION_FIRST_STRONG} 14116 * {@link #TEXT_DIRECTION_ANY_RTL}, 14117 * {@link #TEXT_DIRECTION_LTR}, 14118 * {@link #TEXT_DIRECTION_RTL}, 14119 * {@link #TEXT_DIRECTION_LOCALE}, 14120 * 14121 * @hide 14122 */ 14123 public void setTextDirection(int textDirection) { 14124 if (textDirection != mTextDirection) { 14125 mTextDirection = textDirection; 14126 resetResolvedTextDirection(); 14127 requestLayout(); 14128 } 14129 } 14130 14131 /** 14132 * Return the resolved text direction. 14133 * 14134 * @return the resolved text direction. Return one of: 14135 * 14136 * {@link #TEXT_DIRECTION_FIRST_STRONG} 14137 * {@link #TEXT_DIRECTION_ANY_RTL}, 14138 * {@link #TEXT_DIRECTION_LTR}, 14139 * {@link #TEXT_DIRECTION_RTL}, 14140 * {@link #TEXT_DIRECTION_LOCALE}, 14141 * 14142 * @hide 14143 */ 14144 public int getResolvedTextDirection() { 14145 if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) { 14146 resolveTextDirection(); 14147 } 14148 return mResolvedTextDirection; 14149 } 14150 14151 /** 14152 * Resolve the text direction. 14153 * 14154 * @hide 14155 */ 14156 protected void resolveTextDirection() { 14157 if (mTextDirection != TEXT_DIRECTION_INHERIT) { 14158 mResolvedTextDirection = mTextDirection; 14159 return; 14160 } 14161 if (mParent != null && mParent instanceof ViewGroup) { 14162 mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection(); 14163 return; 14164 } 14165 mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG; 14166 } 14167 14168 /** 14169 * Reset resolved text direction. Will be resolved during a call to getResolvedTextDirection(). 14170 * 14171 * @hide 14172 */ 14173 protected void resetResolvedTextDirection() { 14174 mResolvedTextDirection = TEXT_DIRECTION_INHERIT; 14175 } 14176 14177 // 14178 // Properties 14179 // 14180 /** 14181 * A Property wrapper around the <code>alpha</code> functionality handled by the 14182 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 14183 */ 14184 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 14185 @Override 14186 public void setValue(View object, float value) { 14187 object.setAlpha(value); 14188 } 14189 14190 @Override 14191 public Float get(View object) { 14192 return object.getAlpha(); 14193 } 14194 }; 14195 14196 /** 14197 * A Property wrapper around the <code>translationX</code> functionality handled by the 14198 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 14199 */ 14200 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 14201 @Override 14202 public void setValue(View object, float value) { 14203 object.setTranslationX(value); 14204 } 14205 14206 @Override 14207 public Float get(View object) { 14208 return object.getTranslationX(); 14209 } 14210 }; 14211 14212 /** 14213 * A Property wrapper around the <code>translationY</code> functionality handled by the 14214 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 14215 */ 14216 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 14217 @Override 14218 public void setValue(View object, float value) { 14219 object.setTranslationY(value); 14220 } 14221 14222 @Override 14223 public Float get(View object) { 14224 return object.getTranslationY(); 14225 } 14226 }; 14227 14228 /** 14229 * A Property wrapper around the <code>x</code> functionality handled by the 14230 * {@link View#setX(float)} and {@link View#getX()} methods. 14231 */ 14232 public static final Property<View, Float> X = new FloatProperty<View>("x") { 14233 @Override 14234 public void setValue(View object, float value) { 14235 object.setX(value); 14236 } 14237 14238 @Override 14239 public Float get(View object) { 14240 return object.getX(); 14241 } 14242 }; 14243 14244 /** 14245 * A Property wrapper around the <code>y</code> functionality handled by the 14246 * {@link View#setY(float)} and {@link View#getY()} methods. 14247 */ 14248 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 14249 @Override 14250 public void setValue(View object, float value) { 14251 object.setY(value); 14252 } 14253 14254 @Override 14255 public Float get(View object) { 14256 return object.getY(); 14257 } 14258 }; 14259 14260 /** 14261 * A Property wrapper around the <code>rotation</code> functionality handled by the 14262 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 14263 */ 14264 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 14265 @Override 14266 public void setValue(View object, float value) { 14267 object.setRotation(value); 14268 } 14269 14270 @Override 14271 public Float get(View object) { 14272 return object.getRotation(); 14273 } 14274 }; 14275 14276 /** 14277 * A Property wrapper around the <code>rotationX</code> functionality handled by the 14278 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 14279 */ 14280 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 14281 @Override 14282 public void setValue(View object, float value) { 14283 object.setRotationX(value); 14284 } 14285 14286 @Override 14287 public Float get(View object) { 14288 return object.getRotationX(); 14289 } 14290 }; 14291 14292 /** 14293 * A Property wrapper around the <code>rotationY</code> functionality handled by the 14294 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 14295 */ 14296 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 14297 @Override 14298 public void setValue(View object, float value) { 14299 object.setRotationY(value); 14300 } 14301 14302 @Override 14303 public Float get(View object) { 14304 return object.getRotationY(); 14305 } 14306 }; 14307 14308 /** 14309 * A Property wrapper around the <code>scaleX</code> functionality handled by the 14310 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 14311 */ 14312 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 14313 @Override 14314 public void setValue(View object, float value) { 14315 object.setScaleX(value); 14316 } 14317 14318 @Override 14319 public Float get(View object) { 14320 return object.getScaleX(); 14321 } 14322 }; 14323 14324 /** 14325 * A Property wrapper around the <code>scaleY</code> functionality handled by the 14326 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 14327 */ 14328 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 14329 @Override 14330 public void setValue(View object, float value) { 14331 object.setScaleY(value); 14332 } 14333 14334 @Override 14335 public Float get(View object) { 14336 return object.getScaleY(); 14337 } 14338 }; 14339 14340 /** 14341 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 14342 * Each MeasureSpec represents a requirement for either the width or the height. 14343 * A MeasureSpec is comprised of a size and a mode. There are three possible 14344 * modes: 14345 * <dl> 14346 * <dt>UNSPECIFIED</dt> 14347 * <dd> 14348 * The parent has not imposed any constraint on the child. It can be whatever size 14349 * it wants. 14350 * </dd> 14351 * 14352 * <dt>EXACTLY</dt> 14353 * <dd> 14354 * The parent has determined an exact size for the child. The child is going to be 14355 * given those bounds regardless of how big it wants to be. 14356 * </dd> 14357 * 14358 * <dt>AT_MOST</dt> 14359 * <dd> 14360 * The child can be as large as it wants up to the specified size. 14361 * </dd> 14362 * </dl> 14363 * 14364 * MeasureSpecs are implemented as ints to reduce object allocation. This class 14365 * is provided to pack and unpack the <size, mode> tuple into the int. 14366 */ 14367 public static class MeasureSpec { 14368 private static final int MODE_SHIFT = 30; 14369 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 14370 14371 /** 14372 * Measure specification mode: The parent has not imposed any constraint 14373 * on the child. It can be whatever size it wants. 14374 */ 14375 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 14376 14377 /** 14378 * Measure specification mode: The parent has determined an exact size 14379 * for the child. The child is going to be given those bounds regardless 14380 * of how big it wants to be. 14381 */ 14382 public static final int EXACTLY = 1 << MODE_SHIFT; 14383 14384 /** 14385 * Measure specification mode: The child can be as large as it wants up 14386 * to the specified size. 14387 */ 14388 public static final int AT_MOST = 2 << MODE_SHIFT; 14389 14390 /** 14391 * Creates a measure specification based on the supplied size and mode. 14392 * 14393 * The mode must always be one of the following: 14394 * <ul> 14395 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 14396 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 14397 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 14398 * </ul> 14399 * 14400 * @param size the size of the measure specification 14401 * @param mode the mode of the measure specification 14402 * @return the measure specification based on size and mode 14403 */ 14404 public static int makeMeasureSpec(int size, int mode) { 14405 return size + mode; 14406 } 14407 14408 /** 14409 * Extracts the mode from the supplied measure specification. 14410 * 14411 * @param measureSpec the measure specification to extract the mode from 14412 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 14413 * {@link android.view.View.MeasureSpec#AT_MOST} or 14414 * {@link android.view.View.MeasureSpec#EXACTLY} 14415 */ 14416 public static int getMode(int measureSpec) { 14417 return (measureSpec & MODE_MASK); 14418 } 14419 14420 /** 14421 * Extracts the size from the supplied measure specification. 14422 * 14423 * @param measureSpec the measure specification to extract the size from 14424 * @return the size in pixels defined in the supplied measure specification 14425 */ 14426 public static int getSize(int measureSpec) { 14427 return (measureSpec & ~MODE_MASK); 14428 } 14429 14430 /** 14431 * Returns a String representation of the specified measure 14432 * specification. 14433 * 14434 * @param measureSpec the measure specification to convert to a String 14435 * @return a String with the following format: "MeasureSpec: MODE SIZE" 14436 */ 14437 public static String toString(int measureSpec) { 14438 int mode = getMode(measureSpec); 14439 int size = getSize(measureSpec); 14440 14441 StringBuilder sb = new StringBuilder("MeasureSpec: "); 14442 14443 if (mode == UNSPECIFIED) 14444 sb.append("UNSPECIFIED "); 14445 else if (mode == EXACTLY) 14446 sb.append("EXACTLY "); 14447 else if (mode == AT_MOST) 14448 sb.append("AT_MOST "); 14449 else 14450 sb.append(mode).append(" "); 14451 14452 sb.append(size); 14453 return sb.toString(); 14454 } 14455 } 14456 14457 class CheckForLongPress implements Runnable { 14458 14459 private int mOriginalWindowAttachCount; 14460 14461 public void run() { 14462 if (isPressed() && (mParent != null) 14463 && mOriginalWindowAttachCount == mWindowAttachCount) { 14464 if (performLongClick()) { 14465 mHasPerformedLongPress = true; 14466 } 14467 } 14468 } 14469 14470 public void rememberWindowAttachCount() { 14471 mOriginalWindowAttachCount = mWindowAttachCount; 14472 } 14473 } 14474 14475 private final class CheckForTap implements Runnable { 14476 public void run() { 14477 mPrivateFlags &= ~PREPRESSED; 14478 mPrivateFlags |= PRESSED; 14479 refreshDrawableState(); 14480 checkForLongClick(ViewConfiguration.getTapTimeout()); 14481 } 14482 } 14483 14484 private final class PerformClick implements Runnable { 14485 public void run() { 14486 performClick(); 14487 } 14488 } 14489 14490 /** @hide */ 14491 public void hackTurnOffWindowResizeAnim(boolean off) { 14492 mAttachInfo.mTurnOffWindowResizeAnim = off; 14493 } 14494 14495 /** 14496 * This method returns a ViewPropertyAnimator object, which can be used to animate 14497 * specific properties on this View. 14498 * 14499 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 14500 */ 14501 public ViewPropertyAnimator animate() { 14502 if (mAnimator == null) { 14503 mAnimator = new ViewPropertyAnimator(this); 14504 } 14505 return mAnimator; 14506 } 14507 14508 /** 14509 * Interface definition for a callback to be invoked when a key event is 14510 * dispatched to this view. The callback will be invoked before the key 14511 * event is given to the view. 14512 */ 14513 public interface OnKeyListener { 14514 /** 14515 * Called when a key is dispatched to a view. This allows listeners to 14516 * get a chance to respond before the target view. 14517 * 14518 * @param v The view the key has been dispatched to. 14519 * @param keyCode The code for the physical key that was pressed 14520 * @param event The KeyEvent object containing full information about 14521 * the event. 14522 * @return True if the listener has consumed the event, false otherwise. 14523 */ 14524 boolean onKey(View v, int keyCode, KeyEvent event); 14525 } 14526 14527 /** 14528 * Interface definition for a callback to be invoked when a touch event is 14529 * dispatched to this view. The callback will be invoked before the touch 14530 * event is given to the view. 14531 */ 14532 public interface OnTouchListener { 14533 /** 14534 * Called when a touch event is dispatched to a view. This allows listeners to 14535 * get a chance to respond before the target view. 14536 * 14537 * @param v The view the touch event has been dispatched to. 14538 * @param event The MotionEvent object containing full information about 14539 * the event. 14540 * @return True if the listener has consumed the event, false otherwise. 14541 */ 14542 boolean onTouch(View v, MotionEvent event); 14543 } 14544 14545 /** 14546 * Interface definition for a callback to be invoked when a hover event is 14547 * dispatched to this view. The callback will be invoked before the hover 14548 * event is given to the view. 14549 */ 14550 public interface OnHoverListener { 14551 /** 14552 * Called when a hover event is dispatched to a view. This allows listeners to 14553 * get a chance to respond before the target view. 14554 * 14555 * @param v The view the hover event has been dispatched to. 14556 * @param event The MotionEvent object containing full information about 14557 * the event. 14558 * @return True if the listener has consumed the event, false otherwise. 14559 */ 14560 boolean onHover(View v, MotionEvent event); 14561 } 14562 14563 /** 14564 * Interface definition for a callback to be invoked when a generic motion event is 14565 * dispatched to this view. The callback will be invoked before the generic motion 14566 * event is given to the view. 14567 */ 14568 public interface OnGenericMotionListener { 14569 /** 14570 * Called when a generic motion event is dispatched to a view. This allows listeners to 14571 * get a chance to respond before the target view. 14572 * 14573 * @param v The view the generic motion event has been dispatched to. 14574 * @param event The MotionEvent object containing full information about 14575 * the event. 14576 * @return True if the listener has consumed the event, false otherwise. 14577 */ 14578 boolean onGenericMotion(View v, MotionEvent event); 14579 } 14580 14581 /** 14582 * Interface definition for a callback to be invoked when a view has been clicked and held. 14583 */ 14584 public interface OnLongClickListener { 14585 /** 14586 * Called when a view has been clicked and held. 14587 * 14588 * @param v The view that was clicked and held. 14589 * 14590 * @return true if the callback consumed the long click, false otherwise. 14591 */ 14592 boolean onLongClick(View v); 14593 } 14594 14595 /** 14596 * Interface definition for a callback to be invoked when a drag is being dispatched 14597 * to this view. The callback will be invoked before the hosting view's own 14598 * onDrag(event) method. If the listener wants to fall back to the hosting view's 14599 * onDrag(event) behavior, it should return 'false' from this callback. 14600 * 14601 * <div class="special reference"> 14602 * <h3>Developer Guides</h3> 14603 * <p>For a guide to implementing drag and drop features, read the 14604 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 14605 * </div> 14606 */ 14607 public interface OnDragListener { 14608 /** 14609 * Called when a drag event is dispatched to a view. This allows listeners 14610 * to get a chance to override base View behavior. 14611 * 14612 * @param v The View that received the drag event. 14613 * @param event The {@link android.view.DragEvent} object for the drag event. 14614 * @return {@code true} if the drag event was handled successfully, or {@code false} 14615 * if the drag event was not handled. Note that {@code false} will trigger the View 14616 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 14617 */ 14618 boolean onDrag(View v, DragEvent event); 14619 } 14620 14621 /** 14622 * Interface definition for a callback to be invoked when the focus state of 14623 * a view changed. 14624 */ 14625 public interface OnFocusChangeListener { 14626 /** 14627 * Called when the focus state of a view has changed. 14628 * 14629 * @param v The view whose state has changed. 14630 * @param hasFocus The new focus state of v. 14631 */ 14632 void onFocusChange(View v, boolean hasFocus); 14633 } 14634 14635 /** 14636 * Interface definition for a callback to be invoked when a view is clicked. 14637 */ 14638 public interface OnClickListener { 14639 /** 14640 * Called when a view has been clicked. 14641 * 14642 * @param v The view that was clicked. 14643 */ 14644 void onClick(View v); 14645 } 14646 14647 /** 14648 * Interface definition for a callback to be invoked when the context menu 14649 * for this view is being built. 14650 */ 14651 public interface OnCreateContextMenuListener { 14652 /** 14653 * Called when the context menu for this view is being built. It is not 14654 * safe to hold onto the menu after this method returns. 14655 * 14656 * @param menu The context menu that is being built 14657 * @param v The view for which the context menu is being built 14658 * @param menuInfo Extra information about the item for which the 14659 * context menu should be shown. This information will vary 14660 * depending on the class of v. 14661 */ 14662 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 14663 } 14664 14665 /** 14666 * Interface definition for a callback to be invoked when the status bar changes 14667 * visibility. This reports <strong>global</strong> changes to the system UI 14668 * state, not just what the application is requesting. 14669 * 14670 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 14671 */ 14672 public interface OnSystemUiVisibilityChangeListener { 14673 /** 14674 * Called when the status bar changes visibility because of a call to 14675 * {@link View#setSystemUiVisibility(int)}. 14676 * 14677 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 14678 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. This tells you the 14679 * <strong>global</strong> state of the UI visibility flags, not what your 14680 * app is currently applying. 14681 */ 14682 public void onSystemUiVisibilityChange(int visibility); 14683 } 14684 14685 /** 14686 * Interface definition for a callback to be invoked when this view is attached 14687 * or detached from its window. 14688 */ 14689 public interface OnAttachStateChangeListener { 14690 /** 14691 * Called when the view is attached to a window. 14692 * @param v The view that was attached 14693 */ 14694 public void onViewAttachedToWindow(View v); 14695 /** 14696 * Called when the view is detached from a window. 14697 * @param v The view that was detached 14698 */ 14699 public void onViewDetachedFromWindow(View v); 14700 } 14701 14702 private final class UnsetPressedState implements Runnable { 14703 public void run() { 14704 setPressed(false); 14705 } 14706 } 14707 14708 /** 14709 * Base class for derived classes that want to save and restore their own 14710 * state in {@link android.view.View#onSaveInstanceState()}. 14711 */ 14712 public static class BaseSavedState extends AbsSavedState { 14713 /** 14714 * Constructor used when reading from a parcel. Reads the state of the superclass. 14715 * 14716 * @param source 14717 */ 14718 public BaseSavedState(Parcel source) { 14719 super(source); 14720 } 14721 14722 /** 14723 * Constructor called by derived classes when creating their SavedState objects 14724 * 14725 * @param superState The state of the superclass of this view 14726 */ 14727 public BaseSavedState(Parcelable superState) { 14728 super(superState); 14729 } 14730 14731 public static final Parcelable.Creator<BaseSavedState> CREATOR = 14732 new Parcelable.Creator<BaseSavedState>() { 14733 public BaseSavedState createFromParcel(Parcel in) { 14734 return new BaseSavedState(in); 14735 } 14736 14737 public BaseSavedState[] newArray(int size) { 14738 return new BaseSavedState[size]; 14739 } 14740 }; 14741 } 14742 14743 /** 14744 * A set of information given to a view when it is attached to its parent 14745 * window. 14746 */ 14747 static class AttachInfo { 14748 interface Callbacks { 14749 void playSoundEffect(int effectId); 14750 boolean performHapticFeedback(int effectId, boolean always); 14751 } 14752 14753 /** 14754 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 14755 * to a Handler. This class contains the target (View) to invalidate and 14756 * the coordinates of the dirty rectangle. 14757 * 14758 * For performance purposes, this class also implements a pool of up to 14759 * POOL_LIMIT objects that get reused. This reduces memory allocations 14760 * whenever possible. 14761 */ 14762 static class InvalidateInfo implements Poolable<InvalidateInfo> { 14763 private static final int POOL_LIMIT = 10; 14764 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 14765 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 14766 public InvalidateInfo newInstance() { 14767 return new InvalidateInfo(); 14768 } 14769 14770 public void onAcquired(InvalidateInfo element) { 14771 } 14772 14773 public void onReleased(InvalidateInfo element) { 14774 element.target = null; 14775 } 14776 }, POOL_LIMIT) 14777 ); 14778 14779 private InvalidateInfo mNext; 14780 private boolean mIsPooled; 14781 14782 View target; 14783 14784 int left; 14785 int top; 14786 int right; 14787 int bottom; 14788 14789 public void setNextPoolable(InvalidateInfo element) { 14790 mNext = element; 14791 } 14792 14793 public InvalidateInfo getNextPoolable() { 14794 return mNext; 14795 } 14796 14797 static InvalidateInfo acquire() { 14798 return sPool.acquire(); 14799 } 14800 14801 void release() { 14802 sPool.release(this); 14803 } 14804 14805 public boolean isPooled() { 14806 return mIsPooled; 14807 } 14808 14809 public void setPooled(boolean isPooled) { 14810 mIsPooled = isPooled; 14811 } 14812 } 14813 14814 final IWindowSession mSession; 14815 14816 final IWindow mWindow; 14817 14818 final IBinder mWindowToken; 14819 14820 final Callbacks mRootCallbacks; 14821 14822 HardwareCanvas mHardwareCanvas; 14823 14824 /** 14825 * The top view of the hierarchy. 14826 */ 14827 View mRootView; 14828 14829 IBinder mPanelParentWindowToken; 14830 Surface mSurface; 14831 14832 boolean mHardwareAccelerated; 14833 boolean mHardwareAccelerationRequested; 14834 HardwareRenderer mHardwareRenderer; 14835 14836 /** 14837 * Scale factor used by the compatibility mode 14838 */ 14839 float mApplicationScale; 14840 14841 /** 14842 * Indicates whether the application is in compatibility mode 14843 */ 14844 boolean mScalingRequired; 14845 14846 /** 14847 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 14848 */ 14849 boolean mTurnOffWindowResizeAnim; 14850 14851 /** 14852 * Left position of this view's window 14853 */ 14854 int mWindowLeft; 14855 14856 /** 14857 * Top position of this view's window 14858 */ 14859 int mWindowTop; 14860 14861 /** 14862 * Indicates whether views need to use 32-bit drawing caches 14863 */ 14864 boolean mUse32BitDrawingCache; 14865 14866 /** 14867 * For windows that are full-screen but using insets to layout inside 14868 * of the screen decorations, these are the current insets for the 14869 * content of the window. 14870 */ 14871 final Rect mContentInsets = new Rect(); 14872 14873 /** 14874 * For windows that are full-screen but using insets to layout inside 14875 * of the screen decorations, these are the current insets for the 14876 * actual visible parts of the window. 14877 */ 14878 final Rect mVisibleInsets = new Rect(); 14879 14880 /** 14881 * The internal insets given by this window. This value is 14882 * supplied by the client (through 14883 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 14884 * be given to the window manager when changed to be used in laying 14885 * out windows behind it. 14886 */ 14887 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 14888 = new ViewTreeObserver.InternalInsetsInfo(); 14889 14890 /** 14891 * All views in the window's hierarchy that serve as scroll containers, 14892 * used to determine if the window can be resized or must be panned 14893 * to adjust for a soft input area. 14894 */ 14895 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 14896 14897 final KeyEvent.DispatcherState mKeyDispatchState 14898 = new KeyEvent.DispatcherState(); 14899 14900 /** 14901 * Indicates whether the view's window currently has the focus. 14902 */ 14903 boolean mHasWindowFocus; 14904 14905 /** 14906 * The current visibility of the window. 14907 */ 14908 int mWindowVisibility; 14909 14910 /** 14911 * Indicates the time at which drawing started to occur. 14912 */ 14913 long mDrawingTime; 14914 14915 /** 14916 * Indicates whether or not ignoring the DIRTY_MASK flags. 14917 */ 14918 boolean mIgnoreDirtyState; 14919 14920 /** 14921 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 14922 * to avoid clearing that flag prematurely. 14923 */ 14924 boolean mSetIgnoreDirtyState = false; 14925 14926 /** 14927 * Indicates whether the view's window is currently in touch mode. 14928 */ 14929 boolean mInTouchMode; 14930 14931 /** 14932 * Indicates that ViewAncestor should trigger a global layout change 14933 * the next time it performs a traversal 14934 */ 14935 boolean mRecomputeGlobalAttributes; 14936 14937 /** 14938 * Always report new attributes at next traversal. 14939 */ 14940 boolean mForceReportNewAttributes; 14941 14942 /** 14943 * Set during a traveral if any views want to keep the screen on. 14944 */ 14945 boolean mKeepScreenOn; 14946 14947 /** 14948 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 14949 */ 14950 int mSystemUiVisibility; 14951 14952 /** 14953 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 14954 * attached. 14955 */ 14956 boolean mHasSystemUiListeners; 14957 14958 /** 14959 * Set if the visibility of any views has changed. 14960 */ 14961 boolean mViewVisibilityChanged; 14962 14963 /** 14964 * Set to true if a view has been scrolled. 14965 */ 14966 boolean mViewScrollChanged; 14967 14968 /** 14969 * Global to the view hierarchy used as a temporary for dealing with 14970 * x/y points in the transparent region computations. 14971 */ 14972 final int[] mTransparentLocation = new int[2]; 14973 14974 /** 14975 * Global to the view hierarchy used as a temporary for dealing with 14976 * x/y points in the ViewGroup.invalidateChild implementation. 14977 */ 14978 final int[] mInvalidateChildLocation = new int[2]; 14979 14980 14981 /** 14982 * Global to the view hierarchy used as a temporary for dealing with 14983 * x/y location when view is transformed. 14984 */ 14985 final float[] mTmpTransformLocation = new float[2]; 14986 14987 /** 14988 * The view tree observer used to dispatch global events like 14989 * layout, pre-draw, touch mode change, etc. 14990 */ 14991 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 14992 14993 /** 14994 * A Canvas used by the view hierarchy to perform bitmap caching. 14995 */ 14996 Canvas mCanvas; 14997 14998 /** 14999 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 15000 * handler can be used to pump events in the UI events queue. 15001 */ 15002 final Handler mHandler; 15003 15004 /** 15005 * Identifier for messages requesting the view to be invalidated. 15006 * Such messages should be sent to {@link #mHandler}. 15007 */ 15008 static final int INVALIDATE_MSG = 0x1; 15009 15010 /** 15011 * Identifier for messages requesting the view to invalidate a region. 15012 * Such messages should be sent to {@link #mHandler}. 15013 */ 15014 static final int INVALIDATE_RECT_MSG = 0x2; 15015 15016 /** 15017 * Temporary for use in computing invalidate rectangles while 15018 * calling up the hierarchy. 15019 */ 15020 final Rect mTmpInvalRect = new Rect(); 15021 15022 /** 15023 * Temporary for use in computing hit areas with transformed views 15024 */ 15025 final RectF mTmpTransformRect = new RectF(); 15026 15027 /** 15028 * Temporary list for use in collecting focusable descendents of a view. 15029 */ 15030 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 15031 15032 /** 15033 * The id of the window for accessibility purposes. 15034 */ 15035 int mAccessibilityWindowId = View.NO_ID; 15036 15037 /** 15038 * Creates a new set of attachment information with the specified 15039 * events handler and thread. 15040 * 15041 * @param handler the events handler the view must use 15042 */ 15043 AttachInfo(IWindowSession session, IWindow window, 15044 Handler handler, Callbacks effectPlayer) { 15045 mSession = session; 15046 mWindow = window; 15047 mWindowToken = window.asBinder(); 15048 mHandler = handler; 15049 mRootCallbacks = effectPlayer; 15050 } 15051 } 15052 15053 /** 15054 * <p>ScrollabilityCache holds various fields used by a View when scrolling 15055 * is supported. This avoids keeping too many unused fields in most 15056 * instances of View.</p> 15057 */ 15058 private static class ScrollabilityCache implements Runnable { 15059 15060 /** 15061 * Scrollbars are not visible 15062 */ 15063 public static final int OFF = 0; 15064 15065 /** 15066 * Scrollbars are visible 15067 */ 15068 public static final int ON = 1; 15069 15070 /** 15071 * Scrollbars are fading away 15072 */ 15073 public static final int FADING = 2; 15074 15075 public boolean fadeScrollBars; 15076 15077 public int fadingEdgeLength; 15078 public int scrollBarDefaultDelayBeforeFade; 15079 public int scrollBarFadeDuration; 15080 15081 public int scrollBarSize; 15082 public ScrollBarDrawable scrollBar; 15083 public float[] interpolatorValues; 15084 public View host; 15085 15086 public final Paint paint; 15087 public final Matrix matrix; 15088 public Shader shader; 15089 15090 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 15091 15092 private static final float[] OPAQUE = { 255 }; 15093 private static final float[] TRANSPARENT = { 0.0f }; 15094 15095 /** 15096 * When fading should start. This time moves into the future every time 15097 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 15098 */ 15099 public long fadeStartTime; 15100 15101 15102 /** 15103 * The current state of the scrollbars: ON, OFF, or FADING 15104 */ 15105 public int state = OFF; 15106 15107 private int mLastColor; 15108 15109 public ScrollabilityCache(ViewConfiguration configuration, View host) { 15110 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 15111 scrollBarSize = configuration.getScaledScrollBarSize(); 15112 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 15113 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 15114 15115 paint = new Paint(); 15116 matrix = new Matrix(); 15117 // use use a height of 1, and then wack the matrix each time we 15118 // actually use it. 15119 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 15120 15121 paint.setShader(shader); 15122 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 15123 this.host = host; 15124 } 15125 15126 public void setFadeColor(int color) { 15127 if (color != 0 && color != mLastColor) { 15128 mLastColor = color; 15129 color |= 0xFF000000; 15130 15131 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 15132 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 15133 15134 paint.setShader(shader); 15135 // Restore the default transfer mode (src_over) 15136 paint.setXfermode(null); 15137 } 15138 } 15139 15140 public void run() { 15141 long now = AnimationUtils.currentAnimationTimeMillis(); 15142 if (now >= fadeStartTime) { 15143 15144 // the animation fades the scrollbars out by changing 15145 // the opacity (alpha) from fully opaque to fully 15146 // transparent 15147 int nextFrame = (int) now; 15148 int framesCount = 0; 15149 15150 Interpolator interpolator = scrollBarInterpolator; 15151 15152 // Start opaque 15153 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 15154 15155 // End transparent 15156 nextFrame += scrollBarFadeDuration; 15157 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 15158 15159 state = FADING; 15160 15161 // Kick off the fade animation 15162 host.invalidate(true); 15163 } 15164 } 15165 } 15166 15167 /** 15168 * Resuable callback for sending 15169 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 15170 */ 15171 private class SendViewScrolledAccessibilityEvent implements Runnable { 15172 public volatile boolean mIsPending; 15173 15174 public void run() { 15175 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 15176 mIsPending = false; 15177 } 15178 } 15179 15180 /** 15181 * <p> 15182 * This class represents a delegate that can be registered in a {@link View} 15183 * to enhance accessibility support via composition rather via inheritance. 15184 * It is specifically targeted to widget developers that extend basic View 15185 * classes i.e. classes in package android.view, that would like their 15186 * applications to be backwards compatible. 15187 * </p> 15188 * <p> 15189 * A scenario in which a developer would like to use an accessibility delegate 15190 * is overriding a method introduced in a later API version then the minimal API 15191 * version supported by the application. For example, the method 15192 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 15193 * in API version 4 when the accessibility APIs were first introduced. If a 15194 * developer would like his application to run on API version 4 devices (assuming 15195 * all other APIs used by the application are version 4 or lower) and take advantage 15196 * of this method, instead of overriding the method which would break the application's 15197 * backwards compatibility, he can override the corresponding method in this 15198 * delegate and register the delegate in the target View if the API version of 15199 * the system is high enough i.e. the API version is same or higher to the API 15200 * version that introduced 15201 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 15202 * </p> 15203 * <p> 15204 * Here is an example implementation: 15205 * </p> 15206 * <code><pre><p> 15207 * if (Build.VERSION.SDK_INT >= 14) { 15208 * // If the API version is equal of higher than the version in 15209 * // which onInitializeAccessibilityNodeInfo was introduced we 15210 * // register a delegate with a customized implementation. 15211 * View view = findViewById(R.id.view_id); 15212 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 15213 * public void onInitializeAccessibilityNodeInfo(View host, 15214 * AccessibilityNodeInfo info) { 15215 * // Let the default implementation populate the info. 15216 * super.onInitializeAccessibilityNodeInfo(host, info); 15217 * // Set some other information. 15218 * info.setEnabled(host.isEnabled()); 15219 * } 15220 * }); 15221 * } 15222 * </code></pre></p> 15223 * <p> 15224 * This delegate contains methods that correspond to the accessibility methods 15225 * in View. If a delegate has been specified the implementation in View hands 15226 * off handling to the corresponding method in this delegate. The default 15227 * implementation the delegate methods behaves exactly as the corresponding 15228 * method in View for the case of no accessibility delegate been set. Hence, 15229 * to customize the behavior of a View method, clients can override only the 15230 * corresponding delegate method without altering the behavior of the rest 15231 * accessibility related methods of the host view. 15232 * </p> 15233 */ 15234 public static class AccessibilityDelegate { 15235 15236 /** 15237 * Sends an accessibility event of the given type. If accessibility is not 15238 * enabled this method has no effect. 15239 * <p> 15240 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 15241 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 15242 * been set. 15243 * </p> 15244 * 15245 * @param host The View hosting the delegate. 15246 * @param eventType The type of the event to send. 15247 * 15248 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 15249 */ 15250 public void sendAccessibilityEvent(View host, int eventType) { 15251 host.sendAccessibilityEventInternal(eventType); 15252 } 15253 15254 /** 15255 * Sends an accessibility event. This method behaves exactly as 15256 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 15257 * empty {@link AccessibilityEvent} and does not perform a check whether 15258 * accessibility is enabled. 15259 * <p> 15260 * The default implementation behaves as 15261 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 15262 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 15263 * the case of no accessibility delegate been set. 15264 * </p> 15265 * 15266 * @param host The View hosting the delegate. 15267 * @param event The event to send. 15268 * 15269 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 15270 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 15271 */ 15272 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 15273 host.sendAccessibilityEventUncheckedInternal(event); 15274 } 15275 15276 /** 15277 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 15278 * to its children for adding their text content to the event. 15279 * <p> 15280 * The default implementation behaves as 15281 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 15282 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 15283 * the case of no accessibility delegate been set. 15284 * </p> 15285 * 15286 * @param host The View hosting the delegate. 15287 * @param event The event. 15288 * @return True if the event population was completed. 15289 * 15290 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 15291 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 15292 */ 15293 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 15294 return host.dispatchPopulateAccessibilityEventInternal(event); 15295 } 15296 15297 /** 15298 * Gives a chance to the host View to populate the accessibility event with its 15299 * text content. 15300 * <p> 15301 * The default implementation behaves as 15302 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 15303 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 15304 * the case of no accessibility delegate been set. 15305 * </p> 15306 * 15307 * @param host The View hosting the delegate. 15308 * @param event The accessibility event which to populate. 15309 * 15310 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 15311 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 15312 */ 15313 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 15314 host.onPopulateAccessibilityEventInternal(event); 15315 } 15316 15317 /** 15318 * Initializes an {@link AccessibilityEvent} with information about the 15319 * the host View which is the event source. 15320 * <p> 15321 * The default implementation behaves as 15322 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 15323 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 15324 * the case of no accessibility delegate been set. 15325 * </p> 15326 * 15327 * @param host The View hosting the delegate. 15328 * @param event The event to initialize. 15329 * 15330 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 15331 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 15332 */ 15333 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 15334 host.onInitializeAccessibilityEventInternal(event); 15335 } 15336 15337 /** 15338 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 15339 * <p> 15340 * The default implementation behaves as 15341 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 15342 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 15343 * the case of no accessibility delegate been set. 15344 * </p> 15345 * 15346 * @param host The View hosting the delegate. 15347 * @param info The instance to initialize. 15348 * 15349 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 15350 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 15351 */ 15352 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 15353 host.onInitializeAccessibilityNodeInfoInternal(info); 15354 } 15355 15356 /** 15357 * Called when a child of the host View has requested sending an 15358 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 15359 * to augment the event. 15360 * <p> 15361 * The default implementation behaves as 15362 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 15363 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 15364 * the case of no accessibility delegate been set. 15365 * </p> 15366 * 15367 * @param host The View hosting the delegate. 15368 * @param child The child which requests sending the event. 15369 * @param event The event to be sent. 15370 * @return True if the event should be sent 15371 * 15372 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 15373 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 15374 */ 15375 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 15376 AccessibilityEvent event) { 15377 return host.onRequestSendAccessibilityEventInternal(child, event); 15378 } 15379 15380 /** 15381 * Gets the provider for managing a virtual view hierarchy rooted at this View 15382 * and reported to {@link android.accessibilityservice.AccessibilityService}s 15383 * that explore the window content. 15384 * <p> 15385 * The default implementation behaves as 15386 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 15387 * the case of no accessibility delegate been set. 15388 * </p> 15389 * 15390 * @return The provider. 15391 * 15392 * @see AccessibilityNodeProvider 15393 */ 15394 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 15395 return null; 15396 } 15397 } 15398} 15399