View.java revision 59dfce8bdaf011337530a0dbec7f7280871f9bc9
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 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 9869 */ 9870 private boolean hasRtlSupport() { 9871 return mContext.getApplicationInfo().hasRtlSupport(); 9872 } 9873 9874 /** 9875 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 9876 * that the parent directionality can and will be resolved before its children. 9877 * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done. 9878 */ 9879 public void resolveLayoutDirection() { 9880 // Clear any previous layout direction resolution 9881 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK; 9882 9883 if (hasRtlSupport()) { 9884 // Set resolved depending on layout direction 9885 switch (getLayoutDirection()) { 9886 case LAYOUT_DIRECTION_INHERIT: 9887 // If this is root view, no need to look at parent's layout dir. 9888 if (canResolveLayoutDirection()) { 9889 ViewGroup viewGroup = ((ViewGroup) mParent); 9890 9891 if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 9892 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9893 } 9894 } else { 9895 // Nothing to do, LTR by default 9896 } 9897 break; 9898 case LAYOUT_DIRECTION_RTL: 9899 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9900 break; 9901 case LAYOUT_DIRECTION_LOCALE: 9902 if(isLayoutDirectionRtl(Locale.getDefault())) { 9903 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9904 } 9905 break; 9906 default: 9907 // Nothing to do, LTR by default 9908 } 9909 } 9910 9911 // Set to resolved 9912 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED; 9913 onResolvedLayoutDirectionChanged(); 9914 // Resolve padding 9915 resolvePadding(); 9916 } 9917 9918 /** 9919 * Called when layout direction has been resolved. 9920 * 9921 * The default implementation does nothing. 9922 */ 9923 public void onResolvedLayoutDirectionChanged() { 9924 } 9925 9926 /** 9927 * Resolve padding depending on layout direction. 9928 */ 9929 public void resolvePadding() { 9930 // If the user specified the absolute padding (either with android:padding or 9931 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 9932 // use the default padding or the padding from the background drawable 9933 // (stored at this point in mPadding*) 9934 int resolvedLayoutDirection = getResolvedLayoutDirection(); 9935 switch (resolvedLayoutDirection) { 9936 case LAYOUT_DIRECTION_RTL: 9937 // Start user padding override Right user padding. Otherwise, if Right user 9938 // padding is not defined, use the default Right padding. If Right user padding 9939 // is defined, just use it. 9940 if (mUserPaddingStart >= 0) { 9941 mUserPaddingRight = mUserPaddingStart; 9942 } else if (mUserPaddingRight < 0) { 9943 mUserPaddingRight = mPaddingRight; 9944 } 9945 if (mUserPaddingEnd >= 0) { 9946 mUserPaddingLeft = mUserPaddingEnd; 9947 } else if (mUserPaddingLeft < 0) { 9948 mUserPaddingLeft = mPaddingLeft; 9949 } 9950 break; 9951 case LAYOUT_DIRECTION_LTR: 9952 default: 9953 // Start user padding override Left user padding. Otherwise, if Left user 9954 // padding is not defined, use the default left padding. If Left user padding 9955 // is defined, just use it. 9956 if (mUserPaddingStart >= 0) { 9957 mUserPaddingLeft = mUserPaddingStart; 9958 } else if (mUserPaddingLeft < 0) { 9959 mUserPaddingLeft = mPaddingLeft; 9960 } 9961 if (mUserPaddingEnd >= 0) { 9962 mUserPaddingRight = mUserPaddingEnd; 9963 } else if (mUserPaddingRight < 0) { 9964 mUserPaddingRight = mPaddingRight; 9965 } 9966 } 9967 9968 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 9969 9970 if(isPaddingRelative()) { 9971 setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom); 9972 } else { 9973 recomputePadding(); 9974 } 9975 onPaddingChanged(resolvedLayoutDirection); 9976 } 9977 9978 /** 9979 * Resolve padding depending on the layout direction. Subclasses that care about 9980 * padding resolution should override this method. The default implementation does 9981 * nothing. 9982 * 9983 * @param layoutDirection the direction of the layout 9984 * 9985 * @see {@link #LAYOUT_DIRECTION_LTR} 9986 * @see {@link #LAYOUT_DIRECTION_RTL} 9987 */ 9988 public void onPaddingChanged(int layoutDirection) { 9989 } 9990 9991 /** 9992 * Check if layout direction resolution can be done. 9993 * 9994 * @return true if layout direction resolution can be done otherwise return false. 9995 */ 9996 public boolean canResolveLayoutDirection() { 9997 switch (getLayoutDirection()) { 9998 case LAYOUT_DIRECTION_INHERIT: 9999 return (mParent != null) && (mParent instanceof ViewGroup); 10000 default: 10001 return true; 10002 } 10003 } 10004 10005 /** 10006 * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset} 10007 * when reset is done. 10008 */ 10009 public void resetResolvedLayoutDirection() { 10010 // Reset the current resolved bits 10011 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK; 10012 onResolvedLayoutDirectionReset(); 10013 // Reset also the text direction 10014 resetResolvedTextDirection(); 10015 } 10016 10017 /** 10018 * Called during reset of resolved layout direction. 10019 * 10020 * Subclasses need to override this method to clear cached information that depends on the 10021 * resolved layout direction, or to inform child views that inherit their layout direction. 10022 * 10023 * The default implementation does nothing. 10024 */ 10025 public void onResolvedLayoutDirectionReset() { 10026 } 10027 10028 /** 10029 * Check if a Locale uses an RTL script. 10030 * 10031 * @param locale Locale to check 10032 * @return true if the Locale uses an RTL script. 10033 */ 10034 protected static boolean isLayoutDirectionRtl(Locale locale) { 10035 return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale)); 10036 } 10037 10038 /** 10039 * This is called when the view is detached from a window. At this point it 10040 * no longer has a surface for drawing. 10041 * 10042 * @see #onAttachedToWindow() 10043 */ 10044 protected void onDetachedFromWindow() { 10045 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 10046 10047 removeUnsetPressCallback(); 10048 removeLongPressCallback(); 10049 removePerformClickCallback(); 10050 removeSendViewScrolledAccessibilityEventCallback(); 10051 10052 destroyDrawingCache(); 10053 10054 destroyLayer(false); 10055 10056 if (mAttachInfo != null) { 10057 if (mDisplayList != null) { 10058 mAttachInfo.mViewRootImpl.invalidateDisplayList(mDisplayList); 10059 } 10060 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 10061 } else { 10062 if (mDisplayList != null) { 10063 // Should never happen 10064 mDisplayList.invalidate(); 10065 } 10066 } 10067 10068 mCurrentAnimation = null; 10069 10070 resetResolvedLayoutDirection(); 10071 } 10072 10073 /** 10074 * @return The number of times this view has been attached to a window 10075 */ 10076 protected int getWindowAttachCount() { 10077 return mWindowAttachCount; 10078 } 10079 10080 /** 10081 * Retrieve a unique token identifying the window this view is attached to. 10082 * @return Return the window's token for use in 10083 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 10084 */ 10085 public IBinder getWindowToken() { 10086 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 10087 } 10088 10089 /** 10090 * Retrieve a unique token identifying the top-level "real" window of 10091 * the window that this view is attached to. That is, this is like 10092 * {@link #getWindowToken}, except if the window this view in is a panel 10093 * window (attached to another containing window), then the token of 10094 * the containing window is returned instead. 10095 * 10096 * @return Returns the associated window token, either 10097 * {@link #getWindowToken()} or the containing window's token. 10098 */ 10099 public IBinder getApplicationWindowToken() { 10100 AttachInfo ai = mAttachInfo; 10101 if (ai != null) { 10102 IBinder appWindowToken = ai.mPanelParentWindowToken; 10103 if (appWindowToken == null) { 10104 appWindowToken = ai.mWindowToken; 10105 } 10106 return appWindowToken; 10107 } 10108 return null; 10109 } 10110 10111 /** 10112 * Retrieve private session object this view hierarchy is using to 10113 * communicate with the window manager. 10114 * @return the session object to communicate with the window manager 10115 */ 10116 /*package*/ IWindowSession getWindowSession() { 10117 return mAttachInfo != null ? mAttachInfo.mSession : null; 10118 } 10119 10120 /** 10121 * @param info the {@link android.view.View.AttachInfo} to associated with 10122 * this view 10123 */ 10124 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 10125 //System.out.println("Attached! " + this); 10126 mAttachInfo = info; 10127 mWindowAttachCount++; 10128 // We will need to evaluate the drawable state at least once. 10129 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 10130 if (mFloatingTreeObserver != null) { 10131 info.mTreeObserver.merge(mFloatingTreeObserver); 10132 mFloatingTreeObserver = null; 10133 } 10134 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 10135 mAttachInfo.mScrollContainers.add(this); 10136 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 10137 } 10138 performCollectViewAttributes(visibility); 10139 onAttachedToWindow(); 10140 10141 ListenerInfo li = mListenerInfo; 10142 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 10143 li != null ? li.mOnAttachStateChangeListeners : null; 10144 if (listeners != null && listeners.size() > 0) { 10145 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 10146 // perform the dispatching. The iterator is a safe guard against listeners that 10147 // could mutate the list by calling the various add/remove methods. This prevents 10148 // the array from being modified while we iterate it. 10149 for (OnAttachStateChangeListener listener : listeners) { 10150 listener.onViewAttachedToWindow(this); 10151 } 10152 } 10153 10154 int vis = info.mWindowVisibility; 10155 if (vis != GONE) { 10156 onWindowVisibilityChanged(vis); 10157 } 10158 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 10159 // If nobody has evaluated the drawable state yet, then do it now. 10160 refreshDrawableState(); 10161 } 10162 } 10163 10164 void dispatchDetachedFromWindow() { 10165 AttachInfo info = mAttachInfo; 10166 if (info != null) { 10167 int vis = info.mWindowVisibility; 10168 if (vis != GONE) { 10169 onWindowVisibilityChanged(GONE); 10170 } 10171 } 10172 10173 onDetachedFromWindow(); 10174 10175 ListenerInfo li = mListenerInfo; 10176 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 10177 li != null ? li.mOnAttachStateChangeListeners : null; 10178 if (listeners != null && listeners.size() > 0) { 10179 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 10180 // perform the dispatching. The iterator is a safe guard against listeners that 10181 // could mutate the list by calling the various add/remove methods. This prevents 10182 // the array from being modified while we iterate it. 10183 for (OnAttachStateChangeListener listener : listeners) { 10184 listener.onViewDetachedFromWindow(this); 10185 } 10186 } 10187 10188 if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) { 10189 mAttachInfo.mScrollContainers.remove(this); 10190 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 10191 } 10192 10193 mAttachInfo = null; 10194 } 10195 10196 /** 10197 * Store this view hierarchy's frozen state into the given container. 10198 * 10199 * @param container The SparseArray in which to save the view's state. 10200 * 10201 * @see #restoreHierarchyState(android.util.SparseArray) 10202 * @see #dispatchSaveInstanceState(android.util.SparseArray) 10203 * @see #onSaveInstanceState() 10204 */ 10205 public void saveHierarchyState(SparseArray<Parcelable> container) { 10206 dispatchSaveInstanceState(container); 10207 } 10208 10209 /** 10210 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 10211 * this view and its children. May be overridden to modify how freezing happens to a 10212 * view's children; for example, some views may want to not store state for their children. 10213 * 10214 * @param container The SparseArray in which to save the view's state. 10215 * 10216 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 10217 * @see #saveHierarchyState(android.util.SparseArray) 10218 * @see #onSaveInstanceState() 10219 */ 10220 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 10221 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 10222 mPrivateFlags &= ~SAVE_STATE_CALLED; 10223 Parcelable state = onSaveInstanceState(); 10224 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 10225 throw new IllegalStateException( 10226 "Derived class did not call super.onSaveInstanceState()"); 10227 } 10228 if (state != null) { 10229 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 10230 // + ": " + state); 10231 container.put(mID, state); 10232 } 10233 } 10234 } 10235 10236 /** 10237 * Hook allowing a view to generate a representation of its internal state 10238 * that can later be used to create a new instance with that same state. 10239 * This state should only contain information that is not persistent or can 10240 * not be reconstructed later. For example, you will never store your 10241 * current position on screen because that will be computed again when a 10242 * new instance of the view is placed in its view hierarchy. 10243 * <p> 10244 * Some examples of things you may store here: the current cursor position 10245 * in a text view (but usually not the text itself since that is stored in a 10246 * content provider or other persistent storage), the currently selected 10247 * item in a list view. 10248 * 10249 * @return Returns a Parcelable object containing the view's current dynamic 10250 * state, or null if there is nothing interesting to save. The 10251 * default implementation returns null. 10252 * @see #onRestoreInstanceState(android.os.Parcelable) 10253 * @see #saveHierarchyState(android.util.SparseArray) 10254 * @see #dispatchSaveInstanceState(android.util.SparseArray) 10255 * @see #setSaveEnabled(boolean) 10256 */ 10257 protected Parcelable onSaveInstanceState() { 10258 mPrivateFlags |= SAVE_STATE_CALLED; 10259 return BaseSavedState.EMPTY_STATE; 10260 } 10261 10262 /** 10263 * Restore this view hierarchy's frozen state from the given container. 10264 * 10265 * @param container The SparseArray which holds previously frozen states. 10266 * 10267 * @see #saveHierarchyState(android.util.SparseArray) 10268 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 10269 * @see #onRestoreInstanceState(android.os.Parcelable) 10270 */ 10271 public void restoreHierarchyState(SparseArray<Parcelable> container) { 10272 dispatchRestoreInstanceState(container); 10273 } 10274 10275 /** 10276 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 10277 * state for this view and its children. May be overridden to modify how restoring 10278 * happens to a view's children; for example, some views may want to not store state 10279 * for their children. 10280 * 10281 * @param container The SparseArray which holds previously saved state. 10282 * 10283 * @see #dispatchSaveInstanceState(android.util.SparseArray) 10284 * @see #restoreHierarchyState(android.util.SparseArray) 10285 * @see #onRestoreInstanceState(android.os.Parcelable) 10286 */ 10287 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 10288 if (mID != NO_ID) { 10289 Parcelable state = container.get(mID); 10290 if (state != null) { 10291 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 10292 // + ": " + state); 10293 mPrivateFlags &= ~SAVE_STATE_CALLED; 10294 onRestoreInstanceState(state); 10295 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 10296 throw new IllegalStateException( 10297 "Derived class did not call super.onRestoreInstanceState()"); 10298 } 10299 } 10300 } 10301 } 10302 10303 /** 10304 * Hook allowing a view to re-apply a representation of its internal state that had previously 10305 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 10306 * null state. 10307 * 10308 * @param state The frozen state that had previously been returned by 10309 * {@link #onSaveInstanceState}. 10310 * 10311 * @see #onSaveInstanceState() 10312 * @see #restoreHierarchyState(android.util.SparseArray) 10313 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 10314 */ 10315 protected void onRestoreInstanceState(Parcelable state) { 10316 mPrivateFlags |= SAVE_STATE_CALLED; 10317 if (state != BaseSavedState.EMPTY_STATE && state != null) { 10318 throw new IllegalArgumentException("Wrong state class, expecting View State but " 10319 + "received " + state.getClass().toString() + " instead. This usually happens " 10320 + "when two views of different type have the same id in the same hierarchy. " 10321 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 10322 + "other views do not use the same id."); 10323 } 10324 } 10325 10326 /** 10327 * <p>Return the time at which the drawing of the view hierarchy started.</p> 10328 * 10329 * @return the drawing start time in milliseconds 10330 */ 10331 public long getDrawingTime() { 10332 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 10333 } 10334 10335 /** 10336 * <p>Enables or disables the duplication of the parent's state into this view. When 10337 * duplication is enabled, this view gets its drawable state from its parent rather 10338 * than from its own internal properties.</p> 10339 * 10340 * <p>Note: in the current implementation, setting this property to true after the 10341 * view was added to a ViewGroup might have no effect at all. This property should 10342 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 10343 * 10344 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 10345 * property is enabled, an exception will be thrown.</p> 10346 * 10347 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 10348 * parent, these states should not be affected by this method.</p> 10349 * 10350 * @param enabled True to enable duplication of the parent's drawable state, false 10351 * to disable it. 10352 * 10353 * @see #getDrawableState() 10354 * @see #isDuplicateParentStateEnabled() 10355 */ 10356 public void setDuplicateParentStateEnabled(boolean enabled) { 10357 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 10358 } 10359 10360 /** 10361 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 10362 * 10363 * @return True if this view's drawable state is duplicated from the parent, 10364 * false otherwise 10365 * 10366 * @see #getDrawableState() 10367 * @see #setDuplicateParentStateEnabled(boolean) 10368 */ 10369 public boolean isDuplicateParentStateEnabled() { 10370 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 10371 } 10372 10373 /** 10374 * <p>Specifies the type of layer backing this view. The layer can be 10375 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 10376 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 10377 * 10378 * <p>A layer is associated with an optional {@link android.graphics.Paint} 10379 * instance that controls how the layer is composed on screen. The following 10380 * properties of the paint are taken into account when composing the layer:</p> 10381 * <ul> 10382 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 10383 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 10384 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 10385 * </ul> 10386 * 10387 * <p>If this view has an alpha value set to < 1.0 by calling 10388 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 10389 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 10390 * equivalent to setting a hardware layer on this view and providing a paint with 10391 * the desired alpha value.<p> 10392 * 10393 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 10394 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 10395 * for more information on when and how to use layers.</p> 10396 * 10397 * @param layerType The ype of layer to use with this view, must be one of 10398 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 10399 * {@link #LAYER_TYPE_HARDWARE} 10400 * @param paint The paint used to compose the layer. This argument is optional 10401 * and can be null. It is ignored when the layer type is 10402 * {@link #LAYER_TYPE_NONE} 10403 * 10404 * @see #getLayerType() 10405 * @see #LAYER_TYPE_NONE 10406 * @see #LAYER_TYPE_SOFTWARE 10407 * @see #LAYER_TYPE_HARDWARE 10408 * @see #setAlpha(float) 10409 * 10410 * @attr ref android.R.styleable#View_layerType 10411 */ 10412 public void setLayerType(int layerType, Paint paint) { 10413 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 10414 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 10415 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 10416 } 10417 10418 if (layerType == mLayerType) { 10419 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 10420 mLayerPaint = paint == null ? new Paint() : paint; 10421 invalidateParentCaches(); 10422 invalidate(true); 10423 } 10424 return; 10425 } 10426 10427 // Destroy any previous software drawing cache if needed 10428 switch (mLayerType) { 10429 case LAYER_TYPE_HARDWARE: 10430 destroyLayer(false); 10431 // fall through - non-accelerated views may use software layer mechanism instead 10432 case LAYER_TYPE_SOFTWARE: 10433 destroyDrawingCache(); 10434 break; 10435 default: 10436 break; 10437 } 10438 10439 mLayerType = layerType; 10440 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 10441 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 10442 mLocalDirtyRect = layerDisabled ? null : new Rect(); 10443 10444 invalidateParentCaches(); 10445 invalidate(true); 10446 } 10447 10448 /** 10449 * Indicates whether this view has a static layer. A view with layer type 10450 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 10451 * dynamic. 10452 */ 10453 boolean hasStaticLayer() { 10454 return true; 10455 } 10456 10457 /** 10458 * Indicates what type of layer is currently associated with this view. By default 10459 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 10460 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 10461 * for more information on the different types of layers. 10462 * 10463 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 10464 * {@link #LAYER_TYPE_HARDWARE} 10465 * 10466 * @see #setLayerType(int, android.graphics.Paint) 10467 * @see #buildLayer() 10468 * @see #LAYER_TYPE_NONE 10469 * @see #LAYER_TYPE_SOFTWARE 10470 * @see #LAYER_TYPE_HARDWARE 10471 */ 10472 public int getLayerType() { 10473 return mLayerType; 10474 } 10475 10476 /** 10477 * Forces this view's layer to be created and this view to be rendered 10478 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 10479 * invoking this method will have no effect. 10480 * 10481 * This method can for instance be used to render a view into its layer before 10482 * starting an animation. If this view is complex, rendering into the layer 10483 * before starting the animation will avoid skipping frames. 10484 * 10485 * @throws IllegalStateException If this view is not attached to a window 10486 * 10487 * @see #setLayerType(int, android.graphics.Paint) 10488 */ 10489 public void buildLayer() { 10490 if (mLayerType == LAYER_TYPE_NONE) return; 10491 10492 if (mAttachInfo == null) { 10493 throw new IllegalStateException("This view must be attached to a window first"); 10494 } 10495 10496 switch (mLayerType) { 10497 case LAYER_TYPE_HARDWARE: 10498 if (mAttachInfo.mHardwareRenderer != null && 10499 mAttachInfo.mHardwareRenderer.isEnabled() && 10500 mAttachInfo.mHardwareRenderer.validate()) { 10501 getHardwareLayer(); 10502 } 10503 break; 10504 case LAYER_TYPE_SOFTWARE: 10505 buildDrawingCache(true); 10506 break; 10507 } 10508 } 10509 10510 // Make sure the HardwareRenderer.validate() was invoked before calling this method 10511 void flushLayer() { 10512 if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) { 10513 mHardwareLayer.flush(); 10514 } 10515 } 10516 10517 /** 10518 * <p>Returns a hardware layer that can be used to draw this view again 10519 * without executing its draw method.</p> 10520 * 10521 * @return A HardwareLayer ready to render, or null if an error occurred. 10522 */ 10523 HardwareLayer getHardwareLayer() { 10524 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 10525 !mAttachInfo.mHardwareRenderer.isEnabled()) { 10526 return null; 10527 } 10528 10529 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 10530 10531 final int width = mRight - mLeft; 10532 final int height = mBottom - mTop; 10533 10534 if (width == 0 || height == 0) { 10535 return null; 10536 } 10537 10538 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 10539 if (mHardwareLayer == null) { 10540 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 10541 width, height, isOpaque()); 10542 mLocalDirtyRect.set(0, 0, width, height); 10543 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 10544 mHardwareLayer.resize(width, height); 10545 mLocalDirtyRect.set(0, 0, width, height); 10546 } 10547 10548 // The layer is not valid if the underlying GPU resources cannot be allocated 10549 if (!mHardwareLayer.isValid()) { 10550 return null; 10551 } 10552 10553 mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect); 10554 mLocalDirtyRect.setEmpty(); 10555 } 10556 10557 return mHardwareLayer; 10558 } 10559 10560 /** 10561 * Destroys this View's hardware layer if possible. 10562 * 10563 * @return True if the layer was destroyed, false otherwise. 10564 * 10565 * @see #setLayerType(int, android.graphics.Paint) 10566 * @see #LAYER_TYPE_HARDWARE 10567 */ 10568 boolean destroyLayer(boolean valid) { 10569 if (mHardwareLayer != null) { 10570 AttachInfo info = mAttachInfo; 10571 if (info != null && info.mHardwareRenderer != null && 10572 info.mHardwareRenderer.isEnabled() && 10573 (valid || info.mHardwareRenderer.validate())) { 10574 mHardwareLayer.destroy(); 10575 mHardwareLayer = null; 10576 10577 invalidate(true); 10578 invalidateParentCaches(); 10579 } 10580 return true; 10581 } 10582 return false; 10583 } 10584 10585 /** 10586 * Destroys all hardware rendering resources. This method is invoked 10587 * when the system needs to reclaim resources. Upon execution of this 10588 * method, you should free any OpenGL resources created by the view. 10589 * 10590 * Note: you <strong>must</strong> call 10591 * <code>super.destroyHardwareResources()</code> when overriding 10592 * this method. 10593 * 10594 * @hide 10595 */ 10596 protected void destroyHardwareResources() { 10597 destroyLayer(true); 10598 } 10599 10600 /** 10601 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 10602 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 10603 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 10604 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 10605 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 10606 * null.</p> 10607 * 10608 * <p>Enabling the drawing cache is similar to 10609 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 10610 * acceleration is turned off. When hardware acceleration is turned on, enabling the 10611 * drawing cache has no effect on rendering because the system uses a different mechanism 10612 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 10613 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 10614 * for information on how to enable software and hardware layers.</p> 10615 * 10616 * <p>This API can be used to manually generate 10617 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 10618 * {@link #getDrawingCache()}.</p> 10619 * 10620 * @param enabled true to enable the drawing cache, false otherwise 10621 * 10622 * @see #isDrawingCacheEnabled() 10623 * @see #getDrawingCache() 10624 * @see #buildDrawingCache() 10625 * @see #setLayerType(int, android.graphics.Paint) 10626 */ 10627 public void setDrawingCacheEnabled(boolean enabled) { 10628 mCachingFailed = false; 10629 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 10630 } 10631 10632 /** 10633 * <p>Indicates whether the drawing cache is enabled for this view.</p> 10634 * 10635 * @return true if the drawing cache is enabled 10636 * 10637 * @see #setDrawingCacheEnabled(boolean) 10638 * @see #getDrawingCache() 10639 */ 10640 @ViewDebug.ExportedProperty(category = "drawing") 10641 public boolean isDrawingCacheEnabled() { 10642 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 10643 } 10644 10645 /** 10646 * Debugging utility which recursively outputs the dirty state of a view and its 10647 * descendants. 10648 * 10649 * @hide 10650 */ 10651 @SuppressWarnings({"UnusedDeclaration"}) 10652 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 10653 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) + 10654 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" + 10655 (mPrivateFlags & View.DRAWING_CACHE_VALID) + 10656 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")"); 10657 if (clear) { 10658 mPrivateFlags &= clearMask; 10659 } 10660 if (this instanceof ViewGroup) { 10661 ViewGroup parent = (ViewGroup) this; 10662 final int count = parent.getChildCount(); 10663 for (int i = 0; i < count; i++) { 10664 final View child = parent.getChildAt(i); 10665 child.outputDirtyFlags(indent + " ", clear, clearMask); 10666 } 10667 } 10668 } 10669 10670 /** 10671 * This method is used by ViewGroup to cause its children to restore or recreate their 10672 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 10673 * to recreate its own display list, which would happen if it went through the normal 10674 * draw/dispatchDraw mechanisms. 10675 * 10676 * @hide 10677 */ 10678 protected void dispatchGetDisplayList() {} 10679 10680 /** 10681 * A view that is not attached or hardware accelerated cannot create a display list. 10682 * This method checks these conditions and returns the appropriate result. 10683 * 10684 * @return true if view has the ability to create a display list, false otherwise. 10685 * 10686 * @hide 10687 */ 10688 public boolean canHaveDisplayList() { 10689 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 10690 } 10691 10692 /** 10693 * @return The HardwareRenderer associated with that view or null if hardware rendering 10694 * is not supported or this this has not been attached to a window. 10695 * 10696 * @hide 10697 */ 10698 public HardwareRenderer getHardwareRenderer() { 10699 if (mAttachInfo != null) { 10700 return mAttachInfo.mHardwareRenderer; 10701 } 10702 return null; 10703 } 10704 10705 /** 10706 * Returns a DisplayList. If the incoming displayList is null, one will be created. 10707 * Otherwise, the same display list will be returned (after having been rendered into 10708 * along the way, depending on the invalidation state of the view). 10709 * 10710 * @param displayList The previous version of this displayList, could be null. 10711 * @param isLayer Whether the requester of the display list is a layer. If so, 10712 * the view will avoid creating a layer inside the resulting display list. 10713 * @return A new or reused DisplayList object. 10714 */ 10715 private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) { 10716 if (!canHaveDisplayList()) { 10717 return null; 10718 } 10719 10720 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || 10721 displayList == null || !displayList.isValid() || 10722 (!isLayer && mRecreateDisplayList))) { 10723 // Don't need to recreate the display list, just need to tell our 10724 // children to restore/recreate theirs 10725 if (displayList != null && displayList.isValid() && 10726 !isLayer && !mRecreateDisplayList) { 10727 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10728 mPrivateFlags &= ~DIRTY_MASK; 10729 dispatchGetDisplayList(); 10730 10731 return displayList; 10732 } 10733 10734 if (!isLayer) { 10735 // If we got here, we're recreating it. Mark it as such to ensure that 10736 // we copy in child display lists into ours in drawChild() 10737 mRecreateDisplayList = true; 10738 } 10739 if (displayList == null) { 10740 final String name = getClass().getSimpleName(); 10741 displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name); 10742 // If we're creating a new display list, make sure our parent gets invalidated 10743 // since they will need to recreate their display list to account for this 10744 // new child display list. 10745 invalidateParentCaches(); 10746 } 10747 10748 boolean caching = false; 10749 final HardwareCanvas canvas = displayList.start(); 10750 int restoreCount = 0; 10751 int width = mRight - mLeft; 10752 int height = mBottom - mTop; 10753 10754 try { 10755 canvas.setViewport(width, height); 10756 // The dirty rect should always be null for a display list 10757 canvas.onPreDraw(null); 10758 int layerType = ( 10759 !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ? 10760 getLayerType() : LAYER_TYPE_NONE; 10761 if (!isLayer && layerType != LAYER_TYPE_NONE && USE_DISPLAY_LIST_PROPERTIES) { 10762 if (layerType == LAYER_TYPE_HARDWARE) { 10763 final HardwareLayer layer = getHardwareLayer(); 10764 if (layer != null && layer.isValid()) { 10765 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 10766 } else { 10767 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 10768 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 10769 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 10770 } 10771 caching = true; 10772 } else { 10773 buildDrawingCache(true); 10774 Bitmap cache = getDrawingCache(true); 10775 if (cache != null) { 10776 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 10777 caching = true; 10778 } 10779 } 10780 } else { 10781 10782 computeScroll(); 10783 10784 if (!USE_DISPLAY_LIST_PROPERTIES) { 10785 restoreCount = canvas.save(); 10786 } 10787 canvas.translate(-mScrollX, -mScrollY); 10788 if (!isLayer) { 10789 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10790 mPrivateFlags &= ~DIRTY_MASK; 10791 } 10792 10793 // Fast path for layouts with no backgrounds 10794 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10795 dispatchDraw(canvas); 10796 } else { 10797 draw(canvas); 10798 } 10799 } 10800 } finally { 10801 if (USE_DISPLAY_LIST_PROPERTIES) { 10802 canvas.restoreToCount(restoreCount); 10803 } 10804 canvas.onPostDraw(); 10805 10806 displayList.end(); 10807 if (USE_DISPLAY_LIST_PROPERTIES) { 10808 displayList.setCaching(caching); 10809 } 10810 if (isLayer && USE_DISPLAY_LIST_PROPERTIES) { 10811 displayList.setLeftTopRightBottom(0, 0, width, height); 10812 } else { 10813 setDisplayListProperties(displayList); 10814 } 10815 } 10816 } else if (!isLayer) { 10817 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10818 mPrivateFlags &= ~DIRTY_MASK; 10819 } 10820 10821 return displayList; 10822 } 10823 10824 /** 10825 * Get the DisplayList for the HardwareLayer 10826 * 10827 * @param layer The HardwareLayer whose DisplayList we want 10828 * @return A DisplayList fopr the specified HardwareLayer 10829 */ 10830 private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) { 10831 DisplayList displayList = getDisplayList(layer.getDisplayList(), true); 10832 layer.setDisplayList(displayList); 10833 return displayList; 10834 } 10835 10836 10837 /** 10838 * <p>Returns a display list that can be used to draw this view again 10839 * without executing its draw method.</p> 10840 * 10841 * @return A DisplayList ready to replay, or null if caching is not enabled. 10842 * 10843 * @hide 10844 */ 10845 public DisplayList getDisplayList() { 10846 mDisplayList = getDisplayList(mDisplayList, false); 10847 return mDisplayList; 10848 } 10849 10850 /** 10851 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 10852 * 10853 * @return A non-scaled bitmap representing this view or null if cache is disabled. 10854 * 10855 * @see #getDrawingCache(boolean) 10856 */ 10857 public Bitmap getDrawingCache() { 10858 return getDrawingCache(false); 10859 } 10860 10861 /** 10862 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 10863 * is null when caching is disabled. If caching is enabled and the cache is not ready, 10864 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 10865 * draw from the cache when the cache is enabled. To benefit from the cache, you must 10866 * request the drawing cache by calling this method and draw it on screen if the 10867 * returned bitmap is not null.</p> 10868 * 10869 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10870 * this method will create a bitmap of the same size as this view. Because this bitmap 10871 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10872 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10873 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10874 * size than the view. This implies that your application must be able to handle this 10875 * size.</p> 10876 * 10877 * @param autoScale Indicates whether the generated bitmap should be scaled based on 10878 * the current density of the screen when the application is in compatibility 10879 * mode. 10880 * 10881 * @return A bitmap representing this view or null if cache is disabled. 10882 * 10883 * @see #setDrawingCacheEnabled(boolean) 10884 * @see #isDrawingCacheEnabled() 10885 * @see #buildDrawingCache(boolean) 10886 * @see #destroyDrawingCache() 10887 */ 10888 public Bitmap getDrawingCache(boolean autoScale) { 10889 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 10890 return null; 10891 } 10892 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 10893 buildDrawingCache(autoScale); 10894 } 10895 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 10896 } 10897 10898 /** 10899 * <p>Frees the resources used by the drawing cache. If you call 10900 * {@link #buildDrawingCache()} manually without calling 10901 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10902 * should cleanup the cache with this method afterwards.</p> 10903 * 10904 * @see #setDrawingCacheEnabled(boolean) 10905 * @see #buildDrawingCache() 10906 * @see #getDrawingCache() 10907 */ 10908 public void destroyDrawingCache() { 10909 if (mDrawingCache != null) { 10910 mDrawingCache.recycle(); 10911 mDrawingCache = null; 10912 } 10913 if (mUnscaledDrawingCache != null) { 10914 mUnscaledDrawingCache.recycle(); 10915 mUnscaledDrawingCache = null; 10916 } 10917 } 10918 10919 /** 10920 * Setting a solid background color for the drawing cache's bitmaps will improve 10921 * performance and memory usage. Note, though that this should only be used if this 10922 * view will always be drawn on top of a solid color. 10923 * 10924 * @param color The background color to use for the drawing cache's bitmap 10925 * 10926 * @see #setDrawingCacheEnabled(boolean) 10927 * @see #buildDrawingCache() 10928 * @see #getDrawingCache() 10929 */ 10930 public void setDrawingCacheBackgroundColor(int color) { 10931 if (color != mDrawingCacheBackgroundColor) { 10932 mDrawingCacheBackgroundColor = color; 10933 mPrivateFlags &= ~DRAWING_CACHE_VALID; 10934 } 10935 } 10936 10937 /** 10938 * @see #setDrawingCacheBackgroundColor(int) 10939 * 10940 * @return The background color to used for the drawing cache's bitmap 10941 */ 10942 public int getDrawingCacheBackgroundColor() { 10943 return mDrawingCacheBackgroundColor; 10944 } 10945 10946 /** 10947 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 10948 * 10949 * @see #buildDrawingCache(boolean) 10950 */ 10951 public void buildDrawingCache() { 10952 buildDrawingCache(false); 10953 } 10954 10955 /** 10956 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 10957 * 10958 * <p>If you call {@link #buildDrawingCache()} manually without calling 10959 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10960 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 10961 * 10962 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10963 * this method will create a bitmap of the same size as this view. Because this bitmap 10964 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10965 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10966 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10967 * size than the view. This implies that your application must be able to handle this 10968 * size.</p> 10969 * 10970 * <p>You should avoid calling this method when hardware acceleration is enabled. If 10971 * you do not need the drawing cache bitmap, calling this method will increase memory 10972 * usage and cause the view to be rendered in software once, thus negatively impacting 10973 * performance.</p> 10974 * 10975 * @see #getDrawingCache() 10976 * @see #destroyDrawingCache() 10977 */ 10978 public void buildDrawingCache(boolean autoScale) { 10979 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 10980 mDrawingCache == null : mUnscaledDrawingCache == null)) { 10981 mCachingFailed = false; 10982 10983 if (ViewDebug.TRACE_HIERARCHY) { 10984 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 10985 } 10986 10987 int width = mRight - mLeft; 10988 int height = mBottom - mTop; 10989 10990 final AttachInfo attachInfo = mAttachInfo; 10991 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 10992 10993 if (autoScale && scalingRequired) { 10994 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 10995 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 10996 } 10997 10998 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 10999 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 11000 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 11001 11002 if (width <= 0 || height <= 0 || 11003 // Projected bitmap size in bytes 11004 (width * height * (opaque && !use32BitCache ? 2 : 4) > 11005 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 11006 destroyDrawingCache(); 11007 mCachingFailed = true; 11008 return; 11009 } 11010 11011 boolean clear = true; 11012 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 11013 11014 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 11015 Bitmap.Config quality; 11016 if (!opaque) { 11017 // Never pick ARGB_4444 because it looks awful 11018 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 11019 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 11020 case DRAWING_CACHE_QUALITY_AUTO: 11021 quality = Bitmap.Config.ARGB_8888; 11022 break; 11023 case DRAWING_CACHE_QUALITY_LOW: 11024 quality = Bitmap.Config.ARGB_8888; 11025 break; 11026 case DRAWING_CACHE_QUALITY_HIGH: 11027 quality = Bitmap.Config.ARGB_8888; 11028 break; 11029 default: 11030 quality = Bitmap.Config.ARGB_8888; 11031 break; 11032 } 11033 } else { 11034 // Optimization for translucent windows 11035 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 11036 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 11037 } 11038 11039 // Try to cleanup memory 11040 if (bitmap != null) bitmap.recycle(); 11041 11042 try { 11043 bitmap = Bitmap.createBitmap(width, height, quality); 11044 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 11045 if (autoScale) { 11046 mDrawingCache = bitmap; 11047 } else { 11048 mUnscaledDrawingCache = bitmap; 11049 } 11050 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 11051 } catch (OutOfMemoryError e) { 11052 // If there is not enough memory to create the bitmap cache, just 11053 // ignore the issue as bitmap caches are not required to draw the 11054 // view hierarchy 11055 if (autoScale) { 11056 mDrawingCache = null; 11057 } else { 11058 mUnscaledDrawingCache = null; 11059 } 11060 mCachingFailed = true; 11061 return; 11062 } 11063 11064 clear = drawingCacheBackgroundColor != 0; 11065 } 11066 11067 Canvas canvas; 11068 if (attachInfo != null) { 11069 canvas = attachInfo.mCanvas; 11070 if (canvas == null) { 11071 canvas = new Canvas(); 11072 } 11073 canvas.setBitmap(bitmap); 11074 // Temporarily clobber the cached Canvas in case one of our children 11075 // is also using a drawing cache. Without this, the children would 11076 // steal the canvas by attaching their own bitmap to it and bad, bad 11077 // thing would happen (invisible views, corrupted drawings, etc.) 11078 attachInfo.mCanvas = null; 11079 } else { 11080 // This case should hopefully never or seldom happen 11081 canvas = new Canvas(bitmap); 11082 } 11083 11084 if (clear) { 11085 bitmap.eraseColor(drawingCacheBackgroundColor); 11086 } 11087 11088 computeScroll(); 11089 final int restoreCount = canvas.save(); 11090 11091 if (autoScale && scalingRequired) { 11092 final float scale = attachInfo.mApplicationScale; 11093 canvas.scale(scale, scale); 11094 } 11095 11096 canvas.translate(-mScrollX, -mScrollY); 11097 11098 mPrivateFlags |= DRAWN; 11099 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 11100 mLayerType != LAYER_TYPE_NONE) { 11101 mPrivateFlags |= DRAWING_CACHE_VALID; 11102 } 11103 11104 // Fast path for layouts with no backgrounds 11105 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 11106 if (ViewDebug.TRACE_HIERARCHY) { 11107 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 11108 } 11109 mPrivateFlags &= ~DIRTY_MASK; 11110 dispatchDraw(canvas); 11111 } else { 11112 draw(canvas); 11113 } 11114 11115 canvas.restoreToCount(restoreCount); 11116 canvas.setBitmap(null); 11117 11118 if (attachInfo != null) { 11119 // Restore the cached Canvas for our siblings 11120 attachInfo.mCanvas = canvas; 11121 } 11122 } 11123 } 11124 11125 /** 11126 * Create a snapshot of the view into a bitmap. We should probably make 11127 * some form of this public, but should think about the API. 11128 */ 11129 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 11130 int width = mRight - mLeft; 11131 int height = mBottom - mTop; 11132 11133 final AttachInfo attachInfo = mAttachInfo; 11134 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 11135 width = (int) ((width * scale) + 0.5f); 11136 height = (int) ((height * scale) + 0.5f); 11137 11138 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 11139 if (bitmap == null) { 11140 throw new OutOfMemoryError(); 11141 } 11142 11143 Resources resources = getResources(); 11144 if (resources != null) { 11145 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 11146 } 11147 11148 Canvas canvas; 11149 if (attachInfo != null) { 11150 canvas = attachInfo.mCanvas; 11151 if (canvas == null) { 11152 canvas = new Canvas(); 11153 } 11154 canvas.setBitmap(bitmap); 11155 // Temporarily clobber the cached Canvas in case one of our children 11156 // is also using a drawing cache. Without this, the children would 11157 // steal the canvas by attaching their own bitmap to it and bad, bad 11158 // things would happen (invisible views, corrupted drawings, etc.) 11159 attachInfo.mCanvas = null; 11160 } else { 11161 // This case should hopefully never or seldom happen 11162 canvas = new Canvas(bitmap); 11163 } 11164 11165 if ((backgroundColor & 0xff000000) != 0) { 11166 bitmap.eraseColor(backgroundColor); 11167 } 11168 11169 computeScroll(); 11170 final int restoreCount = canvas.save(); 11171 canvas.scale(scale, scale); 11172 canvas.translate(-mScrollX, -mScrollY); 11173 11174 // Temporarily remove the dirty mask 11175 int flags = mPrivateFlags; 11176 mPrivateFlags &= ~DIRTY_MASK; 11177 11178 // Fast path for layouts with no backgrounds 11179 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 11180 dispatchDraw(canvas); 11181 } else { 11182 draw(canvas); 11183 } 11184 11185 mPrivateFlags = flags; 11186 11187 canvas.restoreToCount(restoreCount); 11188 canvas.setBitmap(null); 11189 11190 if (attachInfo != null) { 11191 // Restore the cached Canvas for our siblings 11192 attachInfo.mCanvas = canvas; 11193 } 11194 11195 return bitmap; 11196 } 11197 11198 /** 11199 * Indicates whether this View is currently in edit mode. A View is usually 11200 * in edit mode when displayed within a developer tool. For instance, if 11201 * this View is being drawn by a visual user interface builder, this method 11202 * should return true. 11203 * 11204 * Subclasses should check the return value of this method to provide 11205 * different behaviors if their normal behavior might interfere with the 11206 * host environment. For instance: the class spawns a thread in its 11207 * constructor, the drawing code relies on device-specific features, etc. 11208 * 11209 * This method is usually checked in the drawing code of custom widgets. 11210 * 11211 * @return True if this View is in edit mode, false otherwise. 11212 */ 11213 public boolean isInEditMode() { 11214 return false; 11215 } 11216 11217 /** 11218 * If the View draws content inside its padding and enables fading edges, 11219 * it needs to support padding offsets. Padding offsets are added to the 11220 * fading edges to extend the length of the fade so that it covers pixels 11221 * drawn inside the padding. 11222 * 11223 * Subclasses of this class should override this method if they need 11224 * to draw content inside the padding. 11225 * 11226 * @return True if padding offset must be applied, false otherwise. 11227 * 11228 * @see #getLeftPaddingOffset() 11229 * @see #getRightPaddingOffset() 11230 * @see #getTopPaddingOffset() 11231 * @see #getBottomPaddingOffset() 11232 * 11233 * @since CURRENT 11234 */ 11235 protected boolean isPaddingOffsetRequired() { 11236 return false; 11237 } 11238 11239 /** 11240 * Amount by which to extend the left fading region. Called only when 11241 * {@link #isPaddingOffsetRequired()} returns true. 11242 * 11243 * @return The left padding offset in pixels. 11244 * 11245 * @see #isPaddingOffsetRequired() 11246 * 11247 * @since CURRENT 11248 */ 11249 protected int getLeftPaddingOffset() { 11250 return 0; 11251 } 11252 11253 /** 11254 * Amount by which to extend the right fading region. Called only when 11255 * {@link #isPaddingOffsetRequired()} returns true. 11256 * 11257 * @return The right padding offset in pixels. 11258 * 11259 * @see #isPaddingOffsetRequired() 11260 * 11261 * @since CURRENT 11262 */ 11263 protected int getRightPaddingOffset() { 11264 return 0; 11265 } 11266 11267 /** 11268 * Amount by which to extend the top fading region. Called only when 11269 * {@link #isPaddingOffsetRequired()} returns true. 11270 * 11271 * @return The top padding offset in pixels. 11272 * 11273 * @see #isPaddingOffsetRequired() 11274 * 11275 * @since CURRENT 11276 */ 11277 protected int getTopPaddingOffset() { 11278 return 0; 11279 } 11280 11281 /** 11282 * Amount by which to extend the bottom fading region. Called only when 11283 * {@link #isPaddingOffsetRequired()} returns true. 11284 * 11285 * @return The bottom padding offset in pixels. 11286 * 11287 * @see #isPaddingOffsetRequired() 11288 * 11289 * @since CURRENT 11290 */ 11291 protected int getBottomPaddingOffset() { 11292 return 0; 11293 } 11294 11295 /** 11296 * @hide 11297 * @param offsetRequired 11298 */ 11299 protected int getFadeTop(boolean offsetRequired) { 11300 int top = mPaddingTop; 11301 if (offsetRequired) top += getTopPaddingOffset(); 11302 return top; 11303 } 11304 11305 /** 11306 * @hide 11307 * @param offsetRequired 11308 */ 11309 protected int getFadeHeight(boolean offsetRequired) { 11310 int padding = mPaddingTop; 11311 if (offsetRequired) padding += getTopPaddingOffset(); 11312 return mBottom - mTop - mPaddingBottom - padding; 11313 } 11314 11315 /** 11316 * <p>Indicates whether this view is attached to a hardware accelerated 11317 * window or not.</p> 11318 * 11319 * <p>Even if this method returns true, it does not mean that every call 11320 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 11321 * accelerated {@link android.graphics.Canvas}. For instance, if this view 11322 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 11323 * window is hardware accelerated, 11324 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 11325 * return false, and this method will return true.</p> 11326 * 11327 * @return True if the view is attached to a window and the window is 11328 * hardware accelerated; false in any other case. 11329 */ 11330 public boolean isHardwareAccelerated() { 11331 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 11332 } 11333 11334 /** 11335 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 11336 * case of an active Animation being run on the view. 11337 */ 11338 private boolean drawAnimation(ViewGroup parent, long drawingTime, 11339 Animation a, boolean scalingRequired) { 11340 Transformation invalidationTransform; 11341 final int flags = parent.mGroupFlags; 11342 final boolean initialized = a.isInitialized(); 11343 if (!initialized) { 11344 a.initialize(mRight - mLeft, mBottom - mTop, getWidth(), getHeight()); 11345 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 11346 onAnimationStart(); 11347 } 11348 11349 boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f); 11350 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 11351 if (parent.mInvalidationTransformation == null) { 11352 parent.mInvalidationTransformation = new Transformation(); 11353 } 11354 invalidationTransform = parent.mInvalidationTransformation; 11355 a.getTransformation(drawingTime, invalidationTransform, 1f); 11356 } else { 11357 invalidationTransform = parent.mChildTransformation; 11358 } 11359 if (more) { 11360 if (!a.willChangeBounds()) { 11361 if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) == 11362 parent.FLAG_OPTIMIZE_INVALIDATE) { 11363 parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED; 11364 } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) { 11365 // The child need to draw an animation, potentially offscreen, so 11366 // make sure we do not cancel invalidate requests 11367 parent.mPrivateFlags |= DRAW_ANIMATION; 11368 parent.invalidate(mLeft, mTop, mRight, mBottom); 11369 } 11370 } else { 11371 if (parent.mInvalidateRegion == null) { 11372 parent.mInvalidateRegion = new RectF(); 11373 } 11374 final RectF region = parent.mInvalidateRegion; 11375 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 11376 invalidationTransform); 11377 11378 // The child need to draw an animation, potentially offscreen, so 11379 // make sure we do not cancel invalidate requests 11380 parent.mPrivateFlags |= DRAW_ANIMATION; 11381 11382 final int left = mLeft + (int) region.left; 11383 final int top = mTop + (int) region.top; 11384 parent.invalidate(left, top, left + (int) (region.width() + .5f), 11385 top + (int) (region.height() + .5f)); 11386 } 11387 } 11388 return more; 11389 } 11390 11391 void setDisplayListProperties() { 11392 setDisplayListProperties(mDisplayList); 11393 } 11394 11395 /** 11396 * This method is called by getDisplayList() when a display list is created or re-rendered. 11397 * It sets or resets the current value of all properties on that display list (resetting is 11398 * necessary when a display list is being re-created, because we need to make sure that 11399 * previously-set transform values 11400 */ 11401 void setDisplayListProperties(DisplayList displayList) { 11402 if (USE_DISPLAY_LIST_PROPERTIES && displayList != null) { 11403 displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 11404 if (mParent instanceof ViewGroup) { 11405 displayList.setClipChildren( 11406 (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 11407 } 11408 if (mAttachInfo != null && mAttachInfo.mScalingRequired && 11409 mAttachInfo.mApplicationScale != 1.0f) { 11410 displayList.setApplicationScale(1f / mAttachInfo.mApplicationScale); 11411 } 11412 if (mTransformationInfo != null) { 11413 displayList.setTransformationInfo(mTransformationInfo.mAlpha, 11414 mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY, 11415 mTransformationInfo.mRotation, mTransformationInfo.mRotationX, 11416 mTransformationInfo.mRotationY, mTransformationInfo.mScaleX, 11417 mTransformationInfo.mScaleY); 11418 if (mTransformationInfo.mCamera == null) { 11419 mTransformationInfo.mCamera = new Camera(); 11420 mTransformationInfo.matrix3D = new Matrix(); 11421 } 11422 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ()); 11423 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) { 11424 displayList.setPivotX(getPivotX()); 11425 displayList.setPivotY(getPivotY()); 11426 } 11427 } 11428 } 11429 } 11430 11431 /** 11432 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 11433 * This draw() method is an implementation detail and is not intended to be overridden or 11434 * to be called from anywhere else other than ViewGroup.drawChild(). 11435 */ 11436 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 11437 boolean useDisplayListProperties = USE_DISPLAY_LIST_PROPERTIES && mAttachInfo != null && 11438 mAttachInfo.mHardwareAccelerated; 11439 boolean more = false; 11440 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 11441 final int flags = parent.mGroupFlags; 11442 11443 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 11444 parent.mChildTransformation.clear(); 11445 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 11446 } 11447 11448 Transformation transformToApply = null; 11449 boolean concatMatrix = false; 11450 11451 boolean scalingRequired = false; 11452 boolean caching; 11453 int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE; 11454 11455 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 11456 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 11457 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 11458 caching = true; 11459 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 11460 } else { 11461 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 11462 } 11463 11464 final Animation a = getAnimation(); 11465 if (a != null) { 11466 more = drawAnimation(parent, drawingTime, a, scalingRequired); 11467 concatMatrix = a.willChangeTransformationMatrix(); 11468 transformToApply = parent.mChildTransformation; 11469 } else if ((flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 11470 final boolean hasTransform = 11471 parent.getChildStaticTransformation(this, parent.mChildTransformation); 11472 if (hasTransform) { 11473 final int transformType = parent.mChildTransformation.getTransformationType(); 11474 transformToApply = transformType != Transformation.TYPE_IDENTITY ? 11475 parent.mChildTransformation : null; 11476 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 11477 } 11478 } 11479 11480 concatMatrix |= !childHasIdentityMatrix; 11481 11482 // Sets the flag as early as possible to allow draw() implementations 11483 // to call invalidate() successfully when doing animations 11484 mPrivateFlags |= DRAWN; 11485 11486 if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 11487 (mPrivateFlags & DRAW_ANIMATION) == 0) { 11488 return more; 11489 } 11490 11491 if (hardwareAccelerated) { 11492 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 11493 // retain the flag's value temporarily in the mRecreateDisplayList flag 11494 mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED; 11495 mPrivateFlags &= ~INVALIDATED; 11496 } 11497 11498 computeScroll(); 11499 11500 final int sx = mScrollX; 11501 final int sy = mScrollY; 11502 11503 DisplayList displayList = null; 11504 Bitmap cache = null; 11505 boolean hasDisplayList = false; 11506 if (caching) { 11507 if (!hardwareAccelerated) { 11508 if (layerType != LAYER_TYPE_NONE) { 11509 layerType = LAYER_TYPE_SOFTWARE; 11510 buildDrawingCache(true); 11511 } 11512 cache = getDrawingCache(true); 11513 } else { 11514 switch (layerType) { 11515 case LAYER_TYPE_SOFTWARE: 11516 if (useDisplayListProperties) { 11517 hasDisplayList = canHaveDisplayList(); 11518 } else { 11519 buildDrawingCache(true); 11520 cache = getDrawingCache(true); 11521 } 11522 break; 11523 case LAYER_TYPE_HARDWARE: 11524 if (useDisplayListProperties) { 11525 hasDisplayList = canHaveDisplayList(); 11526 } 11527 break; 11528 case LAYER_TYPE_NONE: 11529 // Delay getting the display list until animation-driven alpha values are 11530 // set up and possibly passed on to the view 11531 hasDisplayList = canHaveDisplayList(); 11532 break; 11533 } 11534 } 11535 } 11536 useDisplayListProperties &= hasDisplayList; 11537 11538 final boolean hasNoCache = cache == null || hasDisplayList; 11539 final boolean offsetForScroll = cache == null && !hasDisplayList && 11540 layerType != LAYER_TYPE_HARDWARE; 11541 11542 int restoreTo = -1; 11543 if (!useDisplayListProperties || transformToApply != null) { 11544 restoreTo = canvas.save(); 11545 } 11546 if (offsetForScroll) { 11547 canvas.translate(mLeft - sx, mTop - sy); 11548 } else { 11549 if (!useDisplayListProperties) { 11550 canvas.translate(mLeft, mTop); 11551 } 11552 if (scalingRequired) { 11553 if (useDisplayListProperties) { 11554 restoreTo = canvas.save(); 11555 } 11556 // mAttachInfo cannot be null, otherwise scalingRequired == false 11557 final float scale = 1.0f / mAttachInfo.mApplicationScale; 11558 canvas.scale(scale, scale); 11559 } 11560 } 11561 11562 float alpha = useDisplayListProperties ? 1 : getAlpha(); 11563 if (transformToApply != null || alpha < 1.0f || !hasIdentityMatrix()) { 11564 if (transformToApply != null || !childHasIdentityMatrix) { 11565 int transX = 0; 11566 int transY = 0; 11567 11568 if (offsetForScroll) { 11569 transX = -sx; 11570 transY = -sy; 11571 } 11572 11573 if (transformToApply != null) { 11574 if (concatMatrix) { 11575 // Undo the scroll translation, apply the transformation matrix, 11576 // then redo the scroll translate to get the correct result. 11577 canvas.translate(-transX, -transY); 11578 canvas.concat(transformToApply.getMatrix()); 11579 canvas.translate(transX, transY); 11580 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 11581 } 11582 11583 float transformAlpha = transformToApply.getAlpha(); 11584 if (transformAlpha < 1.0f) { 11585 alpha *= transformToApply.getAlpha(); 11586 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 11587 } 11588 } 11589 11590 if (!childHasIdentityMatrix && !useDisplayListProperties) { 11591 canvas.translate(-transX, -transY); 11592 canvas.concat(getMatrix()); 11593 canvas.translate(transX, transY); 11594 } 11595 } 11596 11597 if (alpha < 1.0f) { 11598 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 11599 if (hasNoCache) { 11600 final int multipliedAlpha = (int) (255 * alpha); 11601 if (!onSetAlpha(multipliedAlpha)) { 11602 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 11603 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 11604 layerType != LAYER_TYPE_NONE) { 11605 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 11606 } 11607 if (layerType == LAYER_TYPE_NONE) { 11608 final int scrollX = hasDisplayList ? 0 : sx; 11609 final int scrollY = hasDisplayList ? 0 : sy; 11610 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 11611 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 11612 } 11613 } else { 11614 // Alpha is handled by the child directly, clobber the layer's alpha 11615 mPrivateFlags |= ALPHA_SET; 11616 } 11617 } 11618 } 11619 } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) { 11620 onSetAlpha(255); 11621 mPrivateFlags &= ~ALPHA_SET; 11622 } 11623 11624 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 11625 !useDisplayListProperties) { 11626 if (offsetForScroll) { 11627 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 11628 } else { 11629 if (!scalingRequired || cache == null) { 11630 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 11631 } else { 11632 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 11633 } 11634 } 11635 } 11636 11637 if (hasDisplayList) { 11638 displayList = getDisplayList(); 11639 if (!displayList.isValid()) { 11640 // Uncommon, but possible. If a view is removed from the hierarchy during the call 11641 // to getDisplayList(), the display list will be marked invalid and we should not 11642 // try to use it again. 11643 displayList = null; 11644 hasDisplayList = false; 11645 } 11646 } 11647 11648 if (hasNoCache) { 11649 boolean layerRendered = false; 11650 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 11651 final HardwareLayer layer = getHardwareLayer(); 11652 if (layer != null && layer.isValid()) { 11653 mLayerPaint.setAlpha((int) (alpha * 255)); 11654 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 11655 layerRendered = true; 11656 } else { 11657 final int scrollX = hasDisplayList ? 0 : sx; 11658 final int scrollY = hasDisplayList ? 0 : sy; 11659 canvas.saveLayer(scrollX, scrollY, 11660 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 11661 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 11662 } 11663 } 11664 11665 if (!layerRendered) { 11666 if (!hasDisplayList) { 11667 // Fast path for layouts with no backgrounds 11668 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 11669 if (ViewDebug.TRACE_HIERARCHY) { 11670 ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW); 11671 } 11672 mPrivateFlags &= ~DIRTY_MASK; 11673 dispatchDraw(canvas); 11674 } else { 11675 draw(canvas); 11676 } 11677 } else { 11678 mPrivateFlags &= ~DIRTY_MASK; 11679 ((HardwareCanvas) canvas).drawDisplayList(displayList, 11680 mRight - mLeft, mBottom - mTop, null, flags); 11681 } 11682 } 11683 } else if (cache != null) { 11684 mPrivateFlags &= ~DIRTY_MASK; 11685 Paint cachePaint; 11686 11687 if (layerType == LAYER_TYPE_NONE) { 11688 cachePaint = parent.mCachePaint; 11689 if (cachePaint == null) { 11690 cachePaint = new Paint(); 11691 cachePaint.setDither(false); 11692 parent.mCachePaint = cachePaint; 11693 } 11694 if (alpha < 1.0f) { 11695 cachePaint.setAlpha((int) (alpha * 255)); 11696 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 11697 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 11698 cachePaint.setAlpha(255); 11699 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 11700 } 11701 } else { 11702 cachePaint = mLayerPaint; 11703 cachePaint.setAlpha((int) (alpha * 255)); 11704 } 11705 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 11706 } 11707 11708 if (restoreTo >= 0) { 11709 canvas.restoreToCount(restoreTo); 11710 } 11711 11712 if (a != null && !more) { 11713 if (!hardwareAccelerated && !a.getFillAfter()) { 11714 onSetAlpha(255); 11715 } 11716 parent.finishAnimatingView(this, a); 11717 } 11718 11719 if (more && hardwareAccelerated) { 11720 // invalidation is the trigger to recreate display lists, so if we're using 11721 // display lists to render, force an invalidate to allow the animation to 11722 // continue drawing another frame 11723 parent.invalidate(true); 11724 if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) { 11725 // alpha animations should cause the child to recreate its display list 11726 invalidate(true); 11727 } 11728 } 11729 11730 mRecreateDisplayList = false; 11731 11732 return more; 11733 } 11734 11735 /** 11736 * Manually render this view (and all of its children) to the given Canvas. 11737 * The view must have already done a full layout before this function is 11738 * called. When implementing a view, implement 11739 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 11740 * If you do need to override this method, call the superclass version. 11741 * 11742 * @param canvas The Canvas to which the View is rendered. 11743 */ 11744 public void draw(Canvas canvas) { 11745 if (ViewDebug.TRACE_HIERARCHY) { 11746 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 11747 } 11748 11749 final int privateFlags = mPrivateFlags; 11750 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 11751 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 11752 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 11753 11754 /* 11755 * Draw traversal performs several drawing steps which must be executed 11756 * in the appropriate order: 11757 * 11758 * 1. Draw the background 11759 * 2. If necessary, save the canvas' layers to prepare for fading 11760 * 3. Draw view's content 11761 * 4. Draw children 11762 * 5. If necessary, draw the fading edges and restore layers 11763 * 6. Draw decorations (scrollbars for instance) 11764 */ 11765 11766 // Step 1, draw the background, if needed 11767 int saveCount; 11768 11769 if (!dirtyOpaque) { 11770 final Drawable background = mBGDrawable; 11771 if (background != null) { 11772 final int scrollX = mScrollX; 11773 final int scrollY = mScrollY; 11774 11775 if (mBackgroundSizeChanged) { 11776 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 11777 mBackgroundSizeChanged = false; 11778 } 11779 11780 if ((scrollX | scrollY) == 0) { 11781 background.draw(canvas); 11782 } else { 11783 canvas.translate(scrollX, scrollY); 11784 background.draw(canvas); 11785 canvas.translate(-scrollX, -scrollY); 11786 } 11787 } 11788 } 11789 11790 // skip step 2 & 5 if possible (common case) 11791 final int viewFlags = mViewFlags; 11792 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 11793 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 11794 if (!verticalEdges && !horizontalEdges) { 11795 // Step 3, draw the content 11796 if (!dirtyOpaque) onDraw(canvas); 11797 11798 // Step 4, draw the children 11799 dispatchDraw(canvas); 11800 11801 // Step 6, draw decorations (scrollbars) 11802 onDrawScrollBars(canvas); 11803 11804 // we're done... 11805 return; 11806 } 11807 11808 /* 11809 * Here we do the full fledged routine... 11810 * (this is an uncommon case where speed matters less, 11811 * this is why we repeat some of the tests that have been 11812 * done above) 11813 */ 11814 11815 boolean drawTop = false; 11816 boolean drawBottom = false; 11817 boolean drawLeft = false; 11818 boolean drawRight = false; 11819 11820 float topFadeStrength = 0.0f; 11821 float bottomFadeStrength = 0.0f; 11822 float leftFadeStrength = 0.0f; 11823 float rightFadeStrength = 0.0f; 11824 11825 // Step 2, save the canvas' layers 11826 int paddingLeft = mPaddingLeft; 11827 11828 final boolean offsetRequired = isPaddingOffsetRequired(); 11829 if (offsetRequired) { 11830 paddingLeft += getLeftPaddingOffset(); 11831 } 11832 11833 int left = mScrollX + paddingLeft; 11834 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 11835 int top = mScrollY + getFadeTop(offsetRequired); 11836 int bottom = top + getFadeHeight(offsetRequired); 11837 11838 if (offsetRequired) { 11839 right += getRightPaddingOffset(); 11840 bottom += getBottomPaddingOffset(); 11841 } 11842 11843 final ScrollabilityCache scrollabilityCache = mScrollCache; 11844 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 11845 int length = (int) fadeHeight; 11846 11847 // clip the fade length if top and bottom fades overlap 11848 // overlapping fades produce odd-looking artifacts 11849 if (verticalEdges && (top + length > bottom - length)) { 11850 length = (bottom - top) / 2; 11851 } 11852 11853 // also clip horizontal fades if necessary 11854 if (horizontalEdges && (left + length > right - length)) { 11855 length = (right - left) / 2; 11856 } 11857 11858 if (verticalEdges) { 11859 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 11860 drawTop = topFadeStrength * fadeHeight > 1.0f; 11861 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 11862 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 11863 } 11864 11865 if (horizontalEdges) { 11866 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 11867 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 11868 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 11869 drawRight = rightFadeStrength * fadeHeight > 1.0f; 11870 } 11871 11872 saveCount = canvas.getSaveCount(); 11873 11874 int solidColor = getSolidColor(); 11875 if (solidColor == 0) { 11876 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 11877 11878 if (drawTop) { 11879 canvas.saveLayer(left, top, right, top + length, null, flags); 11880 } 11881 11882 if (drawBottom) { 11883 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 11884 } 11885 11886 if (drawLeft) { 11887 canvas.saveLayer(left, top, left + length, bottom, null, flags); 11888 } 11889 11890 if (drawRight) { 11891 canvas.saveLayer(right - length, top, right, bottom, null, flags); 11892 } 11893 } else { 11894 scrollabilityCache.setFadeColor(solidColor); 11895 } 11896 11897 // Step 3, draw the content 11898 if (!dirtyOpaque) onDraw(canvas); 11899 11900 // Step 4, draw the children 11901 dispatchDraw(canvas); 11902 11903 // Step 5, draw the fade effect and restore layers 11904 final Paint p = scrollabilityCache.paint; 11905 final Matrix matrix = scrollabilityCache.matrix; 11906 final Shader fade = scrollabilityCache.shader; 11907 11908 if (drawTop) { 11909 matrix.setScale(1, fadeHeight * topFadeStrength); 11910 matrix.postTranslate(left, top); 11911 fade.setLocalMatrix(matrix); 11912 canvas.drawRect(left, top, right, top + length, p); 11913 } 11914 11915 if (drawBottom) { 11916 matrix.setScale(1, fadeHeight * bottomFadeStrength); 11917 matrix.postRotate(180); 11918 matrix.postTranslate(left, bottom); 11919 fade.setLocalMatrix(matrix); 11920 canvas.drawRect(left, bottom - length, right, bottom, p); 11921 } 11922 11923 if (drawLeft) { 11924 matrix.setScale(1, fadeHeight * leftFadeStrength); 11925 matrix.postRotate(-90); 11926 matrix.postTranslate(left, top); 11927 fade.setLocalMatrix(matrix); 11928 canvas.drawRect(left, top, left + length, bottom, p); 11929 } 11930 11931 if (drawRight) { 11932 matrix.setScale(1, fadeHeight * rightFadeStrength); 11933 matrix.postRotate(90); 11934 matrix.postTranslate(right, top); 11935 fade.setLocalMatrix(matrix); 11936 canvas.drawRect(right - length, top, right, bottom, p); 11937 } 11938 11939 canvas.restoreToCount(saveCount); 11940 11941 // Step 6, draw decorations (scrollbars) 11942 onDrawScrollBars(canvas); 11943 } 11944 11945 /** 11946 * Override this if your view is known to always be drawn on top of a solid color background, 11947 * and needs to draw fading edges. Returning a non-zero color enables the view system to 11948 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 11949 * should be set to 0xFF. 11950 * 11951 * @see #setVerticalFadingEdgeEnabled(boolean) 11952 * @see #setHorizontalFadingEdgeEnabled(boolean) 11953 * 11954 * @return The known solid color background for this view, or 0 if the color may vary 11955 */ 11956 @ViewDebug.ExportedProperty(category = "drawing") 11957 public int getSolidColor() { 11958 return 0; 11959 } 11960 11961 /** 11962 * Build a human readable string representation of the specified view flags. 11963 * 11964 * @param flags the view flags to convert to a string 11965 * @return a String representing the supplied flags 11966 */ 11967 private static String printFlags(int flags) { 11968 String output = ""; 11969 int numFlags = 0; 11970 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 11971 output += "TAKES_FOCUS"; 11972 numFlags++; 11973 } 11974 11975 switch (flags & VISIBILITY_MASK) { 11976 case INVISIBLE: 11977 if (numFlags > 0) { 11978 output += " "; 11979 } 11980 output += "INVISIBLE"; 11981 // USELESS HERE numFlags++; 11982 break; 11983 case GONE: 11984 if (numFlags > 0) { 11985 output += " "; 11986 } 11987 output += "GONE"; 11988 // USELESS HERE numFlags++; 11989 break; 11990 default: 11991 break; 11992 } 11993 return output; 11994 } 11995 11996 /** 11997 * Build a human readable string representation of the specified private 11998 * view flags. 11999 * 12000 * @param privateFlags the private view flags to convert to a string 12001 * @return a String representing the supplied flags 12002 */ 12003 private static String printPrivateFlags(int privateFlags) { 12004 String output = ""; 12005 int numFlags = 0; 12006 12007 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 12008 output += "WANTS_FOCUS"; 12009 numFlags++; 12010 } 12011 12012 if ((privateFlags & FOCUSED) == FOCUSED) { 12013 if (numFlags > 0) { 12014 output += " "; 12015 } 12016 output += "FOCUSED"; 12017 numFlags++; 12018 } 12019 12020 if ((privateFlags & SELECTED) == SELECTED) { 12021 if (numFlags > 0) { 12022 output += " "; 12023 } 12024 output += "SELECTED"; 12025 numFlags++; 12026 } 12027 12028 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 12029 if (numFlags > 0) { 12030 output += " "; 12031 } 12032 output += "IS_ROOT_NAMESPACE"; 12033 numFlags++; 12034 } 12035 12036 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 12037 if (numFlags > 0) { 12038 output += " "; 12039 } 12040 output += "HAS_BOUNDS"; 12041 numFlags++; 12042 } 12043 12044 if ((privateFlags & DRAWN) == DRAWN) { 12045 if (numFlags > 0) { 12046 output += " "; 12047 } 12048 output += "DRAWN"; 12049 // USELESS HERE numFlags++; 12050 } 12051 return output; 12052 } 12053 12054 /** 12055 * <p>Indicates whether or not this view's layout will be requested during 12056 * the next hierarchy layout pass.</p> 12057 * 12058 * @return true if the layout will be forced during next layout pass 12059 */ 12060 public boolean isLayoutRequested() { 12061 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 12062 } 12063 12064 /** 12065 * Assign a size and position to a view and all of its 12066 * descendants 12067 * 12068 * <p>This is the second phase of the layout mechanism. 12069 * (The first is measuring). In this phase, each parent calls 12070 * layout on all of its children to position them. 12071 * This is typically done using the child measurements 12072 * that were stored in the measure pass().</p> 12073 * 12074 * <p>Derived classes should not override this method. 12075 * Derived classes with children should override 12076 * onLayout. In that method, they should 12077 * call layout on each of their children.</p> 12078 * 12079 * @param l Left position, relative to parent 12080 * @param t Top position, relative to parent 12081 * @param r Right position, relative to parent 12082 * @param b Bottom position, relative to parent 12083 */ 12084 @SuppressWarnings({"unchecked"}) 12085 public void layout(int l, int t, int r, int b) { 12086 int oldL = mLeft; 12087 int oldT = mTop; 12088 int oldB = mBottom; 12089 int oldR = mRight; 12090 boolean changed = setFrame(l, t, r, b); 12091 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 12092 if (ViewDebug.TRACE_HIERARCHY) { 12093 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 12094 } 12095 12096 onLayout(changed, l, t, r, b); 12097 mPrivateFlags &= ~LAYOUT_REQUIRED; 12098 12099 ListenerInfo li = mListenerInfo; 12100 if (li != null && li.mOnLayoutChangeListeners != null) { 12101 ArrayList<OnLayoutChangeListener> listenersCopy = 12102 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 12103 int numListeners = listenersCopy.size(); 12104 for (int i = 0; i < numListeners; ++i) { 12105 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 12106 } 12107 } 12108 } 12109 mPrivateFlags &= ~FORCE_LAYOUT; 12110 } 12111 12112 /** 12113 * Called from layout when this view should 12114 * assign a size and position to each of its children. 12115 * 12116 * Derived classes with children should override 12117 * this method and call layout on each of 12118 * their children. 12119 * @param changed This is a new size or position for this view 12120 * @param left Left position, relative to parent 12121 * @param top Top position, relative to parent 12122 * @param right Right position, relative to parent 12123 * @param bottom Bottom position, relative to parent 12124 */ 12125 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 12126 } 12127 12128 /** 12129 * Assign a size and position to this view. 12130 * 12131 * This is called from layout. 12132 * 12133 * @param left Left position, relative to parent 12134 * @param top Top position, relative to parent 12135 * @param right Right position, relative to parent 12136 * @param bottom Bottom position, relative to parent 12137 * @return true if the new size and position are different than the 12138 * previous ones 12139 * {@hide} 12140 */ 12141 protected boolean setFrame(int left, int top, int right, int bottom) { 12142 boolean changed = false; 12143 12144 if (DBG) { 12145 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 12146 + right + "," + bottom + ")"); 12147 } 12148 12149 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 12150 changed = true; 12151 12152 // Remember our drawn bit 12153 int drawn = mPrivateFlags & DRAWN; 12154 12155 int oldWidth = mRight - mLeft; 12156 int oldHeight = mBottom - mTop; 12157 int newWidth = right - left; 12158 int newHeight = bottom - top; 12159 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 12160 12161 // Invalidate our old position 12162 invalidate(sizeChanged); 12163 12164 mLeft = left; 12165 mTop = top; 12166 mRight = right; 12167 mBottom = bottom; 12168 if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) { 12169 mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 12170 } 12171 12172 mPrivateFlags |= HAS_BOUNDS; 12173 12174 12175 if (sizeChanged) { 12176 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 12177 // A change in dimension means an auto-centered pivot point changes, too 12178 if (mTransformationInfo != null) { 12179 mTransformationInfo.mMatrixDirty = true; 12180 } 12181 } 12182 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 12183 } 12184 12185 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 12186 // If we are visible, force the DRAWN bit to on so that 12187 // this invalidate will go through (at least to our parent). 12188 // This is because someone may have invalidated this view 12189 // before this call to setFrame came in, thereby clearing 12190 // the DRAWN bit. 12191 mPrivateFlags |= DRAWN; 12192 invalidate(sizeChanged); 12193 // parent display list may need to be recreated based on a change in the bounds 12194 // of any child 12195 invalidateParentCaches(); 12196 } 12197 12198 // Reset drawn bit to original value (invalidate turns it off) 12199 mPrivateFlags |= drawn; 12200 12201 mBackgroundSizeChanged = true; 12202 } 12203 return changed; 12204 } 12205 12206 /** 12207 * Finalize inflating a view from XML. This is called as the last phase 12208 * of inflation, after all child views have been added. 12209 * 12210 * <p>Even if the subclass overrides onFinishInflate, they should always be 12211 * sure to call the super method, so that we get called. 12212 */ 12213 protected void onFinishInflate() { 12214 } 12215 12216 /** 12217 * Returns the resources associated with this view. 12218 * 12219 * @return Resources object. 12220 */ 12221 public Resources getResources() { 12222 return mResources; 12223 } 12224 12225 /** 12226 * Invalidates the specified Drawable. 12227 * 12228 * @param drawable the drawable to invalidate 12229 */ 12230 public void invalidateDrawable(Drawable drawable) { 12231 if (verifyDrawable(drawable)) { 12232 final Rect dirty = drawable.getBounds(); 12233 final int scrollX = mScrollX; 12234 final int scrollY = mScrollY; 12235 12236 invalidate(dirty.left + scrollX, dirty.top + scrollY, 12237 dirty.right + scrollX, dirty.bottom + scrollY); 12238 } 12239 } 12240 12241 /** 12242 * Schedules an action on a drawable to occur at a specified time. 12243 * 12244 * @param who the recipient of the action 12245 * @param what the action to run on the drawable 12246 * @param when the time at which the action must occur. Uses the 12247 * {@link SystemClock#uptimeMillis} timebase. 12248 */ 12249 public void scheduleDrawable(Drawable who, Runnable what, long when) { 12250 if (verifyDrawable(who) && what != null) { 12251 final long delay = when - SystemClock.uptimeMillis(); 12252 if (mAttachInfo != null) { 12253 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 12254 Choreographer.CALLBACK_ANIMATION, what, who, 12255 Choreographer.subtractFrameDelay(delay)); 12256 } else { 12257 ViewRootImpl.getRunQueue().postDelayed(what, delay); 12258 } 12259 } 12260 } 12261 12262 /** 12263 * Cancels a scheduled action on a drawable. 12264 * 12265 * @param who the recipient of the action 12266 * @param what the action to cancel 12267 */ 12268 public void unscheduleDrawable(Drawable who, Runnable what) { 12269 if (verifyDrawable(who) && what != null) { 12270 if (mAttachInfo != null) { 12271 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 12272 Choreographer.CALLBACK_ANIMATION, what, who); 12273 } else { 12274 ViewRootImpl.getRunQueue().removeCallbacks(what); 12275 } 12276 } 12277 } 12278 12279 /** 12280 * Unschedule any events associated with the given Drawable. This can be 12281 * used when selecting a new Drawable into a view, so that the previous 12282 * one is completely unscheduled. 12283 * 12284 * @param who The Drawable to unschedule. 12285 * 12286 * @see #drawableStateChanged 12287 */ 12288 public void unscheduleDrawable(Drawable who) { 12289 if (mAttachInfo != null && who != null) { 12290 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 12291 Choreographer.CALLBACK_ANIMATION, null, who); 12292 } 12293 } 12294 12295 /** 12296 * Return the layout direction of a given Drawable. 12297 * 12298 * @param who the Drawable to query 12299 */ 12300 public int getResolvedLayoutDirection(Drawable who) { 12301 return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT; 12302 } 12303 12304 /** 12305 * If your view subclass is displaying its own Drawable objects, it should 12306 * override this function and return true for any Drawable it is 12307 * displaying. This allows animations for those drawables to be 12308 * scheduled. 12309 * 12310 * <p>Be sure to call through to the super class when overriding this 12311 * function. 12312 * 12313 * @param who The Drawable to verify. Return true if it is one you are 12314 * displaying, else return the result of calling through to the 12315 * super class. 12316 * 12317 * @return boolean If true than the Drawable is being displayed in the 12318 * view; else false and it is not allowed to animate. 12319 * 12320 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 12321 * @see #drawableStateChanged() 12322 */ 12323 protected boolean verifyDrawable(Drawable who) { 12324 return who == mBGDrawable; 12325 } 12326 12327 /** 12328 * This function is called whenever the state of the view changes in such 12329 * a way that it impacts the state of drawables being shown. 12330 * 12331 * <p>Be sure to call through to the superclass when overriding this 12332 * function. 12333 * 12334 * @see Drawable#setState(int[]) 12335 */ 12336 protected void drawableStateChanged() { 12337 Drawable d = mBGDrawable; 12338 if (d != null && d.isStateful()) { 12339 d.setState(getDrawableState()); 12340 } 12341 } 12342 12343 /** 12344 * Call this to force a view to update its drawable state. This will cause 12345 * drawableStateChanged to be called on this view. Views that are interested 12346 * in the new state should call getDrawableState. 12347 * 12348 * @see #drawableStateChanged 12349 * @see #getDrawableState 12350 */ 12351 public void refreshDrawableState() { 12352 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 12353 drawableStateChanged(); 12354 12355 ViewParent parent = mParent; 12356 if (parent != null) { 12357 parent.childDrawableStateChanged(this); 12358 } 12359 } 12360 12361 /** 12362 * Return an array of resource IDs of the drawable states representing the 12363 * current state of the view. 12364 * 12365 * @return The current drawable state 12366 * 12367 * @see Drawable#setState(int[]) 12368 * @see #drawableStateChanged() 12369 * @see #onCreateDrawableState(int) 12370 */ 12371 public final int[] getDrawableState() { 12372 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 12373 return mDrawableState; 12374 } else { 12375 mDrawableState = onCreateDrawableState(0); 12376 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 12377 return mDrawableState; 12378 } 12379 } 12380 12381 /** 12382 * Generate the new {@link android.graphics.drawable.Drawable} state for 12383 * this view. This is called by the view 12384 * system when the cached Drawable state is determined to be invalid. To 12385 * retrieve the current state, you should use {@link #getDrawableState}. 12386 * 12387 * @param extraSpace if non-zero, this is the number of extra entries you 12388 * would like in the returned array in which you can place your own 12389 * states. 12390 * 12391 * @return Returns an array holding the current {@link Drawable} state of 12392 * the view. 12393 * 12394 * @see #mergeDrawableStates(int[], int[]) 12395 */ 12396 protected int[] onCreateDrawableState(int extraSpace) { 12397 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 12398 mParent instanceof View) { 12399 return ((View) mParent).onCreateDrawableState(extraSpace); 12400 } 12401 12402 int[] drawableState; 12403 12404 int privateFlags = mPrivateFlags; 12405 12406 int viewStateIndex = 0; 12407 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 12408 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 12409 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 12410 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 12411 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 12412 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 12413 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 12414 HardwareRenderer.isAvailable()) { 12415 // This is set if HW acceleration is requested, even if the current 12416 // process doesn't allow it. This is just to allow app preview 12417 // windows to better match their app. 12418 viewStateIndex |= VIEW_STATE_ACCELERATED; 12419 } 12420 if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 12421 12422 final int privateFlags2 = mPrivateFlags2; 12423 if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 12424 if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 12425 12426 drawableState = VIEW_STATE_SETS[viewStateIndex]; 12427 12428 //noinspection ConstantIfStatement 12429 if (false) { 12430 Log.i("View", "drawableStateIndex=" + viewStateIndex); 12431 Log.i("View", toString() 12432 + " pressed=" + ((privateFlags & PRESSED) != 0) 12433 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 12434 + " fo=" + hasFocus() 12435 + " sl=" + ((privateFlags & SELECTED) != 0) 12436 + " wf=" + hasWindowFocus() 12437 + ": " + Arrays.toString(drawableState)); 12438 } 12439 12440 if (extraSpace == 0) { 12441 return drawableState; 12442 } 12443 12444 final int[] fullState; 12445 if (drawableState != null) { 12446 fullState = new int[drawableState.length + extraSpace]; 12447 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 12448 } else { 12449 fullState = new int[extraSpace]; 12450 } 12451 12452 return fullState; 12453 } 12454 12455 /** 12456 * Merge your own state values in <var>additionalState</var> into the base 12457 * state values <var>baseState</var> that were returned by 12458 * {@link #onCreateDrawableState(int)}. 12459 * 12460 * @param baseState The base state values returned by 12461 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 12462 * own additional state values. 12463 * 12464 * @param additionalState The additional state values you would like 12465 * added to <var>baseState</var>; this array is not modified. 12466 * 12467 * @return As a convenience, the <var>baseState</var> array you originally 12468 * passed into the function is returned. 12469 * 12470 * @see #onCreateDrawableState(int) 12471 */ 12472 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 12473 final int N = baseState.length; 12474 int i = N - 1; 12475 while (i >= 0 && baseState[i] == 0) { 12476 i--; 12477 } 12478 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 12479 return baseState; 12480 } 12481 12482 /** 12483 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 12484 * on all Drawable objects associated with this view. 12485 */ 12486 public void jumpDrawablesToCurrentState() { 12487 if (mBGDrawable != null) { 12488 mBGDrawable.jumpToCurrentState(); 12489 } 12490 } 12491 12492 /** 12493 * Sets the background color for this view. 12494 * @param color the color of the background 12495 */ 12496 @RemotableViewMethod 12497 public void setBackgroundColor(int color) { 12498 if (mBGDrawable instanceof ColorDrawable) { 12499 ((ColorDrawable) mBGDrawable).setColor(color); 12500 } else { 12501 setBackgroundDrawable(new ColorDrawable(color)); 12502 } 12503 } 12504 12505 /** 12506 * Set the background to a given resource. The resource should refer to 12507 * a Drawable object or 0 to remove the background. 12508 * @param resid The identifier of the resource. 12509 * @attr ref android.R.styleable#View_background 12510 */ 12511 @RemotableViewMethod 12512 public void setBackgroundResource(int resid) { 12513 if (resid != 0 && resid == mBackgroundResource) { 12514 return; 12515 } 12516 12517 Drawable d= null; 12518 if (resid != 0) { 12519 d = mResources.getDrawable(resid); 12520 } 12521 setBackgroundDrawable(d); 12522 12523 mBackgroundResource = resid; 12524 } 12525 12526 /** 12527 * Set the background to a given Drawable, or remove the background. If the 12528 * background has padding, this View's padding is set to the background's 12529 * padding. However, when a background is removed, this View's padding isn't 12530 * touched. If setting the padding is desired, please use 12531 * {@link #setPadding(int, int, int, int)}. 12532 * 12533 * @param d The Drawable to use as the background, or null to remove the 12534 * background 12535 */ 12536 public void setBackgroundDrawable(Drawable d) { 12537 if (d == mBGDrawable) { 12538 return; 12539 } 12540 12541 boolean requestLayout = false; 12542 12543 mBackgroundResource = 0; 12544 12545 /* 12546 * Regardless of whether we're setting a new background or not, we want 12547 * to clear the previous drawable. 12548 */ 12549 if (mBGDrawable != null) { 12550 mBGDrawable.setCallback(null); 12551 unscheduleDrawable(mBGDrawable); 12552 } 12553 12554 if (d != null) { 12555 Rect padding = sThreadLocal.get(); 12556 if (padding == null) { 12557 padding = new Rect(); 12558 sThreadLocal.set(padding); 12559 } 12560 if (d.getPadding(padding)) { 12561 switch (d.getResolvedLayoutDirectionSelf()) { 12562 case LAYOUT_DIRECTION_RTL: 12563 setPadding(padding.right, padding.top, padding.left, padding.bottom); 12564 break; 12565 case LAYOUT_DIRECTION_LTR: 12566 default: 12567 setPadding(padding.left, padding.top, padding.right, padding.bottom); 12568 } 12569 } 12570 12571 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 12572 // if it has a different minimum size, we should layout again 12573 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 12574 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 12575 requestLayout = true; 12576 } 12577 12578 d.setCallback(this); 12579 if (d.isStateful()) { 12580 d.setState(getDrawableState()); 12581 } 12582 d.setVisible(getVisibility() == VISIBLE, false); 12583 mBGDrawable = d; 12584 12585 if ((mPrivateFlags & SKIP_DRAW) != 0) { 12586 mPrivateFlags &= ~SKIP_DRAW; 12587 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 12588 requestLayout = true; 12589 } 12590 } else { 12591 /* Remove the background */ 12592 mBGDrawable = null; 12593 12594 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 12595 /* 12596 * This view ONLY drew the background before and we're removing 12597 * the background, so now it won't draw anything 12598 * (hence we SKIP_DRAW) 12599 */ 12600 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 12601 mPrivateFlags |= SKIP_DRAW; 12602 } 12603 12604 /* 12605 * When the background is set, we try to apply its padding to this 12606 * View. When the background is removed, we don't touch this View's 12607 * padding. This is noted in the Javadocs. Hence, we don't need to 12608 * requestLayout(), the invalidate() below is sufficient. 12609 */ 12610 12611 // The old background's minimum size could have affected this 12612 // View's layout, so let's requestLayout 12613 requestLayout = true; 12614 } 12615 12616 computeOpaqueFlags(); 12617 12618 if (requestLayout) { 12619 requestLayout(); 12620 } 12621 12622 mBackgroundSizeChanged = true; 12623 invalidate(true); 12624 } 12625 12626 /** 12627 * Gets the background drawable 12628 * @return The drawable used as the background for this view, if any. 12629 */ 12630 public Drawable getBackground() { 12631 return mBGDrawable; 12632 } 12633 12634 /** 12635 * Sets the padding. The view may add on the space required to display 12636 * the scrollbars, depending on the style and visibility of the scrollbars. 12637 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 12638 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 12639 * from the values set in this call. 12640 * 12641 * @attr ref android.R.styleable#View_padding 12642 * @attr ref android.R.styleable#View_paddingBottom 12643 * @attr ref android.R.styleable#View_paddingLeft 12644 * @attr ref android.R.styleable#View_paddingRight 12645 * @attr ref android.R.styleable#View_paddingTop 12646 * @param left the left padding in pixels 12647 * @param top the top padding in pixels 12648 * @param right the right padding in pixels 12649 * @param bottom the bottom padding in pixels 12650 */ 12651 public void setPadding(int left, int top, int right, int bottom) { 12652 mUserPaddingStart = -1; 12653 mUserPaddingEnd = -1; 12654 mUserPaddingRelative = false; 12655 12656 internalSetPadding(left, top, right, bottom); 12657 } 12658 12659 private void internalSetPadding(int left, int top, int right, int bottom) { 12660 mUserPaddingLeft = left; 12661 mUserPaddingRight = right; 12662 mUserPaddingBottom = bottom; 12663 12664 final int viewFlags = mViewFlags; 12665 boolean changed = false; 12666 12667 // Common case is there are no scroll bars. 12668 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 12669 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 12670 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 12671 ? 0 : getVerticalScrollbarWidth(); 12672 switch (mVerticalScrollbarPosition) { 12673 case SCROLLBAR_POSITION_DEFAULT: 12674 if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12675 left += offset; 12676 } else { 12677 right += offset; 12678 } 12679 break; 12680 case SCROLLBAR_POSITION_RIGHT: 12681 right += offset; 12682 break; 12683 case SCROLLBAR_POSITION_LEFT: 12684 left += offset; 12685 break; 12686 } 12687 } 12688 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 12689 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 12690 ? 0 : getHorizontalScrollbarHeight(); 12691 } 12692 } 12693 12694 if (mPaddingLeft != left) { 12695 changed = true; 12696 mPaddingLeft = left; 12697 } 12698 if (mPaddingTop != top) { 12699 changed = true; 12700 mPaddingTop = top; 12701 } 12702 if (mPaddingRight != right) { 12703 changed = true; 12704 mPaddingRight = right; 12705 } 12706 if (mPaddingBottom != bottom) { 12707 changed = true; 12708 mPaddingBottom = bottom; 12709 } 12710 12711 if (changed) { 12712 requestLayout(); 12713 } 12714 } 12715 12716 /** 12717 * Sets the relative padding. The view may add on the space required to display 12718 * the scrollbars, depending on the style and visibility of the scrollbars. 12719 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 12720 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 12721 * from the values set in this call. 12722 * 12723 * @attr ref android.R.styleable#View_padding 12724 * @attr ref android.R.styleable#View_paddingBottom 12725 * @attr ref android.R.styleable#View_paddingStart 12726 * @attr ref android.R.styleable#View_paddingEnd 12727 * @attr ref android.R.styleable#View_paddingTop 12728 * @param start the start padding in pixels 12729 * @param top the top padding in pixels 12730 * @param end the end padding in pixels 12731 * @param bottom the bottom padding in pixels 12732 */ 12733 public void setPaddingRelative(int start, int top, int end, int bottom) { 12734 mUserPaddingStart = start; 12735 mUserPaddingEnd = end; 12736 mUserPaddingRelative = true; 12737 12738 switch(getResolvedLayoutDirection()) { 12739 case LAYOUT_DIRECTION_RTL: 12740 internalSetPadding(end, top, start, bottom); 12741 break; 12742 case LAYOUT_DIRECTION_LTR: 12743 default: 12744 internalSetPadding(start, top, end, bottom); 12745 } 12746 } 12747 12748 /** 12749 * Returns the top padding of this view. 12750 * 12751 * @return the top padding in pixels 12752 */ 12753 public int getPaddingTop() { 12754 return mPaddingTop; 12755 } 12756 12757 /** 12758 * Returns the bottom padding of this view. If there are inset and enabled 12759 * scrollbars, this value may include the space required to display the 12760 * scrollbars as well. 12761 * 12762 * @return the bottom padding in pixels 12763 */ 12764 public int getPaddingBottom() { 12765 return mPaddingBottom; 12766 } 12767 12768 /** 12769 * Returns the left padding of this view. If there are inset and enabled 12770 * scrollbars, this value may include the space required to display the 12771 * scrollbars as well. 12772 * 12773 * @return the left padding in pixels 12774 */ 12775 public int getPaddingLeft() { 12776 return mPaddingLeft; 12777 } 12778 12779 /** 12780 * Returns the start padding of this view depending on its resolved layout direction. 12781 * If there are inset and enabled scrollbars, this value may include the space 12782 * required to display the scrollbars as well. 12783 * 12784 * @return the start padding in pixels 12785 */ 12786 public int getPaddingStart() { 12787 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 12788 mPaddingRight : mPaddingLeft; 12789 } 12790 12791 /** 12792 * Returns the right padding of this view. If there are inset and enabled 12793 * scrollbars, this value may include the space required to display the 12794 * scrollbars as well. 12795 * 12796 * @return the right padding in pixels 12797 */ 12798 public int getPaddingRight() { 12799 return mPaddingRight; 12800 } 12801 12802 /** 12803 * Returns the end padding of this view depending on its resolved layout direction. 12804 * If there are inset and enabled scrollbars, this value may include the space 12805 * required to display the scrollbars as well. 12806 * 12807 * @return the end padding in pixels 12808 */ 12809 public int getPaddingEnd() { 12810 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 12811 mPaddingLeft : mPaddingRight; 12812 } 12813 12814 /** 12815 * Return if the padding as been set thru relative values 12816 * {@link #setPaddingRelative(int, int, int, int)} or thru 12817 * @attr ref android.R.styleable#View_paddingStart or 12818 * @attr ref android.R.styleable#View_paddingEnd 12819 * 12820 * @return true if the padding is relative or false if it is not. 12821 */ 12822 public boolean isPaddingRelative() { 12823 return mUserPaddingRelative; 12824 } 12825 12826 /** 12827 * Changes the selection state of this view. A view can be selected or not. 12828 * Note that selection is not the same as focus. Views are typically 12829 * selected in the context of an AdapterView like ListView or GridView; 12830 * the selected view is the view that is highlighted. 12831 * 12832 * @param selected true if the view must be selected, false otherwise 12833 */ 12834 public void setSelected(boolean selected) { 12835 if (((mPrivateFlags & SELECTED) != 0) != selected) { 12836 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 12837 if (!selected) resetPressedState(); 12838 invalidate(true); 12839 refreshDrawableState(); 12840 dispatchSetSelected(selected); 12841 } 12842 } 12843 12844 /** 12845 * Dispatch setSelected to all of this View's children. 12846 * 12847 * @see #setSelected(boolean) 12848 * 12849 * @param selected The new selected state 12850 */ 12851 protected void dispatchSetSelected(boolean selected) { 12852 } 12853 12854 /** 12855 * Indicates the selection state of this view. 12856 * 12857 * @return true if the view is selected, false otherwise 12858 */ 12859 @ViewDebug.ExportedProperty 12860 public boolean isSelected() { 12861 return (mPrivateFlags & SELECTED) != 0; 12862 } 12863 12864 /** 12865 * Changes the activated state of this view. A view can be activated or not. 12866 * Note that activation is not the same as selection. Selection is 12867 * a transient property, representing the view (hierarchy) the user is 12868 * currently interacting with. Activation is a longer-term state that the 12869 * user can move views in and out of. For example, in a list view with 12870 * single or multiple selection enabled, the views in the current selection 12871 * set are activated. (Um, yeah, we are deeply sorry about the terminology 12872 * here.) The activated state is propagated down to children of the view it 12873 * is set on. 12874 * 12875 * @param activated true if the view must be activated, false otherwise 12876 */ 12877 public void setActivated(boolean activated) { 12878 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 12879 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 12880 invalidate(true); 12881 refreshDrawableState(); 12882 dispatchSetActivated(activated); 12883 } 12884 } 12885 12886 /** 12887 * Dispatch setActivated to all of this View's children. 12888 * 12889 * @see #setActivated(boolean) 12890 * 12891 * @param activated The new activated state 12892 */ 12893 protected void dispatchSetActivated(boolean activated) { 12894 } 12895 12896 /** 12897 * Indicates the activation state of this view. 12898 * 12899 * @return true if the view is activated, false otherwise 12900 */ 12901 @ViewDebug.ExportedProperty 12902 public boolean isActivated() { 12903 return (mPrivateFlags & ACTIVATED) != 0; 12904 } 12905 12906 /** 12907 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 12908 * observer can be used to get notifications when global events, like 12909 * layout, happen. 12910 * 12911 * The returned ViewTreeObserver observer is not guaranteed to remain 12912 * valid for the lifetime of this View. If the caller of this method keeps 12913 * a long-lived reference to ViewTreeObserver, it should always check for 12914 * the return value of {@link ViewTreeObserver#isAlive()}. 12915 * 12916 * @return The ViewTreeObserver for this view's hierarchy. 12917 */ 12918 public ViewTreeObserver getViewTreeObserver() { 12919 if (mAttachInfo != null) { 12920 return mAttachInfo.mTreeObserver; 12921 } 12922 if (mFloatingTreeObserver == null) { 12923 mFloatingTreeObserver = new ViewTreeObserver(); 12924 } 12925 return mFloatingTreeObserver; 12926 } 12927 12928 /** 12929 * <p>Finds the topmost view in the current view hierarchy.</p> 12930 * 12931 * @return the topmost view containing this view 12932 */ 12933 public View getRootView() { 12934 if (mAttachInfo != null) { 12935 final View v = mAttachInfo.mRootView; 12936 if (v != null) { 12937 return v; 12938 } 12939 } 12940 12941 View parent = this; 12942 12943 while (parent.mParent != null && parent.mParent instanceof View) { 12944 parent = (View) parent.mParent; 12945 } 12946 12947 return parent; 12948 } 12949 12950 /** 12951 * <p>Computes the coordinates of this view on the screen. The argument 12952 * must be an array of two integers. After the method returns, the array 12953 * contains the x and y location in that order.</p> 12954 * 12955 * @param location an array of two integers in which to hold the coordinates 12956 */ 12957 public void getLocationOnScreen(int[] location) { 12958 getLocationInWindow(location); 12959 12960 final AttachInfo info = mAttachInfo; 12961 if (info != null) { 12962 location[0] += info.mWindowLeft; 12963 location[1] += info.mWindowTop; 12964 } 12965 } 12966 12967 /** 12968 * <p>Computes the coordinates of this view in its window. The argument 12969 * must be an array of two integers. After the method returns, the array 12970 * contains the x and y location in that order.</p> 12971 * 12972 * @param location an array of two integers in which to hold the coordinates 12973 */ 12974 public void getLocationInWindow(int[] location) { 12975 if (location == null || location.length < 2) { 12976 throw new IllegalArgumentException("location must be an array of two integers"); 12977 } 12978 12979 if (mAttachInfo == null) { 12980 // When the view is not attached to a window, this method does not make sense 12981 location[0] = location[1] = 0; 12982 return; 12983 } 12984 12985 float[] position = mAttachInfo.mTmpTransformLocation; 12986 position[0] = position[1] = 0.0f; 12987 12988 if (!hasIdentityMatrix()) { 12989 getMatrix().mapPoints(position); 12990 } 12991 12992 position[0] += mLeft; 12993 position[1] += mTop; 12994 12995 ViewParent viewParent = mParent; 12996 while (viewParent instanceof View) { 12997 final View view = (View) viewParent; 12998 12999 position[0] -= view.mScrollX; 13000 position[1] -= view.mScrollY; 13001 13002 if (!view.hasIdentityMatrix()) { 13003 view.getMatrix().mapPoints(position); 13004 } 13005 13006 position[0] += view.mLeft; 13007 position[1] += view.mTop; 13008 13009 viewParent = view.mParent; 13010 } 13011 13012 if (viewParent instanceof ViewRootImpl) { 13013 // *cough* 13014 final ViewRootImpl vr = (ViewRootImpl) viewParent; 13015 position[1] -= vr.mCurScrollY; 13016 } 13017 13018 location[0] = (int) (position[0] + 0.5f); 13019 location[1] = (int) (position[1] + 0.5f); 13020 } 13021 13022 /** 13023 * {@hide} 13024 * @param id the id of the view to be found 13025 * @return the view of the specified id, null if cannot be found 13026 */ 13027 protected View findViewTraversal(int id) { 13028 if (id == mID) { 13029 return this; 13030 } 13031 return null; 13032 } 13033 13034 /** 13035 * {@hide} 13036 * @param tag the tag of the view to be found 13037 * @return the view of specified tag, null if cannot be found 13038 */ 13039 protected View findViewWithTagTraversal(Object tag) { 13040 if (tag != null && tag.equals(mTag)) { 13041 return this; 13042 } 13043 return null; 13044 } 13045 13046 /** 13047 * {@hide} 13048 * @param predicate The predicate to evaluate. 13049 * @param childToSkip If not null, ignores this child during the recursive traversal. 13050 * @return The first view that matches the predicate or null. 13051 */ 13052 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 13053 if (predicate.apply(this)) { 13054 return this; 13055 } 13056 return null; 13057 } 13058 13059 /** 13060 * Look for a child view with the given id. If this view has the given 13061 * id, return this view. 13062 * 13063 * @param id The id to search for. 13064 * @return The view that has the given id in the hierarchy or null 13065 */ 13066 public final View findViewById(int id) { 13067 if (id < 0) { 13068 return null; 13069 } 13070 return findViewTraversal(id); 13071 } 13072 13073 /** 13074 * Finds a view by its unuque and stable accessibility id. 13075 * 13076 * @param accessibilityId The searched accessibility id. 13077 * @return The found view. 13078 */ 13079 final View findViewByAccessibilityId(int accessibilityId) { 13080 if (accessibilityId < 0) { 13081 return null; 13082 } 13083 return findViewByAccessibilityIdTraversal(accessibilityId); 13084 } 13085 13086 /** 13087 * Performs the traversal to find a view by its unuque and stable accessibility id. 13088 * 13089 * <strong>Note:</strong>This method does not stop at the root namespace 13090 * boundary since the user can touch the screen at an arbitrary location 13091 * potentially crossing the root namespace bounday which will send an 13092 * accessibility event to accessibility services and they should be able 13093 * to obtain the event source. Also accessibility ids are guaranteed to be 13094 * unique in the window. 13095 * 13096 * @param accessibilityId The accessibility id. 13097 * @return The found view. 13098 */ 13099 View findViewByAccessibilityIdTraversal(int accessibilityId) { 13100 if (getAccessibilityViewId() == accessibilityId) { 13101 return this; 13102 } 13103 return null; 13104 } 13105 13106 /** 13107 * Look for a child view with the given tag. If this view has the given 13108 * tag, return this view. 13109 * 13110 * @param tag The tag to search for, using "tag.equals(getTag())". 13111 * @return The View that has the given tag in the hierarchy or null 13112 */ 13113 public final View findViewWithTag(Object tag) { 13114 if (tag == null) { 13115 return null; 13116 } 13117 return findViewWithTagTraversal(tag); 13118 } 13119 13120 /** 13121 * {@hide} 13122 * Look for a child view that matches the specified predicate. 13123 * If this view matches the predicate, return this view. 13124 * 13125 * @param predicate The predicate to evaluate. 13126 * @return The first view that matches the predicate or null. 13127 */ 13128 public final View findViewByPredicate(Predicate<View> predicate) { 13129 return findViewByPredicateTraversal(predicate, null); 13130 } 13131 13132 /** 13133 * {@hide} 13134 * Look for a child view that matches the specified predicate, 13135 * starting with the specified view and its descendents and then 13136 * recusively searching the ancestors and siblings of that view 13137 * until this view is reached. 13138 * 13139 * This method is useful in cases where the predicate does not match 13140 * a single unique view (perhaps multiple views use the same id) 13141 * and we are trying to find the view that is "closest" in scope to the 13142 * starting view. 13143 * 13144 * @param start The view to start from. 13145 * @param predicate The predicate to evaluate. 13146 * @return The first view that matches the predicate or null. 13147 */ 13148 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 13149 View childToSkip = null; 13150 for (;;) { 13151 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 13152 if (view != null || start == this) { 13153 return view; 13154 } 13155 13156 ViewParent parent = start.getParent(); 13157 if (parent == null || !(parent instanceof View)) { 13158 return null; 13159 } 13160 13161 childToSkip = start; 13162 start = (View) parent; 13163 } 13164 } 13165 13166 /** 13167 * Sets the identifier for this view. The identifier does not have to be 13168 * unique in this view's hierarchy. The identifier should be a positive 13169 * number. 13170 * 13171 * @see #NO_ID 13172 * @see #getId() 13173 * @see #findViewById(int) 13174 * 13175 * @param id a number used to identify the view 13176 * 13177 * @attr ref android.R.styleable#View_id 13178 */ 13179 public void setId(int id) { 13180 mID = id; 13181 } 13182 13183 /** 13184 * {@hide} 13185 * 13186 * @param isRoot true if the view belongs to the root namespace, false 13187 * otherwise 13188 */ 13189 public void setIsRootNamespace(boolean isRoot) { 13190 if (isRoot) { 13191 mPrivateFlags |= IS_ROOT_NAMESPACE; 13192 } else { 13193 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 13194 } 13195 } 13196 13197 /** 13198 * {@hide} 13199 * 13200 * @return true if the view belongs to the root namespace, false otherwise 13201 */ 13202 public boolean isRootNamespace() { 13203 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 13204 } 13205 13206 /** 13207 * Returns this view's identifier. 13208 * 13209 * @return a positive integer used to identify the view or {@link #NO_ID} 13210 * if the view has no ID 13211 * 13212 * @see #setId(int) 13213 * @see #findViewById(int) 13214 * @attr ref android.R.styleable#View_id 13215 */ 13216 @ViewDebug.CapturedViewProperty 13217 public int getId() { 13218 return mID; 13219 } 13220 13221 /** 13222 * Returns this view's tag. 13223 * 13224 * @return the Object stored in this view as a tag 13225 * 13226 * @see #setTag(Object) 13227 * @see #getTag(int) 13228 */ 13229 @ViewDebug.ExportedProperty 13230 public Object getTag() { 13231 return mTag; 13232 } 13233 13234 /** 13235 * Sets the tag associated with this view. A tag can be used to mark 13236 * a view in its hierarchy and does not have to be unique within the 13237 * hierarchy. Tags can also be used to store data within a view without 13238 * resorting to another data structure. 13239 * 13240 * @param tag an Object to tag the view with 13241 * 13242 * @see #getTag() 13243 * @see #setTag(int, Object) 13244 */ 13245 public void setTag(final Object tag) { 13246 mTag = tag; 13247 } 13248 13249 /** 13250 * Returns the tag associated with this view and the specified key. 13251 * 13252 * @param key The key identifying the tag 13253 * 13254 * @return the Object stored in this view as a tag 13255 * 13256 * @see #setTag(int, Object) 13257 * @see #getTag() 13258 */ 13259 public Object getTag(int key) { 13260 if (mKeyedTags != null) return mKeyedTags.get(key); 13261 return null; 13262 } 13263 13264 /** 13265 * Sets a tag associated with this view and a key. A tag can be used 13266 * to mark a view in its hierarchy and does not have to be unique within 13267 * the hierarchy. Tags can also be used to store data within a view 13268 * without resorting to another data structure. 13269 * 13270 * The specified key should be an id declared in the resources of the 13271 * application to ensure it is unique (see the <a 13272 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 13273 * Keys identified as belonging to 13274 * the Android framework or not associated with any package will cause 13275 * an {@link IllegalArgumentException} to be thrown. 13276 * 13277 * @param key The key identifying the tag 13278 * @param tag An Object to tag the view with 13279 * 13280 * @throws IllegalArgumentException If they specified key is not valid 13281 * 13282 * @see #setTag(Object) 13283 * @see #getTag(int) 13284 */ 13285 public void setTag(int key, final Object tag) { 13286 // If the package id is 0x00 or 0x01, it's either an undefined package 13287 // or a framework id 13288 if ((key >>> 24) < 2) { 13289 throw new IllegalArgumentException("The key must be an application-specific " 13290 + "resource id."); 13291 } 13292 13293 setKeyedTag(key, tag); 13294 } 13295 13296 /** 13297 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 13298 * framework id. 13299 * 13300 * @hide 13301 */ 13302 public void setTagInternal(int key, Object tag) { 13303 if ((key >>> 24) != 0x1) { 13304 throw new IllegalArgumentException("The key must be a framework-specific " 13305 + "resource id."); 13306 } 13307 13308 setKeyedTag(key, tag); 13309 } 13310 13311 private void setKeyedTag(int key, Object tag) { 13312 if (mKeyedTags == null) { 13313 mKeyedTags = new SparseArray<Object>(); 13314 } 13315 13316 mKeyedTags.put(key, tag); 13317 } 13318 13319 /** 13320 * @param consistency The type of consistency. See ViewDebug for more information. 13321 * 13322 * @hide 13323 */ 13324 protected boolean dispatchConsistencyCheck(int consistency) { 13325 return onConsistencyCheck(consistency); 13326 } 13327 13328 /** 13329 * Method that subclasses should implement to check their consistency. The type of 13330 * consistency check is indicated by the bit field passed as a parameter. 13331 * 13332 * @param consistency The type of consistency. See ViewDebug for more information. 13333 * 13334 * @throws IllegalStateException if the view is in an inconsistent state. 13335 * 13336 * @hide 13337 */ 13338 protected boolean onConsistencyCheck(int consistency) { 13339 boolean result = true; 13340 13341 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 13342 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 13343 13344 if (checkLayout) { 13345 if (getParent() == null) { 13346 result = false; 13347 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 13348 "View " + this + " does not have a parent."); 13349 } 13350 13351 if (mAttachInfo == null) { 13352 result = false; 13353 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 13354 "View " + this + " is not attached to a window."); 13355 } 13356 } 13357 13358 if (checkDrawing) { 13359 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 13360 // from their draw() method 13361 13362 if ((mPrivateFlags & DRAWN) != DRAWN && 13363 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 13364 result = false; 13365 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 13366 "View " + this + " was invalidated but its drawing cache is valid."); 13367 } 13368 } 13369 13370 return result; 13371 } 13372 13373 /** 13374 * Prints information about this view in the log output, with the tag 13375 * {@link #VIEW_LOG_TAG}. 13376 * 13377 * @hide 13378 */ 13379 public void debug() { 13380 debug(0); 13381 } 13382 13383 /** 13384 * Prints information about this view in the log output, with the tag 13385 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 13386 * indentation defined by the <code>depth</code>. 13387 * 13388 * @param depth the indentation level 13389 * 13390 * @hide 13391 */ 13392 protected void debug(int depth) { 13393 String output = debugIndent(depth - 1); 13394 13395 output += "+ " + this; 13396 int id = getId(); 13397 if (id != -1) { 13398 output += " (id=" + id + ")"; 13399 } 13400 Object tag = getTag(); 13401 if (tag != null) { 13402 output += " (tag=" + tag + ")"; 13403 } 13404 Log.d(VIEW_LOG_TAG, output); 13405 13406 if ((mPrivateFlags & FOCUSED) != 0) { 13407 output = debugIndent(depth) + " FOCUSED"; 13408 Log.d(VIEW_LOG_TAG, output); 13409 } 13410 13411 output = debugIndent(depth); 13412 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 13413 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 13414 + "} "; 13415 Log.d(VIEW_LOG_TAG, output); 13416 13417 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 13418 || mPaddingBottom != 0) { 13419 output = debugIndent(depth); 13420 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 13421 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 13422 Log.d(VIEW_LOG_TAG, output); 13423 } 13424 13425 output = debugIndent(depth); 13426 output += "mMeasureWidth=" + mMeasuredWidth + 13427 " mMeasureHeight=" + mMeasuredHeight; 13428 Log.d(VIEW_LOG_TAG, output); 13429 13430 output = debugIndent(depth); 13431 if (mLayoutParams == null) { 13432 output += "BAD! no layout params"; 13433 } else { 13434 output = mLayoutParams.debug(output); 13435 } 13436 Log.d(VIEW_LOG_TAG, output); 13437 13438 output = debugIndent(depth); 13439 output += "flags={"; 13440 output += View.printFlags(mViewFlags); 13441 output += "}"; 13442 Log.d(VIEW_LOG_TAG, output); 13443 13444 output = debugIndent(depth); 13445 output += "privateFlags={"; 13446 output += View.printPrivateFlags(mPrivateFlags); 13447 output += "}"; 13448 Log.d(VIEW_LOG_TAG, output); 13449 } 13450 13451 /** 13452 * Creates a string of whitespaces used for indentation. 13453 * 13454 * @param depth the indentation level 13455 * @return a String containing (depth * 2 + 3) * 2 white spaces 13456 * 13457 * @hide 13458 */ 13459 protected static String debugIndent(int depth) { 13460 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 13461 for (int i = 0; i < (depth * 2) + 3; i++) { 13462 spaces.append(' ').append(' '); 13463 } 13464 return spaces.toString(); 13465 } 13466 13467 /** 13468 * <p>Return the offset of the widget's text baseline from the widget's top 13469 * boundary. If this widget does not support baseline alignment, this 13470 * method returns -1. </p> 13471 * 13472 * @return the offset of the baseline within the widget's bounds or -1 13473 * if baseline alignment is not supported 13474 */ 13475 @ViewDebug.ExportedProperty(category = "layout") 13476 public int getBaseline() { 13477 return -1; 13478 } 13479 13480 /** 13481 * Call this when something has changed which has invalidated the 13482 * layout of this view. This will schedule a layout pass of the view 13483 * tree. 13484 */ 13485 public void requestLayout() { 13486 if (ViewDebug.TRACE_HIERARCHY) { 13487 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 13488 } 13489 13490 mPrivateFlags |= FORCE_LAYOUT; 13491 mPrivateFlags |= INVALIDATED; 13492 13493 if (mLayoutParams != null) { 13494 mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection()); 13495 } 13496 13497 if (mParent != null && !mParent.isLayoutRequested()) { 13498 mParent.requestLayout(); 13499 } 13500 } 13501 13502 /** 13503 * Forces this view to be laid out during the next layout pass. 13504 * This method does not call requestLayout() or forceLayout() 13505 * on the parent. 13506 */ 13507 public void forceLayout() { 13508 mPrivateFlags |= FORCE_LAYOUT; 13509 mPrivateFlags |= INVALIDATED; 13510 } 13511 13512 /** 13513 * <p> 13514 * This is called to find out how big a view should be. The parent 13515 * supplies constraint information in the width and height parameters. 13516 * </p> 13517 * 13518 * <p> 13519 * The actual measurement work of a view is performed in 13520 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 13521 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 13522 * </p> 13523 * 13524 * 13525 * @param widthMeasureSpec Horizontal space requirements as imposed by the 13526 * parent 13527 * @param heightMeasureSpec Vertical space requirements as imposed by the 13528 * parent 13529 * 13530 * @see #onMeasure(int, int) 13531 */ 13532 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 13533 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 13534 widthMeasureSpec != mOldWidthMeasureSpec || 13535 heightMeasureSpec != mOldHeightMeasureSpec) { 13536 13537 // first clears the measured dimension flag 13538 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 13539 13540 if (ViewDebug.TRACE_HIERARCHY) { 13541 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 13542 } 13543 13544 // measure ourselves, this should set the measured dimension flag back 13545 onMeasure(widthMeasureSpec, heightMeasureSpec); 13546 13547 // flag not set, setMeasuredDimension() was not invoked, we raise 13548 // an exception to warn the developer 13549 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 13550 throw new IllegalStateException("onMeasure() did not set the" 13551 + " measured dimension by calling" 13552 + " setMeasuredDimension()"); 13553 } 13554 13555 mPrivateFlags |= LAYOUT_REQUIRED; 13556 } 13557 13558 mOldWidthMeasureSpec = widthMeasureSpec; 13559 mOldHeightMeasureSpec = heightMeasureSpec; 13560 } 13561 13562 /** 13563 * <p> 13564 * Measure the view and its content to determine the measured width and the 13565 * measured height. This method is invoked by {@link #measure(int, int)} and 13566 * should be overriden by subclasses to provide accurate and efficient 13567 * measurement of their contents. 13568 * </p> 13569 * 13570 * <p> 13571 * <strong>CONTRACT:</strong> When overriding this method, you 13572 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 13573 * measured width and height of this view. Failure to do so will trigger an 13574 * <code>IllegalStateException</code>, thrown by 13575 * {@link #measure(int, int)}. Calling the superclass' 13576 * {@link #onMeasure(int, int)} is a valid use. 13577 * </p> 13578 * 13579 * <p> 13580 * The base class implementation of measure defaults to the background size, 13581 * unless a larger size is allowed by the MeasureSpec. Subclasses should 13582 * override {@link #onMeasure(int, int)} to provide better measurements of 13583 * their content. 13584 * </p> 13585 * 13586 * <p> 13587 * If this method is overridden, it is the subclass's responsibility to make 13588 * sure the measured height and width are at least the view's minimum height 13589 * and width ({@link #getSuggestedMinimumHeight()} and 13590 * {@link #getSuggestedMinimumWidth()}). 13591 * </p> 13592 * 13593 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 13594 * The requirements are encoded with 13595 * {@link android.view.View.MeasureSpec}. 13596 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 13597 * The requirements are encoded with 13598 * {@link android.view.View.MeasureSpec}. 13599 * 13600 * @see #getMeasuredWidth() 13601 * @see #getMeasuredHeight() 13602 * @see #setMeasuredDimension(int, int) 13603 * @see #getSuggestedMinimumHeight() 13604 * @see #getSuggestedMinimumWidth() 13605 * @see android.view.View.MeasureSpec#getMode(int) 13606 * @see android.view.View.MeasureSpec#getSize(int) 13607 */ 13608 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 13609 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 13610 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 13611 } 13612 13613 /** 13614 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 13615 * measured width and measured height. Failing to do so will trigger an 13616 * exception at measurement time.</p> 13617 * 13618 * @param measuredWidth The measured width of this view. May be a complex 13619 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 13620 * {@link #MEASURED_STATE_TOO_SMALL}. 13621 * @param measuredHeight The measured height of this view. May be a complex 13622 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 13623 * {@link #MEASURED_STATE_TOO_SMALL}. 13624 */ 13625 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 13626 mMeasuredWidth = measuredWidth; 13627 mMeasuredHeight = measuredHeight; 13628 13629 mPrivateFlags |= MEASURED_DIMENSION_SET; 13630 } 13631 13632 /** 13633 * Merge two states as returned by {@link #getMeasuredState()}. 13634 * @param curState The current state as returned from a view or the result 13635 * of combining multiple views. 13636 * @param newState The new view state to combine. 13637 * @return Returns a new integer reflecting the combination of the two 13638 * states. 13639 */ 13640 public static int combineMeasuredStates(int curState, int newState) { 13641 return curState | newState; 13642 } 13643 13644 /** 13645 * Version of {@link #resolveSizeAndState(int, int, int)} 13646 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 13647 */ 13648 public static int resolveSize(int size, int measureSpec) { 13649 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 13650 } 13651 13652 /** 13653 * Utility to reconcile a desired size and state, with constraints imposed 13654 * by a MeasureSpec. Will take the desired size, unless a different size 13655 * is imposed by the constraints. The returned value is a compound integer, 13656 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 13657 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 13658 * size is smaller than the size the view wants to be. 13659 * 13660 * @param size How big the view wants to be 13661 * @param measureSpec Constraints imposed by the parent 13662 * @return Size information bit mask as defined by 13663 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 13664 */ 13665 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 13666 int result = size; 13667 int specMode = MeasureSpec.getMode(measureSpec); 13668 int specSize = MeasureSpec.getSize(measureSpec); 13669 switch (specMode) { 13670 case MeasureSpec.UNSPECIFIED: 13671 result = size; 13672 break; 13673 case MeasureSpec.AT_MOST: 13674 if (specSize < size) { 13675 result = specSize | MEASURED_STATE_TOO_SMALL; 13676 } else { 13677 result = size; 13678 } 13679 break; 13680 case MeasureSpec.EXACTLY: 13681 result = specSize; 13682 break; 13683 } 13684 return result | (childMeasuredState&MEASURED_STATE_MASK); 13685 } 13686 13687 /** 13688 * Utility to return a default size. Uses the supplied size if the 13689 * MeasureSpec imposed no constraints. Will get larger if allowed 13690 * by the MeasureSpec. 13691 * 13692 * @param size Default size for this view 13693 * @param measureSpec Constraints imposed by the parent 13694 * @return The size this view should be. 13695 */ 13696 public static int getDefaultSize(int size, int measureSpec) { 13697 int result = size; 13698 int specMode = MeasureSpec.getMode(measureSpec); 13699 int specSize = MeasureSpec.getSize(measureSpec); 13700 13701 switch (specMode) { 13702 case MeasureSpec.UNSPECIFIED: 13703 result = size; 13704 break; 13705 case MeasureSpec.AT_MOST: 13706 case MeasureSpec.EXACTLY: 13707 result = specSize; 13708 break; 13709 } 13710 return result; 13711 } 13712 13713 /** 13714 * Returns the suggested minimum height that the view should use. This 13715 * returns the maximum of the view's minimum height 13716 * and the background's minimum height 13717 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 13718 * <p> 13719 * When being used in {@link #onMeasure(int, int)}, the caller should still 13720 * ensure the returned height is within the requirements of the parent. 13721 * 13722 * @return The suggested minimum height of the view. 13723 */ 13724 protected int getSuggestedMinimumHeight() { 13725 int suggestedMinHeight = mMinHeight; 13726 13727 if (mBGDrawable != null) { 13728 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 13729 if (suggestedMinHeight < bgMinHeight) { 13730 suggestedMinHeight = bgMinHeight; 13731 } 13732 } 13733 13734 return suggestedMinHeight; 13735 } 13736 13737 /** 13738 * Returns the suggested minimum width that the view should use. This 13739 * returns the maximum of the view's minimum width) 13740 * and the background's minimum width 13741 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 13742 * <p> 13743 * When being used in {@link #onMeasure(int, int)}, the caller should still 13744 * ensure the returned width is within the requirements of the parent. 13745 * 13746 * @return The suggested minimum width of the view. 13747 */ 13748 protected int getSuggestedMinimumWidth() { 13749 int suggestedMinWidth = mMinWidth; 13750 13751 if (mBGDrawable != null) { 13752 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 13753 if (suggestedMinWidth < bgMinWidth) { 13754 suggestedMinWidth = bgMinWidth; 13755 } 13756 } 13757 13758 return suggestedMinWidth; 13759 } 13760 13761 /** 13762 * Sets the minimum height of the view. It is not guaranteed the view will 13763 * be able to achieve this minimum height (for example, if its parent layout 13764 * constrains it with less available height). 13765 * 13766 * @param minHeight The minimum height the view will try to be. 13767 */ 13768 public void setMinimumHeight(int minHeight) { 13769 mMinHeight = minHeight; 13770 } 13771 13772 /** 13773 * Sets the minimum width of the view. It is not guaranteed the view will 13774 * be able to achieve this minimum width (for example, if its parent layout 13775 * constrains it with less available width). 13776 * 13777 * @param minWidth The minimum width the view will try to be. 13778 */ 13779 public void setMinimumWidth(int minWidth) { 13780 mMinWidth = minWidth; 13781 } 13782 13783 /** 13784 * Get the animation currently associated with this view. 13785 * 13786 * @return The animation that is currently playing or 13787 * scheduled to play for this view. 13788 */ 13789 public Animation getAnimation() { 13790 return mCurrentAnimation; 13791 } 13792 13793 /** 13794 * Start the specified animation now. 13795 * 13796 * @param animation the animation to start now 13797 */ 13798 public void startAnimation(Animation animation) { 13799 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 13800 setAnimation(animation); 13801 invalidateParentCaches(); 13802 invalidate(true); 13803 } 13804 13805 /** 13806 * Cancels any animations for this view. 13807 */ 13808 public void clearAnimation() { 13809 if (mCurrentAnimation != null) { 13810 mCurrentAnimation.detach(); 13811 } 13812 mCurrentAnimation = null; 13813 invalidateParentIfNeeded(); 13814 } 13815 13816 /** 13817 * Sets the next animation to play for this view. 13818 * If you want the animation to play immediately, use 13819 * startAnimation. This method provides allows fine-grained 13820 * control over the start time and invalidation, but you 13821 * must make sure that 1) the animation has a start time set, and 13822 * 2) the view will be invalidated when the animation is supposed to 13823 * start. 13824 * 13825 * @param animation The next animation, or null. 13826 */ 13827 public void setAnimation(Animation animation) { 13828 mCurrentAnimation = animation; 13829 if (animation != null) { 13830 animation.reset(); 13831 } 13832 } 13833 13834 /** 13835 * Invoked by a parent ViewGroup to notify the start of the animation 13836 * currently associated with this view. If you override this method, 13837 * always call super.onAnimationStart(); 13838 * 13839 * @see #setAnimation(android.view.animation.Animation) 13840 * @see #getAnimation() 13841 */ 13842 protected void onAnimationStart() { 13843 mPrivateFlags |= ANIMATION_STARTED; 13844 } 13845 13846 /** 13847 * Invoked by a parent ViewGroup to notify the end of the animation 13848 * currently associated with this view. If you override this method, 13849 * always call super.onAnimationEnd(); 13850 * 13851 * @see #setAnimation(android.view.animation.Animation) 13852 * @see #getAnimation() 13853 */ 13854 protected void onAnimationEnd() { 13855 mPrivateFlags &= ~ANIMATION_STARTED; 13856 } 13857 13858 /** 13859 * Invoked if there is a Transform that involves alpha. Subclass that can 13860 * draw themselves with the specified alpha should return true, and then 13861 * respect that alpha when their onDraw() is called. If this returns false 13862 * then the view may be redirected to draw into an offscreen buffer to 13863 * fulfill the request, which will look fine, but may be slower than if the 13864 * subclass handles it internally. The default implementation returns false. 13865 * 13866 * @param alpha The alpha (0..255) to apply to the view's drawing 13867 * @return true if the view can draw with the specified alpha. 13868 */ 13869 protected boolean onSetAlpha(int alpha) { 13870 return false; 13871 } 13872 13873 /** 13874 * This is used by the RootView to perform an optimization when 13875 * the view hierarchy contains one or several SurfaceView. 13876 * SurfaceView is always considered transparent, but its children are not, 13877 * therefore all View objects remove themselves from the global transparent 13878 * region (passed as a parameter to this function). 13879 * 13880 * @param region The transparent region for this ViewAncestor (window). 13881 * 13882 * @return Returns true if the effective visibility of the view at this 13883 * point is opaque, regardless of the transparent region; returns false 13884 * if it is possible for underlying windows to be seen behind the view. 13885 * 13886 * {@hide} 13887 */ 13888 public boolean gatherTransparentRegion(Region region) { 13889 final AttachInfo attachInfo = mAttachInfo; 13890 if (region != null && attachInfo != null) { 13891 final int pflags = mPrivateFlags; 13892 if ((pflags & SKIP_DRAW) == 0) { 13893 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 13894 // remove it from the transparent region. 13895 final int[] location = attachInfo.mTransparentLocation; 13896 getLocationInWindow(location); 13897 region.op(location[0], location[1], location[0] + mRight - mLeft, 13898 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 13899 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 13900 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 13901 // exists, so we remove the background drawable's non-transparent 13902 // parts from this transparent region. 13903 applyDrawableToTransparentRegion(mBGDrawable, region); 13904 } 13905 } 13906 return true; 13907 } 13908 13909 /** 13910 * Play a sound effect for this view. 13911 * 13912 * <p>The framework will play sound effects for some built in actions, such as 13913 * clicking, but you may wish to play these effects in your widget, 13914 * for instance, for internal navigation. 13915 * 13916 * <p>The sound effect will only be played if sound effects are enabled by the user, and 13917 * {@link #isSoundEffectsEnabled()} is true. 13918 * 13919 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 13920 */ 13921 public void playSoundEffect(int soundConstant) { 13922 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 13923 return; 13924 } 13925 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 13926 } 13927 13928 /** 13929 * BZZZTT!!1! 13930 * 13931 * <p>Provide haptic feedback to the user for this view. 13932 * 13933 * <p>The framework will provide haptic feedback for some built in actions, 13934 * such as long presses, but you may wish to provide feedback for your 13935 * own widget. 13936 * 13937 * <p>The feedback will only be performed if 13938 * {@link #isHapticFeedbackEnabled()} is true. 13939 * 13940 * @param feedbackConstant One of the constants defined in 13941 * {@link HapticFeedbackConstants} 13942 */ 13943 public boolean performHapticFeedback(int feedbackConstant) { 13944 return performHapticFeedback(feedbackConstant, 0); 13945 } 13946 13947 /** 13948 * BZZZTT!!1! 13949 * 13950 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 13951 * 13952 * @param feedbackConstant One of the constants defined in 13953 * {@link HapticFeedbackConstants} 13954 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 13955 */ 13956 public boolean performHapticFeedback(int feedbackConstant, int flags) { 13957 if (mAttachInfo == null) { 13958 return false; 13959 } 13960 //noinspection SimplifiableIfStatement 13961 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 13962 && !isHapticFeedbackEnabled()) { 13963 return false; 13964 } 13965 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 13966 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 13967 } 13968 13969 /** 13970 * Request that the visibility of the status bar be changed. 13971 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 13972 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 13973 */ 13974 public void setSystemUiVisibility(int visibility) { 13975 if (visibility != mSystemUiVisibility) { 13976 mSystemUiVisibility = visibility; 13977 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 13978 mParent.recomputeViewAttributes(this); 13979 } 13980 } 13981 } 13982 13983 /** 13984 * Returns the status bar visibility that this view has requested. 13985 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 13986 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 13987 */ 13988 public int getSystemUiVisibility() { 13989 return mSystemUiVisibility; 13990 } 13991 13992 /** 13993 * Set a listener to receive callbacks when the visibility of the system bar changes. 13994 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 13995 */ 13996 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 13997 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 13998 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 13999 mParent.recomputeViewAttributes(this); 14000 } 14001 } 14002 14003 /** 14004 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 14005 * the view hierarchy. 14006 */ 14007 public void dispatchSystemUiVisibilityChanged(int visibility) { 14008 ListenerInfo li = mListenerInfo; 14009 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 14010 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 14011 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 14012 } 14013 } 14014 14015 void updateLocalSystemUiVisibility(int localValue, int localChanges) { 14016 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 14017 if (val != mSystemUiVisibility) { 14018 setSystemUiVisibility(val); 14019 } 14020 } 14021 14022 /** 14023 * Creates an image that the system displays during the drag and drop 14024 * operation. This is called a "drag shadow". The default implementation 14025 * for a DragShadowBuilder based on a View returns an image that has exactly the same 14026 * appearance as the given View. The default also positions the center of the drag shadow 14027 * directly under the touch point. If no View is provided (the constructor with no parameters 14028 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 14029 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 14030 * default is an invisible drag shadow. 14031 * <p> 14032 * You are not required to use the View you provide to the constructor as the basis of the 14033 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 14034 * anything you want as the drag shadow. 14035 * </p> 14036 * <p> 14037 * You pass a DragShadowBuilder object to the system when you start the drag. The system 14038 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 14039 * size and position of the drag shadow. It uses this data to construct a 14040 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 14041 * so that your application can draw the shadow image in the Canvas. 14042 * </p> 14043 * 14044 * <div class="special reference"> 14045 * <h3>Developer Guides</h3> 14046 * <p>For a guide to implementing drag and drop features, read the 14047 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 14048 * </div> 14049 */ 14050 public static class DragShadowBuilder { 14051 private final WeakReference<View> mView; 14052 14053 /** 14054 * Constructs a shadow image builder based on a View. By default, the resulting drag 14055 * shadow will have the same appearance and dimensions as the View, with the touch point 14056 * over the center of the View. 14057 * @param view A View. Any View in scope can be used. 14058 */ 14059 public DragShadowBuilder(View view) { 14060 mView = new WeakReference<View>(view); 14061 } 14062 14063 /** 14064 * Construct a shadow builder object with no associated View. This 14065 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 14066 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 14067 * to supply the drag shadow's dimensions and appearance without 14068 * reference to any View object. If they are not overridden, then the result is an 14069 * invisible drag shadow. 14070 */ 14071 public DragShadowBuilder() { 14072 mView = new WeakReference<View>(null); 14073 } 14074 14075 /** 14076 * Returns the View object that had been passed to the 14077 * {@link #View.DragShadowBuilder(View)} 14078 * constructor. If that View parameter was {@code null} or if the 14079 * {@link #View.DragShadowBuilder()} 14080 * constructor was used to instantiate the builder object, this method will return 14081 * null. 14082 * 14083 * @return The View object associate with this builder object. 14084 */ 14085 @SuppressWarnings({"JavadocReference"}) 14086 final public View getView() { 14087 return mView.get(); 14088 } 14089 14090 /** 14091 * Provides the metrics for the shadow image. These include the dimensions of 14092 * the shadow image, and the point within that shadow that should 14093 * be centered under the touch location while dragging. 14094 * <p> 14095 * The default implementation sets the dimensions of the shadow to be the 14096 * same as the dimensions of the View itself and centers the shadow under 14097 * the touch point. 14098 * </p> 14099 * 14100 * @param shadowSize A {@link android.graphics.Point} containing the width and height 14101 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 14102 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 14103 * image. 14104 * 14105 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 14106 * shadow image that should be underneath the touch point during the drag and drop 14107 * operation. Your application must set {@link android.graphics.Point#x} to the 14108 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 14109 */ 14110 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 14111 final View view = mView.get(); 14112 if (view != null) { 14113 shadowSize.set(view.getWidth(), view.getHeight()); 14114 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 14115 } else { 14116 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 14117 } 14118 } 14119 14120 /** 14121 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 14122 * based on the dimensions it received from the 14123 * {@link #onProvideShadowMetrics(Point, Point)} callback. 14124 * 14125 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 14126 */ 14127 public void onDrawShadow(Canvas canvas) { 14128 final View view = mView.get(); 14129 if (view != null) { 14130 view.draw(canvas); 14131 } else { 14132 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 14133 } 14134 } 14135 } 14136 14137 /** 14138 * Starts a drag and drop operation. When your application calls this method, it passes a 14139 * {@link android.view.View.DragShadowBuilder} object to the system. The 14140 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 14141 * to get metrics for the drag shadow, and then calls the object's 14142 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 14143 * <p> 14144 * Once the system has the drag shadow, it begins the drag and drop operation by sending 14145 * drag events to all the View objects in your application that are currently visible. It does 14146 * this either by calling the View object's drag listener (an implementation of 14147 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 14148 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 14149 * Both are passed a {@link android.view.DragEvent} object that has a 14150 * {@link android.view.DragEvent#getAction()} value of 14151 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 14152 * </p> 14153 * <p> 14154 * Your application can invoke startDrag() on any attached View object. The View object does not 14155 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 14156 * be related to the View the user selected for dragging. 14157 * </p> 14158 * @param data A {@link android.content.ClipData} object pointing to the data to be 14159 * transferred by the drag and drop operation. 14160 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 14161 * drag shadow. 14162 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 14163 * drop operation. This Object is put into every DragEvent object sent by the system during the 14164 * current drag. 14165 * <p> 14166 * myLocalState is a lightweight mechanism for the sending information from the dragged View 14167 * to the target Views. For example, it can contain flags that differentiate between a 14168 * a copy operation and a move operation. 14169 * </p> 14170 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 14171 * so the parameter should be set to 0. 14172 * @return {@code true} if the method completes successfully, or 14173 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 14174 * do a drag, and so no drag operation is in progress. 14175 */ 14176 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 14177 Object myLocalState, int flags) { 14178 if (ViewDebug.DEBUG_DRAG) { 14179 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 14180 } 14181 boolean okay = false; 14182 14183 Point shadowSize = new Point(); 14184 Point shadowTouchPoint = new Point(); 14185 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 14186 14187 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 14188 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 14189 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 14190 } 14191 14192 if (ViewDebug.DEBUG_DRAG) { 14193 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 14194 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 14195 } 14196 Surface surface = new Surface(); 14197 try { 14198 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 14199 flags, shadowSize.x, shadowSize.y, surface); 14200 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 14201 + " surface=" + surface); 14202 if (token != null) { 14203 Canvas canvas = surface.lockCanvas(null); 14204 try { 14205 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 14206 shadowBuilder.onDrawShadow(canvas); 14207 } finally { 14208 surface.unlockCanvasAndPost(canvas); 14209 } 14210 14211 final ViewRootImpl root = getViewRootImpl(); 14212 14213 // Cache the local state object for delivery with DragEvents 14214 root.setLocalDragState(myLocalState); 14215 14216 // repurpose 'shadowSize' for the last touch point 14217 root.getLastTouchPoint(shadowSize); 14218 14219 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 14220 shadowSize.x, shadowSize.y, 14221 shadowTouchPoint.x, shadowTouchPoint.y, data); 14222 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 14223 14224 // Off and running! Release our local surface instance; the drag 14225 // shadow surface is now managed by the system process. 14226 surface.release(); 14227 } 14228 } catch (Exception e) { 14229 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 14230 surface.destroy(); 14231 } 14232 14233 return okay; 14234 } 14235 14236 /** 14237 * Handles drag events sent by the system following a call to 14238 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 14239 *<p> 14240 * When the system calls this method, it passes a 14241 * {@link android.view.DragEvent} object. A call to 14242 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 14243 * in DragEvent. The method uses these to determine what is happening in the drag and drop 14244 * operation. 14245 * @param event The {@link android.view.DragEvent} sent by the system. 14246 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 14247 * in DragEvent, indicating the type of drag event represented by this object. 14248 * @return {@code true} if the method was successful, otherwise {@code false}. 14249 * <p> 14250 * The method should return {@code true} in response to an action type of 14251 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 14252 * operation. 14253 * </p> 14254 * <p> 14255 * The method should also return {@code true} in response to an action type of 14256 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 14257 * {@code false} if it didn't. 14258 * </p> 14259 */ 14260 public boolean onDragEvent(DragEvent event) { 14261 return false; 14262 } 14263 14264 /** 14265 * Detects if this View is enabled and has a drag event listener. 14266 * If both are true, then it calls the drag event listener with the 14267 * {@link android.view.DragEvent} it received. If the drag event listener returns 14268 * {@code true}, then dispatchDragEvent() returns {@code true}. 14269 * <p> 14270 * For all other cases, the method calls the 14271 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 14272 * method and returns its result. 14273 * </p> 14274 * <p> 14275 * This ensures that a drag event is always consumed, even if the View does not have a drag 14276 * event listener. However, if the View has a listener and the listener returns true, then 14277 * onDragEvent() is not called. 14278 * </p> 14279 */ 14280 public boolean dispatchDragEvent(DragEvent event) { 14281 //noinspection SimplifiableIfStatement 14282 ListenerInfo li = mListenerInfo; 14283 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 14284 && li.mOnDragListener.onDrag(this, event)) { 14285 return true; 14286 } 14287 return onDragEvent(event); 14288 } 14289 14290 boolean canAcceptDrag() { 14291 return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0; 14292 } 14293 14294 /** 14295 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 14296 * it is ever exposed at all. 14297 * @hide 14298 */ 14299 public void onCloseSystemDialogs(String reason) { 14300 } 14301 14302 /** 14303 * Given a Drawable whose bounds have been set to draw into this view, 14304 * update a Region being computed for 14305 * {@link #gatherTransparentRegion(android.graphics.Region)} so 14306 * that any non-transparent parts of the Drawable are removed from the 14307 * given transparent region. 14308 * 14309 * @param dr The Drawable whose transparency is to be applied to the region. 14310 * @param region A Region holding the current transparency information, 14311 * where any parts of the region that are set are considered to be 14312 * transparent. On return, this region will be modified to have the 14313 * transparency information reduced by the corresponding parts of the 14314 * Drawable that are not transparent. 14315 * {@hide} 14316 */ 14317 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 14318 if (DBG) { 14319 Log.i("View", "Getting transparent region for: " + this); 14320 } 14321 final Region r = dr.getTransparentRegion(); 14322 final Rect db = dr.getBounds(); 14323 final AttachInfo attachInfo = mAttachInfo; 14324 if (r != null && attachInfo != null) { 14325 final int w = getRight()-getLeft(); 14326 final int h = getBottom()-getTop(); 14327 if (db.left > 0) { 14328 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 14329 r.op(0, 0, db.left, h, Region.Op.UNION); 14330 } 14331 if (db.right < w) { 14332 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 14333 r.op(db.right, 0, w, h, Region.Op.UNION); 14334 } 14335 if (db.top > 0) { 14336 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 14337 r.op(0, 0, w, db.top, Region.Op.UNION); 14338 } 14339 if (db.bottom < h) { 14340 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 14341 r.op(0, db.bottom, w, h, Region.Op.UNION); 14342 } 14343 final int[] location = attachInfo.mTransparentLocation; 14344 getLocationInWindow(location); 14345 r.translate(location[0], location[1]); 14346 region.op(r, Region.Op.INTERSECT); 14347 } else { 14348 region.op(db, Region.Op.DIFFERENCE); 14349 } 14350 } 14351 14352 private void checkForLongClick(int delayOffset) { 14353 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 14354 mHasPerformedLongPress = false; 14355 14356 if (mPendingCheckForLongPress == null) { 14357 mPendingCheckForLongPress = new CheckForLongPress(); 14358 } 14359 mPendingCheckForLongPress.rememberWindowAttachCount(); 14360 postDelayed(mPendingCheckForLongPress, 14361 ViewConfiguration.getLongPressTimeout() - delayOffset); 14362 } 14363 } 14364 14365 /** 14366 * Inflate a view from an XML resource. This convenience method wraps the {@link 14367 * LayoutInflater} class, which provides a full range of options for view inflation. 14368 * 14369 * @param context The Context object for your activity or application. 14370 * @param resource The resource ID to inflate 14371 * @param root A view group that will be the parent. Used to properly inflate the 14372 * layout_* parameters. 14373 * @see LayoutInflater 14374 */ 14375 public static View inflate(Context context, int resource, ViewGroup root) { 14376 LayoutInflater factory = LayoutInflater.from(context); 14377 return factory.inflate(resource, root); 14378 } 14379 14380 /** 14381 * Scroll the view with standard behavior for scrolling beyond the normal 14382 * content boundaries. Views that call this method should override 14383 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 14384 * results of an over-scroll operation. 14385 * 14386 * Views can use this method to handle any touch or fling-based scrolling. 14387 * 14388 * @param deltaX Change in X in pixels 14389 * @param deltaY Change in Y in pixels 14390 * @param scrollX Current X scroll value in pixels before applying deltaX 14391 * @param scrollY Current Y scroll value in pixels before applying deltaY 14392 * @param scrollRangeX Maximum content scroll range along the X axis 14393 * @param scrollRangeY Maximum content scroll range along the Y axis 14394 * @param maxOverScrollX Number of pixels to overscroll by in either direction 14395 * along the X axis. 14396 * @param maxOverScrollY Number of pixels to overscroll by in either direction 14397 * along the Y axis. 14398 * @param isTouchEvent true if this scroll operation is the result of a touch event. 14399 * @return true if scrolling was clamped to an over-scroll boundary along either 14400 * axis, false otherwise. 14401 */ 14402 @SuppressWarnings({"UnusedParameters"}) 14403 protected boolean overScrollBy(int deltaX, int deltaY, 14404 int scrollX, int scrollY, 14405 int scrollRangeX, int scrollRangeY, 14406 int maxOverScrollX, int maxOverScrollY, 14407 boolean isTouchEvent) { 14408 final int overScrollMode = mOverScrollMode; 14409 final boolean canScrollHorizontal = 14410 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 14411 final boolean canScrollVertical = 14412 computeVerticalScrollRange() > computeVerticalScrollExtent(); 14413 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 14414 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 14415 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 14416 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 14417 14418 int newScrollX = scrollX + deltaX; 14419 if (!overScrollHorizontal) { 14420 maxOverScrollX = 0; 14421 } 14422 14423 int newScrollY = scrollY + deltaY; 14424 if (!overScrollVertical) { 14425 maxOverScrollY = 0; 14426 } 14427 14428 // Clamp values if at the limits and record 14429 final int left = -maxOverScrollX; 14430 final int right = maxOverScrollX + scrollRangeX; 14431 final int top = -maxOverScrollY; 14432 final int bottom = maxOverScrollY + scrollRangeY; 14433 14434 boolean clampedX = false; 14435 if (newScrollX > right) { 14436 newScrollX = right; 14437 clampedX = true; 14438 } else if (newScrollX < left) { 14439 newScrollX = left; 14440 clampedX = true; 14441 } 14442 14443 boolean clampedY = false; 14444 if (newScrollY > bottom) { 14445 newScrollY = bottom; 14446 clampedY = true; 14447 } else if (newScrollY < top) { 14448 newScrollY = top; 14449 clampedY = true; 14450 } 14451 14452 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 14453 14454 return clampedX || clampedY; 14455 } 14456 14457 /** 14458 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 14459 * respond to the results of an over-scroll operation. 14460 * 14461 * @param scrollX New X scroll value in pixels 14462 * @param scrollY New Y scroll value in pixels 14463 * @param clampedX True if scrollX was clamped to an over-scroll boundary 14464 * @param clampedY True if scrollY was clamped to an over-scroll boundary 14465 */ 14466 protected void onOverScrolled(int scrollX, int scrollY, 14467 boolean clampedX, boolean clampedY) { 14468 // Intentionally empty. 14469 } 14470 14471 /** 14472 * Returns the over-scroll mode for this view. The result will be 14473 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 14474 * (allow over-scrolling only if the view content is larger than the container), 14475 * or {@link #OVER_SCROLL_NEVER}. 14476 * 14477 * @return This view's over-scroll mode. 14478 */ 14479 public int getOverScrollMode() { 14480 return mOverScrollMode; 14481 } 14482 14483 /** 14484 * Set the over-scroll mode for this view. Valid over-scroll modes are 14485 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 14486 * (allow over-scrolling only if the view content is larger than the container), 14487 * or {@link #OVER_SCROLL_NEVER}. 14488 * 14489 * Setting the over-scroll mode of a view will have an effect only if the 14490 * view is capable of scrolling. 14491 * 14492 * @param overScrollMode The new over-scroll mode for this view. 14493 */ 14494 public void setOverScrollMode(int overScrollMode) { 14495 if (overScrollMode != OVER_SCROLL_ALWAYS && 14496 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 14497 overScrollMode != OVER_SCROLL_NEVER) { 14498 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 14499 } 14500 mOverScrollMode = overScrollMode; 14501 } 14502 14503 /** 14504 * Gets a scale factor that determines the distance the view should scroll 14505 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 14506 * @return The vertical scroll scale factor. 14507 * @hide 14508 */ 14509 protected float getVerticalScrollFactor() { 14510 if (mVerticalScrollFactor == 0) { 14511 TypedValue outValue = new TypedValue(); 14512 if (!mContext.getTheme().resolveAttribute( 14513 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 14514 throw new IllegalStateException( 14515 "Expected theme to define listPreferredItemHeight."); 14516 } 14517 mVerticalScrollFactor = outValue.getDimension( 14518 mContext.getResources().getDisplayMetrics()); 14519 } 14520 return mVerticalScrollFactor; 14521 } 14522 14523 /** 14524 * Gets a scale factor that determines the distance the view should scroll 14525 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 14526 * @return The horizontal scroll scale factor. 14527 * @hide 14528 */ 14529 protected float getHorizontalScrollFactor() { 14530 // TODO: Should use something else. 14531 return getVerticalScrollFactor(); 14532 } 14533 14534 /** 14535 * Return the value specifying the text direction or policy that was set with 14536 * {@link #setTextDirection(int)}. 14537 * 14538 * @return the defined text direction. It can be one of: 14539 * 14540 * {@link #TEXT_DIRECTION_INHERIT}, 14541 * {@link #TEXT_DIRECTION_FIRST_STRONG} 14542 * {@link #TEXT_DIRECTION_ANY_RTL}, 14543 * {@link #TEXT_DIRECTION_LTR}, 14544 * {@link #TEXT_DIRECTION_RTL}, 14545 * {@link #TEXT_DIRECTION_LOCALE}, 14546 */ 14547 @ViewDebug.ExportedProperty(category = "text", mapping = { 14548 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 14549 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 14550 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 14551 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 14552 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 14553 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 14554 }) 14555 public int getTextDirection() { 14556 return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT; 14557 } 14558 14559 /** 14560 * Set the text direction. 14561 * 14562 * @param textDirection the direction to set. Should be one of: 14563 * 14564 * {@link #TEXT_DIRECTION_INHERIT}, 14565 * {@link #TEXT_DIRECTION_FIRST_STRONG} 14566 * {@link #TEXT_DIRECTION_ANY_RTL}, 14567 * {@link #TEXT_DIRECTION_LTR}, 14568 * {@link #TEXT_DIRECTION_RTL}, 14569 * {@link #TEXT_DIRECTION_LOCALE}, 14570 */ 14571 public void setTextDirection(int textDirection) { 14572 if (getTextDirection() != textDirection) { 14573 // Reset the current text direction and the resolved one 14574 mPrivateFlags2 &= ~TEXT_DIRECTION_MASK; 14575 resetResolvedTextDirection(); 14576 // Set the new text direction 14577 mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK); 14578 requestLayout(); 14579 invalidate(true); 14580 } 14581 } 14582 14583 /** 14584 * Return the resolved text direction. 14585 * 14586 * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches 14587 * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds 14588 * up the parent chain of the view. if there is no parent, then it will return the default 14589 * {@link #TEXT_DIRECTION_FIRST_STRONG}. 14590 * 14591 * @return the resolved text direction. Returns one of: 14592 * 14593 * {@link #TEXT_DIRECTION_FIRST_STRONG} 14594 * {@link #TEXT_DIRECTION_ANY_RTL}, 14595 * {@link #TEXT_DIRECTION_LTR}, 14596 * {@link #TEXT_DIRECTION_RTL}, 14597 * {@link #TEXT_DIRECTION_LOCALE}, 14598 */ 14599 public int getResolvedTextDirection() { 14600 // The text direction will be resolved only if needed 14601 if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) { 14602 resolveTextDirection(); 14603 } 14604 return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 14605 } 14606 14607 /** 14608 * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when 14609 * resolution is done. 14610 */ 14611 public void resolveTextDirection() { 14612 // Reset any previous text direction resolution 14613 mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK); 14614 14615 if (hasRtlSupport()) { 14616 // Set resolved text direction flag depending on text direction flag 14617 final int textDirection = getTextDirection(); 14618 switch(textDirection) { 14619 case TEXT_DIRECTION_INHERIT: 14620 if (canResolveTextDirection()) { 14621 ViewGroup viewGroup = ((ViewGroup) mParent); 14622 14623 // Set current resolved direction to the same value as the parent's one 14624 final int parentResolvedDirection = viewGroup.getResolvedTextDirection(); 14625 switch (parentResolvedDirection) { 14626 case TEXT_DIRECTION_FIRST_STRONG: 14627 case TEXT_DIRECTION_ANY_RTL: 14628 case TEXT_DIRECTION_LTR: 14629 case TEXT_DIRECTION_RTL: 14630 case TEXT_DIRECTION_LOCALE: 14631 mPrivateFlags2 |= 14632 (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 14633 break; 14634 default: 14635 // Default resolved direction is "first strong" heuristic 14636 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT; 14637 } 14638 } else { 14639 // We cannot do the resolution if there is no parent, so use the default one 14640 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT; 14641 } 14642 break; 14643 case TEXT_DIRECTION_FIRST_STRONG: 14644 case TEXT_DIRECTION_ANY_RTL: 14645 case TEXT_DIRECTION_LTR: 14646 case TEXT_DIRECTION_RTL: 14647 case TEXT_DIRECTION_LOCALE: 14648 // Resolved direction is the same as text direction 14649 mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 14650 break; 14651 default: 14652 // Default resolved direction is "first strong" heuristic 14653 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT; 14654 } 14655 } else { 14656 // Default resolved direction is "first strong" heuristic 14657 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT; 14658 } 14659 14660 // Set to resolved 14661 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED; 14662 onResolvedTextDirectionChanged(); 14663 } 14664 14665 /** 14666 * Called when text direction has been resolved. Subclasses that care about text direction 14667 * resolution should override this method. 14668 * 14669 * The default implementation does nothing. 14670 */ 14671 public void onResolvedTextDirectionChanged() { 14672 } 14673 14674 /** 14675 * Check if text direction resolution can be done. 14676 * 14677 * @return true if text direction resolution can be done otherwise return false. 14678 */ 14679 public boolean canResolveTextDirection() { 14680 switch (getTextDirection()) { 14681 case TEXT_DIRECTION_INHERIT: 14682 return (mParent != null) && (mParent instanceof ViewGroup); 14683 default: 14684 return true; 14685 } 14686 } 14687 14688 /** 14689 * Reset resolved text direction. Text direction can be resolved with a call to 14690 * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when 14691 * reset is done. 14692 */ 14693 public void resetResolvedTextDirection() { 14694 mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK); 14695 onResolvedTextDirectionReset(); 14696 } 14697 14698 /** 14699 * Called when text direction is reset. Subclasses that care about text direction reset should 14700 * override this method and do a reset of the text direction of their children. The default 14701 * implementation does nothing. 14702 */ 14703 public void onResolvedTextDirectionReset() { 14704 } 14705 14706 // 14707 // Properties 14708 // 14709 /** 14710 * A Property wrapper around the <code>alpha</code> functionality handled by the 14711 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 14712 */ 14713 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 14714 @Override 14715 public void setValue(View object, float value) { 14716 object.setAlpha(value); 14717 } 14718 14719 @Override 14720 public Float get(View object) { 14721 return object.getAlpha(); 14722 } 14723 }; 14724 14725 /** 14726 * A Property wrapper around the <code>translationX</code> functionality handled by the 14727 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 14728 */ 14729 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 14730 @Override 14731 public void setValue(View object, float value) { 14732 object.setTranslationX(value); 14733 } 14734 14735 @Override 14736 public Float get(View object) { 14737 return object.getTranslationX(); 14738 } 14739 }; 14740 14741 /** 14742 * A Property wrapper around the <code>translationY</code> functionality handled by the 14743 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 14744 */ 14745 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 14746 @Override 14747 public void setValue(View object, float value) { 14748 object.setTranslationY(value); 14749 } 14750 14751 @Override 14752 public Float get(View object) { 14753 return object.getTranslationY(); 14754 } 14755 }; 14756 14757 /** 14758 * A Property wrapper around the <code>x</code> functionality handled by the 14759 * {@link View#setX(float)} and {@link View#getX()} methods. 14760 */ 14761 public static final Property<View, Float> X = new FloatProperty<View>("x") { 14762 @Override 14763 public void setValue(View object, float value) { 14764 object.setX(value); 14765 } 14766 14767 @Override 14768 public Float get(View object) { 14769 return object.getX(); 14770 } 14771 }; 14772 14773 /** 14774 * A Property wrapper around the <code>y</code> functionality handled by the 14775 * {@link View#setY(float)} and {@link View#getY()} methods. 14776 */ 14777 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 14778 @Override 14779 public void setValue(View object, float value) { 14780 object.setY(value); 14781 } 14782 14783 @Override 14784 public Float get(View object) { 14785 return object.getY(); 14786 } 14787 }; 14788 14789 /** 14790 * A Property wrapper around the <code>rotation</code> functionality handled by the 14791 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 14792 */ 14793 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 14794 @Override 14795 public void setValue(View object, float value) { 14796 object.setRotation(value); 14797 } 14798 14799 @Override 14800 public Float get(View object) { 14801 return object.getRotation(); 14802 } 14803 }; 14804 14805 /** 14806 * A Property wrapper around the <code>rotationX</code> functionality handled by the 14807 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 14808 */ 14809 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 14810 @Override 14811 public void setValue(View object, float value) { 14812 object.setRotationX(value); 14813 } 14814 14815 @Override 14816 public Float get(View object) { 14817 return object.getRotationX(); 14818 } 14819 }; 14820 14821 /** 14822 * A Property wrapper around the <code>rotationY</code> functionality handled by the 14823 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 14824 */ 14825 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 14826 @Override 14827 public void setValue(View object, float value) { 14828 object.setRotationY(value); 14829 } 14830 14831 @Override 14832 public Float get(View object) { 14833 return object.getRotationY(); 14834 } 14835 }; 14836 14837 /** 14838 * A Property wrapper around the <code>scaleX</code> functionality handled by the 14839 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 14840 */ 14841 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 14842 @Override 14843 public void setValue(View object, float value) { 14844 object.setScaleX(value); 14845 } 14846 14847 @Override 14848 public Float get(View object) { 14849 return object.getScaleX(); 14850 } 14851 }; 14852 14853 /** 14854 * A Property wrapper around the <code>scaleY</code> functionality handled by the 14855 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 14856 */ 14857 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 14858 @Override 14859 public void setValue(View object, float value) { 14860 object.setScaleY(value); 14861 } 14862 14863 @Override 14864 public Float get(View object) { 14865 return object.getScaleY(); 14866 } 14867 }; 14868 14869 /** 14870 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 14871 * Each MeasureSpec represents a requirement for either the width or the height. 14872 * A MeasureSpec is comprised of a size and a mode. There are three possible 14873 * modes: 14874 * <dl> 14875 * <dt>UNSPECIFIED</dt> 14876 * <dd> 14877 * The parent has not imposed any constraint on the child. It can be whatever size 14878 * it wants. 14879 * </dd> 14880 * 14881 * <dt>EXACTLY</dt> 14882 * <dd> 14883 * The parent has determined an exact size for the child. The child is going to be 14884 * given those bounds regardless of how big it wants to be. 14885 * </dd> 14886 * 14887 * <dt>AT_MOST</dt> 14888 * <dd> 14889 * The child can be as large as it wants up to the specified size. 14890 * </dd> 14891 * </dl> 14892 * 14893 * MeasureSpecs are implemented as ints to reduce object allocation. This class 14894 * is provided to pack and unpack the <size, mode> tuple into the int. 14895 */ 14896 public static class MeasureSpec { 14897 private static final int MODE_SHIFT = 30; 14898 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 14899 14900 /** 14901 * Measure specification mode: The parent has not imposed any constraint 14902 * on the child. It can be whatever size it wants. 14903 */ 14904 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 14905 14906 /** 14907 * Measure specification mode: The parent has determined an exact size 14908 * for the child. The child is going to be given those bounds regardless 14909 * of how big it wants to be. 14910 */ 14911 public static final int EXACTLY = 1 << MODE_SHIFT; 14912 14913 /** 14914 * Measure specification mode: The child can be as large as it wants up 14915 * to the specified size. 14916 */ 14917 public static final int AT_MOST = 2 << MODE_SHIFT; 14918 14919 /** 14920 * Creates a measure specification based on the supplied size and mode. 14921 * 14922 * The mode must always be one of the following: 14923 * <ul> 14924 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 14925 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 14926 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 14927 * </ul> 14928 * 14929 * @param size the size of the measure specification 14930 * @param mode the mode of the measure specification 14931 * @return the measure specification based on size and mode 14932 */ 14933 public static int makeMeasureSpec(int size, int mode) { 14934 return size + mode; 14935 } 14936 14937 /** 14938 * Extracts the mode from the supplied measure specification. 14939 * 14940 * @param measureSpec the measure specification to extract the mode from 14941 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 14942 * {@link android.view.View.MeasureSpec#AT_MOST} or 14943 * {@link android.view.View.MeasureSpec#EXACTLY} 14944 */ 14945 public static int getMode(int measureSpec) { 14946 return (measureSpec & MODE_MASK); 14947 } 14948 14949 /** 14950 * Extracts the size from the supplied measure specification. 14951 * 14952 * @param measureSpec the measure specification to extract the size from 14953 * @return the size in pixels defined in the supplied measure specification 14954 */ 14955 public static int getSize(int measureSpec) { 14956 return (measureSpec & ~MODE_MASK); 14957 } 14958 14959 /** 14960 * Returns a String representation of the specified measure 14961 * specification. 14962 * 14963 * @param measureSpec the measure specification to convert to a String 14964 * @return a String with the following format: "MeasureSpec: MODE SIZE" 14965 */ 14966 public static String toString(int measureSpec) { 14967 int mode = getMode(measureSpec); 14968 int size = getSize(measureSpec); 14969 14970 StringBuilder sb = new StringBuilder("MeasureSpec: "); 14971 14972 if (mode == UNSPECIFIED) 14973 sb.append("UNSPECIFIED "); 14974 else if (mode == EXACTLY) 14975 sb.append("EXACTLY "); 14976 else if (mode == AT_MOST) 14977 sb.append("AT_MOST "); 14978 else 14979 sb.append(mode).append(" "); 14980 14981 sb.append(size); 14982 return sb.toString(); 14983 } 14984 } 14985 14986 class CheckForLongPress implements Runnable { 14987 14988 private int mOriginalWindowAttachCount; 14989 14990 public void run() { 14991 if (isPressed() && (mParent != null) 14992 && mOriginalWindowAttachCount == mWindowAttachCount) { 14993 if (performLongClick()) { 14994 mHasPerformedLongPress = true; 14995 } 14996 } 14997 } 14998 14999 public void rememberWindowAttachCount() { 15000 mOriginalWindowAttachCount = mWindowAttachCount; 15001 } 15002 } 15003 15004 private final class CheckForTap implements Runnable { 15005 public void run() { 15006 mPrivateFlags &= ~PREPRESSED; 15007 setPressed(true); 15008 checkForLongClick(ViewConfiguration.getTapTimeout()); 15009 } 15010 } 15011 15012 private final class PerformClick implements Runnable { 15013 public void run() { 15014 performClick(); 15015 } 15016 } 15017 15018 /** @hide */ 15019 public void hackTurnOffWindowResizeAnim(boolean off) { 15020 mAttachInfo.mTurnOffWindowResizeAnim = off; 15021 } 15022 15023 /** 15024 * This method returns a ViewPropertyAnimator object, which can be used to animate 15025 * specific properties on this View. 15026 * 15027 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 15028 */ 15029 public ViewPropertyAnimator animate() { 15030 if (mAnimator == null) { 15031 mAnimator = new ViewPropertyAnimator(this); 15032 } 15033 return mAnimator; 15034 } 15035 15036 /** 15037 * Interface definition for a callback to be invoked when a key event is 15038 * dispatched to this view. The callback will be invoked before the key 15039 * event is given to the view. 15040 */ 15041 public interface OnKeyListener { 15042 /** 15043 * Called when a key is dispatched to a view. This allows listeners to 15044 * get a chance to respond before the target view. 15045 * 15046 * @param v The view the key has been dispatched to. 15047 * @param keyCode The code for the physical key that was pressed 15048 * @param event The KeyEvent object containing full information about 15049 * the event. 15050 * @return True if the listener has consumed the event, false otherwise. 15051 */ 15052 boolean onKey(View v, int keyCode, KeyEvent event); 15053 } 15054 15055 /** 15056 * Interface definition for a callback to be invoked when a touch event is 15057 * dispatched to this view. The callback will be invoked before the touch 15058 * event is given to the view. 15059 */ 15060 public interface OnTouchListener { 15061 /** 15062 * Called when a touch event is dispatched to a view. This allows listeners to 15063 * get a chance to respond before the target view. 15064 * 15065 * @param v The view the touch event has been dispatched to. 15066 * @param event The MotionEvent object containing full information about 15067 * the event. 15068 * @return True if the listener has consumed the event, false otherwise. 15069 */ 15070 boolean onTouch(View v, MotionEvent event); 15071 } 15072 15073 /** 15074 * Interface definition for a callback to be invoked when a hover event is 15075 * dispatched to this view. The callback will be invoked before the hover 15076 * event is given to the view. 15077 */ 15078 public interface OnHoverListener { 15079 /** 15080 * Called when a hover event is dispatched to a view. This allows listeners to 15081 * get a chance to respond before the target view. 15082 * 15083 * @param v The view the hover event has been dispatched to. 15084 * @param event The MotionEvent object containing full information about 15085 * the event. 15086 * @return True if the listener has consumed the event, false otherwise. 15087 */ 15088 boolean onHover(View v, MotionEvent event); 15089 } 15090 15091 /** 15092 * Interface definition for a callback to be invoked when a generic motion event is 15093 * dispatched to this view. The callback will be invoked before the generic motion 15094 * event is given to the view. 15095 */ 15096 public interface OnGenericMotionListener { 15097 /** 15098 * Called when a generic motion event is dispatched to a view. This allows listeners to 15099 * get a chance to respond before the target view. 15100 * 15101 * @param v The view the generic motion event has been dispatched to. 15102 * @param event The MotionEvent object containing full information about 15103 * the event. 15104 * @return True if the listener has consumed the event, false otherwise. 15105 */ 15106 boolean onGenericMotion(View v, MotionEvent event); 15107 } 15108 15109 /** 15110 * Interface definition for a callback to be invoked when a view has been clicked and held. 15111 */ 15112 public interface OnLongClickListener { 15113 /** 15114 * Called when a view has been clicked and held. 15115 * 15116 * @param v The view that was clicked and held. 15117 * 15118 * @return true if the callback consumed the long click, false otherwise. 15119 */ 15120 boolean onLongClick(View v); 15121 } 15122 15123 /** 15124 * Interface definition for a callback to be invoked when a drag is being dispatched 15125 * to this view. The callback will be invoked before the hosting view's own 15126 * onDrag(event) method. If the listener wants to fall back to the hosting view's 15127 * onDrag(event) behavior, it should return 'false' from this callback. 15128 * 15129 * <div class="special reference"> 15130 * <h3>Developer Guides</h3> 15131 * <p>For a guide to implementing drag and drop features, read the 15132 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 15133 * </div> 15134 */ 15135 public interface OnDragListener { 15136 /** 15137 * Called when a drag event is dispatched to a view. This allows listeners 15138 * to get a chance to override base View behavior. 15139 * 15140 * @param v The View that received the drag event. 15141 * @param event The {@link android.view.DragEvent} object for the drag event. 15142 * @return {@code true} if the drag event was handled successfully, or {@code false} 15143 * if the drag event was not handled. Note that {@code false} will trigger the View 15144 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 15145 */ 15146 boolean onDrag(View v, DragEvent event); 15147 } 15148 15149 /** 15150 * Interface definition for a callback to be invoked when the focus state of 15151 * a view changed. 15152 */ 15153 public interface OnFocusChangeListener { 15154 /** 15155 * Called when the focus state of a view has changed. 15156 * 15157 * @param v The view whose state has changed. 15158 * @param hasFocus The new focus state of v. 15159 */ 15160 void onFocusChange(View v, boolean hasFocus); 15161 } 15162 15163 /** 15164 * Interface definition for a callback to be invoked when a view is clicked. 15165 */ 15166 public interface OnClickListener { 15167 /** 15168 * Called when a view has been clicked. 15169 * 15170 * @param v The view that was clicked. 15171 */ 15172 void onClick(View v); 15173 } 15174 15175 /** 15176 * Interface definition for a callback to be invoked when the context menu 15177 * for this view is being built. 15178 */ 15179 public interface OnCreateContextMenuListener { 15180 /** 15181 * Called when the context menu for this view is being built. It is not 15182 * safe to hold onto the menu after this method returns. 15183 * 15184 * @param menu The context menu that is being built 15185 * @param v The view for which the context menu is being built 15186 * @param menuInfo Extra information about the item for which the 15187 * context menu should be shown. This information will vary 15188 * depending on the class of v. 15189 */ 15190 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 15191 } 15192 15193 /** 15194 * Interface definition for a callback to be invoked when the status bar changes 15195 * visibility. This reports <strong>global</strong> changes to the system UI 15196 * state, not just what the application is requesting. 15197 * 15198 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 15199 */ 15200 public interface OnSystemUiVisibilityChangeListener { 15201 /** 15202 * Called when the status bar changes visibility because of a call to 15203 * {@link View#setSystemUiVisibility(int)}. 15204 * 15205 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 15206 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. This tells you the 15207 * <strong>global</strong> state of the UI visibility flags, not what your 15208 * app is currently applying. 15209 */ 15210 public void onSystemUiVisibilityChange(int visibility); 15211 } 15212 15213 /** 15214 * Interface definition for a callback to be invoked when this view is attached 15215 * or detached from its window. 15216 */ 15217 public interface OnAttachStateChangeListener { 15218 /** 15219 * Called when the view is attached to a window. 15220 * @param v The view that was attached 15221 */ 15222 public void onViewAttachedToWindow(View v); 15223 /** 15224 * Called when the view is detached from a window. 15225 * @param v The view that was detached 15226 */ 15227 public void onViewDetachedFromWindow(View v); 15228 } 15229 15230 private final class UnsetPressedState implements Runnable { 15231 public void run() { 15232 setPressed(false); 15233 } 15234 } 15235 15236 /** 15237 * Base class for derived classes that want to save and restore their own 15238 * state in {@link android.view.View#onSaveInstanceState()}. 15239 */ 15240 public static class BaseSavedState extends AbsSavedState { 15241 /** 15242 * Constructor used when reading from a parcel. Reads the state of the superclass. 15243 * 15244 * @param source 15245 */ 15246 public BaseSavedState(Parcel source) { 15247 super(source); 15248 } 15249 15250 /** 15251 * Constructor called by derived classes when creating their SavedState objects 15252 * 15253 * @param superState The state of the superclass of this view 15254 */ 15255 public BaseSavedState(Parcelable superState) { 15256 super(superState); 15257 } 15258 15259 public static final Parcelable.Creator<BaseSavedState> CREATOR = 15260 new Parcelable.Creator<BaseSavedState>() { 15261 public BaseSavedState createFromParcel(Parcel in) { 15262 return new BaseSavedState(in); 15263 } 15264 15265 public BaseSavedState[] newArray(int size) { 15266 return new BaseSavedState[size]; 15267 } 15268 }; 15269 } 15270 15271 /** 15272 * A set of information given to a view when it is attached to its parent 15273 * window. 15274 */ 15275 static class AttachInfo { 15276 interface Callbacks { 15277 void playSoundEffect(int effectId); 15278 boolean performHapticFeedback(int effectId, boolean always); 15279 } 15280 15281 /** 15282 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 15283 * to a Handler. This class contains the target (View) to invalidate and 15284 * the coordinates of the dirty rectangle. 15285 * 15286 * For performance purposes, this class also implements a pool of up to 15287 * POOL_LIMIT objects that get reused. This reduces memory allocations 15288 * whenever possible. 15289 */ 15290 static class InvalidateInfo implements Poolable<InvalidateInfo> { 15291 private static final int POOL_LIMIT = 10; 15292 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 15293 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 15294 public InvalidateInfo newInstance() { 15295 return new InvalidateInfo(); 15296 } 15297 15298 public void onAcquired(InvalidateInfo element) { 15299 } 15300 15301 public void onReleased(InvalidateInfo element) { 15302 element.target = null; 15303 } 15304 }, POOL_LIMIT) 15305 ); 15306 15307 private InvalidateInfo mNext; 15308 private boolean mIsPooled; 15309 15310 View target; 15311 15312 int left; 15313 int top; 15314 int right; 15315 int bottom; 15316 15317 public void setNextPoolable(InvalidateInfo element) { 15318 mNext = element; 15319 } 15320 15321 public InvalidateInfo getNextPoolable() { 15322 return mNext; 15323 } 15324 15325 static InvalidateInfo acquire() { 15326 return sPool.acquire(); 15327 } 15328 15329 void release() { 15330 sPool.release(this); 15331 } 15332 15333 public boolean isPooled() { 15334 return mIsPooled; 15335 } 15336 15337 public void setPooled(boolean isPooled) { 15338 mIsPooled = isPooled; 15339 } 15340 } 15341 15342 final IWindowSession mSession; 15343 15344 final IWindow mWindow; 15345 15346 final IBinder mWindowToken; 15347 15348 final Callbacks mRootCallbacks; 15349 15350 HardwareCanvas mHardwareCanvas; 15351 15352 /** 15353 * The top view of the hierarchy. 15354 */ 15355 View mRootView; 15356 15357 IBinder mPanelParentWindowToken; 15358 Surface mSurface; 15359 15360 boolean mHardwareAccelerated; 15361 boolean mHardwareAccelerationRequested; 15362 HardwareRenderer mHardwareRenderer; 15363 15364 boolean mScreenOn; 15365 15366 /** 15367 * Scale factor used by the compatibility mode 15368 */ 15369 float mApplicationScale; 15370 15371 /** 15372 * Indicates whether the application is in compatibility mode 15373 */ 15374 boolean mScalingRequired; 15375 15376 /** 15377 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 15378 */ 15379 boolean mTurnOffWindowResizeAnim; 15380 15381 /** 15382 * Left position of this view's window 15383 */ 15384 int mWindowLeft; 15385 15386 /** 15387 * Top position of this view's window 15388 */ 15389 int mWindowTop; 15390 15391 /** 15392 * Indicates whether views need to use 32-bit drawing caches 15393 */ 15394 boolean mUse32BitDrawingCache; 15395 15396 /** 15397 * For windows that are full-screen but using insets to layout inside 15398 * of the screen decorations, these are the current insets for the 15399 * content of the window. 15400 */ 15401 final Rect mContentInsets = new Rect(); 15402 15403 /** 15404 * For windows that are full-screen but using insets to layout inside 15405 * of the screen decorations, these are the current insets for the 15406 * actual visible parts of the window. 15407 */ 15408 final Rect mVisibleInsets = new Rect(); 15409 15410 /** 15411 * The internal insets given by this window. This value is 15412 * supplied by the client (through 15413 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 15414 * be given to the window manager when changed to be used in laying 15415 * out windows behind it. 15416 */ 15417 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 15418 = new ViewTreeObserver.InternalInsetsInfo(); 15419 15420 /** 15421 * All views in the window's hierarchy that serve as scroll containers, 15422 * used to determine if the window can be resized or must be panned 15423 * to adjust for a soft input area. 15424 */ 15425 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 15426 15427 final KeyEvent.DispatcherState mKeyDispatchState 15428 = new KeyEvent.DispatcherState(); 15429 15430 /** 15431 * Indicates whether the view's window currently has the focus. 15432 */ 15433 boolean mHasWindowFocus; 15434 15435 /** 15436 * The current visibility of the window. 15437 */ 15438 int mWindowVisibility; 15439 15440 /** 15441 * Indicates the time at which drawing started to occur. 15442 */ 15443 long mDrawingTime; 15444 15445 /** 15446 * Indicates whether or not ignoring the DIRTY_MASK flags. 15447 */ 15448 boolean mIgnoreDirtyState; 15449 15450 /** 15451 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 15452 * to avoid clearing that flag prematurely. 15453 */ 15454 boolean mSetIgnoreDirtyState = false; 15455 15456 /** 15457 * Indicates whether the view's window is currently in touch mode. 15458 */ 15459 boolean mInTouchMode; 15460 15461 /** 15462 * Indicates that ViewAncestor should trigger a global layout change 15463 * the next time it performs a traversal 15464 */ 15465 boolean mRecomputeGlobalAttributes; 15466 15467 /** 15468 * Always report new attributes at next traversal. 15469 */ 15470 boolean mForceReportNewAttributes; 15471 15472 /** 15473 * Set during a traveral if any views want to keep the screen on. 15474 */ 15475 boolean mKeepScreenOn; 15476 15477 /** 15478 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 15479 */ 15480 int mSystemUiVisibility; 15481 15482 /** 15483 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 15484 * attached. 15485 */ 15486 boolean mHasSystemUiListeners; 15487 15488 /** 15489 * Set if the visibility of any views has changed. 15490 */ 15491 boolean mViewVisibilityChanged; 15492 15493 /** 15494 * Set to true if a view has been scrolled. 15495 */ 15496 boolean mViewScrollChanged; 15497 15498 /** 15499 * Global to the view hierarchy used as a temporary for dealing with 15500 * x/y points in the transparent region computations. 15501 */ 15502 final int[] mTransparentLocation = new int[2]; 15503 15504 /** 15505 * Global to the view hierarchy used as a temporary for dealing with 15506 * x/y points in the ViewGroup.invalidateChild implementation. 15507 */ 15508 final int[] mInvalidateChildLocation = new int[2]; 15509 15510 15511 /** 15512 * Global to the view hierarchy used as a temporary for dealing with 15513 * x/y location when view is transformed. 15514 */ 15515 final float[] mTmpTransformLocation = new float[2]; 15516 15517 /** 15518 * The view tree observer used to dispatch global events like 15519 * layout, pre-draw, touch mode change, etc. 15520 */ 15521 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 15522 15523 /** 15524 * A Canvas used by the view hierarchy to perform bitmap caching. 15525 */ 15526 Canvas mCanvas; 15527 15528 /** 15529 * The view root impl. 15530 */ 15531 final ViewRootImpl mViewRootImpl; 15532 15533 /** 15534 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 15535 * handler can be used to pump events in the UI events queue. 15536 */ 15537 final Handler mHandler; 15538 15539 /** 15540 * Temporary for use in computing invalidate rectangles while 15541 * calling up the hierarchy. 15542 */ 15543 final Rect mTmpInvalRect = new Rect(); 15544 15545 /** 15546 * Temporary for use in computing hit areas with transformed views 15547 */ 15548 final RectF mTmpTransformRect = new RectF(); 15549 15550 /** 15551 * Temporary list for use in collecting focusable descendents of a view. 15552 */ 15553 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 15554 15555 /** 15556 * The id of the window for accessibility purposes. 15557 */ 15558 int mAccessibilityWindowId = View.NO_ID; 15559 15560 /** 15561 * Creates a new set of attachment information with the specified 15562 * events handler and thread. 15563 * 15564 * @param handler the events handler the view must use 15565 */ 15566 AttachInfo(IWindowSession session, IWindow window, 15567 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 15568 mSession = session; 15569 mWindow = window; 15570 mWindowToken = window.asBinder(); 15571 mViewRootImpl = viewRootImpl; 15572 mHandler = handler; 15573 mRootCallbacks = effectPlayer; 15574 } 15575 } 15576 15577 /** 15578 * <p>ScrollabilityCache holds various fields used by a View when scrolling 15579 * is supported. This avoids keeping too many unused fields in most 15580 * instances of View.</p> 15581 */ 15582 private static class ScrollabilityCache implements Runnable { 15583 15584 /** 15585 * Scrollbars are not visible 15586 */ 15587 public static final int OFF = 0; 15588 15589 /** 15590 * Scrollbars are visible 15591 */ 15592 public static final int ON = 1; 15593 15594 /** 15595 * Scrollbars are fading away 15596 */ 15597 public static final int FADING = 2; 15598 15599 public boolean fadeScrollBars; 15600 15601 public int fadingEdgeLength; 15602 public int scrollBarDefaultDelayBeforeFade; 15603 public int scrollBarFadeDuration; 15604 15605 public int scrollBarSize; 15606 public ScrollBarDrawable scrollBar; 15607 public float[] interpolatorValues; 15608 public View host; 15609 15610 public final Paint paint; 15611 public final Matrix matrix; 15612 public Shader shader; 15613 15614 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 15615 15616 private static final float[] OPAQUE = { 255 }; 15617 private static final float[] TRANSPARENT = { 0.0f }; 15618 15619 /** 15620 * When fading should start. This time moves into the future every time 15621 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 15622 */ 15623 public long fadeStartTime; 15624 15625 15626 /** 15627 * The current state of the scrollbars: ON, OFF, or FADING 15628 */ 15629 public int state = OFF; 15630 15631 private int mLastColor; 15632 15633 public ScrollabilityCache(ViewConfiguration configuration, View host) { 15634 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 15635 scrollBarSize = configuration.getScaledScrollBarSize(); 15636 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 15637 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 15638 15639 paint = new Paint(); 15640 matrix = new Matrix(); 15641 // use use a height of 1, and then wack the matrix each time we 15642 // actually use it. 15643 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 15644 15645 paint.setShader(shader); 15646 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 15647 this.host = host; 15648 } 15649 15650 public void setFadeColor(int color) { 15651 if (color != 0 && color != mLastColor) { 15652 mLastColor = color; 15653 color |= 0xFF000000; 15654 15655 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 15656 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 15657 15658 paint.setShader(shader); 15659 // Restore the default transfer mode (src_over) 15660 paint.setXfermode(null); 15661 } 15662 } 15663 15664 public void run() { 15665 long now = AnimationUtils.currentAnimationTimeMillis(); 15666 if (now >= fadeStartTime) { 15667 15668 // the animation fades the scrollbars out by changing 15669 // the opacity (alpha) from fully opaque to fully 15670 // transparent 15671 int nextFrame = (int) now; 15672 int framesCount = 0; 15673 15674 Interpolator interpolator = scrollBarInterpolator; 15675 15676 // Start opaque 15677 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 15678 15679 // End transparent 15680 nextFrame += scrollBarFadeDuration; 15681 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 15682 15683 state = FADING; 15684 15685 // Kick off the fade animation 15686 host.invalidate(true); 15687 } 15688 } 15689 } 15690 15691 /** 15692 * Resuable callback for sending 15693 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 15694 */ 15695 private class SendViewScrolledAccessibilityEvent implements Runnable { 15696 public volatile boolean mIsPending; 15697 15698 public void run() { 15699 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 15700 mIsPending = false; 15701 } 15702 } 15703 15704 /** 15705 * <p> 15706 * This class represents a delegate that can be registered in a {@link View} 15707 * to enhance accessibility support via composition rather via inheritance. 15708 * It is specifically targeted to widget developers that extend basic View 15709 * classes i.e. classes in package android.view, that would like their 15710 * applications to be backwards compatible. 15711 * </p> 15712 * <p> 15713 * A scenario in which a developer would like to use an accessibility delegate 15714 * is overriding a method introduced in a later API version then the minimal API 15715 * version supported by the application. For example, the method 15716 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 15717 * in API version 4 when the accessibility APIs were first introduced. If a 15718 * developer would like his application to run on API version 4 devices (assuming 15719 * all other APIs used by the application are version 4 or lower) and take advantage 15720 * of this method, instead of overriding the method which would break the application's 15721 * backwards compatibility, he can override the corresponding method in this 15722 * delegate and register the delegate in the target View if the API version of 15723 * the system is high enough i.e. the API version is same or higher to the API 15724 * version that introduced 15725 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 15726 * </p> 15727 * <p> 15728 * Here is an example implementation: 15729 * </p> 15730 * <code><pre><p> 15731 * if (Build.VERSION.SDK_INT >= 14) { 15732 * // If the API version is equal of higher than the version in 15733 * // which onInitializeAccessibilityNodeInfo was introduced we 15734 * // register a delegate with a customized implementation. 15735 * View view = findViewById(R.id.view_id); 15736 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 15737 * public void onInitializeAccessibilityNodeInfo(View host, 15738 * AccessibilityNodeInfo info) { 15739 * // Let the default implementation populate the info. 15740 * super.onInitializeAccessibilityNodeInfo(host, info); 15741 * // Set some other information. 15742 * info.setEnabled(host.isEnabled()); 15743 * } 15744 * }); 15745 * } 15746 * </code></pre></p> 15747 * <p> 15748 * This delegate contains methods that correspond to the accessibility methods 15749 * in View. If a delegate has been specified the implementation in View hands 15750 * off handling to the corresponding method in this delegate. The default 15751 * implementation the delegate methods behaves exactly as the corresponding 15752 * method in View for the case of no accessibility delegate been set. Hence, 15753 * to customize the behavior of a View method, clients can override only the 15754 * corresponding delegate method without altering the behavior of the rest 15755 * accessibility related methods of the host view. 15756 * </p> 15757 */ 15758 public static class AccessibilityDelegate { 15759 15760 /** 15761 * Sends an accessibility event of the given type. If accessibility is not 15762 * enabled this method has no effect. 15763 * <p> 15764 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 15765 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 15766 * been set. 15767 * </p> 15768 * 15769 * @param host The View hosting the delegate. 15770 * @param eventType The type of the event to send. 15771 * 15772 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 15773 */ 15774 public void sendAccessibilityEvent(View host, int eventType) { 15775 host.sendAccessibilityEventInternal(eventType); 15776 } 15777 15778 /** 15779 * Sends an accessibility event. This method behaves exactly as 15780 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 15781 * empty {@link AccessibilityEvent} and does not perform a check whether 15782 * accessibility is enabled. 15783 * <p> 15784 * The default implementation behaves as 15785 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 15786 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 15787 * the case of no accessibility delegate been set. 15788 * </p> 15789 * 15790 * @param host The View hosting the delegate. 15791 * @param event The event to send. 15792 * 15793 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 15794 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 15795 */ 15796 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 15797 host.sendAccessibilityEventUncheckedInternal(event); 15798 } 15799 15800 /** 15801 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 15802 * to its children for adding their text content to the event. 15803 * <p> 15804 * The default implementation behaves as 15805 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 15806 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 15807 * the case of no accessibility delegate been set. 15808 * </p> 15809 * 15810 * @param host The View hosting the delegate. 15811 * @param event The event. 15812 * @return True if the event population was completed. 15813 * 15814 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 15815 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 15816 */ 15817 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 15818 return host.dispatchPopulateAccessibilityEventInternal(event); 15819 } 15820 15821 /** 15822 * Gives a chance to the host View to populate the accessibility event with its 15823 * text content. 15824 * <p> 15825 * The default implementation behaves as 15826 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 15827 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 15828 * the case of no accessibility delegate been set. 15829 * </p> 15830 * 15831 * @param host The View hosting the delegate. 15832 * @param event The accessibility event which to populate. 15833 * 15834 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 15835 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 15836 */ 15837 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 15838 host.onPopulateAccessibilityEventInternal(event); 15839 } 15840 15841 /** 15842 * Initializes an {@link AccessibilityEvent} with information about the 15843 * the host View which is the event source. 15844 * <p> 15845 * The default implementation behaves as 15846 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 15847 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 15848 * the case of no accessibility delegate been set. 15849 * </p> 15850 * 15851 * @param host The View hosting the delegate. 15852 * @param event The event to initialize. 15853 * 15854 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 15855 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 15856 */ 15857 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 15858 host.onInitializeAccessibilityEventInternal(event); 15859 } 15860 15861 /** 15862 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 15863 * <p> 15864 * The default implementation behaves as 15865 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 15866 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 15867 * the case of no accessibility delegate been set. 15868 * </p> 15869 * 15870 * @param host The View hosting the delegate. 15871 * @param info The instance to initialize. 15872 * 15873 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 15874 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 15875 */ 15876 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 15877 host.onInitializeAccessibilityNodeInfoInternal(info); 15878 } 15879 15880 /** 15881 * Called when a child of the host View has requested sending an 15882 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 15883 * to augment the event. 15884 * <p> 15885 * The default implementation behaves as 15886 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 15887 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 15888 * the case of no accessibility delegate been set. 15889 * </p> 15890 * 15891 * @param host The View hosting the delegate. 15892 * @param child The child which requests sending the event. 15893 * @param event The event to be sent. 15894 * @return True if the event should be sent 15895 * 15896 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 15897 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 15898 */ 15899 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 15900 AccessibilityEvent event) { 15901 return host.onRequestSendAccessibilityEventInternal(child, event); 15902 } 15903 15904 /** 15905 * Gets the provider for managing a virtual view hierarchy rooted at this View 15906 * and reported to {@link android.accessibilityservice.AccessibilityService}s 15907 * that explore the window content. 15908 * <p> 15909 * The default implementation behaves as 15910 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 15911 * the case of no accessibility delegate been set. 15912 * </p> 15913 * 15914 * @return The provider. 15915 * 15916 * @see AccessibilityNodeProvider 15917 */ 15918 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 15919 return null; 15920 } 15921 } 15922} 15923