View.java revision a08f3e866a46c990e786defa95013ee0313b0887
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.content.ClipData; 20import android.content.Context; 21import android.content.res.Configuration; 22import android.content.res.Resources; 23import android.content.res.TypedArray; 24import android.graphics.Bitmap; 25import android.graphics.Camera; 26import android.graphics.Canvas; 27import android.graphics.Interpolator; 28import android.graphics.LinearGradient; 29import android.graphics.Matrix; 30import android.graphics.Paint; 31import android.graphics.PixelFormat; 32import android.graphics.Point; 33import android.graphics.PorterDuff; 34import android.graphics.PorterDuffXfermode; 35import android.graphics.Rect; 36import android.graphics.RectF; 37import android.graphics.Region; 38import android.graphics.Shader; 39import android.graphics.drawable.ColorDrawable; 40import android.graphics.drawable.Drawable; 41import android.os.Handler; 42import android.os.IBinder; 43import android.os.Parcel; 44import android.os.Parcelable; 45import android.os.RemoteException; 46import android.os.SystemClock; 47import android.text.TextUtils; 48import android.util.AttributeSet; 49import android.util.FloatProperty; 50import android.util.LocaleUtil; 51import android.util.Log; 52import android.util.Pool; 53import android.util.Poolable; 54import android.util.PoolableManager; 55import android.util.Pools; 56import android.util.Property; 57import android.util.SparseArray; 58import android.util.TypedValue; 59import android.view.ContextMenu.ContextMenuInfo; 60import android.view.accessibility.AccessibilityEvent; 61import android.view.accessibility.AccessibilityEventSource; 62import android.view.accessibility.AccessibilityManager; 63import android.view.accessibility.AccessibilityNodeInfo; 64import android.view.accessibility.AccessibilityNodeProvider; 65import android.view.animation.Animation; 66import android.view.animation.AnimationUtils; 67import android.view.animation.Transformation; 68import android.view.inputmethod.EditorInfo; 69import android.view.inputmethod.InputConnection; 70import android.view.inputmethod.InputMethodManager; 71import android.widget.ScrollBarDrawable; 72 73import static android.os.Build.VERSION_CODES.*; 74 75import com.android.internal.R; 76import com.android.internal.util.Predicate; 77import com.android.internal.view.menu.MenuBuilder; 78 79import java.lang.ref.WeakReference; 80import java.lang.reflect.InvocationTargetException; 81import java.lang.reflect.Method; 82import java.util.ArrayList; 83import java.util.Arrays; 84import java.util.Locale; 85import java.util.concurrent.CopyOnWriteArrayList; 86 87/** 88 * <p> 89 * This class represents the basic building block for user interface components. A View 90 * occupies a rectangular area on the screen and is responsible for drawing and 91 * event handling. View is the base class for <em>widgets</em>, which are 92 * used to create interactive UI components (buttons, text fields, etc.). The 93 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 94 * are invisible containers that hold other Views (or other ViewGroups) and define 95 * their layout properties. 96 * </p> 97 * 98 * <div class="special reference"> 99 * <h3>Developer Guides</h3> 100 * <p>For information about using this class to develop your application's user interface, 101 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 102 * </div> 103 * 104 * <a name="Using"></a> 105 * <h3>Using Views</h3> 106 * <p> 107 * All of the views in a window are arranged in a single tree. You can add views 108 * either from code or by specifying a tree of views in one or more XML layout 109 * files. There are many specialized subclasses of views that act as controls or 110 * are capable of displaying text, images, or other content. 111 * </p> 112 * <p> 113 * Once you have created a tree of views, there are typically a few types of 114 * common operations you may wish to perform: 115 * <ul> 116 * <li><strong>Set properties:</strong> for example setting the text of a 117 * {@link android.widget.TextView}. The available properties and the methods 118 * that set them will vary among the different subclasses of views. Note that 119 * properties that are known at build time can be set in the XML layout 120 * files.</li> 121 * <li><strong>Set focus:</strong> The framework will handled moving focus in 122 * response to user input. To force focus to a specific view, call 123 * {@link #requestFocus}.</li> 124 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 125 * that will be notified when something interesting happens to the view. For 126 * example, all views will let you set a listener to be notified when the view 127 * gains or loses focus. You can register such a listener using 128 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 129 * Other view subclasses offer more specialized listeners. For example, a Button 130 * exposes a listener to notify clients when the button is clicked.</li> 131 * <li><strong>Set visibility:</strong> You can hide or show views using 132 * {@link #setVisibility(int)}.</li> 133 * </ul> 134 * </p> 135 * <p><em> 136 * Note: The Android framework is responsible for measuring, laying out and 137 * drawing views. You should not call methods that perform these actions on 138 * views yourself unless you are actually implementing a 139 * {@link android.view.ViewGroup}. 140 * </em></p> 141 * 142 * <a name="Lifecycle"></a> 143 * <h3>Implementing a Custom View</h3> 144 * 145 * <p> 146 * To implement a custom view, you will usually begin by providing overrides for 147 * some of the standard methods that the framework calls on all views. You do 148 * not need to override all of these methods. In fact, you can start by just 149 * overriding {@link #onDraw(android.graphics.Canvas)}. 150 * <table border="2" width="85%" align="center" cellpadding="5"> 151 * <thead> 152 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 153 * </thead> 154 * 155 * <tbody> 156 * <tr> 157 * <td rowspan="2">Creation</td> 158 * <td>Constructors</td> 159 * <td>There is a form of the constructor that are called when the view 160 * is created from code and a form that is called when the view is 161 * inflated from a layout file. The second form should parse and apply 162 * any attributes defined in the layout file. 163 * </td> 164 * </tr> 165 * <tr> 166 * <td><code>{@link #onFinishInflate()}</code></td> 167 * <td>Called after a view and all of its children has been inflated 168 * from XML.</td> 169 * </tr> 170 * 171 * <tr> 172 * <td rowspan="3">Layout</td> 173 * <td><code>{@link #onMeasure(int, int)}</code></td> 174 * <td>Called to determine the size requirements for this view and all 175 * of its children. 176 * </td> 177 * </tr> 178 * <tr> 179 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 180 * <td>Called when this view should assign a size and position to all 181 * of its children. 182 * </td> 183 * </tr> 184 * <tr> 185 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 186 * <td>Called when the size of this view has changed. 187 * </td> 188 * </tr> 189 * 190 * <tr> 191 * <td>Drawing</td> 192 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 193 * <td>Called when the view should render its content. 194 * </td> 195 * </tr> 196 * 197 * <tr> 198 * <td rowspan="4">Event processing</td> 199 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 200 * <td>Called when a new key event occurs. 201 * </td> 202 * </tr> 203 * <tr> 204 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 205 * <td>Called when a key up event occurs. 206 * </td> 207 * </tr> 208 * <tr> 209 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 210 * <td>Called when a trackball motion event occurs. 211 * </td> 212 * </tr> 213 * <tr> 214 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 215 * <td>Called when a touch screen motion event occurs. 216 * </td> 217 * </tr> 218 * 219 * <tr> 220 * <td rowspan="2">Focus</td> 221 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 222 * <td>Called when the view gains or loses focus. 223 * </td> 224 * </tr> 225 * 226 * <tr> 227 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 228 * <td>Called when the window containing the view gains or loses focus. 229 * </td> 230 * </tr> 231 * 232 * <tr> 233 * <td rowspan="3">Attaching</td> 234 * <td><code>{@link #onAttachedToWindow()}</code></td> 235 * <td>Called when the view is attached to a window. 236 * </td> 237 * </tr> 238 * 239 * <tr> 240 * <td><code>{@link #onDetachedFromWindow}</code></td> 241 * <td>Called when the view is detached from its window. 242 * </td> 243 * </tr> 244 * 245 * <tr> 246 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 247 * <td>Called when the visibility of the window containing the view 248 * has changed. 249 * </td> 250 * </tr> 251 * </tbody> 252 * 253 * </table> 254 * </p> 255 * 256 * <a name="IDs"></a> 257 * <h3>IDs</h3> 258 * Views may have an integer id associated with them. These ids are typically 259 * assigned in the layout XML files, and are used to find specific views within 260 * the view tree. A common pattern is to: 261 * <ul> 262 * <li>Define a Button in the layout file and assign it a unique ID. 263 * <pre> 264 * <Button 265 * android:id="@+id/my_button" 266 * android:layout_width="wrap_content" 267 * android:layout_height="wrap_content" 268 * android:text="@string/my_button_text"/> 269 * </pre></li> 270 * <li>From the onCreate method of an Activity, find the Button 271 * <pre class="prettyprint"> 272 * Button myButton = (Button) findViewById(R.id.my_button); 273 * </pre></li> 274 * </ul> 275 * <p> 276 * View IDs need not be unique throughout the tree, but it is good practice to 277 * ensure that they are at least unique within the part of the tree you are 278 * searching. 279 * </p> 280 * 281 * <a name="Position"></a> 282 * <h3>Position</h3> 283 * <p> 284 * The geometry of a view is that of a rectangle. A view has a location, 285 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 286 * two dimensions, expressed as a width and a height. The unit for location 287 * and dimensions is the pixel. 288 * </p> 289 * 290 * <p> 291 * It is possible to retrieve the location of a view by invoking the methods 292 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 293 * coordinate of the rectangle representing the view. The latter returns the 294 * top, or Y, coordinate of the rectangle representing the view. These methods 295 * both return the location of the view relative to its parent. For instance, 296 * when getLeft() returns 20, that means the view is located 20 pixels to the 297 * right of the left edge of its direct parent. 298 * </p> 299 * 300 * <p> 301 * In addition, several convenience methods are offered to avoid unnecessary 302 * computations, namely {@link #getRight()} and {@link #getBottom()}. 303 * These methods return the coordinates of the right and bottom edges of the 304 * rectangle representing the view. For instance, calling {@link #getRight()} 305 * is similar to the following computation: <code>getLeft() + getWidth()</code> 306 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 307 * </p> 308 * 309 * <a name="SizePaddingMargins"></a> 310 * <h3>Size, padding and margins</h3> 311 * <p> 312 * The size of a view is expressed with a width and a height. A view actually 313 * possess two pairs of width and height values. 314 * </p> 315 * 316 * <p> 317 * The first pair is known as <em>measured width</em> and 318 * <em>measured height</em>. These dimensions define how big a view wants to be 319 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 320 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 321 * and {@link #getMeasuredHeight()}. 322 * </p> 323 * 324 * <p> 325 * The second pair is simply known as <em>width</em> and <em>height</em>, or 326 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 327 * dimensions define the actual size of the view on screen, at drawing time and 328 * after layout. These values may, but do not have to, be different from the 329 * measured width and height. The width and height can be obtained by calling 330 * {@link #getWidth()} and {@link #getHeight()}. 331 * </p> 332 * 333 * <p> 334 * To measure its dimensions, a view takes into account its padding. The padding 335 * is expressed in pixels for the left, top, right and bottom parts of the view. 336 * Padding can be used to offset the content of the view by a specific amount of 337 * pixels. For instance, a left padding of 2 will push the view's content by 338 * 2 pixels to the right of the left edge. Padding can be set using the 339 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 340 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 341 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 342 * {@link #getPaddingEnd()}. 343 * </p> 344 * 345 * <p> 346 * Even though a view can define a padding, it does not provide any support for 347 * margins. However, view groups provide such a support. Refer to 348 * {@link android.view.ViewGroup} and 349 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 350 * </p> 351 * 352 * <a name="Layout"></a> 353 * <h3>Layout</h3> 354 * <p> 355 * Layout is a two pass process: a measure pass and a layout pass. The measuring 356 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 357 * of the view tree. Each view pushes dimension specifications down the tree 358 * during the recursion. At the end of the measure pass, every view has stored 359 * its measurements. The second pass happens in 360 * {@link #layout(int,int,int,int)} and is also top-down. During 361 * this pass each parent is responsible for positioning all of its children 362 * using the sizes computed in the measure pass. 363 * </p> 364 * 365 * <p> 366 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 367 * {@link #getMeasuredHeight()} values must be set, along with those for all of 368 * that view's descendants. A view's measured width and measured height values 369 * must respect the constraints imposed by the view's parents. This guarantees 370 * that at the end of the measure pass, all parents accept all of their 371 * children's measurements. A parent view may call measure() more than once on 372 * its children. For example, the parent may measure each child once with 373 * unspecified dimensions to find out how big they want to be, then call 374 * measure() on them again with actual numbers if the sum of all the children's 375 * unconstrained sizes is too big or too small. 376 * </p> 377 * 378 * <p> 379 * The measure pass uses two classes to communicate dimensions. The 380 * {@link MeasureSpec} class is used by views to tell their parents how they 381 * want to be measured and positioned. The base LayoutParams class just 382 * describes how big the view wants to be for both width and height. For each 383 * dimension, it can specify one of: 384 * <ul> 385 * <li> an exact number 386 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 387 * (minus padding) 388 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 389 * enclose its content (plus padding). 390 * </ul> 391 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 392 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 393 * an X and Y value. 394 * </p> 395 * 396 * <p> 397 * MeasureSpecs are used to push requirements down the tree from parent to 398 * child. A MeasureSpec can be in one of three modes: 399 * <ul> 400 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 401 * of a child view. For example, a LinearLayout may call measure() on its child 402 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 403 * tall the child view wants to be given a width of 240 pixels. 404 * <li>EXACTLY: This is used by the parent to impose an exact size on the 405 * child. The child must use this size, and guarantee that all of its 406 * descendants will fit within this size. 407 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 408 * child. The child must gurantee that it and all of its descendants will fit 409 * within this size. 410 * </ul> 411 * </p> 412 * 413 * <p> 414 * To intiate a layout, call {@link #requestLayout}. This method is typically 415 * called by a view on itself when it believes that is can no longer fit within 416 * its current bounds. 417 * </p> 418 * 419 * <a name="Drawing"></a> 420 * <h3>Drawing</h3> 421 * <p> 422 * Drawing is handled by walking the tree and rendering each view that 423 * intersects the invalid region. Because the tree is traversed in-order, 424 * this means that parents will draw before (i.e., behind) their children, with 425 * siblings drawn in the order they appear in the tree. 426 * If you set a background drawable for a View, then the View will draw it for you 427 * before calling back to its <code>onDraw()</code> method. 428 * </p> 429 * 430 * <p> 431 * Note that the framework will not draw views that are not in the invalid region. 432 * </p> 433 * 434 * <p> 435 * To force a view to draw, call {@link #invalidate()}. 436 * </p> 437 * 438 * <a name="EventHandlingThreading"></a> 439 * <h3>Event Handling and Threading</h3> 440 * <p> 441 * The basic cycle of a view is as follows: 442 * <ol> 443 * <li>An event comes in and is dispatched to the appropriate view. The view 444 * handles the event and notifies any listeners.</li> 445 * <li>If in the course of processing the event, the view's bounds may need 446 * to be changed, the view will call {@link #requestLayout()}.</li> 447 * <li>Similarly, if in the course of processing the event the view's appearance 448 * may need to be changed, the view will call {@link #invalidate()}.</li> 449 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 450 * the framework will take care of measuring, laying out, and drawing the tree 451 * as appropriate.</li> 452 * </ol> 453 * </p> 454 * 455 * <p><em>Note: The entire view tree is single threaded. You must always be on 456 * the UI thread when calling any method on any view.</em> 457 * If you are doing work on other threads and want to update the state of a view 458 * from that thread, you should use a {@link Handler}. 459 * </p> 460 * 461 * <a name="FocusHandling"></a> 462 * <h3>Focus Handling</h3> 463 * <p> 464 * The framework will handle routine focus movement in response to user input. 465 * This includes changing the focus as views are removed or hidden, or as new 466 * views become available. Views indicate their willingness to take focus 467 * through the {@link #isFocusable} method. To change whether a view can take 468 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 469 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 470 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 471 * </p> 472 * <p> 473 * Focus movement is based on an algorithm which finds the nearest neighbor in a 474 * given direction. In rare cases, the default algorithm may not match the 475 * intended behavior of the developer. In these situations, you can provide 476 * explicit overrides by using these XML attributes in the layout file: 477 * <pre> 478 * nextFocusDown 479 * nextFocusLeft 480 * nextFocusRight 481 * nextFocusUp 482 * </pre> 483 * </p> 484 * 485 * 486 * <p> 487 * To get a particular view to take focus, call {@link #requestFocus()}. 488 * </p> 489 * 490 * <a name="TouchMode"></a> 491 * <h3>Touch Mode</h3> 492 * <p> 493 * When a user is navigating a user interface via directional keys such as a D-pad, it is 494 * necessary to give focus to actionable items such as buttons so the user can see 495 * what will take input. If the device has touch capabilities, however, and the user 496 * begins interacting with the interface by touching it, it is no longer necessary to 497 * always highlight, or give focus to, a particular view. This motivates a mode 498 * for interaction named 'touch mode'. 499 * </p> 500 * <p> 501 * For a touch capable device, once the user touches the screen, the device 502 * will enter touch mode. From this point onward, only views for which 503 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 504 * Other views that are touchable, like buttons, will not take focus when touched; they will 505 * only fire the on click listeners. 506 * </p> 507 * <p> 508 * Any time a user hits a directional key, such as a D-pad direction, the view device will 509 * exit touch mode, and find a view to take focus, so that the user may resume interacting 510 * with the user interface without touching the screen again. 511 * </p> 512 * <p> 513 * The touch mode state is maintained across {@link android.app.Activity}s. Call 514 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 515 * </p> 516 * 517 * <a name="Scrolling"></a> 518 * <h3>Scrolling</h3> 519 * <p> 520 * The framework provides basic support for views that wish to internally 521 * scroll their content. This includes keeping track of the X and Y scroll 522 * offset as well as mechanisms for drawing scrollbars. See 523 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 524 * {@link #awakenScrollBars()} for more details. 525 * </p> 526 * 527 * <a name="Tags"></a> 528 * <h3>Tags</h3> 529 * <p> 530 * Unlike IDs, tags are not used to identify views. Tags are essentially an 531 * extra piece of information that can be associated with a view. They are most 532 * often used as a convenience to store data related to views in the views 533 * themselves rather than by putting them in a separate structure. 534 * </p> 535 * 536 * <a name="Animation"></a> 537 * <h3>Animation</h3> 538 * <p> 539 * You can attach an {@link Animation} object to a view using 540 * {@link #setAnimation(Animation)} or 541 * {@link #startAnimation(Animation)}. The animation can alter the scale, 542 * rotation, translation and alpha of a view over time. If the animation is 543 * attached to a view that has children, the animation will affect the entire 544 * subtree rooted by that node. When an animation is started, the framework will 545 * take care of redrawing the appropriate views until the animation completes. 546 * </p> 547 * <p> 548 * Starting with Android 3.0, the preferred way of animating views is to use the 549 * {@link android.animation} package APIs. 550 * </p> 551 * 552 * <a name="Security"></a> 553 * <h3>Security</h3> 554 * <p> 555 * Sometimes it is essential that an application be able to verify that an action 556 * is being performed with the full knowledge and consent of the user, such as 557 * granting a permission request, making a purchase or clicking on an advertisement. 558 * Unfortunately, a malicious application could try to spoof the user into 559 * performing these actions, unaware, by concealing the intended purpose of the view. 560 * As a remedy, the framework offers a touch filtering mechanism that can be used to 561 * improve the security of views that provide access to sensitive functionality. 562 * </p><p> 563 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 564 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 565 * will discard touches that are received whenever the view's window is obscured by 566 * another visible window. As a result, the view will not receive touches whenever a 567 * toast, dialog or other window appears above the view's window. 568 * </p><p> 569 * For more fine-grained control over security, consider overriding the 570 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 571 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 572 * </p> 573 * 574 * @attr ref android.R.styleable#View_alpha 575 * @attr ref android.R.styleable#View_background 576 * @attr ref android.R.styleable#View_clickable 577 * @attr ref android.R.styleable#View_contentDescription 578 * @attr ref android.R.styleable#View_drawingCacheQuality 579 * @attr ref android.R.styleable#View_duplicateParentState 580 * @attr ref android.R.styleable#View_id 581 * @attr ref android.R.styleable#View_requiresFadingEdge 582 * @attr ref android.R.styleable#View_fadingEdgeLength 583 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 584 * @attr ref android.R.styleable#View_fitsSystemWindows 585 * @attr ref android.R.styleable#View_isScrollContainer 586 * @attr ref android.R.styleable#View_focusable 587 * @attr ref android.R.styleable#View_focusableInTouchMode 588 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 589 * @attr ref android.R.styleable#View_keepScreenOn 590 * @attr ref android.R.styleable#View_layerType 591 * @attr ref android.R.styleable#View_longClickable 592 * @attr ref android.R.styleable#View_minHeight 593 * @attr ref android.R.styleable#View_minWidth 594 * @attr ref android.R.styleable#View_nextFocusDown 595 * @attr ref android.R.styleable#View_nextFocusLeft 596 * @attr ref android.R.styleable#View_nextFocusRight 597 * @attr ref android.R.styleable#View_nextFocusUp 598 * @attr ref android.R.styleable#View_onClick 599 * @attr ref android.R.styleable#View_padding 600 * @attr ref android.R.styleable#View_paddingBottom 601 * @attr ref android.R.styleable#View_paddingLeft 602 * @attr ref android.R.styleable#View_paddingRight 603 * @attr ref android.R.styleable#View_paddingTop 604 * @attr ref android.R.styleable#View_paddingStart 605 * @attr ref android.R.styleable#View_paddingEnd 606 * @attr ref android.R.styleable#View_saveEnabled 607 * @attr ref android.R.styleable#View_rotation 608 * @attr ref android.R.styleable#View_rotationX 609 * @attr ref android.R.styleable#View_rotationY 610 * @attr ref android.R.styleable#View_scaleX 611 * @attr ref android.R.styleable#View_scaleY 612 * @attr ref android.R.styleable#View_scrollX 613 * @attr ref android.R.styleable#View_scrollY 614 * @attr ref android.R.styleable#View_scrollbarSize 615 * @attr ref android.R.styleable#View_scrollbarStyle 616 * @attr ref android.R.styleable#View_scrollbars 617 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 618 * @attr ref android.R.styleable#View_scrollbarFadeDuration 619 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 620 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 621 * @attr ref android.R.styleable#View_scrollbarThumbVertical 622 * @attr ref android.R.styleable#View_scrollbarTrackVertical 623 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 624 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 625 * @attr ref android.R.styleable#View_soundEffectsEnabled 626 * @attr ref android.R.styleable#View_tag 627 * @attr ref android.R.styleable#View_transformPivotX 628 * @attr ref android.R.styleable#View_transformPivotY 629 * @attr ref android.R.styleable#View_translationX 630 * @attr ref android.R.styleable#View_translationY 631 * @attr ref android.R.styleable#View_visibility 632 * 633 * @see android.view.ViewGroup 634 */ 635public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback, 636 AccessibilityEventSource { 637 private static final boolean DBG = false; 638 639 /** 640 * The logging tag used by this class with android.util.Log. 641 */ 642 protected static final String VIEW_LOG_TAG = "View"; 643 644 /** 645 * Used to mark a View that has no ID. 646 */ 647 public static final int NO_ID = -1; 648 649 /** 650 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 651 * calling setFlags. 652 */ 653 private static final int NOT_FOCUSABLE = 0x00000000; 654 655 /** 656 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 657 * setFlags. 658 */ 659 private static final int FOCUSABLE = 0x00000001; 660 661 /** 662 * Mask for use with setFlags indicating bits used for focus. 663 */ 664 private static final int FOCUSABLE_MASK = 0x00000001; 665 666 /** 667 * This view will adjust its padding to fit sytem windows (e.g. status bar) 668 */ 669 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 670 671 /** 672 * This view is visible. 673 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 674 * android:visibility}. 675 */ 676 public static final int VISIBLE = 0x00000000; 677 678 /** 679 * This view is invisible, but it still takes up space for layout purposes. 680 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 681 * android:visibility}. 682 */ 683 public static final int INVISIBLE = 0x00000004; 684 685 /** 686 * This view is invisible, and it doesn't take any space for layout 687 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 688 * android:visibility}. 689 */ 690 public static final int GONE = 0x00000008; 691 692 /** 693 * Mask for use with setFlags indicating bits used for visibility. 694 * {@hide} 695 */ 696 static final int VISIBILITY_MASK = 0x0000000C; 697 698 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 699 700 /** 701 * This view is enabled. Interpretation varies by subclass. 702 * Use with ENABLED_MASK when calling setFlags. 703 * {@hide} 704 */ 705 static final int ENABLED = 0x00000000; 706 707 /** 708 * This view is disabled. Interpretation varies by subclass. 709 * Use with ENABLED_MASK when calling setFlags. 710 * {@hide} 711 */ 712 static final int DISABLED = 0x00000020; 713 714 /** 715 * Mask for use with setFlags indicating bits used for indicating whether 716 * this view is enabled 717 * {@hide} 718 */ 719 static final int ENABLED_MASK = 0x00000020; 720 721 /** 722 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 723 * called and further optimizations will be performed. It is okay to have 724 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 725 * {@hide} 726 */ 727 static final int WILL_NOT_DRAW = 0x00000080; 728 729 /** 730 * Mask for use with setFlags indicating bits used for indicating whether 731 * this view is will draw 732 * {@hide} 733 */ 734 static final int DRAW_MASK = 0x00000080; 735 736 /** 737 * <p>This view doesn't show scrollbars.</p> 738 * {@hide} 739 */ 740 static final int SCROLLBARS_NONE = 0x00000000; 741 742 /** 743 * <p>This view shows horizontal scrollbars.</p> 744 * {@hide} 745 */ 746 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 747 748 /** 749 * <p>This view shows vertical scrollbars.</p> 750 * {@hide} 751 */ 752 static final int SCROLLBARS_VERTICAL = 0x00000200; 753 754 /** 755 * <p>Mask for use with setFlags indicating bits used for indicating which 756 * scrollbars are enabled.</p> 757 * {@hide} 758 */ 759 static final int SCROLLBARS_MASK = 0x00000300; 760 761 /** 762 * Indicates that the view should filter touches when its window is obscured. 763 * Refer to the class comments for more information about this security feature. 764 * {@hide} 765 */ 766 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 767 768 // note flag value 0x00000800 is now available for next flags... 769 770 /** 771 * <p>This view doesn't show fading edges.</p> 772 * {@hide} 773 */ 774 static final int FADING_EDGE_NONE = 0x00000000; 775 776 /** 777 * <p>This view shows horizontal fading edges.</p> 778 * {@hide} 779 */ 780 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 781 782 /** 783 * <p>This view shows vertical fading edges.</p> 784 * {@hide} 785 */ 786 static final int FADING_EDGE_VERTICAL = 0x00002000; 787 788 /** 789 * <p>Mask for use with setFlags indicating bits used for indicating which 790 * fading edges are enabled.</p> 791 * {@hide} 792 */ 793 static final int FADING_EDGE_MASK = 0x00003000; 794 795 /** 796 * <p>Indicates this view can be clicked. When clickable, a View reacts 797 * to clicks by notifying the OnClickListener.<p> 798 * {@hide} 799 */ 800 static final int CLICKABLE = 0x00004000; 801 802 /** 803 * <p>Indicates this view is caching its drawing into a bitmap.</p> 804 * {@hide} 805 */ 806 static final int DRAWING_CACHE_ENABLED = 0x00008000; 807 808 /** 809 * <p>Indicates that no icicle should be saved for this view.<p> 810 * {@hide} 811 */ 812 static final int SAVE_DISABLED = 0x000010000; 813 814 /** 815 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 816 * property.</p> 817 * {@hide} 818 */ 819 static final int SAVE_DISABLED_MASK = 0x000010000; 820 821 /** 822 * <p>Indicates that no drawing cache should ever be created for this view.<p> 823 * {@hide} 824 */ 825 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 826 827 /** 828 * <p>Indicates this view can take / keep focus when int touch mode.</p> 829 * {@hide} 830 */ 831 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 832 833 /** 834 * <p>Enables low quality mode for the drawing cache.</p> 835 */ 836 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 837 838 /** 839 * <p>Enables high quality mode for the drawing cache.</p> 840 */ 841 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 842 843 /** 844 * <p>Enables automatic quality mode for the drawing cache.</p> 845 */ 846 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 847 848 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 849 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 850 }; 851 852 /** 853 * <p>Mask for use with setFlags indicating bits used for the cache 854 * quality property.</p> 855 * {@hide} 856 */ 857 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 858 859 /** 860 * <p> 861 * Indicates this view can be long clicked. When long clickable, a View 862 * reacts to long clicks by notifying the OnLongClickListener or showing a 863 * context menu. 864 * </p> 865 * {@hide} 866 */ 867 static final int LONG_CLICKABLE = 0x00200000; 868 869 /** 870 * <p>Indicates that this view gets its drawable states from its direct parent 871 * and ignores its original internal states.</p> 872 * 873 * @hide 874 */ 875 static final int DUPLICATE_PARENT_STATE = 0x00400000; 876 877 /** 878 * The scrollbar style to display the scrollbars inside the content area, 879 * without increasing the padding. The scrollbars will be overlaid with 880 * translucency on the view's content. 881 */ 882 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 883 884 /** 885 * The scrollbar style to display the scrollbars inside the padded area, 886 * increasing the padding of the view. The scrollbars will not overlap the 887 * content area of the view. 888 */ 889 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 890 891 /** 892 * The scrollbar style to display the scrollbars at the edge of the view, 893 * without increasing the padding. The scrollbars will be overlaid with 894 * translucency. 895 */ 896 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 897 898 /** 899 * The scrollbar style to display the scrollbars at the edge of the view, 900 * increasing the padding of the view. The scrollbars will only overlap the 901 * background, if any. 902 */ 903 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 904 905 /** 906 * Mask to check if the scrollbar style is overlay or inset. 907 * {@hide} 908 */ 909 static final int SCROLLBARS_INSET_MASK = 0x01000000; 910 911 /** 912 * Mask to check if the scrollbar style is inside or outside. 913 * {@hide} 914 */ 915 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 916 917 /** 918 * Mask for scrollbar style. 919 * {@hide} 920 */ 921 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 922 923 /** 924 * View flag indicating that the screen should remain on while the 925 * window containing this view is visible to the user. This effectively 926 * takes care of automatically setting the WindowManager's 927 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 928 */ 929 public static final int KEEP_SCREEN_ON = 0x04000000; 930 931 /** 932 * View flag indicating whether this view should have sound effects enabled 933 * for events such as clicking and touching. 934 */ 935 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 936 937 /** 938 * View flag indicating whether this view should have haptic feedback 939 * enabled for events such as long presses. 940 */ 941 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 942 943 /** 944 * <p>Indicates that the view hierarchy should stop saving state when 945 * it reaches this view. If state saving is initiated immediately at 946 * the view, it will be allowed. 947 * {@hide} 948 */ 949 static final int PARENT_SAVE_DISABLED = 0x20000000; 950 951 /** 952 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 953 * {@hide} 954 */ 955 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 956 957 /** 958 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 959 * should add all focusable Views regardless if they are focusable in touch mode. 960 */ 961 public static final int FOCUSABLES_ALL = 0x00000000; 962 963 /** 964 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 965 * should add only Views focusable in touch mode. 966 */ 967 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 968 969 /** 970 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 971 * item. 972 */ 973 public static final int FOCUS_BACKWARD = 0x00000001; 974 975 /** 976 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 977 * item. 978 */ 979 public static final int FOCUS_FORWARD = 0x00000002; 980 981 /** 982 * Use with {@link #focusSearch(int)}. Move focus to the left. 983 */ 984 public static final int FOCUS_LEFT = 0x00000011; 985 986 /** 987 * Use with {@link #focusSearch(int)}. Move focus up. 988 */ 989 public static final int FOCUS_UP = 0x00000021; 990 991 /** 992 * Use with {@link #focusSearch(int)}. Move focus to the right. 993 */ 994 public static final int FOCUS_RIGHT = 0x00000042; 995 996 /** 997 * Use with {@link #focusSearch(int)}. Move focus down. 998 */ 999 public static final int FOCUS_DOWN = 0x00000082; 1000 1001 /** 1002 * Bits of {@link #getMeasuredWidthAndState()} and 1003 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1004 */ 1005 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1006 1007 /** 1008 * Bits of {@link #getMeasuredWidthAndState()} and 1009 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1010 */ 1011 public static final int MEASURED_STATE_MASK = 0xff000000; 1012 1013 /** 1014 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1015 * for functions that combine both width and height into a single int, 1016 * such as {@link #getMeasuredState()} and the childState argument of 1017 * {@link #resolveSizeAndState(int, int, int)}. 1018 */ 1019 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1020 1021 /** 1022 * Bit of {@link #getMeasuredWidthAndState()} and 1023 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1024 * is smaller that the space the view would like to have. 1025 */ 1026 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1027 1028 /** 1029 * Base View state sets 1030 */ 1031 // Singles 1032 /** 1033 * Indicates the view has no states set. States are used with 1034 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1035 * view depending on its state. 1036 * 1037 * @see android.graphics.drawable.Drawable 1038 * @see #getDrawableState() 1039 */ 1040 protected static final int[] EMPTY_STATE_SET; 1041 /** 1042 * Indicates the view is enabled. States are used with 1043 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1044 * view depending on its state. 1045 * 1046 * @see android.graphics.drawable.Drawable 1047 * @see #getDrawableState() 1048 */ 1049 protected static final int[] ENABLED_STATE_SET; 1050 /** 1051 * Indicates the view is focused. States are used with 1052 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1053 * view depending on its state. 1054 * 1055 * @see android.graphics.drawable.Drawable 1056 * @see #getDrawableState() 1057 */ 1058 protected static final int[] FOCUSED_STATE_SET; 1059 /** 1060 * Indicates the view is selected. States are used with 1061 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1062 * view depending on its state. 1063 * 1064 * @see android.graphics.drawable.Drawable 1065 * @see #getDrawableState() 1066 */ 1067 protected static final int[] SELECTED_STATE_SET; 1068 /** 1069 * Indicates the view is pressed. States are used with 1070 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1071 * view depending on its state. 1072 * 1073 * @see android.graphics.drawable.Drawable 1074 * @see #getDrawableState() 1075 * @hide 1076 */ 1077 protected static final int[] PRESSED_STATE_SET; 1078 /** 1079 * Indicates the view's window has focus. 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[] WINDOW_FOCUSED_STATE_SET; 1087 // Doubles 1088 /** 1089 * Indicates the view is enabled and has the focus. 1090 * 1091 * @see #ENABLED_STATE_SET 1092 * @see #FOCUSED_STATE_SET 1093 */ 1094 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1095 /** 1096 * Indicates the view is enabled and selected. 1097 * 1098 * @see #ENABLED_STATE_SET 1099 * @see #SELECTED_STATE_SET 1100 */ 1101 protected static final int[] ENABLED_SELECTED_STATE_SET; 1102 /** 1103 * Indicates the view is enabled and that its window has focus. 1104 * 1105 * @see #ENABLED_STATE_SET 1106 * @see #WINDOW_FOCUSED_STATE_SET 1107 */ 1108 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1109 /** 1110 * Indicates the view is focused and selected. 1111 * 1112 * @see #FOCUSED_STATE_SET 1113 * @see #SELECTED_STATE_SET 1114 */ 1115 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1116 /** 1117 * Indicates the view has the focus and that its window has the focus. 1118 * 1119 * @see #FOCUSED_STATE_SET 1120 * @see #WINDOW_FOCUSED_STATE_SET 1121 */ 1122 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1123 /** 1124 * Indicates the view is selected and that its window has the focus. 1125 * 1126 * @see #SELECTED_STATE_SET 1127 * @see #WINDOW_FOCUSED_STATE_SET 1128 */ 1129 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1130 // Triples 1131 /** 1132 * Indicates the view is enabled, focused and selected. 1133 * 1134 * @see #ENABLED_STATE_SET 1135 * @see #FOCUSED_STATE_SET 1136 * @see #SELECTED_STATE_SET 1137 */ 1138 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1139 /** 1140 * Indicates the view is enabled, focused and its window has the focus. 1141 * 1142 * @see #ENABLED_STATE_SET 1143 * @see #FOCUSED_STATE_SET 1144 * @see #WINDOW_FOCUSED_STATE_SET 1145 */ 1146 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1147 /** 1148 * Indicates the view is enabled, selected and its window has the focus. 1149 * 1150 * @see #ENABLED_STATE_SET 1151 * @see #SELECTED_STATE_SET 1152 * @see #WINDOW_FOCUSED_STATE_SET 1153 */ 1154 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1155 /** 1156 * Indicates the view is focused, selected and its window has the focus. 1157 * 1158 * @see #FOCUSED_STATE_SET 1159 * @see #SELECTED_STATE_SET 1160 * @see #WINDOW_FOCUSED_STATE_SET 1161 */ 1162 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1163 /** 1164 * Indicates the view is enabled, focused, selected and its window 1165 * has the focus. 1166 * 1167 * @see #ENABLED_STATE_SET 1168 * @see #FOCUSED_STATE_SET 1169 * @see #SELECTED_STATE_SET 1170 * @see #WINDOW_FOCUSED_STATE_SET 1171 */ 1172 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1173 /** 1174 * Indicates the view is pressed and its window has the focus. 1175 * 1176 * @see #PRESSED_STATE_SET 1177 * @see #WINDOW_FOCUSED_STATE_SET 1178 */ 1179 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1180 /** 1181 * Indicates the view is pressed and selected. 1182 * 1183 * @see #PRESSED_STATE_SET 1184 * @see #SELECTED_STATE_SET 1185 */ 1186 protected static final int[] PRESSED_SELECTED_STATE_SET; 1187 /** 1188 * Indicates the view is pressed, selected and its window has the focus. 1189 * 1190 * @see #PRESSED_STATE_SET 1191 * @see #SELECTED_STATE_SET 1192 * @see #WINDOW_FOCUSED_STATE_SET 1193 */ 1194 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1195 /** 1196 * Indicates the view is pressed and focused. 1197 * 1198 * @see #PRESSED_STATE_SET 1199 * @see #FOCUSED_STATE_SET 1200 */ 1201 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1202 /** 1203 * Indicates the view is pressed, focused and its window has the focus. 1204 * 1205 * @see #PRESSED_STATE_SET 1206 * @see #FOCUSED_STATE_SET 1207 * @see #WINDOW_FOCUSED_STATE_SET 1208 */ 1209 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1210 /** 1211 * Indicates the view is pressed, focused and selected. 1212 * 1213 * @see #PRESSED_STATE_SET 1214 * @see #SELECTED_STATE_SET 1215 * @see #FOCUSED_STATE_SET 1216 */ 1217 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1218 /** 1219 * Indicates the view is pressed, focused, selected and its window has the focus. 1220 * 1221 * @see #PRESSED_STATE_SET 1222 * @see #FOCUSED_STATE_SET 1223 * @see #SELECTED_STATE_SET 1224 * @see #WINDOW_FOCUSED_STATE_SET 1225 */ 1226 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1227 /** 1228 * Indicates the view is pressed and enabled. 1229 * 1230 * @see #PRESSED_STATE_SET 1231 * @see #ENABLED_STATE_SET 1232 */ 1233 protected static final int[] PRESSED_ENABLED_STATE_SET; 1234 /** 1235 * Indicates the view is pressed, enabled and its window has the focus. 1236 * 1237 * @see #PRESSED_STATE_SET 1238 * @see #ENABLED_STATE_SET 1239 * @see #WINDOW_FOCUSED_STATE_SET 1240 */ 1241 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1242 /** 1243 * Indicates the view is pressed, enabled and selected. 1244 * 1245 * @see #PRESSED_STATE_SET 1246 * @see #ENABLED_STATE_SET 1247 * @see #SELECTED_STATE_SET 1248 */ 1249 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1250 /** 1251 * Indicates the view is pressed, enabled, selected and its window has the 1252 * focus. 1253 * 1254 * @see #PRESSED_STATE_SET 1255 * @see #ENABLED_STATE_SET 1256 * @see #SELECTED_STATE_SET 1257 * @see #WINDOW_FOCUSED_STATE_SET 1258 */ 1259 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1260 /** 1261 * Indicates the view is pressed, enabled and focused. 1262 * 1263 * @see #PRESSED_STATE_SET 1264 * @see #ENABLED_STATE_SET 1265 * @see #FOCUSED_STATE_SET 1266 */ 1267 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1268 /** 1269 * Indicates the view is pressed, enabled, focused and its window has the 1270 * focus. 1271 * 1272 * @see #PRESSED_STATE_SET 1273 * @see #ENABLED_STATE_SET 1274 * @see #FOCUSED_STATE_SET 1275 * @see #WINDOW_FOCUSED_STATE_SET 1276 */ 1277 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1278 /** 1279 * Indicates the view is pressed, enabled, focused and selected. 1280 * 1281 * @see #PRESSED_STATE_SET 1282 * @see #ENABLED_STATE_SET 1283 * @see #SELECTED_STATE_SET 1284 * @see #FOCUSED_STATE_SET 1285 */ 1286 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1287 /** 1288 * Indicates the view is pressed, enabled, focused, selected and its window 1289 * has the focus. 1290 * 1291 * @see #PRESSED_STATE_SET 1292 * @see #ENABLED_STATE_SET 1293 * @see #SELECTED_STATE_SET 1294 * @see #FOCUSED_STATE_SET 1295 * @see #WINDOW_FOCUSED_STATE_SET 1296 */ 1297 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1298 1299 /** 1300 * The order here is very important to {@link #getDrawableState()} 1301 */ 1302 private static final int[][] VIEW_STATE_SETS; 1303 1304 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1305 static final int VIEW_STATE_SELECTED = 1 << 1; 1306 static final int VIEW_STATE_FOCUSED = 1 << 2; 1307 static final int VIEW_STATE_ENABLED = 1 << 3; 1308 static final int VIEW_STATE_PRESSED = 1 << 4; 1309 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1310 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1311 static final int VIEW_STATE_HOVERED = 1 << 7; 1312 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1313 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1314 1315 static final int[] VIEW_STATE_IDS = new int[] { 1316 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1317 R.attr.state_selected, VIEW_STATE_SELECTED, 1318 R.attr.state_focused, VIEW_STATE_FOCUSED, 1319 R.attr.state_enabled, VIEW_STATE_ENABLED, 1320 R.attr.state_pressed, VIEW_STATE_PRESSED, 1321 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1322 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1323 R.attr.state_hovered, VIEW_STATE_HOVERED, 1324 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1325 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED, 1326 }; 1327 1328 static { 1329 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1330 throw new IllegalStateException( 1331 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1332 } 1333 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1334 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1335 int viewState = R.styleable.ViewDrawableStates[i]; 1336 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1337 if (VIEW_STATE_IDS[j] == viewState) { 1338 orderedIds[i * 2] = viewState; 1339 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1340 } 1341 } 1342 } 1343 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1344 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1345 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1346 int numBits = Integer.bitCount(i); 1347 int[] set = new int[numBits]; 1348 int pos = 0; 1349 for (int j = 0; j < orderedIds.length; j += 2) { 1350 if ((i & orderedIds[j+1]) != 0) { 1351 set[pos++] = orderedIds[j]; 1352 } 1353 } 1354 VIEW_STATE_SETS[i] = set; 1355 } 1356 1357 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1358 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1359 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1360 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1361 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1362 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1363 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1364 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1365 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1366 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1367 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1368 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1369 | VIEW_STATE_FOCUSED]; 1370 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1371 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1372 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1373 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1374 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1375 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1376 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1377 | VIEW_STATE_ENABLED]; 1378 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1379 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1380 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1381 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1382 | VIEW_STATE_ENABLED]; 1383 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1384 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1385 | VIEW_STATE_ENABLED]; 1386 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1387 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1388 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1389 1390 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1391 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1392 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1393 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1394 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1395 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1396 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1397 | VIEW_STATE_PRESSED]; 1398 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1399 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1400 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1401 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1402 | VIEW_STATE_PRESSED]; 1403 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1404 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1405 | VIEW_STATE_PRESSED]; 1406 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1407 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1408 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1409 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1410 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1411 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1412 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1413 | VIEW_STATE_PRESSED]; 1414 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1415 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1416 | VIEW_STATE_PRESSED]; 1417 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1418 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1419 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1420 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1421 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1422 | VIEW_STATE_PRESSED]; 1423 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1424 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1425 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1426 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1427 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1428 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1429 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1430 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1431 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1432 | VIEW_STATE_PRESSED]; 1433 } 1434 1435 /** 1436 * Accessibility event types that are dispatched for text population. 1437 */ 1438 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1439 AccessibilityEvent.TYPE_VIEW_CLICKED 1440 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1441 | AccessibilityEvent.TYPE_VIEW_SELECTED 1442 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1443 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1444 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1445 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1446 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1447 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED; 1448 1449 /** 1450 * Temporary Rect currently for use in setBackground(). This will probably 1451 * be extended in the future to hold our own class with more than just 1452 * a Rect. :) 1453 */ 1454 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1455 1456 /** 1457 * Temporary flag, used to enable processing of View properties in the native DisplayList 1458 * object instead of during draw(). Soon to be enabled by default for hardware-accelerated 1459 * apps. 1460 * @hide 1461 */ 1462 public static final boolean USE_DISPLAY_LIST_PROPERTIES = false; 1463 1464 /** 1465 * Map used to store views' tags. 1466 */ 1467 private SparseArray<Object> mKeyedTags; 1468 1469 /** 1470 * The next available accessiiblity id. 1471 */ 1472 private static int sNextAccessibilityViewId; 1473 1474 /** 1475 * The animation currently associated with this view. 1476 * @hide 1477 */ 1478 protected Animation mCurrentAnimation = null; 1479 1480 /** 1481 * Width as measured during measure pass. 1482 * {@hide} 1483 */ 1484 @ViewDebug.ExportedProperty(category = "measurement") 1485 int mMeasuredWidth; 1486 1487 /** 1488 * Height as measured during measure pass. 1489 * {@hide} 1490 */ 1491 @ViewDebug.ExportedProperty(category = "measurement") 1492 int mMeasuredHeight; 1493 1494 /** 1495 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1496 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1497 * its display list. This flag, used only when hw accelerated, allows us to clear the 1498 * flag while retaining this information until it's needed (at getDisplayList() time and 1499 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1500 * 1501 * {@hide} 1502 */ 1503 boolean mRecreateDisplayList = false; 1504 1505 /** 1506 * The view's identifier. 1507 * {@hide} 1508 * 1509 * @see #setId(int) 1510 * @see #getId() 1511 */ 1512 @ViewDebug.ExportedProperty(resolveId = true) 1513 int mID = NO_ID; 1514 1515 /** 1516 * The stable ID of this view for accessibility purposes. 1517 */ 1518 int mAccessibilityViewId = NO_ID; 1519 1520 /** 1521 * The view's tag. 1522 * {@hide} 1523 * 1524 * @see #setTag(Object) 1525 * @see #getTag() 1526 */ 1527 protected Object mTag; 1528 1529 // for mPrivateFlags: 1530 /** {@hide} */ 1531 static final int WANTS_FOCUS = 0x00000001; 1532 /** {@hide} */ 1533 static final int FOCUSED = 0x00000002; 1534 /** {@hide} */ 1535 static final int SELECTED = 0x00000004; 1536 /** {@hide} */ 1537 static final int IS_ROOT_NAMESPACE = 0x00000008; 1538 /** {@hide} */ 1539 static final int HAS_BOUNDS = 0x00000010; 1540 /** {@hide} */ 1541 static final int DRAWN = 0x00000020; 1542 /** 1543 * When this flag is set, this view is running an animation on behalf of its 1544 * children and should therefore not cancel invalidate requests, even if they 1545 * lie outside of this view's bounds. 1546 * 1547 * {@hide} 1548 */ 1549 static final int DRAW_ANIMATION = 0x00000040; 1550 /** {@hide} */ 1551 static final int SKIP_DRAW = 0x00000080; 1552 /** {@hide} */ 1553 static final int ONLY_DRAWS_BACKGROUND = 0x00000100; 1554 /** {@hide} */ 1555 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1556 /** {@hide} */ 1557 static final int DRAWABLE_STATE_DIRTY = 0x00000400; 1558 /** {@hide} */ 1559 static final int MEASURED_DIMENSION_SET = 0x00000800; 1560 /** {@hide} */ 1561 static final int FORCE_LAYOUT = 0x00001000; 1562 /** {@hide} */ 1563 static final int LAYOUT_REQUIRED = 0x00002000; 1564 1565 private static final int PRESSED = 0x00004000; 1566 1567 /** {@hide} */ 1568 static final int DRAWING_CACHE_VALID = 0x00008000; 1569 /** 1570 * Flag used to indicate that this view should be drawn once more (and only once 1571 * more) after its animation has completed. 1572 * {@hide} 1573 */ 1574 static final int ANIMATION_STARTED = 0x00010000; 1575 1576 private static final int SAVE_STATE_CALLED = 0x00020000; 1577 1578 /** 1579 * Indicates that the View returned true when onSetAlpha() was called and that 1580 * the alpha must be restored. 1581 * {@hide} 1582 */ 1583 static final int ALPHA_SET = 0x00040000; 1584 1585 /** 1586 * Set by {@link #setScrollContainer(boolean)}. 1587 */ 1588 static final int SCROLL_CONTAINER = 0x00080000; 1589 1590 /** 1591 * Set by {@link #setScrollContainer(boolean)}. 1592 */ 1593 static final int SCROLL_CONTAINER_ADDED = 0x00100000; 1594 1595 /** 1596 * View flag indicating whether this view was invalidated (fully or partially.) 1597 * 1598 * @hide 1599 */ 1600 static final int DIRTY = 0x00200000; 1601 1602 /** 1603 * View flag indicating whether this view was invalidated by an opaque 1604 * invalidate request. 1605 * 1606 * @hide 1607 */ 1608 static final int DIRTY_OPAQUE = 0x00400000; 1609 1610 /** 1611 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}. 1612 * 1613 * @hide 1614 */ 1615 static final int DIRTY_MASK = 0x00600000; 1616 1617 /** 1618 * Indicates whether the background is opaque. 1619 * 1620 * @hide 1621 */ 1622 static final int OPAQUE_BACKGROUND = 0x00800000; 1623 1624 /** 1625 * Indicates whether the scrollbars are opaque. 1626 * 1627 * @hide 1628 */ 1629 static final int OPAQUE_SCROLLBARS = 0x01000000; 1630 1631 /** 1632 * Indicates whether the view is opaque. 1633 * 1634 * @hide 1635 */ 1636 static final int OPAQUE_MASK = 0x01800000; 1637 1638 /** 1639 * Indicates a prepressed state; 1640 * the short time between ACTION_DOWN and recognizing 1641 * a 'real' press. Prepressed is used to recognize quick taps 1642 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1643 * 1644 * @hide 1645 */ 1646 private static final int PREPRESSED = 0x02000000; 1647 1648 /** 1649 * Indicates whether the view is temporarily detached. 1650 * 1651 * @hide 1652 */ 1653 static final int CANCEL_NEXT_UP_EVENT = 0x04000000; 1654 1655 /** 1656 * Indicates that we should awaken scroll bars once attached 1657 * 1658 * @hide 1659 */ 1660 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1661 1662 /** 1663 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1664 * @hide 1665 */ 1666 private static final int HOVERED = 0x10000000; 1667 1668 /** 1669 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1670 * for transform operations 1671 * 1672 * @hide 1673 */ 1674 private static final int PIVOT_EXPLICITLY_SET = 0x20000000; 1675 1676 /** {@hide} */ 1677 static final int ACTIVATED = 0x40000000; 1678 1679 /** 1680 * Indicates that this view was specifically invalidated, not just dirtied because some 1681 * child view was invalidated. The flag is used to determine when we need to recreate 1682 * a view's display list (as opposed to just returning a reference to its existing 1683 * display list). 1684 * 1685 * @hide 1686 */ 1687 static final int INVALIDATED = 0x80000000; 1688 1689 /* Masks for mPrivateFlags2 */ 1690 1691 /** 1692 * Indicates that this view has reported that it can accept the current drag's content. 1693 * Cleared when the drag operation concludes. 1694 * @hide 1695 */ 1696 static final int DRAG_CAN_ACCEPT = 0x00000001; 1697 1698 /** 1699 * Indicates that this view is currently directly under the drag location in a 1700 * drag-and-drop operation involving content that it can accept. Cleared when 1701 * the drag exits the view, or when the drag operation concludes. 1702 * @hide 1703 */ 1704 static final int DRAG_HOVERED = 0x00000002; 1705 1706 /** 1707 * Horizontal layout direction of this view is from Left to Right. 1708 * Use with {@link #setLayoutDirection}. 1709 */ 1710 public static final int LAYOUT_DIRECTION_LTR = 0; 1711 1712 /** 1713 * Horizontal layout direction of this view is from Right to Left. 1714 * Use with {@link #setLayoutDirection}. 1715 */ 1716 public static final int LAYOUT_DIRECTION_RTL = 1; 1717 1718 /** 1719 * Horizontal layout direction of this view is inherited from its parent. 1720 * Use with {@link #setLayoutDirection}. 1721 */ 1722 public static final int LAYOUT_DIRECTION_INHERIT = 2; 1723 1724 /** 1725 * Horizontal layout direction of this view is from deduced from the default language 1726 * script for the locale. Use with {@link #setLayoutDirection}. 1727 */ 1728 public static final int LAYOUT_DIRECTION_LOCALE = 3; 1729 1730 /** 1731 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1732 * @hide 1733 */ 1734 static final int LAYOUT_DIRECTION_MASK_SHIFT = 2; 1735 1736 /** 1737 * Mask for use with private flags indicating bits used for horizontal layout direction. 1738 * @hide 1739 */ 1740 static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT; 1741 1742 /** 1743 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1744 * right-to-left direction. 1745 * @hide 1746 */ 1747 static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT; 1748 1749 /** 1750 * Indicates whether the view horizontal layout direction has been resolved. 1751 * @hide 1752 */ 1753 static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT; 1754 1755 /** 1756 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1757 * @hide 1758 */ 1759 static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT; 1760 1761 /* 1762 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1763 * flag value. 1764 * @hide 1765 */ 1766 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1767 LAYOUT_DIRECTION_LTR, 1768 LAYOUT_DIRECTION_RTL, 1769 LAYOUT_DIRECTION_INHERIT, 1770 LAYOUT_DIRECTION_LOCALE 1771 }; 1772 1773 /** 1774 * Default horizontal layout direction. 1775 * @hide 1776 */ 1777 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1778 1779 1780 /** 1781 * Indicates that the view is tracking some sort of transient state 1782 * that the app should not need to be aware of, but that the framework 1783 * should take special care to preserve. 1784 * 1785 * @hide 1786 */ 1787 static final int HAS_TRANSIENT_STATE = 0x00000100; 1788 1789 1790 /** 1791 * Text direction is inherited thru {@link ViewGroup} 1792 */ 1793 public static final int TEXT_DIRECTION_INHERIT = 0; 1794 1795 /** 1796 * Text direction is using "first strong algorithm". The first strong directional character 1797 * determines the paragraph direction. If there is no strong directional character, the 1798 * paragraph direction is the view's resolved layout direction. 1799 */ 1800 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1801 1802 /** 1803 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1804 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1805 * If there are neither, the paragraph direction is the view's resolved layout direction. 1806 */ 1807 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1808 1809 /** 1810 * Text direction is forced to LTR. 1811 */ 1812 public static final int TEXT_DIRECTION_LTR = 3; 1813 1814 /** 1815 * Text direction is forced to RTL. 1816 */ 1817 public static final int TEXT_DIRECTION_RTL = 4; 1818 1819 /** 1820 * Text direction is coming from the system Locale. 1821 */ 1822 public static final int TEXT_DIRECTION_LOCALE = 5; 1823 1824 /** 1825 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 1826 * @hide 1827 */ 1828 static final int TEXT_DIRECTION_MASK_SHIFT = 6; 1829 1830 /** 1831 * Default text direction is inherited 1832 */ 1833 protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 1834 1835 /** 1836 * Mask for use with private flags indicating bits used for text direction. 1837 * @hide 1838 */ 1839 static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT; 1840 1841 /** 1842 * Array of text direction flags for mapping attribute "textDirection" to correct 1843 * flag value. 1844 * @hide 1845 */ 1846 private static final int[] TEXT_DIRECTION_FLAGS = { 1847 TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT, 1848 TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT, 1849 TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT, 1850 TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT, 1851 TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT, 1852 TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT 1853 }; 1854 1855 /** 1856 * Indicates whether the view text direction has been resolved. 1857 * @hide 1858 */ 1859 static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT; 1860 1861 /** 1862 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1863 * @hide 1864 */ 1865 static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 1866 1867 /** 1868 * Mask for use with private flags indicating bits used for resolved text direction. 1869 * @hide 1870 */ 1871 static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1872 1873 /** 1874 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 1875 * @hide 1876 */ 1877 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = 1878 TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1879 1880 1881 /* End of masks for mPrivateFlags2 */ 1882 1883 static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED; 1884 1885 /** 1886 * Always allow a user to over-scroll this view, provided it is a 1887 * view that can scroll. 1888 * 1889 * @see #getOverScrollMode() 1890 * @see #setOverScrollMode(int) 1891 */ 1892 public static final int OVER_SCROLL_ALWAYS = 0; 1893 1894 /** 1895 * Allow a user to over-scroll this view only if the content is large 1896 * enough to meaningfully scroll, provided it is a view that can scroll. 1897 * 1898 * @see #getOverScrollMode() 1899 * @see #setOverScrollMode(int) 1900 */ 1901 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 1902 1903 /** 1904 * Never allow a user to over-scroll this view. 1905 * 1906 * @see #getOverScrollMode() 1907 * @see #setOverScrollMode(int) 1908 */ 1909 public static final int OVER_SCROLL_NEVER = 2; 1910 1911 /** 1912 * View has requested the system UI (status bar) to be visible (the default). 1913 * 1914 * @see #setSystemUiVisibility(int) 1915 */ 1916 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 1917 1918 /** 1919 * View has requested the system UI to enter an unobtrusive "low profile" mode. 1920 * 1921 * This is for use in games, book readers, video players, or any other "immersive" application 1922 * where the usual system chrome is deemed too distracting. 1923 * 1924 * In low profile mode, the status bar and/or navigation icons may dim. 1925 * 1926 * @see #setSystemUiVisibility(int) 1927 */ 1928 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 1929 1930 /** 1931 * View has requested that the system navigation be temporarily hidden. 1932 * 1933 * This is an even less obtrusive state than that called for by 1934 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 1935 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 1936 * those to disappear. This is useful (in conjunction with the 1937 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 1938 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 1939 * window flags) for displaying content using every last pixel on the display. 1940 * 1941 * There is a limitation: because navigation controls are so important, the least user 1942 * interaction will cause them to reappear immediately. 1943 * 1944 * @see #setSystemUiVisibility(int) 1945 */ 1946 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 1947 1948 /** 1949 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 1950 */ 1951 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 1952 1953 /** 1954 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 1955 */ 1956 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 1957 1958 /** 1959 * @hide 1960 * 1961 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1962 * out of the public fields to keep the undefined bits out of the developer's way. 1963 * 1964 * Flag to make the status bar not expandable. Unless you also 1965 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 1966 */ 1967 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 1968 1969 /** 1970 * @hide 1971 * 1972 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1973 * out of the public fields to keep the undefined bits out of the developer's way. 1974 * 1975 * Flag to hide notification icons and scrolling ticker text. 1976 */ 1977 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 1978 1979 /** 1980 * @hide 1981 * 1982 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1983 * out of the public fields to keep the undefined bits out of the developer's way. 1984 * 1985 * Flag to disable incoming notification alerts. This will not block 1986 * icons, but it will block sound, vibrating and other visual or aural notifications. 1987 */ 1988 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 1989 1990 /** 1991 * @hide 1992 * 1993 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1994 * out of the public fields to keep the undefined bits out of the developer's way. 1995 * 1996 * Flag to hide only the scrolling ticker. Note that 1997 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 1998 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 1999 */ 2000 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2001 2002 /** 2003 * @hide 2004 * 2005 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2006 * out of the public fields to keep the undefined bits out of the developer's way. 2007 * 2008 * Flag to hide the center system info area. 2009 */ 2010 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2011 2012 /** 2013 * @hide 2014 * 2015 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2016 * out of the public fields to keep the undefined bits out of the developer's way. 2017 * 2018 * Flag to hide only the home button. Don't use this 2019 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2020 */ 2021 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2022 2023 /** 2024 * @hide 2025 * 2026 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2027 * out of the public fields to keep the undefined bits out of the developer's way. 2028 * 2029 * Flag to hide only the back button. Don't use this 2030 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2031 */ 2032 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2033 2034 /** 2035 * @hide 2036 * 2037 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2038 * out of the public fields to keep the undefined bits out of the developer's way. 2039 * 2040 * Flag to hide only the clock. You might use this if your activity has 2041 * its own clock making the status bar's clock redundant. 2042 */ 2043 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2044 2045 /** 2046 * @hide 2047 * 2048 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2049 * out of the public fields to keep the undefined bits out of the developer's way. 2050 * 2051 * Flag to hide only the recent apps button. Don't use this 2052 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2053 */ 2054 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2055 2056 /** 2057 * @hide 2058 * 2059 * NOTE: This flag may only be used in subtreeSystemUiVisibility, etc. etc. 2060 * 2061 * This hides HOME and RECENT and is provided for compatibility with interim implementations. 2062 */ 2063 @Deprecated 2064 public static final int STATUS_BAR_DISABLE_NAVIGATION = 2065 STATUS_BAR_DISABLE_HOME | STATUS_BAR_DISABLE_RECENT; 2066 2067 /** 2068 * @hide 2069 */ 2070 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2071 2072 /** 2073 * These are the system UI flags that can be cleared by events outside 2074 * of an application. Currently this is just the ability to tap on the 2075 * screen while hiding the navigation bar to have it return. 2076 * @hide 2077 */ 2078 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2079 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION; 2080 2081 /** 2082 * Find views that render the specified text. 2083 * 2084 * @see #findViewsWithText(ArrayList, CharSequence, int) 2085 */ 2086 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2087 2088 /** 2089 * Find find views that contain the specified content description. 2090 * 2091 * @see #findViewsWithText(ArrayList, CharSequence, int) 2092 */ 2093 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2094 2095 /** 2096 * Find views that contain {@link AccessibilityNodeProvider}. Such 2097 * a View is a root of virtual view hierarchy and may contain the searched 2098 * text. If this flag is set Views with providers are automatically 2099 * added and it is a responsibility of the client to call the APIs of 2100 * the provider to determine whether the virtual tree rooted at this View 2101 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2102 * represeting the virtual views with this text. 2103 * 2104 * @see #findViewsWithText(ArrayList, CharSequence, int) 2105 * 2106 * @hide 2107 */ 2108 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2109 2110 /** 2111 * Indicates that the screen has changed state and is now off. 2112 * 2113 * @see #onScreenStateChanged(int) 2114 */ 2115 public static final int SCREEN_STATE_OFF = 0x0; 2116 2117 /** 2118 * Indicates that the screen has changed state and is now on. 2119 * 2120 * @see #onScreenStateChanged(int) 2121 */ 2122 public static final int SCREEN_STATE_ON = 0x1; 2123 2124 /** 2125 * Controls the over-scroll mode for this view. 2126 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2127 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2128 * and {@link #OVER_SCROLL_NEVER}. 2129 */ 2130 private int mOverScrollMode; 2131 2132 /** 2133 * The parent this view is attached to. 2134 * {@hide} 2135 * 2136 * @see #getParent() 2137 */ 2138 protected ViewParent mParent; 2139 2140 /** 2141 * {@hide} 2142 */ 2143 AttachInfo mAttachInfo; 2144 2145 /** 2146 * {@hide} 2147 */ 2148 @ViewDebug.ExportedProperty(flagMapping = { 2149 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT, 2150 name = "FORCE_LAYOUT"), 2151 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED, 2152 name = "LAYOUT_REQUIRED"), 2153 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID, 2154 name = "DRAWING_CACHE_INVALID", outputIf = false), 2155 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true), 2156 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false), 2157 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2158 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY") 2159 }) 2160 int mPrivateFlags; 2161 int mPrivateFlags2; 2162 2163 /** 2164 * This view's request for the visibility of the status bar. 2165 * @hide 2166 */ 2167 @ViewDebug.ExportedProperty(flagMapping = { 2168 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2169 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2170 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2171 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2172 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2173 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2174 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2175 equals = SYSTEM_UI_FLAG_VISIBLE, 2176 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2177 }) 2178 int mSystemUiVisibility; 2179 2180 /** 2181 * Count of how many windows this view has been attached to. 2182 */ 2183 int mWindowAttachCount; 2184 2185 /** 2186 * The layout parameters associated with this view and used by the parent 2187 * {@link android.view.ViewGroup} to determine how this view should be 2188 * laid out. 2189 * {@hide} 2190 */ 2191 protected ViewGroup.LayoutParams mLayoutParams; 2192 2193 /** 2194 * The view flags hold various views states. 2195 * {@hide} 2196 */ 2197 @ViewDebug.ExportedProperty 2198 int mViewFlags; 2199 2200 static class TransformationInfo { 2201 /** 2202 * The transform matrix for the View. This transform is calculated internally 2203 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2204 * is used by default. Do *not* use this variable directly; instead call 2205 * getMatrix(), which will automatically recalculate the matrix if necessary 2206 * to get the correct matrix based on the latest rotation and scale properties. 2207 */ 2208 private final Matrix mMatrix = new Matrix(); 2209 2210 /** 2211 * The transform matrix for the View. This transform is calculated internally 2212 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2213 * is used by default. Do *not* use this variable directly; instead call 2214 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2215 * to get the correct matrix based on the latest rotation and scale properties. 2216 */ 2217 private Matrix mInverseMatrix; 2218 2219 /** 2220 * An internal variable that tracks whether we need to recalculate the 2221 * transform matrix, based on whether the rotation or scaleX/Y properties 2222 * have changed since the matrix was last calculated. 2223 */ 2224 boolean mMatrixDirty = false; 2225 2226 /** 2227 * An internal variable that tracks whether we need to recalculate the 2228 * transform matrix, based on whether the rotation or scaleX/Y properties 2229 * have changed since the matrix was last calculated. 2230 */ 2231 private boolean mInverseMatrixDirty = true; 2232 2233 /** 2234 * A variable that tracks whether we need to recalculate the 2235 * transform matrix, based on whether the rotation or scaleX/Y properties 2236 * have changed since the matrix was last calculated. This variable 2237 * is only valid after a call to updateMatrix() or to a function that 2238 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2239 */ 2240 private boolean mMatrixIsIdentity = true; 2241 2242 /** 2243 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2244 */ 2245 private Camera mCamera = null; 2246 2247 /** 2248 * This matrix is used when computing the matrix for 3D rotations. 2249 */ 2250 private Matrix matrix3D = null; 2251 2252 /** 2253 * These prev values are used to recalculate a centered pivot point when necessary. The 2254 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2255 * set), so thes values are only used then as well. 2256 */ 2257 private int mPrevWidth = -1; 2258 private int mPrevHeight = -1; 2259 2260 /** 2261 * The degrees rotation around the vertical axis through the pivot point. 2262 */ 2263 @ViewDebug.ExportedProperty 2264 float mRotationY = 0f; 2265 2266 /** 2267 * The degrees rotation around the horizontal axis through the pivot point. 2268 */ 2269 @ViewDebug.ExportedProperty 2270 float mRotationX = 0f; 2271 2272 /** 2273 * The degrees rotation around the pivot point. 2274 */ 2275 @ViewDebug.ExportedProperty 2276 float mRotation = 0f; 2277 2278 /** 2279 * The amount of translation of the object away from its left property (post-layout). 2280 */ 2281 @ViewDebug.ExportedProperty 2282 float mTranslationX = 0f; 2283 2284 /** 2285 * The amount of translation of the object away from its top property (post-layout). 2286 */ 2287 @ViewDebug.ExportedProperty 2288 float mTranslationY = 0f; 2289 2290 /** 2291 * The amount of scale in the x direction around the pivot point. A 2292 * value of 1 means no scaling is applied. 2293 */ 2294 @ViewDebug.ExportedProperty 2295 float mScaleX = 1f; 2296 2297 /** 2298 * The amount of scale in the y direction around the pivot point. A 2299 * value of 1 means no scaling is applied. 2300 */ 2301 @ViewDebug.ExportedProperty 2302 float mScaleY = 1f; 2303 2304 /** 2305 * The x location of the point around which the view is rotated and scaled. 2306 */ 2307 @ViewDebug.ExportedProperty 2308 float mPivotX = 0f; 2309 2310 /** 2311 * The y location of the point around which the view is rotated and scaled. 2312 */ 2313 @ViewDebug.ExportedProperty 2314 float mPivotY = 0f; 2315 2316 /** 2317 * The opacity of the View. This is a value from 0 to 1, where 0 means 2318 * completely transparent and 1 means completely opaque. 2319 */ 2320 @ViewDebug.ExportedProperty 2321 float mAlpha = 1f; 2322 } 2323 2324 TransformationInfo mTransformationInfo; 2325 2326 private boolean mLastIsOpaque; 2327 2328 /** 2329 * Convenience value to check for float values that are close enough to zero to be considered 2330 * zero. 2331 */ 2332 private static final float NONZERO_EPSILON = .001f; 2333 2334 /** 2335 * The distance in pixels from the left edge of this view's parent 2336 * to the left edge of this view. 2337 * {@hide} 2338 */ 2339 @ViewDebug.ExportedProperty(category = "layout") 2340 protected int mLeft; 2341 /** 2342 * The distance in pixels from the left edge of this view's parent 2343 * to the right edge of this view. 2344 * {@hide} 2345 */ 2346 @ViewDebug.ExportedProperty(category = "layout") 2347 protected int mRight; 2348 /** 2349 * The distance in pixels from the top edge of this view's parent 2350 * to the top edge of this view. 2351 * {@hide} 2352 */ 2353 @ViewDebug.ExportedProperty(category = "layout") 2354 protected int mTop; 2355 /** 2356 * The distance in pixels from the top edge of this view's parent 2357 * to the bottom edge of this view. 2358 * {@hide} 2359 */ 2360 @ViewDebug.ExportedProperty(category = "layout") 2361 protected int mBottom; 2362 2363 /** 2364 * The offset, in pixels, by which the content of this view is scrolled 2365 * horizontally. 2366 * {@hide} 2367 */ 2368 @ViewDebug.ExportedProperty(category = "scrolling") 2369 protected int mScrollX; 2370 /** 2371 * The offset, in pixels, by which the content of this view is scrolled 2372 * vertically. 2373 * {@hide} 2374 */ 2375 @ViewDebug.ExportedProperty(category = "scrolling") 2376 protected int mScrollY; 2377 2378 /** 2379 * The left padding in pixels, that is the distance in pixels between the 2380 * left edge of this view and the left edge of its content. 2381 * {@hide} 2382 */ 2383 @ViewDebug.ExportedProperty(category = "padding") 2384 protected int mPaddingLeft; 2385 /** 2386 * The right padding in pixels, that is the distance in pixels between the 2387 * right edge of this view and the right edge of its content. 2388 * {@hide} 2389 */ 2390 @ViewDebug.ExportedProperty(category = "padding") 2391 protected int mPaddingRight; 2392 /** 2393 * The top padding in pixels, that is the distance in pixels between the 2394 * top edge of this view and the top edge of its content. 2395 * {@hide} 2396 */ 2397 @ViewDebug.ExportedProperty(category = "padding") 2398 protected int mPaddingTop; 2399 /** 2400 * The bottom padding in pixels, that is the distance in pixels between the 2401 * bottom edge of this view and the bottom edge of its content. 2402 * {@hide} 2403 */ 2404 @ViewDebug.ExportedProperty(category = "padding") 2405 protected int mPaddingBottom; 2406 2407 /** 2408 * Briefly describes the view and is primarily used for accessibility support. 2409 */ 2410 private CharSequence mContentDescription; 2411 2412 /** 2413 * Cache the paddingRight set by the user to append to the scrollbar's size. 2414 * 2415 * @hide 2416 */ 2417 @ViewDebug.ExportedProperty(category = "padding") 2418 protected int mUserPaddingRight; 2419 2420 /** 2421 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2422 * 2423 * @hide 2424 */ 2425 @ViewDebug.ExportedProperty(category = "padding") 2426 protected int mUserPaddingBottom; 2427 2428 /** 2429 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2430 * 2431 * @hide 2432 */ 2433 @ViewDebug.ExportedProperty(category = "padding") 2434 protected int mUserPaddingLeft; 2435 2436 /** 2437 * Cache if the user padding is relative. 2438 * 2439 */ 2440 @ViewDebug.ExportedProperty(category = "padding") 2441 boolean mUserPaddingRelative; 2442 2443 /** 2444 * Cache the paddingStart set by the user to append to the scrollbar's size. 2445 * 2446 */ 2447 @ViewDebug.ExportedProperty(category = "padding") 2448 int mUserPaddingStart; 2449 2450 /** 2451 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2452 * 2453 */ 2454 @ViewDebug.ExportedProperty(category = "padding") 2455 int mUserPaddingEnd; 2456 2457 /** 2458 * @hide 2459 */ 2460 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2461 /** 2462 * @hide 2463 */ 2464 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2465 2466 private Drawable mBGDrawable; 2467 2468 private int mBackgroundResource; 2469 private boolean mBackgroundSizeChanged; 2470 2471 static class ListenerInfo { 2472 /** 2473 * Listener used to dispatch focus change events. 2474 * This field should be made private, so it is hidden from the SDK. 2475 * {@hide} 2476 */ 2477 protected OnFocusChangeListener mOnFocusChangeListener; 2478 2479 /** 2480 * Listeners for layout change events. 2481 */ 2482 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2483 2484 /** 2485 * Listeners for attach events. 2486 */ 2487 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2488 2489 /** 2490 * Listener used to dispatch click events. 2491 * This field should be made private, so it is hidden from the SDK. 2492 * {@hide} 2493 */ 2494 public OnClickListener mOnClickListener; 2495 2496 /** 2497 * Listener used to dispatch long click events. 2498 * This field should be made private, so it is hidden from the SDK. 2499 * {@hide} 2500 */ 2501 protected OnLongClickListener mOnLongClickListener; 2502 2503 /** 2504 * Listener used to build the context menu. 2505 * This field should be made private, so it is hidden from the SDK. 2506 * {@hide} 2507 */ 2508 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2509 2510 private OnKeyListener mOnKeyListener; 2511 2512 private OnTouchListener mOnTouchListener; 2513 2514 private OnHoverListener mOnHoverListener; 2515 2516 private OnGenericMotionListener mOnGenericMotionListener; 2517 2518 private OnDragListener mOnDragListener; 2519 2520 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2521 } 2522 2523 ListenerInfo mListenerInfo; 2524 2525 /** 2526 * The application environment this view lives in. 2527 * This field should be made private, so it is hidden from the SDK. 2528 * {@hide} 2529 */ 2530 protected Context mContext; 2531 2532 private final Resources mResources; 2533 2534 private ScrollabilityCache mScrollCache; 2535 2536 private int[] mDrawableState = null; 2537 2538 /** 2539 * Set to true when drawing cache is enabled and cannot be created. 2540 * 2541 * @hide 2542 */ 2543 public boolean mCachingFailed; 2544 2545 private Bitmap mDrawingCache; 2546 private Bitmap mUnscaledDrawingCache; 2547 private HardwareLayer mHardwareLayer; 2548 DisplayList mDisplayList; 2549 2550 /** 2551 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2552 * the user may specify which view to go to next. 2553 */ 2554 private int mNextFocusLeftId = View.NO_ID; 2555 2556 /** 2557 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2558 * the user may specify which view to go to next. 2559 */ 2560 private int mNextFocusRightId = View.NO_ID; 2561 2562 /** 2563 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2564 * the user may specify which view to go to next. 2565 */ 2566 private int mNextFocusUpId = View.NO_ID; 2567 2568 /** 2569 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2570 * the user may specify which view to go to next. 2571 */ 2572 private int mNextFocusDownId = View.NO_ID; 2573 2574 /** 2575 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 2576 * the user may specify which view to go to next. 2577 */ 2578 int mNextFocusForwardId = View.NO_ID; 2579 2580 private CheckForLongPress mPendingCheckForLongPress; 2581 private CheckForTap mPendingCheckForTap = null; 2582 private PerformClick mPerformClick; 2583 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 2584 2585 private UnsetPressedState mUnsetPressedState; 2586 2587 /** 2588 * Whether the long press's action has been invoked. The tap's action is invoked on the 2589 * up event while a long press is invoked as soon as the long press duration is reached, so 2590 * a long press could be performed before the tap is checked, in which case the tap's action 2591 * should not be invoked. 2592 */ 2593 private boolean mHasPerformedLongPress; 2594 2595 /** 2596 * The minimum height of the view. We'll try our best to have the height 2597 * of this view to at least this amount. 2598 */ 2599 @ViewDebug.ExportedProperty(category = "measurement") 2600 private int mMinHeight; 2601 2602 /** 2603 * The minimum width of the view. We'll try our best to have the width 2604 * of this view to at least this amount. 2605 */ 2606 @ViewDebug.ExportedProperty(category = "measurement") 2607 private int mMinWidth; 2608 2609 /** 2610 * The delegate to handle touch events that are physically in this view 2611 * but should be handled by another view. 2612 */ 2613 private TouchDelegate mTouchDelegate = null; 2614 2615 /** 2616 * Solid color to use as a background when creating the drawing cache. Enables 2617 * the cache to use 16 bit bitmaps instead of 32 bit. 2618 */ 2619 private int mDrawingCacheBackgroundColor = 0; 2620 2621 /** 2622 * Special tree observer used when mAttachInfo is null. 2623 */ 2624 private ViewTreeObserver mFloatingTreeObserver; 2625 2626 /** 2627 * Cache the touch slop from the context that created the view. 2628 */ 2629 private int mTouchSlop; 2630 2631 /** 2632 * Object that handles automatic animation of view properties. 2633 */ 2634 private ViewPropertyAnimator mAnimator = null; 2635 2636 /** 2637 * Flag indicating that a drag can cross window boundaries. When 2638 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 2639 * with this flag set, all visible applications will be able to participate 2640 * in the drag operation and receive the dragged content. 2641 * 2642 * @hide 2643 */ 2644 public static final int DRAG_FLAG_GLOBAL = 1; 2645 2646 /** 2647 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 2648 */ 2649 private float mVerticalScrollFactor; 2650 2651 /** 2652 * Position of the vertical scroll bar. 2653 */ 2654 private int mVerticalScrollbarPosition; 2655 2656 /** 2657 * Position the scroll bar at the default position as determined by the system. 2658 */ 2659 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 2660 2661 /** 2662 * Position the scroll bar along the left edge. 2663 */ 2664 public static final int SCROLLBAR_POSITION_LEFT = 1; 2665 2666 /** 2667 * Position the scroll bar along the right edge. 2668 */ 2669 public static final int SCROLLBAR_POSITION_RIGHT = 2; 2670 2671 /** 2672 * Indicates that the view does not have a layer. 2673 * 2674 * @see #getLayerType() 2675 * @see #setLayerType(int, android.graphics.Paint) 2676 * @see #LAYER_TYPE_SOFTWARE 2677 * @see #LAYER_TYPE_HARDWARE 2678 */ 2679 public static final int LAYER_TYPE_NONE = 0; 2680 2681 /** 2682 * <p>Indicates that the view has a software layer. A software layer is backed 2683 * by a bitmap and causes the view to be rendered using Android's software 2684 * rendering pipeline, even if hardware acceleration is enabled.</p> 2685 * 2686 * <p>Software layers have various usages:</p> 2687 * <p>When the application is not using hardware acceleration, a software layer 2688 * is useful to apply a specific color filter and/or blending mode and/or 2689 * translucency to a view and all its children.</p> 2690 * <p>When the application is using hardware acceleration, a software layer 2691 * is useful to render drawing primitives not supported by the hardware 2692 * accelerated pipeline. It can also be used to cache a complex view tree 2693 * into a texture and reduce the complexity of drawing operations. For instance, 2694 * when animating a complex view tree with a translation, a software layer can 2695 * be used to render the view tree only once.</p> 2696 * <p>Software layers should be avoided when the affected view tree updates 2697 * often. Every update will require to re-render the software layer, which can 2698 * potentially be slow (particularly when hardware acceleration is turned on 2699 * since the layer will have to be uploaded into a hardware texture after every 2700 * update.)</p> 2701 * 2702 * @see #getLayerType() 2703 * @see #setLayerType(int, android.graphics.Paint) 2704 * @see #LAYER_TYPE_NONE 2705 * @see #LAYER_TYPE_HARDWARE 2706 */ 2707 public static final int LAYER_TYPE_SOFTWARE = 1; 2708 2709 /** 2710 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 2711 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 2712 * OpenGL hardware) and causes the view to be rendered using Android's hardware 2713 * rendering pipeline, but only if hardware acceleration is turned on for the 2714 * view hierarchy. When hardware acceleration is turned off, hardware layers 2715 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 2716 * 2717 * <p>A hardware layer is useful to apply a specific color filter and/or 2718 * blending mode and/or translucency to a view and all its children.</p> 2719 * <p>A hardware layer can be used to cache a complex view tree into a 2720 * texture and reduce the complexity of drawing operations. For instance, 2721 * when animating a complex view tree with a translation, a hardware layer can 2722 * be used to render the view tree only once.</p> 2723 * <p>A hardware layer can also be used to increase the rendering quality when 2724 * rotation transformations are applied on a view. It can also be used to 2725 * prevent potential clipping issues when applying 3D transforms on a view.</p> 2726 * 2727 * @see #getLayerType() 2728 * @see #setLayerType(int, android.graphics.Paint) 2729 * @see #LAYER_TYPE_NONE 2730 * @see #LAYER_TYPE_SOFTWARE 2731 */ 2732 public static final int LAYER_TYPE_HARDWARE = 2; 2733 2734 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 2735 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 2736 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 2737 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 2738 }) 2739 int mLayerType = LAYER_TYPE_NONE; 2740 Paint mLayerPaint; 2741 Rect mLocalDirtyRect; 2742 2743 /** 2744 * Set to true when the view is sending hover accessibility events because it 2745 * is the innermost hovered view. 2746 */ 2747 private boolean mSendingHoverAccessibilityEvents; 2748 2749 /** 2750 * Delegate for injecting accessiblity functionality. 2751 */ 2752 AccessibilityDelegate mAccessibilityDelegate; 2753 2754 /** 2755 * Consistency verifier for debugging purposes. 2756 * @hide 2757 */ 2758 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 2759 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 2760 new InputEventConsistencyVerifier(this, 0) : null; 2761 2762 /** 2763 * Simple constructor to use when creating a view from code. 2764 * 2765 * @param context The Context the view is running in, through which it can 2766 * access the current theme, resources, etc. 2767 */ 2768 public View(Context context) { 2769 mContext = context; 2770 mResources = context != null ? context.getResources() : null; 2771 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 2772 // Set layout and text direction defaults 2773 mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) | 2774 (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT); 2775 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 2776 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 2777 mUserPaddingStart = -1; 2778 mUserPaddingEnd = -1; 2779 mUserPaddingRelative = false; 2780 } 2781 2782 /** 2783 * Constructor that is called when inflating a view from XML. This is called 2784 * when a view is being constructed from an XML file, supplying attributes 2785 * that were specified in the XML file. This version uses a default style of 2786 * 0, so the only attribute values applied are those in the Context's Theme 2787 * and the given AttributeSet. 2788 * 2789 * <p> 2790 * The method onFinishInflate() will be called after all children have been 2791 * added. 2792 * 2793 * @param context The Context the view is running in, through which it can 2794 * access the current theme, resources, etc. 2795 * @param attrs The attributes of the XML tag that is inflating the view. 2796 * @see #View(Context, AttributeSet, int) 2797 */ 2798 public View(Context context, AttributeSet attrs) { 2799 this(context, attrs, 0); 2800 } 2801 2802 /** 2803 * Perform inflation from XML and apply a class-specific base style. This 2804 * constructor of View allows subclasses to use their own base style when 2805 * they are inflating. For example, a Button class's constructor would call 2806 * this version of the super class constructor and supply 2807 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 2808 * the theme's button style to modify all of the base view attributes (in 2809 * particular its background) as well as the Button class's attributes. 2810 * 2811 * @param context The Context the view is running in, through which it can 2812 * access the current theme, resources, etc. 2813 * @param attrs The attributes of the XML tag that is inflating the view. 2814 * @param defStyle The default style to apply to this view. If 0, no style 2815 * will be applied (beyond what is included in the theme). This may 2816 * either be an attribute resource, whose value will be retrieved 2817 * from the current theme, or an explicit style resource. 2818 * @see #View(Context, AttributeSet) 2819 */ 2820 public View(Context context, AttributeSet attrs, int defStyle) { 2821 this(context); 2822 2823 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 2824 defStyle, 0); 2825 2826 Drawable background = null; 2827 2828 int leftPadding = -1; 2829 int topPadding = -1; 2830 int rightPadding = -1; 2831 int bottomPadding = -1; 2832 int startPadding = -1; 2833 int endPadding = -1; 2834 2835 int padding = -1; 2836 2837 int viewFlagValues = 0; 2838 int viewFlagMasks = 0; 2839 2840 boolean setScrollContainer = false; 2841 2842 int x = 0; 2843 int y = 0; 2844 2845 float tx = 0; 2846 float ty = 0; 2847 float rotation = 0; 2848 float rotationX = 0; 2849 float rotationY = 0; 2850 float sx = 1f; 2851 float sy = 1f; 2852 boolean transformSet = false; 2853 2854 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 2855 2856 int overScrollMode = mOverScrollMode; 2857 final int N = a.getIndexCount(); 2858 for (int i = 0; i < N; i++) { 2859 int attr = a.getIndex(i); 2860 switch (attr) { 2861 case com.android.internal.R.styleable.View_background: 2862 background = a.getDrawable(attr); 2863 break; 2864 case com.android.internal.R.styleable.View_padding: 2865 padding = a.getDimensionPixelSize(attr, -1); 2866 break; 2867 case com.android.internal.R.styleable.View_paddingLeft: 2868 leftPadding = a.getDimensionPixelSize(attr, -1); 2869 break; 2870 case com.android.internal.R.styleable.View_paddingTop: 2871 topPadding = a.getDimensionPixelSize(attr, -1); 2872 break; 2873 case com.android.internal.R.styleable.View_paddingRight: 2874 rightPadding = a.getDimensionPixelSize(attr, -1); 2875 break; 2876 case com.android.internal.R.styleable.View_paddingBottom: 2877 bottomPadding = a.getDimensionPixelSize(attr, -1); 2878 break; 2879 case com.android.internal.R.styleable.View_paddingStart: 2880 startPadding = a.getDimensionPixelSize(attr, -1); 2881 break; 2882 case com.android.internal.R.styleable.View_paddingEnd: 2883 endPadding = a.getDimensionPixelSize(attr, -1); 2884 break; 2885 case com.android.internal.R.styleable.View_scrollX: 2886 x = a.getDimensionPixelOffset(attr, 0); 2887 break; 2888 case com.android.internal.R.styleable.View_scrollY: 2889 y = a.getDimensionPixelOffset(attr, 0); 2890 break; 2891 case com.android.internal.R.styleable.View_alpha: 2892 setAlpha(a.getFloat(attr, 1f)); 2893 break; 2894 case com.android.internal.R.styleable.View_transformPivotX: 2895 setPivotX(a.getDimensionPixelOffset(attr, 0)); 2896 break; 2897 case com.android.internal.R.styleable.View_transformPivotY: 2898 setPivotY(a.getDimensionPixelOffset(attr, 0)); 2899 break; 2900 case com.android.internal.R.styleable.View_translationX: 2901 tx = a.getDimensionPixelOffset(attr, 0); 2902 transformSet = true; 2903 break; 2904 case com.android.internal.R.styleable.View_translationY: 2905 ty = a.getDimensionPixelOffset(attr, 0); 2906 transformSet = true; 2907 break; 2908 case com.android.internal.R.styleable.View_rotation: 2909 rotation = a.getFloat(attr, 0); 2910 transformSet = true; 2911 break; 2912 case com.android.internal.R.styleable.View_rotationX: 2913 rotationX = a.getFloat(attr, 0); 2914 transformSet = true; 2915 break; 2916 case com.android.internal.R.styleable.View_rotationY: 2917 rotationY = a.getFloat(attr, 0); 2918 transformSet = true; 2919 break; 2920 case com.android.internal.R.styleable.View_scaleX: 2921 sx = a.getFloat(attr, 1f); 2922 transformSet = true; 2923 break; 2924 case com.android.internal.R.styleable.View_scaleY: 2925 sy = a.getFloat(attr, 1f); 2926 transformSet = true; 2927 break; 2928 case com.android.internal.R.styleable.View_id: 2929 mID = a.getResourceId(attr, NO_ID); 2930 break; 2931 case com.android.internal.R.styleable.View_tag: 2932 mTag = a.getText(attr); 2933 break; 2934 case com.android.internal.R.styleable.View_fitsSystemWindows: 2935 if (a.getBoolean(attr, false)) { 2936 viewFlagValues |= FITS_SYSTEM_WINDOWS; 2937 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 2938 } 2939 break; 2940 case com.android.internal.R.styleable.View_focusable: 2941 if (a.getBoolean(attr, false)) { 2942 viewFlagValues |= FOCUSABLE; 2943 viewFlagMasks |= FOCUSABLE_MASK; 2944 } 2945 break; 2946 case com.android.internal.R.styleable.View_focusableInTouchMode: 2947 if (a.getBoolean(attr, false)) { 2948 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 2949 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 2950 } 2951 break; 2952 case com.android.internal.R.styleable.View_clickable: 2953 if (a.getBoolean(attr, false)) { 2954 viewFlagValues |= CLICKABLE; 2955 viewFlagMasks |= CLICKABLE; 2956 } 2957 break; 2958 case com.android.internal.R.styleable.View_longClickable: 2959 if (a.getBoolean(attr, false)) { 2960 viewFlagValues |= LONG_CLICKABLE; 2961 viewFlagMasks |= LONG_CLICKABLE; 2962 } 2963 break; 2964 case com.android.internal.R.styleable.View_saveEnabled: 2965 if (!a.getBoolean(attr, true)) { 2966 viewFlagValues |= SAVE_DISABLED; 2967 viewFlagMasks |= SAVE_DISABLED_MASK; 2968 } 2969 break; 2970 case com.android.internal.R.styleable.View_duplicateParentState: 2971 if (a.getBoolean(attr, false)) { 2972 viewFlagValues |= DUPLICATE_PARENT_STATE; 2973 viewFlagMasks |= DUPLICATE_PARENT_STATE; 2974 } 2975 break; 2976 case com.android.internal.R.styleable.View_visibility: 2977 final int visibility = a.getInt(attr, 0); 2978 if (visibility != 0) { 2979 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 2980 viewFlagMasks |= VISIBILITY_MASK; 2981 } 2982 break; 2983 case com.android.internal.R.styleable.View_layoutDirection: 2984 // Clear any layout direction flags (included resolved bits) already set 2985 mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK); 2986 // Set the layout direction flags depending on the value of the attribute 2987 final int layoutDirection = a.getInt(attr, -1); 2988 final int value = (layoutDirection != -1) ? 2989 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 2990 mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT); 2991 break; 2992 case com.android.internal.R.styleable.View_drawingCacheQuality: 2993 final int cacheQuality = a.getInt(attr, 0); 2994 if (cacheQuality != 0) { 2995 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 2996 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 2997 } 2998 break; 2999 case com.android.internal.R.styleable.View_contentDescription: 3000 mContentDescription = a.getString(attr); 3001 break; 3002 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3003 if (!a.getBoolean(attr, true)) { 3004 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3005 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3006 } 3007 break; 3008 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3009 if (!a.getBoolean(attr, true)) { 3010 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3011 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3012 } 3013 break; 3014 case R.styleable.View_scrollbars: 3015 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3016 if (scrollbars != SCROLLBARS_NONE) { 3017 viewFlagValues |= scrollbars; 3018 viewFlagMasks |= SCROLLBARS_MASK; 3019 initializeScrollbars(a); 3020 } 3021 break; 3022 //noinspection deprecation 3023 case R.styleable.View_fadingEdge: 3024 if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) { 3025 // Ignore the attribute starting with ICS 3026 break; 3027 } 3028 // With builds < ICS, fall through and apply fading edges 3029 case R.styleable.View_requiresFadingEdge: 3030 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3031 if (fadingEdge != FADING_EDGE_NONE) { 3032 viewFlagValues |= fadingEdge; 3033 viewFlagMasks |= FADING_EDGE_MASK; 3034 initializeFadingEdge(a); 3035 } 3036 break; 3037 case R.styleable.View_scrollbarStyle: 3038 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3039 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3040 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3041 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3042 } 3043 break; 3044 case R.styleable.View_isScrollContainer: 3045 setScrollContainer = true; 3046 if (a.getBoolean(attr, false)) { 3047 setScrollContainer(true); 3048 } 3049 break; 3050 case com.android.internal.R.styleable.View_keepScreenOn: 3051 if (a.getBoolean(attr, false)) { 3052 viewFlagValues |= KEEP_SCREEN_ON; 3053 viewFlagMasks |= KEEP_SCREEN_ON; 3054 } 3055 break; 3056 case R.styleable.View_filterTouchesWhenObscured: 3057 if (a.getBoolean(attr, false)) { 3058 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3059 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3060 } 3061 break; 3062 case R.styleable.View_nextFocusLeft: 3063 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3064 break; 3065 case R.styleable.View_nextFocusRight: 3066 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3067 break; 3068 case R.styleable.View_nextFocusUp: 3069 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3070 break; 3071 case R.styleable.View_nextFocusDown: 3072 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3073 break; 3074 case R.styleable.View_nextFocusForward: 3075 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3076 break; 3077 case R.styleable.View_minWidth: 3078 mMinWidth = a.getDimensionPixelSize(attr, 0); 3079 break; 3080 case R.styleable.View_minHeight: 3081 mMinHeight = a.getDimensionPixelSize(attr, 0); 3082 break; 3083 case R.styleable.View_onClick: 3084 if (context.isRestricted()) { 3085 throw new IllegalStateException("The android:onClick attribute cannot " 3086 + "be used within a restricted context"); 3087 } 3088 3089 final String handlerName = a.getString(attr); 3090 if (handlerName != null) { 3091 setOnClickListener(new OnClickListener() { 3092 private Method mHandler; 3093 3094 public void onClick(View v) { 3095 if (mHandler == null) { 3096 try { 3097 mHandler = getContext().getClass().getMethod(handlerName, 3098 View.class); 3099 } catch (NoSuchMethodException e) { 3100 int id = getId(); 3101 String idText = id == NO_ID ? "" : " with id '" 3102 + getContext().getResources().getResourceEntryName( 3103 id) + "'"; 3104 throw new IllegalStateException("Could not find a method " + 3105 handlerName + "(View) in the activity " 3106 + getContext().getClass() + " for onClick handler" 3107 + " on view " + View.this.getClass() + idText, e); 3108 } 3109 } 3110 3111 try { 3112 mHandler.invoke(getContext(), View.this); 3113 } catch (IllegalAccessException e) { 3114 throw new IllegalStateException("Could not execute non " 3115 + "public method of the activity", e); 3116 } catch (InvocationTargetException e) { 3117 throw new IllegalStateException("Could not execute " 3118 + "method of the activity", e); 3119 } 3120 } 3121 }); 3122 } 3123 break; 3124 case R.styleable.View_overScrollMode: 3125 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3126 break; 3127 case R.styleable.View_verticalScrollbarPosition: 3128 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3129 break; 3130 case R.styleable.View_layerType: 3131 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3132 break; 3133 case R.styleable.View_textDirection: 3134 // Clear any text direction flag already set 3135 mPrivateFlags2 &= ~TEXT_DIRECTION_MASK; 3136 // Set the text direction flags depending on the value of the attribute 3137 final int textDirection = a.getInt(attr, -1); 3138 if (textDirection != -1) { 3139 mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection]; 3140 } 3141 break; 3142 } 3143 } 3144 3145 a.recycle(); 3146 3147 setOverScrollMode(overScrollMode); 3148 3149 if (background != null) { 3150 setBackgroundDrawable(background); 3151 } 3152 3153 // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved 3154 // layout direction). Those cached values will be used later during padding resolution. 3155 mUserPaddingStart = startPadding; 3156 mUserPaddingEnd = endPadding; 3157 3158 updateUserPaddingRelative(); 3159 3160 if (padding >= 0) { 3161 leftPadding = padding; 3162 topPadding = padding; 3163 rightPadding = padding; 3164 bottomPadding = padding; 3165 } 3166 3167 // If the user specified the padding (either with android:padding or 3168 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 3169 // use the default padding or the padding from the background drawable 3170 // (stored at this point in mPadding*) 3171 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft, 3172 topPadding >= 0 ? topPadding : mPaddingTop, 3173 rightPadding >= 0 ? rightPadding : mPaddingRight, 3174 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3175 3176 if (viewFlagMasks != 0) { 3177 setFlags(viewFlagValues, viewFlagMasks); 3178 } 3179 3180 // Needs to be called after mViewFlags is set 3181 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3182 recomputePadding(); 3183 } 3184 3185 if (x != 0 || y != 0) { 3186 scrollTo(x, y); 3187 } 3188 3189 if (transformSet) { 3190 setTranslationX(tx); 3191 setTranslationY(ty); 3192 setRotation(rotation); 3193 setRotationX(rotationX); 3194 setRotationY(rotationY); 3195 setScaleX(sx); 3196 setScaleY(sy); 3197 } 3198 3199 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3200 setScrollContainer(true); 3201 } 3202 3203 computeOpaqueFlags(); 3204 } 3205 3206 private void updateUserPaddingRelative() { 3207 mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0); 3208 } 3209 3210 /** 3211 * Non-public constructor for use in testing 3212 */ 3213 View() { 3214 mResources = null; 3215 } 3216 3217 /** 3218 * <p> 3219 * Initializes the fading edges from a given set of styled attributes. This 3220 * method should be called by subclasses that need fading edges and when an 3221 * instance of these subclasses is created programmatically rather than 3222 * being inflated from XML. This method is automatically called when the XML 3223 * is inflated. 3224 * </p> 3225 * 3226 * @param a the styled attributes set to initialize the fading edges from 3227 */ 3228 protected void initializeFadingEdge(TypedArray a) { 3229 initScrollCache(); 3230 3231 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3232 R.styleable.View_fadingEdgeLength, 3233 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3234 } 3235 3236 /** 3237 * Returns the size of the vertical faded edges used to indicate that more 3238 * content in this view is visible. 3239 * 3240 * @return The size in pixels of the vertical faded edge or 0 if vertical 3241 * faded edges are not enabled for this view. 3242 * @attr ref android.R.styleable#View_fadingEdgeLength 3243 */ 3244 public int getVerticalFadingEdgeLength() { 3245 if (isVerticalFadingEdgeEnabled()) { 3246 ScrollabilityCache cache = mScrollCache; 3247 if (cache != null) { 3248 return cache.fadingEdgeLength; 3249 } 3250 } 3251 return 0; 3252 } 3253 3254 /** 3255 * Set the size of the faded edge used to indicate that more content in this 3256 * view is available. Will not change whether the fading edge is enabled; use 3257 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3258 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3259 * for the vertical or horizontal fading edges. 3260 * 3261 * @param length The size in pixels of the faded edge used to indicate that more 3262 * content in this view is visible. 3263 */ 3264 public void setFadingEdgeLength(int length) { 3265 initScrollCache(); 3266 mScrollCache.fadingEdgeLength = length; 3267 } 3268 3269 /** 3270 * Returns the size of the horizontal faded edges used to indicate that more 3271 * content in this view is visible. 3272 * 3273 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3274 * faded edges are not enabled for this view. 3275 * @attr ref android.R.styleable#View_fadingEdgeLength 3276 */ 3277 public int getHorizontalFadingEdgeLength() { 3278 if (isHorizontalFadingEdgeEnabled()) { 3279 ScrollabilityCache cache = mScrollCache; 3280 if (cache != null) { 3281 return cache.fadingEdgeLength; 3282 } 3283 } 3284 return 0; 3285 } 3286 3287 /** 3288 * Returns the width of the vertical scrollbar. 3289 * 3290 * @return The width in pixels of the vertical scrollbar or 0 if there 3291 * is no vertical scrollbar. 3292 */ 3293 public int getVerticalScrollbarWidth() { 3294 ScrollabilityCache cache = mScrollCache; 3295 if (cache != null) { 3296 ScrollBarDrawable scrollBar = cache.scrollBar; 3297 if (scrollBar != null) { 3298 int size = scrollBar.getSize(true); 3299 if (size <= 0) { 3300 size = cache.scrollBarSize; 3301 } 3302 return size; 3303 } 3304 return 0; 3305 } 3306 return 0; 3307 } 3308 3309 /** 3310 * Returns the height of the horizontal scrollbar. 3311 * 3312 * @return The height in pixels of the horizontal scrollbar or 0 if 3313 * there is no horizontal scrollbar. 3314 */ 3315 protected int getHorizontalScrollbarHeight() { 3316 ScrollabilityCache cache = mScrollCache; 3317 if (cache != null) { 3318 ScrollBarDrawable scrollBar = cache.scrollBar; 3319 if (scrollBar != null) { 3320 int size = scrollBar.getSize(false); 3321 if (size <= 0) { 3322 size = cache.scrollBarSize; 3323 } 3324 return size; 3325 } 3326 return 0; 3327 } 3328 return 0; 3329 } 3330 3331 /** 3332 * <p> 3333 * Initializes the scrollbars from a given set of styled attributes. This 3334 * method should be called by subclasses that need scrollbars and when an 3335 * instance of these subclasses is created programmatically rather than 3336 * being inflated from XML. This method is automatically called when the XML 3337 * is inflated. 3338 * </p> 3339 * 3340 * @param a the styled attributes set to initialize the scrollbars from 3341 */ 3342 protected void initializeScrollbars(TypedArray a) { 3343 initScrollCache(); 3344 3345 final ScrollabilityCache scrollabilityCache = mScrollCache; 3346 3347 if (scrollabilityCache.scrollBar == null) { 3348 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 3349 } 3350 3351 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 3352 3353 if (!fadeScrollbars) { 3354 scrollabilityCache.state = ScrollabilityCache.ON; 3355 } 3356 scrollabilityCache.fadeScrollBars = fadeScrollbars; 3357 3358 3359 scrollabilityCache.scrollBarFadeDuration = a.getInt( 3360 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 3361 .getScrollBarFadeDuration()); 3362 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 3363 R.styleable.View_scrollbarDefaultDelayBeforeFade, 3364 ViewConfiguration.getScrollDefaultDelay()); 3365 3366 3367 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 3368 com.android.internal.R.styleable.View_scrollbarSize, 3369 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3370 3371 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3372 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3373 3374 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3375 if (thumb != null) { 3376 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3377 } 3378 3379 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3380 false); 3381 if (alwaysDraw) { 3382 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3383 } 3384 3385 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3386 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3387 3388 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3389 if (thumb != null) { 3390 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3391 } 3392 3393 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3394 false); 3395 if (alwaysDraw) { 3396 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3397 } 3398 3399 // Re-apply user/background padding so that scrollbar(s) get added 3400 resolvePadding(); 3401 } 3402 3403 /** 3404 * <p> 3405 * Initalizes the scrollability cache if necessary. 3406 * </p> 3407 */ 3408 private void initScrollCache() { 3409 if (mScrollCache == null) { 3410 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 3411 } 3412 } 3413 3414 /** 3415 * Set the position of the vertical scroll bar. Should be one of 3416 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 3417 * {@link #SCROLLBAR_POSITION_RIGHT}. 3418 * 3419 * @param position Where the vertical scroll bar should be positioned. 3420 */ 3421 public void setVerticalScrollbarPosition(int position) { 3422 if (mVerticalScrollbarPosition != position) { 3423 mVerticalScrollbarPosition = position; 3424 computeOpaqueFlags(); 3425 resolvePadding(); 3426 } 3427 } 3428 3429 /** 3430 * @return The position where the vertical scroll bar will show, if applicable. 3431 * @see #setVerticalScrollbarPosition(int) 3432 */ 3433 public int getVerticalScrollbarPosition() { 3434 return mVerticalScrollbarPosition; 3435 } 3436 3437 ListenerInfo getListenerInfo() { 3438 if (mListenerInfo != null) { 3439 return mListenerInfo; 3440 } 3441 mListenerInfo = new ListenerInfo(); 3442 return mListenerInfo; 3443 } 3444 3445 /** 3446 * Register a callback to be invoked when focus of this view changed. 3447 * 3448 * @param l The callback that will run. 3449 */ 3450 public void setOnFocusChangeListener(OnFocusChangeListener l) { 3451 getListenerInfo().mOnFocusChangeListener = l; 3452 } 3453 3454 /** 3455 * Add a listener that will be called when the bounds of the view change due to 3456 * layout processing. 3457 * 3458 * @param listener The listener that will be called when layout bounds change. 3459 */ 3460 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 3461 ListenerInfo li = getListenerInfo(); 3462 if (li.mOnLayoutChangeListeners == null) { 3463 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 3464 } 3465 if (!li.mOnLayoutChangeListeners.contains(listener)) { 3466 li.mOnLayoutChangeListeners.add(listener); 3467 } 3468 } 3469 3470 /** 3471 * Remove a listener for layout changes. 3472 * 3473 * @param listener The listener for layout bounds change. 3474 */ 3475 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 3476 ListenerInfo li = mListenerInfo; 3477 if (li == null || li.mOnLayoutChangeListeners == null) { 3478 return; 3479 } 3480 li.mOnLayoutChangeListeners.remove(listener); 3481 } 3482 3483 /** 3484 * Add a listener for attach state changes. 3485 * 3486 * This listener will be called whenever this view is attached or detached 3487 * from a window. Remove the listener using 3488 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 3489 * 3490 * @param listener Listener to attach 3491 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 3492 */ 3493 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3494 ListenerInfo li = getListenerInfo(); 3495 if (li.mOnAttachStateChangeListeners == null) { 3496 li.mOnAttachStateChangeListeners 3497 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 3498 } 3499 li.mOnAttachStateChangeListeners.add(listener); 3500 } 3501 3502 /** 3503 * Remove a listener for attach state changes. The listener will receive no further 3504 * notification of window attach/detach events. 3505 * 3506 * @param listener Listener to remove 3507 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 3508 */ 3509 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3510 ListenerInfo li = mListenerInfo; 3511 if (li == null || li.mOnAttachStateChangeListeners == null) { 3512 return; 3513 } 3514 li.mOnAttachStateChangeListeners.remove(listener); 3515 } 3516 3517 /** 3518 * Returns the focus-change callback registered for this view. 3519 * 3520 * @return The callback, or null if one is not registered. 3521 */ 3522 public OnFocusChangeListener getOnFocusChangeListener() { 3523 ListenerInfo li = mListenerInfo; 3524 return li != null ? li.mOnFocusChangeListener : null; 3525 } 3526 3527 /** 3528 * Register a callback to be invoked when this view is clicked. If this view is not 3529 * clickable, it becomes clickable. 3530 * 3531 * @param l The callback that will run 3532 * 3533 * @see #setClickable(boolean) 3534 */ 3535 public void setOnClickListener(OnClickListener l) { 3536 if (!isClickable()) { 3537 setClickable(true); 3538 } 3539 getListenerInfo().mOnClickListener = l; 3540 } 3541 3542 /** 3543 * Return whether this view has an attached OnClickListener. Returns 3544 * true if there is a listener, false if there is none. 3545 */ 3546 public boolean hasOnClickListeners() { 3547 ListenerInfo li = mListenerInfo; 3548 return (li != null && li.mOnClickListener != null); 3549 } 3550 3551 /** 3552 * Register a callback to be invoked when this view is clicked and held. If this view is not 3553 * long clickable, it becomes long clickable. 3554 * 3555 * @param l The callback that will run 3556 * 3557 * @see #setLongClickable(boolean) 3558 */ 3559 public void setOnLongClickListener(OnLongClickListener l) { 3560 if (!isLongClickable()) { 3561 setLongClickable(true); 3562 } 3563 getListenerInfo().mOnLongClickListener = l; 3564 } 3565 3566 /** 3567 * Register a callback to be invoked when the context menu for this view is 3568 * being built. If this view is not long clickable, it becomes long clickable. 3569 * 3570 * @param l The callback that will run 3571 * 3572 */ 3573 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 3574 if (!isLongClickable()) { 3575 setLongClickable(true); 3576 } 3577 getListenerInfo().mOnCreateContextMenuListener = l; 3578 } 3579 3580 /** 3581 * Call this view's OnClickListener, if it is defined. Performs all normal 3582 * actions associated with clicking: reporting accessibility event, playing 3583 * a sound, etc. 3584 * 3585 * @return True there was an assigned OnClickListener that was called, false 3586 * otherwise is returned. 3587 */ 3588 public boolean performClick() { 3589 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 3590 3591 ListenerInfo li = mListenerInfo; 3592 if (li != null && li.mOnClickListener != null) { 3593 playSoundEffect(SoundEffectConstants.CLICK); 3594 li.mOnClickListener.onClick(this); 3595 return true; 3596 } 3597 3598 return false; 3599 } 3600 3601 /** 3602 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 3603 * this only calls the listener, and does not do any associated clicking 3604 * actions like reporting an accessibility event. 3605 * 3606 * @return True there was an assigned OnClickListener that was called, false 3607 * otherwise is returned. 3608 */ 3609 public boolean callOnClick() { 3610 ListenerInfo li = mListenerInfo; 3611 if (li != null && li.mOnClickListener != null) { 3612 li.mOnClickListener.onClick(this); 3613 return true; 3614 } 3615 return false; 3616 } 3617 3618 /** 3619 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 3620 * OnLongClickListener did not consume the event. 3621 * 3622 * @return True if one of the above receivers consumed the event, false otherwise. 3623 */ 3624 public boolean performLongClick() { 3625 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 3626 3627 boolean handled = false; 3628 ListenerInfo li = mListenerInfo; 3629 if (li != null && li.mOnLongClickListener != null) { 3630 handled = li.mOnLongClickListener.onLongClick(View.this); 3631 } 3632 if (!handled) { 3633 handled = showContextMenu(); 3634 } 3635 if (handled) { 3636 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 3637 } 3638 return handled; 3639 } 3640 3641 /** 3642 * Performs button-related actions during a touch down event. 3643 * 3644 * @param event The event. 3645 * @return True if the down was consumed. 3646 * 3647 * @hide 3648 */ 3649 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 3650 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 3651 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 3652 return true; 3653 } 3654 } 3655 return false; 3656 } 3657 3658 /** 3659 * Bring up the context menu for this view. 3660 * 3661 * @return Whether a context menu was displayed. 3662 */ 3663 public boolean showContextMenu() { 3664 return getParent().showContextMenuForChild(this); 3665 } 3666 3667 /** 3668 * Bring up the context menu for this view, referring to the item under the specified point. 3669 * 3670 * @param x The referenced x coordinate. 3671 * @param y The referenced y coordinate. 3672 * @param metaState The keyboard modifiers that were pressed. 3673 * @return Whether a context menu was displayed. 3674 * 3675 * @hide 3676 */ 3677 public boolean showContextMenu(float x, float y, int metaState) { 3678 return showContextMenu(); 3679 } 3680 3681 /** 3682 * Start an action mode. 3683 * 3684 * @param callback Callback that will control the lifecycle of the action mode 3685 * @return The new action mode if it is started, null otherwise 3686 * 3687 * @see ActionMode 3688 */ 3689 public ActionMode startActionMode(ActionMode.Callback callback) { 3690 ViewParent parent = getParent(); 3691 if (parent == null) return null; 3692 return parent.startActionModeForChild(this, callback); 3693 } 3694 3695 /** 3696 * Register a callback to be invoked when a key is pressed in this view. 3697 * @param l the key listener to attach to this view 3698 */ 3699 public void setOnKeyListener(OnKeyListener l) { 3700 getListenerInfo().mOnKeyListener = l; 3701 } 3702 3703 /** 3704 * Register a callback to be invoked when a touch event is sent to this view. 3705 * @param l the touch listener to attach to this view 3706 */ 3707 public void setOnTouchListener(OnTouchListener l) { 3708 getListenerInfo().mOnTouchListener = l; 3709 } 3710 3711 /** 3712 * Register a callback to be invoked when a generic motion event is sent to this view. 3713 * @param l the generic motion listener to attach to this view 3714 */ 3715 public void setOnGenericMotionListener(OnGenericMotionListener l) { 3716 getListenerInfo().mOnGenericMotionListener = l; 3717 } 3718 3719 /** 3720 * Register a callback to be invoked when a hover event is sent to this view. 3721 * @param l the hover listener to attach to this view 3722 */ 3723 public void setOnHoverListener(OnHoverListener l) { 3724 getListenerInfo().mOnHoverListener = l; 3725 } 3726 3727 /** 3728 * Register a drag event listener callback object for this View. The parameter is 3729 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 3730 * View, the system calls the 3731 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 3732 * @param l An implementation of {@link android.view.View.OnDragListener}. 3733 */ 3734 public void setOnDragListener(OnDragListener l) { 3735 getListenerInfo().mOnDragListener = l; 3736 } 3737 3738 /** 3739 * Give this view focus. This will cause 3740 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3741 * 3742 * Note: this does not check whether this {@link View} should get focus, it just 3743 * gives it focus no matter what. It should only be called internally by framework 3744 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 3745 * 3746 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 3747 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 3748 * focus moved when requestFocus() is called. It may not always 3749 * apply, in which case use the default View.FOCUS_DOWN. 3750 * @param previouslyFocusedRect The rectangle of the view that had focus 3751 * prior in this View's coordinate system. 3752 */ 3753 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 3754 if (DBG) { 3755 System.out.println(this + " requestFocus()"); 3756 } 3757 3758 if ((mPrivateFlags & FOCUSED) == 0) { 3759 mPrivateFlags |= FOCUSED; 3760 3761 if (mParent != null) { 3762 mParent.requestChildFocus(this, this); 3763 } 3764 3765 onFocusChanged(true, direction, previouslyFocusedRect); 3766 refreshDrawableState(); 3767 } 3768 } 3769 3770 /** 3771 * Request that a rectangle of this view be visible on the screen, 3772 * scrolling if necessary just enough. 3773 * 3774 * <p>A View should call this if it maintains some notion of which part 3775 * of its content is interesting. For example, a text editing view 3776 * should call this when its cursor moves. 3777 * 3778 * @param rectangle The rectangle. 3779 * @return Whether any parent scrolled. 3780 */ 3781 public boolean requestRectangleOnScreen(Rect rectangle) { 3782 return requestRectangleOnScreen(rectangle, false); 3783 } 3784 3785 /** 3786 * Request that a rectangle of this view be visible on the screen, 3787 * scrolling if necessary just enough. 3788 * 3789 * <p>A View should call this if it maintains some notion of which part 3790 * of its content is interesting. For example, a text editing view 3791 * should call this when its cursor moves. 3792 * 3793 * <p>When <code>immediate</code> is set to true, scrolling will not be 3794 * animated. 3795 * 3796 * @param rectangle The rectangle. 3797 * @param immediate True to forbid animated scrolling, false otherwise 3798 * @return Whether any parent scrolled. 3799 */ 3800 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 3801 View child = this; 3802 ViewParent parent = mParent; 3803 boolean scrolled = false; 3804 while (parent != null) { 3805 scrolled |= parent.requestChildRectangleOnScreen(child, 3806 rectangle, immediate); 3807 3808 // offset rect so next call has the rectangle in the 3809 // coordinate system of its direct child. 3810 rectangle.offset(child.getLeft(), child.getTop()); 3811 rectangle.offset(-child.getScrollX(), -child.getScrollY()); 3812 3813 if (!(parent instanceof View)) { 3814 break; 3815 } 3816 3817 child = (View) parent; 3818 parent = child.getParent(); 3819 } 3820 return scrolled; 3821 } 3822 3823 /** 3824 * Called when this view wants to give up focus. If focus is cleared 3825 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 3826 * <p> 3827 * <strong>Note:</strong> When a View clears focus the framework is trying 3828 * to give focus to the first focusable View from the top. Hence, if this 3829 * View is the first from the top that can take focus, then its focus will 3830 * not be cleared nor will the focus change callback be invoked. 3831 * </p> 3832 */ 3833 public void clearFocus() { 3834 if (DBG) { 3835 System.out.println(this + " clearFocus()"); 3836 } 3837 3838 if ((mPrivateFlags & FOCUSED) != 0) { 3839 mPrivateFlags &= ~FOCUSED; 3840 3841 if (mParent != null) { 3842 mParent.clearChildFocus(this); 3843 } 3844 3845 onFocusChanged(false, 0, null); 3846 refreshDrawableState(); 3847 } 3848 } 3849 3850 /** 3851 * Called to clear the focus of a view that is about to be removed. 3852 * Doesn't call clearChildFocus, which prevents this view from taking 3853 * focus again before it has been removed from the parent 3854 */ 3855 void clearFocusForRemoval() { 3856 if ((mPrivateFlags & FOCUSED) != 0) { 3857 mPrivateFlags &= ~FOCUSED; 3858 3859 onFocusChanged(false, 0, null); 3860 refreshDrawableState(); 3861 3862 // The view cleared focus and invoked the callbacks, so now is the 3863 // time to give focus to the the first focusable from the top to 3864 // ensure that the gain focus is announced after clear focus. 3865 getRootView().requestFocus(FOCUS_FORWARD); 3866 } 3867 } 3868 3869 /** 3870 * Called internally by the view system when a new view is getting focus. 3871 * This is what clears the old focus. 3872 */ 3873 void unFocus() { 3874 if (DBG) { 3875 System.out.println(this + " unFocus()"); 3876 } 3877 3878 if ((mPrivateFlags & FOCUSED) != 0) { 3879 mPrivateFlags &= ~FOCUSED; 3880 3881 onFocusChanged(false, 0, null); 3882 refreshDrawableState(); 3883 } 3884 } 3885 3886 /** 3887 * Returns true if this view has focus iteself, or is the ancestor of the 3888 * view that has focus. 3889 * 3890 * @return True if this view has or contains focus, false otherwise. 3891 */ 3892 @ViewDebug.ExportedProperty(category = "focus") 3893 public boolean hasFocus() { 3894 return (mPrivateFlags & FOCUSED) != 0; 3895 } 3896 3897 /** 3898 * Returns true if this view is focusable or if it contains a reachable View 3899 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 3900 * is a View whose parents do not block descendants focus. 3901 * 3902 * Only {@link #VISIBLE} views are considered focusable. 3903 * 3904 * @return True if the view is focusable or if the view contains a focusable 3905 * View, false otherwise. 3906 * 3907 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 3908 */ 3909 public boolean hasFocusable() { 3910 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 3911 } 3912 3913 /** 3914 * Called by the view system when the focus state of this view changes. 3915 * When the focus change event is caused by directional navigation, direction 3916 * and previouslyFocusedRect provide insight into where the focus is coming from. 3917 * When overriding, be sure to call up through to the super class so that 3918 * the standard focus handling will occur. 3919 * 3920 * @param gainFocus True if the View has focus; false otherwise. 3921 * @param direction The direction focus has moved when requestFocus() 3922 * is called to give this view focus. Values are 3923 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 3924 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 3925 * It may not always apply, in which case use the default. 3926 * @param previouslyFocusedRect The rectangle, in this view's coordinate 3927 * system, of the previously focused view. If applicable, this will be 3928 * passed in as finer grained information about where the focus is coming 3929 * from (in addition to direction). Will be <code>null</code> otherwise. 3930 */ 3931 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 3932 if (gainFocus) { 3933 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 3934 } 3935 3936 InputMethodManager imm = InputMethodManager.peekInstance(); 3937 if (!gainFocus) { 3938 if (isPressed()) { 3939 setPressed(false); 3940 } 3941 if (imm != null && mAttachInfo != null 3942 && mAttachInfo.mHasWindowFocus) { 3943 imm.focusOut(this); 3944 } 3945 onFocusLost(); 3946 } else if (imm != null && mAttachInfo != null 3947 && mAttachInfo.mHasWindowFocus) { 3948 imm.focusIn(this); 3949 } 3950 3951 invalidate(true); 3952 ListenerInfo li = mListenerInfo; 3953 if (li != null && li.mOnFocusChangeListener != null) { 3954 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 3955 } 3956 3957 if (mAttachInfo != null) { 3958 mAttachInfo.mKeyDispatchState.reset(this); 3959 } 3960 } 3961 3962 /** 3963 * Sends an accessibility event of the given type. If accessiiblity is 3964 * not enabled this method has no effect. The default implementation calls 3965 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 3966 * to populate information about the event source (this View), then calls 3967 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 3968 * populate the text content of the event source including its descendants, 3969 * and last calls 3970 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 3971 * on its parent to resuest sending of the event to interested parties. 3972 * <p> 3973 * If an {@link AccessibilityDelegate} has been specified via calling 3974 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3975 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 3976 * responsible for handling this call. 3977 * </p> 3978 * 3979 * @param eventType The type of the event to send, as defined by several types from 3980 * {@link android.view.accessibility.AccessibilityEvent}, such as 3981 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 3982 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 3983 * 3984 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 3985 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3986 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 3987 * @see AccessibilityDelegate 3988 */ 3989 public void sendAccessibilityEvent(int eventType) { 3990 if (mAccessibilityDelegate != null) { 3991 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 3992 } else { 3993 sendAccessibilityEventInternal(eventType); 3994 } 3995 } 3996 3997 /** 3998 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 3999 * {@link AccessibilityEvent} to make an announcement which is related to some 4000 * sort of a context change for which none of the events representing UI transitions 4001 * is a good fit. For example, announcing a new page in a book. If accessibility 4002 * is not enabled this method does nothing. 4003 * 4004 * @param text The announcement text. 4005 */ 4006 public void announceForAccessibility(CharSequence text) { 4007 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4008 AccessibilityEvent event = AccessibilityEvent.obtain( 4009 AccessibilityEvent.TYPE_ANNOUNCEMENT); 4010 event.getText().add(text); 4011 sendAccessibilityEventUnchecked(event); 4012 } 4013 } 4014 4015 /** 4016 * @see #sendAccessibilityEvent(int) 4017 * 4018 * Note: Called from the default {@link AccessibilityDelegate}. 4019 */ 4020 void sendAccessibilityEventInternal(int eventType) { 4021 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4022 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 4023 } 4024 } 4025 4026 /** 4027 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 4028 * takes as an argument an empty {@link AccessibilityEvent} and does not 4029 * perform a check whether accessibility is enabled. 4030 * <p> 4031 * If an {@link AccessibilityDelegate} has been specified via calling 4032 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4033 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 4034 * is responsible for handling this call. 4035 * </p> 4036 * 4037 * @param event The event to send. 4038 * 4039 * @see #sendAccessibilityEvent(int) 4040 */ 4041 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 4042 if (mAccessibilityDelegate != null) { 4043 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 4044 } else { 4045 sendAccessibilityEventUncheckedInternal(event); 4046 } 4047 } 4048 4049 /** 4050 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 4051 * 4052 * Note: Called from the default {@link AccessibilityDelegate}. 4053 */ 4054 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 4055 if (!isShown()) { 4056 return; 4057 } 4058 onInitializeAccessibilityEvent(event); 4059 // Only a subset of accessibility events populates text content. 4060 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 4061 dispatchPopulateAccessibilityEvent(event); 4062 } 4063 // In the beginning we called #isShown(), so we know that getParent() is not null. 4064 getParent().requestSendAccessibilityEvent(this, event); 4065 } 4066 4067 /** 4068 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 4069 * to its children for adding their text content to the event. Note that the 4070 * event text is populated in a separate dispatch path since we add to the 4071 * event not only the text of the source but also the text of all its descendants. 4072 * A typical implementation will call 4073 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 4074 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4075 * on each child. Override this method if custom population of the event text 4076 * content is required. 4077 * <p> 4078 * If an {@link AccessibilityDelegate} has been specified via calling 4079 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4080 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 4081 * is responsible for handling this call. 4082 * </p> 4083 * <p> 4084 * <em>Note:</em> Accessibility events of certain types are not dispatched for 4085 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 4086 * </p> 4087 * 4088 * @param event The event. 4089 * 4090 * @return True if the event population was completed. 4091 */ 4092 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 4093 if (mAccessibilityDelegate != null) { 4094 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 4095 } else { 4096 return dispatchPopulateAccessibilityEventInternal(event); 4097 } 4098 } 4099 4100 /** 4101 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4102 * 4103 * Note: Called from the default {@link AccessibilityDelegate}. 4104 */ 4105 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4106 onPopulateAccessibilityEvent(event); 4107 return false; 4108 } 4109 4110 /** 4111 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4112 * giving a chance to this View to populate the accessibility event with its 4113 * text content. While this method is free to modify event 4114 * attributes other than text content, doing so should normally be performed in 4115 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 4116 * <p> 4117 * Example: Adding formatted date string to an accessibility event in addition 4118 * to the text added by the super implementation: 4119 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4120 * super.onPopulateAccessibilityEvent(event); 4121 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 4122 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 4123 * mCurrentDate.getTimeInMillis(), flags); 4124 * event.getText().add(selectedDateUtterance); 4125 * }</pre> 4126 * <p> 4127 * If an {@link AccessibilityDelegate} has been specified via calling 4128 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4129 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 4130 * is responsible for handling this call. 4131 * </p> 4132 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4133 * information to the event, in case the default implementation has basic information to add. 4134 * </p> 4135 * 4136 * @param event The accessibility event which to populate. 4137 * 4138 * @see #sendAccessibilityEvent(int) 4139 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4140 */ 4141 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4142 if (mAccessibilityDelegate != null) { 4143 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 4144 } else { 4145 onPopulateAccessibilityEventInternal(event); 4146 } 4147 } 4148 4149 /** 4150 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 4151 * 4152 * Note: Called from the default {@link AccessibilityDelegate}. 4153 */ 4154 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4155 4156 } 4157 4158 /** 4159 * Initializes an {@link AccessibilityEvent} with information about 4160 * this View which is the event source. In other words, the source of 4161 * an accessibility event is the view whose state change triggered firing 4162 * the event. 4163 * <p> 4164 * Example: Setting the password property of an event in addition 4165 * to properties set by the super implementation: 4166 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4167 * super.onInitializeAccessibilityEvent(event); 4168 * event.setPassword(true); 4169 * }</pre> 4170 * <p> 4171 * If an {@link AccessibilityDelegate} has been specified via calling 4172 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4173 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 4174 * is responsible for handling this call. 4175 * </p> 4176 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4177 * information to the event, in case the default implementation has basic information to add. 4178 * </p> 4179 * @param event The event to initialize. 4180 * 4181 * @see #sendAccessibilityEvent(int) 4182 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4183 */ 4184 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4185 if (mAccessibilityDelegate != null) { 4186 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 4187 } else { 4188 onInitializeAccessibilityEventInternal(event); 4189 } 4190 } 4191 4192 /** 4193 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4194 * 4195 * Note: Called from the default {@link AccessibilityDelegate}. 4196 */ 4197 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 4198 event.setSource(this); 4199 event.setClassName(View.class.getName()); 4200 event.setPackageName(getContext().getPackageName()); 4201 event.setEnabled(isEnabled()); 4202 event.setContentDescription(mContentDescription); 4203 4204 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) { 4205 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList; 4206 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, 4207 FOCUSABLES_ALL); 4208 event.setItemCount(focusablesTempList.size()); 4209 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 4210 focusablesTempList.clear(); 4211 } 4212 } 4213 4214 /** 4215 * Returns an {@link AccessibilityNodeInfo} representing this view from the 4216 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 4217 * This method is responsible for obtaining an accessibility node info from a 4218 * pool of reusable instances and calling 4219 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 4220 * initialize the former. 4221 * <p> 4222 * Note: The client is responsible for recycling the obtained instance by calling 4223 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 4224 * </p> 4225 * 4226 * @return A populated {@link AccessibilityNodeInfo}. 4227 * 4228 * @see AccessibilityNodeInfo 4229 */ 4230 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 4231 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 4232 if (provider != null) { 4233 return provider.createAccessibilityNodeInfo(View.NO_ID); 4234 } else { 4235 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 4236 onInitializeAccessibilityNodeInfo(info); 4237 return info; 4238 } 4239 } 4240 4241 /** 4242 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 4243 * The base implementation sets: 4244 * <ul> 4245 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 4246 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 4247 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 4248 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 4249 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 4250 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 4251 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 4252 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 4253 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 4254 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 4255 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 4256 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 4257 * </ul> 4258 * <p> 4259 * Subclasses should override this method, call the super implementation, 4260 * and set additional attributes. 4261 * </p> 4262 * <p> 4263 * If an {@link AccessibilityDelegate} has been specified via calling 4264 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4265 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 4266 * is responsible for handling this call. 4267 * </p> 4268 * 4269 * @param info The instance to initialize. 4270 */ 4271 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 4272 if (mAccessibilityDelegate != null) { 4273 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 4274 } else { 4275 onInitializeAccessibilityNodeInfoInternal(info); 4276 } 4277 } 4278 4279 /** 4280 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 4281 * 4282 * Note: Called from the default {@link AccessibilityDelegate}. 4283 */ 4284 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 4285 Rect bounds = mAttachInfo.mTmpInvalRect; 4286 getDrawingRect(bounds); 4287 info.setBoundsInParent(bounds); 4288 4289 int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation; 4290 getLocationOnScreen(locationOnScreen); 4291 bounds.offsetTo(0, 0); 4292 bounds.offset(locationOnScreen[0], locationOnScreen[1]); 4293 info.setBoundsInScreen(bounds); 4294 4295 if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { 4296 ViewParent parent = getParent(); 4297 if (parent instanceof View) { 4298 View parentView = (View) parent; 4299 info.setParent(parentView); 4300 } 4301 } 4302 4303 info.setPackageName(mContext.getPackageName()); 4304 info.setClassName(View.class.getName()); 4305 info.setContentDescription(getContentDescription()); 4306 4307 info.setEnabled(isEnabled()); 4308 info.setClickable(isClickable()); 4309 info.setFocusable(isFocusable()); 4310 info.setFocused(isFocused()); 4311 info.setSelected(isSelected()); 4312 info.setLongClickable(isLongClickable()); 4313 4314 // TODO: These make sense only if we are in an AdapterView but all 4315 // views can be selected. Maybe from accessiiblity perspective 4316 // we should report as selectable view in an AdapterView. 4317 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 4318 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 4319 4320 if (isFocusable()) { 4321 if (isFocused()) { 4322 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 4323 } else { 4324 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 4325 } 4326 } 4327 } 4328 4329 /** 4330 * Sets a delegate for implementing accessibility support via compositon as 4331 * opposed to inheritance. The delegate's primary use is for implementing 4332 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 4333 * 4334 * @param delegate The delegate instance. 4335 * 4336 * @see AccessibilityDelegate 4337 */ 4338 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 4339 mAccessibilityDelegate = delegate; 4340 } 4341 4342 /** 4343 * Gets the provider for managing a virtual view hierarchy rooted at this View 4344 * and reported to {@link android.accessibilityservice.AccessibilityService}s 4345 * that explore the window content. 4346 * <p> 4347 * If this method returns an instance, this instance is responsible for managing 4348 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 4349 * View including the one representing the View itself. Similarly the returned 4350 * instance is responsible for performing accessibility actions on any virtual 4351 * view or the root view itself. 4352 * </p> 4353 * <p> 4354 * If an {@link AccessibilityDelegate} has been specified via calling 4355 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4356 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 4357 * is responsible for handling this call. 4358 * </p> 4359 * 4360 * @return The provider. 4361 * 4362 * @see AccessibilityNodeProvider 4363 */ 4364 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 4365 if (mAccessibilityDelegate != null) { 4366 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 4367 } else { 4368 return null; 4369 } 4370 } 4371 4372 /** 4373 * Gets the unique identifier of this view on the screen for accessibility purposes. 4374 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 4375 * 4376 * @return The view accessibility id. 4377 * 4378 * @hide 4379 */ 4380 public int getAccessibilityViewId() { 4381 if (mAccessibilityViewId == NO_ID) { 4382 mAccessibilityViewId = sNextAccessibilityViewId++; 4383 } 4384 return mAccessibilityViewId; 4385 } 4386 4387 /** 4388 * Gets the unique identifier of the window in which this View reseides. 4389 * 4390 * @return The window accessibility id. 4391 * 4392 * @hide 4393 */ 4394 public int getAccessibilityWindowId() { 4395 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 4396 } 4397 4398 /** 4399 * Gets the {@link View} description. It briefly describes the view and is 4400 * primarily used for accessibility support. Set this property to enable 4401 * better accessibility support for your application. This is especially 4402 * true for views that do not have textual representation (For example, 4403 * ImageButton). 4404 * 4405 * @return The content descriptiopn. 4406 * 4407 * @attr ref android.R.styleable#View_contentDescription 4408 */ 4409 public CharSequence getContentDescription() { 4410 return mContentDescription; 4411 } 4412 4413 /** 4414 * Sets the {@link View} description. It briefly describes the view and is 4415 * primarily used for accessibility support. Set this property to enable 4416 * better accessibility support for your application. This is especially 4417 * true for views that do not have textual representation (For example, 4418 * ImageButton). 4419 * 4420 * @param contentDescription The content description. 4421 * 4422 * @attr ref android.R.styleable#View_contentDescription 4423 */ 4424 @RemotableViewMethod 4425 public void setContentDescription(CharSequence contentDescription) { 4426 mContentDescription = contentDescription; 4427 } 4428 4429 /** 4430 * Invoked whenever this view loses focus, either by losing window focus or by losing 4431 * focus within its window. This method can be used to clear any state tied to the 4432 * focus. For instance, if a button is held pressed with the trackball and the window 4433 * loses focus, this method can be used to cancel the press. 4434 * 4435 * Subclasses of View overriding this method should always call super.onFocusLost(). 4436 * 4437 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 4438 * @see #onWindowFocusChanged(boolean) 4439 * 4440 * @hide pending API council approval 4441 */ 4442 protected void onFocusLost() { 4443 resetPressedState(); 4444 } 4445 4446 private void resetPressedState() { 4447 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 4448 return; 4449 } 4450 4451 if (isPressed()) { 4452 setPressed(false); 4453 4454 if (!mHasPerformedLongPress) { 4455 removeLongPressCallback(); 4456 } 4457 } 4458 } 4459 4460 /** 4461 * Returns true if this view has focus 4462 * 4463 * @return True if this view has focus, false otherwise. 4464 */ 4465 @ViewDebug.ExportedProperty(category = "focus") 4466 public boolean isFocused() { 4467 return (mPrivateFlags & FOCUSED) != 0; 4468 } 4469 4470 /** 4471 * Find the view in the hierarchy rooted at this view that currently has 4472 * focus. 4473 * 4474 * @return The view that currently has focus, or null if no focused view can 4475 * be found. 4476 */ 4477 public View findFocus() { 4478 return (mPrivateFlags & FOCUSED) != 0 ? this : null; 4479 } 4480 4481 /** 4482 * Change whether this view is one of the set of scrollable containers in 4483 * its window. This will be used to determine whether the window can 4484 * resize or must pan when a soft input area is open -- scrollable 4485 * containers allow the window to use resize mode since the container 4486 * will appropriately shrink. 4487 */ 4488 public void setScrollContainer(boolean isScrollContainer) { 4489 if (isScrollContainer) { 4490 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) { 4491 mAttachInfo.mScrollContainers.add(this); 4492 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 4493 } 4494 mPrivateFlags |= SCROLL_CONTAINER; 4495 } else { 4496 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 4497 mAttachInfo.mScrollContainers.remove(this); 4498 } 4499 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED); 4500 } 4501 } 4502 4503 /** 4504 * Returns the quality of the drawing cache. 4505 * 4506 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4507 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4508 * 4509 * @see #setDrawingCacheQuality(int) 4510 * @see #setDrawingCacheEnabled(boolean) 4511 * @see #isDrawingCacheEnabled() 4512 * 4513 * @attr ref android.R.styleable#View_drawingCacheQuality 4514 */ 4515 public int getDrawingCacheQuality() { 4516 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 4517 } 4518 4519 /** 4520 * Set the drawing cache quality of this view. This value is used only when the 4521 * drawing cache is enabled 4522 * 4523 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4524 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4525 * 4526 * @see #getDrawingCacheQuality() 4527 * @see #setDrawingCacheEnabled(boolean) 4528 * @see #isDrawingCacheEnabled() 4529 * 4530 * @attr ref android.R.styleable#View_drawingCacheQuality 4531 */ 4532 public void setDrawingCacheQuality(int quality) { 4533 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 4534 } 4535 4536 /** 4537 * Returns whether the screen should remain on, corresponding to the current 4538 * value of {@link #KEEP_SCREEN_ON}. 4539 * 4540 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 4541 * 4542 * @see #setKeepScreenOn(boolean) 4543 * 4544 * @attr ref android.R.styleable#View_keepScreenOn 4545 */ 4546 public boolean getKeepScreenOn() { 4547 return (mViewFlags & KEEP_SCREEN_ON) != 0; 4548 } 4549 4550 /** 4551 * Controls whether the screen should remain on, modifying the 4552 * value of {@link #KEEP_SCREEN_ON}. 4553 * 4554 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 4555 * 4556 * @see #getKeepScreenOn() 4557 * 4558 * @attr ref android.R.styleable#View_keepScreenOn 4559 */ 4560 public void setKeepScreenOn(boolean keepScreenOn) { 4561 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 4562 } 4563 4564 /** 4565 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4566 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4567 * 4568 * @attr ref android.R.styleable#View_nextFocusLeft 4569 */ 4570 public int getNextFocusLeftId() { 4571 return mNextFocusLeftId; 4572 } 4573 4574 /** 4575 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4576 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 4577 * decide automatically. 4578 * 4579 * @attr ref android.R.styleable#View_nextFocusLeft 4580 */ 4581 public void setNextFocusLeftId(int nextFocusLeftId) { 4582 mNextFocusLeftId = nextFocusLeftId; 4583 } 4584 4585 /** 4586 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4587 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4588 * 4589 * @attr ref android.R.styleable#View_nextFocusRight 4590 */ 4591 public int getNextFocusRightId() { 4592 return mNextFocusRightId; 4593 } 4594 4595 /** 4596 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4597 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 4598 * decide automatically. 4599 * 4600 * @attr ref android.R.styleable#View_nextFocusRight 4601 */ 4602 public void setNextFocusRightId(int nextFocusRightId) { 4603 mNextFocusRightId = nextFocusRightId; 4604 } 4605 4606 /** 4607 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4608 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4609 * 4610 * @attr ref android.R.styleable#View_nextFocusUp 4611 */ 4612 public int getNextFocusUpId() { 4613 return mNextFocusUpId; 4614 } 4615 4616 /** 4617 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4618 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 4619 * decide automatically. 4620 * 4621 * @attr ref android.R.styleable#View_nextFocusUp 4622 */ 4623 public void setNextFocusUpId(int nextFocusUpId) { 4624 mNextFocusUpId = nextFocusUpId; 4625 } 4626 4627 /** 4628 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4629 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4630 * 4631 * @attr ref android.R.styleable#View_nextFocusDown 4632 */ 4633 public int getNextFocusDownId() { 4634 return mNextFocusDownId; 4635 } 4636 4637 /** 4638 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4639 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 4640 * decide automatically. 4641 * 4642 * @attr ref android.R.styleable#View_nextFocusDown 4643 */ 4644 public void setNextFocusDownId(int nextFocusDownId) { 4645 mNextFocusDownId = nextFocusDownId; 4646 } 4647 4648 /** 4649 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4650 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4651 * 4652 * @attr ref android.R.styleable#View_nextFocusForward 4653 */ 4654 public int getNextFocusForwardId() { 4655 return mNextFocusForwardId; 4656 } 4657 4658 /** 4659 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4660 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 4661 * decide automatically. 4662 * 4663 * @attr ref android.R.styleable#View_nextFocusForward 4664 */ 4665 public void setNextFocusForwardId(int nextFocusForwardId) { 4666 mNextFocusForwardId = nextFocusForwardId; 4667 } 4668 4669 /** 4670 * Returns the visibility of this view and all of its ancestors 4671 * 4672 * @return True if this view and all of its ancestors are {@link #VISIBLE} 4673 */ 4674 public boolean isShown() { 4675 View current = this; 4676 //noinspection ConstantConditions 4677 do { 4678 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 4679 return false; 4680 } 4681 ViewParent parent = current.mParent; 4682 if (parent == null) { 4683 return false; // We are not attached to the view root 4684 } 4685 if (!(parent instanceof View)) { 4686 return true; 4687 } 4688 current = (View) parent; 4689 } while (current != null); 4690 4691 return false; 4692 } 4693 4694 /** 4695 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag 4696 * is set 4697 * 4698 * @param insets Insets for system windows 4699 * 4700 * @return True if this view applied the insets, false otherwise 4701 */ 4702 protected boolean fitSystemWindows(Rect insets) { 4703 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 4704 mPaddingLeft = insets.left; 4705 mPaddingTop = insets.top; 4706 mPaddingRight = insets.right; 4707 mPaddingBottom = insets.bottom; 4708 requestLayout(); 4709 return true; 4710 } 4711 return false; 4712 } 4713 4714 /** 4715 * Set whether or not this view should account for system screen decorations 4716 * such as the status bar and inset its content. This allows this view to be 4717 * positioned in absolute screen coordinates and remain visible to the user. 4718 * 4719 * <p>This should only be used by top-level window decor views. 4720 * 4721 * @param fitSystemWindows true to inset content for system screen decorations, false for 4722 * default behavior. 4723 * 4724 * @attr ref android.R.styleable#View_fitsSystemWindows 4725 */ 4726 public void setFitsSystemWindows(boolean fitSystemWindows) { 4727 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 4728 } 4729 4730 /** 4731 * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view 4732 * will account for system screen decorations such as the status bar and inset its 4733 * content. This allows the view to be positioned in absolute screen coordinates 4734 * and remain visible to the user. 4735 * 4736 * @return true if this view will adjust its content bounds for system screen decorations. 4737 * 4738 * @attr ref android.R.styleable#View_fitsSystemWindows 4739 */ 4740 public boolean fitsSystemWindows() { 4741 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 4742 } 4743 4744 /** 4745 * Returns the visibility status for this view. 4746 * 4747 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4748 * @attr ref android.R.styleable#View_visibility 4749 */ 4750 @ViewDebug.ExportedProperty(mapping = { 4751 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 4752 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 4753 @ViewDebug.IntToString(from = GONE, to = "GONE") 4754 }) 4755 public int getVisibility() { 4756 return mViewFlags & VISIBILITY_MASK; 4757 } 4758 4759 /** 4760 * Set the enabled state of this view. 4761 * 4762 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4763 * @attr ref android.R.styleable#View_visibility 4764 */ 4765 @RemotableViewMethod 4766 public void setVisibility(int visibility) { 4767 setFlags(visibility, VISIBILITY_MASK); 4768 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); 4769 } 4770 4771 /** 4772 * Returns the enabled status for this view. The interpretation of the 4773 * enabled state varies by subclass. 4774 * 4775 * @return True if this view is enabled, false otherwise. 4776 */ 4777 @ViewDebug.ExportedProperty 4778 public boolean isEnabled() { 4779 return (mViewFlags & ENABLED_MASK) == ENABLED; 4780 } 4781 4782 /** 4783 * Set the enabled state of this view. The interpretation of the enabled 4784 * state varies by subclass. 4785 * 4786 * @param enabled True if this view is enabled, false otherwise. 4787 */ 4788 @RemotableViewMethod 4789 public void setEnabled(boolean enabled) { 4790 if (enabled == isEnabled()) return; 4791 4792 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 4793 4794 /* 4795 * The View most likely has to change its appearance, so refresh 4796 * the drawable state. 4797 */ 4798 refreshDrawableState(); 4799 4800 // Invalidate too, since the default behavior for views is to be 4801 // be drawn at 50% alpha rather than to change the drawable. 4802 invalidate(true); 4803 } 4804 4805 /** 4806 * Set whether this view can receive the focus. 4807 * 4808 * Setting this to false will also ensure that this view is not focusable 4809 * in touch mode. 4810 * 4811 * @param focusable If true, this view can receive the focus. 4812 * 4813 * @see #setFocusableInTouchMode(boolean) 4814 * @attr ref android.R.styleable#View_focusable 4815 */ 4816 public void setFocusable(boolean focusable) { 4817 if (!focusable) { 4818 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 4819 } 4820 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 4821 } 4822 4823 /** 4824 * Set whether this view can receive focus while in touch mode. 4825 * 4826 * Setting this to true will also ensure that this view is focusable. 4827 * 4828 * @param focusableInTouchMode If true, this view can receive the focus while 4829 * in touch mode. 4830 * 4831 * @see #setFocusable(boolean) 4832 * @attr ref android.R.styleable#View_focusableInTouchMode 4833 */ 4834 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 4835 // Focusable in touch mode should always be set before the focusable flag 4836 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 4837 // which, in touch mode, will not successfully request focus on this view 4838 // because the focusable in touch mode flag is not set 4839 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 4840 if (focusableInTouchMode) { 4841 setFlags(FOCUSABLE, FOCUSABLE_MASK); 4842 } 4843 } 4844 4845 /** 4846 * Set whether this view should have sound effects enabled for events such as 4847 * clicking and touching. 4848 * 4849 * <p>You may wish to disable sound effects for a view if you already play sounds, 4850 * for instance, a dial key that plays dtmf tones. 4851 * 4852 * @param soundEffectsEnabled whether sound effects are enabled for this view. 4853 * @see #isSoundEffectsEnabled() 4854 * @see #playSoundEffect(int) 4855 * @attr ref android.R.styleable#View_soundEffectsEnabled 4856 */ 4857 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 4858 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 4859 } 4860 4861 /** 4862 * @return whether this view should have sound effects enabled for events such as 4863 * clicking and touching. 4864 * 4865 * @see #setSoundEffectsEnabled(boolean) 4866 * @see #playSoundEffect(int) 4867 * @attr ref android.R.styleable#View_soundEffectsEnabled 4868 */ 4869 @ViewDebug.ExportedProperty 4870 public boolean isSoundEffectsEnabled() { 4871 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 4872 } 4873 4874 /** 4875 * Set whether this view should have haptic feedback for events such as 4876 * long presses. 4877 * 4878 * <p>You may wish to disable haptic feedback if your view already controls 4879 * its own haptic feedback. 4880 * 4881 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 4882 * @see #isHapticFeedbackEnabled() 4883 * @see #performHapticFeedback(int) 4884 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4885 */ 4886 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 4887 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 4888 } 4889 4890 /** 4891 * @return whether this view should have haptic feedback enabled for events 4892 * long presses. 4893 * 4894 * @see #setHapticFeedbackEnabled(boolean) 4895 * @see #performHapticFeedback(int) 4896 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4897 */ 4898 @ViewDebug.ExportedProperty 4899 public boolean isHapticFeedbackEnabled() { 4900 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 4901 } 4902 4903 /** 4904 * Returns the layout direction for this view. 4905 * 4906 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 4907 * {@link #LAYOUT_DIRECTION_RTL}, 4908 * {@link #LAYOUT_DIRECTION_INHERIT} or 4909 * {@link #LAYOUT_DIRECTION_LOCALE}. 4910 * @attr ref android.R.styleable#View_layoutDirection 4911 */ 4912 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4913 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 4914 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 4915 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 4916 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 4917 }) 4918 public int getLayoutDirection() { 4919 return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT; 4920 } 4921 4922 /** 4923 * Set the layout direction for this view. This will propagate a reset of layout direction 4924 * resolution to the view's children and resolve layout direction for this view. 4925 * 4926 * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR}, 4927 * {@link #LAYOUT_DIRECTION_RTL}, 4928 * {@link #LAYOUT_DIRECTION_INHERIT} or 4929 * {@link #LAYOUT_DIRECTION_LOCALE}. 4930 * 4931 * @attr ref android.R.styleable#View_layoutDirection 4932 */ 4933 @RemotableViewMethod 4934 public void setLayoutDirection(int layoutDirection) { 4935 if (getLayoutDirection() != layoutDirection) { 4936 // Reset the current layout direction and the resolved one 4937 mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK; 4938 resetResolvedLayoutDirection(); 4939 // Set the new layout direction (filtered) and ask for a layout pass 4940 mPrivateFlags2 |= 4941 ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK); 4942 requestLayout(); 4943 } 4944 } 4945 4946 /** 4947 * Returns the resolved layout direction for this view. 4948 * 4949 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 4950 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 4951 */ 4952 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4953 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 4954 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 4955 }) 4956 public int getResolvedLayoutDirection() { 4957 // The layout diretion will be resolved only if needed 4958 if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) { 4959 resolveLayoutDirection(); 4960 } 4961 return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ? 4962 LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 4963 } 4964 4965 /** 4966 * Indicates whether or not this view's layout is right-to-left. This is resolved from 4967 * layout attribute and/or the inherited value from the parent 4968 * 4969 * @return true if the layout is right-to-left. 4970 */ 4971 @ViewDebug.ExportedProperty(category = "layout") 4972 public boolean isLayoutRtl() { 4973 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 4974 } 4975 4976 /** 4977 * Indicates whether the view is currently tracking transient state that the 4978 * app should not need to concern itself with saving and restoring, but that 4979 * the framework should take special note to preserve when possible. 4980 * 4981 * @return true if the view has transient state 4982 */ 4983 @ViewDebug.ExportedProperty(category = "layout") 4984 public boolean hasTransientState() { 4985 return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE; 4986 } 4987 4988 /** 4989 * Set whether this view is currently tracking transient state that the 4990 * framework should attempt to preserve when possible. 4991 * 4992 * @param hasTransientState true if this view has transient state 4993 */ 4994 public void setHasTransientState(boolean hasTransientState) { 4995 if (hasTransientState() == hasTransientState) return; 4996 4997 mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) | 4998 (hasTransientState ? HAS_TRANSIENT_STATE : 0); 4999 if (mParent != null) { 5000 try { 5001 mParent.childHasTransientStateChanged(this, hasTransientState); 5002 } catch (AbstractMethodError e) { 5003 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 5004 " does not fully implement ViewParent", e); 5005 } 5006 } 5007 } 5008 5009 /** 5010 * If this view doesn't do any drawing on its own, set this flag to 5011 * allow further optimizations. By default, this flag is not set on 5012 * View, but could be set on some View subclasses such as ViewGroup. 5013 * 5014 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 5015 * you should clear this flag. 5016 * 5017 * @param willNotDraw whether or not this View draw on its own 5018 */ 5019 public void setWillNotDraw(boolean willNotDraw) { 5020 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 5021 } 5022 5023 /** 5024 * Returns whether or not this View draws on its own. 5025 * 5026 * @return true if this view has nothing to draw, false otherwise 5027 */ 5028 @ViewDebug.ExportedProperty(category = "drawing") 5029 public boolean willNotDraw() { 5030 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 5031 } 5032 5033 /** 5034 * When a View's drawing cache is enabled, drawing is redirected to an 5035 * offscreen bitmap. Some views, like an ImageView, must be able to 5036 * bypass this mechanism if they already draw a single bitmap, to avoid 5037 * unnecessary usage of the memory. 5038 * 5039 * @param willNotCacheDrawing true if this view does not cache its 5040 * drawing, false otherwise 5041 */ 5042 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 5043 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 5044 } 5045 5046 /** 5047 * Returns whether or not this View can cache its drawing or not. 5048 * 5049 * @return true if this view does not cache its drawing, false otherwise 5050 */ 5051 @ViewDebug.ExportedProperty(category = "drawing") 5052 public boolean willNotCacheDrawing() { 5053 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 5054 } 5055 5056 /** 5057 * Indicates whether this view reacts to click events or not. 5058 * 5059 * @return true if the view is clickable, false otherwise 5060 * 5061 * @see #setClickable(boolean) 5062 * @attr ref android.R.styleable#View_clickable 5063 */ 5064 @ViewDebug.ExportedProperty 5065 public boolean isClickable() { 5066 return (mViewFlags & CLICKABLE) == CLICKABLE; 5067 } 5068 5069 /** 5070 * Enables or disables click events for this view. When a view 5071 * is clickable it will change its state to "pressed" on every click. 5072 * Subclasses should set the view clickable to visually react to 5073 * user's clicks. 5074 * 5075 * @param clickable true to make the view clickable, false otherwise 5076 * 5077 * @see #isClickable() 5078 * @attr ref android.R.styleable#View_clickable 5079 */ 5080 public void setClickable(boolean clickable) { 5081 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 5082 } 5083 5084 /** 5085 * Indicates whether this view reacts to long click events or not. 5086 * 5087 * @return true if the view is long clickable, false otherwise 5088 * 5089 * @see #setLongClickable(boolean) 5090 * @attr ref android.R.styleable#View_longClickable 5091 */ 5092 public boolean isLongClickable() { 5093 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 5094 } 5095 5096 /** 5097 * Enables or disables long click events for this view. When a view is long 5098 * clickable it reacts to the user holding down the button for a longer 5099 * duration than a tap. This event can either launch the listener or a 5100 * context menu. 5101 * 5102 * @param longClickable true to make the view long clickable, false otherwise 5103 * @see #isLongClickable() 5104 * @attr ref android.R.styleable#View_longClickable 5105 */ 5106 public void setLongClickable(boolean longClickable) { 5107 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 5108 } 5109 5110 /** 5111 * Sets the pressed state for this view. 5112 * 5113 * @see #isClickable() 5114 * @see #setClickable(boolean) 5115 * 5116 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 5117 * the View's internal state from a previously set "pressed" state. 5118 */ 5119 public void setPressed(boolean pressed) { 5120 final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED); 5121 5122 if (pressed) { 5123 mPrivateFlags |= PRESSED; 5124 } else { 5125 mPrivateFlags &= ~PRESSED; 5126 } 5127 5128 if (needsRefresh) { 5129 refreshDrawableState(); 5130 } 5131 dispatchSetPressed(pressed); 5132 } 5133 5134 /** 5135 * Dispatch setPressed to all of this View's children. 5136 * 5137 * @see #setPressed(boolean) 5138 * 5139 * @param pressed The new pressed state 5140 */ 5141 protected void dispatchSetPressed(boolean pressed) { 5142 } 5143 5144 /** 5145 * Indicates whether the view is currently in pressed state. Unless 5146 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 5147 * the pressed state. 5148 * 5149 * @see #setPressed(boolean) 5150 * @see #isClickable() 5151 * @see #setClickable(boolean) 5152 * 5153 * @return true if the view is currently pressed, false otherwise 5154 */ 5155 public boolean isPressed() { 5156 return (mPrivateFlags & PRESSED) == PRESSED; 5157 } 5158 5159 /** 5160 * Indicates whether this view will save its state (that is, 5161 * whether its {@link #onSaveInstanceState} method will be called). 5162 * 5163 * @return Returns true if the view state saving is enabled, else false. 5164 * 5165 * @see #setSaveEnabled(boolean) 5166 * @attr ref android.R.styleable#View_saveEnabled 5167 */ 5168 public boolean isSaveEnabled() { 5169 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 5170 } 5171 5172 /** 5173 * Controls whether the saving of this view's state is 5174 * enabled (that is, whether its {@link #onSaveInstanceState} method 5175 * will be called). Note that even if freezing is enabled, the 5176 * view still must have an id assigned to it (via {@link #setId(int)}) 5177 * for its state to be saved. This flag can only disable the 5178 * saving of this view; any child views may still have their state saved. 5179 * 5180 * @param enabled Set to false to <em>disable</em> state saving, or true 5181 * (the default) to allow it. 5182 * 5183 * @see #isSaveEnabled() 5184 * @see #setId(int) 5185 * @see #onSaveInstanceState() 5186 * @attr ref android.R.styleable#View_saveEnabled 5187 */ 5188 public void setSaveEnabled(boolean enabled) { 5189 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 5190 } 5191 5192 /** 5193 * Gets whether the framework should discard touches when the view's 5194 * window is obscured by another visible window. 5195 * Refer to the {@link View} security documentation for more details. 5196 * 5197 * @return True if touch filtering is enabled. 5198 * 5199 * @see #setFilterTouchesWhenObscured(boolean) 5200 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 5201 */ 5202 @ViewDebug.ExportedProperty 5203 public boolean getFilterTouchesWhenObscured() { 5204 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 5205 } 5206 5207 /** 5208 * Sets whether the framework should discard touches when the view's 5209 * window is obscured by another visible window. 5210 * Refer to the {@link View} security documentation for more details. 5211 * 5212 * @param enabled True if touch filtering should be enabled. 5213 * 5214 * @see #getFilterTouchesWhenObscured 5215 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 5216 */ 5217 public void setFilterTouchesWhenObscured(boolean enabled) { 5218 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 5219 FILTER_TOUCHES_WHEN_OBSCURED); 5220 } 5221 5222 /** 5223 * Indicates whether the entire hierarchy under this view will save its 5224 * state when a state saving traversal occurs from its parent. The default 5225 * is true; if false, these views will not be saved unless 5226 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 5227 * 5228 * @return Returns true if the view state saving from parent is enabled, else false. 5229 * 5230 * @see #setSaveFromParentEnabled(boolean) 5231 */ 5232 public boolean isSaveFromParentEnabled() { 5233 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 5234 } 5235 5236 /** 5237 * Controls whether the entire hierarchy under this view will save its 5238 * state when a state saving traversal occurs from its parent. The default 5239 * is true; if false, these views will not be saved unless 5240 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 5241 * 5242 * @param enabled Set to false to <em>disable</em> state saving, or true 5243 * (the default) to allow it. 5244 * 5245 * @see #isSaveFromParentEnabled() 5246 * @see #setId(int) 5247 * @see #onSaveInstanceState() 5248 */ 5249 public void setSaveFromParentEnabled(boolean enabled) { 5250 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 5251 } 5252 5253 5254 /** 5255 * Returns whether this View is able to take focus. 5256 * 5257 * @return True if this view can take focus, or false otherwise. 5258 * @attr ref android.R.styleable#View_focusable 5259 */ 5260 @ViewDebug.ExportedProperty(category = "focus") 5261 public final boolean isFocusable() { 5262 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 5263 } 5264 5265 /** 5266 * When a view is focusable, it may not want to take focus when in touch mode. 5267 * For example, a button would like focus when the user is navigating via a D-pad 5268 * so that the user can click on it, but once the user starts touching the screen, 5269 * the button shouldn't take focus 5270 * @return Whether the view is focusable in touch mode. 5271 * @attr ref android.R.styleable#View_focusableInTouchMode 5272 */ 5273 @ViewDebug.ExportedProperty 5274 public final boolean isFocusableInTouchMode() { 5275 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 5276 } 5277 5278 /** 5279 * Find the nearest view in the specified direction that can take focus. 5280 * This does not actually give focus to that view. 5281 * 5282 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5283 * 5284 * @return The nearest focusable in the specified direction, or null if none 5285 * can be found. 5286 */ 5287 public View focusSearch(int direction) { 5288 if (mParent != null) { 5289 return mParent.focusSearch(this, direction); 5290 } else { 5291 return null; 5292 } 5293 } 5294 5295 /** 5296 * This method is the last chance for the focused view and its ancestors to 5297 * respond to an arrow key. This is called when the focused view did not 5298 * consume the key internally, nor could the view system find a new view in 5299 * the requested direction to give focus to. 5300 * 5301 * @param focused The currently focused view. 5302 * @param direction The direction focus wants to move. One of FOCUS_UP, 5303 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 5304 * @return True if the this view consumed this unhandled move. 5305 */ 5306 public boolean dispatchUnhandledMove(View focused, int direction) { 5307 return false; 5308 } 5309 5310 /** 5311 * If a user manually specified the next view id for a particular direction, 5312 * use the root to look up the view. 5313 * @param root The root view of the hierarchy containing this view. 5314 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 5315 * or FOCUS_BACKWARD. 5316 * @return The user specified next view, or null if there is none. 5317 */ 5318 View findUserSetNextFocus(View root, int direction) { 5319 switch (direction) { 5320 case FOCUS_LEFT: 5321 if (mNextFocusLeftId == View.NO_ID) return null; 5322 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 5323 case FOCUS_RIGHT: 5324 if (mNextFocusRightId == View.NO_ID) return null; 5325 return findViewInsideOutShouldExist(root, mNextFocusRightId); 5326 case FOCUS_UP: 5327 if (mNextFocusUpId == View.NO_ID) return null; 5328 return findViewInsideOutShouldExist(root, mNextFocusUpId); 5329 case FOCUS_DOWN: 5330 if (mNextFocusDownId == View.NO_ID) return null; 5331 return findViewInsideOutShouldExist(root, mNextFocusDownId); 5332 case FOCUS_FORWARD: 5333 if (mNextFocusForwardId == View.NO_ID) return null; 5334 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 5335 case FOCUS_BACKWARD: { 5336 if (mID == View.NO_ID) return null; 5337 final int id = mID; 5338 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5339 @Override 5340 public boolean apply(View t) { 5341 return t.mNextFocusForwardId == id; 5342 } 5343 }); 5344 } 5345 } 5346 return null; 5347 } 5348 5349 private View findViewInsideOutShouldExist(View root, final int childViewId) { 5350 View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5351 @Override 5352 public boolean apply(View t) { 5353 return t.mID == childViewId; 5354 } 5355 }); 5356 5357 if (result == null) { 5358 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified " 5359 + "by user for id " + childViewId); 5360 } 5361 return result; 5362 } 5363 5364 /** 5365 * Find and return all focusable views that are descendants of this view, 5366 * possibly including this view if it is focusable itself. 5367 * 5368 * @param direction The direction of the focus 5369 * @return A list of focusable views 5370 */ 5371 public ArrayList<View> getFocusables(int direction) { 5372 ArrayList<View> result = new ArrayList<View>(24); 5373 addFocusables(result, direction); 5374 return result; 5375 } 5376 5377 /** 5378 * Add any focusable views that are descendants of this view (possibly 5379 * including this view if it is focusable itself) to views. If we are in touch mode, 5380 * only add views that are also focusable in touch mode. 5381 * 5382 * @param views Focusable views found so far 5383 * @param direction The direction of the focus 5384 */ 5385 public void addFocusables(ArrayList<View> views, int direction) { 5386 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 5387 } 5388 5389 /** 5390 * Adds any focusable views that are descendants of this view (possibly 5391 * including this view if it is focusable itself) to views. This method 5392 * adds all focusable views regardless if we are in touch mode or 5393 * only views focusable in touch mode if we are in touch mode depending on 5394 * the focusable mode paramater. 5395 * 5396 * @param views Focusable views found so far or null if all we are interested is 5397 * the number of focusables. 5398 * @param direction The direction of the focus. 5399 * @param focusableMode The type of focusables to be added. 5400 * 5401 * @see #FOCUSABLES_ALL 5402 * @see #FOCUSABLES_TOUCH_MODE 5403 */ 5404 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 5405 if (!isFocusable()) { 5406 return; 5407 } 5408 5409 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 5410 isInTouchMode() && !isFocusableInTouchMode()) { 5411 return; 5412 } 5413 5414 if (views != null) { 5415 views.add(this); 5416 } 5417 } 5418 5419 /** 5420 * Finds the Views that contain given text. The containment is case insensitive. 5421 * The search is performed by either the text that the View renders or the content 5422 * description that describes the view for accessibility purposes and the view does 5423 * not render or both. Clients can specify how the search is to be performed via 5424 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 5425 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 5426 * 5427 * @param outViews The output list of matching Views. 5428 * @param searched The text to match against. 5429 * 5430 * @see #FIND_VIEWS_WITH_TEXT 5431 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 5432 * @see #setContentDescription(CharSequence) 5433 */ 5434 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 5435 if (getAccessibilityNodeProvider() != null) { 5436 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 5437 outViews.add(this); 5438 } 5439 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 5440 && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) { 5441 String searchedLowerCase = searched.toString().toLowerCase(); 5442 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 5443 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 5444 outViews.add(this); 5445 } 5446 } 5447 } 5448 5449 /** 5450 * Find and return all touchable views that are descendants of this view, 5451 * possibly including this view if it is touchable itself. 5452 * 5453 * @return A list of touchable views 5454 */ 5455 public ArrayList<View> getTouchables() { 5456 ArrayList<View> result = new ArrayList<View>(); 5457 addTouchables(result); 5458 return result; 5459 } 5460 5461 /** 5462 * Add any touchable views that are descendants of this view (possibly 5463 * including this view if it is touchable itself) to views. 5464 * 5465 * @param views Touchable views found so far 5466 */ 5467 public void addTouchables(ArrayList<View> views) { 5468 final int viewFlags = mViewFlags; 5469 5470 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 5471 && (viewFlags & ENABLED_MASK) == ENABLED) { 5472 views.add(this); 5473 } 5474 } 5475 5476 /** 5477 * Call this to try to give focus to a specific view or to one of its 5478 * descendants. 5479 * 5480 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5481 * false), or if it is focusable and it is not focusable in touch mode 5482 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5483 * 5484 * See also {@link #focusSearch(int)}, which is what you call to say that you 5485 * have focus, and you want your parent to look for the next one. 5486 * 5487 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 5488 * {@link #FOCUS_DOWN} and <code>null</code>. 5489 * 5490 * @return Whether this view or one of its descendants actually took focus. 5491 */ 5492 public final boolean requestFocus() { 5493 return requestFocus(View.FOCUS_DOWN); 5494 } 5495 5496 5497 /** 5498 * Call this to try to give focus to a specific view or to one of its 5499 * descendants and give it a hint about what direction focus is heading. 5500 * 5501 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5502 * false), or if it is focusable and it is not focusable in touch mode 5503 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5504 * 5505 * See also {@link #focusSearch(int)}, which is what you call to say that you 5506 * have focus, and you want your parent to look for the next one. 5507 * 5508 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 5509 * <code>null</code> set for the previously focused rectangle. 5510 * 5511 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5512 * @return Whether this view or one of its descendants actually took focus. 5513 */ 5514 public final boolean requestFocus(int direction) { 5515 return requestFocus(direction, null); 5516 } 5517 5518 /** 5519 * Call this to try to give focus to a specific view or to one of its descendants 5520 * and give it hints about the direction and a specific rectangle that the focus 5521 * is coming from. The rectangle can help give larger views a finer grained hint 5522 * about where focus is coming from, and therefore, where to show selection, or 5523 * forward focus change internally. 5524 * 5525 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5526 * false), or if it is focusable and it is not focusable in touch mode 5527 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5528 * 5529 * A View will not take focus if it is not visible. 5530 * 5531 * A View will not take focus if one of its parents has 5532 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 5533 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 5534 * 5535 * See also {@link #focusSearch(int)}, which is what you call to say that you 5536 * have focus, and you want your parent to look for the next one. 5537 * 5538 * You may wish to override this method if your custom {@link View} has an internal 5539 * {@link View} that it wishes to forward the request to. 5540 * 5541 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5542 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 5543 * to give a finer grained hint about where focus is coming from. May be null 5544 * if there is no hint. 5545 * @return Whether this view or one of its descendants actually took focus. 5546 */ 5547 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 5548 // need to be focusable 5549 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 5550 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5551 return false; 5552 } 5553 5554 // need to be focusable in touch mode if in touch mode 5555 if (isInTouchMode() && 5556 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 5557 return false; 5558 } 5559 5560 // need to not have any parents blocking us 5561 if (hasAncestorThatBlocksDescendantFocus()) { 5562 return false; 5563 } 5564 5565 handleFocusGainInternal(direction, previouslyFocusedRect); 5566 return true; 5567 } 5568 5569 /** 5570 * Call this to try to give focus to a specific view or to one of its descendants. This is a 5571 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 5572 * touch mode to request focus when they are touched. 5573 * 5574 * @return Whether this view or one of its descendants actually took focus. 5575 * 5576 * @see #isInTouchMode() 5577 * 5578 */ 5579 public final boolean requestFocusFromTouch() { 5580 // Leave touch mode if we need to 5581 if (isInTouchMode()) { 5582 ViewRootImpl viewRoot = getViewRootImpl(); 5583 if (viewRoot != null) { 5584 viewRoot.ensureTouchMode(false); 5585 } 5586 } 5587 return requestFocus(View.FOCUS_DOWN); 5588 } 5589 5590 /** 5591 * @return Whether any ancestor of this view blocks descendant focus. 5592 */ 5593 private boolean hasAncestorThatBlocksDescendantFocus() { 5594 ViewParent ancestor = mParent; 5595 while (ancestor instanceof ViewGroup) { 5596 final ViewGroup vgAncestor = (ViewGroup) ancestor; 5597 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 5598 return true; 5599 } else { 5600 ancestor = vgAncestor.getParent(); 5601 } 5602 } 5603 return false; 5604 } 5605 5606 /** 5607 * @hide 5608 */ 5609 public void dispatchStartTemporaryDetach() { 5610 onStartTemporaryDetach(); 5611 } 5612 5613 /** 5614 * This is called when a container is going to temporarily detach a child, with 5615 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 5616 * It will either be followed by {@link #onFinishTemporaryDetach()} or 5617 * {@link #onDetachedFromWindow()} when the container is done. 5618 */ 5619 public void onStartTemporaryDetach() { 5620 removeUnsetPressCallback(); 5621 mPrivateFlags |= CANCEL_NEXT_UP_EVENT; 5622 } 5623 5624 /** 5625 * @hide 5626 */ 5627 public void dispatchFinishTemporaryDetach() { 5628 onFinishTemporaryDetach(); 5629 } 5630 5631 /** 5632 * Called after {@link #onStartTemporaryDetach} when the container is done 5633 * changing the view. 5634 */ 5635 public void onFinishTemporaryDetach() { 5636 } 5637 5638 /** 5639 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 5640 * for this view's window. Returns null if the view is not currently attached 5641 * to the window. Normally you will not need to use this directly, but 5642 * just use the standard high-level event callbacks like 5643 * {@link #onKeyDown(int, KeyEvent)}. 5644 */ 5645 public KeyEvent.DispatcherState getKeyDispatcherState() { 5646 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 5647 } 5648 5649 /** 5650 * Dispatch a key event before it is processed by any input method 5651 * associated with the view hierarchy. This can be used to intercept 5652 * key events in special situations before the IME consumes them; a 5653 * typical example would be handling the BACK key to update the application's 5654 * UI instead of allowing the IME to see it and close itself. 5655 * 5656 * @param event The key event to be dispatched. 5657 * @return True if the event was handled, false otherwise. 5658 */ 5659 public boolean dispatchKeyEventPreIme(KeyEvent event) { 5660 return onKeyPreIme(event.getKeyCode(), event); 5661 } 5662 5663 /** 5664 * Dispatch a key event to the next view on the focus path. This path runs 5665 * from the top of the view tree down to the currently focused view. If this 5666 * view has focus, it will dispatch to itself. Otherwise it will dispatch 5667 * the next node down the focus path. This method also fires any key 5668 * listeners. 5669 * 5670 * @param event The key event to be dispatched. 5671 * @return True if the event was handled, false otherwise. 5672 */ 5673 public boolean dispatchKeyEvent(KeyEvent event) { 5674 if (mInputEventConsistencyVerifier != null) { 5675 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 5676 } 5677 5678 // Give any attached key listener a first crack at the event. 5679 //noinspection SimplifiableIfStatement 5680 ListenerInfo li = mListenerInfo; 5681 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5682 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 5683 return true; 5684 } 5685 5686 if (event.dispatch(this, mAttachInfo != null 5687 ? mAttachInfo.mKeyDispatchState : null, this)) { 5688 return true; 5689 } 5690 5691 if (mInputEventConsistencyVerifier != null) { 5692 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5693 } 5694 return false; 5695 } 5696 5697 /** 5698 * Dispatches a key shortcut event. 5699 * 5700 * @param event The key event to be dispatched. 5701 * @return True if the event was handled by the view, false otherwise. 5702 */ 5703 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 5704 return onKeyShortcut(event.getKeyCode(), event); 5705 } 5706 5707 /** 5708 * Pass the touch screen motion event down to the target view, or this 5709 * view if it is the target. 5710 * 5711 * @param event The motion event to be dispatched. 5712 * @return True if the event was handled by the view, false otherwise. 5713 */ 5714 public boolean dispatchTouchEvent(MotionEvent event) { 5715 if (mInputEventConsistencyVerifier != null) { 5716 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 5717 } 5718 5719 if (onFilterTouchEventForSecurity(event)) { 5720 //noinspection SimplifiableIfStatement 5721 ListenerInfo li = mListenerInfo; 5722 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5723 && li.mOnTouchListener.onTouch(this, event)) { 5724 return true; 5725 } 5726 5727 if (onTouchEvent(event)) { 5728 return true; 5729 } 5730 } 5731 5732 if (mInputEventConsistencyVerifier != null) { 5733 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5734 } 5735 return false; 5736 } 5737 5738 /** 5739 * Filter the touch event to apply security policies. 5740 * 5741 * @param event The motion event to be filtered. 5742 * @return True if the event should be dispatched, false if the event should be dropped. 5743 * 5744 * @see #getFilterTouchesWhenObscured 5745 */ 5746 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 5747 //noinspection RedundantIfStatement 5748 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 5749 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 5750 // Window is obscured, drop this touch. 5751 return false; 5752 } 5753 return true; 5754 } 5755 5756 /** 5757 * Pass a trackball motion event down to the focused view. 5758 * 5759 * @param event The motion event to be dispatched. 5760 * @return True if the event was handled by the view, false otherwise. 5761 */ 5762 public boolean dispatchTrackballEvent(MotionEvent event) { 5763 if (mInputEventConsistencyVerifier != null) { 5764 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 5765 } 5766 5767 return onTrackballEvent(event); 5768 } 5769 5770 /** 5771 * Dispatch a generic motion event. 5772 * <p> 5773 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5774 * are delivered to the view under the pointer. All other generic motion events are 5775 * delivered to the focused view. Hover events are handled specially and are delivered 5776 * to {@link #onHoverEvent(MotionEvent)}. 5777 * </p> 5778 * 5779 * @param event The motion event to be dispatched. 5780 * @return True if the event was handled by the view, false otherwise. 5781 */ 5782 public boolean dispatchGenericMotionEvent(MotionEvent event) { 5783 if (mInputEventConsistencyVerifier != null) { 5784 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 5785 } 5786 5787 final int source = event.getSource(); 5788 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5789 final int action = event.getAction(); 5790 if (action == MotionEvent.ACTION_HOVER_ENTER 5791 || action == MotionEvent.ACTION_HOVER_MOVE 5792 || action == MotionEvent.ACTION_HOVER_EXIT) { 5793 if (dispatchHoverEvent(event)) { 5794 return true; 5795 } 5796 } else if (dispatchGenericPointerEvent(event)) { 5797 return true; 5798 } 5799 } else if (dispatchGenericFocusedEvent(event)) { 5800 return true; 5801 } 5802 5803 if (dispatchGenericMotionEventInternal(event)) { 5804 return true; 5805 } 5806 5807 if (mInputEventConsistencyVerifier != null) { 5808 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5809 } 5810 return false; 5811 } 5812 5813 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 5814 //noinspection SimplifiableIfStatement 5815 ListenerInfo li = mListenerInfo; 5816 if (li != null && li.mOnGenericMotionListener != null 5817 && (mViewFlags & ENABLED_MASK) == ENABLED 5818 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 5819 return true; 5820 } 5821 5822 if (onGenericMotionEvent(event)) { 5823 return true; 5824 } 5825 5826 if (mInputEventConsistencyVerifier != null) { 5827 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5828 } 5829 return false; 5830 } 5831 5832 /** 5833 * Dispatch a hover event. 5834 * <p> 5835 * Do not call this method directly. 5836 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5837 * </p> 5838 * 5839 * @param event The motion event to be dispatched. 5840 * @return True if the event was handled by the view, false otherwise. 5841 */ 5842 protected boolean dispatchHoverEvent(MotionEvent event) { 5843 //noinspection SimplifiableIfStatement 5844 ListenerInfo li = mListenerInfo; 5845 if (li != null && li.mOnHoverListener != null 5846 && (mViewFlags & ENABLED_MASK) == ENABLED 5847 && li.mOnHoverListener.onHover(this, event)) { 5848 return true; 5849 } 5850 5851 return onHoverEvent(event); 5852 } 5853 5854 /** 5855 * Returns true if the view has a child to which it has recently sent 5856 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 5857 * it does not have a hovered child, then it must be the innermost hovered view. 5858 * @hide 5859 */ 5860 protected boolean hasHoveredChild() { 5861 return false; 5862 } 5863 5864 /** 5865 * Dispatch a generic motion event to the view under the first pointer. 5866 * <p> 5867 * Do not call this method directly. 5868 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5869 * </p> 5870 * 5871 * @param event The motion event to be dispatched. 5872 * @return True if the event was handled by the view, false otherwise. 5873 */ 5874 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 5875 return false; 5876 } 5877 5878 /** 5879 * Dispatch a generic motion event to the currently focused view. 5880 * <p> 5881 * Do not call this method directly. 5882 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5883 * </p> 5884 * 5885 * @param event The motion event to be dispatched. 5886 * @return True if the event was handled by the view, false otherwise. 5887 */ 5888 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 5889 return false; 5890 } 5891 5892 /** 5893 * Dispatch a pointer event. 5894 * <p> 5895 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 5896 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 5897 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 5898 * and should not be expected to handle other pointing device features. 5899 * </p> 5900 * 5901 * @param event The motion event to be dispatched. 5902 * @return True if the event was handled by the view, false otherwise. 5903 * @hide 5904 */ 5905 public final boolean dispatchPointerEvent(MotionEvent event) { 5906 if (event.isTouchEvent()) { 5907 return dispatchTouchEvent(event); 5908 } else { 5909 return dispatchGenericMotionEvent(event); 5910 } 5911 } 5912 5913 /** 5914 * Called when the window containing this view gains or loses window focus. 5915 * ViewGroups should override to route to their children. 5916 * 5917 * @param hasFocus True if the window containing this view now has focus, 5918 * false otherwise. 5919 */ 5920 public void dispatchWindowFocusChanged(boolean hasFocus) { 5921 onWindowFocusChanged(hasFocus); 5922 } 5923 5924 /** 5925 * Called when the window containing this view gains or loses focus. Note 5926 * that this is separate from view focus: to receive key events, both 5927 * your view and its window must have focus. If a window is displayed 5928 * on top of yours that takes input focus, then your own window will lose 5929 * focus but the view focus will remain unchanged. 5930 * 5931 * @param hasWindowFocus True if the window containing this view now has 5932 * focus, false otherwise. 5933 */ 5934 public void onWindowFocusChanged(boolean hasWindowFocus) { 5935 InputMethodManager imm = InputMethodManager.peekInstance(); 5936 if (!hasWindowFocus) { 5937 if (isPressed()) { 5938 setPressed(false); 5939 } 5940 if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5941 imm.focusOut(this); 5942 } 5943 removeLongPressCallback(); 5944 removeTapCallback(); 5945 onFocusLost(); 5946 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5947 imm.focusIn(this); 5948 } 5949 refreshDrawableState(); 5950 } 5951 5952 /** 5953 * Returns true if this view is in a window that currently has window focus. 5954 * Note that this is not the same as the view itself having focus. 5955 * 5956 * @return True if this view is in a window that currently has window focus. 5957 */ 5958 public boolean hasWindowFocus() { 5959 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 5960 } 5961 5962 /** 5963 * Dispatch a view visibility change down the view hierarchy. 5964 * ViewGroups should override to route to their children. 5965 * @param changedView The view whose visibility changed. Could be 'this' or 5966 * an ancestor view. 5967 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5968 * {@link #INVISIBLE} or {@link #GONE}. 5969 */ 5970 protected void dispatchVisibilityChanged(View changedView, int visibility) { 5971 onVisibilityChanged(changedView, visibility); 5972 } 5973 5974 /** 5975 * Called when the visibility of the view or an ancestor of the view is changed. 5976 * @param changedView The view whose visibility changed. Could be 'this' or 5977 * an ancestor view. 5978 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5979 * {@link #INVISIBLE} or {@link #GONE}. 5980 */ 5981 protected void onVisibilityChanged(View changedView, int visibility) { 5982 if (visibility == VISIBLE) { 5983 if (mAttachInfo != null) { 5984 initialAwakenScrollBars(); 5985 } else { 5986 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH; 5987 } 5988 } 5989 } 5990 5991 /** 5992 * Dispatch a hint about whether this view is displayed. For instance, when 5993 * a View moves out of the screen, it might receives a display hint indicating 5994 * the view is not displayed. Applications should not <em>rely</em> on this hint 5995 * as there is no guarantee that they will receive one. 5996 * 5997 * @param hint A hint about whether or not this view is displayed: 5998 * {@link #VISIBLE} or {@link #INVISIBLE}. 5999 */ 6000 public void dispatchDisplayHint(int hint) { 6001 onDisplayHint(hint); 6002 } 6003 6004 /** 6005 * Gives this view a hint about whether is displayed or not. For instance, when 6006 * a View moves out of the screen, it might receives a display hint indicating 6007 * the view is not displayed. Applications should not <em>rely</em> on this hint 6008 * as there is no guarantee that they will receive one. 6009 * 6010 * @param hint A hint about whether or not this view is displayed: 6011 * {@link #VISIBLE} or {@link #INVISIBLE}. 6012 */ 6013 protected void onDisplayHint(int hint) { 6014 } 6015 6016 /** 6017 * Dispatch a window visibility change down the view hierarchy. 6018 * ViewGroups should override to route to their children. 6019 * 6020 * @param visibility The new visibility of the window. 6021 * 6022 * @see #onWindowVisibilityChanged(int) 6023 */ 6024 public void dispatchWindowVisibilityChanged(int visibility) { 6025 onWindowVisibilityChanged(visibility); 6026 } 6027 6028 /** 6029 * Called when the window containing has change its visibility 6030 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 6031 * that this tells you whether or not your window is being made visible 6032 * to the window manager; this does <em>not</em> tell you whether or not 6033 * your window is obscured by other windows on the screen, even if it 6034 * is itself visible. 6035 * 6036 * @param visibility The new visibility of the window. 6037 */ 6038 protected void onWindowVisibilityChanged(int visibility) { 6039 if (visibility == VISIBLE) { 6040 initialAwakenScrollBars(); 6041 } 6042 } 6043 6044 /** 6045 * Returns the current visibility of the window this view is attached to 6046 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 6047 * 6048 * @return Returns the current visibility of the view's window. 6049 */ 6050 public int getWindowVisibility() { 6051 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 6052 } 6053 6054 /** 6055 * Retrieve the overall visible display size in which the window this view is 6056 * attached to has been positioned in. This takes into account screen 6057 * decorations above the window, for both cases where the window itself 6058 * is being position inside of them or the window is being placed under 6059 * then and covered insets are used for the window to position its content 6060 * inside. In effect, this tells you the available area where content can 6061 * be placed and remain visible to users. 6062 * 6063 * <p>This function requires an IPC back to the window manager to retrieve 6064 * the requested information, so should not be used in performance critical 6065 * code like drawing. 6066 * 6067 * @param outRect Filled in with the visible display frame. If the view 6068 * is not attached to a window, this is simply the raw display size. 6069 */ 6070 public void getWindowVisibleDisplayFrame(Rect outRect) { 6071 if (mAttachInfo != null) { 6072 try { 6073 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 6074 } catch (RemoteException e) { 6075 return; 6076 } 6077 // XXX This is really broken, and probably all needs to be done 6078 // in the window manager, and we need to know more about whether 6079 // we want the area behind or in front of the IME. 6080 final Rect insets = mAttachInfo.mVisibleInsets; 6081 outRect.left += insets.left; 6082 outRect.top += insets.top; 6083 outRect.right -= insets.right; 6084 outRect.bottom -= insets.bottom; 6085 return; 6086 } 6087 Display d = WindowManagerImpl.getDefault().getDefaultDisplay(); 6088 d.getRectSize(outRect); 6089 } 6090 6091 /** 6092 * Dispatch a notification about a resource configuration change down 6093 * the view hierarchy. 6094 * ViewGroups should override to route to their children. 6095 * 6096 * @param newConfig The new resource configuration. 6097 * 6098 * @see #onConfigurationChanged(android.content.res.Configuration) 6099 */ 6100 public void dispatchConfigurationChanged(Configuration newConfig) { 6101 onConfigurationChanged(newConfig); 6102 } 6103 6104 /** 6105 * Called when the current configuration of the resources being used 6106 * by the application have changed. You can use this to decide when 6107 * to reload resources that can changed based on orientation and other 6108 * configuration characterstics. You only need to use this if you are 6109 * not relying on the normal {@link android.app.Activity} mechanism of 6110 * recreating the activity instance upon a configuration change. 6111 * 6112 * @param newConfig The new resource configuration. 6113 */ 6114 protected void onConfigurationChanged(Configuration newConfig) { 6115 } 6116 6117 /** 6118 * Private function to aggregate all per-view attributes in to the view 6119 * root. 6120 */ 6121 void dispatchCollectViewAttributes(int visibility) { 6122 performCollectViewAttributes(visibility); 6123 } 6124 6125 void performCollectViewAttributes(int visibility) { 6126 if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) { 6127 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 6128 mAttachInfo.mKeepScreenOn = true; 6129 } 6130 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility; 6131 ListenerInfo li = mListenerInfo; 6132 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 6133 mAttachInfo.mHasSystemUiListeners = true; 6134 } 6135 } 6136 } 6137 6138 void needGlobalAttributesUpdate(boolean force) { 6139 final AttachInfo ai = mAttachInfo; 6140 if (ai != null) { 6141 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 6142 || ai.mHasSystemUiListeners) { 6143 ai.mRecomputeGlobalAttributes = true; 6144 } 6145 } 6146 } 6147 6148 /** 6149 * Returns whether the device is currently in touch mode. Touch mode is entered 6150 * once the user begins interacting with the device by touch, and affects various 6151 * things like whether focus is always visible to the user. 6152 * 6153 * @return Whether the device is in touch mode. 6154 */ 6155 @ViewDebug.ExportedProperty 6156 public boolean isInTouchMode() { 6157 if (mAttachInfo != null) { 6158 return mAttachInfo.mInTouchMode; 6159 } else { 6160 return ViewRootImpl.isInTouchMode(); 6161 } 6162 } 6163 6164 /** 6165 * Returns the context the view is running in, through which it can 6166 * access the current theme, resources, etc. 6167 * 6168 * @return The view's Context. 6169 */ 6170 @ViewDebug.CapturedViewProperty 6171 public final Context getContext() { 6172 return mContext; 6173 } 6174 6175 /** 6176 * Handle a key event before it is processed by any input method 6177 * associated with the view hierarchy. This can be used to intercept 6178 * key events in special situations before the IME consumes them; a 6179 * typical example would be handling the BACK key to update the application's 6180 * UI instead of allowing the IME to see it and close itself. 6181 * 6182 * @param keyCode The value in event.getKeyCode(). 6183 * @param event Description of the key event. 6184 * @return If you handled the event, return true. If you want to allow the 6185 * event to be handled by the next receiver, return false. 6186 */ 6187 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 6188 return false; 6189 } 6190 6191 /** 6192 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 6193 * KeyEvent.Callback.onKeyDown()}: perform press of the view 6194 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 6195 * is released, if the view is enabled and clickable. 6196 * 6197 * @param keyCode A key code that represents the button pressed, from 6198 * {@link android.view.KeyEvent}. 6199 * @param event The KeyEvent object that defines the button action. 6200 */ 6201 public boolean onKeyDown(int keyCode, KeyEvent event) { 6202 boolean result = false; 6203 6204 switch (keyCode) { 6205 case KeyEvent.KEYCODE_DPAD_CENTER: 6206 case KeyEvent.KEYCODE_ENTER: { 6207 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6208 return true; 6209 } 6210 // Long clickable items don't necessarily have to be clickable 6211 if (((mViewFlags & CLICKABLE) == CLICKABLE || 6212 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 6213 (event.getRepeatCount() == 0)) { 6214 setPressed(true); 6215 checkForLongClick(0); 6216 return true; 6217 } 6218 break; 6219 } 6220 } 6221 return result; 6222 } 6223 6224 /** 6225 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 6226 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 6227 * the event). 6228 */ 6229 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 6230 return false; 6231 } 6232 6233 /** 6234 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 6235 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 6236 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 6237 * {@link KeyEvent#KEYCODE_ENTER} is released. 6238 * 6239 * @param keyCode A key code that represents the button pressed, from 6240 * {@link android.view.KeyEvent}. 6241 * @param event The KeyEvent object that defines the button action. 6242 */ 6243 public boolean onKeyUp(int keyCode, KeyEvent event) { 6244 boolean result = false; 6245 6246 switch (keyCode) { 6247 case KeyEvent.KEYCODE_DPAD_CENTER: 6248 case KeyEvent.KEYCODE_ENTER: { 6249 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6250 return true; 6251 } 6252 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 6253 setPressed(false); 6254 6255 if (!mHasPerformedLongPress) { 6256 // This is a tap, so remove the longpress check 6257 removeLongPressCallback(); 6258 6259 result = performClick(); 6260 } 6261 } 6262 break; 6263 } 6264 } 6265 return result; 6266 } 6267 6268 /** 6269 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 6270 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 6271 * the event). 6272 * 6273 * @param keyCode A key code that represents the button pressed, from 6274 * {@link android.view.KeyEvent}. 6275 * @param repeatCount The number of times the action was made. 6276 * @param event The KeyEvent object that defines the button action. 6277 */ 6278 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 6279 return false; 6280 } 6281 6282 /** 6283 * Called on the focused view when a key shortcut event is not handled. 6284 * Override this method to implement local key shortcuts for the View. 6285 * Key shortcuts can also be implemented by setting the 6286 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 6287 * 6288 * @param keyCode The value in event.getKeyCode(). 6289 * @param event Description of the key event. 6290 * @return If you handled the event, return true. If you want to allow the 6291 * event to be handled by the next receiver, return false. 6292 */ 6293 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 6294 return false; 6295 } 6296 6297 /** 6298 * Check whether the called view is a text editor, in which case it 6299 * would make sense to automatically display a soft input window for 6300 * it. Subclasses should override this if they implement 6301 * {@link #onCreateInputConnection(EditorInfo)} to return true if 6302 * a call on that method would return a non-null InputConnection, and 6303 * they are really a first-class editor that the user would normally 6304 * start typing on when the go into a window containing your view. 6305 * 6306 * <p>The default implementation always returns false. This does 6307 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 6308 * will not be called or the user can not otherwise perform edits on your 6309 * view; it is just a hint to the system that this is not the primary 6310 * purpose of this view. 6311 * 6312 * @return Returns true if this view is a text editor, else false. 6313 */ 6314 public boolean onCheckIsTextEditor() { 6315 return false; 6316 } 6317 6318 /** 6319 * Create a new InputConnection for an InputMethod to interact 6320 * with the view. The default implementation returns null, since it doesn't 6321 * support input methods. You can override this to implement such support. 6322 * This is only needed for views that take focus and text input. 6323 * 6324 * <p>When implementing this, you probably also want to implement 6325 * {@link #onCheckIsTextEditor()} to indicate you will return a 6326 * non-null InputConnection. 6327 * 6328 * @param outAttrs Fill in with attribute information about the connection. 6329 */ 6330 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 6331 return null; 6332 } 6333 6334 /** 6335 * Called by the {@link android.view.inputmethod.InputMethodManager} 6336 * when a view who is not the current 6337 * input connection target is trying to make a call on the manager. The 6338 * default implementation returns false; you can override this to return 6339 * true for certain views if you are performing InputConnection proxying 6340 * to them. 6341 * @param view The View that is making the InputMethodManager call. 6342 * @return Return true to allow the call, false to reject. 6343 */ 6344 public boolean checkInputConnectionProxy(View view) { 6345 return false; 6346 } 6347 6348 /** 6349 * Show the context menu for this view. It is not safe to hold on to the 6350 * menu after returning from this method. 6351 * 6352 * You should normally not overload this method. Overload 6353 * {@link #onCreateContextMenu(ContextMenu)} or define an 6354 * {@link OnCreateContextMenuListener} to add items to the context menu. 6355 * 6356 * @param menu The context menu to populate 6357 */ 6358 public void createContextMenu(ContextMenu menu) { 6359 ContextMenuInfo menuInfo = getContextMenuInfo(); 6360 6361 // Sets the current menu info so all items added to menu will have 6362 // my extra info set. 6363 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 6364 6365 onCreateContextMenu(menu); 6366 ListenerInfo li = mListenerInfo; 6367 if (li != null && li.mOnCreateContextMenuListener != null) { 6368 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 6369 } 6370 6371 // Clear the extra information so subsequent items that aren't mine don't 6372 // have my extra info. 6373 ((MenuBuilder)menu).setCurrentMenuInfo(null); 6374 6375 if (mParent != null) { 6376 mParent.createContextMenu(menu); 6377 } 6378 } 6379 6380 /** 6381 * Views should implement this if they have extra information to associate 6382 * with the context menu. The return result is supplied as a parameter to 6383 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 6384 * callback. 6385 * 6386 * @return Extra information about the item for which the context menu 6387 * should be shown. This information will vary across different 6388 * subclasses of View. 6389 */ 6390 protected ContextMenuInfo getContextMenuInfo() { 6391 return null; 6392 } 6393 6394 /** 6395 * Views should implement this if the view itself is going to add items to 6396 * the context menu. 6397 * 6398 * @param menu the context menu to populate 6399 */ 6400 protected void onCreateContextMenu(ContextMenu menu) { 6401 } 6402 6403 /** 6404 * Implement this method to handle trackball motion events. The 6405 * <em>relative</em> movement of the trackball since the last event 6406 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 6407 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 6408 * that a movement of 1 corresponds to the user pressing one DPAD key (so 6409 * they will often be fractional values, representing the more fine-grained 6410 * movement information available from a trackball). 6411 * 6412 * @param event The motion event. 6413 * @return True if the event was handled, false otherwise. 6414 */ 6415 public boolean onTrackballEvent(MotionEvent event) { 6416 return false; 6417 } 6418 6419 /** 6420 * Implement this method to handle generic motion events. 6421 * <p> 6422 * Generic motion events describe joystick movements, mouse hovers, track pad 6423 * touches, scroll wheel movements and other input events. The 6424 * {@link MotionEvent#getSource() source} of the motion event specifies 6425 * the class of input that was received. Implementations of this method 6426 * must examine the bits in the source before processing the event. 6427 * The following code example shows how this is done. 6428 * </p><p> 6429 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 6430 * are delivered to the view under the pointer. All other generic motion events are 6431 * delivered to the focused view. 6432 * </p> 6433 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 6434 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 6435 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 6436 * // process the joystick movement... 6437 * return true; 6438 * } 6439 * } 6440 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 6441 * switch (event.getAction()) { 6442 * case MotionEvent.ACTION_HOVER_MOVE: 6443 * // process the mouse hover movement... 6444 * return true; 6445 * case MotionEvent.ACTION_SCROLL: 6446 * // process the scroll wheel movement... 6447 * return true; 6448 * } 6449 * } 6450 * return super.onGenericMotionEvent(event); 6451 * }</pre> 6452 * 6453 * @param event The generic motion event being processed. 6454 * @return True if the event was handled, false otherwise. 6455 */ 6456 public boolean onGenericMotionEvent(MotionEvent event) { 6457 return false; 6458 } 6459 6460 /** 6461 * Implement this method to handle hover events. 6462 * <p> 6463 * This method is called whenever a pointer is hovering into, over, or out of the 6464 * bounds of a view and the view is not currently being touched. 6465 * Hover events are represented as pointer events with action 6466 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 6467 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 6468 * </p> 6469 * <ul> 6470 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 6471 * when the pointer enters the bounds of the view.</li> 6472 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 6473 * when the pointer has already entered the bounds of the view and has moved.</li> 6474 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 6475 * when the pointer has exited the bounds of the view or when the pointer is 6476 * about to go down due to a button click, tap, or similar user action that 6477 * causes the view to be touched.</li> 6478 * </ul> 6479 * <p> 6480 * The view should implement this method to return true to indicate that it is 6481 * handling the hover event, such as by changing its drawable state. 6482 * </p><p> 6483 * The default implementation calls {@link #setHovered} to update the hovered state 6484 * of the view when a hover enter or hover exit event is received, if the view 6485 * is enabled and is clickable. The default implementation also sends hover 6486 * accessibility events. 6487 * </p> 6488 * 6489 * @param event The motion event that describes the hover. 6490 * @return True if the view handled the hover event. 6491 * 6492 * @see #isHovered 6493 * @see #setHovered 6494 * @see #onHoverChanged 6495 */ 6496 public boolean onHoverEvent(MotionEvent event) { 6497 // The root view may receive hover (or touch) events that are outside the bounds of 6498 // the window. This code ensures that we only send accessibility events for 6499 // hovers that are actually within the bounds of the root view. 6500 final int action = event.getAction(); 6501 if (!mSendingHoverAccessibilityEvents) { 6502 if ((action == MotionEvent.ACTION_HOVER_ENTER 6503 || action == MotionEvent.ACTION_HOVER_MOVE) 6504 && !hasHoveredChild() 6505 && pointInView(event.getX(), event.getY())) { 6506 mSendingHoverAccessibilityEvents = true; 6507 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 6508 } 6509 } else { 6510 if (action == MotionEvent.ACTION_HOVER_EXIT 6511 || (action == MotionEvent.ACTION_HOVER_MOVE 6512 && !pointInView(event.getX(), event.getY()))) { 6513 mSendingHoverAccessibilityEvents = false; 6514 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 6515 } 6516 } 6517 6518 if (isHoverable()) { 6519 switch (action) { 6520 case MotionEvent.ACTION_HOVER_ENTER: 6521 setHovered(true); 6522 break; 6523 case MotionEvent.ACTION_HOVER_EXIT: 6524 setHovered(false); 6525 break; 6526 } 6527 6528 // Dispatch the event to onGenericMotionEvent before returning true. 6529 // This is to provide compatibility with existing applications that 6530 // handled HOVER_MOVE events in onGenericMotionEvent and that would 6531 // break because of the new default handling for hoverable views 6532 // in onHoverEvent. 6533 // Note that onGenericMotionEvent will be called by default when 6534 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 6535 dispatchGenericMotionEventInternal(event); 6536 return true; 6537 } 6538 return false; 6539 } 6540 6541 /** 6542 * Returns true if the view should handle {@link #onHoverEvent} 6543 * by calling {@link #setHovered} to change its hovered state. 6544 * 6545 * @return True if the view is hoverable. 6546 */ 6547 private boolean isHoverable() { 6548 final int viewFlags = mViewFlags; 6549 //noinspection SimplifiableIfStatement 6550 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6551 return false; 6552 } 6553 6554 return (viewFlags & CLICKABLE) == CLICKABLE 6555 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6556 } 6557 6558 /** 6559 * Returns true if the view is currently hovered. 6560 * 6561 * @return True if the view is currently hovered. 6562 * 6563 * @see #setHovered 6564 * @see #onHoverChanged 6565 */ 6566 @ViewDebug.ExportedProperty 6567 public boolean isHovered() { 6568 return (mPrivateFlags & HOVERED) != 0; 6569 } 6570 6571 /** 6572 * Sets whether the view is currently hovered. 6573 * <p> 6574 * Calling this method also changes the drawable state of the view. This 6575 * enables the view to react to hover by using different drawable resources 6576 * to change its appearance. 6577 * </p><p> 6578 * The {@link #onHoverChanged} method is called when the hovered state changes. 6579 * </p> 6580 * 6581 * @param hovered True if the view is hovered. 6582 * 6583 * @see #isHovered 6584 * @see #onHoverChanged 6585 */ 6586 public void setHovered(boolean hovered) { 6587 if (hovered) { 6588 if ((mPrivateFlags & HOVERED) == 0) { 6589 mPrivateFlags |= HOVERED; 6590 refreshDrawableState(); 6591 onHoverChanged(true); 6592 } 6593 } else { 6594 if ((mPrivateFlags & HOVERED) != 0) { 6595 mPrivateFlags &= ~HOVERED; 6596 refreshDrawableState(); 6597 onHoverChanged(false); 6598 } 6599 } 6600 } 6601 6602 /** 6603 * Implement this method to handle hover state changes. 6604 * <p> 6605 * This method is called whenever the hover state changes as a result of a 6606 * call to {@link #setHovered}. 6607 * </p> 6608 * 6609 * @param hovered The current hover state, as returned by {@link #isHovered}. 6610 * 6611 * @see #isHovered 6612 * @see #setHovered 6613 */ 6614 public void onHoverChanged(boolean hovered) { 6615 } 6616 6617 /** 6618 * Implement this method to handle touch screen motion events. 6619 * 6620 * @param event The motion event. 6621 * @return True if the event was handled, false otherwise. 6622 */ 6623 public boolean onTouchEvent(MotionEvent event) { 6624 final int viewFlags = mViewFlags; 6625 6626 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6627 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) { 6628 setPressed(false); 6629 } 6630 // A disabled view that is clickable still consumes the touch 6631 // events, it just doesn't respond to them. 6632 return (((viewFlags & CLICKABLE) == CLICKABLE || 6633 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 6634 } 6635 6636 if (mTouchDelegate != null) { 6637 if (mTouchDelegate.onTouchEvent(event)) { 6638 return true; 6639 } 6640 } 6641 6642 if (((viewFlags & CLICKABLE) == CLICKABLE || 6643 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 6644 switch (event.getAction()) { 6645 case MotionEvent.ACTION_UP: 6646 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; 6647 if ((mPrivateFlags & PRESSED) != 0 || prepressed) { 6648 // take focus if we don't have it already and we should in 6649 // touch mode. 6650 boolean focusTaken = false; 6651 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 6652 focusTaken = requestFocus(); 6653 } 6654 6655 if (prepressed) { 6656 // The button is being released before we actually 6657 // showed it as pressed. Make it show the pressed 6658 // state now (before scheduling the click) to ensure 6659 // the user sees it. 6660 setPressed(true); 6661 } 6662 6663 if (!mHasPerformedLongPress) { 6664 // This is a tap, so remove the longpress check 6665 removeLongPressCallback(); 6666 6667 // Only perform take click actions if we were in the pressed state 6668 if (!focusTaken) { 6669 // Use a Runnable and post this rather than calling 6670 // performClick directly. This lets other visual state 6671 // of the view update before click actions start. 6672 if (mPerformClick == null) { 6673 mPerformClick = new PerformClick(); 6674 } 6675 if (!post(mPerformClick)) { 6676 performClick(); 6677 } 6678 } 6679 } 6680 6681 if (mUnsetPressedState == null) { 6682 mUnsetPressedState = new UnsetPressedState(); 6683 } 6684 6685 if (prepressed) { 6686 postDelayed(mUnsetPressedState, 6687 ViewConfiguration.getPressedStateDuration()); 6688 } else if (!post(mUnsetPressedState)) { 6689 // If the post failed, unpress right now 6690 mUnsetPressedState.run(); 6691 } 6692 removeTapCallback(); 6693 } 6694 break; 6695 6696 case MotionEvent.ACTION_DOWN: 6697 mHasPerformedLongPress = false; 6698 6699 if (performButtonActionOnTouchDown(event)) { 6700 break; 6701 } 6702 6703 // Walk up the hierarchy to determine if we're inside a scrolling container. 6704 boolean isInScrollingContainer = isInScrollingContainer(); 6705 6706 // For views inside a scrolling container, delay the pressed feedback for 6707 // a short period in case this is a scroll. 6708 if (isInScrollingContainer) { 6709 mPrivateFlags |= PREPRESSED; 6710 if (mPendingCheckForTap == null) { 6711 mPendingCheckForTap = new CheckForTap(); 6712 } 6713 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 6714 } else { 6715 // Not inside a scrolling container, so show the feedback right away 6716 setPressed(true); 6717 checkForLongClick(0); 6718 } 6719 break; 6720 6721 case MotionEvent.ACTION_CANCEL: 6722 setPressed(false); 6723 removeTapCallback(); 6724 break; 6725 6726 case MotionEvent.ACTION_MOVE: 6727 final int x = (int) event.getX(); 6728 final int y = (int) event.getY(); 6729 6730 // Be lenient about moving outside of buttons 6731 if (!pointInView(x, y, mTouchSlop)) { 6732 // Outside button 6733 removeTapCallback(); 6734 if ((mPrivateFlags & PRESSED) != 0) { 6735 // Remove any future long press/tap checks 6736 removeLongPressCallback(); 6737 6738 setPressed(false); 6739 } 6740 } 6741 break; 6742 } 6743 return true; 6744 } 6745 6746 return false; 6747 } 6748 6749 /** 6750 * @hide 6751 */ 6752 public boolean isInScrollingContainer() { 6753 ViewParent p = getParent(); 6754 while (p != null && p instanceof ViewGroup) { 6755 if (((ViewGroup) p).shouldDelayChildPressedState()) { 6756 return true; 6757 } 6758 p = p.getParent(); 6759 } 6760 return false; 6761 } 6762 6763 /** 6764 * Remove the longpress detection timer. 6765 */ 6766 private void removeLongPressCallback() { 6767 if (mPendingCheckForLongPress != null) { 6768 removeCallbacks(mPendingCheckForLongPress); 6769 } 6770 } 6771 6772 /** 6773 * Remove the pending click action 6774 */ 6775 private void removePerformClickCallback() { 6776 if (mPerformClick != null) { 6777 removeCallbacks(mPerformClick); 6778 } 6779 } 6780 6781 /** 6782 * Remove the prepress detection timer. 6783 */ 6784 private void removeUnsetPressCallback() { 6785 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) { 6786 setPressed(false); 6787 removeCallbacks(mUnsetPressedState); 6788 } 6789 } 6790 6791 /** 6792 * Remove the tap detection timer. 6793 */ 6794 private void removeTapCallback() { 6795 if (mPendingCheckForTap != null) { 6796 mPrivateFlags &= ~PREPRESSED; 6797 removeCallbacks(mPendingCheckForTap); 6798 } 6799 } 6800 6801 /** 6802 * Cancels a pending long press. Your subclass can use this if you 6803 * want the context menu to come up if the user presses and holds 6804 * at the same place, but you don't want it to come up if they press 6805 * and then move around enough to cause scrolling. 6806 */ 6807 public void cancelLongPress() { 6808 removeLongPressCallback(); 6809 6810 /* 6811 * The prepressed state handled by the tap callback is a display 6812 * construct, but the tap callback will post a long press callback 6813 * less its own timeout. Remove it here. 6814 */ 6815 removeTapCallback(); 6816 } 6817 6818 /** 6819 * Remove the pending callback for sending a 6820 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 6821 */ 6822 private void removeSendViewScrolledAccessibilityEventCallback() { 6823 if (mSendViewScrolledAccessibilityEvent != null) { 6824 removeCallbacks(mSendViewScrolledAccessibilityEvent); 6825 } 6826 } 6827 6828 /** 6829 * Sets the TouchDelegate for this View. 6830 */ 6831 public void setTouchDelegate(TouchDelegate delegate) { 6832 mTouchDelegate = delegate; 6833 } 6834 6835 /** 6836 * Gets the TouchDelegate for this View. 6837 */ 6838 public TouchDelegate getTouchDelegate() { 6839 return mTouchDelegate; 6840 } 6841 6842 /** 6843 * Set flags controlling behavior of this view. 6844 * 6845 * @param flags Constant indicating the value which should be set 6846 * @param mask Constant indicating the bit range that should be changed 6847 */ 6848 void setFlags(int flags, int mask) { 6849 int old = mViewFlags; 6850 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 6851 6852 int changed = mViewFlags ^ old; 6853 if (changed == 0) { 6854 return; 6855 } 6856 int privateFlags = mPrivateFlags; 6857 6858 /* Check if the FOCUSABLE bit has changed */ 6859 if (((changed & FOCUSABLE_MASK) != 0) && 6860 ((privateFlags & HAS_BOUNDS) !=0)) { 6861 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 6862 && ((privateFlags & FOCUSED) != 0)) { 6863 /* Give up focus if we are no longer focusable */ 6864 clearFocus(); 6865 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 6866 && ((privateFlags & FOCUSED) == 0)) { 6867 /* 6868 * Tell the view system that we are now available to take focus 6869 * if no one else already has it. 6870 */ 6871 if (mParent != null) mParent.focusableViewAvailable(this); 6872 } 6873 } 6874 6875 if ((flags & VISIBILITY_MASK) == VISIBLE) { 6876 if ((changed & VISIBILITY_MASK) != 0) { 6877 /* 6878 * If this view is becoming visible, invalidate it in case it changed while 6879 * it was not visible. Marking it drawn ensures that the invalidation will 6880 * go through. 6881 */ 6882 mPrivateFlags |= DRAWN; 6883 invalidate(true); 6884 6885 needGlobalAttributesUpdate(true); 6886 6887 // a view becoming visible is worth notifying the parent 6888 // about in case nothing has focus. even if this specific view 6889 // isn't focusable, it may contain something that is, so let 6890 // the root view try to give this focus if nothing else does. 6891 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 6892 mParent.focusableViewAvailable(this); 6893 } 6894 } 6895 } 6896 6897 /* Check if the GONE bit has changed */ 6898 if ((changed & GONE) != 0) { 6899 needGlobalAttributesUpdate(false); 6900 requestLayout(); 6901 6902 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 6903 if (hasFocus()) clearFocus(); 6904 destroyDrawingCache(); 6905 if (mParent instanceof View) { 6906 // GONE views noop invalidation, so invalidate the parent 6907 ((View) mParent).invalidate(true); 6908 } 6909 // Mark the view drawn to ensure that it gets invalidated properly the next 6910 // time it is visible and gets invalidated 6911 mPrivateFlags |= DRAWN; 6912 } 6913 if (mAttachInfo != null) { 6914 mAttachInfo.mViewVisibilityChanged = true; 6915 } 6916 } 6917 6918 /* Check if the VISIBLE bit has changed */ 6919 if ((changed & INVISIBLE) != 0) { 6920 needGlobalAttributesUpdate(false); 6921 /* 6922 * If this view is becoming invisible, set the DRAWN flag so that 6923 * the next invalidate() will not be skipped. 6924 */ 6925 mPrivateFlags |= DRAWN; 6926 6927 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 6928 // root view becoming invisible shouldn't clear focus 6929 if (getRootView() != this) { 6930 clearFocus(); 6931 } 6932 } 6933 if (mAttachInfo != null) { 6934 mAttachInfo.mViewVisibilityChanged = true; 6935 } 6936 } 6937 6938 if ((changed & VISIBILITY_MASK) != 0) { 6939 if (mParent instanceof ViewGroup) { 6940 ((ViewGroup) mParent).onChildVisibilityChanged(this, 6941 (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK)); 6942 ((View) mParent).invalidate(true); 6943 } else if (mParent != null) { 6944 mParent.invalidateChild(this, null); 6945 } 6946 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6947 } 6948 6949 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 6950 destroyDrawingCache(); 6951 } 6952 6953 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 6954 destroyDrawingCache(); 6955 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6956 invalidateParentCaches(); 6957 } 6958 6959 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 6960 destroyDrawingCache(); 6961 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6962 } 6963 6964 if ((changed & DRAW_MASK) != 0) { 6965 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 6966 if (mBGDrawable != null) { 6967 mPrivateFlags &= ~SKIP_DRAW; 6968 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 6969 } else { 6970 mPrivateFlags |= SKIP_DRAW; 6971 } 6972 } else { 6973 mPrivateFlags &= ~SKIP_DRAW; 6974 } 6975 requestLayout(); 6976 invalidate(true); 6977 } 6978 6979 if ((changed & KEEP_SCREEN_ON) != 0) { 6980 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 6981 mParent.recomputeViewAttributes(this); 6982 } 6983 } 6984 } 6985 6986 /** 6987 * Change the view's z order in the tree, so it's on top of other sibling 6988 * views 6989 */ 6990 public void bringToFront() { 6991 if (mParent != null) { 6992 mParent.bringChildToFront(this); 6993 } 6994 } 6995 6996 /** 6997 * This is called in response to an internal scroll in this view (i.e., the 6998 * view scrolled its own contents). This is typically as a result of 6999 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 7000 * called. 7001 * 7002 * @param l Current horizontal scroll origin. 7003 * @param t Current vertical scroll origin. 7004 * @param oldl Previous horizontal scroll origin. 7005 * @param oldt Previous vertical scroll origin. 7006 */ 7007 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 7008 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 7009 postSendViewScrolledAccessibilityEventCallback(); 7010 } 7011 7012 mBackgroundSizeChanged = true; 7013 7014 final AttachInfo ai = mAttachInfo; 7015 if (ai != null) { 7016 ai.mViewScrollChanged = true; 7017 } 7018 } 7019 7020 /** 7021 * Interface definition for a callback to be invoked when the layout bounds of a view 7022 * changes due to layout processing. 7023 */ 7024 public interface OnLayoutChangeListener { 7025 /** 7026 * Called when the focus state of a view has changed. 7027 * 7028 * @param v The view whose state has changed. 7029 * @param left The new value of the view's left property. 7030 * @param top The new value of the view's top property. 7031 * @param right The new value of the view's right property. 7032 * @param bottom The new value of the view's bottom property. 7033 * @param oldLeft The previous value of the view's left property. 7034 * @param oldTop The previous value of the view's top property. 7035 * @param oldRight The previous value of the view's right property. 7036 * @param oldBottom The previous value of the view's bottom property. 7037 */ 7038 void onLayoutChange(View v, int left, int top, int right, int bottom, 7039 int oldLeft, int oldTop, int oldRight, int oldBottom); 7040 } 7041 7042 /** 7043 * This is called during layout when the size of this view has changed. If 7044 * you were just added to the view hierarchy, you're called with the old 7045 * values of 0. 7046 * 7047 * @param w Current width of this view. 7048 * @param h Current height of this view. 7049 * @param oldw Old width of this view. 7050 * @param oldh Old height of this view. 7051 */ 7052 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 7053 } 7054 7055 /** 7056 * Called by draw to draw the child views. This may be overridden 7057 * by derived classes to gain control just before its children are drawn 7058 * (but after its own view has been drawn). 7059 * @param canvas the canvas on which to draw the view 7060 */ 7061 protected void dispatchDraw(Canvas canvas) { 7062 } 7063 7064 /** 7065 * Gets the parent of this view. Note that the parent is a 7066 * ViewParent and not necessarily a View. 7067 * 7068 * @return Parent of this view. 7069 */ 7070 public final ViewParent getParent() { 7071 return mParent; 7072 } 7073 7074 /** 7075 * Set the horizontal scrolled position of your view. This will cause a call to 7076 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7077 * invalidated. 7078 * @param value the x position to scroll to 7079 */ 7080 public void setScrollX(int value) { 7081 scrollTo(value, mScrollY); 7082 } 7083 7084 /** 7085 * Set the vertical scrolled position of your view. This will cause a call to 7086 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7087 * invalidated. 7088 * @param value the y position to scroll to 7089 */ 7090 public void setScrollY(int value) { 7091 scrollTo(mScrollX, value); 7092 } 7093 7094 /** 7095 * Return the scrolled left position of this view. This is the left edge of 7096 * the displayed part of your view. You do not need to draw any pixels 7097 * farther left, since those are outside of the frame of your view on 7098 * screen. 7099 * 7100 * @return The left edge of the displayed part of your view, in pixels. 7101 */ 7102 public final int getScrollX() { 7103 return mScrollX; 7104 } 7105 7106 /** 7107 * Return the scrolled top position of this view. This is the top edge of 7108 * the displayed part of your view. You do not need to draw any pixels above 7109 * it, since those are outside of the frame of your view on screen. 7110 * 7111 * @return The top edge of the displayed part of your view, in pixels. 7112 */ 7113 public final int getScrollY() { 7114 return mScrollY; 7115 } 7116 7117 /** 7118 * Return the width of the your view. 7119 * 7120 * @return The width of your view, in pixels. 7121 */ 7122 @ViewDebug.ExportedProperty(category = "layout") 7123 public final int getWidth() { 7124 return mRight - mLeft; 7125 } 7126 7127 /** 7128 * Return the height of your view. 7129 * 7130 * @return The height of your view, in pixels. 7131 */ 7132 @ViewDebug.ExportedProperty(category = "layout") 7133 public final int getHeight() { 7134 return mBottom - mTop; 7135 } 7136 7137 /** 7138 * Return the visible drawing bounds of your view. Fills in the output 7139 * rectangle with the values from getScrollX(), getScrollY(), 7140 * getWidth(), and getHeight(). 7141 * 7142 * @param outRect The (scrolled) drawing bounds of the view. 7143 */ 7144 public void getDrawingRect(Rect outRect) { 7145 outRect.left = mScrollX; 7146 outRect.top = mScrollY; 7147 outRect.right = mScrollX + (mRight - mLeft); 7148 outRect.bottom = mScrollY + (mBottom - mTop); 7149 } 7150 7151 /** 7152 * Like {@link #getMeasuredWidthAndState()}, but only returns the 7153 * raw width component (that is the result is masked by 7154 * {@link #MEASURED_SIZE_MASK}). 7155 * 7156 * @return The raw measured width of this view. 7157 */ 7158 public final int getMeasuredWidth() { 7159 return mMeasuredWidth & MEASURED_SIZE_MASK; 7160 } 7161 7162 /** 7163 * Return the full width measurement information for this view as computed 7164 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 7165 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 7166 * This should be used during measurement and layout calculations only. Use 7167 * {@link #getWidth()} to see how wide a view is after layout. 7168 * 7169 * @return The measured width of this view as a bit mask. 7170 */ 7171 public final int getMeasuredWidthAndState() { 7172 return mMeasuredWidth; 7173 } 7174 7175 /** 7176 * Like {@link #getMeasuredHeightAndState()}, but only returns the 7177 * raw width component (that is the result is masked by 7178 * {@link #MEASURED_SIZE_MASK}). 7179 * 7180 * @return The raw measured height of this view. 7181 */ 7182 public final int getMeasuredHeight() { 7183 return mMeasuredHeight & MEASURED_SIZE_MASK; 7184 } 7185 7186 /** 7187 * Return the full height measurement information for this view as computed 7188 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 7189 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 7190 * This should be used during measurement and layout calculations only. Use 7191 * {@link #getHeight()} to see how wide a view is after layout. 7192 * 7193 * @return The measured width of this view as a bit mask. 7194 */ 7195 public final int getMeasuredHeightAndState() { 7196 return mMeasuredHeight; 7197 } 7198 7199 /** 7200 * Return only the state bits of {@link #getMeasuredWidthAndState()} 7201 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 7202 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 7203 * and the height component is at the shifted bits 7204 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 7205 */ 7206 public final int getMeasuredState() { 7207 return (mMeasuredWidth&MEASURED_STATE_MASK) 7208 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 7209 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 7210 } 7211 7212 /** 7213 * The transform matrix of this view, which is calculated based on the current 7214 * roation, scale, and pivot properties. 7215 * 7216 * @see #getRotation() 7217 * @see #getScaleX() 7218 * @see #getScaleY() 7219 * @see #getPivotX() 7220 * @see #getPivotY() 7221 * @return The current transform matrix for the view 7222 */ 7223 public Matrix getMatrix() { 7224 if (mTransformationInfo != null) { 7225 updateMatrix(); 7226 return mTransformationInfo.mMatrix; 7227 } 7228 return Matrix.IDENTITY_MATRIX; 7229 } 7230 7231 /** 7232 * Utility function to determine if the value is far enough away from zero to be 7233 * considered non-zero. 7234 * @param value A floating point value to check for zero-ness 7235 * @return whether the passed-in value is far enough away from zero to be considered non-zero 7236 */ 7237 private static boolean nonzero(float value) { 7238 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 7239 } 7240 7241 /** 7242 * Returns true if the transform matrix is the identity matrix. 7243 * Recomputes the matrix if necessary. 7244 * 7245 * @return True if the transform matrix is the identity matrix, false otherwise. 7246 */ 7247 final boolean hasIdentityMatrix() { 7248 if (mTransformationInfo != null) { 7249 updateMatrix(); 7250 return mTransformationInfo.mMatrixIsIdentity; 7251 } 7252 return true; 7253 } 7254 7255 void ensureTransformationInfo() { 7256 if (mTransformationInfo == null) { 7257 mTransformationInfo = new TransformationInfo(); 7258 } 7259 } 7260 7261 /** 7262 * Recomputes the transform matrix if necessary. 7263 */ 7264 private void updateMatrix() { 7265 final TransformationInfo info = mTransformationInfo; 7266 if (info == null) { 7267 return; 7268 } 7269 if (info.mMatrixDirty) { 7270 // transform-related properties have changed since the last time someone 7271 // asked for the matrix; recalculate it with the current values 7272 7273 // Figure out if we need to update the pivot point 7274 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7275 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 7276 info.mPrevWidth = mRight - mLeft; 7277 info.mPrevHeight = mBottom - mTop; 7278 info.mPivotX = info.mPrevWidth / 2f; 7279 info.mPivotY = info.mPrevHeight / 2f; 7280 } 7281 } 7282 info.mMatrix.reset(); 7283 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 7284 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 7285 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 7286 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 7287 } else { 7288 if (info.mCamera == null) { 7289 info.mCamera = new Camera(); 7290 info.matrix3D = new Matrix(); 7291 } 7292 info.mCamera.save(); 7293 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 7294 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 7295 info.mCamera.getMatrix(info.matrix3D); 7296 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 7297 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 7298 info.mPivotY + info.mTranslationY); 7299 info.mMatrix.postConcat(info.matrix3D); 7300 info.mCamera.restore(); 7301 } 7302 info.mMatrixDirty = false; 7303 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 7304 info.mInverseMatrixDirty = true; 7305 } 7306 } 7307 7308 /** 7309 * Utility method to retrieve the inverse of the current mMatrix property. 7310 * We cache the matrix to avoid recalculating it when transform properties 7311 * have not changed. 7312 * 7313 * @return The inverse of the current matrix of this view. 7314 */ 7315 final Matrix getInverseMatrix() { 7316 final TransformationInfo info = mTransformationInfo; 7317 if (info != null) { 7318 updateMatrix(); 7319 if (info.mInverseMatrixDirty) { 7320 if (info.mInverseMatrix == null) { 7321 info.mInverseMatrix = new Matrix(); 7322 } 7323 info.mMatrix.invert(info.mInverseMatrix); 7324 info.mInverseMatrixDirty = false; 7325 } 7326 return info.mInverseMatrix; 7327 } 7328 return Matrix.IDENTITY_MATRIX; 7329 } 7330 7331 /** 7332 * Gets the distance along the Z axis from the camera to this view. 7333 * 7334 * @see #setCameraDistance(float) 7335 * 7336 * @return The distance along the Z axis. 7337 */ 7338 public float getCameraDistance() { 7339 ensureTransformationInfo(); 7340 final float dpi = mResources.getDisplayMetrics().densityDpi; 7341 final TransformationInfo info = mTransformationInfo; 7342 if (info.mCamera == null) { 7343 info.mCamera = new Camera(); 7344 info.matrix3D = new Matrix(); 7345 } 7346 return -(info.mCamera.getLocationZ() * dpi); 7347 } 7348 7349 /** 7350 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 7351 * views are drawn) from the camera to this view. The camera's distance 7352 * affects 3D transformations, for instance rotations around the X and Y 7353 * axis. If the rotationX or rotationY properties are changed and this view is 7354 * large (more than half the size of the screen), it is recommended to always 7355 * use a camera distance that's greater than the height (X axis rotation) or 7356 * the width (Y axis rotation) of this view.</p> 7357 * 7358 * <p>The distance of the camera from the view plane can have an affect on the 7359 * perspective distortion of the view when it is rotated around the x or y axis. 7360 * For example, a large distance will result in a large viewing angle, and there 7361 * will not be much perspective distortion of the view as it rotates. A short 7362 * distance may cause much more perspective distortion upon rotation, and can 7363 * also result in some drawing artifacts if the rotated view ends up partially 7364 * behind the camera (which is why the recommendation is to use a distance at 7365 * least as far as the size of the view, if the view is to be rotated.)</p> 7366 * 7367 * <p>The distance is expressed in "depth pixels." The default distance depends 7368 * on the screen density. For instance, on a medium density display, the 7369 * default distance is 1280. On a high density display, the default distance 7370 * is 1920.</p> 7371 * 7372 * <p>If you want to specify a distance that leads to visually consistent 7373 * results across various densities, use the following formula:</p> 7374 * <pre> 7375 * float scale = context.getResources().getDisplayMetrics().density; 7376 * view.setCameraDistance(distance * scale); 7377 * </pre> 7378 * 7379 * <p>The density scale factor of a high density display is 1.5, 7380 * and 1920 = 1280 * 1.5.</p> 7381 * 7382 * @param distance The distance in "depth pixels", if negative the opposite 7383 * value is used 7384 * 7385 * @see #setRotationX(float) 7386 * @see #setRotationY(float) 7387 */ 7388 public void setCameraDistance(float distance) { 7389 invalidateViewProperty(true, false); 7390 7391 ensureTransformationInfo(); 7392 final float dpi = mResources.getDisplayMetrics().densityDpi; 7393 final TransformationInfo info = mTransformationInfo; 7394 if (info.mCamera == null) { 7395 info.mCamera = new Camera(); 7396 info.matrix3D = new Matrix(); 7397 } 7398 7399 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 7400 info.mMatrixDirty = true; 7401 7402 invalidateViewProperty(false, false); 7403 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7404 mDisplayList.setCameraDistance(-Math.abs(distance) / dpi); 7405 } 7406 } 7407 7408 /** 7409 * The degrees that the view is rotated around the pivot point. 7410 * 7411 * @see #setRotation(float) 7412 * @see #getPivotX() 7413 * @see #getPivotY() 7414 * 7415 * @return The degrees of rotation. 7416 */ 7417 @ViewDebug.ExportedProperty(category = "drawing") 7418 public float getRotation() { 7419 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 7420 } 7421 7422 /** 7423 * Sets the degrees that the view is rotated around the pivot point. Increasing values 7424 * result in clockwise rotation. 7425 * 7426 * @param rotation The degrees of rotation. 7427 * 7428 * @see #getRotation() 7429 * @see #getPivotX() 7430 * @see #getPivotY() 7431 * @see #setRotationX(float) 7432 * @see #setRotationY(float) 7433 * 7434 * @attr ref android.R.styleable#View_rotation 7435 */ 7436 public void setRotation(float rotation) { 7437 ensureTransformationInfo(); 7438 final TransformationInfo info = mTransformationInfo; 7439 if (info.mRotation != rotation) { 7440 // Double-invalidation is necessary to capture view's old and new areas 7441 invalidateViewProperty(true, false); 7442 info.mRotation = rotation; 7443 info.mMatrixDirty = true; 7444 invalidateViewProperty(false, true); 7445 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7446 mDisplayList.setRotation(rotation); 7447 } 7448 } 7449 } 7450 7451 /** 7452 * The degrees that the view is rotated around the vertical axis through the pivot point. 7453 * 7454 * @see #getPivotX() 7455 * @see #getPivotY() 7456 * @see #setRotationY(float) 7457 * 7458 * @return The degrees of Y rotation. 7459 */ 7460 @ViewDebug.ExportedProperty(category = "drawing") 7461 public float getRotationY() { 7462 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 7463 } 7464 7465 /** 7466 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 7467 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 7468 * down the y axis. 7469 * 7470 * When rotating large views, it is recommended to adjust the camera distance 7471 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 7472 * 7473 * @param rotationY The degrees of Y rotation. 7474 * 7475 * @see #getRotationY() 7476 * @see #getPivotX() 7477 * @see #getPivotY() 7478 * @see #setRotation(float) 7479 * @see #setRotationX(float) 7480 * @see #setCameraDistance(float) 7481 * 7482 * @attr ref android.R.styleable#View_rotationY 7483 */ 7484 public void setRotationY(float rotationY) { 7485 ensureTransformationInfo(); 7486 final TransformationInfo info = mTransformationInfo; 7487 if (info.mRotationY != rotationY) { 7488 invalidateViewProperty(true, false); 7489 info.mRotationY = rotationY; 7490 info.mMatrixDirty = true; 7491 invalidateViewProperty(false, true); 7492 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7493 mDisplayList.setRotationY(rotationY); 7494 } 7495 } 7496 } 7497 7498 /** 7499 * The degrees that the view is rotated around the horizontal axis through the pivot point. 7500 * 7501 * @see #getPivotX() 7502 * @see #getPivotY() 7503 * @see #setRotationX(float) 7504 * 7505 * @return The degrees of X rotation. 7506 */ 7507 @ViewDebug.ExportedProperty(category = "drawing") 7508 public float getRotationX() { 7509 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 7510 } 7511 7512 /** 7513 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 7514 * Increasing values result in clockwise rotation from the viewpoint of looking down the 7515 * x axis. 7516 * 7517 * When rotating large views, it is recommended to adjust the camera distance 7518 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 7519 * 7520 * @param rotationX The degrees of X rotation. 7521 * 7522 * @see #getRotationX() 7523 * @see #getPivotX() 7524 * @see #getPivotY() 7525 * @see #setRotation(float) 7526 * @see #setRotationY(float) 7527 * @see #setCameraDistance(float) 7528 * 7529 * @attr ref android.R.styleable#View_rotationX 7530 */ 7531 public void setRotationX(float rotationX) { 7532 ensureTransformationInfo(); 7533 final TransformationInfo info = mTransformationInfo; 7534 if (info.mRotationX != rotationX) { 7535 invalidateViewProperty(true, false); 7536 info.mRotationX = rotationX; 7537 info.mMatrixDirty = true; 7538 invalidateViewProperty(false, true); 7539 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7540 mDisplayList.setRotationX(rotationX); 7541 } 7542 } 7543 } 7544 7545 /** 7546 * The amount that the view is scaled in x around the pivot point, as a proportion of 7547 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 7548 * 7549 * <p>By default, this is 1.0f. 7550 * 7551 * @see #getPivotX() 7552 * @see #getPivotY() 7553 * @return The scaling factor. 7554 */ 7555 @ViewDebug.ExportedProperty(category = "drawing") 7556 public float getScaleX() { 7557 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 7558 } 7559 7560 /** 7561 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 7562 * the view's unscaled width. A value of 1 means that no scaling is applied. 7563 * 7564 * @param scaleX The scaling factor. 7565 * @see #getPivotX() 7566 * @see #getPivotY() 7567 * 7568 * @attr ref android.R.styleable#View_scaleX 7569 */ 7570 public void setScaleX(float scaleX) { 7571 ensureTransformationInfo(); 7572 final TransformationInfo info = mTransformationInfo; 7573 if (info.mScaleX != scaleX) { 7574 invalidateViewProperty(true, false); 7575 info.mScaleX = scaleX; 7576 info.mMatrixDirty = true; 7577 invalidateViewProperty(false, true); 7578 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7579 mDisplayList.setScaleX(scaleX); 7580 } 7581 } 7582 } 7583 7584 /** 7585 * The amount that the view is scaled in y around the pivot point, as a proportion of 7586 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 7587 * 7588 * <p>By default, this is 1.0f. 7589 * 7590 * @see #getPivotX() 7591 * @see #getPivotY() 7592 * @return The scaling factor. 7593 */ 7594 @ViewDebug.ExportedProperty(category = "drawing") 7595 public float getScaleY() { 7596 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 7597 } 7598 7599 /** 7600 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 7601 * the view's unscaled width. A value of 1 means that no scaling is applied. 7602 * 7603 * @param scaleY The scaling factor. 7604 * @see #getPivotX() 7605 * @see #getPivotY() 7606 * 7607 * @attr ref android.R.styleable#View_scaleY 7608 */ 7609 public void setScaleY(float scaleY) { 7610 ensureTransformationInfo(); 7611 final TransformationInfo info = mTransformationInfo; 7612 if (info.mScaleY != scaleY) { 7613 invalidateViewProperty(true, false); 7614 info.mScaleY = scaleY; 7615 info.mMatrixDirty = true; 7616 invalidateViewProperty(false, true); 7617 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7618 mDisplayList.setScaleY(scaleY); 7619 } 7620 } 7621 } 7622 7623 /** 7624 * The x location of the point around which the view is {@link #setRotation(float) rotated} 7625 * and {@link #setScaleX(float) scaled}. 7626 * 7627 * @see #getRotation() 7628 * @see #getScaleX() 7629 * @see #getScaleY() 7630 * @see #getPivotY() 7631 * @return The x location of the pivot point. 7632 */ 7633 @ViewDebug.ExportedProperty(category = "drawing") 7634 public float getPivotX() { 7635 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 7636 } 7637 7638 /** 7639 * Sets the x location of the point around which the view is 7640 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 7641 * By default, the pivot point is centered on the object. 7642 * Setting this property disables this behavior and causes the view to use only the 7643 * explicitly set pivotX and pivotY values. 7644 * 7645 * @param pivotX The x location of the pivot point. 7646 * @see #getRotation() 7647 * @see #getScaleX() 7648 * @see #getScaleY() 7649 * @see #getPivotY() 7650 * 7651 * @attr ref android.R.styleable#View_transformPivotX 7652 */ 7653 public void setPivotX(float pivotX) { 7654 ensureTransformationInfo(); 7655 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7656 final TransformationInfo info = mTransformationInfo; 7657 if (info.mPivotX != pivotX) { 7658 invalidateViewProperty(true, false); 7659 info.mPivotX = pivotX; 7660 info.mMatrixDirty = true; 7661 invalidateViewProperty(false, true); 7662 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7663 mDisplayList.setPivotX(pivotX); 7664 } 7665 } 7666 } 7667 7668 /** 7669 * The y location of the point around which the view is {@link #setRotation(float) rotated} 7670 * and {@link #setScaleY(float) scaled}. 7671 * 7672 * @see #getRotation() 7673 * @see #getScaleX() 7674 * @see #getScaleY() 7675 * @see #getPivotY() 7676 * @return The y location of the pivot point. 7677 */ 7678 @ViewDebug.ExportedProperty(category = "drawing") 7679 public float getPivotY() { 7680 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 7681 } 7682 7683 /** 7684 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 7685 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 7686 * Setting this property disables this behavior and causes the view to use only the 7687 * explicitly set pivotX and pivotY values. 7688 * 7689 * @param pivotY The y location of the pivot point. 7690 * @see #getRotation() 7691 * @see #getScaleX() 7692 * @see #getScaleY() 7693 * @see #getPivotY() 7694 * 7695 * @attr ref android.R.styleable#View_transformPivotY 7696 */ 7697 public void setPivotY(float pivotY) { 7698 ensureTransformationInfo(); 7699 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7700 final TransformationInfo info = mTransformationInfo; 7701 if (info.mPivotY != pivotY) { 7702 invalidateViewProperty(true, false); 7703 info.mPivotY = pivotY; 7704 info.mMatrixDirty = true; 7705 invalidateViewProperty(false, true); 7706 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7707 mDisplayList.setPivotY(pivotY); 7708 } 7709 } 7710 } 7711 7712 /** 7713 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 7714 * completely transparent and 1 means the view is completely opaque. 7715 * 7716 * <p>By default this is 1.0f. 7717 * @return The opacity of the view. 7718 */ 7719 @ViewDebug.ExportedProperty(category = "drawing") 7720 public float getAlpha() { 7721 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 7722 } 7723 7724 /** 7725 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 7726 * completely transparent and 1 means the view is completely opaque.</p> 7727 * 7728 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 7729 * responsible for applying the opacity itself. Otherwise, calling this method is 7730 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 7731 * setting a hardware layer.</p> 7732 * 7733 * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have 7734 * performance implications. It is generally best to use the alpha property sparingly and 7735 * transiently, as in the case of fading animations.</p> 7736 * 7737 * @param alpha The opacity of the view. 7738 * 7739 * @see #setLayerType(int, android.graphics.Paint) 7740 * 7741 * @attr ref android.R.styleable#View_alpha 7742 */ 7743 public void setAlpha(float alpha) { 7744 ensureTransformationInfo(); 7745 if (mTransformationInfo.mAlpha != alpha) { 7746 mTransformationInfo.mAlpha = alpha; 7747 if (onSetAlpha((int) (alpha * 255))) { 7748 mPrivateFlags |= ALPHA_SET; 7749 // subclass is handling alpha - don't optimize rendering cache invalidation 7750 invalidateParentCaches(); 7751 invalidate(true); 7752 } else { 7753 mPrivateFlags &= ~ALPHA_SET; 7754 invalidateViewProperty(true, false); 7755 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7756 mDisplayList.setAlpha(alpha); 7757 } 7758 } 7759 } 7760 } 7761 7762 /** 7763 * Faster version of setAlpha() which performs the same steps except there are 7764 * no calls to invalidate(). The caller of this function should perform proper invalidation 7765 * on the parent and this object. The return value indicates whether the subclass handles 7766 * alpha (the return value for onSetAlpha()). 7767 * 7768 * @param alpha The new value for the alpha property 7769 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 7770 * the new value for the alpha property is different from the old value 7771 */ 7772 boolean setAlphaNoInvalidation(float alpha) { 7773 ensureTransformationInfo(); 7774 if (mTransformationInfo.mAlpha != alpha) { 7775 mTransformationInfo.mAlpha = alpha; 7776 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 7777 if (subclassHandlesAlpha) { 7778 mPrivateFlags |= ALPHA_SET; 7779 return true; 7780 } else { 7781 mPrivateFlags &= ~ALPHA_SET; 7782 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7783 mDisplayList.setAlpha(alpha); 7784 } 7785 } 7786 } 7787 return false; 7788 } 7789 7790 /** 7791 * Top position of this view relative to its parent. 7792 * 7793 * @return The top of this view, in pixels. 7794 */ 7795 @ViewDebug.CapturedViewProperty 7796 public final int getTop() { 7797 return mTop; 7798 } 7799 7800 /** 7801 * Sets the top position of this view relative to its parent. This method is meant to be called 7802 * by the layout system and should not generally be called otherwise, because the property 7803 * may be changed at any time by the layout. 7804 * 7805 * @param top The top of this view, in pixels. 7806 */ 7807 public final void setTop(int top) { 7808 if (top != mTop) { 7809 updateMatrix(); 7810 final boolean matrixIsIdentity = mTransformationInfo == null 7811 || mTransformationInfo.mMatrixIsIdentity; 7812 if (matrixIsIdentity) { 7813 if (mAttachInfo != null) { 7814 int minTop; 7815 int yLoc; 7816 if (top < mTop) { 7817 minTop = top; 7818 yLoc = top - mTop; 7819 } else { 7820 minTop = mTop; 7821 yLoc = 0; 7822 } 7823 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 7824 } 7825 } else { 7826 // Double-invalidation is necessary to capture view's old and new areas 7827 invalidate(true); 7828 } 7829 7830 int width = mRight - mLeft; 7831 int oldHeight = mBottom - mTop; 7832 7833 mTop = top; 7834 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7835 mDisplayList.setTop(mTop); 7836 } 7837 7838 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7839 7840 if (!matrixIsIdentity) { 7841 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7842 // A change in dimension means an auto-centered pivot point changes, too 7843 mTransformationInfo.mMatrixDirty = true; 7844 } 7845 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7846 invalidate(true); 7847 } 7848 mBackgroundSizeChanged = true; 7849 invalidateParentIfNeeded(); 7850 } 7851 } 7852 7853 /** 7854 * Bottom position of this view relative to its parent. 7855 * 7856 * @return The bottom of this view, in pixels. 7857 */ 7858 @ViewDebug.CapturedViewProperty 7859 public final int getBottom() { 7860 return mBottom; 7861 } 7862 7863 /** 7864 * True if this view has changed since the last time being drawn. 7865 * 7866 * @return The dirty state of this view. 7867 */ 7868 public boolean isDirty() { 7869 return (mPrivateFlags & DIRTY_MASK) != 0; 7870 } 7871 7872 /** 7873 * Sets the bottom position of this view relative to its parent. This method is meant to be 7874 * called by the layout system and should not generally be called otherwise, because the 7875 * property may be changed at any time by the layout. 7876 * 7877 * @param bottom The bottom of this view, in pixels. 7878 */ 7879 public final void setBottom(int bottom) { 7880 if (bottom != mBottom) { 7881 updateMatrix(); 7882 final boolean matrixIsIdentity = mTransformationInfo == null 7883 || mTransformationInfo.mMatrixIsIdentity; 7884 if (matrixIsIdentity) { 7885 if (mAttachInfo != null) { 7886 int maxBottom; 7887 if (bottom < mBottom) { 7888 maxBottom = mBottom; 7889 } else { 7890 maxBottom = bottom; 7891 } 7892 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 7893 } 7894 } else { 7895 // Double-invalidation is necessary to capture view's old and new areas 7896 invalidate(true); 7897 } 7898 7899 int width = mRight - mLeft; 7900 int oldHeight = mBottom - mTop; 7901 7902 mBottom = bottom; 7903 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7904 mDisplayList.setBottom(mBottom); 7905 } 7906 7907 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7908 7909 if (!matrixIsIdentity) { 7910 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7911 // A change in dimension means an auto-centered pivot point changes, too 7912 mTransformationInfo.mMatrixDirty = true; 7913 } 7914 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7915 invalidate(true); 7916 } 7917 mBackgroundSizeChanged = true; 7918 invalidateParentIfNeeded(); 7919 } 7920 } 7921 7922 /** 7923 * Left position of this view relative to its parent. 7924 * 7925 * @return The left edge of this view, in pixels. 7926 */ 7927 @ViewDebug.CapturedViewProperty 7928 public final int getLeft() { 7929 return mLeft; 7930 } 7931 7932 /** 7933 * Sets the left position of this view relative to its parent. This method is meant to be called 7934 * by the layout system and should not generally be called otherwise, because the property 7935 * may be changed at any time by the layout. 7936 * 7937 * @param left The bottom of this view, in pixels. 7938 */ 7939 public final void setLeft(int left) { 7940 if (left != mLeft) { 7941 updateMatrix(); 7942 final boolean matrixIsIdentity = mTransformationInfo == null 7943 || mTransformationInfo.mMatrixIsIdentity; 7944 if (matrixIsIdentity) { 7945 if (mAttachInfo != null) { 7946 int minLeft; 7947 int xLoc; 7948 if (left < mLeft) { 7949 minLeft = left; 7950 xLoc = left - mLeft; 7951 } else { 7952 minLeft = mLeft; 7953 xLoc = 0; 7954 } 7955 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 7956 } 7957 } else { 7958 // Double-invalidation is necessary to capture view's old and new areas 7959 invalidate(true); 7960 } 7961 7962 int oldWidth = mRight - mLeft; 7963 int height = mBottom - mTop; 7964 7965 mLeft = left; 7966 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 7967 mDisplayList.setLeft(left); 7968 } 7969 7970 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7971 7972 if (!matrixIsIdentity) { 7973 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7974 // A change in dimension means an auto-centered pivot point changes, too 7975 mTransformationInfo.mMatrixDirty = true; 7976 } 7977 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7978 invalidate(true); 7979 } 7980 mBackgroundSizeChanged = true; 7981 invalidateParentIfNeeded(); 7982 if (USE_DISPLAY_LIST_PROPERTIES) { 7983 7984 } 7985 } 7986 } 7987 7988 /** 7989 * Right position of this view relative to its parent. 7990 * 7991 * @return The right edge of this view, in pixels. 7992 */ 7993 @ViewDebug.CapturedViewProperty 7994 public final int getRight() { 7995 return mRight; 7996 } 7997 7998 /** 7999 * Sets the right position of this view relative to its parent. This method is meant to be called 8000 * by the layout system and should not generally be called otherwise, because the property 8001 * may be changed at any time by the layout. 8002 * 8003 * @param right The bottom of this view, in pixels. 8004 */ 8005 public final void setRight(int right) { 8006 if (right != mRight) { 8007 updateMatrix(); 8008 final boolean matrixIsIdentity = mTransformationInfo == null 8009 || mTransformationInfo.mMatrixIsIdentity; 8010 if (matrixIsIdentity) { 8011 if (mAttachInfo != null) { 8012 int maxRight; 8013 if (right < mRight) { 8014 maxRight = mRight; 8015 } else { 8016 maxRight = right; 8017 } 8018 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 8019 } 8020 } else { 8021 // Double-invalidation is necessary to capture view's old and new areas 8022 invalidate(true); 8023 } 8024 8025 int oldWidth = mRight - mLeft; 8026 int height = mBottom - mTop; 8027 8028 mRight = right; 8029 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 8030 mDisplayList.setRight(mRight); 8031 } 8032 8033 onSizeChanged(mRight - mLeft, height, oldWidth, height); 8034 8035 if (!matrixIsIdentity) { 8036 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 8037 // A change in dimension means an auto-centered pivot point changes, too 8038 mTransformationInfo.mMatrixDirty = true; 8039 } 8040 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8041 invalidate(true); 8042 } 8043 mBackgroundSizeChanged = true; 8044 invalidateParentIfNeeded(); 8045 } 8046 } 8047 8048 /** 8049 * The visual x position of this view, in pixels. This is equivalent to the 8050 * {@link #setTranslationX(float) translationX} property plus the current 8051 * {@link #getLeft() left} property. 8052 * 8053 * @return The visual x position of this view, in pixels. 8054 */ 8055 @ViewDebug.ExportedProperty(category = "drawing") 8056 public float getX() { 8057 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 8058 } 8059 8060 /** 8061 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 8062 * {@link #setTranslationX(float) translationX} property to be the difference between 8063 * the x value passed in and the current {@link #getLeft() left} property. 8064 * 8065 * @param x The visual x position of this view, in pixels. 8066 */ 8067 public void setX(float x) { 8068 setTranslationX(x - mLeft); 8069 } 8070 8071 /** 8072 * The visual y position of this view, in pixels. This is equivalent to the 8073 * {@link #setTranslationY(float) translationY} property plus the current 8074 * {@link #getTop() top} property. 8075 * 8076 * @return The visual y position of this view, in pixels. 8077 */ 8078 @ViewDebug.ExportedProperty(category = "drawing") 8079 public float getY() { 8080 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 8081 } 8082 8083 /** 8084 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 8085 * {@link #setTranslationY(float) translationY} property to be the difference between 8086 * the y value passed in and the current {@link #getTop() top} property. 8087 * 8088 * @param y The visual y position of this view, in pixels. 8089 */ 8090 public void setY(float y) { 8091 setTranslationY(y - mTop); 8092 } 8093 8094 8095 /** 8096 * The horizontal location of this view relative to its {@link #getLeft() left} position. 8097 * This position is post-layout, in addition to wherever the object's 8098 * layout placed it. 8099 * 8100 * @return The horizontal position of this view relative to its left position, in pixels. 8101 */ 8102 @ViewDebug.ExportedProperty(category = "drawing") 8103 public float getTranslationX() { 8104 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 8105 } 8106 8107 /** 8108 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 8109 * This effectively positions the object post-layout, in addition to wherever the object's 8110 * layout placed it. 8111 * 8112 * @param translationX The horizontal position of this view relative to its left position, 8113 * in pixels. 8114 * 8115 * @attr ref android.R.styleable#View_translationX 8116 */ 8117 public void setTranslationX(float translationX) { 8118 ensureTransformationInfo(); 8119 final TransformationInfo info = mTransformationInfo; 8120 if (info.mTranslationX != translationX) { 8121 // Double-invalidation is necessary to capture view's old and new areas 8122 invalidateViewProperty(true, false); 8123 info.mTranslationX = translationX; 8124 info.mMatrixDirty = true; 8125 invalidateViewProperty(false, true); 8126 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 8127 mDisplayList.setTranslationX(translationX); 8128 } 8129 } 8130 } 8131 8132 /** 8133 * The horizontal location of this view relative to its {@link #getTop() top} position. 8134 * This position is post-layout, in addition to wherever the object's 8135 * layout placed it. 8136 * 8137 * @return The vertical position of this view relative to its top position, 8138 * in pixels. 8139 */ 8140 @ViewDebug.ExportedProperty(category = "drawing") 8141 public float getTranslationY() { 8142 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 8143 } 8144 8145 /** 8146 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 8147 * This effectively positions the object post-layout, in addition to wherever the object's 8148 * layout placed it. 8149 * 8150 * @param translationY The vertical position of this view relative to its top position, 8151 * in pixels. 8152 * 8153 * @attr ref android.R.styleable#View_translationY 8154 */ 8155 public void setTranslationY(float translationY) { 8156 ensureTransformationInfo(); 8157 final TransformationInfo info = mTransformationInfo; 8158 if (info.mTranslationY != translationY) { 8159 invalidateViewProperty(true, false); 8160 info.mTranslationY = translationY; 8161 info.mMatrixDirty = true; 8162 invalidateViewProperty(false, true); 8163 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 8164 mDisplayList.setTranslationY(translationY); 8165 } 8166 } 8167 } 8168 8169 /** 8170 * Hit rectangle in parent's coordinates 8171 * 8172 * @param outRect The hit rectangle of the view. 8173 */ 8174 public void getHitRect(Rect outRect) { 8175 updateMatrix(); 8176 final TransformationInfo info = mTransformationInfo; 8177 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 8178 outRect.set(mLeft, mTop, mRight, mBottom); 8179 } else { 8180 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 8181 tmpRect.set(-info.mPivotX, -info.mPivotY, 8182 getWidth() - info.mPivotX, getHeight() - info.mPivotY); 8183 info.mMatrix.mapRect(tmpRect); 8184 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 8185 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 8186 } 8187 } 8188 8189 /** 8190 * Determines whether the given point, in local coordinates is inside the view. 8191 */ 8192 /*package*/ final boolean pointInView(float localX, float localY) { 8193 return localX >= 0 && localX < (mRight - mLeft) 8194 && localY >= 0 && localY < (mBottom - mTop); 8195 } 8196 8197 /** 8198 * Utility method to determine whether the given point, in local coordinates, 8199 * is inside the view, where the area of the view is expanded by the slop factor. 8200 * This method is called while processing touch-move events to determine if the event 8201 * is still within the view. 8202 */ 8203 private boolean pointInView(float localX, float localY, float slop) { 8204 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 8205 localY < ((mBottom - mTop) + slop); 8206 } 8207 8208 /** 8209 * When a view has focus and the user navigates away from it, the next view is searched for 8210 * starting from the rectangle filled in by this method. 8211 * 8212 * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)}) 8213 * of the view. However, if your view maintains some idea of internal selection, 8214 * such as a cursor, or a selected row or column, you should override this method and 8215 * fill in a more specific rectangle. 8216 * 8217 * @param r The rectangle to fill in, in this view's coordinates. 8218 */ 8219 public void getFocusedRect(Rect r) { 8220 getDrawingRect(r); 8221 } 8222 8223 /** 8224 * If some part of this view is not clipped by any of its parents, then 8225 * return that area in r in global (root) coordinates. To convert r to local 8226 * coordinates (without taking possible View rotations into account), offset 8227 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 8228 * If the view is completely clipped or translated out, return false. 8229 * 8230 * @param r If true is returned, r holds the global coordinates of the 8231 * visible portion of this view. 8232 * @param globalOffset If true is returned, globalOffset holds the dx,dy 8233 * between this view and its root. globalOffet may be null. 8234 * @return true if r is non-empty (i.e. part of the view is visible at the 8235 * root level. 8236 */ 8237 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 8238 int width = mRight - mLeft; 8239 int height = mBottom - mTop; 8240 if (width > 0 && height > 0) { 8241 r.set(0, 0, width, height); 8242 if (globalOffset != null) { 8243 globalOffset.set(-mScrollX, -mScrollY); 8244 } 8245 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 8246 } 8247 return false; 8248 } 8249 8250 public final boolean getGlobalVisibleRect(Rect r) { 8251 return getGlobalVisibleRect(r, null); 8252 } 8253 8254 public final boolean getLocalVisibleRect(Rect r) { 8255 Point offset = new Point(); 8256 if (getGlobalVisibleRect(r, offset)) { 8257 r.offset(-offset.x, -offset.y); // make r local 8258 return true; 8259 } 8260 return false; 8261 } 8262 8263 /** 8264 * Offset this view's vertical location by the specified number of pixels. 8265 * 8266 * @param offset the number of pixels to offset the view by 8267 */ 8268 public void offsetTopAndBottom(int offset) { 8269 if (offset != 0) { 8270 updateMatrix(); 8271 final boolean matrixIsIdentity = mTransformationInfo == null 8272 || mTransformationInfo.mMatrixIsIdentity; 8273 if (matrixIsIdentity) { 8274 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 8275 invalidateViewProperty(false, false); 8276 } else { 8277 final ViewParent p = mParent; 8278 if (p != null && mAttachInfo != null) { 8279 final Rect r = mAttachInfo.mTmpInvalRect; 8280 int minTop; 8281 int maxBottom; 8282 int yLoc; 8283 if (offset < 0) { 8284 minTop = mTop + offset; 8285 maxBottom = mBottom; 8286 yLoc = offset; 8287 } else { 8288 minTop = mTop; 8289 maxBottom = mBottom + offset; 8290 yLoc = 0; 8291 } 8292 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 8293 p.invalidateChild(this, r); 8294 } 8295 } 8296 } else { 8297 invalidateViewProperty(false, false); 8298 } 8299 8300 mTop += offset; 8301 mBottom += offset; 8302 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 8303 mDisplayList.offsetTopBottom(offset); 8304 invalidateViewProperty(false, false); 8305 } else { 8306 if (!matrixIsIdentity) { 8307 invalidateViewProperty(false, true); 8308 } 8309 invalidateParentIfNeeded(); 8310 } 8311 } 8312 } 8313 8314 /** 8315 * Offset this view's horizontal location by the specified amount of pixels. 8316 * 8317 * @param offset the numer of pixels to offset the view by 8318 */ 8319 public void offsetLeftAndRight(int offset) { 8320 if (offset != 0) { 8321 updateMatrix(); 8322 final boolean matrixIsIdentity = mTransformationInfo == null 8323 || mTransformationInfo.mMatrixIsIdentity; 8324 if (matrixIsIdentity) { 8325 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 8326 invalidateViewProperty(false, false); 8327 } else { 8328 final ViewParent p = mParent; 8329 if (p != null && mAttachInfo != null) { 8330 final Rect r = mAttachInfo.mTmpInvalRect; 8331 int minLeft; 8332 int maxRight; 8333 if (offset < 0) { 8334 minLeft = mLeft + offset; 8335 maxRight = mRight; 8336 } else { 8337 minLeft = mLeft; 8338 maxRight = mRight + offset; 8339 } 8340 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 8341 p.invalidateChild(this, r); 8342 } 8343 } 8344 } else { 8345 invalidateViewProperty(false, false); 8346 } 8347 8348 mLeft += offset; 8349 mRight += offset; 8350 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 8351 mDisplayList.offsetLeftRight(offset); 8352 invalidateViewProperty(false, false); 8353 } else { 8354 if (!matrixIsIdentity) { 8355 invalidateViewProperty(false, true); 8356 } 8357 invalidateParentIfNeeded(); 8358 } 8359 } 8360 } 8361 8362 /** 8363 * Get the LayoutParams associated with this view. All views should have 8364 * layout parameters. These supply parameters to the <i>parent</i> of this 8365 * view specifying how it should be arranged. There are many subclasses of 8366 * ViewGroup.LayoutParams, and these correspond to the different subclasses 8367 * of ViewGroup that are responsible for arranging their children. 8368 * 8369 * This method may return null if this View is not attached to a parent 8370 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 8371 * was not invoked successfully. When a View is attached to a parent 8372 * ViewGroup, this method must not return null. 8373 * 8374 * @return The LayoutParams associated with this view, or null if no 8375 * parameters have been set yet 8376 */ 8377 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 8378 public ViewGroup.LayoutParams getLayoutParams() { 8379 return mLayoutParams; 8380 } 8381 8382 /** 8383 * Set the layout parameters associated with this view. These supply 8384 * parameters to the <i>parent</i> of this view specifying how it should be 8385 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 8386 * correspond to the different subclasses of ViewGroup that are responsible 8387 * for arranging their children. 8388 * 8389 * @param params The layout parameters for this view, cannot be null 8390 */ 8391 public void setLayoutParams(ViewGroup.LayoutParams params) { 8392 if (params == null) { 8393 throw new NullPointerException("Layout parameters cannot be null"); 8394 } 8395 mLayoutParams = params; 8396 if (mParent instanceof ViewGroup) { 8397 ((ViewGroup) mParent).onSetLayoutParams(this, params); 8398 } 8399 requestLayout(); 8400 } 8401 8402 /** 8403 * Set the scrolled position of your view. This will cause a call to 8404 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8405 * invalidated. 8406 * @param x the x position to scroll to 8407 * @param y the y position to scroll to 8408 */ 8409 public void scrollTo(int x, int y) { 8410 if (mScrollX != x || mScrollY != y) { 8411 int oldX = mScrollX; 8412 int oldY = mScrollY; 8413 mScrollX = x; 8414 mScrollY = y; 8415 invalidateParentCaches(); 8416 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 8417 if (!awakenScrollBars()) { 8418 invalidate(true); 8419 } 8420 } 8421 } 8422 8423 /** 8424 * Move the scrolled position of your view. This will cause a call to 8425 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8426 * invalidated. 8427 * @param x the amount of pixels to scroll by horizontally 8428 * @param y the amount of pixels to scroll by vertically 8429 */ 8430 public void scrollBy(int x, int y) { 8431 scrollTo(mScrollX + x, mScrollY + y); 8432 } 8433 8434 /** 8435 * <p>Trigger the scrollbars to draw. When invoked this method starts an 8436 * animation to fade the scrollbars out after a default delay. If a subclass 8437 * provides animated scrolling, the start delay should equal the duration 8438 * of the scrolling animation.</p> 8439 * 8440 * <p>The animation starts only if at least one of the scrollbars is 8441 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 8442 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8443 * this method returns true, and false otherwise. If the animation is 8444 * started, this method calls {@link #invalidate()}; in that case the 8445 * caller should not call {@link #invalidate()}.</p> 8446 * 8447 * <p>This method should be invoked every time a subclass directly updates 8448 * the scroll parameters.</p> 8449 * 8450 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 8451 * and {@link #scrollTo(int, int)}.</p> 8452 * 8453 * @return true if the animation is played, false otherwise 8454 * 8455 * @see #awakenScrollBars(int) 8456 * @see #scrollBy(int, int) 8457 * @see #scrollTo(int, int) 8458 * @see #isHorizontalScrollBarEnabled() 8459 * @see #isVerticalScrollBarEnabled() 8460 * @see #setHorizontalScrollBarEnabled(boolean) 8461 * @see #setVerticalScrollBarEnabled(boolean) 8462 */ 8463 protected boolean awakenScrollBars() { 8464 return mScrollCache != null && 8465 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 8466 } 8467 8468 /** 8469 * Trigger the scrollbars to draw. 8470 * This method differs from awakenScrollBars() only in its default duration. 8471 * initialAwakenScrollBars() will show the scroll bars for longer than 8472 * usual to give the user more of a chance to notice them. 8473 * 8474 * @return true if the animation is played, false otherwise. 8475 */ 8476 private boolean initialAwakenScrollBars() { 8477 return mScrollCache != null && 8478 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 8479 } 8480 8481 /** 8482 * <p> 8483 * Trigger the scrollbars to draw. When invoked this method starts an 8484 * animation to fade the scrollbars out after a fixed delay. If a subclass 8485 * provides animated scrolling, the start delay should equal the duration of 8486 * the scrolling animation. 8487 * </p> 8488 * 8489 * <p> 8490 * The animation starts only if at least one of the scrollbars is enabled, 8491 * as specified by {@link #isHorizontalScrollBarEnabled()} and 8492 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8493 * this method returns true, and false otherwise. If the animation is 8494 * started, this method calls {@link #invalidate()}; in that case the caller 8495 * should not call {@link #invalidate()}. 8496 * </p> 8497 * 8498 * <p> 8499 * This method should be invoked everytime a subclass directly updates the 8500 * scroll parameters. 8501 * </p> 8502 * 8503 * @param startDelay the delay, in milliseconds, after which the animation 8504 * should start; when the delay is 0, the animation starts 8505 * immediately 8506 * @return true if the animation is played, false otherwise 8507 * 8508 * @see #scrollBy(int, int) 8509 * @see #scrollTo(int, int) 8510 * @see #isHorizontalScrollBarEnabled() 8511 * @see #isVerticalScrollBarEnabled() 8512 * @see #setHorizontalScrollBarEnabled(boolean) 8513 * @see #setVerticalScrollBarEnabled(boolean) 8514 */ 8515 protected boolean awakenScrollBars(int startDelay) { 8516 return awakenScrollBars(startDelay, true); 8517 } 8518 8519 /** 8520 * <p> 8521 * Trigger the scrollbars to draw. When invoked this method starts an 8522 * animation to fade the scrollbars out after a fixed delay. If a subclass 8523 * provides animated scrolling, the start delay should equal the duration of 8524 * the scrolling animation. 8525 * </p> 8526 * 8527 * <p> 8528 * The animation starts only if at least one of the scrollbars is enabled, 8529 * as specified by {@link #isHorizontalScrollBarEnabled()} and 8530 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8531 * this method returns true, and false otherwise. If the animation is 8532 * started, this method calls {@link #invalidate()} if the invalidate parameter 8533 * is set to true; in that case the caller 8534 * should not call {@link #invalidate()}. 8535 * </p> 8536 * 8537 * <p> 8538 * This method should be invoked everytime a subclass directly updates the 8539 * scroll parameters. 8540 * </p> 8541 * 8542 * @param startDelay the delay, in milliseconds, after which the animation 8543 * should start; when the delay is 0, the animation starts 8544 * immediately 8545 * 8546 * @param invalidate Wheter this method should call invalidate 8547 * 8548 * @return true if the animation is played, false otherwise 8549 * 8550 * @see #scrollBy(int, int) 8551 * @see #scrollTo(int, int) 8552 * @see #isHorizontalScrollBarEnabled() 8553 * @see #isVerticalScrollBarEnabled() 8554 * @see #setHorizontalScrollBarEnabled(boolean) 8555 * @see #setVerticalScrollBarEnabled(boolean) 8556 */ 8557 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 8558 final ScrollabilityCache scrollCache = mScrollCache; 8559 8560 if (scrollCache == null || !scrollCache.fadeScrollBars) { 8561 return false; 8562 } 8563 8564 if (scrollCache.scrollBar == null) { 8565 scrollCache.scrollBar = new ScrollBarDrawable(); 8566 } 8567 8568 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 8569 8570 if (invalidate) { 8571 // Invalidate to show the scrollbars 8572 invalidate(true); 8573 } 8574 8575 if (scrollCache.state == ScrollabilityCache.OFF) { 8576 // FIXME: this is copied from WindowManagerService. 8577 // We should get this value from the system when it 8578 // is possible to do so. 8579 final int KEY_REPEAT_FIRST_DELAY = 750; 8580 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 8581 } 8582 8583 // Tell mScrollCache when we should start fading. This may 8584 // extend the fade start time if one was already scheduled 8585 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 8586 scrollCache.fadeStartTime = fadeStartTime; 8587 scrollCache.state = ScrollabilityCache.ON; 8588 8589 // Schedule our fader to run, unscheduling any old ones first 8590 if (mAttachInfo != null) { 8591 mAttachInfo.mHandler.removeCallbacks(scrollCache); 8592 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 8593 } 8594 8595 return true; 8596 } 8597 8598 return false; 8599 } 8600 8601 /** 8602 * Do not invalidate views which are not visible and which are not running an animation. They 8603 * will not get drawn and they should not set dirty flags as if they will be drawn 8604 */ 8605 private boolean skipInvalidate() { 8606 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 8607 (!(mParent instanceof ViewGroup) || 8608 !((ViewGroup) mParent).isViewTransitioning(this)); 8609 } 8610 /** 8611 * Mark the area defined by dirty as needing to be drawn. If the view is 8612 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 8613 * in the future. This must be called from a UI thread. To call from a non-UI 8614 * thread, call {@link #postInvalidate()}. 8615 * 8616 * WARNING: This method is destructive to dirty. 8617 * @param dirty the rectangle representing the bounds of the dirty region 8618 */ 8619 public void invalidate(Rect dirty) { 8620 if (ViewDebug.TRACE_HIERARCHY) { 8621 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8622 } 8623 8624 if (skipInvalidate()) { 8625 return; 8626 } 8627 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8628 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8629 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8630 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8631 mPrivateFlags |= INVALIDATED; 8632 mPrivateFlags |= DIRTY; 8633 final ViewParent p = mParent; 8634 final AttachInfo ai = mAttachInfo; 8635 //noinspection PointlessBooleanExpression,ConstantConditions 8636 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8637 if (p != null && ai != null && ai.mHardwareAccelerated) { 8638 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8639 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8640 p.invalidateChild(this, null); 8641 return; 8642 } 8643 } 8644 if (p != null && ai != null) { 8645 final int scrollX = mScrollX; 8646 final int scrollY = mScrollY; 8647 final Rect r = ai.mTmpInvalRect; 8648 r.set(dirty.left - scrollX, dirty.top - scrollY, 8649 dirty.right - scrollX, dirty.bottom - scrollY); 8650 mParent.invalidateChild(this, r); 8651 } 8652 } 8653 } 8654 8655 /** 8656 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 8657 * The coordinates of the dirty rect are relative to the view. 8658 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 8659 * will be called at some point in the future. This must be called from 8660 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 8661 * @param l the left position of the dirty region 8662 * @param t the top position of the dirty region 8663 * @param r the right position of the dirty region 8664 * @param b the bottom position of the dirty region 8665 */ 8666 public void invalidate(int l, int t, int r, int b) { 8667 if (ViewDebug.TRACE_HIERARCHY) { 8668 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8669 } 8670 8671 if (skipInvalidate()) { 8672 return; 8673 } 8674 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8675 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8676 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8677 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8678 mPrivateFlags |= INVALIDATED; 8679 mPrivateFlags |= DIRTY; 8680 final ViewParent p = mParent; 8681 final AttachInfo ai = mAttachInfo; 8682 //noinspection PointlessBooleanExpression,ConstantConditions 8683 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8684 if (p != null && ai != null && ai.mHardwareAccelerated) { 8685 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8686 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8687 p.invalidateChild(this, null); 8688 return; 8689 } 8690 } 8691 if (p != null && ai != null && l < r && t < b) { 8692 final int scrollX = mScrollX; 8693 final int scrollY = mScrollY; 8694 final Rect tmpr = ai.mTmpInvalRect; 8695 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 8696 p.invalidateChild(this, tmpr); 8697 } 8698 } 8699 } 8700 8701 /** 8702 * Invalidate the whole view. If the view is visible, 8703 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 8704 * the future. This must be called from a UI thread. To call from a non-UI thread, 8705 * call {@link #postInvalidate()}. 8706 */ 8707 public void invalidate() { 8708 invalidate(true); 8709 } 8710 8711 /** 8712 * This is where the invalidate() work actually happens. A full invalidate() 8713 * causes the drawing cache to be invalidated, but this function can be called with 8714 * invalidateCache set to false to skip that invalidation step for cases that do not 8715 * need it (for example, a component that remains at the same dimensions with the same 8716 * content). 8717 * 8718 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 8719 * well. This is usually true for a full invalidate, but may be set to false if the 8720 * View's contents or dimensions have not changed. 8721 */ 8722 void invalidate(boolean invalidateCache) { 8723 if (ViewDebug.TRACE_HIERARCHY) { 8724 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8725 } 8726 8727 if (skipInvalidate()) { 8728 return; 8729 } 8730 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8731 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) || 8732 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) { 8733 mLastIsOpaque = isOpaque(); 8734 mPrivateFlags &= ~DRAWN; 8735 mPrivateFlags |= DIRTY; 8736 if (invalidateCache) { 8737 mPrivateFlags |= INVALIDATED; 8738 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8739 } 8740 final AttachInfo ai = mAttachInfo; 8741 final ViewParent p = mParent; 8742 //noinspection PointlessBooleanExpression,ConstantConditions 8743 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8744 if (p != null && ai != null && ai.mHardwareAccelerated) { 8745 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8746 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8747 p.invalidateChild(this, null); 8748 return; 8749 } 8750 } 8751 8752 if (p != null && ai != null) { 8753 final Rect r = ai.mTmpInvalRect; 8754 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8755 // Don't call invalidate -- we don't want to internally scroll 8756 // our own bounds 8757 p.invalidateChild(this, r); 8758 } 8759 } 8760 } 8761 8762 /** 8763 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 8764 * set any flags or handle all of the cases handled by the default invalidation methods. 8765 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 8766 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 8767 * walk up the hierarchy, transforming the dirty rect as necessary. 8768 * 8769 * The method also handles normal invalidation logic if display list properties are not 8770 * being used in this view. The invalidateParent and forceRedraw flags are used by that 8771 * backup approach, to handle these cases used in the various property-setting methods. 8772 * 8773 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 8774 * are not being used in this view 8775 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 8776 * list properties are not being used in this view 8777 */ 8778 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 8779 if (!USE_DISPLAY_LIST_PROPERTIES || mDisplayList == null || 8780 (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) { 8781 if (invalidateParent) { 8782 invalidateParentCaches(); 8783 } 8784 if (forceRedraw) { 8785 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 8786 } 8787 invalidate(false); 8788 } else { 8789 final AttachInfo ai = mAttachInfo; 8790 final ViewParent p = mParent; 8791 if (p != null && ai != null) { 8792 final Rect r = ai.mTmpInvalRect; 8793 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8794 if (mParent instanceof ViewGroup) { 8795 ((ViewGroup) mParent).invalidateChildFast(this, r); 8796 } else { 8797 mParent.invalidateChild(this, r); 8798 } 8799 } 8800 } 8801 } 8802 8803 /** 8804 * Utility method to transform a given Rect by the current matrix of this view. 8805 */ 8806 void transformRect(final Rect rect) { 8807 if (!getMatrix().isIdentity()) { 8808 RectF boundingRect = mAttachInfo.mTmpTransformRect; 8809 boundingRect.set(rect); 8810 getMatrix().mapRect(boundingRect); 8811 rect.set((int) (boundingRect.left - 0.5f), 8812 (int) (boundingRect.top - 0.5f), 8813 (int) (boundingRect.right + 0.5f), 8814 (int) (boundingRect.bottom + 0.5f)); 8815 } 8816 } 8817 8818 /** 8819 * Used to indicate that the parent of this view should clear its caches. This functionality 8820 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8821 * which is necessary when various parent-managed properties of the view change, such as 8822 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 8823 * clears the parent caches and does not causes an invalidate event. 8824 * 8825 * @hide 8826 */ 8827 protected void invalidateParentCaches() { 8828 if (mParent instanceof View) { 8829 ((View) mParent).mPrivateFlags |= INVALIDATED; 8830 } 8831 } 8832 8833 /** 8834 * Used to indicate that the parent of this view should be invalidated. This functionality 8835 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8836 * which is necessary when various parent-managed properties of the view change, such as 8837 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 8838 * an invalidation event to the parent. 8839 * 8840 * @hide 8841 */ 8842 protected void invalidateParentIfNeeded() { 8843 if (isHardwareAccelerated() && mParent instanceof View) { 8844 ((View) mParent).invalidate(true); 8845 } 8846 } 8847 8848 /** 8849 * Indicates whether this View is opaque. An opaque View guarantees that it will 8850 * draw all the pixels overlapping its bounds using a fully opaque color. 8851 * 8852 * Subclasses of View should override this method whenever possible to indicate 8853 * whether an instance is opaque. Opaque Views are treated in a special way by 8854 * the View hierarchy, possibly allowing it to perform optimizations during 8855 * invalidate/draw passes. 8856 * 8857 * @return True if this View is guaranteed to be fully opaque, false otherwise. 8858 */ 8859 @ViewDebug.ExportedProperty(category = "drawing") 8860 public boolean isOpaque() { 8861 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK && 8862 ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1) 8863 >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD); 8864 } 8865 8866 /** 8867 * @hide 8868 */ 8869 protected void computeOpaqueFlags() { 8870 // Opaque if: 8871 // - Has a background 8872 // - Background is opaque 8873 // - Doesn't have scrollbars or scrollbars are inside overlay 8874 8875 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) { 8876 mPrivateFlags |= OPAQUE_BACKGROUND; 8877 } else { 8878 mPrivateFlags &= ~OPAQUE_BACKGROUND; 8879 } 8880 8881 final int flags = mViewFlags; 8882 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 8883 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 8884 mPrivateFlags |= OPAQUE_SCROLLBARS; 8885 } else { 8886 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 8887 } 8888 } 8889 8890 /** 8891 * @hide 8892 */ 8893 protected boolean hasOpaqueScrollbars() { 8894 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 8895 } 8896 8897 /** 8898 * @return A handler associated with the thread running the View. This 8899 * handler can be used to pump events in the UI events queue. 8900 */ 8901 public Handler getHandler() { 8902 if (mAttachInfo != null) { 8903 return mAttachInfo.mHandler; 8904 } 8905 return null; 8906 } 8907 8908 /** 8909 * Gets the view root associated with the View. 8910 * @return The view root, or null if none. 8911 * @hide 8912 */ 8913 public ViewRootImpl getViewRootImpl() { 8914 if (mAttachInfo != null) { 8915 return mAttachInfo.mViewRootImpl; 8916 } 8917 return null; 8918 } 8919 8920 /** 8921 * <p>Causes the Runnable to be added to the message queue. 8922 * The runnable will be run on the user interface thread.</p> 8923 * 8924 * <p>This method can be invoked from outside of the UI thread 8925 * only when this View is attached to a window.</p> 8926 * 8927 * @param action The Runnable that will be executed. 8928 * 8929 * @return Returns true if the Runnable was successfully placed in to the 8930 * message queue. Returns false on failure, usually because the 8931 * looper processing the message queue is exiting. 8932 */ 8933 public boolean post(Runnable action) { 8934 final AttachInfo attachInfo = mAttachInfo; 8935 if (attachInfo != null) { 8936 return attachInfo.mHandler.post(action); 8937 } 8938 // Assume that post will succeed later 8939 ViewRootImpl.getRunQueue().post(action); 8940 return true; 8941 } 8942 8943 /** 8944 * <p>Causes the Runnable to be added to the message queue, to be run 8945 * after the specified amount of time elapses. 8946 * The runnable will be run on the user interface thread.</p> 8947 * 8948 * <p>This method can be invoked from outside of the UI thread 8949 * only when this View is attached to a window.</p> 8950 * 8951 * @param action The Runnable that will be executed. 8952 * @param delayMillis The delay (in milliseconds) until the Runnable 8953 * will be executed. 8954 * 8955 * @return true if the Runnable was successfully placed in to the 8956 * message queue. Returns false on failure, usually because the 8957 * looper processing the message queue is exiting. Note that a 8958 * result of true does not mean the Runnable will be processed -- 8959 * if the looper is quit before the delivery time of the message 8960 * occurs then the message will be dropped. 8961 */ 8962 public boolean postDelayed(Runnable action, long delayMillis) { 8963 final AttachInfo attachInfo = mAttachInfo; 8964 if (attachInfo != null) { 8965 return attachInfo.mHandler.postDelayed(action, delayMillis); 8966 } 8967 // Assume that post will succeed later 8968 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 8969 return true; 8970 } 8971 8972 /** 8973 * <p>Causes the Runnable to execute on the next animation time step. 8974 * The runnable will be run on the user interface thread.</p> 8975 * 8976 * <p>This method can be invoked from outside of the UI thread 8977 * only when this View is attached to a window.</p> 8978 * 8979 * @param action The Runnable that will be executed. 8980 * 8981 * @hide 8982 */ 8983 public void postOnAnimation(Runnable action) { 8984 final AttachInfo attachInfo = mAttachInfo; 8985 if (attachInfo != null) { 8986 attachInfo.mViewRootImpl.mChoreographer.postCallback( 8987 Choreographer.CALLBACK_ANIMATION, action, null); 8988 } else { 8989 // Assume that post will succeed later 8990 ViewRootImpl.getRunQueue().post(action); 8991 } 8992 } 8993 8994 /** 8995 * <p>Causes the Runnable to execute on the next animation time step, 8996 * after the specified amount of time elapses. 8997 * The runnable will be run on the user interface thread.</p> 8998 * 8999 * <p>This method can be invoked from outside of the UI thread 9000 * only when this View is attached to a window.</p> 9001 * 9002 * @param action The Runnable that will be executed. 9003 * @param delayMillis The delay (in milliseconds) until the Runnable 9004 * will be executed. 9005 * 9006 * @hide 9007 */ 9008 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 9009 final AttachInfo attachInfo = mAttachInfo; 9010 if (attachInfo != null) { 9011 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 9012 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 9013 } else { 9014 // Assume that post will succeed later 9015 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 9016 } 9017 } 9018 9019 /** 9020 * <p>Removes the specified Runnable from the message queue.</p> 9021 * 9022 * <p>This method can be invoked from outside of the UI thread 9023 * only when this View is attached to a window.</p> 9024 * 9025 * @param action The Runnable to remove from the message handling queue 9026 * 9027 * @return true if this view could ask the Handler to remove the Runnable, 9028 * false otherwise. When the returned value is true, the Runnable 9029 * may or may not have been actually removed from the message queue 9030 * (for instance, if the Runnable was not in the queue already.) 9031 */ 9032 public boolean removeCallbacks(Runnable action) { 9033 if (action != null) { 9034 final AttachInfo attachInfo = mAttachInfo; 9035 if (attachInfo != null) { 9036 attachInfo.mHandler.removeCallbacks(action); 9037 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 9038 Choreographer.CALLBACK_ANIMATION, action, null); 9039 } else { 9040 // Assume that post will succeed later 9041 ViewRootImpl.getRunQueue().removeCallbacks(action); 9042 } 9043 } 9044 return true; 9045 } 9046 9047 /** 9048 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 9049 * Use this to invalidate the View from a non-UI thread.</p> 9050 * 9051 * <p>This method can be invoked from outside of the UI thread 9052 * only when this View is attached to a window.</p> 9053 * 9054 * @see #invalidate() 9055 */ 9056 public void postInvalidate() { 9057 postInvalidateDelayed(0); 9058 } 9059 9060 /** 9061 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 9062 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 9063 * 9064 * <p>This method can be invoked from outside of the UI thread 9065 * only when this View is attached to a window.</p> 9066 * 9067 * @param left The left coordinate of the rectangle to invalidate. 9068 * @param top The top coordinate of the rectangle to invalidate. 9069 * @param right The right coordinate of the rectangle to invalidate. 9070 * @param bottom The bottom coordinate of the rectangle to invalidate. 9071 * 9072 * @see #invalidate(int, int, int, int) 9073 * @see #invalidate(Rect) 9074 */ 9075 public void postInvalidate(int left, int top, int right, int bottom) { 9076 postInvalidateDelayed(0, left, top, right, bottom); 9077 } 9078 9079 /** 9080 * <p>Cause an invalidate to happen on a subsequent cycle through the event 9081 * loop. Waits for the specified amount of time.</p> 9082 * 9083 * <p>This method can be invoked from outside of the UI thread 9084 * only when this View is attached to a window.</p> 9085 * 9086 * @param delayMilliseconds the duration in milliseconds to delay the 9087 * invalidation by 9088 */ 9089 public void postInvalidateDelayed(long delayMilliseconds) { 9090 // We try only with the AttachInfo because there's no point in invalidating 9091 // if we are not attached to our window 9092 final AttachInfo attachInfo = mAttachInfo; 9093 if (attachInfo != null) { 9094 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 9095 } 9096 } 9097 9098 /** 9099 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 9100 * through the event loop. Waits for the specified amount of time.</p> 9101 * 9102 * <p>This method can be invoked from outside of the UI thread 9103 * only when this View is attached to a window.</p> 9104 * 9105 * @param delayMilliseconds the duration in milliseconds to delay the 9106 * invalidation by 9107 * @param left The left coordinate of the rectangle to invalidate. 9108 * @param top The top coordinate of the rectangle to invalidate. 9109 * @param right The right coordinate of the rectangle to invalidate. 9110 * @param bottom The bottom coordinate of the rectangle to invalidate. 9111 */ 9112 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 9113 int right, int bottom) { 9114 9115 // We try only with the AttachInfo because there's no point in invalidating 9116 // if we are not attached to our window 9117 final AttachInfo attachInfo = mAttachInfo; 9118 if (attachInfo != null) { 9119 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 9120 info.target = this; 9121 info.left = left; 9122 info.top = top; 9123 info.right = right; 9124 info.bottom = bottom; 9125 9126 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 9127 } 9128 } 9129 9130 /** 9131 * <p>Cause an invalidate to happen on the next animation time step, typically the 9132 * next display frame.</p> 9133 * 9134 * <p>This method can be invoked from outside of the UI thread 9135 * only when this View is attached to a window.</p> 9136 * 9137 * @hide 9138 */ 9139 public void postInvalidateOnAnimation() { 9140 // We try only with the AttachInfo because there's no point in invalidating 9141 // if we are not attached to our window 9142 final AttachInfo attachInfo = mAttachInfo; 9143 if (attachInfo != null) { 9144 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 9145 } 9146 } 9147 9148 /** 9149 * <p>Cause an invalidate of the specified area to happen on the next animation 9150 * time step, typically the next display frame.</p> 9151 * 9152 * <p>This method can be invoked from outside of the UI thread 9153 * only when this View is attached to a window.</p> 9154 * 9155 * @param left The left coordinate of the rectangle to invalidate. 9156 * @param top The top coordinate of the rectangle to invalidate. 9157 * @param right The right coordinate of the rectangle to invalidate. 9158 * @param bottom The bottom coordinate of the rectangle to invalidate. 9159 * 9160 * @hide 9161 */ 9162 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 9163 // We try only with the AttachInfo because there's no point in invalidating 9164 // if we are not attached to our window 9165 final AttachInfo attachInfo = mAttachInfo; 9166 if (attachInfo != null) { 9167 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 9168 info.target = this; 9169 info.left = left; 9170 info.top = top; 9171 info.right = right; 9172 info.bottom = bottom; 9173 9174 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 9175 } 9176 } 9177 9178 /** 9179 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 9180 * This event is sent at most once every 9181 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 9182 */ 9183 private void postSendViewScrolledAccessibilityEventCallback() { 9184 if (mSendViewScrolledAccessibilityEvent == null) { 9185 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 9186 } 9187 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 9188 mSendViewScrolledAccessibilityEvent.mIsPending = true; 9189 postDelayed(mSendViewScrolledAccessibilityEvent, 9190 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 9191 } 9192 } 9193 9194 /** 9195 * Called by a parent to request that a child update its values for mScrollX 9196 * and mScrollY if necessary. This will typically be done if the child is 9197 * animating a scroll using a {@link android.widget.Scroller Scroller} 9198 * object. 9199 */ 9200 public void computeScroll() { 9201 } 9202 9203 /** 9204 * <p>Indicate whether the horizontal edges are faded when the view is 9205 * scrolled horizontally.</p> 9206 * 9207 * @return true if the horizontal edges should are faded on scroll, false 9208 * otherwise 9209 * 9210 * @see #setHorizontalFadingEdgeEnabled(boolean) 9211 * @attr ref android.R.styleable#View_requiresFadingEdge 9212 */ 9213 public boolean isHorizontalFadingEdgeEnabled() { 9214 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 9215 } 9216 9217 /** 9218 * <p>Define whether the horizontal edges should be faded when this view 9219 * is scrolled horizontally.</p> 9220 * 9221 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 9222 * be faded when the view is scrolled 9223 * horizontally 9224 * 9225 * @see #isHorizontalFadingEdgeEnabled() 9226 * @attr ref android.R.styleable#View_requiresFadingEdge 9227 */ 9228 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 9229 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 9230 if (horizontalFadingEdgeEnabled) { 9231 initScrollCache(); 9232 } 9233 9234 mViewFlags ^= FADING_EDGE_HORIZONTAL; 9235 } 9236 } 9237 9238 /** 9239 * <p>Indicate whether the vertical edges are faded when the view is 9240 * scrolled horizontally.</p> 9241 * 9242 * @return true if the vertical edges should are faded on scroll, false 9243 * otherwise 9244 * 9245 * @see #setVerticalFadingEdgeEnabled(boolean) 9246 * @attr ref android.R.styleable#View_requiresFadingEdge 9247 */ 9248 public boolean isVerticalFadingEdgeEnabled() { 9249 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 9250 } 9251 9252 /** 9253 * <p>Define whether the vertical edges should be faded when this view 9254 * is scrolled vertically.</p> 9255 * 9256 * @param verticalFadingEdgeEnabled true if the vertical edges should 9257 * be faded when the view is scrolled 9258 * vertically 9259 * 9260 * @see #isVerticalFadingEdgeEnabled() 9261 * @attr ref android.R.styleable#View_requiresFadingEdge 9262 */ 9263 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 9264 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 9265 if (verticalFadingEdgeEnabled) { 9266 initScrollCache(); 9267 } 9268 9269 mViewFlags ^= FADING_EDGE_VERTICAL; 9270 } 9271 } 9272 9273 /** 9274 * Returns the strength, or intensity, of the top faded edge. The strength is 9275 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 9276 * returns 0.0 or 1.0 but no value in between. 9277 * 9278 * Subclasses should override this method to provide a smoother fade transition 9279 * when scrolling occurs. 9280 * 9281 * @return the intensity of the top fade as a float between 0.0f and 1.0f 9282 */ 9283 protected float getTopFadingEdgeStrength() { 9284 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 9285 } 9286 9287 /** 9288 * Returns the strength, or intensity, of the bottom faded edge. The strength is 9289 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 9290 * returns 0.0 or 1.0 but no value in between. 9291 * 9292 * Subclasses should override this method to provide a smoother fade transition 9293 * when scrolling occurs. 9294 * 9295 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 9296 */ 9297 protected float getBottomFadingEdgeStrength() { 9298 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 9299 computeVerticalScrollRange() ? 1.0f : 0.0f; 9300 } 9301 9302 /** 9303 * Returns the strength, or intensity, of the left faded edge. The strength is 9304 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 9305 * returns 0.0 or 1.0 but no value in between. 9306 * 9307 * Subclasses should override this method to provide a smoother fade transition 9308 * when scrolling occurs. 9309 * 9310 * @return the intensity of the left fade as a float between 0.0f and 1.0f 9311 */ 9312 protected float getLeftFadingEdgeStrength() { 9313 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 9314 } 9315 9316 /** 9317 * Returns the strength, or intensity, of the right faded edge. The strength is 9318 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 9319 * returns 0.0 or 1.0 but no value in between. 9320 * 9321 * Subclasses should override this method to provide a smoother fade transition 9322 * when scrolling occurs. 9323 * 9324 * @return the intensity of the right fade as a float between 0.0f and 1.0f 9325 */ 9326 protected float getRightFadingEdgeStrength() { 9327 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 9328 computeHorizontalScrollRange() ? 1.0f : 0.0f; 9329 } 9330 9331 /** 9332 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 9333 * scrollbar is not drawn by default.</p> 9334 * 9335 * @return true if the horizontal scrollbar should be painted, false 9336 * otherwise 9337 * 9338 * @see #setHorizontalScrollBarEnabled(boolean) 9339 */ 9340 public boolean isHorizontalScrollBarEnabled() { 9341 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 9342 } 9343 9344 /** 9345 * <p>Define whether the horizontal scrollbar should be drawn or not. The 9346 * scrollbar is not drawn by default.</p> 9347 * 9348 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 9349 * be painted 9350 * 9351 * @see #isHorizontalScrollBarEnabled() 9352 */ 9353 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 9354 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 9355 mViewFlags ^= SCROLLBARS_HORIZONTAL; 9356 computeOpaqueFlags(); 9357 resolvePadding(); 9358 } 9359 } 9360 9361 /** 9362 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 9363 * scrollbar is not drawn by default.</p> 9364 * 9365 * @return true if the vertical scrollbar should be painted, false 9366 * otherwise 9367 * 9368 * @see #setVerticalScrollBarEnabled(boolean) 9369 */ 9370 public boolean isVerticalScrollBarEnabled() { 9371 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 9372 } 9373 9374 /** 9375 * <p>Define whether the vertical scrollbar should be drawn or not. The 9376 * scrollbar is not drawn by default.</p> 9377 * 9378 * @param verticalScrollBarEnabled true if the vertical scrollbar should 9379 * be painted 9380 * 9381 * @see #isVerticalScrollBarEnabled() 9382 */ 9383 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 9384 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 9385 mViewFlags ^= SCROLLBARS_VERTICAL; 9386 computeOpaqueFlags(); 9387 resolvePadding(); 9388 } 9389 } 9390 9391 /** 9392 * @hide 9393 */ 9394 protected void recomputePadding() { 9395 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 9396 } 9397 9398 /** 9399 * Define whether scrollbars will fade when the view is not scrolling. 9400 * 9401 * @param fadeScrollbars wheter to enable fading 9402 * 9403 */ 9404 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 9405 initScrollCache(); 9406 final ScrollabilityCache scrollabilityCache = mScrollCache; 9407 scrollabilityCache.fadeScrollBars = fadeScrollbars; 9408 if (fadeScrollbars) { 9409 scrollabilityCache.state = ScrollabilityCache.OFF; 9410 } else { 9411 scrollabilityCache.state = ScrollabilityCache.ON; 9412 } 9413 } 9414 9415 /** 9416 * 9417 * Returns true if scrollbars will fade when this view is not scrolling 9418 * 9419 * @return true if scrollbar fading is enabled 9420 */ 9421 public boolean isScrollbarFadingEnabled() { 9422 return mScrollCache != null && mScrollCache.fadeScrollBars; 9423 } 9424 9425 /** 9426 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 9427 * inset. When inset, they add to the padding of the view. And the scrollbars 9428 * can be drawn inside the padding area or on the edge of the view. For example, 9429 * if a view has a background drawable and you want to draw the scrollbars 9430 * inside the padding specified by the drawable, you can use 9431 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 9432 * appear at the edge of the view, ignoring the padding, then you can use 9433 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 9434 * @param style the style of the scrollbars. Should be one of 9435 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 9436 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 9437 * @see #SCROLLBARS_INSIDE_OVERLAY 9438 * @see #SCROLLBARS_INSIDE_INSET 9439 * @see #SCROLLBARS_OUTSIDE_OVERLAY 9440 * @see #SCROLLBARS_OUTSIDE_INSET 9441 */ 9442 public void setScrollBarStyle(int style) { 9443 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 9444 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 9445 computeOpaqueFlags(); 9446 resolvePadding(); 9447 } 9448 } 9449 9450 /** 9451 * <p>Returns the current scrollbar style.</p> 9452 * @return the current scrollbar style 9453 * @see #SCROLLBARS_INSIDE_OVERLAY 9454 * @see #SCROLLBARS_INSIDE_INSET 9455 * @see #SCROLLBARS_OUTSIDE_OVERLAY 9456 * @see #SCROLLBARS_OUTSIDE_INSET 9457 */ 9458 @ViewDebug.ExportedProperty(mapping = { 9459 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 9460 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 9461 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 9462 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 9463 }) 9464 public int getScrollBarStyle() { 9465 return mViewFlags & SCROLLBARS_STYLE_MASK; 9466 } 9467 9468 /** 9469 * <p>Compute the horizontal range that the horizontal scrollbar 9470 * represents.</p> 9471 * 9472 * <p>The range is expressed in arbitrary units that must be the same as the 9473 * units used by {@link #computeHorizontalScrollExtent()} and 9474 * {@link #computeHorizontalScrollOffset()}.</p> 9475 * 9476 * <p>The default range is the drawing width of this view.</p> 9477 * 9478 * @return the total horizontal range represented by the horizontal 9479 * scrollbar 9480 * 9481 * @see #computeHorizontalScrollExtent() 9482 * @see #computeHorizontalScrollOffset() 9483 * @see android.widget.ScrollBarDrawable 9484 */ 9485 protected int computeHorizontalScrollRange() { 9486 return getWidth(); 9487 } 9488 9489 /** 9490 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 9491 * within the horizontal range. This value is used to compute the position 9492 * of the thumb within the scrollbar's track.</p> 9493 * 9494 * <p>The range is expressed in arbitrary units that must be the same as the 9495 * units used by {@link #computeHorizontalScrollRange()} and 9496 * {@link #computeHorizontalScrollExtent()}.</p> 9497 * 9498 * <p>The default offset is the scroll offset of this view.</p> 9499 * 9500 * @return the horizontal offset of the scrollbar's thumb 9501 * 9502 * @see #computeHorizontalScrollRange() 9503 * @see #computeHorizontalScrollExtent() 9504 * @see android.widget.ScrollBarDrawable 9505 */ 9506 protected int computeHorizontalScrollOffset() { 9507 return mScrollX; 9508 } 9509 9510 /** 9511 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 9512 * within the horizontal range. This value is used to compute the length 9513 * of the thumb within the scrollbar's track.</p> 9514 * 9515 * <p>The range is expressed in arbitrary units that must be the same as the 9516 * units used by {@link #computeHorizontalScrollRange()} and 9517 * {@link #computeHorizontalScrollOffset()}.</p> 9518 * 9519 * <p>The default extent is the drawing width of this view.</p> 9520 * 9521 * @return the horizontal extent of the scrollbar's thumb 9522 * 9523 * @see #computeHorizontalScrollRange() 9524 * @see #computeHorizontalScrollOffset() 9525 * @see android.widget.ScrollBarDrawable 9526 */ 9527 protected int computeHorizontalScrollExtent() { 9528 return getWidth(); 9529 } 9530 9531 /** 9532 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 9533 * 9534 * <p>The range is expressed in arbitrary units that must be the same as the 9535 * units used by {@link #computeVerticalScrollExtent()} and 9536 * {@link #computeVerticalScrollOffset()}.</p> 9537 * 9538 * @return the total vertical range represented by the vertical scrollbar 9539 * 9540 * <p>The default range is the drawing height of this view.</p> 9541 * 9542 * @see #computeVerticalScrollExtent() 9543 * @see #computeVerticalScrollOffset() 9544 * @see android.widget.ScrollBarDrawable 9545 */ 9546 protected int computeVerticalScrollRange() { 9547 return getHeight(); 9548 } 9549 9550 /** 9551 * <p>Compute the vertical offset of the vertical scrollbar's thumb 9552 * within the horizontal range. This value is used to compute the position 9553 * of the thumb within the scrollbar's track.</p> 9554 * 9555 * <p>The range is expressed in arbitrary units that must be the same as the 9556 * units used by {@link #computeVerticalScrollRange()} and 9557 * {@link #computeVerticalScrollExtent()}.</p> 9558 * 9559 * <p>The default offset is the scroll offset of this view.</p> 9560 * 9561 * @return the vertical offset of the scrollbar's thumb 9562 * 9563 * @see #computeVerticalScrollRange() 9564 * @see #computeVerticalScrollExtent() 9565 * @see android.widget.ScrollBarDrawable 9566 */ 9567 protected int computeVerticalScrollOffset() { 9568 return mScrollY; 9569 } 9570 9571 /** 9572 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 9573 * within the vertical range. This value is used to compute the length 9574 * of the thumb within the scrollbar's track.</p> 9575 * 9576 * <p>The range is expressed in arbitrary units that must be the same as the 9577 * units used by {@link #computeVerticalScrollRange()} and 9578 * {@link #computeVerticalScrollOffset()}.</p> 9579 * 9580 * <p>The default extent is the drawing height of this view.</p> 9581 * 9582 * @return the vertical extent of the scrollbar's thumb 9583 * 9584 * @see #computeVerticalScrollRange() 9585 * @see #computeVerticalScrollOffset() 9586 * @see android.widget.ScrollBarDrawable 9587 */ 9588 protected int computeVerticalScrollExtent() { 9589 return getHeight(); 9590 } 9591 9592 /** 9593 * Check if this view can be scrolled horizontally in a certain direction. 9594 * 9595 * @param direction Negative to check scrolling left, positive to check scrolling right. 9596 * @return true if this view can be scrolled in the specified direction, false otherwise. 9597 */ 9598 public boolean canScrollHorizontally(int direction) { 9599 final int offset = computeHorizontalScrollOffset(); 9600 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 9601 if (range == 0) return false; 9602 if (direction < 0) { 9603 return offset > 0; 9604 } else { 9605 return offset < range - 1; 9606 } 9607 } 9608 9609 /** 9610 * Check if this view can be scrolled vertically in a certain direction. 9611 * 9612 * @param direction Negative to check scrolling up, positive to check scrolling down. 9613 * @return true if this view can be scrolled in the specified direction, false otherwise. 9614 */ 9615 public boolean canScrollVertically(int direction) { 9616 final int offset = computeVerticalScrollOffset(); 9617 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 9618 if (range == 0) return false; 9619 if (direction < 0) { 9620 return offset > 0; 9621 } else { 9622 return offset < range - 1; 9623 } 9624 } 9625 9626 /** 9627 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 9628 * scrollbars are painted only if they have been awakened first.</p> 9629 * 9630 * @param canvas the canvas on which to draw the scrollbars 9631 * 9632 * @see #awakenScrollBars(int) 9633 */ 9634 protected final void onDrawScrollBars(Canvas canvas) { 9635 // scrollbars are drawn only when the animation is running 9636 final ScrollabilityCache cache = mScrollCache; 9637 if (cache != null) { 9638 9639 int state = cache.state; 9640 9641 if (state == ScrollabilityCache.OFF) { 9642 return; 9643 } 9644 9645 boolean invalidate = false; 9646 9647 if (state == ScrollabilityCache.FADING) { 9648 // We're fading -- get our fade interpolation 9649 if (cache.interpolatorValues == null) { 9650 cache.interpolatorValues = new float[1]; 9651 } 9652 9653 float[] values = cache.interpolatorValues; 9654 9655 // Stops the animation if we're done 9656 if (cache.scrollBarInterpolator.timeToValues(values) == 9657 Interpolator.Result.FREEZE_END) { 9658 cache.state = ScrollabilityCache.OFF; 9659 } else { 9660 cache.scrollBar.setAlpha(Math.round(values[0])); 9661 } 9662 9663 // This will make the scroll bars inval themselves after 9664 // drawing. We only want this when we're fading so that 9665 // we prevent excessive redraws 9666 invalidate = true; 9667 } else { 9668 // We're just on -- but we may have been fading before so 9669 // reset alpha 9670 cache.scrollBar.setAlpha(255); 9671 } 9672 9673 9674 final int viewFlags = mViewFlags; 9675 9676 final boolean drawHorizontalScrollBar = 9677 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 9678 final boolean drawVerticalScrollBar = 9679 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 9680 && !isVerticalScrollBarHidden(); 9681 9682 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 9683 final int width = mRight - mLeft; 9684 final int height = mBottom - mTop; 9685 9686 final ScrollBarDrawable scrollBar = cache.scrollBar; 9687 9688 final int scrollX = mScrollX; 9689 final int scrollY = mScrollY; 9690 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 9691 9692 int left, top, right, bottom; 9693 9694 if (drawHorizontalScrollBar) { 9695 int size = scrollBar.getSize(false); 9696 if (size <= 0) { 9697 size = cache.scrollBarSize; 9698 } 9699 9700 scrollBar.setParameters(computeHorizontalScrollRange(), 9701 computeHorizontalScrollOffset(), 9702 computeHorizontalScrollExtent(), false); 9703 final int verticalScrollBarGap = drawVerticalScrollBar ? 9704 getVerticalScrollbarWidth() : 0; 9705 top = scrollY + height - size - (mUserPaddingBottom & inside); 9706 left = scrollX + (mPaddingLeft & inside); 9707 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 9708 bottom = top + size; 9709 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 9710 if (invalidate) { 9711 invalidate(left, top, right, bottom); 9712 } 9713 } 9714 9715 if (drawVerticalScrollBar) { 9716 int size = scrollBar.getSize(true); 9717 if (size <= 0) { 9718 size = cache.scrollBarSize; 9719 } 9720 9721 scrollBar.setParameters(computeVerticalScrollRange(), 9722 computeVerticalScrollOffset(), 9723 computeVerticalScrollExtent(), true); 9724 switch (mVerticalScrollbarPosition) { 9725 default: 9726 case SCROLLBAR_POSITION_DEFAULT: 9727 case SCROLLBAR_POSITION_RIGHT: 9728 left = scrollX + width - size - (mUserPaddingRight & inside); 9729 break; 9730 case SCROLLBAR_POSITION_LEFT: 9731 left = scrollX + (mUserPaddingLeft & inside); 9732 break; 9733 } 9734 top = scrollY + (mPaddingTop & inside); 9735 right = left + size; 9736 bottom = scrollY + height - (mUserPaddingBottom & inside); 9737 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 9738 if (invalidate) { 9739 invalidate(left, top, right, bottom); 9740 } 9741 } 9742 } 9743 } 9744 } 9745 9746 /** 9747 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 9748 * FastScroller is visible. 9749 * @return whether to temporarily hide the vertical scrollbar 9750 * @hide 9751 */ 9752 protected boolean isVerticalScrollBarHidden() { 9753 return false; 9754 } 9755 9756 /** 9757 * <p>Draw the horizontal scrollbar if 9758 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 9759 * 9760 * @param canvas the canvas on which to draw the scrollbar 9761 * @param scrollBar the scrollbar's drawable 9762 * 9763 * @see #isHorizontalScrollBarEnabled() 9764 * @see #computeHorizontalScrollRange() 9765 * @see #computeHorizontalScrollExtent() 9766 * @see #computeHorizontalScrollOffset() 9767 * @see android.widget.ScrollBarDrawable 9768 * @hide 9769 */ 9770 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 9771 int l, int t, int r, int b) { 9772 scrollBar.setBounds(l, t, r, b); 9773 scrollBar.draw(canvas); 9774 } 9775 9776 /** 9777 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 9778 * returns true.</p> 9779 * 9780 * @param canvas the canvas on which to draw the scrollbar 9781 * @param scrollBar the scrollbar's drawable 9782 * 9783 * @see #isVerticalScrollBarEnabled() 9784 * @see #computeVerticalScrollRange() 9785 * @see #computeVerticalScrollExtent() 9786 * @see #computeVerticalScrollOffset() 9787 * @see android.widget.ScrollBarDrawable 9788 * @hide 9789 */ 9790 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 9791 int l, int t, int r, int b) { 9792 scrollBar.setBounds(l, t, r, b); 9793 scrollBar.draw(canvas); 9794 } 9795 9796 /** 9797 * Implement this to do your drawing. 9798 * 9799 * @param canvas the canvas on which the background will be drawn 9800 */ 9801 protected void onDraw(Canvas canvas) { 9802 } 9803 9804 /* 9805 * Caller is responsible for calling requestLayout if necessary. 9806 * (This allows addViewInLayout to not request a new layout.) 9807 */ 9808 void assignParent(ViewParent parent) { 9809 if (mParent == null) { 9810 mParent = parent; 9811 } else if (parent == null) { 9812 mParent = null; 9813 } else { 9814 throw new RuntimeException("view " + this + " being added, but" 9815 + " it already has a parent"); 9816 } 9817 } 9818 9819 /** 9820 * This is called when the view is attached to a window. At this point it 9821 * has a Surface and will start drawing. Note that this function is 9822 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 9823 * however it may be called any time before the first onDraw -- including 9824 * before or after {@link #onMeasure(int, int)}. 9825 * 9826 * @see #onDetachedFromWindow() 9827 */ 9828 protected void onAttachedToWindow() { 9829 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 9830 mParent.requestTransparentRegion(this); 9831 } 9832 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 9833 initialAwakenScrollBars(); 9834 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH; 9835 } 9836 jumpDrawablesToCurrentState(); 9837 // Order is important here: LayoutDirection MUST be resolved before Padding 9838 // and TextDirection 9839 resolveLayoutDirection(); 9840 resolvePadding(); 9841 resolveTextDirection(); 9842 if (isFocused()) { 9843 InputMethodManager imm = InputMethodManager.peekInstance(); 9844 imm.focusIn(this); 9845 } 9846 } 9847 9848 /** 9849 * @see #onScreenStateChanged(int) 9850 */ 9851 void dispatchScreenStateChanged(int screenState) { 9852 onScreenStateChanged(screenState); 9853 } 9854 9855 /** 9856 * This method is called whenever the state of the screen this view is 9857 * attached to changes. A state change will usually occurs when the screen 9858 * turns on or off (whether it happens automatically or the user does it 9859 * manually.) 9860 * 9861 * @param screenState The new state of the screen. Can be either 9862 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 9863 */ 9864 public void onScreenStateChanged(int screenState) { 9865 } 9866 9867 /** 9868 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 9869 * that the parent directionality can and will be resolved before its children. 9870 * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done. 9871 */ 9872 public void resolveLayoutDirection() { 9873 // Clear any previous layout direction resolution 9874 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK; 9875 9876 // Set resolved depending on layout direction 9877 switch (getLayoutDirection()) { 9878 case LAYOUT_DIRECTION_INHERIT: 9879 // If this is root view, no need to look at parent's layout dir. 9880 if (canResolveLayoutDirection()) { 9881 ViewGroup viewGroup = ((ViewGroup) mParent); 9882 9883 if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 9884 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9885 } 9886 } else { 9887 // Nothing to do, LTR by default 9888 } 9889 break; 9890 case LAYOUT_DIRECTION_RTL: 9891 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9892 break; 9893 case LAYOUT_DIRECTION_LOCALE: 9894 if(isLayoutDirectionRtl(Locale.getDefault())) { 9895 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9896 } 9897 break; 9898 default: 9899 // Nothing to do, LTR by default 9900 } 9901 9902 // Set to resolved 9903 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED; 9904 onResolvedLayoutDirectionChanged(); 9905 // Resolve padding 9906 resolvePadding(); 9907 } 9908 9909 /** 9910 * Called when layout direction has been resolved. 9911 * 9912 * The default implementation does nothing. 9913 */ 9914 public void onResolvedLayoutDirectionChanged() { 9915 } 9916 9917 /** 9918 * Resolve padding depending on layout direction. 9919 */ 9920 public void resolvePadding() { 9921 // If the user specified the absolute padding (either with android:padding or 9922 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 9923 // use the default padding or the padding from the background drawable 9924 // (stored at this point in mPadding*) 9925 int resolvedLayoutDirection = getResolvedLayoutDirection(); 9926 switch (resolvedLayoutDirection) { 9927 case LAYOUT_DIRECTION_RTL: 9928 // Start user padding override Right user padding. Otherwise, if Right user 9929 // padding is not defined, use the default Right padding. If Right user padding 9930 // is defined, just use it. 9931 if (mUserPaddingStart >= 0) { 9932 mUserPaddingRight = mUserPaddingStart; 9933 } else if (mUserPaddingRight < 0) { 9934 mUserPaddingRight = mPaddingRight; 9935 } 9936 if (mUserPaddingEnd >= 0) { 9937 mUserPaddingLeft = mUserPaddingEnd; 9938 } else if (mUserPaddingLeft < 0) { 9939 mUserPaddingLeft = mPaddingLeft; 9940 } 9941 break; 9942 case LAYOUT_DIRECTION_LTR: 9943 default: 9944 // Start user padding override Left user padding. Otherwise, if Left user 9945 // padding is not defined, use the default left padding. If Left user padding 9946 // is defined, just use it. 9947 if (mUserPaddingStart >= 0) { 9948 mUserPaddingLeft = mUserPaddingStart; 9949 } else if (mUserPaddingLeft < 0) { 9950 mUserPaddingLeft = mPaddingLeft; 9951 } 9952 if (mUserPaddingEnd >= 0) { 9953 mUserPaddingRight = mUserPaddingEnd; 9954 } else if (mUserPaddingRight < 0) { 9955 mUserPaddingRight = mPaddingRight; 9956 } 9957 } 9958 9959 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 9960 9961 if(isPaddingRelative()) { 9962 setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom); 9963 } else { 9964 recomputePadding(); 9965 } 9966 onPaddingChanged(resolvedLayoutDirection); 9967 } 9968 9969 /** 9970 * Resolve padding depending on the layout direction. Subclasses that care about 9971 * padding resolution should override this method. The default implementation does 9972 * nothing. 9973 * 9974 * @param layoutDirection the direction of the layout 9975 * 9976 * @see {@link #LAYOUT_DIRECTION_LTR} 9977 * @see {@link #LAYOUT_DIRECTION_RTL} 9978 */ 9979 public void onPaddingChanged(int layoutDirection) { 9980 } 9981 9982 /** 9983 * Check if layout direction resolution can be done. 9984 * 9985 * @return true if layout direction resolution can be done otherwise return false. 9986 */ 9987 public boolean canResolveLayoutDirection() { 9988 switch (getLayoutDirection()) { 9989 case LAYOUT_DIRECTION_INHERIT: 9990 return (mParent != null) && (mParent instanceof ViewGroup); 9991 default: 9992 return true; 9993 } 9994 } 9995 9996 /** 9997 * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset} 9998 * when reset is done. 9999 */ 10000 public void resetResolvedLayoutDirection() { 10001 // Reset the current resolved bits 10002 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK; 10003 onResolvedLayoutDirectionReset(); 10004 // Reset also the text direction 10005 resetResolvedTextDirection(); 10006 } 10007 10008 /** 10009 * Called during reset of resolved layout direction. 10010 * 10011 * Subclasses need to override this method to clear cached information that depends on the 10012 * resolved layout direction, or to inform child views that inherit their layout direction. 10013 * 10014 * The default implementation does nothing. 10015 */ 10016 public void onResolvedLayoutDirectionReset() { 10017 } 10018 10019 /** 10020 * Check if a Locale uses an RTL script. 10021 * 10022 * @param locale Locale to check 10023 * @return true if the Locale uses an RTL script. 10024 */ 10025 protected static boolean isLayoutDirectionRtl(Locale locale) { 10026 return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale)); 10027 } 10028 10029 /** 10030 * This is called when the view is detached from a window. At this point it 10031 * no longer has a surface for drawing. 10032 * 10033 * @see #onAttachedToWindow() 10034 */ 10035 protected void onDetachedFromWindow() { 10036 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 10037 10038 removeUnsetPressCallback(); 10039 removeLongPressCallback(); 10040 removePerformClickCallback(); 10041 removeSendViewScrolledAccessibilityEventCallback(); 10042 10043 destroyDrawingCache(); 10044 10045 destroyLayer(false); 10046 10047 if (mAttachInfo != null) { 10048 if (mDisplayList != null) { 10049 mAttachInfo.mViewRootImpl.invalidateDisplayList(mDisplayList); 10050 } 10051 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 10052 } else { 10053 if (mDisplayList != null) { 10054 // Should never happen 10055 mDisplayList.invalidate(); 10056 } 10057 } 10058 10059 mCurrentAnimation = null; 10060 10061 resetResolvedLayoutDirection(); 10062 } 10063 10064 /** 10065 * @return The number of times this view has been attached to a window 10066 */ 10067 protected int getWindowAttachCount() { 10068 return mWindowAttachCount; 10069 } 10070 10071 /** 10072 * Retrieve a unique token identifying the window this view is attached to. 10073 * @return Return the window's token for use in 10074 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 10075 */ 10076 public IBinder getWindowToken() { 10077 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 10078 } 10079 10080 /** 10081 * Retrieve a unique token identifying the top-level "real" window of 10082 * the window that this view is attached to. That is, this is like 10083 * {@link #getWindowToken}, except if the window this view in is a panel 10084 * window (attached to another containing window), then the token of 10085 * the containing window is returned instead. 10086 * 10087 * @return Returns the associated window token, either 10088 * {@link #getWindowToken()} or the containing window's token. 10089 */ 10090 public IBinder getApplicationWindowToken() { 10091 AttachInfo ai = mAttachInfo; 10092 if (ai != null) { 10093 IBinder appWindowToken = ai.mPanelParentWindowToken; 10094 if (appWindowToken == null) { 10095 appWindowToken = ai.mWindowToken; 10096 } 10097 return appWindowToken; 10098 } 10099 return null; 10100 } 10101 10102 /** 10103 * Retrieve private session object this view hierarchy is using to 10104 * communicate with the window manager. 10105 * @return the session object to communicate with the window manager 10106 */ 10107 /*package*/ IWindowSession getWindowSession() { 10108 return mAttachInfo != null ? mAttachInfo.mSession : null; 10109 } 10110 10111 /** 10112 * @param info the {@link android.view.View.AttachInfo} to associated with 10113 * this view 10114 */ 10115 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 10116 //System.out.println("Attached! " + this); 10117 mAttachInfo = info; 10118 mWindowAttachCount++; 10119 // We will need to evaluate the drawable state at least once. 10120 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 10121 if (mFloatingTreeObserver != null) { 10122 info.mTreeObserver.merge(mFloatingTreeObserver); 10123 mFloatingTreeObserver = null; 10124 } 10125 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 10126 mAttachInfo.mScrollContainers.add(this); 10127 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 10128 } 10129 performCollectViewAttributes(visibility); 10130 onAttachedToWindow(); 10131 10132 ListenerInfo li = mListenerInfo; 10133 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 10134 li != null ? li.mOnAttachStateChangeListeners : null; 10135 if (listeners != null && listeners.size() > 0) { 10136 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 10137 // perform the dispatching. The iterator is a safe guard against listeners that 10138 // could mutate the list by calling the various add/remove methods. This prevents 10139 // the array from being modified while we iterate it. 10140 for (OnAttachStateChangeListener listener : listeners) { 10141 listener.onViewAttachedToWindow(this); 10142 } 10143 } 10144 10145 int vis = info.mWindowVisibility; 10146 if (vis != GONE) { 10147 onWindowVisibilityChanged(vis); 10148 } 10149 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 10150 // If nobody has evaluated the drawable state yet, then do it now. 10151 refreshDrawableState(); 10152 } 10153 } 10154 10155 void dispatchDetachedFromWindow() { 10156 AttachInfo info = mAttachInfo; 10157 if (info != null) { 10158 int vis = info.mWindowVisibility; 10159 if (vis != GONE) { 10160 onWindowVisibilityChanged(GONE); 10161 } 10162 } 10163 10164 onDetachedFromWindow(); 10165 10166 ListenerInfo li = mListenerInfo; 10167 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 10168 li != null ? li.mOnAttachStateChangeListeners : null; 10169 if (listeners != null && listeners.size() > 0) { 10170 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 10171 // perform the dispatching. The iterator is a safe guard against listeners that 10172 // could mutate the list by calling the various add/remove methods. This prevents 10173 // the array from being modified while we iterate it. 10174 for (OnAttachStateChangeListener listener : listeners) { 10175 listener.onViewDetachedFromWindow(this); 10176 } 10177 } 10178 10179 if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) { 10180 mAttachInfo.mScrollContainers.remove(this); 10181 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 10182 } 10183 10184 mAttachInfo = null; 10185 } 10186 10187 /** 10188 * Store this view hierarchy's frozen state into the given container. 10189 * 10190 * @param container The SparseArray in which to save the view's state. 10191 * 10192 * @see #restoreHierarchyState(android.util.SparseArray) 10193 * @see #dispatchSaveInstanceState(android.util.SparseArray) 10194 * @see #onSaveInstanceState() 10195 */ 10196 public void saveHierarchyState(SparseArray<Parcelable> container) { 10197 dispatchSaveInstanceState(container); 10198 } 10199 10200 /** 10201 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 10202 * this view and its children. May be overridden to modify how freezing happens to a 10203 * view's children; for example, some views may want to not store state for their children. 10204 * 10205 * @param container The SparseArray in which to save the view's state. 10206 * 10207 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 10208 * @see #saveHierarchyState(android.util.SparseArray) 10209 * @see #onSaveInstanceState() 10210 */ 10211 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 10212 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 10213 mPrivateFlags &= ~SAVE_STATE_CALLED; 10214 Parcelable state = onSaveInstanceState(); 10215 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 10216 throw new IllegalStateException( 10217 "Derived class did not call super.onSaveInstanceState()"); 10218 } 10219 if (state != null) { 10220 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 10221 // + ": " + state); 10222 container.put(mID, state); 10223 } 10224 } 10225 } 10226 10227 /** 10228 * Hook allowing a view to generate a representation of its internal state 10229 * that can later be used to create a new instance with that same state. 10230 * This state should only contain information that is not persistent or can 10231 * not be reconstructed later. For example, you will never store your 10232 * current position on screen because that will be computed again when a 10233 * new instance of the view is placed in its view hierarchy. 10234 * <p> 10235 * Some examples of things you may store here: the current cursor position 10236 * in a text view (but usually not the text itself since that is stored in a 10237 * content provider or other persistent storage), the currently selected 10238 * item in a list view. 10239 * 10240 * @return Returns a Parcelable object containing the view's current dynamic 10241 * state, or null if there is nothing interesting to save. The 10242 * default implementation returns null. 10243 * @see #onRestoreInstanceState(android.os.Parcelable) 10244 * @see #saveHierarchyState(android.util.SparseArray) 10245 * @see #dispatchSaveInstanceState(android.util.SparseArray) 10246 * @see #setSaveEnabled(boolean) 10247 */ 10248 protected Parcelable onSaveInstanceState() { 10249 mPrivateFlags |= SAVE_STATE_CALLED; 10250 return BaseSavedState.EMPTY_STATE; 10251 } 10252 10253 /** 10254 * Restore this view hierarchy's frozen state from the given container. 10255 * 10256 * @param container The SparseArray which holds previously frozen states. 10257 * 10258 * @see #saveHierarchyState(android.util.SparseArray) 10259 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 10260 * @see #onRestoreInstanceState(android.os.Parcelable) 10261 */ 10262 public void restoreHierarchyState(SparseArray<Parcelable> container) { 10263 dispatchRestoreInstanceState(container); 10264 } 10265 10266 /** 10267 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 10268 * state for this view and its children. May be overridden to modify how restoring 10269 * happens to a view's children; for example, some views may want to not store state 10270 * for their children. 10271 * 10272 * @param container The SparseArray which holds previously saved state. 10273 * 10274 * @see #dispatchSaveInstanceState(android.util.SparseArray) 10275 * @see #restoreHierarchyState(android.util.SparseArray) 10276 * @see #onRestoreInstanceState(android.os.Parcelable) 10277 */ 10278 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 10279 if (mID != NO_ID) { 10280 Parcelable state = container.get(mID); 10281 if (state != null) { 10282 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 10283 // + ": " + state); 10284 mPrivateFlags &= ~SAVE_STATE_CALLED; 10285 onRestoreInstanceState(state); 10286 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 10287 throw new IllegalStateException( 10288 "Derived class did not call super.onRestoreInstanceState()"); 10289 } 10290 } 10291 } 10292 } 10293 10294 /** 10295 * Hook allowing a view to re-apply a representation of its internal state that had previously 10296 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 10297 * null state. 10298 * 10299 * @param state The frozen state that had previously been returned by 10300 * {@link #onSaveInstanceState}. 10301 * 10302 * @see #onSaveInstanceState() 10303 * @see #restoreHierarchyState(android.util.SparseArray) 10304 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 10305 */ 10306 protected void onRestoreInstanceState(Parcelable state) { 10307 mPrivateFlags |= SAVE_STATE_CALLED; 10308 if (state != BaseSavedState.EMPTY_STATE && state != null) { 10309 throw new IllegalArgumentException("Wrong state class, expecting View State but " 10310 + "received " + state.getClass().toString() + " instead. This usually happens " 10311 + "when two views of different type have the same id in the same hierarchy. " 10312 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 10313 + "other views do not use the same id."); 10314 } 10315 } 10316 10317 /** 10318 * <p>Return the time at which the drawing of the view hierarchy started.</p> 10319 * 10320 * @return the drawing start time in milliseconds 10321 */ 10322 public long getDrawingTime() { 10323 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 10324 } 10325 10326 /** 10327 * <p>Enables or disables the duplication of the parent's state into this view. When 10328 * duplication is enabled, this view gets its drawable state from its parent rather 10329 * than from its own internal properties.</p> 10330 * 10331 * <p>Note: in the current implementation, setting this property to true after the 10332 * view was added to a ViewGroup might have no effect at all. This property should 10333 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 10334 * 10335 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 10336 * property is enabled, an exception will be thrown.</p> 10337 * 10338 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 10339 * parent, these states should not be affected by this method.</p> 10340 * 10341 * @param enabled True to enable duplication of the parent's drawable state, false 10342 * to disable it. 10343 * 10344 * @see #getDrawableState() 10345 * @see #isDuplicateParentStateEnabled() 10346 */ 10347 public void setDuplicateParentStateEnabled(boolean enabled) { 10348 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 10349 } 10350 10351 /** 10352 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 10353 * 10354 * @return True if this view's drawable state is duplicated from the parent, 10355 * false otherwise 10356 * 10357 * @see #getDrawableState() 10358 * @see #setDuplicateParentStateEnabled(boolean) 10359 */ 10360 public boolean isDuplicateParentStateEnabled() { 10361 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 10362 } 10363 10364 /** 10365 * <p>Specifies the type of layer backing this view. The layer can be 10366 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 10367 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 10368 * 10369 * <p>A layer is associated with an optional {@link android.graphics.Paint} 10370 * instance that controls how the layer is composed on screen. The following 10371 * properties of the paint are taken into account when composing the layer:</p> 10372 * <ul> 10373 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 10374 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 10375 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 10376 * </ul> 10377 * 10378 * <p>If this view has an alpha value set to < 1.0 by calling 10379 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 10380 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 10381 * equivalent to setting a hardware layer on this view and providing a paint with 10382 * the desired alpha value.<p> 10383 * 10384 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 10385 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 10386 * for more information on when and how to use layers.</p> 10387 * 10388 * @param layerType The ype of layer to use with this view, must be one of 10389 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 10390 * {@link #LAYER_TYPE_HARDWARE} 10391 * @param paint The paint used to compose the layer. This argument is optional 10392 * and can be null. It is ignored when the layer type is 10393 * {@link #LAYER_TYPE_NONE} 10394 * 10395 * @see #getLayerType() 10396 * @see #LAYER_TYPE_NONE 10397 * @see #LAYER_TYPE_SOFTWARE 10398 * @see #LAYER_TYPE_HARDWARE 10399 * @see #setAlpha(float) 10400 * 10401 * @attr ref android.R.styleable#View_layerType 10402 */ 10403 public void setLayerType(int layerType, Paint paint) { 10404 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 10405 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 10406 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 10407 } 10408 10409 if (layerType == mLayerType) { 10410 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 10411 mLayerPaint = paint == null ? new Paint() : paint; 10412 invalidateParentCaches(); 10413 invalidate(true); 10414 } 10415 return; 10416 } 10417 10418 // Destroy any previous software drawing cache if needed 10419 switch (mLayerType) { 10420 case LAYER_TYPE_HARDWARE: 10421 destroyLayer(false); 10422 // fall through - non-accelerated views may use software layer mechanism instead 10423 case LAYER_TYPE_SOFTWARE: 10424 destroyDrawingCache(); 10425 break; 10426 default: 10427 break; 10428 } 10429 10430 mLayerType = layerType; 10431 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 10432 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 10433 mLocalDirtyRect = layerDisabled ? null : new Rect(); 10434 10435 invalidateParentCaches(); 10436 invalidate(true); 10437 } 10438 10439 /** 10440 * Indicates whether this view has a static layer. A view with layer type 10441 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 10442 * dynamic. 10443 */ 10444 boolean hasStaticLayer() { 10445 return true; 10446 } 10447 10448 /** 10449 * Indicates what type of layer is currently associated with this view. By default 10450 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 10451 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 10452 * for more information on the different types of layers. 10453 * 10454 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 10455 * {@link #LAYER_TYPE_HARDWARE} 10456 * 10457 * @see #setLayerType(int, android.graphics.Paint) 10458 * @see #buildLayer() 10459 * @see #LAYER_TYPE_NONE 10460 * @see #LAYER_TYPE_SOFTWARE 10461 * @see #LAYER_TYPE_HARDWARE 10462 */ 10463 public int getLayerType() { 10464 return mLayerType; 10465 } 10466 10467 /** 10468 * Forces this view's layer to be created and this view to be rendered 10469 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 10470 * invoking this method will have no effect. 10471 * 10472 * This method can for instance be used to render a view into its layer before 10473 * starting an animation. If this view is complex, rendering into the layer 10474 * before starting the animation will avoid skipping frames. 10475 * 10476 * @throws IllegalStateException If this view is not attached to a window 10477 * 10478 * @see #setLayerType(int, android.graphics.Paint) 10479 */ 10480 public void buildLayer() { 10481 if (mLayerType == LAYER_TYPE_NONE) return; 10482 10483 if (mAttachInfo == null) { 10484 throw new IllegalStateException("This view must be attached to a window first"); 10485 } 10486 10487 switch (mLayerType) { 10488 case LAYER_TYPE_HARDWARE: 10489 if (mAttachInfo.mHardwareRenderer != null && 10490 mAttachInfo.mHardwareRenderer.isEnabled() && 10491 mAttachInfo.mHardwareRenderer.validate()) { 10492 getHardwareLayer(); 10493 } 10494 break; 10495 case LAYER_TYPE_SOFTWARE: 10496 buildDrawingCache(true); 10497 break; 10498 } 10499 } 10500 10501 // Make sure the HardwareRenderer.validate() was invoked before calling this method 10502 void flushLayer() { 10503 if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) { 10504 mHardwareLayer.flush(); 10505 } 10506 } 10507 10508 /** 10509 * <p>Returns a hardware layer that can be used to draw this view again 10510 * without executing its draw method.</p> 10511 * 10512 * @return A HardwareLayer ready to render, or null if an error occurred. 10513 */ 10514 HardwareLayer getHardwareLayer() { 10515 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 10516 !mAttachInfo.mHardwareRenderer.isEnabled()) { 10517 return null; 10518 } 10519 10520 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 10521 10522 final int width = mRight - mLeft; 10523 final int height = mBottom - mTop; 10524 10525 if (width == 0 || height == 0) { 10526 return null; 10527 } 10528 10529 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 10530 if (mHardwareLayer == null) { 10531 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 10532 width, height, isOpaque()); 10533 mLocalDirtyRect.set(0, 0, width, height); 10534 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 10535 mHardwareLayer.resize(width, height); 10536 mLocalDirtyRect.set(0, 0, width, height); 10537 } 10538 10539 // The layer is not valid if the underlying GPU resources cannot be allocated 10540 if (!mHardwareLayer.isValid()) { 10541 return null; 10542 } 10543 10544 mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect); 10545 mLocalDirtyRect.setEmpty(); 10546 } 10547 10548 return mHardwareLayer; 10549 } 10550 10551 /** 10552 * Destroys this View's hardware layer if possible. 10553 * 10554 * @return True if the layer was destroyed, false otherwise. 10555 * 10556 * @see #setLayerType(int, android.graphics.Paint) 10557 * @see #LAYER_TYPE_HARDWARE 10558 */ 10559 boolean destroyLayer(boolean valid) { 10560 if (mHardwareLayer != null) { 10561 AttachInfo info = mAttachInfo; 10562 if (info != null && info.mHardwareRenderer != null && 10563 info.mHardwareRenderer.isEnabled() && 10564 (valid || info.mHardwareRenderer.validate())) { 10565 mHardwareLayer.destroy(); 10566 mHardwareLayer = null; 10567 10568 invalidate(true); 10569 invalidateParentCaches(); 10570 } 10571 return true; 10572 } 10573 return false; 10574 } 10575 10576 /** 10577 * Destroys all hardware rendering resources. This method is invoked 10578 * when the system needs to reclaim resources. Upon execution of this 10579 * method, you should free any OpenGL resources created by the view. 10580 * 10581 * Note: you <strong>must</strong> call 10582 * <code>super.destroyHardwareResources()</code> when overriding 10583 * this method. 10584 * 10585 * @hide 10586 */ 10587 protected void destroyHardwareResources() { 10588 destroyLayer(true); 10589 } 10590 10591 /** 10592 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 10593 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 10594 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 10595 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 10596 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 10597 * null.</p> 10598 * 10599 * <p>Enabling the drawing cache is similar to 10600 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 10601 * acceleration is turned off. When hardware acceleration is turned on, enabling the 10602 * drawing cache has no effect on rendering because the system uses a different mechanism 10603 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 10604 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 10605 * for information on how to enable software and hardware layers.</p> 10606 * 10607 * <p>This API can be used to manually generate 10608 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 10609 * {@link #getDrawingCache()}.</p> 10610 * 10611 * @param enabled true to enable the drawing cache, false otherwise 10612 * 10613 * @see #isDrawingCacheEnabled() 10614 * @see #getDrawingCache() 10615 * @see #buildDrawingCache() 10616 * @see #setLayerType(int, android.graphics.Paint) 10617 */ 10618 public void setDrawingCacheEnabled(boolean enabled) { 10619 mCachingFailed = false; 10620 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 10621 } 10622 10623 /** 10624 * <p>Indicates whether the drawing cache is enabled for this view.</p> 10625 * 10626 * @return true if the drawing cache is enabled 10627 * 10628 * @see #setDrawingCacheEnabled(boolean) 10629 * @see #getDrawingCache() 10630 */ 10631 @ViewDebug.ExportedProperty(category = "drawing") 10632 public boolean isDrawingCacheEnabled() { 10633 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 10634 } 10635 10636 /** 10637 * Debugging utility which recursively outputs the dirty state of a view and its 10638 * descendants. 10639 * 10640 * @hide 10641 */ 10642 @SuppressWarnings({"UnusedDeclaration"}) 10643 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 10644 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) + 10645 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" + 10646 (mPrivateFlags & View.DRAWING_CACHE_VALID) + 10647 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")"); 10648 if (clear) { 10649 mPrivateFlags &= clearMask; 10650 } 10651 if (this instanceof ViewGroup) { 10652 ViewGroup parent = (ViewGroup) this; 10653 final int count = parent.getChildCount(); 10654 for (int i = 0; i < count; i++) { 10655 final View child = parent.getChildAt(i); 10656 child.outputDirtyFlags(indent + " ", clear, clearMask); 10657 } 10658 } 10659 } 10660 10661 /** 10662 * This method is used by ViewGroup to cause its children to restore or recreate their 10663 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 10664 * to recreate its own display list, which would happen if it went through the normal 10665 * draw/dispatchDraw mechanisms. 10666 * 10667 * @hide 10668 */ 10669 protected void dispatchGetDisplayList() {} 10670 10671 /** 10672 * A view that is not attached or hardware accelerated cannot create a display list. 10673 * This method checks these conditions and returns the appropriate result. 10674 * 10675 * @return true if view has the ability to create a display list, false otherwise. 10676 * 10677 * @hide 10678 */ 10679 public boolean canHaveDisplayList() { 10680 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 10681 } 10682 10683 /** 10684 * @return The HardwareRenderer associated with that view or null if hardware rendering 10685 * is not supported or this this has not been attached to a window. 10686 * 10687 * @hide 10688 */ 10689 public HardwareRenderer getHardwareRenderer() { 10690 if (mAttachInfo != null) { 10691 return mAttachInfo.mHardwareRenderer; 10692 } 10693 return null; 10694 } 10695 10696 /** 10697 * Returns a DisplayList. If the incoming displayList is null, one will be created. 10698 * Otherwise, the same display list will be returned (after having been rendered into 10699 * along the way, depending on the invalidation state of the view). 10700 * 10701 * @param displayList The previous version of this displayList, could be null. 10702 * @param isLayer Whether the requester of the display list is a layer. If so, 10703 * the view will avoid creating a layer inside the resulting display list. 10704 * @return A new or reused DisplayList object. 10705 */ 10706 private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) { 10707 if (!canHaveDisplayList()) { 10708 return null; 10709 } 10710 10711 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || 10712 displayList == null || !displayList.isValid() || 10713 (!isLayer && mRecreateDisplayList))) { 10714 // Don't need to recreate the display list, just need to tell our 10715 // children to restore/recreate theirs 10716 if (displayList != null && displayList.isValid() && 10717 !isLayer && !mRecreateDisplayList) { 10718 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10719 mPrivateFlags &= ~DIRTY_MASK; 10720 dispatchGetDisplayList(); 10721 10722 return displayList; 10723 } 10724 10725 if (!isLayer) { 10726 // If we got here, we're recreating it. Mark it as such to ensure that 10727 // we copy in child display lists into ours in drawChild() 10728 mRecreateDisplayList = true; 10729 } 10730 if (displayList == null) { 10731 final String name = getClass().getSimpleName(); 10732 displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name); 10733 // If we're creating a new display list, make sure our parent gets invalidated 10734 // since they will need to recreate their display list to account for this 10735 // new child display list. 10736 invalidateParentCaches(); 10737 } 10738 10739 boolean caching = false; 10740 final HardwareCanvas canvas = displayList.start(); 10741 int restoreCount = 0; 10742 int width = mRight - mLeft; 10743 int height = mBottom - mTop; 10744 10745 try { 10746 canvas.setViewport(width, height); 10747 // The dirty rect should always be null for a display list 10748 canvas.onPreDraw(null); 10749 int layerType = ( 10750 !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ? 10751 getLayerType() : LAYER_TYPE_NONE; 10752 if (!isLayer && layerType != LAYER_TYPE_NONE && USE_DISPLAY_LIST_PROPERTIES) { 10753 if (layerType == LAYER_TYPE_HARDWARE) { 10754 final HardwareLayer layer = getHardwareLayer(); 10755 if (layer != null && layer.isValid()) { 10756 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 10757 } else { 10758 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 10759 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 10760 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 10761 } 10762 caching = true; 10763 } else { 10764 buildDrawingCache(true); 10765 Bitmap cache = getDrawingCache(true); 10766 if (cache != null) { 10767 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 10768 caching = true; 10769 } 10770 } 10771 } else { 10772 10773 computeScroll(); 10774 10775 if (!USE_DISPLAY_LIST_PROPERTIES) { 10776 restoreCount = canvas.save(); 10777 } 10778 canvas.translate(-mScrollX, -mScrollY); 10779 if (!isLayer) { 10780 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10781 mPrivateFlags &= ~DIRTY_MASK; 10782 } 10783 10784 // Fast path for layouts with no backgrounds 10785 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10786 dispatchDraw(canvas); 10787 } else { 10788 draw(canvas); 10789 } 10790 } 10791 } finally { 10792 if (USE_DISPLAY_LIST_PROPERTIES) { 10793 canvas.restoreToCount(restoreCount); 10794 } 10795 canvas.onPostDraw(); 10796 10797 displayList.end(); 10798 if (USE_DISPLAY_LIST_PROPERTIES) { 10799 displayList.setCaching(caching); 10800 } 10801 if (isLayer && USE_DISPLAY_LIST_PROPERTIES) { 10802 displayList.setLeftTopRightBottom(0, 0, width, height); 10803 } else { 10804 setDisplayListProperties(displayList); 10805 } 10806 } 10807 } else if (!isLayer) { 10808 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10809 mPrivateFlags &= ~DIRTY_MASK; 10810 } 10811 10812 return displayList; 10813 } 10814 10815 /** 10816 * Get the DisplayList for the HardwareLayer 10817 * 10818 * @param layer The HardwareLayer whose DisplayList we want 10819 * @return A DisplayList fopr the specified HardwareLayer 10820 */ 10821 private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) { 10822 DisplayList displayList = getDisplayList(layer.getDisplayList(), true); 10823 layer.setDisplayList(displayList); 10824 return displayList; 10825 } 10826 10827 10828 /** 10829 * <p>Returns a display list that can be used to draw this view again 10830 * without executing its draw method.</p> 10831 * 10832 * @return A DisplayList ready to replay, or null if caching is not enabled. 10833 * 10834 * @hide 10835 */ 10836 public DisplayList getDisplayList() { 10837 mDisplayList = getDisplayList(mDisplayList, false); 10838 return mDisplayList; 10839 } 10840 10841 /** 10842 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 10843 * 10844 * @return A non-scaled bitmap representing this view or null if cache is disabled. 10845 * 10846 * @see #getDrawingCache(boolean) 10847 */ 10848 public Bitmap getDrawingCache() { 10849 return getDrawingCache(false); 10850 } 10851 10852 /** 10853 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 10854 * is null when caching is disabled. If caching is enabled and the cache is not ready, 10855 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 10856 * draw from the cache when the cache is enabled. To benefit from the cache, you must 10857 * request the drawing cache by calling this method and draw it on screen if the 10858 * returned bitmap is not null.</p> 10859 * 10860 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10861 * this method will create a bitmap of the same size as this view. Because this bitmap 10862 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10863 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10864 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10865 * size than the view. This implies that your application must be able to handle this 10866 * size.</p> 10867 * 10868 * @param autoScale Indicates whether the generated bitmap should be scaled based on 10869 * the current density of the screen when the application is in compatibility 10870 * mode. 10871 * 10872 * @return A bitmap representing this view or null if cache is disabled. 10873 * 10874 * @see #setDrawingCacheEnabled(boolean) 10875 * @see #isDrawingCacheEnabled() 10876 * @see #buildDrawingCache(boolean) 10877 * @see #destroyDrawingCache() 10878 */ 10879 public Bitmap getDrawingCache(boolean autoScale) { 10880 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 10881 return null; 10882 } 10883 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 10884 buildDrawingCache(autoScale); 10885 } 10886 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 10887 } 10888 10889 /** 10890 * <p>Frees the resources used by the drawing cache. If you call 10891 * {@link #buildDrawingCache()} manually without calling 10892 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10893 * should cleanup the cache with this method afterwards.</p> 10894 * 10895 * @see #setDrawingCacheEnabled(boolean) 10896 * @see #buildDrawingCache() 10897 * @see #getDrawingCache() 10898 */ 10899 public void destroyDrawingCache() { 10900 if (mDrawingCache != null) { 10901 mDrawingCache.recycle(); 10902 mDrawingCache = null; 10903 } 10904 if (mUnscaledDrawingCache != null) { 10905 mUnscaledDrawingCache.recycle(); 10906 mUnscaledDrawingCache = null; 10907 } 10908 } 10909 10910 /** 10911 * Setting a solid background color for the drawing cache's bitmaps will improve 10912 * performance and memory usage. Note, though that this should only be used if this 10913 * view will always be drawn on top of a solid color. 10914 * 10915 * @param color The background color to use for the drawing cache's bitmap 10916 * 10917 * @see #setDrawingCacheEnabled(boolean) 10918 * @see #buildDrawingCache() 10919 * @see #getDrawingCache() 10920 */ 10921 public void setDrawingCacheBackgroundColor(int color) { 10922 if (color != mDrawingCacheBackgroundColor) { 10923 mDrawingCacheBackgroundColor = color; 10924 mPrivateFlags &= ~DRAWING_CACHE_VALID; 10925 } 10926 } 10927 10928 /** 10929 * @see #setDrawingCacheBackgroundColor(int) 10930 * 10931 * @return The background color to used for the drawing cache's bitmap 10932 */ 10933 public int getDrawingCacheBackgroundColor() { 10934 return mDrawingCacheBackgroundColor; 10935 } 10936 10937 /** 10938 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 10939 * 10940 * @see #buildDrawingCache(boolean) 10941 */ 10942 public void buildDrawingCache() { 10943 buildDrawingCache(false); 10944 } 10945 10946 /** 10947 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 10948 * 10949 * <p>If you call {@link #buildDrawingCache()} manually without calling 10950 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10951 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 10952 * 10953 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10954 * this method will create a bitmap of the same size as this view. Because this bitmap 10955 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10956 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10957 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10958 * size than the view. This implies that your application must be able to handle this 10959 * size.</p> 10960 * 10961 * <p>You should avoid calling this method when hardware acceleration is enabled. If 10962 * you do not need the drawing cache bitmap, calling this method will increase memory 10963 * usage and cause the view to be rendered in software once, thus negatively impacting 10964 * performance.</p> 10965 * 10966 * @see #getDrawingCache() 10967 * @see #destroyDrawingCache() 10968 */ 10969 public void buildDrawingCache(boolean autoScale) { 10970 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 10971 mDrawingCache == null : mUnscaledDrawingCache == null)) { 10972 mCachingFailed = false; 10973 10974 if (ViewDebug.TRACE_HIERARCHY) { 10975 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 10976 } 10977 10978 int width = mRight - mLeft; 10979 int height = mBottom - mTop; 10980 10981 final AttachInfo attachInfo = mAttachInfo; 10982 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 10983 10984 if (autoScale && scalingRequired) { 10985 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 10986 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 10987 } 10988 10989 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 10990 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 10991 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 10992 10993 if (width <= 0 || height <= 0 || 10994 // Projected bitmap size in bytes 10995 (width * height * (opaque && !use32BitCache ? 2 : 4) > 10996 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 10997 destroyDrawingCache(); 10998 mCachingFailed = true; 10999 return; 11000 } 11001 11002 boolean clear = true; 11003 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 11004 11005 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 11006 Bitmap.Config quality; 11007 if (!opaque) { 11008 // Never pick ARGB_4444 because it looks awful 11009 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 11010 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 11011 case DRAWING_CACHE_QUALITY_AUTO: 11012 quality = Bitmap.Config.ARGB_8888; 11013 break; 11014 case DRAWING_CACHE_QUALITY_LOW: 11015 quality = Bitmap.Config.ARGB_8888; 11016 break; 11017 case DRAWING_CACHE_QUALITY_HIGH: 11018 quality = Bitmap.Config.ARGB_8888; 11019 break; 11020 default: 11021 quality = Bitmap.Config.ARGB_8888; 11022 break; 11023 } 11024 } else { 11025 // Optimization for translucent windows 11026 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 11027 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 11028 } 11029 11030 // Try to cleanup memory 11031 if (bitmap != null) bitmap.recycle(); 11032 11033 try { 11034 bitmap = Bitmap.createBitmap(width, height, quality); 11035 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 11036 if (autoScale) { 11037 mDrawingCache = bitmap; 11038 } else { 11039 mUnscaledDrawingCache = bitmap; 11040 } 11041 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 11042 } catch (OutOfMemoryError e) { 11043 // If there is not enough memory to create the bitmap cache, just 11044 // ignore the issue as bitmap caches are not required to draw the 11045 // view hierarchy 11046 if (autoScale) { 11047 mDrawingCache = null; 11048 } else { 11049 mUnscaledDrawingCache = null; 11050 } 11051 mCachingFailed = true; 11052 return; 11053 } 11054 11055 clear = drawingCacheBackgroundColor != 0; 11056 } 11057 11058 Canvas canvas; 11059 if (attachInfo != null) { 11060 canvas = attachInfo.mCanvas; 11061 if (canvas == null) { 11062 canvas = new Canvas(); 11063 } 11064 canvas.setBitmap(bitmap); 11065 // Temporarily clobber the cached Canvas in case one of our children 11066 // is also using a drawing cache. Without this, the children would 11067 // steal the canvas by attaching their own bitmap to it and bad, bad 11068 // thing would happen (invisible views, corrupted drawings, etc.) 11069 attachInfo.mCanvas = null; 11070 } else { 11071 // This case should hopefully never or seldom happen 11072 canvas = new Canvas(bitmap); 11073 } 11074 11075 if (clear) { 11076 bitmap.eraseColor(drawingCacheBackgroundColor); 11077 } 11078 11079 computeScroll(); 11080 final int restoreCount = canvas.save(); 11081 11082 if (autoScale && scalingRequired) { 11083 final float scale = attachInfo.mApplicationScale; 11084 canvas.scale(scale, scale); 11085 } 11086 11087 canvas.translate(-mScrollX, -mScrollY); 11088 11089 mPrivateFlags |= DRAWN; 11090 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 11091 mLayerType != LAYER_TYPE_NONE) { 11092 mPrivateFlags |= DRAWING_CACHE_VALID; 11093 } 11094 11095 // Fast path for layouts with no backgrounds 11096 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 11097 if (ViewDebug.TRACE_HIERARCHY) { 11098 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 11099 } 11100 mPrivateFlags &= ~DIRTY_MASK; 11101 dispatchDraw(canvas); 11102 } else { 11103 draw(canvas); 11104 } 11105 11106 canvas.restoreToCount(restoreCount); 11107 canvas.setBitmap(null); 11108 11109 if (attachInfo != null) { 11110 // Restore the cached Canvas for our siblings 11111 attachInfo.mCanvas = canvas; 11112 } 11113 } 11114 } 11115 11116 /** 11117 * Create a snapshot of the view into a bitmap. We should probably make 11118 * some form of this public, but should think about the API. 11119 */ 11120 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 11121 int width = mRight - mLeft; 11122 int height = mBottom - mTop; 11123 11124 final AttachInfo attachInfo = mAttachInfo; 11125 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 11126 width = (int) ((width * scale) + 0.5f); 11127 height = (int) ((height * scale) + 0.5f); 11128 11129 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 11130 if (bitmap == null) { 11131 throw new OutOfMemoryError(); 11132 } 11133 11134 Resources resources = getResources(); 11135 if (resources != null) { 11136 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 11137 } 11138 11139 Canvas canvas; 11140 if (attachInfo != null) { 11141 canvas = attachInfo.mCanvas; 11142 if (canvas == null) { 11143 canvas = new Canvas(); 11144 } 11145 canvas.setBitmap(bitmap); 11146 // Temporarily clobber the cached Canvas in case one of our children 11147 // is also using a drawing cache. Without this, the children would 11148 // steal the canvas by attaching their own bitmap to it and bad, bad 11149 // things would happen (invisible views, corrupted drawings, etc.) 11150 attachInfo.mCanvas = null; 11151 } else { 11152 // This case should hopefully never or seldom happen 11153 canvas = new Canvas(bitmap); 11154 } 11155 11156 if ((backgroundColor & 0xff000000) != 0) { 11157 bitmap.eraseColor(backgroundColor); 11158 } 11159 11160 computeScroll(); 11161 final int restoreCount = canvas.save(); 11162 canvas.scale(scale, scale); 11163 canvas.translate(-mScrollX, -mScrollY); 11164 11165 // Temporarily remove the dirty mask 11166 int flags = mPrivateFlags; 11167 mPrivateFlags &= ~DIRTY_MASK; 11168 11169 // Fast path for layouts with no backgrounds 11170 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 11171 dispatchDraw(canvas); 11172 } else { 11173 draw(canvas); 11174 } 11175 11176 mPrivateFlags = flags; 11177 11178 canvas.restoreToCount(restoreCount); 11179 canvas.setBitmap(null); 11180 11181 if (attachInfo != null) { 11182 // Restore the cached Canvas for our siblings 11183 attachInfo.mCanvas = canvas; 11184 } 11185 11186 return bitmap; 11187 } 11188 11189 /** 11190 * Indicates whether this View is currently in edit mode. A View is usually 11191 * in edit mode when displayed within a developer tool. For instance, if 11192 * this View is being drawn by a visual user interface builder, this method 11193 * should return true. 11194 * 11195 * Subclasses should check the return value of this method to provide 11196 * different behaviors if their normal behavior might interfere with the 11197 * host environment. For instance: the class spawns a thread in its 11198 * constructor, the drawing code relies on device-specific features, etc. 11199 * 11200 * This method is usually checked in the drawing code of custom widgets. 11201 * 11202 * @return True if this View is in edit mode, false otherwise. 11203 */ 11204 public boolean isInEditMode() { 11205 return false; 11206 } 11207 11208 /** 11209 * If the View draws content inside its padding and enables fading edges, 11210 * it needs to support padding offsets. Padding offsets are added to the 11211 * fading edges to extend the length of the fade so that it covers pixels 11212 * drawn inside the padding. 11213 * 11214 * Subclasses of this class should override this method if they need 11215 * to draw content inside the padding. 11216 * 11217 * @return True if padding offset must be applied, false otherwise. 11218 * 11219 * @see #getLeftPaddingOffset() 11220 * @see #getRightPaddingOffset() 11221 * @see #getTopPaddingOffset() 11222 * @see #getBottomPaddingOffset() 11223 * 11224 * @since CURRENT 11225 */ 11226 protected boolean isPaddingOffsetRequired() { 11227 return false; 11228 } 11229 11230 /** 11231 * Amount by which to extend the left fading region. Called only when 11232 * {@link #isPaddingOffsetRequired()} returns true. 11233 * 11234 * @return The left padding offset in pixels. 11235 * 11236 * @see #isPaddingOffsetRequired() 11237 * 11238 * @since CURRENT 11239 */ 11240 protected int getLeftPaddingOffset() { 11241 return 0; 11242 } 11243 11244 /** 11245 * Amount by which to extend the right fading region. Called only when 11246 * {@link #isPaddingOffsetRequired()} returns true. 11247 * 11248 * @return The right padding offset in pixels. 11249 * 11250 * @see #isPaddingOffsetRequired() 11251 * 11252 * @since CURRENT 11253 */ 11254 protected int getRightPaddingOffset() { 11255 return 0; 11256 } 11257 11258 /** 11259 * Amount by which to extend the top fading region. Called only when 11260 * {@link #isPaddingOffsetRequired()} returns true. 11261 * 11262 * @return The top padding offset in pixels. 11263 * 11264 * @see #isPaddingOffsetRequired() 11265 * 11266 * @since CURRENT 11267 */ 11268 protected int getTopPaddingOffset() { 11269 return 0; 11270 } 11271 11272 /** 11273 * Amount by which to extend the bottom fading region. Called only when 11274 * {@link #isPaddingOffsetRequired()} returns true. 11275 * 11276 * @return The bottom padding offset in pixels. 11277 * 11278 * @see #isPaddingOffsetRequired() 11279 * 11280 * @since CURRENT 11281 */ 11282 protected int getBottomPaddingOffset() { 11283 return 0; 11284 } 11285 11286 /** 11287 * @hide 11288 * @param offsetRequired 11289 */ 11290 protected int getFadeTop(boolean offsetRequired) { 11291 int top = mPaddingTop; 11292 if (offsetRequired) top += getTopPaddingOffset(); 11293 return top; 11294 } 11295 11296 /** 11297 * @hide 11298 * @param offsetRequired 11299 */ 11300 protected int getFadeHeight(boolean offsetRequired) { 11301 int padding = mPaddingTop; 11302 if (offsetRequired) padding += getTopPaddingOffset(); 11303 return mBottom - mTop - mPaddingBottom - padding; 11304 } 11305 11306 /** 11307 * <p>Indicates whether this view is attached to a hardware accelerated 11308 * window or not.</p> 11309 * 11310 * <p>Even if this method returns true, it does not mean that every call 11311 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 11312 * accelerated {@link android.graphics.Canvas}. For instance, if this view 11313 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 11314 * window is hardware accelerated, 11315 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 11316 * return false, and this method will return true.</p> 11317 * 11318 * @return True if the view is attached to a window and the window is 11319 * hardware accelerated; false in any other case. 11320 */ 11321 public boolean isHardwareAccelerated() { 11322 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 11323 } 11324 11325 /** 11326 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 11327 * case of an active Animation being run on the view. 11328 */ 11329 private boolean drawAnimation(ViewGroup parent, long drawingTime, 11330 Animation a, boolean scalingRequired) { 11331 Transformation invalidationTransform; 11332 final int flags = parent.mGroupFlags; 11333 final boolean initialized = a.isInitialized(); 11334 if (!initialized) { 11335 a.initialize(mRight - mLeft, mBottom - mTop, getWidth(), getHeight()); 11336 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 11337 onAnimationStart(); 11338 } 11339 11340 boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f); 11341 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 11342 if (parent.mInvalidationTransformation == null) { 11343 parent.mInvalidationTransformation = new Transformation(); 11344 } 11345 invalidationTransform = parent.mInvalidationTransformation; 11346 a.getTransformation(drawingTime, invalidationTransform, 1f); 11347 } else { 11348 invalidationTransform = parent.mChildTransformation; 11349 } 11350 if (more) { 11351 if (!a.willChangeBounds()) { 11352 if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) == 11353 parent.FLAG_OPTIMIZE_INVALIDATE) { 11354 parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED; 11355 } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) { 11356 // The child need to draw an animation, potentially offscreen, so 11357 // make sure we do not cancel invalidate requests 11358 parent.mPrivateFlags |= DRAW_ANIMATION; 11359 parent.invalidate(mLeft, mTop, mRight, mBottom); 11360 } 11361 } else { 11362 if (parent.mInvalidateRegion == null) { 11363 parent.mInvalidateRegion = new RectF(); 11364 } 11365 final RectF region = parent.mInvalidateRegion; 11366 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 11367 invalidationTransform); 11368 11369 // The child need to draw an animation, potentially offscreen, so 11370 // make sure we do not cancel invalidate requests 11371 parent.mPrivateFlags |= DRAW_ANIMATION; 11372 11373 final int left = mLeft + (int) region.left; 11374 final int top = mTop + (int) region.top; 11375 parent.invalidate(left, top, left + (int) (region.width() + .5f), 11376 top + (int) (region.height() + .5f)); 11377 } 11378 } 11379 return more; 11380 } 11381 11382 void setDisplayListProperties() { 11383 setDisplayListProperties(mDisplayList); 11384 } 11385 11386 /** 11387 * This method is called by getDisplayList() when a display list is created or re-rendered. 11388 * It sets or resets the current value of all properties on that display list (resetting is 11389 * necessary when a display list is being re-created, because we need to make sure that 11390 * previously-set transform values 11391 */ 11392 void setDisplayListProperties(DisplayList displayList) { 11393 if (USE_DISPLAY_LIST_PROPERTIES && displayList != null) { 11394 displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 11395 if (mParent instanceof ViewGroup) { 11396 displayList.setClipChildren( 11397 (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 11398 } 11399 if (mAttachInfo != null && mAttachInfo.mScalingRequired && 11400 mAttachInfo.mApplicationScale != 1.0f) { 11401 displayList.setApplicationScale(1f / mAttachInfo.mApplicationScale); 11402 } 11403 if (mTransformationInfo != null) { 11404 displayList.setTransformationInfo(mTransformationInfo.mAlpha, 11405 mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY, 11406 mTransformationInfo.mRotation, mTransformationInfo.mRotationX, 11407 mTransformationInfo.mRotationY, mTransformationInfo.mScaleX, 11408 mTransformationInfo.mScaleY); 11409 if (mTransformationInfo.mCamera == null) { 11410 mTransformationInfo.mCamera = new Camera(); 11411 mTransformationInfo.matrix3D = new Matrix(); 11412 } 11413 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ()); 11414 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) { 11415 displayList.setPivotX(getPivotX()); 11416 displayList.setPivotY(getPivotY()); 11417 } 11418 } 11419 } 11420 } 11421 11422 /** 11423 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 11424 * This draw() method is an implementation detail and is not intended to be overridden or 11425 * to be called from anywhere else other than ViewGroup.drawChild(). 11426 */ 11427 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 11428 boolean useDisplayListProperties = USE_DISPLAY_LIST_PROPERTIES && mAttachInfo != null && 11429 mAttachInfo.mHardwareAccelerated; 11430 boolean more = false; 11431 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 11432 final int flags = parent.mGroupFlags; 11433 11434 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 11435 parent.mChildTransformation.clear(); 11436 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 11437 } 11438 11439 Transformation transformToApply = null; 11440 boolean concatMatrix = false; 11441 11442 boolean scalingRequired = false; 11443 boolean caching; 11444 int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE; 11445 11446 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 11447 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 11448 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 11449 caching = true; 11450 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 11451 } else { 11452 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 11453 } 11454 11455 final Animation a = getAnimation(); 11456 if (a != null) { 11457 more = drawAnimation(parent, drawingTime, a, scalingRequired); 11458 concatMatrix = a.willChangeTransformationMatrix(); 11459 transformToApply = parent.mChildTransformation; 11460 } else if ((flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 11461 final boolean hasTransform = 11462 parent.getChildStaticTransformation(this, parent.mChildTransformation); 11463 if (hasTransform) { 11464 final int transformType = parent.mChildTransformation.getTransformationType(); 11465 transformToApply = transformType != Transformation.TYPE_IDENTITY ? 11466 parent.mChildTransformation : null; 11467 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 11468 } 11469 } 11470 11471 concatMatrix |= !childHasIdentityMatrix; 11472 11473 // Sets the flag as early as possible to allow draw() implementations 11474 // to call invalidate() successfully when doing animations 11475 mPrivateFlags |= DRAWN; 11476 11477 if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 11478 (mPrivateFlags & DRAW_ANIMATION) == 0) { 11479 return more; 11480 } 11481 11482 if (hardwareAccelerated) { 11483 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 11484 // retain the flag's value temporarily in the mRecreateDisplayList flag 11485 mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED; 11486 mPrivateFlags &= ~INVALIDATED; 11487 } 11488 11489 computeScroll(); 11490 11491 final int sx = mScrollX; 11492 final int sy = mScrollY; 11493 11494 DisplayList displayList = null; 11495 Bitmap cache = null; 11496 boolean hasDisplayList = false; 11497 if (caching) { 11498 if (!hardwareAccelerated) { 11499 if (layerType != LAYER_TYPE_NONE) { 11500 layerType = LAYER_TYPE_SOFTWARE; 11501 buildDrawingCache(true); 11502 } 11503 cache = getDrawingCache(true); 11504 } else { 11505 switch (layerType) { 11506 case LAYER_TYPE_SOFTWARE: 11507 if (useDisplayListProperties) { 11508 hasDisplayList = canHaveDisplayList(); 11509 } else { 11510 buildDrawingCache(true); 11511 cache = getDrawingCache(true); 11512 } 11513 break; 11514 case LAYER_TYPE_HARDWARE: 11515 if (useDisplayListProperties) { 11516 hasDisplayList = canHaveDisplayList(); 11517 } 11518 break; 11519 case LAYER_TYPE_NONE: 11520 // Delay getting the display list until animation-driven alpha values are 11521 // set up and possibly passed on to the view 11522 hasDisplayList = canHaveDisplayList(); 11523 break; 11524 } 11525 } 11526 } 11527 useDisplayListProperties &= hasDisplayList; 11528 11529 final boolean hasNoCache = cache == null || hasDisplayList; 11530 final boolean offsetForScroll = cache == null && !hasDisplayList && 11531 layerType != LAYER_TYPE_HARDWARE; 11532 11533 int restoreTo = -1; 11534 if (!useDisplayListProperties || transformToApply != null) { 11535 restoreTo = canvas.save(); 11536 } 11537 if (offsetForScroll) { 11538 canvas.translate(mLeft - sx, mTop - sy); 11539 } else { 11540 if (!useDisplayListProperties) { 11541 canvas.translate(mLeft, mTop); 11542 } 11543 if (scalingRequired) { 11544 if (useDisplayListProperties) { 11545 restoreTo = canvas.save(); 11546 } 11547 // mAttachInfo cannot be null, otherwise scalingRequired == false 11548 final float scale = 1.0f / mAttachInfo.mApplicationScale; 11549 canvas.scale(scale, scale); 11550 } 11551 } 11552 11553 float alpha = useDisplayListProperties ? 1 : getAlpha(); 11554 if (transformToApply != null || alpha < 1.0f || !hasIdentityMatrix()) { 11555 if (transformToApply != null || !childHasIdentityMatrix) { 11556 int transX = 0; 11557 int transY = 0; 11558 11559 if (offsetForScroll) { 11560 transX = -sx; 11561 transY = -sy; 11562 } 11563 11564 if (transformToApply != null) { 11565 if (concatMatrix) { 11566 // Undo the scroll translation, apply the transformation matrix, 11567 // then redo the scroll translate to get the correct result. 11568 canvas.translate(-transX, -transY); 11569 canvas.concat(transformToApply.getMatrix()); 11570 canvas.translate(transX, transY); 11571 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 11572 } 11573 11574 float transformAlpha = transformToApply.getAlpha(); 11575 if (transformAlpha < 1.0f) { 11576 alpha *= transformToApply.getAlpha(); 11577 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 11578 } 11579 } 11580 11581 if (!childHasIdentityMatrix && !useDisplayListProperties) { 11582 canvas.translate(-transX, -transY); 11583 canvas.concat(getMatrix()); 11584 canvas.translate(transX, transY); 11585 } 11586 } 11587 11588 if (alpha < 1.0f) { 11589 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 11590 if (hasNoCache) { 11591 final int multipliedAlpha = (int) (255 * alpha); 11592 if (!onSetAlpha(multipliedAlpha)) { 11593 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 11594 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 11595 layerType != LAYER_TYPE_NONE) { 11596 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 11597 } 11598 if (layerType == LAYER_TYPE_NONE) { 11599 final int scrollX = hasDisplayList ? 0 : sx; 11600 final int scrollY = hasDisplayList ? 0 : sy; 11601 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 11602 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 11603 } 11604 } else { 11605 // Alpha is handled by the child directly, clobber the layer's alpha 11606 mPrivateFlags |= ALPHA_SET; 11607 } 11608 } 11609 } 11610 } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) { 11611 onSetAlpha(255); 11612 mPrivateFlags &= ~ALPHA_SET; 11613 } 11614 11615 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 11616 !useDisplayListProperties) { 11617 if (offsetForScroll) { 11618 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 11619 } else { 11620 if (!scalingRequired || cache == null) { 11621 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 11622 } else { 11623 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 11624 } 11625 } 11626 } 11627 11628 if (hasDisplayList) { 11629 displayList = getDisplayList(); 11630 if (!displayList.isValid()) { 11631 // Uncommon, but possible. If a view is removed from the hierarchy during the call 11632 // to getDisplayList(), the display list will be marked invalid and we should not 11633 // try to use it again. 11634 displayList = null; 11635 hasDisplayList = false; 11636 } 11637 } 11638 11639 if (hasNoCache) { 11640 boolean layerRendered = false; 11641 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 11642 final HardwareLayer layer = getHardwareLayer(); 11643 if (layer != null && layer.isValid()) { 11644 mLayerPaint.setAlpha((int) (alpha * 255)); 11645 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 11646 layerRendered = true; 11647 } else { 11648 final int scrollX = hasDisplayList ? 0 : sx; 11649 final int scrollY = hasDisplayList ? 0 : sy; 11650 canvas.saveLayer(scrollX, scrollY, 11651 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 11652 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 11653 } 11654 } 11655 11656 if (!layerRendered) { 11657 if (!hasDisplayList) { 11658 // Fast path for layouts with no backgrounds 11659 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 11660 if (ViewDebug.TRACE_HIERARCHY) { 11661 ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW); 11662 } 11663 mPrivateFlags &= ~DIRTY_MASK; 11664 dispatchDraw(canvas); 11665 } else { 11666 draw(canvas); 11667 } 11668 } else { 11669 mPrivateFlags &= ~DIRTY_MASK; 11670 ((HardwareCanvas) canvas).drawDisplayList(displayList, 11671 mRight - mLeft, mBottom - mTop, null, flags); 11672 } 11673 } 11674 } else if (cache != null) { 11675 mPrivateFlags &= ~DIRTY_MASK; 11676 Paint cachePaint; 11677 11678 if (layerType == LAYER_TYPE_NONE) { 11679 cachePaint = parent.mCachePaint; 11680 if (cachePaint == null) { 11681 cachePaint = new Paint(); 11682 cachePaint.setDither(false); 11683 parent.mCachePaint = cachePaint; 11684 } 11685 if (alpha < 1.0f) { 11686 cachePaint.setAlpha((int) (alpha * 255)); 11687 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 11688 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 11689 cachePaint.setAlpha(255); 11690 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 11691 } 11692 } else { 11693 cachePaint = mLayerPaint; 11694 cachePaint.setAlpha((int) (alpha * 255)); 11695 } 11696 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 11697 } 11698 11699 if (restoreTo >= 0) { 11700 canvas.restoreToCount(restoreTo); 11701 } 11702 11703 if (a != null && !more) { 11704 if (!hardwareAccelerated && !a.getFillAfter()) { 11705 onSetAlpha(255); 11706 } 11707 parent.finishAnimatingView(this, a); 11708 } 11709 11710 if (more && hardwareAccelerated) { 11711 // invalidation is the trigger to recreate display lists, so if we're using 11712 // display lists to render, force an invalidate to allow the animation to 11713 // continue drawing another frame 11714 parent.invalidate(true); 11715 if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) { 11716 // alpha animations should cause the child to recreate its display list 11717 invalidate(true); 11718 } 11719 } 11720 11721 mRecreateDisplayList = false; 11722 11723 return more; 11724 } 11725 11726 /** 11727 * Manually render this view (and all of its children) to the given Canvas. 11728 * The view must have already done a full layout before this function is 11729 * called. When implementing a view, implement 11730 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 11731 * If you do need to override this method, call the superclass version. 11732 * 11733 * @param canvas The Canvas to which the View is rendered. 11734 */ 11735 public void draw(Canvas canvas) { 11736 if (ViewDebug.TRACE_HIERARCHY) { 11737 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 11738 } 11739 11740 final int privateFlags = mPrivateFlags; 11741 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 11742 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 11743 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 11744 11745 /* 11746 * Draw traversal performs several drawing steps which must be executed 11747 * in the appropriate order: 11748 * 11749 * 1. Draw the background 11750 * 2. If necessary, save the canvas' layers to prepare for fading 11751 * 3. Draw view's content 11752 * 4. Draw children 11753 * 5. If necessary, draw the fading edges and restore layers 11754 * 6. Draw decorations (scrollbars for instance) 11755 */ 11756 11757 // Step 1, draw the background, if needed 11758 int saveCount; 11759 11760 if (!dirtyOpaque) { 11761 final Drawable background = mBGDrawable; 11762 if (background != null) { 11763 final int scrollX = mScrollX; 11764 final int scrollY = mScrollY; 11765 11766 if (mBackgroundSizeChanged) { 11767 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 11768 mBackgroundSizeChanged = false; 11769 } 11770 11771 if ((scrollX | scrollY) == 0) { 11772 background.draw(canvas); 11773 } else { 11774 canvas.translate(scrollX, scrollY); 11775 background.draw(canvas); 11776 canvas.translate(-scrollX, -scrollY); 11777 } 11778 } 11779 } 11780 11781 // skip step 2 & 5 if possible (common case) 11782 final int viewFlags = mViewFlags; 11783 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 11784 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 11785 if (!verticalEdges && !horizontalEdges) { 11786 // Step 3, draw the content 11787 if (!dirtyOpaque) onDraw(canvas); 11788 11789 // Step 4, draw the children 11790 dispatchDraw(canvas); 11791 11792 // Step 6, draw decorations (scrollbars) 11793 onDrawScrollBars(canvas); 11794 11795 // we're done... 11796 return; 11797 } 11798 11799 /* 11800 * Here we do the full fledged routine... 11801 * (this is an uncommon case where speed matters less, 11802 * this is why we repeat some of the tests that have been 11803 * done above) 11804 */ 11805 11806 boolean drawTop = false; 11807 boolean drawBottom = false; 11808 boolean drawLeft = false; 11809 boolean drawRight = false; 11810 11811 float topFadeStrength = 0.0f; 11812 float bottomFadeStrength = 0.0f; 11813 float leftFadeStrength = 0.0f; 11814 float rightFadeStrength = 0.0f; 11815 11816 // Step 2, save the canvas' layers 11817 int paddingLeft = mPaddingLeft; 11818 11819 final boolean offsetRequired = isPaddingOffsetRequired(); 11820 if (offsetRequired) { 11821 paddingLeft += getLeftPaddingOffset(); 11822 } 11823 11824 int left = mScrollX + paddingLeft; 11825 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 11826 int top = mScrollY + getFadeTop(offsetRequired); 11827 int bottom = top + getFadeHeight(offsetRequired); 11828 11829 if (offsetRequired) { 11830 right += getRightPaddingOffset(); 11831 bottom += getBottomPaddingOffset(); 11832 } 11833 11834 final ScrollabilityCache scrollabilityCache = mScrollCache; 11835 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 11836 int length = (int) fadeHeight; 11837 11838 // clip the fade length if top and bottom fades overlap 11839 // overlapping fades produce odd-looking artifacts 11840 if (verticalEdges && (top + length > bottom - length)) { 11841 length = (bottom - top) / 2; 11842 } 11843 11844 // also clip horizontal fades if necessary 11845 if (horizontalEdges && (left + length > right - length)) { 11846 length = (right - left) / 2; 11847 } 11848 11849 if (verticalEdges) { 11850 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 11851 drawTop = topFadeStrength * fadeHeight > 1.0f; 11852 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 11853 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 11854 } 11855 11856 if (horizontalEdges) { 11857 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 11858 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 11859 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 11860 drawRight = rightFadeStrength * fadeHeight > 1.0f; 11861 } 11862 11863 saveCount = canvas.getSaveCount(); 11864 11865 int solidColor = getSolidColor(); 11866 if (solidColor == 0) { 11867 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 11868 11869 if (drawTop) { 11870 canvas.saveLayer(left, top, right, top + length, null, flags); 11871 } 11872 11873 if (drawBottom) { 11874 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 11875 } 11876 11877 if (drawLeft) { 11878 canvas.saveLayer(left, top, left + length, bottom, null, flags); 11879 } 11880 11881 if (drawRight) { 11882 canvas.saveLayer(right - length, top, right, bottom, null, flags); 11883 } 11884 } else { 11885 scrollabilityCache.setFadeColor(solidColor); 11886 } 11887 11888 // Step 3, draw the content 11889 if (!dirtyOpaque) onDraw(canvas); 11890 11891 // Step 4, draw the children 11892 dispatchDraw(canvas); 11893 11894 // Step 5, draw the fade effect and restore layers 11895 final Paint p = scrollabilityCache.paint; 11896 final Matrix matrix = scrollabilityCache.matrix; 11897 final Shader fade = scrollabilityCache.shader; 11898 11899 if (drawTop) { 11900 matrix.setScale(1, fadeHeight * topFadeStrength); 11901 matrix.postTranslate(left, top); 11902 fade.setLocalMatrix(matrix); 11903 canvas.drawRect(left, top, right, top + length, p); 11904 } 11905 11906 if (drawBottom) { 11907 matrix.setScale(1, fadeHeight * bottomFadeStrength); 11908 matrix.postRotate(180); 11909 matrix.postTranslate(left, bottom); 11910 fade.setLocalMatrix(matrix); 11911 canvas.drawRect(left, bottom - length, right, bottom, p); 11912 } 11913 11914 if (drawLeft) { 11915 matrix.setScale(1, fadeHeight * leftFadeStrength); 11916 matrix.postRotate(-90); 11917 matrix.postTranslate(left, top); 11918 fade.setLocalMatrix(matrix); 11919 canvas.drawRect(left, top, left + length, bottom, p); 11920 } 11921 11922 if (drawRight) { 11923 matrix.setScale(1, fadeHeight * rightFadeStrength); 11924 matrix.postRotate(90); 11925 matrix.postTranslate(right, top); 11926 fade.setLocalMatrix(matrix); 11927 canvas.drawRect(right - length, top, right, bottom, p); 11928 } 11929 11930 canvas.restoreToCount(saveCount); 11931 11932 // Step 6, draw decorations (scrollbars) 11933 onDrawScrollBars(canvas); 11934 } 11935 11936 /** 11937 * Override this if your view is known to always be drawn on top of a solid color background, 11938 * and needs to draw fading edges. Returning a non-zero color enables the view system to 11939 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 11940 * should be set to 0xFF. 11941 * 11942 * @see #setVerticalFadingEdgeEnabled(boolean) 11943 * @see #setHorizontalFadingEdgeEnabled(boolean) 11944 * 11945 * @return The known solid color background for this view, or 0 if the color may vary 11946 */ 11947 @ViewDebug.ExportedProperty(category = "drawing") 11948 public int getSolidColor() { 11949 return 0; 11950 } 11951 11952 /** 11953 * Build a human readable string representation of the specified view flags. 11954 * 11955 * @param flags the view flags to convert to a string 11956 * @return a String representing the supplied flags 11957 */ 11958 private static String printFlags(int flags) { 11959 String output = ""; 11960 int numFlags = 0; 11961 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 11962 output += "TAKES_FOCUS"; 11963 numFlags++; 11964 } 11965 11966 switch (flags & VISIBILITY_MASK) { 11967 case INVISIBLE: 11968 if (numFlags > 0) { 11969 output += " "; 11970 } 11971 output += "INVISIBLE"; 11972 // USELESS HERE numFlags++; 11973 break; 11974 case GONE: 11975 if (numFlags > 0) { 11976 output += " "; 11977 } 11978 output += "GONE"; 11979 // USELESS HERE numFlags++; 11980 break; 11981 default: 11982 break; 11983 } 11984 return output; 11985 } 11986 11987 /** 11988 * Build a human readable string representation of the specified private 11989 * view flags. 11990 * 11991 * @param privateFlags the private view flags to convert to a string 11992 * @return a String representing the supplied flags 11993 */ 11994 private static String printPrivateFlags(int privateFlags) { 11995 String output = ""; 11996 int numFlags = 0; 11997 11998 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 11999 output += "WANTS_FOCUS"; 12000 numFlags++; 12001 } 12002 12003 if ((privateFlags & FOCUSED) == FOCUSED) { 12004 if (numFlags > 0) { 12005 output += " "; 12006 } 12007 output += "FOCUSED"; 12008 numFlags++; 12009 } 12010 12011 if ((privateFlags & SELECTED) == SELECTED) { 12012 if (numFlags > 0) { 12013 output += " "; 12014 } 12015 output += "SELECTED"; 12016 numFlags++; 12017 } 12018 12019 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 12020 if (numFlags > 0) { 12021 output += " "; 12022 } 12023 output += "IS_ROOT_NAMESPACE"; 12024 numFlags++; 12025 } 12026 12027 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 12028 if (numFlags > 0) { 12029 output += " "; 12030 } 12031 output += "HAS_BOUNDS"; 12032 numFlags++; 12033 } 12034 12035 if ((privateFlags & DRAWN) == DRAWN) { 12036 if (numFlags > 0) { 12037 output += " "; 12038 } 12039 output += "DRAWN"; 12040 // USELESS HERE numFlags++; 12041 } 12042 return output; 12043 } 12044 12045 /** 12046 * <p>Indicates whether or not this view's layout will be requested during 12047 * the next hierarchy layout pass.</p> 12048 * 12049 * @return true if the layout will be forced during next layout pass 12050 */ 12051 public boolean isLayoutRequested() { 12052 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 12053 } 12054 12055 /** 12056 * Assign a size and position to a view and all of its 12057 * descendants 12058 * 12059 * <p>This is the second phase of the layout mechanism. 12060 * (The first is measuring). In this phase, each parent calls 12061 * layout on all of its children to position them. 12062 * This is typically done using the child measurements 12063 * that were stored in the measure pass().</p> 12064 * 12065 * <p>Derived classes should not override this method. 12066 * Derived classes with children should override 12067 * onLayout. In that method, they should 12068 * call layout on each of their children.</p> 12069 * 12070 * @param l Left position, relative to parent 12071 * @param t Top position, relative to parent 12072 * @param r Right position, relative to parent 12073 * @param b Bottom position, relative to parent 12074 */ 12075 @SuppressWarnings({"unchecked"}) 12076 public void layout(int l, int t, int r, int b) { 12077 int oldL = mLeft; 12078 int oldT = mTop; 12079 int oldB = mBottom; 12080 int oldR = mRight; 12081 boolean changed = setFrame(l, t, r, b); 12082 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 12083 if (ViewDebug.TRACE_HIERARCHY) { 12084 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 12085 } 12086 12087 onLayout(changed, l, t, r, b); 12088 mPrivateFlags &= ~LAYOUT_REQUIRED; 12089 12090 ListenerInfo li = mListenerInfo; 12091 if (li != null && li.mOnLayoutChangeListeners != null) { 12092 ArrayList<OnLayoutChangeListener> listenersCopy = 12093 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 12094 int numListeners = listenersCopy.size(); 12095 for (int i = 0; i < numListeners; ++i) { 12096 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 12097 } 12098 } 12099 } 12100 mPrivateFlags &= ~FORCE_LAYOUT; 12101 } 12102 12103 /** 12104 * Called from layout when this view should 12105 * assign a size and position to each of its children. 12106 * 12107 * Derived classes with children should override 12108 * this method and call layout on each of 12109 * their children. 12110 * @param changed This is a new size or position for this view 12111 * @param left Left position, relative to parent 12112 * @param top Top position, relative to parent 12113 * @param right Right position, relative to parent 12114 * @param bottom Bottom position, relative to parent 12115 */ 12116 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 12117 } 12118 12119 /** 12120 * Assign a size and position to this view. 12121 * 12122 * This is called from layout. 12123 * 12124 * @param left Left position, relative to parent 12125 * @param top Top position, relative to parent 12126 * @param right Right position, relative to parent 12127 * @param bottom Bottom position, relative to parent 12128 * @return true if the new size and position are different than the 12129 * previous ones 12130 * {@hide} 12131 */ 12132 protected boolean setFrame(int left, int top, int right, int bottom) { 12133 boolean changed = false; 12134 12135 if (DBG) { 12136 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 12137 + right + "," + bottom + ")"); 12138 } 12139 12140 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 12141 changed = true; 12142 12143 // Remember our drawn bit 12144 int drawn = mPrivateFlags & DRAWN; 12145 12146 int oldWidth = mRight - mLeft; 12147 int oldHeight = mBottom - mTop; 12148 int newWidth = right - left; 12149 int newHeight = bottom - top; 12150 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 12151 12152 // Invalidate our old position 12153 invalidate(sizeChanged); 12154 12155 mLeft = left; 12156 mTop = top; 12157 mRight = right; 12158 mBottom = bottom; 12159 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 12160 mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 12161 } 12162 12163 mPrivateFlags |= HAS_BOUNDS; 12164 12165 12166 if (sizeChanged) { 12167 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 12168 // A change in dimension means an auto-centered pivot point changes, too 12169 if (mTransformationInfo != null) { 12170 mTransformationInfo.mMatrixDirty = true; 12171 } 12172 } 12173 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 12174 } 12175 12176 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 12177 // If we are visible, force the DRAWN bit to on so that 12178 // this invalidate will go through (at least to our parent). 12179 // This is because someone may have invalidated this view 12180 // before this call to setFrame came in, thereby clearing 12181 // the DRAWN bit. 12182 mPrivateFlags |= DRAWN; 12183 invalidate(sizeChanged); 12184 // parent display list may need to be recreated based on a change in the bounds 12185 // of any child 12186 invalidateParentCaches(); 12187 } 12188 12189 // Reset drawn bit to original value (invalidate turns it off) 12190 mPrivateFlags |= drawn; 12191 12192 mBackgroundSizeChanged = true; 12193 } 12194 return changed; 12195 } 12196 12197 /** 12198 * Finalize inflating a view from XML. This is called as the last phase 12199 * of inflation, after all child views have been added. 12200 * 12201 * <p>Even if the subclass overrides onFinishInflate, they should always be 12202 * sure to call the super method, so that we get called. 12203 */ 12204 protected void onFinishInflate() { 12205 } 12206 12207 /** 12208 * Returns the resources associated with this view. 12209 * 12210 * @return Resources object. 12211 */ 12212 public Resources getResources() { 12213 return mResources; 12214 } 12215 12216 /** 12217 * Invalidates the specified Drawable. 12218 * 12219 * @param drawable the drawable to invalidate 12220 */ 12221 public void invalidateDrawable(Drawable drawable) { 12222 if (verifyDrawable(drawable)) { 12223 final Rect dirty = drawable.getBounds(); 12224 final int scrollX = mScrollX; 12225 final int scrollY = mScrollY; 12226 12227 invalidate(dirty.left + scrollX, dirty.top + scrollY, 12228 dirty.right + scrollX, dirty.bottom + scrollY); 12229 } 12230 } 12231 12232 /** 12233 * Schedules an action on a drawable to occur at a specified time. 12234 * 12235 * @param who the recipient of the action 12236 * @param what the action to run on the drawable 12237 * @param when the time at which the action must occur. Uses the 12238 * {@link SystemClock#uptimeMillis} timebase. 12239 */ 12240 public void scheduleDrawable(Drawable who, Runnable what, long when) { 12241 if (verifyDrawable(who) && what != null) { 12242 final long delay = when - SystemClock.uptimeMillis(); 12243 if (mAttachInfo != null) { 12244 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 12245 Choreographer.CALLBACK_ANIMATION, what, who, 12246 Choreographer.subtractFrameDelay(delay)); 12247 } else { 12248 ViewRootImpl.getRunQueue().postDelayed(what, delay); 12249 } 12250 } 12251 } 12252 12253 /** 12254 * Cancels a scheduled action on a drawable. 12255 * 12256 * @param who the recipient of the action 12257 * @param what the action to cancel 12258 */ 12259 public void unscheduleDrawable(Drawable who, Runnable what) { 12260 if (verifyDrawable(who) && what != null) { 12261 if (mAttachInfo != null) { 12262 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 12263 Choreographer.CALLBACK_ANIMATION, what, who); 12264 } else { 12265 ViewRootImpl.getRunQueue().removeCallbacks(what); 12266 } 12267 } 12268 } 12269 12270 /** 12271 * Unschedule any events associated with the given Drawable. This can be 12272 * used when selecting a new Drawable into a view, so that the previous 12273 * one is completely unscheduled. 12274 * 12275 * @param who The Drawable to unschedule. 12276 * 12277 * @see #drawableStateChanged 12278 */ 12279 public void unscheduleDrawable(Drawable who) { 12280 if (mAttachInfo != null && who != null) { 12281 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 12282 Choreographer.CALLBACK_ANIMATION, null, who); 12283 } 12284 } 12285 12286 /** 12287 * Return the layout direction of a given Drawable. 12288 * 12289 * @param who the Drawable to query 12290 */ 12291 public int getResolvedLayoutDirection(Drawable who) { 12292 return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT; 12293 } 12294 12295 /** 12296 * If your view subclass is displaying its own Drawable objects, it should 12297 * override this function and return true for any Drawable it is 12298 * displaying. This allows animations for those drawables to be 12299 * scheduled. 12300 * 12301 * <p>Be sure to call through to the super class when overriding this 12302 * function. 12303 * 12304 * @param who The Drawable to verify. Return true if it is one you are 12305 * displaying, else return the result of calling through to the 12306 * super class. 12307 * 12308 * @return boolean If true than the Drawable is being displayed in the 12309 * view; else false and it is not allowed to animate. 12310 * 12311 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 12312 * @see #drawableStateChanged() 12313 */ 12314 protected boolean verifyDrawable(Drawable who) { 12315 return who == mBGDrawable; 12316 } 12317 12318 /** 12319 * This function is called whenever the state of the view changes in such 12320 * a way that it impacts the state of drawables being shown. 12321 * 12322 * <p>Be sure to call through to the superclass when overriding this 12323 * function. 12324 * 12325 * @see Drawable#setState(int[]) 12326 */ 12327 protected void drawableStateChanged() { 12328 Drawable d = mBGDrawable; 12329 if (d != null && d.isStateful()) { 12330 d.setState(getDrawableState()); 12331 } 12332 } 12333 12334 /** 12335 * Call this to force a view to update its drawable state. This will cause 12336 * drawableStateChanged to be called on this view. Views that are interested 12337 * in the new state should call getDrawableState. 12338 * 12339 * @see #drawableStateChanged 12340 * @see #getDrawableState 12341 */ 12342 public void refreshDrawableState() { 12343 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 12344 drawableStateChanged(); 12345 12346 ViewParent parent = mParent; 12347 if (parent != null) { 12348 parent.childDrawableStateChanged(this); 12349 } 12350 } 12351 12352 /** 12353 * Return an array of resource IDs of the drawable states representing the 12354 * current state of the view. 12355 * 12356 * @return The current drawable state 12357 * 12358 * @see Drawable#setState(int[]) 12359 * @see #drawableStateChanged() 12360 * @see #onCreateDrawableState(int) 12361 */ 12362 public final int[] getDrawableState() { 12363 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 12364 return mDrawableState; 12365 } else { 12366 mDrawableState = onCreateDrawableState(0); 12367 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 12368 return mDrawableState; 12369 } 12370 } 12371 12372 /** 12373 * Generate the new {@link android.graphics.drawable.Drawable} state for 12374 * this view. This is called by the view 12375 * system when the cached Drawable state is determined to be invalid. To 12376 * retrieve the current state, you should use {@link #getDrawableState}. 12377 * 12378 * @param extraSpace if non-zero, this is the number of extra entries you 12379 * would like in the returned array in which you can place your own 12380 * states. 12381 * 12382 * @return Returns an array holding the current {@link Drawable} state of 12383 * the view. 12384 * 12385 * @see #mergeDrawableStates(int[], int[]) 12386 */ 12387 protected int[] onCreateDrawableState(int extraSpace) { 12388 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 12389 mParent instanceof View) { 12390 return ((View) mParent).onCreateDrawableState(extraSpace); 12391 } 12392 12393 int[] drawableState; 12394 12395 int privateFlags = mPrivateFlags; 12396 12397 int viewStateIndex = 0; 12398 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 12399 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 12400 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 12401 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 12402 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 12403 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 12404 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 12405 HardwareRenderer.isAvailable()) { 12406 // This is set if HW acceleration is requested, even if the current 12407 // process doesn't allow it. This is just to allow app preview 12408 // windows to better match their app. 12409 viewStateIndex |= VIEW_STATE_ACCELERATED; 12410 } 12411 if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 12412 12413 final int privateFlags2 = mPrivateFlags2; 12414 if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 12415 if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 12416 12417 drawableState = VIEW_STATE_SETS[viewStateIndex]; 12418 12419 //noinspection ConstantIfStatement 12420 if (false) { 12421 Log.i("View", "drawableStateIndex=" + viewStateIndex); 12422 Log.i("View", toString() 12423 + " pressed=" + ((privateFlags & PRESSED) != 0) 12424 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 12425 + " fo=" + hasFocus() 12426 + " sl=" + ((privateFlags & SELECTED) != 0) 12427 + " wf=" + hasWindowFocus() 12428 + ": " + Arrays.toString(drawableState)); 12429 } 12430 12431 if (extraSpace == 0) { 12432 return drawableState; 12433 } 12434 12435 final int[] fullState; 12436 if (drawableState != null) { 12437 fullState = new int[drawableState.length + extraSpace]; 12438 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 12439 } else { 12440 fullState = new int[extraSpace]; 12441 } 12442 12443 return fullState; 12444 } 12445 12446 /** 12447 * Merge your own state values in <var>additionalState</var> into the base 12448 * state values <var>baseState</var> that were returned by 12449 * {@link #onCreateDrawableState(int)}. 12450 * 12451 * @param baseState The base state values returned by 12452 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 12453 * own additional state values. 12454 * 12455 * @param additionalState The additional state values you would like 12456 * added to <var>baseState</var>; this array is not modified. 12457 * 12458 * @return As a convenience, the <var>baseState</var> array you originally 12459 * passed into the function is returned. 12460 * 12461 * @see #onCreateDrawableState(int) 12462 */ 12463 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 12464 final int N = baseState.length; 12465 int i = N - 1; 12466 while (i >= 0 && baseState[i] == 0) { 12467 i--; 12468 } 12469 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 12470 return baseState; 12471 } 12472 12473 /** 12474 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 12475 * on all Drawable objects associated with this view. 12476 */ 12477 public void jumpDrawablesToCurrentState() { 12478 if (mBGDrawable != null) { 12479 mBGDrawable.jumpToCurrentState(); 12480 } 12481 } 12482 12483 /** 12484 * Sets the background color for this view. 12485 * @param color the color of the background 12486 */ 12487 @RemotableViewMethod 12488 public void setBackgroundColor(int color) { 12489 if (mBGDrawable instanceof ColorDrawable) { 12490 ((ColorDrawable) mBGDrawable).setColor(color); 12491 } else { 12492 setBackgroundDrawable(new ColorDrawable(color)); 12493 } 12494 } 12495 12496 /** 12497 * Set the background to a given resource. The resource should refer to 12498 * a Drawable object or 0 to remove the background. 12499 * @param resid The identifier of the resource. 12500 * @attr ref android.R.styleable#View_background 12501 */ 12502 @RemotableViewMethod 12503 public void setBackgroundResource(int resid) { 12504 if (resid != 0 && resid == mBackgroundResource) { 12505 return; 12506 } 12507 12508 Drawable d= null; 12509 if (resid != 0) { 12510 d = mResources.getDrawable(resid); 12511 } 12512 setBackgroundDrawable(d); 12513 12514 mBackgroundResource = resid; 12515 } 12516 12517 /** 12518 * Set the background to a given Drawable, or remove the background. If the 12519 * background has padding, this View's padding is set to the background's 12520 * padding. However, when a background is removed, this View's padding isn't 12521 * touched. If setting the padding is desired, please use 12522 * {@link #setPadding(int, int, int, int)}. 12523 * 12524 * @param d The Drawable to use as the background, or null to remove the 12525 * background 12526 */ 12527 public void setBackgroundDrawable(Drawable d) { 12528 if (d == mBGDrawable) { 12529 return; 12530 } 12531 12532 boolean requestLayout = false; 12533 12534 mBackgroundResource = 0; 12535 12536 /* 12537 * Regardless of whether we're setting a new background or not, we want 12538 * to clear the previous drawable. 12539 */ 12540 if (mBGDrawable != null) { 12541 mBGDrawable.setCallback(null); 12542 unscheduleDrawable(mBGDrawable); 12543 } 12544 12545 if (d != null) { 12546 Rect padding = sThreadLocal.get(); 12547 if (padding == null) { 12548 padding = new Rect(); 12549 sThreadLocal.set(padding); 12550 } 12551 if (d.getPadding(padding)) { 12552 switch (d.getResolvedLayoutDirectionSelf()) { 12553 case LAYOUT_DIRECTION_RTL: 12554 setPadding(padding.right, padding.top, padding.left, padding.bottom); 12555 break; 12556 case LAYOUT_DIRECTION_LTR: 12557 default: 12558 setPadding(padding.left, padding.top, padding.right, padding.bottom); 12559 } 12560 } 12561 12562 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 12563 // if it has a different minimum size, we should layout again 12564 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 12565 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 12566 requestLayout = true; 12567 } 12568 12569 d.setCallback(this); 12570 if (d.isStateful()) { 12571 d.setState(getDrawableState()); 12572 } 12573 d.setVisible(getVisibility() == VISIBLE, false); 12574 mBGDrawable = d; 12575 12576 if ((mPrivateFlags & SKIP_DRAW) != 0) { 12577 mPrivateFlags &= ~SKIP_DRAW; 12578 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 12579 requestLayout = true; 12580 } 12581 } else { 12582 /* Remove the background */ 12583 mBGDrawable = null; 12584 12585 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 12586 /* 12587 * This view ONLY drew the background before and we're removing 12588 * the background, so now it won't draw anything 12589 * (hence we SKIP_DRAW) 12590 */ 12591 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 12592 mPrivateFlags |= SKIP_DRAW; 12593 } 12594 12595 /* 12596 * When the background is set, we try to apply its padding to this 12597 * View. When the background is removed, we don't touch this View's 12598 * padding. This is noted in the Javadocs. Hence, we don't need to 12599 * requestLayout(), the invalidate() below is sufficient. 12600 */ 12601 12602 // The old background's minimum size could have affected this 12603 // View's layout, so let's requestLayout 12604 requestLayout = true; 12605 } 12606 12607 computeOpaqueFlags(); 12608 12609 if (requestLayout) { 12610 requestLayout(); 12611 } 12612 12613 mBackgroundSizeChanged = true; 12614 invalidate(true); 12615 } 12616 12617 /** 12618 * Gets the background drawable 12619 * @return The drawable used as the background for this view, if any. 12620 */ 12621 public Drawable getBackground() { 12622 return mBGDrawable; 12623 } 12624 12625 /** 12626 * Sets the padding. The view may add on the space required to display 12627 * the scrollbars, depending on the style and visibility of the scrollbars. 12628 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 12629 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 12630 * from the values set in this call. 12631 * 12632 * @attr ref android.R.styleable#View_padding 12633 * @attr ref android.R.styleable#View_paddingBottom 12634 * @attr ref android.R.styleable#View_paddingLeft 12635 * @attr ref android.R.styleable#View_paddingRight 12636 * @attr ref android.R.styleable#View_paddingTop 12637 * @param left the left padding in pixels 12638 * @param top the top padding in pixels 12639 * @param right the right padding in pixels 12640 * @param bottom the bottom padding in pixels 12641 */ 12642 public void setPadding(int left, int top, int right, int bottom) { 12643 mUserPaddingStart = -1; 12644 mUserPaddingEnd = -1; 12645 mUserPaddingRelative = false; 12646 12647 internalSetPadding(left, top, right, bottom); 12648 } 12649 12650 private void internalSetPadding(int left, int top, int right, int bottom) { 12651 mUserPaddingLeft = left; 12652 mUserPaddingRight = right; 12653 mUserPaddingBottom = bottom; 12654 12655 final int viewFlags = mViewFlags; 12656 boolean changed = false; 12657 12658 // Common case is there are no scroll bars. 12659 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 12660 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 12661 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 12662 ? 0 : getVerticalScrollbarWidth(); 12663 switch (mVerticalScrollbarPosition) { 12664 case SCROLLBAR_POSITION_DEFAULT: 12665 if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12666 left += offset; 12667 } else { 12668 right += offset; 12669 } 12670 break; 12671 case SCROLLBAR_POSITION_RIGHT: 12672 right += offset; 12673 break; 12674 case SCROLLBAR_POSITION_LEFT: 12675 left += offset; 12676 break; 12677 } 12678 } 12679 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 12680 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 12681 ? 0 : getHorizontalScrollbarHeight(); 12682 } 12683 } 12684 12685 if (mPaddingLeft != left) { 12686 changed = true; 12687 mPaddingLeft = left; 12688 } 12689 if (mPaddingTop != top) { 12690 changed = true; 12691 mPaddingTop = top; 12692 } 12693 if (mPaddingRight != right) { 12694 changed = true; 12695 mPaddingRight = right; 12696 } 12697 if (mPaddingBottom != bottom) { 12698 changed = true; 12699 mPaddingBottom = bottom; 12700 } 12701 12702 if (changed) { 12703 requestLayout(); 12704 } 12705 } 12706 12707 /** 12708 * Sets the relative padding. The view may add on the space required to display 12709 * the scrollbars, depending on the style and visibility of the scrollbars. 12710 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 12711 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 12712 * from the values set in this call. 12713 * 12714 * @attr ref android.R.styleable#View_padding 12715 * @attr ref android.R.styleable#View_paddingBottom 12716 * @attr ref android.R.styleable#View_paddingStart 12717 * @attr ref android.R.styleable#View_paddingEnd 12718 * @attr ref android.R.styleable#View_paddingTop 12719 * @param start the start padding in pixels 12720 * @param top the top padding in pixels 12721 * @param end the end padding in pixels 12722 * @param bottom the bottom padding in pixels 12723 */ 12724 public void setPaddingRelative(int start, int top, int end, int bottom) { 12725 mUserPaddingStart = start; 12726 mUserPaddingEnd = end; 12727 mUserPaddingRelative = true; 12728 12729 switch(getResolvedLayoutDirection()) { 12730 case LAYOUT_DIRECTION_RTL: 12731 internalSetPadding(end, top, start, bottom); 12732 break; 12733 case LAYOUT_DIRECTION_LTR: 12734 default: 12735 internalSetPadding(start, top, end, bottom); 12736 } 12737 } 12738 12739 /** 12740 * Returns the top padding of this view. 12741 * 12742 * @return the top padding in pixels 12743 */ 12744 public int getPaddingTop() { 12745 return mPaddingTop; 12746 } 12747 12748 /** 12749 * Returns the bottom padding of this view. If there are inset and enabled 12750 * scrollbars, this value may include the space required to display the 12751 * scrollbars as well. 12752 * 12753 * @return the bottom padding in pixels 12754 */ 12755 public int getPaddingBottom() { 12756 return mPaddingBottom; 12757 } 12758 12759 /** 12760 * Returns the left padding of this view. If there are inset and enabled 12761 * scrollbars, this value may include the space required to display the 12762 * scrollbars as well. 12763 * 12764 * @return the left padding in pixels 12765 */ 12766 public int getPaddingLeft() { 12767 return mPaddingLeft; 12768 } 12769 12770 /** 12771 * Returns the start padding of this view depending on its resolved layout direction. 12772 * If there are inset and enabled scrollbars, this value may include the space 12773 * required to display the scrollbars as well. 12774 * 12775 * @return the start padding in pixels 12776 */ 12777 public int getPaddingStart() { 12778 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 12779 mPaddingRight : mPaddingLeft; 12780 } 12781 12782 /** 12783 * Returns the right padding of this view. If there are inset and enabled 12784 * scrollbars, this value may include the space required to display the 12785 * scrollbars as well. 12786 * 12787 * @return the right padding in pixels 12788 */ 12789 public int getPaddingRight() { 12790 return mPaddingRight; 12791 } 12792 12793 /** 12794 * Returns the end padding of this view depending on its resolved layout direction. 12795 * If there are inset and enabled scrollbars, this value may include the space 12796 * required to display the scrollbars as well. 12797 * 12798 * @return the end padding in pixels 12799 */ 12800 public int getPaddingEnd() { 12801 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 12802 mPaddingLeft : mPaddingRight; 12803 } 12804 12805 /** 12806 * Return if the padding as been set thru relative values 12807 * {@link #setPaddingRelative(int, int, int, int)} or thru 12808 * @attr ref android.R.styleable#View_paddingStart or 12809 * @attr ref android.R.styleable#View_paddingEnd 12810 * 12811 * @return true if the padding is relative or false if it is not. 12812 */ 12813 public boolean isPaddingRelative() { 12814 return mUserPaddingRelative; 12815 } 12816 12817 /** 12818 * Changes the selection state of this view. A view can be selected or not. 12819 * Note that selection is not the same as focus. Views are typically 12820 * selected in the context of an AdapterView like ListView or GridView; 12821 * the selected view is the view that is highlighted. 12822 * 12823 * @param selected true if the view must be selected, false otherwise 12824 */ 12825 public void setSelected(boolean selected) { 12826 if (((mPrivateFlags & SELECTED) != 0) != selected) { 12827 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 12828 if (!selected) resetPressedState(); 12829 invalidate(true); 12830 refreshDrawableState(); 12831 dispatchSetSelected(selected); 12832 } 12833 } 12834 12835 /** 12836 * Dispatch setSelected to all of this View's children. 12837 * 12838 * @see #setSelected(boolean) 12839 * 12840 * @param selected The new selected state 12841 */ 12842 protected void dispatchSetSelected(boolean selected) { 12843 } 12844 12845 /** 12846 * Indicates the selection state of this view. 12847 * 12848 * @return true if the view is selected, false otherwise 12849 */ 12850 @ViewDebug.ExportedProperty 12851 public boolean isSelected() { 12852 return (mPrivateFlags & SELECTED) != 0; 12853 } 12854 12855 /** 12856 * Changes the activated state of this view. A view can be activated or not. 12857 * Note that activation is not the same as selection. Selection is 12858 * a transient property, representing the view (hierarchy) the user is 12859 * currently interacting with. Activation is a longer-term state that the 12860 * user can move views in and out of. For example, in a list view with 12861 * single or multiple selection enabled, the views in the current selection 12862 * set are activated. (Um, yeah, we are deeply sorry about the terminology 12863 * here.) The activated state is propagated down to children of the view it 12864 * is set on. 12865 * 12866 * @param activated true if the view must be activated, false otherwise 12867 */ 12868 public void setActivated(boolean activated) { 12869 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 12870 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 12871 invalidate(true); 12872 refreshDrawableState(); 12873 dispatchSetActivated(activated); 12874 } 12875 } 12876 12877 /** 12878 * Dispatch setActivated to all of this View's children. 12879 * 12880 * @see #setActivated(boolean) 12881 * 12882 * @param activated The new activated state 12883 */ 12884 protected void dispatchSetActivated(boolean activated) { 12885 } 12886 12887 /** 12888 * Indicates the activation state of this view. 12889 * 12890 * @return true if the view is activated, false otherwise 12891 */ 12892 @ViewDebug.ExportedProperty 12893 public boolean isActivated() { 12894 return (mPrivateFlags & ACTIVATED) != 0; 12895 } 12896 12897 /** 12898 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 12899 * observer can be used to get notifications when global events, like 12900 * layout, happen. 12901 * 12902 * The returned ViewTreeObserver observer is not guaranteed to remain 12903 * valid for the lifetime of this View. If the caller of this method keeps 12904 * a long-lived reference to ViewTreeObserver, it should always check for 12905 * the return value of {@link ViewTreeObserver#isAlive()}. 12906 * 12907 * @return The ViewTreeObserver for this view's hierarchy. 12908 */ 12909 public ViewTreeObserver getViewTreeObserver() { 12910 if (mAttachInfo != null) { 12911 return mAttachInfo.mTreeObserver; 12912 } 12913 if (mFloatingTreeObserver == null) { 12914 mFloatingTreeObserver = new ViewTreeObserver(); 12915 } 12916 return mFloatingTreeObserver; 12917 } 12918 12919 /** 12920 * <p>Finds the topmost view in the current view hierarchy.</p> 12921 * 12922 * @return the topmost view containing this view 12923 */ 12924 public View getRootView() { 12925 if (mAttachInfo != null) { 12926 final View v = mAttachInfo.mRootView; 12927 if (v != null) { 12928 return v; 12929 } 12930 } 12931 12932 View parent = this; 12933 12934 while (parent.mParent != null && parent.mParent instanceof View) { 12935 parent = (View) parent.mParent; 12936 } 12937 12938 return parent; 12939 } 12940 12941 /** 12942 * <p>Computes the coordinates of this view on the screen. The argument 12943 * must be an array of two integers. After the method returns, the array 12944 * contains the x and y location in that order.</p> 12945 * 12946 * @param location an array of two integers in which to hold the coordinates 12947 */ 12948 public void getLocationOnScreen(int[] location) { 12949 getLocationInWindow(location); 12950 12951 final AttachInfo info = mAttachInfo; 12952 if (info != null) { 12953 location[0] += info.mWindowLeft; 12954 location[1] += info.mWindowTop; 12955 } 12956 } 12957 12958 /** 12959 * <p>Computes the coordinates of this view in its window. The argument 12960 * must be an array of two integers. After the method returns, the array 12961 * contains the x and y location in that order.</p> 12962 * 12963 * @param location an array of two integers in which to hold the coordinates 12964 */ 12965 public void getLocationInWindow(int[] location) { 12966 if (location == null || location.length < 2) { 12967 throw new IllegalArgumentException("location must be an array of two integers"); 12968 } 12969 12970 if (mAttachInfo == null) { 12971 // When the view is not attached to a window, this method does not make sense 12972 location[0] = location[1] = 0; 12973 return; 12974 } 12975 12976 float[] position = mAttachInfo.mTmpTransformLocation; 12977 position[0] = position[1] = 0.0f; 12978 12979 if (!hasIdentityMatrix()) { 12980 getMatrix().mapPoints(position); 12981 } 12982 12983 position[0] += mLeft; 12984 position[1] += mTop; 12985 12986 ViewParent viewParent = mParent; 12987 while (viewParent instanceof View) { 12988 final View view = (View) viewParent; 12989 12990 position[0] -= view.mScrollX; 12991 position[1] -= view.mScrollY; 12992 12993 if (!view.hasIdentityMatrix()) { 12994 view.getMatrix().mapPoints(position); 12995 } 12996 12997 position[0] += view.mLeft; 12998 position[1] += view.mTop; 12999 13000 viewParent = view.mParent; 13001 } 13002 13003 if (viewParent instanceof ViewRootImpl) { 13004 // *cough* 13005 final ViewRootImpl vr = (ViewRootImpl) viewParent; 13006 position[1] -= vr.mCurScrollY; 13007 } 13008 13009 location[0] = (int) (position[0] + 0.5f); 13010 location[1] = (int) (position[1] + 0.5f); 13011 } 13012 13013 /** 13014 * {@hide} 13015 * @param id the id of the view to be found 13016 * @return the view of the specified id, null if cannot be found 13017 */ 13018 protected View findViewTraversal(int id) { 13019 if (id == mID) { 13020 return this; 13021 } 13022 return null; 13023 } 13024 13025 /** 13026 * {@hide} 13027 * @param tag the tag of the view to be found 13028 * @return the view of specified tag, null if cannot be found 13029 */ 13030 protected View findViewWithTagTraversal(Object tag) { 13031 if (tag != null && tag.equals(mTag)) { 13032 return this; 13033 } 13034 return null; 13035 } 13036 13037 /** 13038 * {@hide} 13039 * @param predicate The predicate to evaluate. 13040 * @param childToSkip If not null, ignores this child during the recursive traversal. 13041 * @return The first view that matches the predicate or null. 13042 */ 13043 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 13044 if (predicate.apply(this)) { 13045 return this; 13046 } 13047 return null; 13048 } 13049 13050 /** 13051 * Look for a child view with the given id. If this view has the given 13052 * id, return this view. 13053 * 13054 * @param id The id to search for. 13055 * @return The view that has the given id in the hierarchy or null 13056 */ 13057 public final View findViewById(int id) { 13058 if (id < 0) { 13059 return null; 13060 } 13061 return findViewTraversal(id); 13062 } 13063 13064 /** 13065 * Finds a view by its unuque and stable accessibility id. 13066 * 13067 * @param accessibilityId The searched accessibility id. 13068 * @return The found view. 13069 */ 13070 final View findViewByAccessibilityId(int accessibilityId) { 13071 if (accessibilityId < 0) { 13072 return null; 13073 } 13074 return findViewByAccessibilityIdTraversal(accessibilityId); 13075 } 13076 13077 /** 13078 * Performs the traversal to find a view by its unuque and stable accessibility id. 13079 * 13080 * <strong>Note:</strong>This method does not stop at the root namespace 13081 * boundary since the user can touch the screen at an arbitrary location 13082 * potentially crossing the root namespace bounday which will send an 13083 * accessibility event to accessibility services and they should be able 13084 * to obtain the event source. Also accessibility ids are guaranteed to be 13085 * unique in the window. 13086 * 13087 * @param accessibilityId The accessibility id. 13088 * @return The found view. 13089 */ 13090 View findViewByAccessibilityIdTraversal(int accessibilityId) { 13091 if (getAccessibilityViewId() == accessibilityId) { 13092 return this; 13093 } 13094 return null; 13095 } 13096 13097 /** 13098 * Look for a child view with the given tag. If this view has the given 13099 * tag, return this view. 13100 * 13101 * @param tag The tag to search for, using "tag.equals(getTag())". 13102 * @return The View that has the given tag in the hierarchy or null 13103 */ 13104 public final View findViewWithTag(Object tag) { 13105 if (tag == null) { 13106 return null; 13107 } 13108 return findViewWithTagTraversal(tag); 13109 } 13110 13111 /** 13112 * {@hide} 13113 * Look for a child view that matches the specified predicate. 13114 * If this view matches the predicate, return this view. 13115 * 13116 * @param predicate The predicate to evaluate. 13117 * @return The first view that matches the predicate or null. 13118 */ 13119 public final View findViewByPredicate(Predicate<View> predicate) { 13120 return findViewByPredicateTraversal(predicate, null); 13121 } 13122 13123 /** 13124 * {@hide} 13125 * Look for a child view that matches the specified predicate, 13126 * starting with the specified view and its descendents and then 13127 * recusively searching the ancestors and siblings of that view 13128 * until this view is reached. 13129 * 13130 * This method is useful in cases where the predicate does not match 13131 * a single unique view (perhaps multiple views use the same id) 13132 * and we are trying to find the view that is "closest" in scope to the 13133 * starting view. 13134 * 13135 * @param start The view to start from. 13136 * @param predicate The predicate to evaluate. 13137 * @return The first view that matches the predicate or null. 13138 */ 13139 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 13140 View childToSkip = null; 13141 for (;;) { 13142 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 13143 if (view != null || start == this) { 13144 return view; 13145 } 13146 13147 ViewParent parent = start.getParent(); 13148 if (parent == null || !(parent instanceof View)) { 13149 return null; 13150 } 13151 13152 childToSkip = start; 13153 start = (View) parent; 13154 } 13155 } 13156 13157 /** 13158 * Sets the identifier for this view. The identifier does not have to be 13159 * unique in this view's hierarchy. The identifier should be a positive 13160 * number. 13161 * 13162 * @see #NO_ID 13163 * @see #getId() 13164 * @see #findViewById(int) 13165 * 13166 * @param id a number used to identify the view 13167 * 13168 * @attr ref android.R.styleable#View_id 13169 */ 13170 public void setId(int id) { 13171 mID = id; 13172 } 13173 13174 /** 13175 * {@hide} 13176 * 13177 * @param isRoot true if the view belongs to the root namespace, false 13178 * otherwise 13179 */ 13180 public void setIsRootNamespace(boolean isRoot) { 13181 if (isRoot) { 13182 mPrivateFlags |= IS_ROOT_NAMESPACE; 13183 } else { 13184 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 13185 } 13186 } 13187 13188 /** 13189 * {@hide} 13190 * 13191 * @return true if the view belongs to the root namespace, false otherwise 13192 */ 13193 public boolean isRootNamespace() { 13194 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 13195 } 13196 13197 /** 13198 * Returns this view's identifier. 13199 * 13200 * @return a positive integer used to identify the view or {@link #NO_ID} 13201 * if the view has no ID 13202 * 13203 * @see #setId(int) 13204 * @see #findViewById(int) 13205 * @attr ref android.R.styleable#View_id 13206 */ 13207 @ViewDebug.CapturedViewProperty 13208 public int getId() { 13209 return mID; 13210 } 13211 13212 /** 13213 * Returns this view's tag. 13214 * 13215 * @return the Object stored in this view as a tag 13216 * 13217 * @see #setTag(Object) 13218 * @see #getTag(int) 13219 */ 13220 @ViewDebug.ExportedProperty 13221 public Object getTag() { 13222 return mTag; 13223 } 13224 13225 /** 13226 * Sets the tag associated with this view. A tag can be used to mark 13227 * a view in its hierarchy and does not have to be unique within the 13228 * hierarchy. Tags can also be used to store data within a view without 13229 * resorting to another data structure. 13230 * 13231 * @param tag an Object to tag the view with 13232 * 13233 * @see #getTag() 13234 * @see #setTag(int, Object) 13235 */ 13236 public void setTag(final Object tag) { 13237 mTag = tag; 13238 } 13239 13240 /** 13241 * Returns the tag associated with this view and the specified key. 13242 * 13243 * @param key The key identifying the tag 13244 * 13245 * @return the Object stored in this view as a tag 13246 * 13247 * @see #setTag(int, Object) 13248 * @see #getTag() 13249 */ 13250 public Object getTag(int key) { 13251 if (mKeyedTags != null) return mKeyedTags.get(key); 13252 return null; 13253 } 13254 13255 /** 13256 * Sets a tag associated with this view and a key. A tag can be used 13257 * to mark a view in its hierarchy and does not have to be unique within 13258 * the hierarchy. Tags can also be used to store data within a view 13259 * without resorting to another data structure. 13260 * 13261 * The specified key should be an id declared in the resources of the 13262 * application to ensure it is unique (see the <a 13263 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 13264 * Keys identified as belonging to 13265 * the Android framework or not associated with any package will cause 13266 * an {@link IllegalArgumentException} to be thrown. 13267 * 13268 * @param key The key identifying the tag 13269 * @param tag An Object to tag the view with 13270 * 13271 * @throws IllegalArgumentException If they specified key is not valid 13272 * 13273 * @see #setTag(Object) 13274 * @see #getTag(int) 13275 */ 13276 public void setTag(int key, final Object tag) { 13277 // If the package id is 0x00 or 0x01, it's either an undefined package 13278 // or a framework id 13279 if ((key >>> 24) < 2) { 13280 throw new IllegalArgumentException("The key must be an application-specific " 13281 + "resource id."); 13282 } 13283 13284 setKeyedTag(key, tag); 13285 } 13286 13287 /** 13288 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 13289 * framework id. 13290 * 13291 * @hide 13292 */ 13293 public void setTagInternal(int key, Object tag) { 13294 if ((key >>> 24) != 0x1) { 13295 throw new IllegalArgumentException("The key must be a framework-specific " 13296 + "resource id."); 13297 } 13298 13299 setKeyedTag(key, tag); 13300 } 13301 13302 private void setKeyedTag(int key, Object tag) { 13303 if (mKeyedTags == null) { 13304 mKeyedTags = new SparseArray<Object>(); 13305 } 13306 13307 mKeyedTags.put(key, tag); 13308 } 13309 13310 /** 13311 * @param consistency The type of consistency. See ViewDebug for more information. 13312 * 13313 * @hide 13314 */ 13315 protected boolean dispatchConsistencyCheck(int consistency) { 13316 return onConsistencyCheck(consistency); 13317 } 13318 13319 /** 13320 * Method that subclasses should implement to check their consistency. The type of 13321 * consistency check is indicated by the bit field passed as a parameter. 13322 * 13323 * @param consistency The type of consistency. See ViewDebug for more information. 13324 * 13325 * @throws IllegalStateException if the view is in an inconsistent state. 13326 * 13327 * @hide 13328 */ 13329 protected boolean onConsistencyCheck(int consistency) { 13330 boolean result = true; 13331 13332 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 13333 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 13334 13335 if (checkLayout) { 13336 if (getParent() == null) { 13337 result = false; 13338 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 13339 "View " + this + " does not have a parent."); 13340 } 13341 13342 if (mAttachInfo == null) { 13343 result = false; 13344 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 13345 "View " + this + " is not attached to a window."); 13346 } 13347 } 13348 13349 if (checkDrawing) { 13350 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 13351 // from their draw() method 13352 13353 if ((mPrivateFlags & DRAWN) != DRAWN && 13354 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 13355 result = false; 13356 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 13357 "View " + this + " was invalidated but its drawing cache is valid."); 13358 } 13359 } 13360 13361 return result; 13362 } 13363 13364 /** 13365 * Prints information about this view in the log output, with the tag 13366 * {@link #VIEW_LOG_TAG}. 13367 * 13368 * @hide 13369 */ 13370 public void debug() { 13371 debug(0); 13372 } 13373 13374 /** 13375 * Prints information about this view in the log output, with the tag 13376 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 13377 * indentation defined by the <code>depth</code>. 13378 * 13379 * @param depth the indentation level 13380 * 13381 * @hide 13382 */ 13383 protected void debug(int depth) { 13384 String output = debugIndent(depth - 1); 13385 13386 output += "+ " + this; 13387 int id = getId(); 13388 if (id != -1) { 13389 output += " (id=" + id + ")"; 13390 } 13391 Object tag = getTag(); 13392 if (tag != null) { 13393 output += " (tag=" + tag + ")"; 13394 } 13395 Log.d(VIEW_LOG_TAG, output); 13396 13397 if ((mPrivateFlags & FOCUSED) != 0) { 13398 output = debugIndent(depth) + " FOCUSED"; 13399 Log.d(VIEW_LOG_TAG, output); 13400 } 13401 13402 output = debugIndent(depth); 13403 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 13404 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 13405 + "} "; 13406 Log.d(VIEW_LOG_TAG, output); 13407 13408 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 13409 || mPaddingBottom != 0) { 13410 output = debugIndent(depth); 13411 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 13412 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 13413 Log.d(VIEW_LOG_TAG, output); 13414 } 13415 13416 output = debugIndent(depth); 13417 output += "mMeasureWidth=" + mMeasuredWidth + 13418 " mMeasureHeight=" + mMeasuredHeight; 13419 Log.d(VIEW_LOG_TAG, output); 13420 13421 output = debugIndent(depth); 13422 if (mLayoutParams == null) { 13423 output += "BAD! no layout params"; 13424 } else { 13425 output = mLayoutParams.debug(output); 13426 } 13427 Log.d(VIEW_LOG_TAG, output); 13428 13429 output = debugIndent(depth); 13430 output += "flags={"; 13431 output += View.printFlags(mViewFlags); 13432 output += "}"; 13433 Log.d(VIEW_LOG_TAG, output); 13434 13435 output = debugIndent(depth); 13436 output += "privateFlags={"; 13437 output += View.printPrivateFlags(mPrivateFlags); 13438 output += "}"; 13439 Log.d(VIEW_LOG_TAG, output); 13440 } 13441 13442 /** 13443 * Creates a string of whitespaces used for indentation. 13444 * 13445 * @param depth the indentation level 13446 * @return a String containing (depth * 2 + 3) * 2 white spaces 13447 * 13448 * @hide 13449 */ 13450 protected static String debugIndent(int depth) { 13451 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 13452 for (int i = 0; i < (depth * 2) + 3; i++) { 13453 spaces.append(' ').append(' '); 13454 } 13455 return spaces.toString(); 13456 } 13457 13458 /** 13459 * <p>Return the offset of the widget's text baseline from the widget's top 13460 * boundary. If this widget does not support baseline alignment, this 13461 * method returns -1. </p> 13462 * 13463 * @return the offset of the baseline within the widget's bounds or -1 13464 * if baseline alignment is not supported 13465 */ 13466 @ViewDebug.ExportedProperty(category = "layout") 13467 public int getBaseline() { 13468 return -1; 13469 } 13470 13471 /** 13472 * Call this when something has changed which has invalidated the 13473 * layout of this view. This will schedule a layout pass of the view 13474 * tree. 13475 */ 13476 public void requestLayout() { 13477 if (ViewDebug.TRACE_HIERARCHY) { 13478 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 13479 } 13480 13481 mPrivateFlags |= FORCE_LAYOUT; 13482 mPrivateFlags |= INVALIDATED; 13483 13484 if (mParent != null) { 13485 if (mLayoutParams != null) { 13486 mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection()); 13487 } 13488 if (!mParent.isLayoutRequested()) { 13489 mParent.requestLayout(); 13490 } 13491 } 13492 } 13493 13494 /** 13495 * Forces this view to be laid out during the next layout pass. 13496 * This method does not call requestLayout() or forceLayout() 13497 * on the parent. 13498 */ 13499 public void forceLayout() { 13500 mPrivateFlags |= FORCE_LAYOUT; 13501 mPrivateFlags |= INVALIDATED; 13502 } 13503 13504 /** 13505 * <p> 13506 * This is called to find out how big a view should be. The parent 13507 * supplies constraint information in the width and height parameters. 13508 * </p> 13509 * 13510 * <p> 13511 * The actual measurement work of a view is performed in 13512 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 13513 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 13514 * </p> 13515 * 13516 * 13517 * @param widthMeasureSpec Horizontal space requirements as imposed by the 13518 * parent 13519 * @param heightMeasureSpec Vertical space requirements as imposed by the 13520 * parent 13521 * 13522 * @see #onMeasure(int, int) 13523 */ 13524 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 13525 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 13526 widthMeasureSpec != mOldWidthMeasureSpec || 13527 heightMeasureSpec != mOldHeightMeasureSpec) { 13528 13529 // first clears the measured dimension flag 13530 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 13531 13532 if (ViewDebug.TRACE_HIERARCHY) { 13533 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 13534 } 13535 13536 // measure ourselves, this should set the measured dimension flag back 13537 onMeasure(widthMeasureSpec, heightMeasureSpec); 13538 13539 // flag not set, setMeasuredDimension() was not invoked, we raise 13540 // an exception to warn the developer 13541 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 13542 throw new IllegalStateException("onMeasure() did not set the" 13543 + " measured dimension by calling" 13544 + " setMeasuredDimension()"); 13545 } 13546 13547 mPrivateFlags |= LAYOUT_REQUIRED; 13548 } 13549 13550 mOldWidthMeasureSpec = widthMeasureSpec; 13551 mOldHeightMeasureSpec = heightMeasureSpec; 13552 } 13553 13554 /** 13555 * <p> 13556 * Measure the view and its content to determine the measured width and the 13557 * measured height. This method is invoked by {@link #measure(int, int)} and 13558 * should be overriden by subclasses to provide accurate and efficient 13559 * measurement of their contents. 13560 * </p> 13561 * 13562 * <p> 13563 * <strong>CONTRACT:</strong> When overriding this method, you 13564 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 13565 * measured width and height of this view. Failure to do so will trigger an 13566 * <code>IllegalStateException</code>, thrown by 13567 * {@link #measure(int, int)}. Calling the superclass' 13568 * {@link #onMeasure(int, int)} is a valid use. 13569 * </p> 13570 * 13571 * <p> 13572 * The base class implementation of measure defaults to the background size, 13573 * unless a larger size is allowed by the MeasureSpec. Subclasses should 13574 * override {@link #onMeasure(int, int)} to provide better measurements of 13575 * their content. 13576 * </p> 13577 * 13578 * <p> 13579 * If this method is overridden, it is the subclass's responsibility to make 13580 * sure the measured height and width are at least the view's minimum height 13581 * and width ({@link #getSuggestedMinimumHeight()} and 13582 * {@link #getSuggestedMinimumWidth()}). 13583 * </p> 13584 * 13585 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 13586 * The requirements are encoded with 13587 * {@link android.view.View.MeasureSpec}. 13588 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 13589 * The requirements are encoded with 13590 * {@link android.view.View.MeasureSpec}. 13591 * 13592 * @see #getMeasuredWidth() 13593 * @see #getMeasuredHeight() 13594 * @see #setMeasuredDimension(int, int) 13595 * @see #getSuggestedMinimumHeight() 13596 * @see #getSuggestedMinimumWidth() 13597 * @see android.view.View.MeasureSpec#getMode(int) 13598 * @see android.view.View.MeasureSpec#getSize(int) 13599 */ 13600 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 13601 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 13602 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 13603 } 13604 13605 /** 13606 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 13607 * measured width and measured height. Failing to do so will trigger an 13608 * exception at measurement time.</p> 13609 * 13610 * @param measuredWidth The measured width of this view. May be a complex 13611 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 13612 * {@link #MEASURED_STATE_TOO_SMALL}. 13613 * @param measuredHeight The measured height of this view. May be a complex 13614 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 13615 * {@link #MEASURED_STATE_TOO_SMALL}. 13616 */ 13617 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 13618 mMeasuredWidth = measuredWidth; 13619 mMeasuredHeight = measuredHeight; 13620 13621 mPrivateFlags |= MEASURED_DIMENSION_SET; 13622 } 13623 13624 /** 13625 * Merge two states as returned by {@link #getMeasuredState()}. 13626 * @param curState The current state as returned from a view or the result 13627 * of combining multiple views. 13628 * @param newState The new view state to combine. 13629 * @return Returns a new integer reflecting the combination of the two 13630 * states. 13631 */ 13632 public static int combineMeasuredStates(int curState, int newState) { 13633 return curState | newState; 13634 } 13635 13636 /** 13637 * Version of {@link #resolveSizeAndState(int, int, int)} 13638 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 13639 */ 13640 public static int resolveSize(int size, int measureSpec) { 13641 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 13642 } 13643 13644 /** 13645 * Utility to reconcile a desired size and state, with constraints imposed 13646 * by a MeasureSpec. Will take the desired size, unless a different size 13647 * is imposed by the constraints. The returned value is a compound integer, 13648 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 13649 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 13650 * size is smaller than the size the view wants to be. 13651 * 13652 * @param size How big the view wants to be 13653 * @param measureSpec Constraints imposed by the parent 13654 * @return Size information bit mask as defined by 13655 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 13656 */ 13657 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 13658 int result = size; 13659 int specMode = MeasureSpec.getMode(measureSpec); 13660 int specSize = MeasureSpec.getSize(measureSpec); 13661 switch (specMode) { 13662 case MeasureSpec.UNSPECIFIED: 13663 result = size; 13664 break; 13665 case MeasureSpec.AT_MOST: 13666 if (specSize < size) { 13667 result = specSize | MEASURED_STATE_TOO_SMALL; 13668 } else { 13669 result = size; 13670 } 13671 break; 13672 case MeasureSpec.EXACTLY: 13673 result = specSize; 13674 break; 13675 } 13676 return result | (childMeasuredState&MEASURED_STATE_MASK); 13677 } 13678 13679 /** 13680 * Utility to return a default size. Uses the supplied size if the 13681 * MeasureSpec imposed no constraints. Will get larger if allowed 13682 * by the MeasureSpec. 13683 * 13684 * @param size Default size for this view 13685 * @param measureSpec Constraints imposed by the parent 13686 * @return The size this view should be. 13687 */ 13688 public static int getDefaultSize(int size, int measureSpec) { 13689 int result = size; 13690 int specMode = MeasureSpec.getMode(measureSpec); 13691 int specSize = MeasureSpec.getSize(measureSpec); 13692 13693 switch (specMode) { 13694 case MeasureSpec.UNSPECIFIED: 13695 result = size; 13696 break; 13697 case MeasureSpec.AT_MOST: 13698 case MeasureSpec.EXACTLY: 13699 result = specSize; 13700 break; 13701 } 13702 return result; 13703 } 13704 13705 /** 13706 * Returns the suggested minimum height that the view should use. This 13707 * returns the maximum of the view's minimum height 13708 * and the background's minimum height 13709 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 13710 * <p> 13711 * When being used in {@link #onMeasure(int, int)}, the caller should still 13712 * ensure the returned height is within the requirements of the parent. 13713 * 13714 * @return The suggested minimum height of the view. 13715 */ 13716 protected int getSuggestedMinimumHeight() { 13717 int suggestedMinHeight = mMinHeight; 13718 13719 if (mBGDrawable != null) { 13720 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 13721 if (suggestedMinHeight < bgMinHeight) { 13722 suggestedMinHeight = bgMinHeight; 13723 } 13724 } 13725 13726 return suggestedMinHeight; 13727 } 13728 13729 /** 13730 * Returns the suggested minimum width that the view should use. This 13731 * returns the maximum of the view's minimum width) 13732 * and the background's minimum width 13733 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 13734 * <p> 13735 * When being used in {@link #onMeasure(int, int)}, the caller should still 13736 * ensure the returned width is within the requirements of the parent. 13737 * 13738 * @return The suggested minimum width of the view. 13739 */ 13740 protected int getSuggestedMinimumWidth() { 13741 int suggestedMinWidth = mMinWidth; 13742 13743 if (mBGDrawable != null) { 13744 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 13745 if (suggestedMinWidth < bgMinWidth) { 13746 suggestedMinWidth = bgMinWidth; 13747 } 13748 } 13749 13750 return suggestedMinWidth; 13751 } 13752 13753 /** 13754 * Sets the minimum height of the view. It is not guaranteed the view will 13755 * be able to achieve this minimum height (for example, if its parent layout 13756 * constrains it with less available height). 13757 * 13758 * @param minHeight The minimum height the view will try to be. 13759 */ 13760 public void setMinimumHeight(int minHeight) { 13761 mMinHeight = minHeight; 13762 } 13763 13764 /** 13765 * Sets the minimum width of the view. It is not guaranteed the view will 13766 * be able to achieve this minimum width (for example, if its parent layout 13767 * constrains it with less available width). 13768 * 13769 * @param minWidth The minimum width the view will try to be. 13770 */ 13771 public void setMinimumWidth(int minWidth) { 13772 mMinWidth = minWidth; 13773 } 13774 13775 /** 13776 * Get the animation currently associated with this view. 13777 * 13778 * @return The animation that is currently playing or 13779 * scheduled to play for this view. 13780 */ 13781 public Animation getAnimation() { 13782 return mCurrentAnimation; 13783 } 13784 13785 /** 13786 * Start the specified animation now. 13787 * 13788 * @param animation the animation to start now 13789 */ 13790 public void startAnimation(Animation animation) { 13791 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 13792 setAnimation(animation); 13793 invalidateParentCaches(); 13794 invalidate(true); 13795 } 13796 13797 /** 13798 * Cancels any animations for this view. 13799 */ 13800 public void clearAnimation() { 13801 if (mCurrentAnimation != null) { 13802 mCurrentAnimation.detach(); 13803 } 13804 mCurrentAnimation = null; 13805 invalidateParentIfNeeded(); 13806 } 13807 13808 /** 13809 * Sets the next animation to play for this view. 13810 * If you want the animation to play immediately, use 13811 * startAnimation. This method provides allows fine-grained 13812 * control over the start time and invalidation, but you 13813 * must make sure that 1) the animation has a start time set, and 13814 * 2) the view will be invalidated when the animation is supposed to 13815 * start. 13816 * 13817 * @param animation The next animation, or null. 13818 */ 13819 public void setAnimation(Animation animation) { 13820 mCurrentAnimation = animation; 13821 if (animation != null) { 13822 animation.reset(); 13823 } 13824 } 13825 13826 /** 13827 * Invoked by a parent ViewGroup to notify the start of the animation 13828 * currently associated with this view. If you override this method, 13829 * always call super.onAnimationStart(); 13830 * 13831 * @see #setAnimation(android.view.animation.Animation) 13832 * @see #getAnimation() 13833 */ 13834 protected void onAnimationStart() { 13835 mPrivateFlags |= ANIMATION_STARTED; 13836 } 13837 13838 /** 13839 * Invoked by a parent ViewGroup to notify the end of the animation 13840 * currently associated with this view. If you override this method, 13841 * always call super.onAnimationEnd(); 13842 * 13843 * @see #setAnimation(android.view.animation.Animation) 13844 * @see #getAnimation() 13845 */ 13846 protected void onAnimationEnd() { 13847 mPrivateFlags &= ~ANIMATION_STARTED; 13848 } 13849 13850 /** 13851 * Invoked if there is a Transform that involves alpha. Subclass that can 13852 * draw themselves with the specified alpha should return true, and then 13853 * respect that alpha when their onDraw() is called. If this returns false 13854 * then the view may be redirected to draw into an offscreen buffer to 13855 * fulfill the request, which will look fine, but may be slower than if the 13856 * subclass handles it internally. The default implementation returns false. 13857 * 13858 * @param alpha The alpha (0..255) to apply to the view's drawing 13859 * @return true if the view can draw with the specified alpha. 13860 */ 13861 protected boolean onSetAlpha(int alpha) { 13862 return false; 13863 } 13864 13865 /** 13866 * This is used by the RootView to perform an optimization when 13867 * the view hierarchy contains one or several SurfaceView. 13868 * SurfaceView is always considered transparent, but its children are not, 13869 * therefore all View objects remove themselves from the global transparent 13870 * region (passed as a parameter to this function). 13871 * 13872 * @param region The transparent region for this ViewAncestor (window). 13873 * 13874 * @return Returns true if the effective visibility of the view at this 13875 * point is opaque, regardless of the transparent region; returns false 13876 * if it is possible for underlying windows to be seen behind the view. 13877 * 13878 * {@hide} 13879 */ 13880 public boolean gatherTransparentRegion(Region region) { 13881 final AttachInfo attachInfo = mAttachInfo; 13882 if (region != null && attachInfo != null) { 13883 final int pflags = mPrivateFlags; 13884 if ((pflags & SKIP_DRAW) == 0) { 13885 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 13886 // remove it from the transparent region. 13887 final int[] location = attachInfo.mTransparentLocation; 13888 getLocationInWindow(location); 13889 region.op(location[0], location[1], location[0] + mRight - mLeft, 13890 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 13891 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 13892 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 13893 // exists, so we remove the background drawable's non-transparent 13894 // parts from this transparent region. 13895 applyDrawableToTransparentRegion(mBGDrawable, region); 13896 } 13897 } 13898 return true; 13899 } 13900 13901 /** 13902 * Play a sound effect for this view. 13903 * 13904 * <p>The framework will play sound effects for some built in actions, such as 13905 * clicking, but you may wish to play these effects in your widget, 13906 * for instance, for internal navigation. 13907 * 13908 * <p>The sound effect will only be played if sound effects are enabled by the user, and 13909 * {@link #isSoundEffectsEnabled()} is true. 13910 * 13911 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 13912 */ 13913 public void playSoundEffect(int soundConstant) { 13914 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 13915 return; 13916 } 13917 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 13918 } 13919 13920 /** 13921 * BZZZTT!!1! 13922 * 13923 * <p>Provide haptic feedback to the user for this view. 13924 * 13925 * <p>The framework will provide haptic feedback for some built in actions, 13926 * such as long presses, but you may wish to provide feedback for your 13927 * own widget. 13928 * 13929 * <p>The feedback will only be performed if 13930 * {@link #isHapticFeedbackEnabled()} is true. 13931 * 13932 * @param feedbackConstant One of the constants defined in 13933 * {@link HapticFeedbackConstants} 13934 */ 13935 public boolean performHapticFeedback(int feedbackConstant) { 13936 return performHapticFeedback(feedbackConstant, 0); 13937 } 13938 13939 /** 13940 * BZZZTT!!1! 13941 * 13942 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 13943 * 13944 * @param feedbackConstant One of the constants defined in 13945 * {@link HapticFeedbackConstants} 13946 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 13947 */ 13948 public boolean performHapticFeedback(int feedbackConstant, int flags) { 13949 if (mAttachInfo == null) { 13950 return false; 13951 } 13952 //noinspection SimplifiableIfStatement 13953 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 13954 && !isHapticFeedbackEnabled()) { 13955 return false; 13956 } 13957 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 13958 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 13959 } 13960 13961 /** 13962 * Request that the visibility of the status bar be changed. 13963 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 13964 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 13965 */ 13966 public void setSystemUiVisibility(int visibility) { 13967 if (visibility != mSystemUiVisibility) { 13968 mSystemUiVisibility = visibility; 13969 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 13970 mParent.recomputeViewAttributes(this); 13971 } 13972 } 13973 } 13974 13975 /** 13976 * Returns the status bar visibility that this view has requested. 13977 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 13978 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 13979 */ 13980 public int getSystemUiVisibility() { 13981 return mSystemUiVisibility; 13982 } 13983 13984 /** 13985 * Set a listener to receive callbacks when the visibility of the system bar changes. 13986 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 13987 */ 13988 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 13989 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 13990 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 13991 mParent.recomputeViewAttributes(this); 13992 } 13993 } 13994 13995 /** 13996 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 13997 * the view hierarchy. 13998 */ 13999 public void dispatchSystemUiVisibilityChanged(int visibility) { 14000 ListenerInfo li = mListenerInfo; 14001 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 14002 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 14003 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 14004 } 14005 } 14006 14007 void updateLocalSystemUiVisibility(int localValue, int localChanges) { 14008 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 14009 if (val != mSystemUiVisibility) { 14010 setSystemUiVisibility(val); 14011 } 14012 } 14013 14014 /** 14015 * Creates an image that the system displays during the drag and drop 14016 * operation. This is called a "drag shadow". The default implementation 14017 * for a DragShadowBuilder based on a View returns an image that has exactly the same 14018 * appearance as the given View. The default also positions the center of the drag shadow 14019 * directly under the touch point. If no View is provided (the constructor with no parameters 14020 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 14021 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 14022 * default is an invisible drag shadow. 14023 * <p> 14024 * You are not required to use the View you provide to the constructor as the basis of the 14025 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 14026 * anything you want as the drag shadow. 14027 * </p> 14028 * <p> 14029 * You pass a DragShadowBuilder object to the system when you start the drag. The system 14030 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 14031 * size and position of the drag shadow. It uses this data to construct a 14032 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 14033 * so that your application can draw the shadow image in the Canvas. 14034 * </p> 14035 * 14036 * <div class="special reference"> 14037 * <h3>Developer Guides</h3> 14038 * <p>For a guide to implementing drag and drop features, read the 14039 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 14040 * </div> 14041 */ 14042 public static class DragShadowBuilder { 14043 private final WeakReference<View> mView; 14044 14045 /** 14046 * Constructs a shadow image builder based on a View. By default, the resulting drag 14047 * shadow will have the same appearance and dimensions as the View, with the touch point 14048 * over the center of the View. 14049 * @param view A View. Any View in scope can be used. 14050 */ 14051 public DragShadowBuilder(View view) { 14052 mView = new WeakReference<View>(view); 14053 } 14054 14055 /** 14056 * Construct a shadow builder object with no associated View. This 14057 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 14058 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 14059 * to supply the drag shadow's dimensions and appearance without 14060 * reference to any View object. If they are not overridden, then the result is an 14061 * invisible drag shadow. 14062 */ 14063 public DragShadowBuilder() { 14064 mView = new WeakReference<View>(null); 14065 } 14066 14067 /** 14068 * Returns the View object that had been passed to the 14069 * {@link #View.DragShadowBuilder(View)} 14070 * constructor. If that View parameter was {@code null} or if the 14071 * {@link #View.DragShadowBuilder()} 14072 * constructor was used to instantiate the builder object, this method will return 14073 * null. 14074 * 14075 * @return The View object associate with this builder object. 14076 */ 14077 @SuppressWarnings({"JavadocReference"}) 14078 final public View getView() { 14079 return mView.get(); 14080 } 14081 14082 /** 14083 * Provides the metrics for the shadow image. These include the dimensions of 14084 * the shadow image, and the point within that shadow that should 14085 * be centered under the touch location while dragging. 14086 * <p> 14087 * The default implementation sets the dimensions of the shadow to be the 14088 * same as the dimensions of the View itself and centers the shadow under 14089 * the touch point. 14090 * </p> 14091 * 14092 * @param shadowSize A {@link android.graphics.Point} containing the width and height 14093 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 14094 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 14095 * image. 14096 * 14097 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 14098 * shadow image that should be underneath the touch point during the drag and drop 14099 * operation. Your application must set {@link android.graphics.Point#x} to the 14100 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 14101 */ 14102 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 14103 final View view = mView.get(); 14104 if (view != null) { 14105 shadowSize.set(view.getWidth(), view.getHeight()); 14106 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 14107 } else { 14108 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 14109 } 14110 } 14111 14112 /** 14113 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 14114 * based on the dimensions it received from the 14115 * {@link #onProvideShadowMetrics(Point, Point)} callback. 14116 * 14117 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 14118 */ 14119 public void onDrawShadow(Canvas canvas) { 14120 final View view = mView.get(); 14121 if (view != null) { 14122 view.draw(canvas); 14123 } else { 14124 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 14125 } 14126 } 14127 } 14128 14129 /** 14130 * Starts a drag and drop operation. When your application calls this method, it passes a 14131 * {@link android.view.View.DragShadowBuilder} object to the system. The 14132 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 14133 * to get metrics for the drag shadow, and then calls the object's 14134 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 14135 * <p> 14136 * Once the system has the drag shadow, it begins the drag and drop operation by sending 14137 * drag events to all the View objects in your application that are currently visible. It does 14138 * this either by calling the View object's drag listener (an implementation of 14139 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 14140 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 14141 * Both are passed a {@link android.view.DragEvent} object that has a 14142 * {@link android.view.DragEvent#getAction()} value of 14143 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 14144 * </p> 14145 * <p> 14146 * Your application can invoke startDrag() on any attached View object. The View object does not 14147 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 14148 * be related to the View the user selected for dragging. 14149 * </p> 14150 * @param data A {@link android.content.ClipData} object pointing to the data to be 14151 * transferred by the drag and drop operation. 14152 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 14153 * drag shadow. 14154 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 14155 * drop operation. This Object is put into every DragEvent object sent by the system during the 14156 * current drag. 14157 * <p> 14158 * myLocalState is a lightweight mechanism for the sending information from the dragged View 14159 * to the target Views. For example, it can contain flags that differentiate between a 14160 * a copy operation and a move operation. 14161 * </p> 14162 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 14163 * so the parameter should be set to 0. 14164 * @return {@code true} if the method completes successfully, or 14165 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 14166 * do a drag, and so no drag operation is in progress. 14167 */ 14168 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 14169 Object myLocalState, int flags) { 14170 if (ViewDebug.DEBUG_DRAG) { 14171 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 14172 } 14173 boolean okay = false; 14174 14175 Point shadowSize = new Point(); 14176 Point shadowTouchPoint = new Point(); 14177 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 14178 14179 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 14180 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 14181 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 14182 } 14183 14184 if (ViewDebug.DEBUG_DRAG) { 14185 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 14186 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 14187 } 14188 Surface surface = new Surface(); 14189 try { 14190 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 14191 flags, shadowSize.x, shadowSize.y, surface); 14192 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 14193 + " surface=" + surface); 14194 if (token != null) { 14195 Canvas canvas = surface.lockCanvas(null); 14196 try { 14197 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 14198 shadowBuilder.onDrawShadow(canvas); 14199 } finally { 14200 surface.unlockCanvasAndPost(canvas); 14201 } 14202 14203 final ViewRootImpl root = getViewRootImpl(); 14204 14205 // Cache the local state object for delivery with DragEvents 14206 root.setLocalDragState(myLocalState); 14207 14208 // repurpose 'shadowSize' for the last touch point 14209 root.getLastTouchPoint(shadowSize); 14210 14211 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 14212 shadowSize.x, shadowSize.y, 14213 shadowTouchPoint.x, shadowTouchPoint.y, data); 14214 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 14215 14216 // Off and running! Release our local surface instance; the drag 14217 // shadow surface is now managed by the system process. 14218 surface.release(); 14219 } 14220 } catch (Exception e) { 14221 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 14222 surface.destroy(); 14223 } 14224 14225 return okay; 14226 } 14227 14228 /** 14229 * Handles drag events sent by the system following a call to 14230 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 14231 *<p> 14232 * When the system calls this method, it passes a 14233 * {@link android.view.DragEvent} object. A call to 14234 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 14235 * in DragEvent. The method uses these to determine what is happening in the drag and drop 14236 * operation. 14237 * @param event The {@link android.view.DragEvent} sent by the system. 14238 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 14239 * in DragEvent, indicating the type of drag event represented by this object. 14240 * @return {@code true} if the method was successful, otherwise {@code false}. 14241 * <p> 14242 * The method should return {@code true} in response to an action type of 14243 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 14244 * operation. 14245 * </p> 14246 * <p> 14247 * The method should also return {@code true} in response to an action type of 14248 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 14249 * {@code false} if it didn't. 14250 * </p> 14251 */ 14252 public boolean onDragEvent(DragEvent event) { 14253 return false; 14254 } 14255 14256 /** 14257 * Detects if this View is enabled and has a drag event listener. 14258 * If both are true, then it calls the drag event listener with the 14259 * {@link android.view.DragEvent} it received. If the drag event listener returns 14260 * {@code true}, then dispatchDragEvent() returns {@code true}. 14261 * <p> 14262 * For all other cases, the method calls the 14263 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 14264 * method and returns its result. 14265 * </p> 14266 * <p> 14267 * This ensures that a drag event is always consumed, even if the View does not have a drag 14268 * event listener. However, if the View has a listener and the listener returns true, then 14269 * onDragEvent() is not called. 14270 * </p> 14271 */ 14272 public boolean dispatchDragEvent(DragEvent event) { 14273 //noinspection SimplifiableIfStatement 14274 ListenerInfo li = mListenerInfo; 14275 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 14276 && li.mOnDragListener.onDrag(this, event)) { 14277 return true; 14278 } 14279 return onDragEvent(event); 14280 } 14281 14282 boolean canAcceptDrag() { 14283 return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0; 14284 } 14285 14286 /** 14287 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 14288 * it is ever exposed at all. 14289 * @hide 14290 */ 14291 public void onCloseSystemDialogs(String reason) { 14292 } 14293 14294 /** 14295 * Given a Drawable whose bounds have been set to draw into this view, 14296 * update a Region being computed for 14297 * {@link #gatherTransparentRegion(android.graphics.Region)} so 14298 * that any non-transparent parts of the Drawable are removed from the 14299 * given transparent region. 14300 * 14301 * @param dr The Drawable whose transparency is to be applied to the region. 14302 * @param region A Region holding the current transparency information, 14303 * where any parts of the region that are set are considered to be 14304 * transparent. On return, this region will be modified to have the 14305 * transparency information reduced by the corresponding parts of the 14306 * Drawable that are not transparent. 14307 * {@hide} 14308 */ 14309 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 14310 if (DBG) { 14311 Log.i("View", "Getting transparent region for: " + this); 14312 } 14313 final Region r = dr.getTransparentRegion(); 14314 final Rect db = dr.getBounds(); 14315 final AttachInfo attachInfo = mAttachInfo; 14316 if (r != null && attachInfo != null) { 14317 final int w = getRight()-getLeft(); 14318 final int h = getBottom()-getTop(); 14319 if (db.left > 0) { 14320 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 14321 r.op(0, 0, db.left, h, Region.Op.UNION); 14322 } 14323 if (db.right < w) { 14324 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 14325 r.op(db.right, 0, w, h, Region.Op.UNION); 14326 } 14327 if (db.top > 0) { 14328 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 14329 r.op(0, 0, w, db.top, Region.Op.UNION); 14330 } 14331 if (db.bottom < h) { 14332 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 14333 r.op(0, db.bottom, w, h, Region.Op.UNION); 14334 } 14335 final int[] location = attachInfo.mTransparentLocation; 14336 getLocationInWindow(location); 14337 r.translate(location[0], location[1]); 14338 region.op(r, Region.Op.INTERSECT); 14339 } else { 14340 region.op(db, Region.Op.DIFFERENCE); 14341 } 14342 } 14343 14344 private void checkForLongClick(int delayOffset) { 14345 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 14346 mHasPerformedLongPress = false; 14347 14348 if (mPendingCheckForLongPress == null) { 14349 mPendingCheckForLongPress = new CheckForLongPress(); 14350 } 14351 mPendingCheckForLongPress.rememberWindowAttachCount(); 14352 postDelayed(mPendingCheckForLongPress, 14353 ViewConfiguration.getLongPressTimeout() - delayOffset); 14354 } 14355 } 14356 14357 /** 14358 * Inflate a view from an XML resource. This convenience method wraps the {@link 14359 * LayoutInflater} class, which provides a full range of options for view inflation. 14360 * 14361 * @param context The Context object for your activity or application. 14362 * @param resource The resource ID to inflate 14363 * @param root A view group that will be the parent. Used to properly inflate the 14364 * layout_* parameters. 14365 * @see LayoutInflater 14366 */ 14367 public static View inflate(Context context, int resource, ViewGroup root) { 14368 LayoutInflater factory = LayoutInflater.from(context); 14369 return factory.inflate(resource, root); 14370 } 14371 14372 /** 14373 * Scroll the view with standard behavior for scrolling beyond the normal 14374 * content boundaries. Views that call this method should override 14375 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 14376 * results of an over-scroll operation. 14377 * 14378 * Views can use this method to handle any touch or fling-based scrolling. 14379 * 14380 * @param deltaX Change in X in pixels 14381 * @param deltaY Change in Y in pixels 14382 * @param scrollX Current X scroll value in pixels before applying deltaX 14383 * @param scrollY Current Y scroll value in pixels before applying deltaY 14384 * @param scrollRangeX Maximum content scroll range along the X axis 14385 * @param scrollRangeY Maximum content scroll range along the Y axis 14386 * @param maxOverScrollX Number of pixels to overscroll by in either direction 14387 * along the X axis. 14388 * @param maxOverScrollY Number of pixels to overscroll by in either direction 14389 * along the Y axis. 14390 * @param isTouchEvent true if this scroll operation is the result of a touch event. 14391 * @return true if scrolling was clamped to an over-scroll boundary along either 14392 * axis, false otherwise. 14393 */ 14394 @SuppressWarnings({"UnusedParameters"}) 14395 protected boolean overScrollBy(int deltaX, int deltaY, 14396 int scrollX, int scrollY, 14397 int scrollRangeX, int scrollRangeY, 14398 int maxOverScrollX, int maxOverScrollY, 14399 boolean isTouchEvent) { 14400 final int overScrollMode = mOverScrollMode; 14401 final boolean canScrollHorizontal = 14402 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 14403 final boolean canScrollVertical = 14404 computeVerticalScrollRange() > computeVerticalScrollExtent(); 14405 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 14406 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 14407 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 14408 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 14409 14410 int newScrollX = scrollX + deltaX; 14411 if (!overScrollHorizontal) { 14412 maxOverScrollX = 0; 14413 } 14414 14415 int newScrollY = scrollY + deltaY; 14416 if (!overScrollVertical) { 14417 maxOverScrollY = 0; 14418 } 14419 14420 // Clamp values if at the limits and record 14421 final int left = -maxOverScrollX; 14422 final int right = maxOverScrollX + scrollRangeX; 14423 final int top = -maxOverScrollY; 14424 final int bottom = maxOverScrollY + scrollRangeY; 14425 14426 boolean clampedX = false; 14427 if (newScrollX > right) { 14428 newScrollX = right; 14429 clampedX = true; 14430 } else if (newScrollX < left) { 14431 newScrollX = left; 14432 clampedX = true; 14433 } 14434 14435 boolean clampedY = false; 14436 if (newScrollY > bottom) { 14437 newScrollY = bottom; 14438 clampedY = true; 14439 } else if (newScrollY < top) { 14440 newScrollY = top; 14441 clampedY = true; 14442 } 14443 14444 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 14445 14446 return clampedX || clampedY; 14447 } 14448 14449 /** 14450 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 14451 * respond to the results of an over-scroll operation. 14452 * 14453 * @param scrollX New X scroll value in pixels 14454 * @param scrollY New Y scroll value in pixels 14455 * @param clampedX True if scrollX was clamped to an over-scroll boundary 14456 * @param clampedY True if scrollY was clamped to an over-scroll boundary 14457 */ 14458 protected void onOverScrolled(int scrollX, int scrollY, 14459 boolean clampedX, boolean clampedY) { 14460 // Intentionally empty. 14461 } 14462 14463 /** 14464 * Returns the over-scroll mode for this view. The result will be 14465 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 14466 * (allow over-scrolling only if the view content is larger than the container), 14467 * or {@link #OVER_SCROLL_NEVER}. 14468 * 14469 * @return This view's over-scroll mode. 14470 */ 14471 public int getOverScrollMode() { 14472 return mOverScrollMode; 14473 } 14474 14475 /** 14476 * Set the over-scroll mode for this view. Valid over-scroll modes are 14477 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 14478 * (allow over-scrolling only if the view content is larger than the container), 14479 * or {@link #OVER_SCROLL_NEVER}. 14480 * 14481 * Setting the over-scroll mode of a view will have an effect only if the 14482 * view is capable of scrolling. 14483 * 14484 * @param overScrollMode The new over-scroll mode for this view. 14485 */ 14486 public void setOverScrollMode(int overScrollMode) { 14487 if (overScrollMode != OVER_SCROLL_ALWAYS && 14488 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 14489 overScrollMode != OVER_SCROLL_NEVER) { 14490 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 14491 } 14492 mOverScrollMode = overScrollMode; 14493 } 14494 14495 /** 14496 * Gets a scale factor that determines the distance the view should scroll 14497 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 14498 * @return The vertical scroll scale factor. 14499 * @hide 14500 */ 14501 protected float getVerticalScrollFactor() { 14502 if (mVerticalScrollFactor == 0) { 14503 TypedValue outValue = new TypedValue(); 14504 if (!mContext.getTheme().resolveAttribute( 14505 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 14506 throw new IllegalStateException( 14507 "Expected theme to define listPreferredItemHeight."); 14508 } 14509 mVerticalScrollFactor = outValue.getDimension( 14510 mContext.getResources().getDisplayMetrics()); 14511 } 14512 return mVerticalScrollFactor; 14513 } 14514 14515 /** 14516 * Gets a scale factor that determines the distance the view should scroll 14517 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 14518 * @return The horizontal scroll scale factor. 14519 * @hide 14520 */ 14521 protected float getHorizontalScrollFactor() { 14522 // TODO: Should use something else. 14523 return getVerticalScrollFactor(); 14524 } 14525 14526 /** 14527 * Return the value specifying the text direction or policy that was set with 14528 * {@link #setTextDirection(int)}. 14529 * 14530 * @return the defined text direction. It can be one of: 14531 * 14532 * {@link #TEXT_DIRECTION_INHERIT}, 14533 * {@link #TEXT_DIRECTION_FIRST_STRONG} 14534 * {@link #TEXT_DIRECTION_ANY_RTL}, 14535 * {@link #TEXT_DIRECTION_LTR}, 14536 * {@link #TEXT_DIRECTION_RTL}, 14537 * {@link #TEXT_DIRECTION_LOCALE}, 14538 */ 14539 @ViewDebug.ExportedProperty(category = "text", mapping = { 14540 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 14541 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 14542 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 14543 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 14544 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 14545 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 14546 }) 14547 public int getTextDirection() { 14548 return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT; 14549 } 14550 14551 /** 14552 * Set the text direction. 14553 * 14554 * @param textDirection the direction to set. Should be one of: 14555 * 14556 * {@link #TEXT_DIRECTION_INHERIT}, 14557 * {@link #TEXT_DIRECTION_FIRST_STRONG} 14558 * {@link #TEXT_DIRECTION_ANY_RTL}, 14559 * {@link #TEXT_DIRECTION_LTR}, 14560 * {@link #TEXT_DIRECTION_RTL}, 14561 * {@link #TEXT_DIRECTION_LOCALE}, 14562 */ 14563 public void setTextDirection(int textDirection) { 14564 if (getTextDirection() != textDirection) { 14565 // Reset the current text direction and the resolved one 14566 mPrivateFlags2 &= ~TEXT_DIRECTION_MASK; 14567 resetResolvedTextDirection(); 14568 // Set the new text direction 14569 mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK); 14570 requestLayout(); 14571 invalidate(true); 14572 } 14573 } 14574 14575 /** 14576 * Return the resolved text direction. 14577 * 14578 * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches 14579 * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds 14580 * up the parent chain of the view. if there is no parent, then it will return the default 14581 * {@link #TEXT_DIRECTION_FIRST_STRONG}. 14582 * 14583 * @return the resolved text direction. Returns one of: 14584 * 14585 * {@link #TEXT_DIRECTION_FIRST_STRONG} 14586 * {@link #TEXT_DIRECTION_ANY_RTL}, 14587 * {@link #TEXT_DIRECTION_LTR}, 14588 * {@link #TEXT_DIRECTION_RTL}, 14589 * {@link #TEXT_DIRECTION_LOCALE}, 14590 */ 14591 public int getResolvedTextDirection() { 14592 // The text direction will be resolved only if needed 14593 if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) { 14594 resolveTextDirection(); 14595 } 14596 return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 14597 } 14598 14599 /** 14600 * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when 14601 * resolution is done. 14602 */ 14603 public void resolveTextDirection() { 14604 // Reset any previous text direction resolution 14605 mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK); 14606 14607 // Set resolved text direction flag depending on text direction flag 14608 final int textDirection = getTextDirection(); 14609 switch(textDirection) { 14610 case TEXT_DIRECTION_INHERIT: 14611 if (canResolveTextDirection()) { 14612 ViewGroup viewGroup = ((ViewGroup) mParent); 14613 14614 // Set current resolved direction to the same value as the parent's one 14615 final int parentResolvedDirection = viewGroup.getResolvedTextDirection(); 14616 switch (parentResolvedDirection) { 14617 case TEXT_DIRECTION_FIRST_STRONG: 14618 case TEXT_DIRECTION_ANY_RTL: 14619 case TEXT_DIRECTION_LTR: 14620 case TEXT_DIRECTION_RTL: 14621 case TEXT_DIRECTION_LOCALE: 14622 mPrivateFlags2 |= 14623 (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 14624 break; 14625 default: 14626 // Default resolved direction is "first strong" heuristic 14627 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT; 14628 } 14629 } else { 14630 // We cannot do the resolution if there is no parent, so use the default one 14631 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT; 14632 } 14633 break; 14634 case TEXT_DIRECTION_FIRST_STRONG: 14635 case TEXT_DIRECTION_ANY_RTL: 14636 case TEXT_DIRECTION_LTR: 14637 case TEXT_DIRECTION_RTL: 14638 case TEXT_DIRECTION_LOCALE: 14639 // Resolved direction is the same as text direction 14640 mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 14641 break; 14642 default: 14643 // Default resolved direction is "first strong" heuristic 14644 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT; 14645 } 14646 14647 // Set to resolved 14648 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED; 14649 onResolvedTextDirectionChanged(); 14650 } 14651 14652 /** 14653 * Called when text direction has been resolved. Subclasses that care about text direction 14654 * resolution should override this method. 14655 * 14656 * The default implementation does nothing. 14657 */ 14658 public void onResolvedTextDirectionChanged() { 14659 } 14660 14661 /** 14662 * Check if text direction resolution can be done. 14663 * 14664 * @return true if text direction resolution can be done otherwise return false. 14665 */ 14666 public boolean canResolveTextDirection() { 14667 switch (getTextDirection()) { 14668 case TEXT_DIRECTION_INHERIT: 14669 return (mParent != null) && (mParent instanceof ViewGroup); 14670 default: 14671 return true; 14672 } 14673 } 14674 14675 /** 14676 * Reset resolved text direction. Text direction can be resolved with a call to 14677 * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when 14678 * reset is done. 14679 */ 14680 public void resetResolvedTextDirection() { 14681 mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK); 14682 onResolvedTextDirectionReset(); 14683 } 14684 14685 /** 14686 * Called when text direction is reset. Subclasses that care about text direction reset should 14687 * override this method and do a reset of the text direction of their children. The default 14688 * implementation does nothing. 14689 */ 14690 public void onResolvedTextDirectionReset() { 14691 } 14692 14693 // 14694 // Properties 14695 // 14696 /** 14697 * A Property wrapper around the <code>alpha</code> functionality handled by the 14698 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 14699 */ 14700 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 14701 @Override 14702 public void setValue(View object, float value) { 14703 object.setAlpha(value); 14704 } 14705 14706 @Override 14707 public Float get(View object) { 14708 return object.getAlpha(); 14709 } 14710 }; 14711 14712 /** 14713 * A Property wrapper around the <code>translationX</code> functionality handled by the 14714 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 14715 */ 14716 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 14717 @Override 14718 public void setValue(View object, float value) { 14719 object.setTranslationX(value); 14720 } 14721 14722 @Override 14723 public Float get(View object) { 14724 return object.getTranslationX(); 14725 } 14726 }; 14727 14728 /** 14729 * A Property wrapper around the <code>translationY</code> functionality handled by the 14730 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 14731 */ 14732 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 14733 @Override 14734 public void setValue(View object, float value) { 14735 object.setTranslationY(value); 14736 } 14737 14738 @Override 14739 public Float get(View object) { 14740 return object.getTranslationY(); 14741 } 14742 }; 14743 14744 /** 14745 * A Property wrapper around the <code>x</code> functionality handled by the 14746 * {@link View#setX(float)} and {@link View#getX()} methods. 14747 */ 14748 public static final Property<View, Float> X = new FloatProperty<View>("x") { 14749 @Override 14750 public void setValue(View object, float value) { 14751 object.setX(value); 14752 } 14753 14754 @Override 14755 public Float get(View object) { 14756 return object.getX(); 14757 } 14758 }; 14759 14760 /** 14761 * A Property wrapper around the <code>y</code> functionality handled by the 14762 * {@link View#setY(float)} and {@link View#getY()} methods. 14763 */ 14764 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 14765 @Override 14766 public void setValue(View object, float value) { 14767 object.setY(value); 14768 } 14769 14770 @Override 14771 public Float get(View object) { 14772 return object.getY(); 14773 } 14774 }; 14775 14776 /** 14777 * A Property wrapper around the <code>rotation</code> functionality handled by the 14778 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 14779 */ 14780 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 14781 @Override 14782 public void setValue(View object, float value) { 14783 object.setRotation(value); 14784 } 14785 14786 @Override 14787 public Float get(View object) { 14788 return object.getRotation(); 14789 } 14790 }; 14791 14792 /** 14793 * A Property wrapper around the <code>rotationX</code> functionality handled by the 14794 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 14795 */ 14796 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 14797 @Override 14798 public void setValue(View object, float value) { 14799 object.setRotationX(value); 14800 } 14801 14802 @Override 14803 public Float get(View object) { 14804 return object.getRotationX(); 14805 } 14806 }; 14807 14808 /** 14809 * A Property wrapper around the <code>rotationY</code> functionality handled by the 14810 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 14811 */ 14812 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 14813 @Override 14814 public void setValue(View object, float value) { 14815 object.setRotationY(value); 14816 } 14817 14818 @Override 14819 public Float get(View object) { 14820 return object.getRotationY(); 14821 } 14822 }; 14823 14824 /** 14825 * A Property wrapper around the <code>scaleX</code> functionality handled by the 14826 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 14827 */ 14828 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 14829 @Override 14830 public void setValue(View object, float value) { 14831 object.setScaleX(value); 14832 } 14833 14834 @Override 14835 public Float get(View object) { 14836 return object.getScaleX(); 14837 } 14838 }; 14839 14840 /** 14841 * A Property wrapper around the <code>scaleY</code> functionality handled by the 14842 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 14843 */ 14844 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 14845 @Override 14846 public void setValue(View object, float value) { 14847 object.setScaleY(value); 14848 } 14849 14850 @Override 14851 public Float get(View object) { 14852 return object.getScaleY(); 14853 } 14854 }; 14855 14856 /** 14857 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 14858 * Each MeasureSpec represents a requirement for either the width or the height. 14859 * A MeasureSpec is comprised of a size and a mode. There are three possible 14860 * modes: 14861 * <dl> 14862 * <dt>UNSPECIFIED</dt> 14863 * <dd> 14864 * The parent has not imposed any constraint on the child. It can be whatever size 14865 * it wants. 14866 * </dd> 14867 * 14868 * <dt>EXACTLY</dt> 14869 * <dd> 14870 * The parent has determined an exact size for the child. The child is going to be 14871 * given those bounds regardless of how big it wants to be. 14872 * </dd> 14873 * 14874 * <dt>AT_MOST</dt> 14875 * <dd> 14876 * The child can be as large as it wants up to the specified size. 14877 * </dd> 14878 * </dl> 14879 * 14880 * MeasureSpecs are implemented as ints to reduce object allocation. This class 14881 * is provided to pack and unpack the <size, mode> tuple into the int. 14882 */ 14883 public static class MeasureSpec { 14884 private static final int MODE_SHIFT = 30; 14885 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 14886 14887 /** 14888 * Measure specification mode: The parent has not imposed any constraint 14889 * on the child. It can be whatever size it wants. 14890 */ 14891 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 14892 14893 /** 14894 * Measure specification mode: The parent has determined an exact size 14895 * for the child. The child is going to be given those bounds regardless 14896 * of how big it wants to be. 14897 */ 14898 public static final int EXACTLY = 1 << MODE_SHIFT; 14899 14900 /** 14901 * Measure specification mode: The child can be as large as it wants up 14902 * to the specified size. 14903 */ 14904 public static final int AT_MOST = 2 << MODE_SHIFT; 14905 14906 /** 14907 * Creates a measure specification based on the supplied size and mode. 14908 * 14909 * The mode must always be one of the following: 14910 * <ul> 14911 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 14912 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 14913 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 14914 * </ul> 14915 * 14916 * @param size the size of the measure specification 14917 * @param mode the mode of the measure specification 14918 * @return the measure specification based on size and mode 14919 */ 14920 public static int makeMeasureSpec(int size, int mode) { 14921 return size + mode; 14922 } 14923 14924 /** 14925 * Extracts the mode from the supplied measure specification. 14926 * 14927 * @param measureSpec the measure specification to extract the mode from 14928 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 14929 * {@link android.view.View.MeasureSpec#AT_MOST} or 14930 * {@link android.view.View.MeasureSpec#EXACTLY} 14931 */ 14932 public static int getMode(int measureSpec) { 14933 return (measureSpec & MODE_MASK); 14934 } 14935 14936 /** 14937 * Extracts the size from the supplied measure specification. 14938 * 14939 * @param measureSpec the measure specification to extract the size from 14940 * @return the size in pixels defined in the supplied measure specification 14941 */ 14942 public static int getSize(int measureSpec) { 14943 return (measureSpec & ~MODE_MASK); 14944 } 14945 14946 /** 14947 * Returns a String representation of the specified measure 14948 * specification. 14949 * 14950 * @param measureSpec the measure specification to convert to a String 14951 * @return a String with the following format: "MeasureSpec: MODE SIZE" 14952 */ 14953 public static String toString(int measureSpec) { 14954 int mode = getMode(measureSpec); 14955 int size = getSize(measureSpec); 14956 14957 StringBuilder sb = new StringBuilder("MeasureSpec: "); 14958 14959 if (mode == UNSPECIFIED) 14960 sb.append("UNSPECIFIED "); 14961 else if (mode == EXACTLY) 14962 sb.append("EXACTLY "); 14963 else if (mode == AT_MOST) 14964 sb.append("AT_MOST "); 14965 else 14966 sb.append(mode).append(" "); 14967 14968 sb.append(size); 14969 return sb.toString(); 14970 } 14971 } 14972 14973 class CheckForLongPress implements Runnable { 14974 14975 private int mOriginalWindowAttachCount; 14976 14977 public void run() { 14978 if (isPressed() && (mParent != null) 14979 && mOriginalWindowAttachCount == mWindowAttachCount) { 14980 if (performLongClick()) { 14981 mHasPerformedLongPress = true; 14982 } 14983 } 14984 } 14985 14986 public void rememberWindowAttachCount() { 14987 mOriginalWindowAttachCount = mWindowAttachCount; 14988 } 14989 } 14990 14991 private final class CheckForTap implements Runnable { 14992 public void run() { 14993 mPrivateFlags &= ~PREPRESSED; 14994 setPressed(true); 14995 checkForLongClick(ViewConfiguration.getTapTimeout()); 14996 } 14997 } 14998 14999 private final class PerformClick implements Runnable { 15000 public void run() { 15001 performClick(); 15002 } 15003 } 15004 15005 /** @hide */ 15006 public void hackTurnOffWindowResizeAnim(boolean off) { 15007 mAttachInfo.mTurnOffWindowResizeAnim = off; 15008 } 15009 15010 /** 15011 * This method returns a ViewPropertyAnimator object, which can be used to animate 15012 * specific properties on this View. 15013 * 15014 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 15015 */ 15016 public ViewPropertyAnimator animate() { 15017 if (mAnimator == null) { 15018 mAnimator = new ViewPropertyAnimator(this); 15019 } 15020 return mAnimator; 15021 } 15022 15023 /** 15024 * Interface definition for a callback to be invoked when a key event is 15025 * dispatched to this view. The callback will be invoked before the key 15026 * event is given to the view. 15027 */ 15028 public interface OnKeyListener { 15029 /** 15030 * Called when a key is dispatched to a view. This allows listeners to 15031 * get a chance to respond before the target view. 15032 * 15033 * @param v The view the key has been dispatched to. 15034 * @param keyCode The code for the physical key that was pressed 15035 * @param event The KeyEvent object containing full information about 15036 * the event. 15037 * @return True if the listener has consumed the event, false otherwise. 15038 */ 15039 boolean onKey(View v, int keyCode, KeyEvent event); 15040 } 15041 15042 /** 15043 * Interface definition for a callback to be invoked when a touch event is 15044 * dispatched to this view. The callback will be invoked before the touch 15045 * event is given to the view. 15046 */ 15047 public interface OnTouchListener { 15048 /** 15049 * Called when a touch event is dispatched to a view. This allows listeners to 15050 * get a chance to respond before the target view. 15051 * 15052 * @param v The view the touch event has been dispatched to. 15053 * @param event The MotionEvent object containing full information about 15054 * the event. 15055 * @return True if the listener has consumed the event, false otherwise. 15056 */ 15057 boolean onTouch(View v, MotionEvent event); 15058 } 15059 15060 /** 15061 * Interface definition for a callback to be invoked when a hover event is 15062 * dispatched to this view. The callback will be invoked before the hover 15063 * event is given to the view. 15064 */ 15065 public interface OnHoverListener { 15066 /** 15067 * Called when a hover event is dispatched to a view. This allows listeners to 15068 * get a chance to respond before the target view. 15069 * 15070 * @param v The view the hover event has been dispatched to. 15071 * @param event The MotionEvent object containing full information about 15072 * the event. 15073 * @return True if the listener has consumed the event, false otherwise. 15074 */ 15075 boolean onHover(View v, MotionEvent event); 15076 } 15077 15078 /** 15079 * Interface definition for a callback to be invoked when a generic motion event is 15080 * dispatched to this view. The callback will be invoked before the generic motion 15081 * event is given to the view. 15082 */ 15083 public interface OnGenericMotionListener { 15084 /** 15085 * Called when a generic motion event is dispatched to a view. This allows listeners to 15086 * get a chance to respond before the target view. 15087 * 15088 * @param v The view the generic motion event has been dispatched to. 15089 * @param event The MotionEvent object containing full information about 15090 * the event. 15091 * @return True if the listener has consumed the event, false otherwise. 15092 */ 15093 boolean onGenericMotion(View v, MotionEvent event); 15094 } 15095 15096 /** 15097 * Interface definition for a callback to be invoked when a view has been clicked and held. 15098 */ 15099 public interface OnLongClickListener { 15100 /** 15101 * Called when a view has been clicked and held. 15102 * 15103 * @param v The view that was clicked and held. 15104 * 15105 * @return true if the callback consumed the long click, false otherwise. 15106 */ 15107 boolean onLongClick(View v); 15108 } 15109 15110 /** 15111 * Interface definition for a callback to be invoked when a drag is being dispatched 15112 * to this view. The callback will be invoked before the hosting view's own 15113 * onDrag(event) method. If the listener wants to fall back to the hosting view's 15114 * onDrag(event) behavior, it should return 'false' from this callback. 15115 * 15116 * <div class="special reference"> 15117 * <h3>Developer Guides</h3> 15118 * <p>For a guide to implementing drag and drop features, read the 15119 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 15120 * </div> 15121 */ 15122 public interface OnDragListener { 15123 /** 15124 * Called when a drag event is dispatched to a view. This allows listeners 15125 * to get a chance to override base View behavior. 15126 * 15127 * @param v The View that received the drag event. 15128 * @param event The {@link android.view.DragEvent} object for the drag event. 15129 * @return {@code true} if the drag event was handled successfully, or {@code false} 15130 * if the drag event was not handled. Note that {@code false} will trigger the View 15131 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 15132 */ 15133 boolean onDrag(View v, DragEvent event); 15134 } 15135 15136 /** 15137 * Interface definition for a callback to be invoked when the focus state of 15138 * a view changed. 15139 */ 15140 public interface OnFocusChangeListener { 15141 /** 15142 * Called when the focus state of a view has changed. 15143 * 15144 * @param v The view whose state has changed. 15145 * @param hasFocus The new focus state of v. 15146 */ 15147 void onFocusChange(View v, boolean hasFocus); 15148 } 15149 15150 /** 15151 * Interface definition for a callback to be invoked when a view is clicked. 15152 */ 15153 public interface OnClickListener { 15154 /** 15155 * Called when a view has been clicked. 15156 * 15157 * @param v The view that was clicked. 15158 */ 15159 void onClick(View v); 15160 } 15161 15162 /** 15163 * Interface definition for a callback to be invoked when the context menu 15164 * for this view is being built. 15165 */ 15166 public interface OnCreateContextMenuListener { 15167 /** 15168 * Called when the context menu for this view is being built. It is not 15169 * safe to hold onto the menu after this method returns. 15170 * 15171 * @param menu The context menu that is being built 15172 * @param v The view for which the context menu is being built 15173 * @param menuInfo Extra information about the item for which the 15174 * context menu should be shown. This information will vary 15175 * depending on the class of v. 15176 */ 15177 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 15178 } 15179 15180 /** 15181 * Interface definition for a callback to be invoked when the status bar changes 15182 * visibility. This reports <strong>global</strong> changes to the system UI 15183 * state, not just what the application is requesting. 15184 * 15185 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 15186 */ 15187 public interface OnSystemUiVisibilityChangeListener { 15188 /** 15189 * Called when the status bar changes visibility because of a call to 15190 * {@link View#setSystemUiVisibility(int)}. 15191 * 15192 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 15193 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. This tells you the 15194 * <strong>global</strong> state of the UI visibility flags, not what your 15195 * app is currently applying. 15196 */ 15197 public void onSystemUiVisibilityChange(int visibility); 15198 } 15199 15200 /** 15201 * Interface definition for a callback to be invoked when this view is attached 15202 * or detached from its window. 15203 */ 15204 public interface OnAttachStateChangeListener { 15205 /** 15206 * Called when the view is attached to a window. 15207 * @param v The view that was attached 15208 */ 15209 public void onViewAttachedToWindow(View v); 15210 /** 15211 * Called when the view is detached from a window. 15212 * @param v The view that was detached 15213 */ 15214 public void onViewDetachedFromWindow(View v); 15215 } 15216 15217 private final class UnsetPressedState implements Runnable { 15218 public void run() { 15219 setPressed(false); 15220 } 15221 } 15222 15223 /** 15224 * Base class for derived classes that want to save and restore their own 15225 * state in {@link android.view.View#onSaveInstanceState()}. 15226 */ 15227 public static class BaseSavedState extends AbsSavedState { 15228 /** 15229 * Constructor used when reading from a parcel. Reads the state of the superclass. 15230 * 15231 * @param source 15232 */ 15233 public BaseSavedState(Parcel source) { 15234 super(source); 15235 } 15236 15237 /** 15238 * Constructor called by derived classes when creating their SavedState objects 15239 * 15240 * @param superState The state of the superclass of this view 15241 */ 15242 public BaseSavedState(Parcelable superState) { 15243 super(superState); 15244 } 15245 15246 public static final Parcelable.Creator<BaseSavedState> CREATOR = 15247 new Parcelable.Creator<BaseSavedState>() { 15248 public BaseSavedState createFromParcel(Parcel in) { 15249 return new BaseSavedState(in); 15250 } 15251 15252 public BaseSavedState[] newArray(int size) { 15253 return new BaseSavedState[size]; 15254 } 15255 }; 15256 } 15257 15258 /** 15259 * A set of information given to a view when it is attached to its parent 15260 * window. 15261 */ 15262 static class AttachInfo { 15263 interface Callbacks { 15264 void playSoundEffect(int effectId); 15265 boolean performHapticFeedback(int effectId, boolean always); 15266 } 15267 15268 /** 15269 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 15270 * to a Handler. This class contains the target (View) to invalidate and 15271 * the coordinates of the dirty rectangle. 15272 * 15273 * For performance purposes, this class also implements a pool of up to 15274 * POOL_LIMIT objects that get reused. This reduces memory allocations 15275 * whenever possible. 15276 */ 15277 static class InvalidateInfo implements Poolable<InvalidateInfo> { 15278 private static final int POOL_LIMIT = 10; 15279 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 15280 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 15281 public InvalidateInfo newInstance() { 15282 return new InvalidateInfo(); 15283 } 15284 15285 public void onAcquired(InvalidateInfo element) { 15286 } 15287 15288 public void onReleased(InvalidateInfo element) { 15289 element.target = null; 15290 } 15291 }, POOL_LIMIT) 15292 ); 15293 15294 private InvalidateInfo mNext; 15295 private boolean mIsPooled; 15296 15297 View target; 15298 15299 int left; 15300 int top; 15301 int right; 15302 int bottom; 15303 15304 public void setNextPoolable(InvalidateInfo element) { 15305 mNext = element; 15306 } 15307 15308 public InvalidateInfo getNextPoolable() { 15309 return mNext; 15310 } 15311 15312 static InvalidateInfo acquire() { 15313 return sPool.acquire(); 15314 } 15315 15316 void release() { 15317 sPool.release(this); 15318 } 15319 15320 public boolean isPooled() { 15321 return mIsPooled; 15322 } 15323 15324 public void setPooled(boolean isPooled) { 15325 mIsPooled = isPooled; 15326 } 15327 } 15328 15329 final IWindowSession mSession; 15330 15331 final IWindow mWindow; 15332 15333 final IBinder mWindowToken; 15334 15335 final Callbacks mRootCallbacks; 15336 15337 HardwareCanvas mHardwareCanvas; 15338 15339 /** 15340 * The top view of the hierarchy. 15341 */ 15342 View mRootView; 15343 15344 IBinder mPanelParentWindowToken; 15345 Surface mSurface; 15346 15347 boolean mHardwareAccelerated; 15348 boolean mHardwareAccelerationRequested; 15349 HardwareRenderer mHardwareRenderer; 15350 15351 boolean mScreenOn; 15352 15353 /** 15354 * Scale factor used by the compatibility mode 15355 */ 15356 float mApplicationScale; 15357 15358 /** 15359 * Indicates whether the application is in compatibility mode 15360 */ 15361 boolean mScalingRequired; 15362 15363 /** 15364 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 15365 */ 15366 boolean mTurnOffWindowResizeAnim; 15367 15368 /** 15369 * Left position of this view's window 15370 */ 15371 int mWindowLeft; 15372 15373 /** 15374 * Top position of this view's window 15375 */ 15376 int mWindowTop; 15377 15378 /** 15379 * Indicates whether views need to use 32-bit drawing caches 15380 */ 15381 boolean mUse32BitDrawingCache; 15382 15383 /** 15384 * For windows that are full-screen but using insets to layout inside 15385 * of the screen decorations, these are the current insets for the 15386 * content of the window. 15387 */ 15388 final Rect mContentInsets = new Rect(); 15389 15390 /** 15391 * For windows that are full-screen but using insets to layout inside 15392 * of the screen decorations, these are the current insets for the 15393 * actual visible parts of the window. 15394 */ 15395 final Rect mVisibleInsets = new Rect(); 15396 15397 /** 15398 * The internal insets given by this window. This value is 15399 * supplied by the client (through 15400 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 15401 * be given to the window manager when changed to be used in laying 15402 * out windows behind it. 15403 */ 15404 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 15405 = new ViewTreeObserver.InternalInsetsInfo(); 15406 15407 /** 15408 * All views in the window's hierarchy that serve as scroll containers, 15409 * used to determine if the window can be resized or must be panned 15410 * to adjust for a soft input area. 15411 */ 15412 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 15413 15414 final KeyEvent.DispatcherState mKeyDispatchState 15415 = new KeyEvent.DispatcherState(); 15416 15417 /** 15418 * Indicates whether the view's window currently has the focus. 15419 */ 15420 boolean mHasWindowFocus; 15421 15422 /** 15423 * The current visibility of the window. 15424 */ 15425 int mWindowVisibility; 15426 15427 /** 15428 * Indicates the time at which drawing started to occur. 15429 */ 15430 long mDrawingTime; 15431 15432 /** 15433 * Indicates whether or not ignoring the DIRTY_MASK flags. 15434 */ 15435 boolean mIgnoreDirtyState; 15436 15437 /** 15438 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 15439 * to avoid clearing that flag prematurely. 15440 */ 15441 boolean mSetIgnoreDirtyState = false; 15442 15443 /** 15444 * Indicates whether the view's window is currently in touch mode. 15445 */ 15446 boolean mInTouchMode; 15447 15448 /** 15449 * Indicates that ViewAncestor should trigger a global layout change 15450 * the next time it performs a traversal 15451 */ 15452 boolean mRecomputeGlobalAttributes; 15453 15454 /** 15455 * Always report new attributes at next traversal. 15456 */ 15457 boolean mForceReportNewAttributes; 15458 15459 /** 15460 * Set during a traveral if any views want to keep the screen on. 15461 */ 15462 boolean mKeepScreenOn; 15463 15464 /** 15465 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 15466 */ 15467 int mSystemUiVisibility; 15468 15469 /** 15470 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 15471 * attached. 15472 */ 15473 boolean mHasSystemUiListeners; 15474 15475 /** 15476 * Set if the visibility of any views has changed. 15477 */ 15478 boolean mViewVisibilityChanged; 15479 15480 /** 15481 * Set to true if a view has been scrolled. 15482 */ 15483 boolean mViewScrollChanged; 15484 15485 /** 15486 * Global to the view hierarchy used as a temporary for dealing with 15487 * x/y points in the transparent region computations. 15488 */ 15489 final int[] mTransparentLocation = new int[2]; 15490 15491 /** 15492 * Global to the view hierarchy used as a temporary for dealing with 15493 * x/y points in the ViewGroup.invalidateChild implementation. 15494 */ 15495 final int[] mInvalidateChildLocation = new int[2]; 15496 15497 15498 /** 15499 * Global to the view hierarchy used as a temporary for dealing with 15500 * x/y location when view is transformed. 15501 */ 15502 final float[] mTmpTransformLocation = new float[2]; 15503 15504 /** 15505 * The view tree observer used to dispatch global events like 15506 * layout, pre-draw, touch mode change, etc. 15507 */ 15508 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 15509 15510 /** 15511 * A Canvas used by the view hierarchy to perform bitmap caching. 15512 */ 15513 Canvas mCanvas; 15514 15515 /** 15516 * The view root impl. 15517 */ 15518 final ViewRootImpl mViewRootImpl; 15519 15520 /** 15521 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 15522 * handler can be used to pump events in the UI events queue. 15523 */ 15524 final Handler mHandler; 15525 15526 /** 15527 * Temporary for use in computing invalidate rectangles while 15528 * calling up the hierarchy. 15529 */ 15530 final Rect mTmpInvalRect = new Rect(); 15531 15532 /** 15533 * Temporary for use in computing hit areas with transformed views 15534 */ 15535 final RectF mTmpTransformRect = new RectF(); 15536 15537 /** 15538 * Temporary list for use in collecting focusable descendents of a view. 15539 */ 15540 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 15541 15542 /** 15543 * The id of the window for accessibility purposes. 15544 */ 15545 int mAccessibilityWindowId = View.NO_ID; 15546 15547 /** 15548 * Creates a new set of attachment information with the specified 15549 * events handler and thread. 15550 * 15551 * @param handler the events handler the view must use 15552 */ 15553 AttachInfo(IWindowSession session, IWindow window, 15554 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 15555 mSession = session; 15556 mWindow = window; 15557 mWindowToken = window.asBinder(); 15558 mViewRootImpl = viewRootImpl; 15559 mHandler = handler; 15560 mRootCallbacks = effectPlayer; 15561 } 15562 } 15563 15564 /** 15565 * <p>ScrollabilityCache holds various fields used by a View when scrolling 15566 * is supported. This avoids keeping too many unused fields in most 15567 * instances of View.</p> 15568 */ 15569 private static class ScrollabilityCache implements Runnable { 15570 15571 /** 15572 * Scrollbars are not visible 15573 */ 15574 public static final int OFF = 0; 15575 15576 /** 15577 * Scrollbars are visible 15578 */ 15579 public static final int ON = 1; 15580 15581 /** 15582 * Scrollbars are fading away 15583 */ 15584 public static final int FADING = 2; 15585 15586 public boolean fadeScrollBars; 15587 15588 public int fadingEdgeLength; 15589 public int scrollBarDefaultDelayBeforeFade; 15590 public int scrollBarFadeDuration; 15591 15592 public int scrollBarSize; 15593 public ScrollBarDrawable scrollBar; 15594 public float[] interpolatorValues; 15595 public View host; 15596 15597 public final Paint paint; 15598 public final Matrix matrix; 15599 public Shader shader; 15600 15601 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 15602 15603 private static final float[] OPAQUE = { 255 }; 15604 private static final float[] TRANSPARENT = { 0.0f }; 15605 15606 /** 15607 * When fading should start. This time moves into the future every time 15608 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 15609 */ 15610 public long fadeStartTime; 15611 15612 15613 /** 15614 * The current state of the scrollbars: ON, OFF, or FADING 15615 */ 15616 public int state = OFF; 15617 15618 private int mLastColor; 15619 15620 public ScrollabilityCache(ViewConfiguration configuration, View host) { 15621 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 15622 scrollBarSize = configuration.getScaledScrollBarSize(); 15623 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 15624 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 15625 15626 paint = new Paint(); 15627 matrix = new Matrix(); 15628 // use use a height of 1, and then wack the matrix each time we 15629 // actually use it. 15630 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 15631 15632 paint.setShader(shader); 15633 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 15634 this.host = host; 15635 } 15636 15637 public void setFadeColor(int color) { 15638 if (color != 0 && color != mLastColor) { 15639 mLastColor = color; 15640 color |= 0xFF000000; 15641 15642 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 15643 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 15644 15645 paint.setShader(shader); 15646 // Restore the default transfer mode (src_over) 15647 paint.setXfermode(null); 15648 } 15649 } 15650 15651 public void run() { 15652 long now = AnimationUtils.currentAnimationTimeMillis(); 15653 if (now >= fadeStartTime) { 15654 15655 // the animation fades the scrollbars out by changing 15656 // the opacity (alpha) from fully opaque to fully 15657 // transparent 15658 int nextFrame = (int) now; 15659 int framesCount = 0; 15660 15661 Interpolator interpolator = scrollBarInterpolator; 15662 15663 // Start opaque 15664 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 15665 15666 // End transparent 15667 nextFrame += scrollBarFadeDuration; 15668 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 15669 15670 state = FADING; 15671 15672 // Kick off the fade animation 15673 host.invalidate(true); 15674 } 15675 } 15676 } 15677 15678 /** 15679 * Resuable callback for sending 15680 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 15681 */ 15682 private class SendViewScrolledAccessibilityEvent implements Runnable { 15683 public volatile boolean mIsPending; 15684 15685 public void run() { 15686 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 15687 mIsPending = false; 15688 } 15689 } 15690 15691 /** 15692 * <p> 15693 * This class represents a delegate that can be registered in a {@link View} 15694 * to enhance accessibility support via composition rather via inheritance. 15695 * It is specifically targeted to widget developers that extend basic View 15696 * classes i.e. classes in package android.view, that would like their 15697 * applications to be backwards compatible. 15698 * </p> 15699 * <p> 15700 * A scenario in which a developer would like to use an accessibility delegate 15701 * is overriding a method introduced in a later API version then the minimal API 15702 * version supported by the application. For example, the method 15703 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 15704 * in API version 4 when the accessibility APIs were first introduced. If a 15705 * developer would like his application to run on API version 4 devices (assuming 15706 * all other APIs used by the application are version 4 or lower) and take advantage 15707 * of this method, instead of overriding the method which would break the application's 15708 * backwards compatibility, he can override the corresponding method in this 15709 * delegate and register the delegate in the target View if the API version of 15710 * the system is high enough i.e. the API version is same or higher to the API 15711 * version that introduced 15712 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 15713 * </p> 15714 * <p> 15715 * Here is an example implementation: 15716 * </p> 15717 * <code><pre><p> 15718 * if (Build.VERSION.SDK_INT >= 14) { 15719 * // If the API version is equal of higher than the version in 15720 * // which onInitializeAccessibilityNodeInfo was introduced we 15721 * // register a delegate with a customized implementation. 15722 * View view = findViewById(R.id.view_id); 15723 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 15724 * public void onInitializeAccessibilityNodeInfo(View host, 15725 * AccessibilityNodeInfo info) { 15726 * // Let the default implementation populate the info. 15727 * super.onInitializeAccessibilityNodeInfo(host, info); 15728 * // Set some other information. 15729 * info.setEnabled(host.isEnabled()); 15730 * } 15731 * }); 15732 * } 15733 * </code></pre></p> 15734 * <p> 15735 * This delegate contains methods that correspond to the accessibility methods 15736 * in View. If a delegate has been specified the implementation in View hands 15737 * off handling to the corresponding method in this delegate. The default 15738 * implementation the delegate methods behaves exactly as the corresponding 15739 * method in View for the case of no accessibility delegate been set. Hence, 15740 * to customize the behavior of a View method, clients can override only the 15741 * corresponding delegate method without altering the behavior of the rest 15742 * accessibility related methods of the host view. 15743 * </p> 15744 */ 15745 public static class AccessibilityDelegate { 15746 15747 /** 15748 * Sends an accessibility event of the given type. If accessibility is not 15749 * enabled this method has no effect. 15750 * <p> 15751 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 15752 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 15753 * been set. 15754 * </p> 15755 * 15756 * @param host The View hosting the delegate. 15757 * @param eventType The type of the event to send. 15758 * 15759 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 15760 */ 15761 public void sendAccessibilityEvent(View host, int eventType) { 15762 host.sendAccessibilityEventInternal(eventType); 15763 } 15764 15765 /** 15766 * Sends an accessibility event. This method behaves exactly as 15767 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 15768 * empty {@link AccessibilityEvent} and does not perform a check whether 15769 * accessibility is enabled. 15770 * <p> 15771 * The default implementation behaves as 15772 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 15773 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 15774 * the case of no accessibility delegate been set. 15775 * </p> 15776 * 15777 * @param host The View hosting the delegate. 15778 * @param event The event to send. 15779 * 15780 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 15781 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 15782 */ 15783 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 15784 host.sendAccessibilityEventUncheckedInternal(event); 15785 } 15786 15787 /** 15788 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 15789 * to its children for adding their text content to the event. 15790 * <p> 15791 * The default implementation behaves as 15792 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 15793 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 15794 * the case of no accessibility delegate been set. 15795 * </p> 15796 * 15797 * @param host The View hosting the delegate. 15798 * @param event The event. 15799 * @return True if the event population was completed. 15800 * 15801 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 15802 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 15803 */ 15804 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 15805 return host.dispatchPopulateAccessibilityEventInternal(event); 15806 } 15807 15808 /** 15809 * Gives a chance to the host View to populate the accessibility event with its 15810 * text content. 15811 * <p> 15812 * The default implementation behaves as 15813 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 15814 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 15815 * the case of no accessibility delegate been set. 15816 * </p> 15817 * 15818 * @param host The View hosting the delegate. 15819 * @param event The accessibility event which to populate. 15820 * 15821 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 15822 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 15823 */ 15824 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 15825 host.onPopulateAccessibilityEventInternal(event); 15826 } 15827 15828 /** 15829 * Initializes an {@link AccessibilityEvent} with information about the 15830 * the host View which is the event source. 15831 * <p> 15832 * The default implementation behaves as 15833 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 15834 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 15835 * the case of no accessibility delegate been set. 15836 * </p> 15837 * 15838 * @param host The View hosting the delegate. 15839 * @param event The event to initialize. 15840 * 15841 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 15842 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 15843 */ 15844 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 15845 host.onInitializeAccessibilityEventInternal(event); 15846 } 15847 15848 /** 15849 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 15850 * <p> 15851 * The default implementation behaves as 15852 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 15853 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 15854 * the case of no accessibility delegate been set. 15855 * </p> 15856 * 15857 * @param host The View hosting the delegate. 15858 * @param info The instance to initialize. 15859 * 15860 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 15861 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 15862 */ 15863 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 15864 host.onInitializeAccessibilityNodeInfoInternal(info); 15865 } 15866 15867 /** 15868 * Called when a child of the host View has requested sending an 15869 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 15870 * to augment the event. 15871 * <p> 15872 * The default implementation behaves as 15873 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 15874 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 15875 * the case of no accessibility delegate been set. 15876 * </p> 15877 * 15878 * @param host The View hosting the delegate. 15879 * @param child The child which requests sending the event. 15880 * @param event The event to be sent. 15881 * @return True if the event should be sent 15882 * 15883 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 15884 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 15885 */ 15886 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 15887 AccessibilityEvent event) { 15888 return host.onRequestSendAccessibilityEventInternal(child, event); 15889 } 15890 15891 /** 15892 * Gets the provider for managing a virtual view hierarchy rooted at this View 15893 * and reported to {@link android.accessibilityservice.AccessibilityService}s 15894 * that explore the window content. 15895 * <p> 15896 * The default implementation behaves as 15897 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 15898 * the case of no accessibility delegate been set. 15899 * </p> 15900 * 15901 * @return The provider. 15902 * 15903 * @see AccessibilityNodeProvider 15904 */ 15905 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 15906 return null; 15907 } 15908 } 15909} 15910