View.java revision f8ed444fad4c5bcb9c163ecb1303871c47e676d0
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.util.FloatProperty; 20import android.util.LocaleUtil; 21import android.util.Property; 22import com.android.internal.R; 23import com.android.internal.util.Predicate; 24import com.android.internal.view.menu.MenuBuilder; 25 26import android.content.ClipData; 27import android.content.Context; 28import android.content.res.Configuration; 29import android.content.res.Resources; 30import android.content.res.TypedArray; 31import android.graphics.Bitmap; 32import android.graphics.Camera; 33import android.graphics.Canvas; 34import android.graphics.Interpolator; 35import android.graphics.LinearGradient; 36import android.graphics.Matrix; 37import android.graphics.Paint; 38import android.graphics.PixelFormat; 39import android.graphics.Point; 40import android.graphics.PorterDuff; 41import android.graphics.PorterDuffXfermode; 42import android.graphics.Rect; 43import android.graphics.RectF; 44import android.graphics.Region; 45import android.graphics.Shader; 46import android.graphics.drawable.ColorDrawable; 47import android.graphics.drawable.Drawable; 48import android.os.Handler; 49import android.os.IBinder; 50import android.os.Message; 51import android.os.Parcel; 52import android.os.Parcelable; 53import android.os.RemoteException; 54import android.os.SystemClock; 55import android.util.AttributeSet; 56import android.util.Log; 57import android.util.Pool; 58import android.util.Poolable; 59import android.util.PoolableManager; 60import android.util.Pools; 61import android.util.SparseArray; 62import android.util.TypedValue; 63import android.view.ContextMenu.ContextMenuInfo; 64import android.view.accessibility.AccessibilityEvent; 65import android.view.accessibility.AccessibilityEventSource; 66import android.view.accessibility.AccessibilityManager; 67import android.view.accessibility.AccessibilityNodeInfo; 68import android.view.animation.Animation; 69import android.view.animation.AnimationUtils; 70import android.view.inputmethod.EditorInfo; 71import android.view.inputmethod.InputConnection; 72import android.view.inputmethod.InputMethodManager; 73import android.widget.ScrollBarDrawable; 74 75import java.lang.ref.WeakReference; 76import java.lang.reflect.InvocationTargetException; 77import java.lang.reflect.Method; 78import java.util.ArrayList; 79import java.util.Arrays; 80import java.util.Locale; 81import java.util.WeakHashMap; 82import java.util.concurrent.CopyOnWriteArrayList; 83 84/** 85 * <p> 86 * This class represents the basic building block for user interface components. A View 87 * occupies a rectangular area on the screen and is responsible for drawing and 88 * event handling. View is the base class for <em>widgets</em>, which are 89 * used to create interactive UI components (buttons, text fields, etc.). The 90 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 91 * are invisible containers that hold other Views (or other ViewGroups) and define 92 * their layout properties. 93 * </p> 94 * 95 * <div class="special"> 96 * <p>For an introduction to using this class to develop your 97 * application's user interface, read the Developer Guide documentation on 98 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics 99 * include: 100 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a> 101 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a> 102 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a> 103 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a> 104 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a> 105 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a> 106 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a> 107 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>. 108 * </p> 109 * </div> 110 * 111 * <a name="Using"></a> 112 * <h3>Using Views</h3> 113 * <p> 114 * All of the views in a window are arranged in a single tree. You can add views 115 * either from code or by specifying a tree of views in one or more XML layout 116 * files. There are many specialized subclasses of views that act as controls or 117 * are capable of displaying text, images, or other content. 118 * </p> 119 * <p> 120 * Once you have created a tree of views, there are typically a few types of 121 * common operations you may wish to perform: 122 * <ul> 123 * <li><strong>Set properties:</strong> for example setting the text of a 124 * {@link android.widget.TextView}. The available properties and the methods 125 * that set them will vary among the different subclasses of views. Note that 126 * properties that are known at build time can be set in the XML layout 127 * files.</li> 128 * <li><strong>Set focus:</strong> The framework will handled moving focus in 129 * response to user input. To force focus to a specific view, call 130 * {@link #requestFocus}.</li> 131 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 132 * that will be notified when something interesting happens to the view. For 133 * example, all views will let you set a listener to be notified when the view 134 * gains or loses focus. You can register such a listener using 135 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 136 * Other view subclasses offer more specialized listeners. For example, a Button 137 * exposes a listener to notify clients when the button is clicked.</li> 138 * <li><strong>Set visibility:</strong> You can hide or show views using 139 * {@link #setVisibility(int)}.</li> 140 * </ul> 141 * </p> 142 * <p><em> 143 * Note: The Android framework is responsible for measuring, laying out and 144 * drawing views. You should not call methods that perform these actions on 145 * views yourself unless you are actually implementing a 146 * {@link android.view.ViewGroup}. 147 * </em></p> 148 * 149 * <a name="Lifecycle"></a> 150 * <h3>Implementing a Custom View</h3> 151 * 152 * <p> 153 * To implement a custom view, you will usually begin by providing overrides for 154 * some of the standard methods that the framework calls on all views. You do 155 * not need to override all of these methods. In fact, you can start by just 156 * overriding {@link #onDraw(android.graphics.Canvas)}. 157 * <table border="2" width="85%" align="center" cellpadding="5"> 158 * <thead> 159 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 160 * </thead> 161 * 162 * <tbody> 163 * <tr> 164 * <td rowspan="2">Creation</td> 165 * <td>Constructors</td> 166 * <td>There is a form of the constructor that are called when the view 167 * is created from code and a form that is called when the view is 168 * inflated from a layout file. The second form should parse and apply 169 * any attributes defined in the layout file. 170 * </td> 171 * </tr> 172 * <tr> 173 * <td><code>{@link #onFinishInflate()}</code></td> 174 * <td>Called after a view and all of its children has been inflated 175 * from XML.</td> 176 * </tr> 177 * 178 * <tr> 179 * <td rowspan="3">Layout</td> 180 * <td><code>{@link #onMeasure(int, int)}</code></td> 181 * <td>Called to determine the size requirements for this view and all 182 * of its children. 183 * </td> 184 * </tr> 185 * <tr> 186 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 187 * <td>Called when this view should assign a size and position to all 188 * of its children. 189 * </td> 190 * </tr> 191 * <tr> 192 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 193 * <td>Called when the size of this view has changed. 194 * </td> 195 * </tr> 196 * 197 * <tr> 198 * <td>Drawing</td> 199 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 200 * <td>Called when the view should render its content. 201 * </td> 202 * </tr> 203 * 204 * <tr> 205 * <td rowspan="4">Event processing</td> 206 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 207 * <td>Called when a new key event occurs. 208 * </td> 209 * </tr> 210 * <tr> 211 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 212 * <td>Called when a key up event occurs. 213 * </td> 214 * </tr> 215 * <tr> 216 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 217 * <td>Called when a trackball motion event occurs. 218 * </td> 219 * </tr> 220 * <tr> 221 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 222 * <td>Called when a touch screen motion event occurs. 223 * </td> 224 * </tr> 225 * 226 * <tr> 227 * <td rowspan="2">Focus</td> 228 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 229 * <td>Called when the view gains or loses focus. 230 * </td> 231 * </tr> 232 * 233 * <tr> 234 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 235 * <td>Called when the window containing the view gains or loses focus. 236 * </td> 237 * </tr> 238 * 239 * <tr> 240 * <td rowspan="3">Attaching</td> 241 * <td><code>{@link #onAttachedToWindow()}</code></td> 242 * <td>Called when the view is attached to a window. 243 * </td> 244 * </tr> 245 * 246 * <tr> 247 * <td><code>{@link #onDetachedFromWindow}</code></td> 248 * <td>Called when the view is detached from its window. 249 * </td> 250 * </tr> 251 * 252 * <tr> 253 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 254 * <td>Called when the visibility of the window containing the view 255 * has changed. 256 * </td> 257 * </tr> 258 * </tbody> 259 * 260 * </table> 261 * </p> 262 * 263 * <a name="IDs"></a> 264 * <h3>IDs</h3> 265 * Views may have an integer id associated with them. These ids are typically 266 * assigned in the layout XML files, and are used to find specific views within 267 * the view tree. A common pattern is to: 268 * <ul> 269 * <li>Define a Button in the layout file and assign it a unique ID. 270 * <pre> 271 * <Button 272 * android:id="@+id/my_button" 273 * android:layout_width="wrap_content" 274 * android:layout_height="wrap_content" 275 * android:text="@string/my_button_text"/> 276 * </pre></li> 277 * <li>From the onCreate method of an Activity, find the Button 278 * <pre class="prettyprint"> 279 * Button myButton = (Button) findViewById(R.id.my_button); 280 * </pre></li> 281 * </ul> 282 * <p> 283 * View IDs need not be unique throughout the tree, but it is good practice to 284 * ensure that they are at least unique within the part of the tree you are 285 * searching. 286 * </p> 287 * 288 * <a name="Position"></a> 289 * <h3>Position</h3> 290 * <p> 291 * The geometry of a view is that of a rectangle. A view has a location, 292 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 293 * two dimensions, expressed as a width and a height. The unit for location 294 * and dimensions is the pixel. 295 * </p> 296 * 297 * <p> 298 * It is possible to retrieve the location of a view by invoking the methods 299 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 300 * coordinate of the rectangle representing the view. The latter returns the 301 * top, or Y, coordinate of the rectangle representing the view. These methods 302 * both return the location of the view relative to its parent. For instance, 303 * when getLeft() returns 20, that means the view is located 20 pixels to the 304 * right of the left edge of its direct parent. 305 * </p> 306 * 307 * <p> 308 * In addition, several convenience methods are offered to avoid unnecessary 309 * computations, namely {@link #getRight()} and {@link #getBottom()}. 310 * These methods return the coordinates of the right and bottom edges of the 311 * rectangle representing the view. For instance, calling {@link #getRight()} 312 * is similar to the following computation: <code>getLeft() + getWidth()</code> 313 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 314 * </p> 315 * 316 * <a name="SizePaddingMargins"></a> 317 * <h3>Size, padding and margins</h3> 318 * <p> 319 * The size of a view is expressed with a width and a height. A view actually 320 * possess two pairs of width and height values. 321 * </p> 322 * 323 * <p> 324 * The first pair is known as <em>measured width</em> and 325 * <em>measured height</em>. These dimensions define how big a view wants to be 326 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 327 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 328 * and {@link #getMeasuredHeight()}. 329 * </p> 330 * 331 * <p> 332 * The second pair is simply known as <em>width</em> and <em>height</em>, or 333 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 334 * dimensions define the actual size of the view on screen, at drawing time and 335 * after layout. These values may, but do not have to, be different from the 336 * measured width and height. The width and height can be obtained by calling 337 * {@link #getWidth()} and {@link #getHeight()}. 338 * </p> 339 * 340 * <p> 341 * To measure its dimensions, a view takes into account its padding. The padding 342 * is expressed in pixels for the left, top, right and bottom parts of the view. 343 * Padding can be used to offset the content of the view by a specific amount of 344 * pixels. For instance, a left padding of 2 will push the view's content by 345 * 2 pixels to the right of the left edge. Padding can be set using the 346 * {@link #setPadding(int, int, int, int)} method and queried by calling 347 * {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 348 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}. 349 * </p> 350 * 351 * <p> 352 * Even though a view can define a padding, it does not provide any support for 353 * margins. However, view groups provide such a support. Refer to 354 * {@link android.view.ViewGroup} and 355 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 356 * </p> 357 * 358 * <a name="Layout"></a> 359 * <h3>Layout</h3> 360 * <p> 361 * Layout is a two pass process: a measure pass and a layout pass. The measuring 362 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 363 * of the view tree. Each view pushes dimension specifications down the tree 364 * during the recursion. At the end of the measure pass, every view has stored 365 * its measurements. The second pass happens in 366 * {@link #layout(int,int,int,int)} and is also top-down. During 367 * this pass each parent is responsible for positioning all of its children 368 * using the sizes computed in the measure pass. 369 * </p> 370 * 371 * <p> 372 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 373 * {@link #getMeasuredHeight()} values must be set, along with those for all of 374 * that view's descendants. A view's measured width and measured height values 375 * must respect the constraints imposed by the view's parents. This guarantees 376 * that at the end of the measure pass, all parents accept all of their 377 * children's measurements. A parent view may call measure() more than once on 378 * its children. For example, the parent may measure each child once with 379 * unspecified dimensions to find out how big they want to be, then call 380 * measure() on them again with actual numbers if the sum of all the children's 381 * unconstrained sizes is too big or too small. 382 * </p> 383 * 384 * <p> 385 * The measure pass uses two classes to communicate dimensions. The 386 * {@link MeasureSpec} class is used by views to tell their parents how they 387 * want to be measured and positioned. The base LayoutParams class just 388 * describes how big the view wants to be for both width and height. For each 389 * dimension, it can specify one of: 390 * <ul> 391 * <li> an exact number 392 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 393 * (minus padding) 394 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 395 * enclose its content (plus padding). 396 * </ul> 397 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 398 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 399 * an X and Y value. 400 * </p> 401 * 402 * <p> 403 * MeasureSpecs are used to push requirements down the tree from parent to 404 * child. A MeasureSpec can be in one of three modes: 405 * <ul> 406 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 407 * of a child view. For example, a LinearLayout may call measure() on its child 408 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 409 * tall the child view wants to be given a width of 240 pixels. 410 * <li>EXACTLY: This is used by the parent to impose an exact size on the 411 * child. The child must use this size, and guarantee that all of its 412 * descendants will fit within this size. 413 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 414 * child. The child must gurantee that it and all of its descendants will fit 415 * within this size. 416 * </ul> 417 * </p> 418 * 419 * <p> 420 * To intiate a layout, call {@link #requestLayout}. This method is typically 421 * called by a view on itself when it believes that is can no longer fit within 422 * its current bounds. 423 * </p> 424 * 425 * <a name="Drawing"></a> 426 * <h3>Drawing</h3> 427 * <p> 428 * Drawing is handled by walking the tree and rendering each view that 429 * intersects the the invalid region. Because the tree is traversed in-order, 430 * this means that parents will draw before (i.e., behind) their children, with 431 * siblings drawn in the order they appear in the tree. 432 * If you set a background drawable for a View, then the View will draw it for you 433 * before calling back to its <code>onDraw()</code> method. 434 * </p> 435 * 436 * <p> 437 * Note that the framework will not draw views that are not in the invalid region. 438 * </p> 439 * 440 * <p> 441 * To force a view to draw, call {@link #invalidate()}. 442 * </p> 443 * 444 * <a name="EventHandlingThreading"></a> 445 * <h3>Event Handling and Threading</h3> 446 * <p> 447 * The basic cycle of a view is as follows: 448 * <ol> 449 * <li>An event comes in and is dispatched to the appropriate view. The view 450 * handles the event and notifies any listeners.</li> 451 * <li>If in the course of processing the event, the view's bounds may need 452 * to be changed, the view will call {@link #requestLayout()}.</li> 453 * <li>Similarly, if in the course of processing the event the view's appearance 454 * may need to be changed, the view will call {@link #invalidate()}.</li> 455 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 456 * the framework will take care of measuring, laying out, and drawing the tree 457 * as appropriate.</li> 458 * </ol> 459 * </p> 460 * 461 * <p><em>Note: The entire view tree is single threaded. You must always be on 462 * the UI thread when calling any method on any view.</em> 463 * If you are doing work on other threads and want to update the state of a view 464 * from that thread, you should use a {@link Handler}. 465 * </p> 466 * 467 * <a name="FocusHandling"></a> 468 * <h3>Focus Handling</h3> 469 * <p> 470 * The framework will handle routine focus movement in response to user input. 471 * This includes changing the focus as views are removed or hidden, or as new 472 * views become available. Views indicate their willingness to take focus 473 * through the {@link #isFocusable} method. To change whether a view can take 474 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 475 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 476 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 477 * </p> 478 * <p> 479 * Focus movement is based on an algorithm which finds the nearest neighbor in a 480 * given direction. In rare cases, the default algorithm may not match the 481 * intended behavior of the developer. In these situations, you can provide 482 * explicit overrides by using these XML attributes in the layout file: 483 * <pre> 484 * nextFocusDown 485 * nextFocusLeft 486 * nextFocusRight 487 * nextFocusUp 488 * </pre> 489 * </p> 490 * 491 * 492 * <p> 493 * To get a particular view to take focus, call {@link #requestFocus()}. 494 * </p> 495 * 496 * <a name="TouchMode"></a> 497 * <h3>Touch Mode</h3> 498 * <p> 499 * When a user is navigating a user interface via directional keys such as a D-pad, it is 500 * necessary to give focus to actionable items such as buttons so the user can see 501 * what will take input. If the device has touch capabilities, however, and the user 502 * begins interacting with the interface by touching it, it is no longer necessary to 503 * always highlight, or give focus to, a particular view. This motivates a mode 504 * for interaction named 'touch mode'. 505 * </p> 506 * <p> 507 * For a touch capable device, once the user touches the screen, the device 508 * will enter touch mode. From this point onward, only views for which 509 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 510 * Other views that are touchable, like buttons, will not take focus when touched; they will 511 * only fire the on click listeners. 512 * </p> 513 * <p> 514 * Any time a user hits a directional key, such as a D-pad direction, the view device will 515 * exit touch mode, and find a view to take focus, so that the user may resume interacting 516 * with the user interface without touching the screen again. 517 * </p> 518 * <p> 519 * The touch mode state is maintained across {@link android.app.Activity}s. Call 520 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 521 * </p> 522 * 523 * <a name="Scrolling"></a> 524 * <h3>Scrolling</h3> 525 * <p> 526 * The framework provides basic support for views that wish to internally 527 * scroll their content. This includes keeping track of the X and Y scroll 528 * offset as well as mechanisms for drawing scrollbars. See 529 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 530 * {@link #awakenScrollBars()} for more details. 531 * </p> 532 * 533 * <a name="Tags"></a> 534 * <h3>Tags</h3> 535 * <p> 536 * Unlike IDs, tags are not used to identify views. Tags are essentially an 537 * extra piece of information that can be associated with a view. They are most 538 * often used as a convenience to store data related to views in the views 539 * themselves rather than by putting them in a separate structure. 540 * </p> 541 * 542 * <a name="Animation"></a> 543 * <h3>Animation</h3> 544 * <p> 545 * You can attach an {@link Animation} object to a view using 546 * {@link #setAnimation(Animation)} or 547 * {@link #startAnimation(Animation)}. The animation can alter the scale, 548 * rotation, translation and alpha of a view over time. If the animation is 549 * attached to a view that has children, the animation will affect the entire 550 * subtree rooted by that node. When an animation is started, the framework will 551 * take care of redrawing the appropriate views until the animation completes. 552 * </p> 553 * <p> 554 * Starting with Android 3.0, the preferred way of animating views is to use the 555 * {@link android.animation} package APIs. 556 * </p> 557 * 558 * <a name="Security"></a> 559 * <h3>Security</h3> 560 * <p> 561 * Sometimes it is essential that an application be able to verify that an action 562 * is being performed with the full knowledge and consent of the user, such as 563 * granting a permission request, making a purchase or clicking on an advertisement. 564 * Unfortunately, a malicious application could try to spoof the user into 565 * performing these actions, unaware, by concealing the intended purpose of the view. 566 * As a remedy, the framework offers a touch filtering mechanism that can be used to 567 * improve the security of views that provide access to sensitive functionality. 568 * </p><p> 569 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 570 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 571 * will discard touches that are received whenever the view's window is obscured by 572 * another visible window. As a result, the view will not receive touches whenever a 573 * toast, dialog or other window appears above the view's window. 574 * </p><p> 575 * For more fine-grained control over security, consider overriding the 576 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 577 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 578 * </p> 579 * 580 * @attr ref android.R.styleable#View_alpha 581 * @attr ref android.R.styleable#View_background 582 * @attr ref android.R.styleable#View_clickable 583 * @attr ref android.R.styleable#View_contentDescription 584 * @attr ref android.R.styleable#View_drawingCacheQuality 585 * @attr ref android.R.styleable#View_duplicateParentState 586 * @attr ref android.R.styleable#View_id 587 * @attr ref android.R.styleable#View_fadingEdge 588 * @attr ref android.R.styleable#View_fadingEdgeLength 589 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 590 * @attr ref android.R.styleable#View_fitsSystemWindows 591 * @attr ref android.R.styleable#View_isScrollContainer 592 * @attr ref android.R.styleable#View_focusable 593 * @attr ref android.R.styleable#View_focusableInTouchMode 594 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 595 * @attr ref android.R.styleable#View_keepScreenOn 596 * @attr ref android.R.styleable#View_layerType 597 * @attr ref android.R.styleable#View_longClickable 598 * @attr ref android.R.styleable#View_minHeight 599 * @attr ref android.R.styleable#View_minWidth 600 * @attr ref android.R.styleable#View_nextFocusDown 601 * @attr ref android.R.styleable#View_nextFocusLeft 602 * @attr ref android.R.styleable#View_nextFocusRight 603 * @attr ref android.R.styleable#View_nextFocusUp 604 * @attr ref android.R.styleable#View_onClick 605 * @attr ref android.R.styleable#View_padding 606 * @attr ref android.R.styleable#View_paddingBottom 607 * @attr ref android.R.styleable#View_paddingLeft 608 * @attr ref android.R.styleable#View_paddingRight 609 * @attr ref android.R.styleable#View_paddingTop 610 * @attr ref android.R.styleable#View_paddingStart 611 * @attr ref android.R.styleable#View_paddingEnd 612 * @attr ref android.R.styleable#View_saveEnabled 613 * @attr ref android.R.styleable#View_rotation 614 * @attr ref android.R.styleable#View_rotationX 615 * @attr ref android.R.styleable#View_rotationY 616 * @attr ref android.R.styleable#View_scaleX 617 * @attr ref android.R.styleable#View_scaleY 618 * @attr ref android.R.styleable#View_scrollX 619 * @attr ref android.R.styleable#View_scrollY 620 * @attr ref android.R.styleable#View_scrollbarSize 621 * @attr ref android.R.styleable#View_scrollbarStyle 622 * @attr ref android.R.styleable#View_scrollbars 623 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 624 * @attr ref android.R.styleable#View_scrollbarFadeDuration 625 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 626 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 627 * @attr ref android.R.styleable#View_scrollbarThumbVertical 628 * @attr ref android.R.styleable#View_scrollbarTrackVertical 629 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 630 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 631 * @attr ref android.R.styleable#View_soundEffectsEnabled 632 * @attr ref android.R.styleable#View_tag 633 * @attr ref android.R.styleable#View_transformPivotX 634 * @attr ref android.R.styleable#View_transformPivotY 635 * @attr ref android.R.styleable#View_translationX 636 * @attr ref android.R.styleable#View_translationY 637 * @attr ref android.R.styleable#View_visibility 638 * 639 * @see android.view.ViewGroup 640 */ 641public class View implements Drawable.Callback2, KeyEvent.Callback, AccessibilityEventSource { 642 private static final boolean DBG = false; 643 644 /** 645 * The logging tag used by this class with android.util.Log. 646 */ 647 protected static final String VIEW_LOG_TAG = "View"; 648 649 /** 650 * Used to mark a View that has no ID. 651 */ 652 public static final int NO_ID = -1; 653 654 /** 655 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 656 * calling setFlags. 657 */ 658 private static final int NOT_FOCUSABLE = 0x00000000; 659 660 /** 661 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 662 * setFlags. 663 */ 664 private static final int FOCUSABLE = 0x00000001; 665 666 /** 667 * Mask for use with setFlags indicating bits used for focus. 668 */ 669 private static final int FOCUSABLE_MASK = 0x00000001; 670 671 /** 672 * This view will adjust its padding to fit sytem windows (e.g. status bar) 673 */ 674 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 675 676 /** 677 * This view is visible. Use with {@link #setVisibility(int)}. 678 */ 679 public static final int VISIBLE = 0x00000000; 680 681 /** 682 * This view is invisible, but it still takes up space for layout purposes. 683 * Use with {@link #setVisibility(int)}. 684 */ 685 public static final int INVISIBLE = 0x00000004; 686 687 /** 688 * This view is invisible, and it doesn't take any space for layout 689 * purposes. Use with {@link #setVisibility(int)}. 690 */ 691 public static final int GONE = 0x00000008; 692 693 /** 694 * Mask for use with setFlags indicating bits used for visibility. 695 * {@hide} 696 */ 697 static final int VISIBILITY_MASK = 0x0000000C; 698 699 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 700 701 /** 702 * This view is enabled. Intrepretation varies by subclass. 703 * Use with ENABLED_MASK when calling setFlags. 704 * {@hide} 705 */ 706 static final int ENABLED = 0x00000000; 707 708 /** 709 * This view is disabled. Intrepretation varies by subclass. 710 * Use with ENABLED_MASK when calling setFlags. 711 * {@hide} 712 */ 713 static final int DISABLED = 0x00000020; 714 715 /** 716 * Mask for use with setFlags indicating bits used for indicating whether 717 * this view is enabled 718 * {@hide} 719 */ 720 static final int ENABLED_MASK = 0x00000020; 721 722 /** 723 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 724 * called and further optimizations will be performed. It is okay to have 725 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 726 * {@hide} 727 */ 728 static final int WILL_NOT_DRAW = 0x00000080; 729 730 /** 731 * Mask for use with setFlags indicating bits used for indicating whether 732 * this view is will draw 733 * {@hide} 734 */ 735 static final int DRAW_MASK = 0x00000080; 736 737 /** 738 * <p>This view doesn't show scrollbars.</p> 739 * {@hide} 740 */ 741 static final int SCROLLBARS_NONE = 0x00000000; 742 743 /** 744 * <p>This view shows horizontal scrollbars.</p> 745 * {@hide} 746 */ 747 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 748 749 /** 750 * <p>This view shows vertical scrollbars.</p> 751 * {@hide} 752 */ 753 static final int SCROLLBARS_VERTICAL = 0x00000200; 754 755 /** 756 * <p>Mask for use with setFlags indicating bits used for indicating which 757 * scrollbars are enabled.</p> 758 * {@hide} 759 */ 760 static final int SCROLLBARS_MASK = 0x00000300; 761 762 /** 763 * Indicates that the view should filter touches when its window is obscured. 764 * Refer to the class comments for more information about this security feature. 765 * {@hide} 766 */ 767 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 768 769 // note flag value 0x00000800 is now available for next flags... 770 771 /** 772 * <p>This view doesn't show fading edges.</p> 773 * {@hide} 774 */ 775 static final int FADING_EDGE_NONE = 0x00000000; 776 777 /** 778 * <p>This view shows horizontal fading edges.</p> 779 * {@hide} 780 */ 781 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 782 783 /** 784 * <p>This view shows vertical fading edges.</p> 785 * {@hide} 786 */ 787 static final int FADING_EDGE_VERTICAL = 0x00002000; 788 789 /** 790 * <p>Mask for use with setFlags indicating bits used for indicating which 791 * fading edges are enabled.</p> 792 * {@hide} 793 */ 794 static final int FADING_EDGE_MASK = 0x00003000; 795 796 /** 797 * <p>Indicates this view can be clicked. When clickable, a View reacts 798 * to clicks by notifying the OnClickListener.<p> 799 * {@hide} 800 */ 801 static final int CLICKABLE = 0x00004000; 802 803 /** 804 * <p>Indicates this view is caching its drawing into a bitmap.</p> 805 * {@hide} 806 */ 807 static final int DRAWING_CACHE_ENABLED = 0x00008000; 808 809 /** 810 * <p>Indicates that no icicle should be saved for this view.<p> 811 * {@hide} 812 */ 813 static final int SAVE_DISABLED = 0x000010000; 814 815 /** 816 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 817 * property.</p> 818 * {@hide} 819 */ 820 static final int SAVE_DISABLED_MASK = 0x000010000; 821 822 /** 823 * <p>Indicates that no drawing cache should ever be created for this view.<p> 824 * {@hide} 825 */ 826 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 827 828 /** 829 * <p>Indicates this view can take / keep focus when int touch mode.</p> 830 * {@hide} 831 */ 832 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 833 834 /** 835 * <p>Enables low quality mode for the drawing cache.</p> 836 */ 837 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 838 839 /** 840 * <p>Enables high quality mode for the drawing cache.</p> 841 */ 842 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 843 844 /** 845 * <p>Enables automatic quality mode for the drawing cache.</p> 846 */ 847 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 848 849 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 850 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 851 }; 852 853 /** 854 * <p>Mask for use with setFlags indicating bits used for the cache 855 * quality property.</p> 856 * {@hide} 857 */ 858 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 859 860 /** 861 * <p> 862 * Indicates this view can be long clicked. When long clickable, a View 863 * reacts to long clicks by notifying the OnLongClickListener or showing a 864 * context menu. 865 * </p> 866 * {@hide} 867 */ 868 static final int LONG_CLICKABLE = 0x00200000; 869 870 /** 871 * <p>Indicates that this view gets its drawable states from its direct parent 872 * and ignores its original internal states.</p> 873 * 874 * @hide 875 */ 876 static final int DUPLICATE_PARENT_STATE = 0x00400000; 877 878 /** 879 * The scrollbar style to display the scrollbars inside the content area, 880 * without increasing the padding. The scrollbars will be overlaid with 881 * translucency on the view's content. 882 */ 883 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 884 885 /** 886 * The scrollbar style to display the scrollbars inside the padded area, 887 * increasing the padding of the view. The scrollbars will not overlap the 888 * content area of the view. 889 */ 890 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 891 892 /** 893 * The scrollbar style to display the scrollbars at the edge of the view, 894 * without increasing the padding. The scrollbars will be overlaid with 895 * translucency. 896 */ 897 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 898 899 /** 900 * The scrollbar style to display the scrollbars at the edge of the view, 901 * increasing the padding of the view. The scrollbars will only overlap the 902 * background, if any. 903 */ 904 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 905 906 /** 907 * Mask to check if the scrollbar style is overlay or inset. 908 * {@hide} 909 */ 910 static final int SCROLLBARS_INSET_MASK = 0x01000000; 911 912 /** 913 * Mask to check if the scrollbar style is inside or outside. 914 * {@hide} 915 */ 916 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 917 918 /** 919 * Mask for scrollbar style. 920 * {@hide} 921 */ 922 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 923 924 /** 925 * View flag indicating that the screen should remain on while the 926 * window containing this view is visible to the user. This effectively 927 * takes care of automatically setting the WindowManager's 928 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 929 */ 930 public static final int KEEP_SCREEN_ON = 0x04000000; 931 932 /** 933 * View flag indicating whether this view should have sound effects enabled 934 * for events such as clicking and touching. 935 */ 936 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 937 938 /** 939 * View flag indicating whether this view should have haptic feedback 940 * enabled for events such as long presses. 941 */ 942 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 943 944 /** 945 * <p>Indicates that the view hierarchy should stop saving state when 946 * it reaches this view. If state saving is initiated immediately at 947 * the view, it will be allowed. 948 * {@hide} 949 */ 950 static final int PARENT_SAVE_DISABLED = 0x20000000; 951 952 /** 953 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 954 * {@hide} 955 */ 956 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 957 958 /** 959 * Horizontal direction of this view is from Left to Right. 960 * Use with {@link #setLayoutDirection}. 961 * {@hide} 962 */ 963 public static final int LAYOUT_DIRECTION_LTR = 0x00000000; 964 965 /** 966 * Horizontal direction of this view is from Right to Left. 967 * Use with {@link #setLayoutDirection}. 968 * {@hide} 969 */ 970 public static final int LAYOUT_DIRECTION_RTL = 0x40000000; 971 972 /** 973 * Horizontal direction of this view is inherited from its parent. 974 * Use with {@link #setLayoutDirection}. 975 * {@hide} 976 */ 977 public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000; 978 979 /** 980 * Horizontal direction of this view is from deduced from the default language 981 * script for the locale. Use with {@link #setLayoutDirection}. 982 * {@hide} 983 */ 984 public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000; 985 986 /** 987 * Mask for use with setFlags indicating bits used for horizontalDirection. 988 * {@hide} 989 */ 990 static final int LAYOUT_DIRECTION_MASK = 0xC0000000; 991 992 /* 993 * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct 994 * flag value. 995 * {@hide} 996 */ 997 private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR, 998 LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE}; 999 1000 /** 1001 * Default horizontalDirection. 1002 * {@hide} 1003 */ 1004 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1005 1006 /** 1007 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1008 * should add all focusable Views regardless if they are focusable in touch mode. 1009 */ 1010 public static final int FOCUSABLES_ALL = 0x00000000; 1011 1012 /** 1013 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1014 * should add only Views focusable in touch mode. 1015 */ 1016 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1017 1018 /** 1019 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1020 * item. 1021 */ 1022 public static final int FOCUS_BACKWARD = 0x00000001; 1023 1024 /** 1025 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1026 * item. 1027 */ 1028 public static final int FOCUS_FORWARD = 0x00000002; 1029 1030 /** 1031 * Use with {@link #focusSearch(int)}. Move focus to the left. 1032 */ 1033 public static final int FOCUS_LEFT = 0x00000011; 1034 1035 /** 1036 * Use with {@link #focusSearch(int)}. Move focus up. 1037 */ 1038 public static final int FOCUS_UP = 0x00000021; 1039 1040 /** 1041 * Use with {@link #focusSearch(int)}. Move focus to the right. 1042 */ 1043 public static final int FOCUS_RIGHT = 0x00000042; 1044 1045 /** 1046 * Use with {@link #focusSearch(int)}. Move focus down. 1047 */ 1048 public static final int FOCUS_DOWN = 0x00000082; 1049 1050 /** 1051 * Bits of {@link #getMeasuredWidthAndState()} and 1052 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1053 */ 1054 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1055 1056 /** 1057 * Bits of {@link #getMeasuredWidthAndState()} and 1058 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1059 */ 1060 public static final int MEASURED_STATE_MASK = 0xff000000; 1061 1062 /** 1063 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1064 * for functions that combine both width and height into a single int, 1065 * such as {@link #getMeasuredState()} and the childState argument of 1066 * {@link #resolveSizeAndState(int, int, int)}. 1067 */ 1068 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1069 1070 /** 1071 * Bit of {@link #getMeasuredWidthAndState()} and 1072 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1073 * is smaller that the space the view would like to have. 1074 */ 1075 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1076 1077 /** 1078 * Base View state sets 1079 */ 1080 // Singles 1081 /** 1082 * Indicates the view has no states set. States are used with 1083 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1084 * view depending on its state. 1085 * 1086 * @see android.graphics.drawable.Drawable 1087 * @see #getDrawableState() 1088 */ 1089 protected static final int[] EMPTY_STATE_SET; 1090 /** 1091 * Indicates the view is enabled. States are used with 1092 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1093 * view depending on its state. 1094 * 1095 * @see android.graphics.drawable.Drawable 1096 * @see #getDrawableState() 1097 */ 1098 protected static final int[] ENABLED_STATE_SET; 1099 /** 1100 * Indicates the view is focused. States are used with 1101 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1102 * view depending on its state. 1103 * 1104 * @see android.graphics.drawable.Drawable 1105 * @see #getDrawableState() 1106 */ 1107 protected static final int[] FOCUSED_STATE_SET; 1108 /** 1109 * Indicates the view is selected. States are used with 1110 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1111 * view depending on its state. 1112 * 1113 * @see android.graphics.drawable.Drawable 1114 * @see #getDrawableState() 1115 */ 1116 protected static final int[] SELECTED_STATE_SET; 1117 /** 1118 * Indicates the view is pressed. States are used with 1119 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1120 * view depending on its state. 1121 * 1122 * @see android.graphics.drawable.Drawable 1123 * @see #getDrawableState() 1124 * @hide 1125 */ 1126 protected static final int[] PRESSED_STATE_SET; 1127 /** 1128 * Indicates the view's window has focus. States are used with 1129 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1130 * view depending on its state. 1131 * 1132 * @see android.graphics.drawable.Drawable 1133 * @see #getDrawableState() 1134 */ 1135 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1136 // Doubles 1137 /** 1138 * Indicates the view is enabled and has the focus. 1139 * 1140 * @see #ENABLED_STATE_SET 1141 * @see #FOCUSED_STATE_SET 1142 */ 1143 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1144 /** 1145 * Indicates the view is enabled and selected. 1146 * 1147 * @see #ENABLED_STATE_SET 1148 * @see #SELECTED_STATE_SET 1149 */ 1150 protected static final int[] ENABLED_SELECTED_STATE_SET; 1151 /** 1152 * Indicates the view is enabled and that its window has focus. 1153 * 1154 * @see #ENABLED_STATE_SET 1155 * @see #WINDOW_FOCUSED_STATE_SET 1156 */ 1157 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1158 /** 1159 * Indicates the view is focused and selected. 1160 * 1161 * @see #FOCUSED_STATE_SET 1162 * @see #SELECTED_STATE_SET 1163 */ 1164 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1165 /** 1166 * Indicates the view has the focus and that its window has the focus. 1167 * 1168 * @see #FOCUSED_STATE_SET 1169 * @see #WINDOW_FOCUSED_STATE_SET 1170 */ 1171 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1172 /** 1173 * Indicates the view is selected and that its window has the focus. 1174 * 1175 * @see #SELECTED_STATE_SET 1176 * @see #WINDOW_FOCUSED_STATE_SET 1177 */ 1178 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1179 // Triples 1180 /** 1181 * Indicates the view is enabled, focused and selected. 1182 * 1183 * @see #ENABLED_STATE_SET 1184 * @see #FOCUSED_STATE_SET 1185 * @see #SELECTED_STATE_SET 1186 */ 1187 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1188 /** 1189 * Indicates the view is enabled, focused and its window has the focus. 1190 * 1191 * @see #ENABLED_STATE_SET 1192 * @see #FOCUSED_STATE_SET 1193 * @see #WINDOW_FOCUSED_STATE_SET 1194 */ 1195 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1196 /** 1197 * Indicates the view is enabled, selected and its window has the focus. 1198 * 1199 * @see #ENABLED_STATE_SET 1200 * @see #SELECTED_STATE_SET 1201 * @see #WINDOW_FOCUSED_STATE_SET 1202 */ 1203 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1204 /** 1205 * Indicates the view is focused, selected and its window has the focus. 1206 * 1207 * @see #FOCUSED_STATE_SET 1208 * @see #SELECTED_STATE_SET 1209 * @see #WINDOW_FOCUSED_STATE_SET 1210 */ 1211 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1212 /** 1213 * Indicates the view is enabled, focused, selected and its window 1214 * has the focus. 1215 * 1216 * @see #ENABLED_STATE_SET 1217 * @see #FOCUSED_STATE_SET 1218 * @see #SELECTED_STATE_SET 1219 * @see #WINDOW_FOCUSED_STATE_SET 1220 */ 1221 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1222 /** 1223 * Indicates the view is pressed and its window has the focus. 1224 * 1225 * @see #PRESSED_STATE_SET 1226 * @see #WINDOW_FOCUSED_STATE_SET 1227 */ 1228 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1229 /** 1230 * Indicates the view is pressed and selected. 1231 * 1232 * @see #PRESSED_STATE_SET 1233 * @see #SELECTED_STATE_SET 1234 */ 1235 protected static final int[] PRESSED_SELECTED_STATE_SET; 1236 /** 1237 * Indicates the view is pressed, selected and its window has the focus. 1238 * 1239 * @see #PRESSED_STATE_SET 1240 * @see #SELECTED_STATE_SET 1241 * @see #WINDOW_FOCUSED_STATE_SET 1242 */ 1243 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1244 /** 1245 * Indicates the view is pressed and focused. 1246 * 1247 * @see #PRESSED_STATE_SET 1248 * @see #FOCUSED_STATE_SET 1249 */ 1250 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1251 /** 1252 * Indicates the view is pressed, focused and its window has the focus. 1253 * 1254 * @see #PRESSED_STATE_SET 1255 * @see #FOCUSED_STATE_SET 1256 * @see #WINDOW_FOCUSED_STATE_SET 1257 */ 1258 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1259 /** 1260 * Indicates the view is pressed, focused and selected. 1261 * 1262 * @see #PRESSED_STATE_SET 1263 * @see #SELECTED_STATE_SET 1264 * @see #FOCUSED_STATE_SET 1265 */ 1266 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1267 /** 1268 * Indicates the view is pressed, focused, selected and its window has the focus. 1269 * 1270 * @see #PRESSED_STATE_SET 1271 * @see #FOCUSED_STATE_SET 1272 * @see #SELECTED_STATE_SET 1273 * @see #WINDOW_FOCUSED_STATE_SET 1274 */ 1275 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1276 /** 1277 * Indicates the view is pressed and enabled. 1278 * 1279 * @see #PRESSED_STATE_SET 1280 * @see #ENABLED_STATE_SET 1281 */ 1282 protected static final int[] PRESSED_ENABLED_STATE_SET; 1283 /** 1284 * Indicates the view is pressed, enabled and its window has the focus. 1285 * 1286 * @see #PRESSED_STATE_SET 1287 * @see #ENABLED_STATE_SET 1288 * @see #WINDOW_FOCUSED_STATE_SET 1289 */ 1290 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1291 /** 1292 * Indicates the view is pressed, enabled and selected. 1293 * 1294 * @see #PRESSED_STATE_SET 1295 * @see #ENABLED_STATE_SET 1296 * @see #SELECTED_STATE_SET 1297 */ 1298 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1299 /** 1300 * Indicates the view is pressed, enabled, selected and its window has the 1301 * focus. 1302 * 1303 * @see #PRESSED_STATE_SET 1304 * @see #ENABLED_STATE_SET 1305 * @see #SELECTED_STATE_SET 1306 * @see #WINDOW_FOCUSED_STATE_SET 1307 */ 1308 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1309 /** 1310 * Indicates the view is pressed, enabled and focused. 1311 * 1312 * @see #PRESSED_STATE_SET 1313 * @see #ENABLED_STATE_SET 1314 * @see #FOCUSED_STATE_SET 1315 */ 1316 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1317 /** 1318 * Indicates the view is pressed, enabled, focused and its window has the 1319 * focus. 1320 * 1321 * @see #PRESSED_STATE_SET 1322 * @see #ENABLED_STATE_SET 1323 * @see #FOCUSED_STATE_SET 1324 * @see #WINDOW_FOCUSED_STATE_SET 1325 */ 1326 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1327 /** 1328 * Indicates the view is pressed, enabled, focused and selected. 1329 * 1330 * @see #PRESSED_STATE_SET 1331 * @see #ENABLED_STATE_SET 1332 * @see #SELECTED_STATE_SET 1333 * @see #FOCUSED_STATE_SET 1334 */ 1335 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1336 /** 1337 * Indicates the view is pressed, enabled, focused, selected and its window 1338 * has the focus. 1339 * 1340 * @see #PRESSED_STATE_SET 1341 * @see #ENABLED_STATE_SET 1342 * @see #SELECTED_STATE_SET 1343 * @see #FOCUSED_STATE_SET 1344 * @see #WINDOW_FOCUSED_STATE_SET 1345 */ 1346 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1347 1348 /** 1349 * The order here is very important to {@link #getDrawableState()} 1350 */ 1351 private static final int[][] VIEW_STATE_SETS; 1352 1353 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1354 static final int VIEW_STATE_SELECTED = 1 << 1; 1355 static final int VIEW_STATE_FOCUSED = 1 << 2; 1356 static final int VIEW_STATE_ENABLED = 1 << 3; 1357 static final int VIEW_STATE_PRESSED = 1 << 4; 1358 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1359 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1360 static final int VIEW_STATE_HOVERED = 1 << 7; 1361 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1362 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1363 1364 static final int[] VIEW_STATE_IDS = new int[] { 1365 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1366 R.attr.state_selected, VIEW_STATE_SELECTED, 1367 R.attr.state_focused, VIEW_STATE_FOCUSED, 1368 R.attr.state_enabled, VIEW_STATE_ENABLED, 1369 R.attr.state_pressed, VIEW_STATE_PRESSED, 1370 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1371 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1372 R.attr.state_hovered, VIEW_STATE_HOVERED, 1373 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1374 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED, 1375 }; 1376 1377 static { 1378 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1379 throw new IllegalStateException( 1380 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1381 } 1382 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1383 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1384 int viewState = R.styleable.ViewDrawableStates[i]; 1385 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1386 if (VIEW_STATE_IDS[j] == viewState) { 1387 orderedIds[i * 2] = viewState; 1388 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1389 } 1390 } 1391 } 1392 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1393 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1394 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1395 int numBits = Integer.bitCount(i); 1396 int[] set = new int[numBits]; 1397 int pos = 0; 1398 for (int j = 0; j < orderedIds.length; j += 2) { 1399 if ((i & orderedIds[j+1]) != 0) { 1400 set[pos++] = orderedIds[j]; 1401 } 1402 } 1403 VIEW_STATE_SETS[i] = set; 1404 } 1405 1406 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1407 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1408 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1409 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1410 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1411 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1412 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1413 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1414 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1415 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1416 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1417 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1418 | VIEW_STATE_FOCUSED]; 1419 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1420 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1421 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1422 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1423 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1424 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1425 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1426 | VIEW_STATE_ENABLED]; 1427 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1428 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1429 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1430 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1431 | VIEW_STATE_ENABLED]; 1432 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1433 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1434 | VIEW_STATE_ENABLED]; 1435 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1436 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1437 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1438 1439 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1440 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1441 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1442 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1443 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1444 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1445 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1446 | VIEW_STATE_PRESSED]; 1447 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1448 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1449 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1450 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1451 | VIEW_STATE_PRESSED]; 1452 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1453 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1454 | VIEW_STATE_PRESSED]; 1455 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1456 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1457 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1458 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1459 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1460 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1461 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1462 | VIEW_STATE_PRESSED]; 1463 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1464 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1465 | VIEW_STATE_PRESSED]; 1466 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1467 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1468 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1469 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1470 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1471 | VIEW_STATE_PRESSED]; 1472 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1473 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1474 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1475 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1476 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1477 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1478 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1479 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1480 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1481 | VIEW_STATE_PRESSED]; 1482 } 1483 1484 /** 1485 * Temporary Rect currently for use in setBackground(). This will probably 1486 * be extended in the future to hold our own class with more than just 1487 * a Rect. :) 1488 */ 1489 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1490 1491 /** 1492 * Map used to store views' tags. 1493 */ 1494 private static WeakHashMap<View, SparseArray<Object>> sTags; 1495 1496 /** 1497 * Lock used to access sTags. 1498 */ 1499 private static final Object sTagsLock = new Object(); 1500 1501 /** 1502 * The next available accessiiblity id. 1503 */ 1504 private static int sNextAccessibilityViewId; 1505 1506 /** 1507 * The animation currently associated with this view. 1508 * @hide 1509 */ 1510 protected Animation mCurrentAnimation = null; 1511 1512 /** 1513 * Width as measured during measure pass. 1514 * {@hide} 1515 */ 1516 @ViewDebug.ExportedProperty(category = "measurement") 1517 int mMeasuredWidth; 1518 1519 /** 1520 * Height as measured during measure pass. 1521 * {@hide} 1522 */ 1523 @ViewDebug.ExportedProperty(category = "measurement") 1524 int mMeasuredHeight; 1525 1526 /** 1527 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1528 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1529 * its display list. This flag, used only when hw accelerated, allows us to clear the 1530 * flag while retaining this information until it's needed (at getDisplayList() time and 1531 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1532 * 1533 * {@hide} 1534 */ 1535 boolean mRecreateDisplayList = false; 1536 1537 /** 1538 * The view's identifier. 1539 * {@hide} 1540 * 1541 * @see #setId(int) 1542 * @see #getId() 1543 */ 1544 @ViewDebug.ExportedProperty(resolveId = true) 1545 int mID = NO_ID; 1546 1547 /** 1548 * The stable ID of this view for accessibility porposes. 1549 */ 1550 int mAccessibilityViewId = NO_ID; 1551 1552 /** 1553 * The view's tag. 1554 * {@hide} 1555 * 1556 * @see #setTag(Object) 1557 * @see #getTag() 1558 */ 1559 protected Object mTag; 1560 1561 // for mPrivateFlags: 1562 /** {@hide} */ 1563 static final int WANTS_FOCUS = 0x00000001; 1564 /** {@hide} */ 1565 static final int FOCUSED = 0x00000002; 1566 /** {@hide} */ 1567 static final int SELECTED = 0x00000004; 1568 /** {@hide} */ 1569 static final int IS_ROOT_NAMESPACE = 0x00000008; 1570 /** {@hide} */ 1571 static final int HAS_BOUNDS = 0x00000010; 1572 /** {@hide} */ 1573 static final int DRAWN = 0x00000020; 1574 /** 1575 * When this flag is set, this view is running an animation on behalf of its 1576 * children and should therefore not cancel invalidate requests, even if they 1577 * lie outside of this view's bounds. 1578 * 1579 * {@hide} 1580 */ 1581 static final int DRAW_ANIMATION = 0x00000040; 1582 /** {@hide} */ 1583 static final int SKIP_DRAW = 0x00000080; 1584 /** {@hide} */ 1585 static final int ONLY_DRAWS_BACKGROUND = 0x00000100; 1586 /** {@hide} */ 1587 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1588 /** {@hide} */ 1589 static final int DRAWABLE_STATE_DIRTY = 0x00000400; 1590 /** {@hide} */ 1591 static final int MEASURED_DIMENSION_SET = 0x00000800; 1592 /** {@hide} */ 1593 static final int FORCE_LAYOUT = 0x00001000; 1594 /** {@hide} */ 1595 static final int LAYOUT_REQUIRED = 0x00002000; 1596 1597 private static final int PRESSED = 0x00004000; 1598 1599 /** {@hide} */ 1600 static final int DRAWING_CACHE_VALID = 0x00008000; 1601 /** 1602 * Flag used to indicate that this view should be drawn once more (and only once 1603 * more) after its animation has completed. 1604 * {@hide} 1605 */ 1606 static final int ANIMATION_STARTED = 0x00010000; 1607 1608 private static final int SAVE_STATE_CALLED = 0x00020000; 1609 1610 /** 1611 * Indicates that the View returned true when onSetAlpha() was called and that 1612 * the alpha must be restored. 1613 * {@hide} 1614 */ 1615 static final int ALPHA_SET = 0x00040000; 1616 1617 /** 1618 * Set by {@link #setScrollContainer(boolean)}. 1619 */ 1620 static final int SCROLL_CONTAINER = 0x00080000; 1621 1622 /** 1623 * Set by {@link #setScrollContainer(boolean)}. 1624 */ 1625 static final int SCROLL_CONTAINER_ADDED = 0x00100000; 1626 1627 /** 1628 * View flag indicating whether this view was invalidated (fully or partially.) 1629 * 1630 * @hide 1631 */ 1632 static final int DIRTY = 0x00200000; 1633 1634 /** 1635 * View flag indicating whether this view was invalidated by an opaque 1636 * invalidate request. 1637 * 1638 * @hide 1639 */ 1640 static final int DIRTY_OPAQUE = 0x00400000; 1641 1642 /** 1643 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}. 1644 * 1645 * @hide 1646 */ 1647 static final int DIRTY_MASK = 0x00600000; 1648 1649 /** 1650 * Indicates whether the background is opaque. 1651 * 1652 * @hide 1653 */ 1654 static final int OPAQUE_BACKGROUND = 0x00800000; 1655 1656 /** 1657 * Indicates whether the scrollbars are opaque. 1658 * 1659 * @hide 1660 */ 1661 static final int OPAQUE_SCROLLBARS = 0x01000000; 1662 1663 /** 1664 * Indicates whether the view is opaque. 1665 * 1666 * @hide 1667 */ 1668 static final int OPAQUE_MASK = 0x01800000; 1669 1670 /** 1671 * Indicates a prepressed state; 1672 * the short time between ACTION_DOWN and recognizing 1673 * a 'real' press. Prepressed is used to recognize quick taps 1674 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1675 * 1676 * @hide 1677 */ 1678 private static final int PREPRESSED = 0x02000000; 1679 1680 /** 1681 * Indicates whether the view is temporarily detached. 1682 * 1683 * @hide 1684 */ 1685 static final int CANCEL_NEXT_UP_EVENT = 0x04000000; 1686 1687 /** 1688 * Indicates that we should awaken scroll bars once attached 1689 * 1690 * @hide 1691 */ 1692 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1693 1694 /** 1695 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1696 * @hide 1697 */ 1698 private static final int HOVERED = 0x10000000; 1699 1700 /** 1701 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1702 * for transform operations 1703 * 1704 * @hide 1705 */ 1706 private static final int PIVOT_EXPLICITLY_SET = 0x20000000; 1707 1708 /** {@hide} */ 1709 static final int ACTIVATED = 0x40000000; 1710 1711 /** 1712 * Indicates that this view was specifically invalidated, not just dirtied because some 1713 * child view was invalidated. The flag is used to determine when we need to recreate 1714 * a view's display list (as opposed to just returning a reference to its existing 1715 * display list). 1716 * 1717 * @hide 1718 */ 1719 static final int INVALIDATED = 0x80000000; 1720 1721 /* Masks for mPrivateFlags2 */ 1722 1723 /** 1724 * Indicates that this view has reported that it can accept the current drag's content. 1725 * Cleared when the drag operation concludes. 1726 * @hide 1727 */ 1728 static final int DRAG_CAN_ACCEPT = 0x00000001; 1729 1730 /** 1731 * Indicates that this view is currently directly under the drag location in a 1732 * drag-and-drop operation involving content that it can accept. Cleared when 1733 * the drag exits the view, or when the drag operation concludes. 1734 * @hide 1735 */ 1736 static final int DRAG_HOVERED = 0x00000002; 1737 1738 /** 1739 * Indicates whether the view layout direction has been resolved and drawn to the 1740 * right-to-left direction. 1741 * 1742 * @hide 1743 */ 1744 static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004; 1745 1746 /** 1747 * Indicates whether the view layout direction has been resolved. 1748 * 1749 * @hide 1750 */ 1751 static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008; 1752 1753 1754 /* End of masks for mPrivateFlags2 */ 1755 1756 static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED; 1757 1758 /** 1759 * Always allow a user to over-scroll this view, provided it is a 1760 * view that can scroll. 1761 * 1762 * @see #getOverScrollMode() 1763 * @see #setOverScrollMode(int) 1764 */ 1765 public static final int OVER_SCROLL_ALWAYS = 0; 1766 1767 /** 1768 * Allow a user to over-scroll this view only if the content is large 1769 * enough to meaningfully scroll, provided it is a view that can scroll. 1770 * 1771 * @see #getOverScrollMode() 1772 * @see #setOverScrollMode(int) 1773 */ 1774 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 1775 1776 /** 1777 * Never allow a user to over-scroll this view. 1778 * 1779 * @see #getOverScrollMode() 1780 * @see #setOverScrollMode(int) 1781 */ 1782 public static final int OVER_SCROLL_NEVER = 2; 1783 1784 /** 1785 * View has requested the status bar to be visible (the default). 1786 * 1787 * @see #setSystemUiVisibility(int) 1788 */ 1789 public static final int STATUS_BAR_VISIBLE = 0; 1790 1791 /** 1792 * View has requested the status bar to be hidden. 1793 * 1794 * @see #setSystemUiVisibility(int) 1795 */ 1796 public static final int STATUS_BAR_HIDDEN = 0x00000001; 1797 1798 /** 1799 * @hide 1800 * 1801 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1802 * out of the public fields to keep the undefined bits out of the developer's way. 1803 * 1804 * Flag to make the status bar not expandable. Unless you also 1805 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 1806 */ 1807 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 1808 1809 /** 1810 * @hide 1811 * 1812 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1813 * out of the public fields to keep the undefined bits out of the developer's way. 1814 * 1815 * Flag to hide notification icons and scrolling ticker text. 1816 */ 1817 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 1818 1819 /** 1820 * @hide 1821 * 1822 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1823 * out of the public fields to keep the undefined bits out of the developer's way. 1824 * 1825 * Flag to disable incoming notification alerts. This will not block 1826 * icons, but it will block sound, vibrating and other visual or aural notifications. 1827 */ 1828 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 1829 1830 /** 1831 * @hide 1832 * 1833 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1834 * out of the public fields to keep the undefined bits out of the developer's way. 1835 * 1836 * Flag to hide only the scrolling ticker. Note that 1837 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 1838 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 1839 */ 1840 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 1841 1842 /** 1843 * @hide 1844 * 1845 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1846 * out of the public fields to keep the undefined bits out of the developer's way. 1847 * 1848 * Flag to hide the center system info area. 1849 */ 1850 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 1851 1852 /** 1853 * @hide 1854 * 1855 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1856 * out of the public fields to keep the undefined bits out of the developer's way. 1857 * 1858 * Flag to hide only the navigation buttons. Don't use this 1859 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1860 * 1861 * THIS DOES NOT DISABLE THE BACK BUTTON 1862 */ 1863 public static final int STATUS_BAR_DISABLE_NAVIGATION = 0x00200000; 1864 1865 /** 1866 * @hide 1867 * 1868 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1869 * out of the public fields to keep the undefined bits out of the developer's way. 1870 * 1871 * Flag to hide only the back button. Don't use this 1872 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1873 */ 1874 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 1875 1876 /** 1877 * @hide 1878 * 1879 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1880 * out of the public fields to keep the undefined bits out of the developer's way. 1881 * 1882 * Flag to hide only the clock. You might use this if your activity has 1883 * its own clock making the status bar's clock redundant. 1884 */ 1885 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 1886 1887 /** 1888 * @hide 1889 */ 1890 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = STATUS_BAR_HIDDEN; 1891 1892 /** 1893 * Controls the over-scroll mode for this view. 1894 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 1895 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 1896 * and {@link #OVER_SCROLL_NEVER}. 1897 */ 1898 private int mOverScrollMode; 1899 1900 /** 1901 * The parent this view is attached to. 1902 * {@hide} 1903 * 1904 * @see #getParent() 1905 */ 1906 protected ViewParent mParent; 1907 1908 /** 1909 * {@hide} 1910 */ 1911 AttachInfo mAttachInfo; 1912 1913 /** 1914 * {@hide} 1915 */ 1916 @ViewDebug.ExportedProperty(flagMapping = { 1917 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT, 1918 name = "FORCE_LAYOUT"), 1919 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED, 1920 name = "LAYOUT_REQUIRED"), 1921 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID, 1922 name = "DRAWING_CACHE_INVALID", outputIf = false), 1923 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true), 1924 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false), 1925 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 1926 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY") 1927 }) 1928 int mPrivateFlags; 1929 int mPrivateFlags2; 1930 1931 /** 1932 * This view's request for the visibility of the status bar. 1933 * @hide 1934 */ 1935 @ViewDebug.ExportedProperty() 1936 int mSystemUiVisibility; 1937 1938 /** 1939 * Count of how many windows this view has been attached to. 1940 */ 1941 int mWindowAttachCount; 1942 1943 /** 1944 * The layout parameters associated with this view and used by the parent 1945 * {@link android.view.ViewGroup} to determine how this view should be 1946 * laid out. 1947 * {@hide} 1948 */ 1949 protected ViewGroup.LayoutParams mLayoutParams; 1950 1951 /** 1952 * The view flags hold various views states. 1953 * {@hide} 1954 */ 1955 @ViewDebug.ExportedProperty 1956 int mViewFlags; 1957 1958 /** 1959 * The transform matrix for the View. This transform is calculated internally 1960 * based on the rotation, scaleX, and scaleY properties. The identity matrix 1961 * is used by default. Do *not* use this variable directly; instead call 1962 * getMatrix(), which will automatically recalculate the matrix if necessary 1963 * to get the correct matrix based on the latest rotation and scale properties. 1964 */ 1965 private final Matrix mMatrix = new Matrix(); 1966 1967 /** 1968 * The transform matrix for the View. This transform is calculated internally 1969 * based on the rotation, scaleX, and scaleY properties. The identity matrix 1970 * is used by default. Do *not* use this variable directly; instead call 1971 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 1972 * to get the correct matrix based on the latest rotation and scale properties. 1973 */ 1974 private Matrix mInverseMatrix; 1975 1976 /** 1977 * An internal variable that tracks whether we need to recalculate the 1978 * transform matrix, based on whether the rotation or scaleX/Y properties 1979 * have changed since the matrix was last calculated. 1980 */ 1981 boolean mMatrixDirty = false; 1982 1983 /** 1984 * An internal variable that tracks whether we need to recalculate the 1985 * transform matrix, based on whether the rotation or scaleX/Y properties 1986 * have changed since the matrix was last calculated. 1987 */ 1988 private boolean mInverseMatrixDirty = true; 1989 1990 /** 1991 * A variable that tracks whether we need to recalculate the 1992 * transform matrix, based on whether the rotation or scaleX/Y properties 1993 * have changed since the matrix was last calculated. This variable 1994 * is only valid after a call to updateMatrix() or to a function that 1995 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 1996 */ 1997 private boolean mMatrixIsIdentity = true; 1998 1999 /** 2000 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2001 */ 2002 private Camera mCamera = null; 2003 2004 /** 2005 * This matrix is used when computing the matrix for 3D rotations. 2006 */ 2007 private Matrix matrix3D = null; 2008 2009 /** 2010 * These prev values are used to recalculate a centered pivot point when necessary. The 2011 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2012 * set), so thes values are only used then as well. 2013 */ 2014 private int mPrevWidth = -1; 2015 private int mPrevHeight = -1; 2016 2017 private boolean mLastIsOpaque; 2018 2019 /** 2020 * Convenience value to check for float values that are close enough to zero to be considered 2021 * zero. 2022 */ 2023 private static final float NONZERO_EPSILON = .001f; 2024 2025 /** 2026 * The degrees rotation around the vertical axis through the pivot point. 2027 */ 2028 @ViewDebug.ExportedProperty 2029 float mRotationY = 0f; 2030 2031 /** 2032 * The degrees rotation around the horizontal axis through the pivot point. 2033 */ 2034 @ViewDebug.ExportedProperty 2035 float mRotationX = 0f; 2036 2037 /** 2038 * The degrees rotation around the pivot point. 2039 */ 2040 @ViewDebug.ExportedProperty 2041 float mRotation = 0f; 2042 2043 /** 2044 * The amount of translation of the object away from its left property (post-layout). 2045 */ 2046 @ViewDebug.ExportedProperty 2047 float mTranslationX = 0f; 2048 2049 /** 2050 * The amount of translation of the object away from its top property (post-layout). 2051 */ 2052 @ViewDebug.ExportedProperty 2053 float mTranslationY = 0f; 2054 2055 /** 2056 * The amount of scale in the x direction around the pivot point. A 2057 * value of 1 means no scaling is applied. 2058 */ 2059 @ViewDebug.ExportedProperty 2060 float mScaleX = 1f; 2061 2062 /** 2063 * The amount of scale in the y direction around the pivot point. A 2064 * value of 1 means no scaling is applied. 2065 */ 2066 @ViewDebug.ExportedProperty 2067 float mScaleY = 1f; 2068 2069 /** 2070 * The amount of scale in the x direction around the pivot point. A 2071 * value of 1 means no scaling is applied. 2072 */ 2073 @ViewDebug.ExportedProperty 2074 float mPivotX = 0f; 2075 2076 /** 2077 * The amount of scale in the y direction around the pivot point. A 2078 * value of 1 means no scaling is applied. 2079 */ 2080 @ViewDebug.ExportedProperty 2081 float mPivotY = 0f; 2082 2083 /** 2084 * The opacity of the View. This is a value from 0 to 1, where 0 means 2085 * completely transparent and 1 means completely opaque. 2086 */ 2087 @ViewDebug.ExportedProperty 2088 float mAlpha = 1f; 2089 2090 /** 2091 * The distance in pixels from the left edge of this view's parent 2092 * to the left edge of this view. 2093 * {@hide} 2094 */ 2095 @ViewDebug.ExportedProperty(category = "layout") 2096 protected int mLeft; 2097 /** 2098 * The distance in pixels from the left edge of this view's parent 2099 * to the right edge of this view. 2100 * {@hide} 2101 */ 2102 @ViewDebug.ExportedProperty(category = "layout") 2103 protected int mRight; 2104 /** 2105 * The distance in pixels from the top edge of this view's parent 2106 * to the top edge of this view. 2107 * {@hide} 2108 */ 2109 @ViewDebug.ExportedProperty(category = "layout") 2110 protected int mTop; 2111 /** 2112 * The distance in pixels from the top edge of this view's parent 2113 * to the bottom edge of this view. 2114 * {@hide} 2115 */ 2116 @ViewDebug.ExportedProperty(category = "layout") 2117 protected int mBottom; 2118 2119 /** 2120 * The offset, in pixels, by which the content of this view is scrolled 2121 * horizontally. 2122 * {@hide} 2123 */ 2124 @ViewDebug.ExportedProperty(category = "scrolling") 2125 protected int mScrollX; 2126 /** 2127 * The offset, in pixels, by which the content of this view is scrolled 2128 * vertically. 2129 * {@hide} 2130 */ 2131 @ViewDebug.ExportedProperty(category = "scrolling") 2132 protected int mScrollY; 2133 2134 /** 2135 * The left padding in pixels, that is the distance in pixels between the 2136 * left edge of this view and the left edge of its content. 2137 * {@hide} 2138 */ 2139 @ViewDebug.ExportedProperty(category = "padding") 2140 protected int mPaddingLeft; 2141 /** 2142 * The right padding in pixels, that is the distance in pixels between the 2143 * right edge of this view and the right edge of its content. 2144 * {@hide} 2145 */ 2146 @ViewDebug.ExportedProperty(category = "padding") 2147 protected int mPaddingRight; 2148 /** 2149 * The top padding in pixels, that is the distance in pixels between the 2150 * top edge of this view and the top edge of its content. 2151 * {@hide} 2152 */ 2153 @ViewDebug.ExportedProperty(category = "padding") 2154 protected int mPaddingTop; 2155 /** 2156 * The bottom padding in pixels, that is the distance in pixels between the 2157 * bottom edge of this view and the bottom edge of its content. 2158 * {@hide} 2159 */ 2160 @ViewDebug.ExportedProperty(category = "padding") 2161 protected int mPaddingBottom; 2162 2163 /** 2164 * Briefly describes the view and is primarily used for accessibility support. 2165 */ 2166 private CharSequence mContentDescription; 2167 2168 /** 2169 * Cache the paddingRight set by the user to append to the scrollbar's size. 2170 */ 2171 @ViewDebug.ExportedProperty(category = "padding") 2172 int mUserPaddingRight; 2173 2174 /** 2175 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2176 */ 2177 @ViewDebug.ExportedProperty(category = "padding") 2178 int mUserPaddingBottom; 2179 2180 /** 2181 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2182 */ 2183 @ViewDebug.ExportedProperty(category = "padding") 2184 int mUserPaddingLeft; 2185 2186 /** 2187 * Cache if the user padding is relative. 2188 * 2189 */ 2190 @ViewDebug.ExportedProperty(category = "padding") 2191 boolean mUserPaddingRelative; 2192 2193 /** 2194 * Cache the paddingStart set by the user to append to the scrollbar's size. 2195 * 2196 */ 2197 @ViewDebug.ExportedProperty(category = "padding") 2198 int mUserPaddingStart; 2199 2200 /** 2201 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2202 * 2203 */ 2204 @ViewDebug.ExportedProperty(category = "padding") 2205 int mUserPaddingEnd; 2206 2207 /** 2208 * @hide 2209 */ 2210 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2211 /** 2212 * @hide 2213 */ 2214 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2215 2216 private Resources mResources = null; 2217 2218 private Drawable mBGDrawable; 2219 2220 private int mBackgroundResource; 2221 private boolean mBackgroundSizeChanged; 2222 2223 /** 2224 * Listener used to dispatch focus change events. 2225 * This field should be made private, so it is hidden from the SDK. 2226 * {@hide} 2227 */ 2228 protected OnFocusChangeListener mOnFocusChangeListener; 2229 2230 /** 2231 * Listeners for layout change events. 2232 */ 2233 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2234 2235 /** 2236 * Listeners for attach events. 2237 */ 2238 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2239 2240 /** 2241 * Listener used to dispatch click events. 2242 * This field should be made private, so it is hidden from the SDK. 2243 * {@hide} 2244 */ 2245 protected OnClickListener mOnClickListener; 2246 2247 /** 2248 * Listener used to dispatch long click events. 2249 * This field should be made private, so it is hidden from the SDK. 2250 * {@hide} 2251 */ 2252 protected OnLongClickListener mOnLongClickListener; 2253 2254 /** 2255 * Listener used to build the context menu. 2256 * This field should be made private, so it is hidden from the SDK. 2257 * {@hide} 2258 */ 2259 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2260 2261 private OnKeyListener mOnKeyListener; 2262 2263 private OnTouchListener mOnTouchListener; 2264 2265 private OnGenericMotionListener mOnGenericMotionListener; 2266 2267 private OnDragListener mOnDragListener; 2268 2269 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2270 2271 /** 2272 * The application environment this view lives in. 2273 * This field should be made private, so it is hidden from the SDK. 2274 * {@hide} 2275 */ 2276 protected Context mContext; 2277 2278 private ScrollabilityCache mScrollCache; 2279 2280 private int[] mDrawableState = null; 2281 2282 /** 2283 * Set to true when drawing cache is enabled and cannot be created. 2284 * 2285 * @hide 2286 */ 2287 public boolean mCachingFailed; 2288 2289 private Bitmap mDrawingCache; 2290 private Bitmap mUnscaledDrawingCache; 2291 private DisplayList mDisplayList; 2292 private HardwareLayer mHardwareLayer; 2293 2294 /** 2295 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2296 * the user may specify which view to go to next. 2297 */ 2298 private int mNextFocusLeftId = View.NO_ID; 2299 2300 /** 2301 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2302 * the user may specify which view to go to next. 2303 */ 2304 private int mNextFocusRightId = View.NO_ID; 2305 2306 /** 2307 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2308 * the user may specify which view to go to next. 2309 */ 2310 private int mNextFocusUpId = View.NO_ID; 2311 2312 /** 2313 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2314 * the user may specify which view to go to next. 2315 */ 2316 private int mNextFocusDownId = View.NO_ID; 2317 2318 /** 2319 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 2320 * the user may specify which view to go to next. 2321 */ 2322 int mNextFocusForwardId = View.NO_ID; 2323 2324 private CheckForLongPress mPendingCheckForLongPress; 2325 private CheckForTap mPendingCheckForTap = null; 2326 private PerformClick mPerformClick; 2327 2328 private UnsetPressedState mUnsetPressedState; 2329 2330 /** 2331 * Whether the long press's action has been invoked. The tap's action is invoked on the 2332 * up event while a long press is invoked as soon as the long press duration is reached, so 2333 * a long press could be performed before the tap is checked, in which case the tap's action 2334 * should not be invoked. 2335 */ 2336 private boolean mHasPerformedLongPress; 2337 2338 /** 2339 * The minimum height of the view. We'll try our best to have the height 2340 * of this view to at least this amount. 2341 */ 2342 @ViewDebug.ExportedProperty(category = "measurement") 2343 private int mMinHeight; 2344 2345 /** 2346 * The minimum width of the view. We'll try our best to have the width 2347 * of this view to at least this amount. 2348 */ 2349 @ViewDebug.ExportedProperty(category = "measurement") 2350 private int mMinWidth; 2351 2352 /** 2353 * The delegate to handle touch events that are physically in this view 2354 * but should be handled by another view. 2355 */ 2356 private TouchDelegate mTouchDelegate = null; 2357 2358 /** 2359 * Solid color to use as a background when creating the drawing cache. Enables 2360 * the cache to use 16 bit bitmaps instead of 32 bit. 2361 */ 2362 private int mDrawingCacheBackgroundColor = 0; 2363 2364 /** 2365 * Special tree observer used when mAttachInfo is null. 2366 */ 2367 private ViewTreeObserver mFloatingTreeObserver; 2368 2369 /** 2370 * Cache the touch slop from the context that created the view. 2371 */ 2372 private int mTouchSlop; 2373 2374 /** 2375 * Object that handles automatic animation of view properties. 2376 */ 2377 private ViewPropertyAnimator mAnimator = null; 2378 2379 /** 2380 * Flag indicating that a drag can cross window boundaries. When 2381 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 2382 * with this flag set, all visible applications will be able to participate 2383 * in the drag operation and receive the dragged content. 2384 * 2385 * @hide 2386 */ 2387 public static final int DRAG_FLAG_GLOBAL = 1; 2388 2389 /** 2390 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 2391 */ 2392 private float mVerticalScrollFactor; 2393 2394 /** 2395 * Position of the vertical scroll bar. 2396 */ 2397 private int mVerticalScrollbarPosition; 2398 2399 /** 2400 * Position the scroll bar at the default position as determined by the system. 2401 */ 2402 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 2403 2404 /** 2405 * Position the scroll bar along the left edge. 2406 */ 2407 public static final int SCROLLBAR_POSITION_LEFT = 1; 2408 2409 /** 2410 * Position the scroll bar along the right edge. 2411 */ 2412 public static final int SCROLLBAR_POSITION_RIGHT = 2; 2413 2414 /** 2415 * Indicates that the view does not have a layer. 2416 * 2417 * @see #getLayerType() 2418 * @see #setLayerType(int, android.graphics.Paint) 2419 * @see #LAYER_TYPE_SOFTWARE 2420 * @see #LAYER_TYPE_HARDWARE 2421 */ 2422 public static final int LAYER_TYPE_NONE = 0; 2423 2424 /** 2425 * <p>Indicates that the view has a software layer. A software layer is backed 2426 * by a bitmap and causes the view to be rendered using Android's software 2427 * rendering pipeline, even if hardware acceleration is enabled.</p> 2428 * 2429 * <p>Software layers have various usages:</p> 2430 * <p>When the application is not using hardware acceleration, a software layer 2431 * is useful to apply a specific color filter and/or blending mode and/or 2432 * translucency to a view and all its children.</p> 2433 * <p>When the application is using hardware acceleration, a software layer 2434 * is useful to render drawing primitives not supported by the hardware 2435 * accelerated pipeline. It can also be used to cache a complex view tree 2436 * into a texture and reduce the complexity of drawing operations. For instance, 2437 * when animating a complex view tree with a translation, a software layer can 2438 * be used to render the view tree only once.</p> 2439 * <p>Software layers should be avoided when the affected view tree updates 2440 * often. Every update will require to re-render the software layer, which can 2441 * potentially be slow (particularly when hardware acceleration is turned on 2442 * since the layer will have to be uploaded into a hardware texture after every 2443 * update.)</p> 2444 * 2445 * @see #getLayerType() 2446 * @see #setLayerType(int, android.graphics.Paint) 2447 * @see #LAYER_TYPE_NONE 2448 * @see #LAYER_TYPE_HARDWARE 2449 */ 2450 public static final int LAYER_TYPE_SOFTWARE = 1; 2451 2452 /** 2453 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 2454 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 2455 * OpenGL hardware) and causes the view to be rendered using Android's hardware 2456 * rendering pipeline, but only if hardware acceleration is turned on for the 2457 * view hierarchy. When hardware acceleration is turned off, hardware layers 2458 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 2459 * 2460 * <p>A hardware layer is useful to apply a specific color filter and/or 2461 * blending mode and/or translucency to a view and all its children.</p> 2462 * <p>A hardware layer can be used to cache a complex view tree into a 2463 * texture and reduce the complexity of drawing operations. For instance, 2464 * when animating a complex view tree with a translation, a hardware layer can 2465 * be used to render the view tree only once.</p> 2466 * <p>A hardware layer can also be used to increase the rendering quality when 2467 * rotation transformations are applied on a view. It can also be used to 2468 * prevent potential clipping issues when applying 3D transforms on a view.</p> 2469 * 2470 * @see #getLayerType() 2471 * @see #setLayerType(int, android.graphics.Paint) 2472 * @see #LAYER_TYPE_NONE 2473 * @see #LAYER_TYPE_SOFTWARE 2474 */ 2475 public static final int LAYER_TYPE_HARDWARE = 2; 2476 2477 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 2478 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 2479 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 2480 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 2481 }) 2482 int mLayerType = LAYER_TYPE_NONE; 2483 Paint mLayerPaint; 2484 Rect mLocalDirtyRect; 2485 2486 /** 2487 * Consistency verifier for debugging purposes. 2488 * @hide 2489 */ 2490 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 2491 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 2492 new InputEventConsistencyVerifier(this, 0) : null; 2493 2494 /** 2495 * Simple constructor to use when creating a view from code. 2496 * 2497 * @param context The Context the view is running in, through which it can 2498 * access the current theme, resources, etc. 2499 */ 2500 public View(Context context) { 2501 mContext = context; 2502 mResources = context != null ? context.getResources() : null; 2503 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT; 2504 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 2505 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 2506 } 2507 2508 /** 2509 * Constructor that is called when inflating a view from XML. This is called 2510 * when a view is being constructed from an XML file, supplying attributes 2511 * that were specified in the XML file. This version uses a default style of 2512 * 0, so the only attribute values applied are those in the Context's Theme 2513 * and the given AttributeSet. 2514 * 2515 * <p> 2516 * The method onFinishInflate() will be called after all children have been 2517 * added. 2518 * 2519 * @param context The Context the view is running in, through which it can 2520 * access the current theme, resources, etc. 2521 * @param attrs The attributes of the XML tag that is inflating the view. 2522 * @see #View(Context, AttributeSet, int) 2523 */ 2524 public View(Context context, AttributeSet attrs) { 2525 this(context, attrs, 0); 2526 } 2527 2528 /** 2529 * Perform inflation from XML and apply a class-specific base style. This 2530 * constructor of View allows subclasses to use their own base style when 2531 * they are inflating. For example, a Button class's constructor would call 2532 * this version of the super class constructor and supply 2533 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 2534 * the theme's button style to modify all of the base view attributes (in 2535 * particular its background) as well as the Button class's attributes. 2536 * 2537 * @param context The Context the view is running in, through which it can 2538 * access the current theme, resources, etc. 2539 * @param attrs The attributes of the XML tag that is inflating the view. 2540 * @param defStyle The default style to apply to this view. If 0, no style 2541 * will be applied (beyond what is included in the theme). This may 2542 * either be an attribute resource, whose value will be retrieved 2543 * from the current theme, or an explicit style resource. 2544 * @see #View(Context, AttributeSet) 2545 */ 2546 public View(Context context, AttributeSet attrs, int defStyle) { 2547 this(context); 2548 2549 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 2550 defStyle, 0); 2551 2552 Drawable background = null; 2553 2554 int leftPadding = -1; 2555 int topPadding = -1; 2556 int rightPadding = -1; 2557 int bottomPadding = -1; 2558 int startPadding = -1; 2559 int endPadding = -1; 2560 2561 int padding = -1; 2562 2563 int viewFlagValues = 0; 2564 int viewFlagMasks = 0; 2565 2566 boolean setScrollContainer = false; 2567 2568 int x = 0; 2569 int y = 0; 2570 2571 float tx = 0; 2572 float ty = 0; 2573 float rotation = 0; 2574 float rotationX = 0; 2575 float rotationY = 0; 2576 float sx = 1f; 2577 float sy = 1f; 2578 boolean transformSet = false; 2579 2580 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 2581 2582 int overScrollMode = mOverScrollMode; 2583 final int N = a.getIndexCount(); 2584 for (int i = 0; i < N; i++) { 2585 int attr = a.getIndex(i); 2586 switch (attr) { 2587 case com.android.internal.R.styleable.View_background: 2588 background = a.getDrawable(attr); 2589 break; 2590 case com.android.internal.R.styleable.View_padding: 2591 padding = a.getDimensionPixelSize(attr, -1); 2592 break; 2593 case com.android.internal.R.styleable.View_paddingLeft: 2594 leftPadding = a.getDimensionPixelSize(attr, -1); 2595 break; 2596 case com.android.internal.R.styleable.View_paddingTop: 2597 topPadding = a.getDimensionPixelSize(attr, -1); 2598 break; 2599 case com.android.internal.R.styleable.View_paddingRight: 2600 rightPadding = a.getDimensionPixelSize(attr, -1); 2601 break; 2602 case com.android.internal.R.styleable.View_paddingBottom: 2603 bottomPadding = a.getDimensionPixelSize(attr, -1); 2604 break; 2605 case com.android.internal.R.styleable.View_paddingStart: 2606 startPadding = a.getDimensionPixelSize(attr, -1); 2607 break; 2608 case com.android.internal.R.styleable.View_paddingEnd: 2609 endPadding = a.getDimensionPixelSize(attr, -1); 2610 break; 2611 case com.android.internal.R.styleable.View_scrollX: 2612 x = a.getDimensionPixelOffset(attr, 0); 2613 break; 2614 case com.android.internal.R.styleable.View_scrollY: 2615 y = a.getDimensionPixelOffset(attr, 0); 2616 break; 2617 case com.android.internal.R.styleable.View_alpha: 2618 setAlpha(a.getFloat(attr, 1f)); 2619 break; 2620 case com.android.internal.R.styleable.View_transformPivotX: 2621 setPivotX(a.getDimensionPixelOffset(attr, 0)); 2622 break; 2623 case com.android.internal.R.styleable.View_transformPivotY: 2624 setPivotY(a.getDimensionPixelOffset(attr, 0)); 2625 break; 2626 case com.android.internal.R.styleable.View_translationX: 2627 tx = a.getDimensionPixelOffset(attr, 0); 2628 transformSet = true; 2629 break; 2630 case com.android.internal.R.styleable.View_translationY: 2631 ty = a.getDimensionPixelOffset(attr, 0); 2632 transformSet = true; 2633 break; 2634 case com.android.internal.R.styleable.View_rotation: 2635 rotation = a.getFloat(attr, 0); 2636 transformSet = true; 2637 break; 2638 case com.android.internal.R.styleable.View_rotationX: 2639 rotationX = a.getFloat(attr, 0); 2640 transformSet = true; 2641 break; 2642 case com.android.internal.R.styleable.View_rotationY: 2643 rotationY = a.getFloat(attr, 0); 2644 transformSet = true; 2645 break; 2646 case com.android.internal.R.styleable.View_scaleX: 2647 sx = a.getFloat(attr, 1f); 2648 transformSet = true; 2649 break; 2650 case com.android.internal.R.styleable.View_scaleY: 2651 sy = a.getFloat(attr, 1f); 2652 transformSet = true; 2653 break; 2654 case com.android.internal.R.styleable.View_id: 2655 mID = a.getResourceId(attr, NO_ID); 2656 break; 2657 case com.android.internal.R.styleable.View_tag: 2658 mTag = a.getText(attr); 2659 break; 2660 case com.android.internal.R.styleable.View_fitsSystemWindows: 2661 if (a.getBoolean(attr, false)) { 2662 viewFlagValues |= FITS_SYSTEM_WINDOWS; 2663 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 2664 } 2665 break; 2666 case com.android.internal.R.styleable.View_focusable: 2667 if (a.getBoolean(attr, false)) { 2668 viewFlagValues |= FOCUSABLE; 2669 viewFlagMasks |= FOCUSABLE_MASK; 2670 } 2671 break; 2672 case com.android.internal.R.styleable.View_focusableInTouchMode: 2673 if (a.getBoolean(attr, false)) { 2674 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 2675 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 2676 } 2677 break; 2678 case com.android.internal.R.styleable.View_clickable: 2679 if (a.getBoolean(attr, false)) { 2680 viewFlagValues |= CLICKABLE; 2681 viewFlagMasks |= CLICKABLE; 2682 } 2683 break; 2684 case com.android.internal.R.styleable.View_longClickable: 2685 if (a.getBoolean(attr, false)) { 2686 viewFlagValues |= LONG_CLICKABLE; 2687 viewFlagMasks |= LONG_CLICKABLE; 2688 } 2689 break; 2690 case com.android.internal.R.styleable.View_saveEnabled: 2691 if (!a.getBoolean(attr, true)) { 2692 viewFlagValues |= SAVE_DISABLED; 2693 viewFlagMasks |= SAVE_DISABLED_MASK; 2694 } 2695 break; 2696 case com.android.internal.R.styleable.View_duplicateParentState: 2697 if (a.getBoolean(attr, false)) { 2698 viewFlagValues |= DUPLICATE_PARENT_STATE; 2699 viewFlagMasks |= DUPLICATE_PARENT_STATE; 2700 } 2701 break; 2702 case com.android.internal.R.styleable.View_visibility: 2703 final int visibility = a.getInt(attr, 0); 2704 if (visibility != 0) { 2705 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 2706 viewFlagMasks |= VISIBILITY_MASK; 2707 } 2708 break; 2709 case com.android.internal.R.styleable.View_layoutDirection: 2710 // Clear any HORIZONTAL_DIRECTION flag already set 2711 viewFlagValues &= ~LAYOUT_DIRECTION_MASK; 2712 // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute 2713 final int layoutDirection = a.getInt(attr, -1); 2714 if (layoutDirection != -1) { 2715 viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection]; 2716 } else { 2717 // Set to default (LAYOUT_DIRECTION_INHERIT) 2718 viewFlagValues |= LAYOUT_DIRECTION_DEFAULT; 2719 } 2720 viewFlagMasks |= LAYOUT_DIRECTION_MASK; 2721 break; 2722 case com.android.internal.R.styleable.View_drawingCacheQuality: 2723 final int cacheQuality = a.getInt(attr, 0); 2724 if (cacheQuality != 0) { 2725 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 2726 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 2727 } 2728 break; 2729 case com.android.internal.R.styleable.View_contentDescription: 2730 mContentDescription = a.getString(attr); 2731 break; 2732 case com.android.internal.R.styleable.View_soundEffectsEnabled: 2733 if (!a.getBoolean(attr, true)) { 2734 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 2735 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 2736 } 2737 break; 2738 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 2739 if (!a.getBoolean(attr, true)) { 2740 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 2741 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 2742 } 2743 break; 2744 case R.styleable.View_scrollbars: 2745 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 2746 if (scrollbars != SCROLLBARS_NONE) { 2747 viewFlagValues |= scrollbars; 2748 viewFlagMasks |= SCROLLBARS_MASK; 2749 initializeScrollbars(a); 2750 } 2751 break; 2752 case R.styleable.View_fadingEdge: 2753 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 2754 if (fadingEdge != FADING_EDGE_NONE) { 2755 viewFlagValues |= fadingEdge; 2756 viewFlagMasks |= FADING_EDGE_MASK; 2757 initializeFadingEdge(a); 2758 } 2759 break; 2760 case R.styleable.View_scrollbarStyle: 2761 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 2762 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 2763 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 2764 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 2765 } 2766 break; 2767 case R.styleable.View_isScrollContainer: 2768 setScrollContainer = true; 2769 if (a.getBoolean(attr, false)) { 2770 setScrollContainer(true); 2771 } 2772 break; 2773 case com.android.internal.R.styleable.View_keepScreenOn: 2774 if (a.getBoolean(attr, false)) { 2775 viewFlagValues |= KEEP_SCREEN_ON; 2776 viewFlagMasks |= KEEP_SCREEN_ON; 2777 } 2778 break; 2779 case R.styleable.View_filterTouchesWhenObscured: 2780 if (a.getBoolean(attr, false)) { 2781 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 2782 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 2783 } 2784 break; 2785 case R.styleable.View_nextFocusLeft: 2786 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 2787 break; 2788 case R.styleable.View_nextFocusRight: 2789 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 2790 break; 2791 case R.styleable.View_nextFocusUp: 2792 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 2793 break; 2794 case R.styleable.View_nextFocusDown: 2795 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 2796 break; 2797 case R.styleable.View_nextFocusForward: 2798 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 2799 break; 2800 case R.styleable.View_minWidth: 2801 mMinWidth = a.getDimensionPixelSize(attr, 0); 2802 break; 2803 case R.styleable.View_minHeight: 2804 mMinHeight = a.getDimensionPixelSize(attr, 0); 2805 break; 2806 case R.styleable.View_onClick: 2807 if (context.isRestricted()) { 2808 throw new IllegalStateException("The android:onClick attribute cannot " 2809 + "be used within a restricted context"); 2810 } 2811 2812 final String handlerName = a.getString(attr); 2813 if (handlerName != null) { 2814 setOnClickListener(new OnClickListener() { 2815 private Method mHandler; 2816 2817 public void onClick(View v) { 2818 if (mHandler == null) { 2819 try { 2820 mHandler = getContext().getClass().getMethod(handlerName, 2821 View.class); 2822 } catch (NoSuchMethodException e) { 2823 int id = getId(); 2824 String idText = id == NO_ID ? "" : " with id '" 2825 + getContext().getResources().getResourceEntryName( 2826 id) + "'"; 2827 throw new IllegalStateException("Could not find a method " + 2828 handlerName + "(View) in the activity " 2829 + getContext().getClass() + " for onClick handler" 2830 + " on view " + View.this.getClass() + idText, e); 2831 } 2832 } 2833 2834 try { 2835 mHandler.invoke(getContext(), View.this); 2836 } catch (IllegalAccessException e) { 2837 throw new IllegalStateException("Could not execute non " 2838 + "public method of the activity", e); 2839 } catch (InvocationTargetException e) { 2840 throw new IllegalStateException("Could not execute " 2841 + "method of the activity", e); 2842 } 2843 } 2844 }); 2845 } 2846 break; 2847 case R.styleable.View_overScrollMode: 2848 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 2849 break; 2850 case R.styleable.View_verticalScrollbarPosition: 2851 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 2852 break; 2853 case R.styleable.View_layerType: 2854 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 2855 break; 2856 } 2857 } 2858 2859 setOverScrollMode(overScrollMode); 2860 2861 if (background != null) { 2862 setBackgroundDrawable(background); 2863 } 2864 2865 mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0); 2866 2867 if (padding >= 0) { 2868 leftPadding = padding; 2869 topPadding = padding; 2870 rightPadding = padding; 2871 bottomPadding = padding; 2872 startPadding = padding; 2873 endPadding = padding; 2874 } 2875 2876 // If the user specified the padding (either with android:padding or 2877 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 2878 // use the default padding or the padding from the background drawable 2879 // (stored at this point in mPadding*) 2880 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft, 2881 topPadding >= 0 ? topPadding : mPaddingTop, 2882 rightPadding >= 0 ? rightPadding : mPaddingRight, 2883 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 2884 2885 // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved 2886 // layout direction). Those cached values will be used later during padding resolution. 2887 mUserPaddingStart = startPadding; 2888 mUserPaddingEnd = endPadding; 2889 2890 if (viewFlagMasks != 0) { 2891 setFlags(viewFlagValues, viewFlagMasks); 2892 } 2893 2894 // Needs to be called after mViewFlags is set 2895 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 2896 recomputePadding(); 2897 } 2898 2899 if (x != 0 || y != 0) { 2900 scrollTo(x, y); 2901 } 2902 2903 if (transformSet) { 2904 setTranslationX(tx); 2905 setTranslationY(ty); 2906 setRotation(rotation); 2907 setRotationX(rotationX); 2908 setRotationY(rotationY); 2909 setScaleX(sx); 2910 setScaleY(sy); 2911 } 2912 2913 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 2914 setScrollContainer(true); 2915 } 2916 2917 computeOpaqueFlags(); 2918 2919 a.recycle(); 2920 } 2921 2922 /** 2923 * Non-public constructor for use in testing 2924 */ 2925 View() { 2926 } 2927 2928 /** 2929 * <p> 2930 * Initializes the fading edges from a given set of styled attributes. This 2931 * method should be called by subclasses that need fading edges and when an 2932 * instance of these subclasses is created programmatically rather than 2933 * being inflated from XML. This method is automatically called when the XML 2934 * is inflated. 2935 * </p> 2936 * 2937 * @param a the styled attributes set to initialize the fading edges from 2938 */ 2939 protected void initializeFadingEdge(TypedArray a) { 2940 initScrollCache(); 2941 2942 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 2943 R.styleable.View_fadingEdgeLength, 2944 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 2945 } 2946 2947 /** 2948 * Returns the size of the vertical faded edges used to indicate that more 2949 * content in this view is visible. 2950 * 2951 * @return The size in pixels of the vertical faded edge or 0 if vertical 2952 * faded edges are not enabled for this view. 2953 * @attr ref android.R.styleable#View_fadingEdgeLength 2954 */ 2955 public int getVerticalFadingEdgeLength() { 2956 if (isVerticalFadingEdgeEnabled()) { 2957 ScrollabilityCache cache = mScrollCache; 2958 if (cache != null) { 2959 return cache.fadingEdgeLength; 2960 } 2961 } 2962 return 0; 2963 } 2964 2965 /** 2966 * Set the size of the faded edge used to indicate that more content in this 2967 * view is available. Will not change whether the fading edge is enabled; use 2968 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 2969 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 2970 * for the vertical or horizontal fading edges. 2971 * 2972 * @param length The size in pixels of the faded edge used to indicate that more 2973 * content in this view is visible. 2974 */ 2975 public void setFadingEdgeLength(int length) { 2976 initScrollCache(); 2977 mScrollCache.fadingEdgeLength = length; 2978 } 2979 2980 /** 2981 * Returns the size of the horizontal faded edges used to indicate that more 2982 * content in this view is visible. 2983 * 2984 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 2985 * faded edges are not enabled for this view. 2986 * @attr ref android.R.styleable#View_fadingEdgeLength 2987 */ 2988 public int getHorizontalFadingEdgeLength() { 2989 if (isHorizontalFadingEdgeEnabled()) { 2990 ScrollabilityCache cache = mScrollCache; 2991 if (cache != null) { 2992 return cache.fadingEdgeLength; 2993 } 2994 } 2995 return 0; 2996 } 2997 2998 /** 2999 * Returns the width of the vertical scrollbar. 3000 * 3001 * @return The width in pixels of the vertical scrollbar or 0 if there 3002 * is no vertical scrollbar. 3003 */ 3004 public int getVerticalScrollbarWidth() { 3005 ScrollabilityCache cache = mScrollCache; 3006 if (cache != null) { 3007 ScrollBarDrawable scrollBar = cache.scrollBar; 3008 if (scrollBar != null) { 3009 int size = scrollBar.getSize(true); 3010 if (size <= 0) { 3011 size = cache.scrollBarSize; 3012 } 3013 return size; 3014 } 3015 return 0; 3016 } 3017 return 0; 3018 } 3019 3020 /** 3021 * Returns the height of the horizontal scrollbar. 3022 * 3023 * @return The height in pixels of the horizontal scrollbar or 0 if 3024 * there is no horizontal scrollbar. 3025 */ 3026 protected int getHorizontalScrollbarHeight() { 3027 ScrollabilityCache cache = mScrollCache; 3028 if (cache != null) { 3029 ScrollBarDrawable scrollBar = cache.scrollBar; 3030 if (scrollBar != null) { 3031 int size = scrollBar.getSize(false); 3032 if (size <= 0) { 3033 size = cache.scrollBarSize; 3034 } 3035 return size; 3036 } 3037 return 0; 3038 } 3039 return 0; 3040 } 3041 3042 /** 3043 * <p> 3044 * Initializes the scrollbars from a given set of styled attributes. This 3045 * method should be called by subclasses that need scrollbars and when an 3046 * instance of these subclasses is created programmatically rather than 3047 * being inflated from XML. This method is automatically called when the XML 3048 * is inflated. 3049 * </p> 3050 * 3051 * @param a the styled attributes set to initialize the scrollbars from 3052 */ 3053 protected void initializeScrollbars(TypedArray a) { 3054 initScrollCache(); 3055 3056 final ScrollabilityCache scrollabilityCache = mScrollCache; 3057 3058 if (scrollabilityCache.scrollBar == null) { 3059 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 3060 } 3061 3062 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 3063 3064 if (!fadeScrollbars) { 3065 scrollabilityCache.state = ScrollabilityCache.ON; 3066 } 3067 scrollabilityCache.fadeScrollBars = fadeScrollbars; 3068 3069 3070 scrollabilityCache.scrollBarFadeDuration = a.getInt( 3071 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 3072 .getScrollBarFadeDuration()); 3073 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 3074 R.styleable.View_scrollbarDefaultDelayBeforeFade, 3075 ViewConfiguration.getScrollDefaultDelay()); 3076 3077 3078 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 3079 com.android.internal.R.styleable.View_scrollbarSize, 3080 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3081 3082 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3083 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3084 3085 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3086 if (thumb != null) { 3087 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3088 } 3089 3090 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3091 false); 3092 if (alwaysDraw) { 3093 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3094 } 3095 3096 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3097 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3098 3099 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3100 if (thumb != null) { 3101 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3102 } 3103 3104 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3105 false); 3106 if (alwaysDraw) { 3107 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3108 } 3109 3110 // Re-apply user/background padding so that scrollbar(s) get added 3111 resolvePadding(); 3112 } 3113 3114 /** 3115 * <p> 3116 * Initalizes the scrollability cache if necessary. 3117 * </p> 3118 */ 3119 private void initScrollCache() { 3120 if (mScrollCache == null) { 3121 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 3122 } 3123 } 3124 3125 /** 3126 * Set the position of the vertical scroll bar. Should be one of 3127 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 3128 * {@link #SCROLLBAR_POSITION_RIGHT}. 3129 * 3130 * @param position Where the vertical scroll bar should be positioned. 3131 */ 3132 public void setVerticalScrollbarPosition(int position) { 3133 if (mVerticalScrollbarPosition != position) { 3134 mVerticalScrollbarPosition = position; 3135 computeOpaqueFlags(); 3136 resolvePadding(); 3137 } 3138 } 3139 3140 /** 3141 * @return The position where the vertical scroll bar will show, if applicable. 3142 * @see #setVerticalScrollbarPosition(int) 3143 */ 3144 public int getVerticalScrollbarPosition() { 3145 return mVerticalScrollbarPosition; 3146 } 3147 3148 /** 3149 * Register a callback to be invoked when focus of this view changed. 3150 * 3151 * @param l The callback that will run. 3152 */ 3153 public void setOnFocusChangeListener(OnFocusChangeListener l) { 3154 mOnFocusChangeListener = l; 3155 } 3156 3157 /** 3158 * Add a listener that will be called when the bounds of the view change due to 3159 * layout processing. 3160 * 3161 * @param listener The listener that will be called when layout bounds change. 3162 */ 3163 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 3164 if (mOnLayoutChangeListeners == null) { 3165 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 3166 } 3167 mOnLayoutChangeListeners.add(listener); 3168 } 3169 3170 /** 3171 * Remove a listener for layout changes. 3172 * 3173 * @param listener The listener for layout bounds change. 3174 */ 3175 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 3176 if (mOnLayoutChangeListeners == null) { 3177 return; 3178 } 3179 mOnLayoutChangeListeners.remove(listener); 3180 } 3181 3182 /** 3183 * Add a listener for attach state changes. 3184 * 3185 * This listener will be called whenever this view is attached or detached 3186 * from a window. Remove the listener using 3187 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 3188 * 3189 * @param listener Listener to attach 3190 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 3191 */ 3192 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3193 if (mOnAttachStateChangeListeners == null) { 3194 mOnAttachStateChangeListeners = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 3195 } 3196 mOnAttachStateChangeListeners.add(listener); 3197 } 3198 3199 /** 3200 * Remove a listener for attach state changes. The listener will receive no further 3201 * notification of window attach/detach events. 3202 * 3203 * @param listener Listener to remove 3204 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 3205 */ 3206 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3207 if (mOnAttachStateChangeListeners == null) { 3208 return; 3209 } 3210 mOnAttachStateChangeListeners.remove(listener); 3211 } 3212 3213 /** 3214 * Returns the focus-change callback registered for this view. 3215 * 3216 * @return The callback, or null if one is not registered. 3217 */ 3218 public OnFocusChangeListener getOnFocusChangeListener() { 3219 return mOnFocusChangeListener; 3220 } 3221 3222 /** 3223 * Register a callback to be invoked when this view is clicked. If this view is not 3224 * clickable, it becomes clickable. 3225 * 3226 * @param l The callback that will run 3227 * 3228 * @see #setClickable(boolean) 3229 */ 3230 public void setOnClickListener(OnClickListener l) { 3231 if (!isClickable()) { 3232 setClickable(true); 3233 } 3234 mOnClickListener = l; 3235 } 3236 3237 /** 3238 * Register a callback to be invoked when this view is clicked and held. If this view is not 3239 * long clickable, it becomes long clickable. 3240 * 3241 * @param l The callback that will run 3242 * 3243 * @see #setLongClickable(boolean) 3244 */ 3245 public void setOnLongClickListener(OnLongClickListener l) { 3246 if (!isLongClickable()) { 3247 setLongClickable(true); 3248 } 3249 mOnLongClickListener = l; 3250 } 3251 3252 /** 3253 * Register a callback to be invoked when the context menu for this view is 3254 * being built. If this view is not long clickable, it becomes long clickable. 3255 * 3256 * @param l The callback that will run 3257 * 3258 */ 3259 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 3260 if (!isLongClickable()) { 3261 setLongClickable(true); 3262 } 3263 mOnCreateContextMenuListener = l; 3264 } 3265 3266 /** 3267 * Call this view's OnClickListener, if it is defined. 3268 * 3269 * @return True there was an assigned OnClickListener that was called, false 3270 * otherwise is returned. 3271 */ 3272 public boolean performClick() { 3273 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 3274 3275 if (mOnClickListener != null) { 3276 playSoundEffect(SoundEffectConstants.CLICK); 3277 mOnClickListener.onClick(this); 3278 return true; 3279 } 3280 3281 return false; 3282 } 3283 3284 /** 3285 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 3286 * OnLongClickListener did not consume the event. 3287 * 3288 * @return True if one of the above receivers consumed the event, false otherwise. 3289 */ 3290 public boolean performLongClick() { 3291 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 3292 3293 boolean handled = false; 3294 if (mOnLongClickListener != null) { 3295 handled = mOnLongClickListener.onLongClick(View.this); 3296 } 3297 if (!handled) { 3298 handled = showContextMenu(); 3299 } 3300 if (handled) { 3301 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 3302 } 3303 return handled; 3304 } 3305 3306 /** 3307 * Performs button-related actions during a touch down event. 3308 * 3309 * @param event The event. 3310 * @return True if the down was consumed. 3311 * 3312 * @hide 3313 */ 3314 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 3315 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 3316 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 3317 return true; 3318 } 3319 } 3320 return false; 3321 } 3322 3323 /** 3324 * Bring up the context menu for this view. 3325 * 3326 * @return Whether a context menu was displayed. 3327 */ 3328 public boolean showContextMenu() { 3329 return getParent().showContextMenuForChild(this); 3330 } 3331 3332 /** 3333 * Bring up the context menu for this view, referring to the item under the specified point. 3334 * 3335 * @param x The referenced x coordinate. 3336 * @param y The referenced y coordinate. 3337 * @param metaState The keyboard modifiers that were pressed. 3338 * @return Whether a context menu was displayed. 3339 * 3340 * @hide 3341 */ 3342 public boolean showContextMenu(float x, float y, int metaState) { 3343 return showContextMenu(); 3344 } 3345 3346 /** 3347 * Start an action mode. 3348 * 3349 * @param callback Callback that will control the lifecycle of the action mode 3350 * @return The new action mode if it is started, null otherwise 3351 * 3352 * @see ActionMode 3353 */ 3354 public ActionMode startActionMode(ActionMode.Callback callback) { 3355 return getParent().startActionModeForChild(this, callback); 3356 } 3357 3358 /** 3359 * Register a callback to be invoked when a key is pressed in this view. 3360 * @param l the key listener to attach to this view 3361 */ 3362 public void setOnKeyListener(OnKeyListener l) { 3363 mOnKeyListener = l; 3364 } 3365 3366 /** 3367 * Register a callback to be invoked when a touch event is sent to this view. 3368 * @param l the touch listener to attach to this view 3369 */ 3370 public void setOnTouchListener(OnTouchListener l) { 3371 mOnTouchListener = l; 3372 } 3373 3374 /** 3375 * Register a callback to be invoked when a generic motion event is sent to this view. 3376 * @param l the generic motion listener to attach to this view 3377 */ 3378 public void setOnGenericMotionListener(OnGenericMotionListener l) { 3379 mOnGenericMotionListener = l; 3380 } 3381 3382 /** 3383 * Register a drag event listener callback object for this View. The parameter is 3384 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 3385 * View, the system calls the 3386 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 3387 * @param l An implementation of {@link android.view.View.OnDragListener}. 3388 */ 3389 public void setOnDragListener(OnDragListener l) { 3390 mOnDragListener = l; 3391 } 3392 3393 /** 3394 * Give this view focus. This will cause 3395 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3396 * 3397 * Note: this does not check whether this {@link View} should get focus, it just 3398 * gives it focus no matter what. It should only be called internally by framework 3399 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 3400 * 3401 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 3402 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 3403 * focus moved when requestFocus() is called. It may not always 3404 * apply, in which case use the default View.FOCUS_DOWN. 3405 * @param previouslyFocusedRect The rectangle of the view that had focus 3406 * prior in this View's coordinate system. 3407 */ 3408 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 3409 if (DBG) { 3410 System.out.println(this + " requestFocus()"); 3411 } 3412 3413 if ((mPrivateFlags & FOCUSED) == 0) { 3414 mPrivateFlags |= FOCUSED; 3415 3416 if (mParent != null) { 3417 mParent.requestChildFocus(this, this); 3418 } 3419 3420 onFocusChanged(true, direction, previouslyFocusedRect); 3421 refreshDrawableState(); 3422 } 3423 } 3424 3425 /** 3426 * Request that a rectangle of this view be visible on the screen, 3427 * scrolling if necessary just enough. 3428 * 3429 * <p>A View should call this if it maintains some notion of which part 3430 * of its content is interesting. For example, a text editing view 3431 * should call this when its cursor moves. 3432 * 3433 * @param rectangle The rectangle. 3434 * @return Whether any parent scrolled. 3435 */ 3436 public boolean requestRectangleOnScreen(Rect rectangle) { 3437 return requestRectangleOnScreen(rectangle, false); 3438 } 3439 3440 /** 3441 * Request that a rectangle of this view be visible on the screen, 3442 * scrolling if necessary just enough. 3443 * 3444 * <p>A View should call this if it maintains some notion of which part 3445 * of its content is interesting. For example, a text editing view 3446 * should call this when its cursor moves. 3447 * 3448 * <p>When <code>immediate</code> is set to true, scrolling will not be 3449 * animated. 3450 * 3451 * @param rectangle The rectangle. 3452 * @param immediate True to forbid animated scrolling, false otherwise 3453 * @return Whether any parent scrolled. 3454 */ 3455 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 3456 View child = this; 3457 ViewParent parent = mParent; 3458 boolean scrolled = false; 3459 while (parent != null) { 3460 scrolled |= parent.requestChildRectangleOnScreen(child, 3461 rectangle, immediate); 3462 3463 // offset rect so next call has the rectangle in the 3464 // coordinate system of its direct child. 3465 rectangle.offset(child.getLeft(), child.getTop()); 3466 rectangle.offset(-child.getScrollX(), -child.getScrollY()); 3467 3468 if (!(parent instanceof View)) { 3469 break; 3470 } 3471 3472 child = (View) parent; 3473 parent = child.getParent(); 3474 } 3475 return scrolled; 3476 } 3477 3478 /** 3479 * Called when this view wants to give up focus. This will cause 3480 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3481 */ 3482 public void clearFocus() { 3483 if (DBG) { 3484 System.out.println(this + " clearFocus()"); 3485 } 3486 3487 if ((mPrivateFlags & FOCUSED) != 0) { 3488 mPrivateFlags &= ~FOCUSED; 3489 3490 if (mParent != null) { 3491 mParent.clearChildFocus(this); 3492 } 3493 3494 onFocusChanged(false, 0, null); 3495 refreshDrawableState(); 3496 } 3497 } 3498 3499 /** 3500 * Called to clear the focus of a view that is about to be removed. 3501 * Doesn't call clearChildFocus, which prevents this view from taking 3502 * focus again before it has been removed from the parent 3503 */ 3504 void clearFocusForRemoval() { 3505 if ((mPrivateFlags & FOCUSED) != 0) { 3506 mPrivateFlags &= ~FOCUSED; 3507 3508 onFocusChanged(false, 0, null); 3509 refreshDrawableState(); 3510 } 3511 } 3512 3513 /** 3514 * Called internally by the view system when a new view is getting focus. 3515 * This is what clears the old focus. 3516 */ 3517 void unFocus() { 3518 if (DBG) { 3519 System.out.println(this + " unFocus()"); 3520 } 3521 3522 if ((mPrivateFlags & FOCUSED) != 0) { 3523 mPrivateFlags &= ~FOCUSED; 3524 3525 onFocusChanged(false, 0, null); 3526 refreshDrawableState(); 3527 } 3528 } 3529 3530 /** 3531 * Returns true if this view has focus iteself, or is the ancestor of the 3532 * view that has focus. 3533 * 3534 * @return True if this view has or contains focus, false otherwise. 3535 */ 3536 @ViewDebug.ExportedProperty(category = "focus") 3537 public boolean hasFocus() { 3538 return (mPrivateFlags & FOCUSED) != 0; 3539 } 3540 3541 /** 3542 * Returns true if this view is focusable or if it contains a reachable View 3543 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 3544 * is a View whose parents do not block descendants focus. 3545 * 3546 * Only {@link #VISIBLE} views are considered focusable. 3547 * 3548 * @return True if the view is focusable or if the view contains a focusable 3549 * View, false otherwise. 3550 * 3551 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 3552 */ 3553 public boolean hasFocusable() { 3554 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 3555 } 3556 3557 /** 3558 * Called by the view system when the focus state of this view changes. 3559 * When the focus change event is caused by directional navigation, direction 3560 * and previouslyFocusedRect provide insight into where the focus is coming from. 3561 * When overriding, be sure to call up through to the super class so that 3562 * the standard focus handling will occur. 3563 * 3564 * @param gainFocus True if the View has focus; false otherwise. 3565 * @param direction The direction focus has moved when requestFocus() 3566 * is called to give this view focus. Values are 3567 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 3568 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 3569 * It may not always apply, in which case use the default. 3570 * @param previouslyFocusedRect The rectangle, in this view's coordinate 3571 * system, of the previously focused view. If applicable, this will be 3572 * passed in as finer grained information about where the focus is coming 3573 * from (in addition to direction). Will be <code>null</code> otherwise. 3574 */ 3575 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 3576 if (gainFocus) { 3577 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 3578 } 3579 3580 InputMethodManager imm = InputMethodManager.peekInstance(); 3581 if (!gainFocus) { 3582 if (isPressed()) { 3583 setPressed(false); 3584 } 3585 if (imm != null && mAttachInfo != null 3586 && mAttachInfo.mHasWindowFocus) { 3587 imm.focusOut(this); 3588 } 3589 onFocusLost(); 3590 } else if (imm != null && mAttachInfo != null 3591 && mAttachInfo.mHasWindowFocus) { 3592 imm.focusIn(this); 3593 } 3594 3595 invalidate(true); 3596 if (mOnFocusChangeListener != null) { 3597 mOnFocusChangeListener.onFocusChange(this, gainFocus); 3598 } 3599 3600 if (mAttachInfo != null) { 3601 mAttachInfo.mKeyDispatchState.reset(this); 3602 } 3603 } 3604 3605 /** 3606 * Sends an accessibility event of the given type. If accessiiblity is 3607 * not enabled this method has no effect. The default implementation calls 3608 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 3609 * to populate information about the event source (this View), then calls 3610 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 3611 * populate the text content of the event source including its descendants, 3612 * and last calls 3613 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 3614 * on its parent to resuest sending of the event to interested parties. 3615 * 3616 * @param eventType The type of the event to send. 3617 * 3618 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 3619 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3620 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 3621 */ 3622 public void sendAccessibilityEvent(int eventType) { 3623 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 3624 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 3625 } 3626 } 3627 3628 /** 3629 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 3630 * takes as an argument an empty {@link AccessibilityEvent} and does not 3631 * perfrom a check whether accessibility is enabled. 3632 * 3633 * @param event The event to send. 3634 * 3635 * @see #sendAccessibilityEvent(int) 3636 */ 3637 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 3638 if (!isShown()) { 3639 return; 3640 } 3641 onInitializeAccessibilityEvent(event); 3642 dispatchPopulateAccessibilityEvent(event); 3643 // In the beginning we called #isShown(), so we know that getParent() is not null. 3644 getParent().requestSendAccessibilityEvent(this, event); 3645 } 3646 3647 /** 3648 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 3649 * to its children for adding their text content to the event. Note that the 3650 * event text is populated in a separate dispatch path since we add to the 3651 * event not only the text of the source but also the text of all its descendants. 3652 * </p> 3653 * A typical implementation will call 3654 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 3655 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3656 * on each child. Override this method if custom population of the event text 3657 * content is required. 3658 * 3659 * @param event The event. 3660 * 3661 * @return True if the event population was completed. 3662 */ 3663 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 3664 onPopulateAccessibilityEvent(event); 3665 return false; 3666 } 3667 3668 /** 3669 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3670 * giving a chance to this View to populate the accessibility event with its 3671 * text content. While the implementation is free to modify other event 3672 * attributes this should be performed in 3673 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 3674 * <p> 3675 * Example: Adding formatted date string to an accessibility event in addition 3676 * to the text added by the super implementation. 3677 * </p><p><pre><code> 3678 * public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3679 * super.onPopulateAccessibilityEvent(event); 3680 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 3681 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 3682 * mCurrentDate.getTimeInMillis(), flags); 3683 * event.getText().add(selectedDateUtterance); 3684 * } 3685 * </code></pre></p> 3686 * 3687 * @param event The accessibility event which to populate. 3688 * 3689 * @see #sendAccessibilityEvent(int) 3690 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3691 */ 3692 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3693 3694 } 3695 3696 /** 3697 * Initializes an {@link AccessibilityEvent} with information about the 3698 * the type of the event and this View which is the event source. In other 3699 * words, the source of an accessibility event is the view whose state 3700 * change triggered firing the event. 3701 * <p> 3702 * Example: Setting the password property of an event in addition 3703 * to properties set by the super implementation. 3704 * </p><p><pre><code> 3705 * public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 3706 * super.onInitializeAccessibilityEvent(event); 3707 * event.setPassword(true); 3708 * } 3709 * </code></pre></p> 3710 * @param event The event to initialeze. 3711 * 3712 * @see #sendAccessibilityEvent(int) 3713 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3714 */ 3715 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 3716 event.setSource(this); 3717 event.setClassName(getClass().getName()); 3718 event.setPackageName(getContext().getPackageName()); 3719 event.setEnabled(isEnabled()); 3720 event.setContentDescription(mContentDescription); 3721 3722 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) { 3723 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList; 3724 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 3725 event.setItemCount(focusablesTempList.size()); 3726 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 3727 focusablesTempList.clear(); 3728 } 3729 } 3730 3731 /** 3732 * Returns an {@link AccessibilityNodeInfo} representing this view from the 3733 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 3734 * This method is responsible for obtaining an accessibility node info from a 3735 * pool of reusable instances and calling 3736 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 3737 * initialize the former. 3738 * <p> 3739 * Note: The client is responsible for recycling the obtained instance by calling 3740 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 3741 * </p> 3742 * @return A populated {@link AccessibilityNodeInfo}. 3743 * 3744 * @see AccessibilityNodeInfo 3745 */ 3746 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 3747 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 3748 onInitializeAccessibilityNodeInfo(info); 3749 return info; 3750 } 3751 3752 /** 3753 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 3754 * The base implementation sets: 3755 * <ul> 3756 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 3757 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 3758 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 3759 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 3760 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 3761 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 3762 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 3763 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 3764 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 3765 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 3766 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 3767 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 3768 * </ul> 3769 * <p> 3770 * Subclasses should override this method, call the super implementation, 3771 * and set additional attributes. 3772 * </p> 3773 * @param info The instance to initialize. 3774 */ 3775 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 3776 Rect bounds = mAttachInfo.mTmpInvalRect; 3777 getDrawingRect(bounds); 3778 info.setBoundsInParent(bounds); 3779 3780 int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation; 3781 getLocationOnScreen(locationOnScreen); 3782 bounds.offset(locationOnScreen[0], locationOnScreen[1]); 3783 info.setBoundsInScreen(bounds); 3784 3785 ViewParent parent = getParent(); 3786 if (parent instanceof View) { 3787 View parentView = (View) parent; 3788 info.setParent(parentView); 3789 } 3790 3791 info.setPackageName(mContext.getPackageName()); 3792 info.setClassName(getClass().getName()); 3793 info.setContentDescription(getContentDescription()); 3794 3795 info.setEnabled(isEnabled()); 3796 info.setClickable(isClickable()); 3797 info.setFocusable(isFocusable()); 3798 info.setFocused(isFocused()); 3799 info.setSelected(isSelected()); 3800 info.setLongClickable(isLongClickable()); 3801 3802 // TODO: These make sense only if we are in an AdapterView but all 3803 // views can be selected. Maybe from accessiiblity perspective 3804 // we should report as selectable view in an AdapterView. 3805 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 3806 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 3807 3808 if (isFocusable()) { 3809 if (isFocused()) { 3810 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 3811 } else { 3812 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 3813 } 3814 } 3815 } 3816 3817 /** 3818 * Gets the unique identifier of this view on the screen for accessibility purposes. 3819 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 3820 * 3821 * @return The view accessibility id. 3822 * 3823 * @hide 3824 */ 3825 public int getAccessibilityViewId() { 3826 if (mAccessibilityViewId == NO_ID) { 3827 mAccessibilityViewId = sNextAccessibilityViewId++; 3828 } 3829 return mAccessibilityViewId; 3830 } 3831 3832 /** 3833 * Gets the unique identifier of the window in which this View reseides. 3834 * 3835 * @return The window accessibility id. 3836 * 3837 * @hide 3838 */ 3839 public int getAccessibilityWindowId() { 3840 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 3841 } 3842 3843 /** 3844 * Gets the {@link View} description. It briefly describes the view and is 3845 * primarily used for accessibility support. Set this property to enable 3846 * better accessibility support for your application. This is especially 3847 * true for views that do not have textual representation (For example, 3848 * ImageButton). 3849 * 3850 * @return The content descriptiopn. 3851 * 3852 * @attr ref android.R.styleable#View_contentDescription 3853 */ 3854 public CharSequence getContentDescription() { 3855 return mContentDescription; 3856 } 3857 3858 /** 3859 * Sets the {@link View} description. It briefly describes the view and is 3860 * primarily used for accessibility support. Set this property to enable 3861 * better accessibility support for your application. This is especially 3862 * true for views that do not have textual representation (For example, 3863 * ImageButton). 3864 * 3865 * @param contentDescription The content description. 3866 * 3867 * @attr ref android.R.styleable#View_contentDescription 3868 */ 3869 public void setContentDescription(CharSequence contentDescription) { 3870 mContentDescription = contentDescription; 3871 } 3872 3873 /** 3874 * Invoked whenever this view loses focus, either by losing window focus or by losing 3875 * focus within its window. This method can be used to clear any state tied to the 3876 * focus. For instance, if a button is held pressed with the trackball and the window 3877 * loses focus, this method can be used to cancel the press. 3878 * 3879 * Subclasses of View overriding this method should always call super.onFocusLost(). 3880 * 3881 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 3882 * @see #onWindowFocusChanged(boolean) 3883 * 3884 * @hide pending API council approval 3885 */ 3886 protected void onFocusLost() { 3887 resetPressedState(); 3888 } 3889 3890 private void resetPressedState() { 3891 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 3892 return; 3893 } 3894 3895 if (isPressed()) { 3896 setPressed(false); 3897 3898 if (!mHasPerformedLongPress) { 3899 removeLongPressCallback(); 3900 } 3901 } 3902 } 3903 3904 /** 3905 * Returns true if this view has focus 3906 * 3907 * @return True if this view has focus, false otherwise. 3908 */ 3909 @ViewDebug.ExportedProperty(category = "focus") 3910 public boolean isFocused() { 3911 return (mPrivateFlags & FOCUSED) != 0; 3912 } 3913 3914 /** 3915 * Find the view in the hierarchy rooted at this view that currently has 3916 * focus. 3917 * 3918 * @return The view that currently has focus, or null if no focused view can 3919 * be found. 3920 */ 3921 public View findFocus() { 3922 return (mPrivateFlags & FOCUSED) != 0 ? this : null; 3923 } 3924 3925 /** 3926 * Change whether this view is one of the set of scrollable containers in 3927 * its window. This will be used to determine whether the window can 3928 * resize or must pan when a soft input area is open -- scrollable 3929 * containers allow the window to use resize mode since the container 3930 * will appropriately shrink. 3931 */ 3932 public void setScrollContainer(boolean isScrollContainer) { 3933 if (isScrollContainer) { 3934 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) { 3935 mAttachInfo.mScrollContainers.add(this); 3936 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 3937 } 3938 mPrivateFlags |= SCROLL_CONTAINER; 3939 } else { 3940 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 3941 mAttachInfo.mScrollContainers.remove(this); 3942 } 3943 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED); 3944 } 3945 } 3946 3947 /** 3948 * Returns the quality of the drawing cache. 3949 * 3950 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 3951 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 3952 * 3953 * @see #setDrawingCacheQuality(int) 3954 * @see #setDrawingCacheEnabled(boolean) 3955 * @see #isDrawingCacheEnabled() 3956 * 3957 * @attr ref android.R.styleable#View_drawingCacheQuality 3958 */ 3959 public int getDrawingCacheQuality() { 3960 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 3961 } 3962 3963 /** 3964 * Set the drawing cache quality of this view. This value is used only when the 3965 * drawing cache is enabled 3966 * 3967 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 3968 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 3969 * 3970 * @see #getDrawingCacheQuality() 3971 * @see #setDrawingCacheEnabled(boolean) 3972 * @see #isDrawingCacheEnabled() 3973 * 3974 * @attr ref android.R.styleable#View_drawingCacheQuality 3975 */ 3976 public void setDrawingCacheQuality(int quality) { 3977 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 3978 } 3979 3980 /** 3981 * Returns whether the screen should remain on, corresponding to the current 3982 * value of {@link #KEEP_SCREEN_ON}. 3983 * 3984 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 3985 * 3986 * @see #setKeepScreenOn(boolean) 3987 * 3988 * @attr ref android.R.styleable#View_keepScreenOn 3989 */ 3990 public boolean getKeepScreenOn() { 3991 return (mViewFlags & KEEP_SCREEN_ON) != 0; 3992 } 3993 3994 /** 3995 * Controls whether the screen should remain on, modifying the 3996 * value of {@link #KEEP_SCREEN_ON}. 3997 * 3998 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 3999 * 4000 * @see #getKeepScreenOn() 4001 * 4002 * @attr ref android.R.styleable#View_keepScreenOn 4003 */ 4004 public void setKeepScreenOn(boolean keepScreenOn) { 4005 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 4006 } 4007 4008 /** 4009 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4010 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4011 * 4012 * @attr ref android.R.styleable#View_nextFocusLeft 4013 */ 4014 public int getNextFocusLeftId() { 4015 return mNextFocusLeftId; 4016 } 4017 4018 /** 4019 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4020 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 4021 * decide automatically. 4022 * 4023 * @attr ref android.R.styleable#View_nextFocusLeft 4024 */ 4025 public void setNextFocusLeftId(int nextFocusLeftId) { 4026 mNextFocusLeftId = nextFocusLeftId; 4027 } 4028 4029 /** 4030 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4031 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4032 * 4033 * @attr ref android.R.styleable#View_nextFocusRight 4034 */ 4035 public int getNextFocusRightId() { 4036 return mNextFocusRightId; 4037 } 4038 4039 /** 4040 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4041 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 4042 * decide automatically. 4043 * 4044 * @attr ref android.R.styleable#View_nextFocusRight 4045 */ 4046 public void setNextFocusRightId(int nextFocusRightId) { 4047 mNextFocusRightId = nextFocusRightId; 4048 } 4049 4050 /** 4051 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4052 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4053 * 4054 * @attr ref android.R.styleable#View_nextFocusUp 4055 */ 4056 public int getNextFocusUpId() { 4057 return mNextFocusUpId; 4058 } 4059 4060 /** 4061 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4062 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 4063 * decide automatically. 4064 * 4065 * @attr ref android.R.styleable#View_nextFocusUp 4066 */ 4067 public void setNextFocusUpId(int nextFocusUpId) { 4068 mNextFocusUpId = nextFocusUpId; 4069 } 4070 4071 /** 4072 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4073 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4074 * 4075 * @attr ref android.R.styleable#View_nextFocusDown 4076 */ 4077 public int getNextFocusDownId() { 4078 return mNextFocusDownId; 4079 } 4080 4081 /** 4082 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4083 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 4084 * decide automatically. 4085 * 4086 * @attr ref android.R.styleable#View_nextFocusDown 4087 */ 4088 public void setNextFocusDownId(int nextFocusDownId) { 4089 mNextFocusDownId = nextFocusDownId; 4090 } 4091 4092 /** 4093 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4094 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4095 * 4096 * @attr ref android.R.styleable#View_nextFocusForward 4097 */ 4098 public int getNextFocusForwardId() { 4099 return mNextFocusForwardId; 4100 } 4101 4102 /** 4103 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4104 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 4105 * decide automatically. 4106 * 4107 * @attr ref android.R.styleable#View_nextFocusForward 4108 */ 4109 public void setNextFocusForwardId(int nextFocusForwardId) { 4110 mNextFocusForwardId = nextFocusForwardId; 4111 } 4112 4113 /** 4114 * Returns the visibility of this view and all of its ancestors 4115 * 4116 * @return True if this view and all of its ancestors are {@link #VISIBLE} 4117 */ 4118 public boolean isShown() { 4119 View current = this; 4120 //noinspection ConstantConditions 4121 do { 4122 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 4123 return false; 4124 } 4125 ViewParent parent = current.mParent; 4126 if (parent == null) { 4127 return false; // We are not attached to the view root 4128 } 4129 if (!(parent instanceof View)) { 4130 return true; 4131 } 4132 current = (View) parent; 4133 } while (current != null); 4134 4135 return false; 4136 } 4137 4138 /** 4139 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag 4140 * is set 4141 * 4142 * @param insets Insets for system windows 4143 * 4144 * @return True if this view applied the insets, false otherwise 4145 */ 4146 protected boolean fitSystemWindows(Rect insets) { 4147 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 4148 mPaddingLeft = insets.left; 4149 mPaddingTop = insets.top; 4150 mPaddingRight = insets.right; 4151 mPaddingBottom = insets.bottom; 4152 requestLayout(); 4153 return true; 4154 } 4155 return false; 4156 } 4157 4158 /** 4159 * Returns the visibility status for this view. 4160 * 4161 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4162 * @attr ref android.R.styleable#View_visibility 4163 */ 4164 @ViewDebug.ExportedProperty(mapping = { 4165 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 4166 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 4167 @ViewDebug.IntToString(from = GONE, to = "GONE") 4168 }) 4169 public int getVisibility() { 4170 return mViewFlags & VISIBILITY_MASK; 4171 } 4172 4173 /** 4174 * Set the enabled state of this view. 4175 * 4176 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4177 * @attr ref android.R.styleable#View_visibility 4178 */ 4179 @RemotableViewMethod 4180 public void setVisibility(int visibility) { 4181 setFlags(visibility, VISIBILITY_MASK); 4182 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); 4183 } 4184 4185 /** 4186 * Returns the enabled status for this view. The interpretation of the 4187 * enabled state varies by subclass. 4188 * 4189 * @return True if this view is enabled, false otherwise. 4190 */ 4191 @ViewDebug.ExportedProperty 4192 public boolean isEnabled() { 4193 return (mViewFlags & ENABLED_MASK) == ENABLED; 4194 } 4195 4196 /** 4197 * Set the enabled state of this view. The interpretation of the enabled 4198 * state varies by subclass. 4199 * 4200 * @param enabled True if this view is enabled, false otherwise. 4201 */ 4202 @RemotableViewMethod 4203 public void setEnabled(boolean enabled) { 4204 if (enabled == isEnabled()) return; 4205 4206 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 4207 4208 /* 4209 * The View most likely has to change its appearance, so refresh 4210 * the drawable state. 4211 */ 4212 refreshDrawableState(); 4213 4214 // Invalidate too, since the default behavior for views is to be 4215 // be drawn at 50% alpha rather than to change the drawable. 4216 invalidate(true); 4217 } 4218 4219 /** 4220 * Set whether this view can receive the focus. 4221 * 4222 * Setting this to false will also ensure that this view is not focusable 4223 * in touch mode. 4224 * 4225 * @param focusable If true, this view can receive the focus. 4226 * 4227 * @see #setFocusableInTouchMode(boolean) 4228 * @attr ref android.R.styleable#View_focusable 4229 */ 4230 public void setFocusable(boolean focusable) { 4231 if (!focusable) { 4232 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 4233 } 4234 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 4235 } 4236 4237 /** 4238 * Set whether this view can receive focus while in touch mode. 4239 * 4240 * Setting this to true will also ensure that this view is focusable. 4241 * 4242 * @param focusableInTouchMode If true, this view can receive the focus while 4243 * in touch mode. 4244 * 4245 * @see #setFocusable(boolean) 4246 * @attr ref android.R.styleable#View_focusableInTouchMode 4247 */ 4248 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 4249 // Focusable in touch mode should always be set before the focusable flag 4250 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 4251 // which, in touch mode, will not successfully request focus on this view 4252 // because the focusable in touch mode flag is not set 4253 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 4254 if (focusableInTouchMode) { 4255 setFlags(FOCUSABLE, FOCUSABLE_MASK); 4256 } 4257 } 4258 4259 /** 4260 * Set whether this view should have sound effects enabled for events such as 4261 * clicking and touching. 4262 * 4263 * <p>You may wish to disable sound effects for a view if you already play sounds, 4264 * for instance, a dial key that plays dtmf tones. 4265 * 4266 * @param soundEffectsEnabled whether sound effects are enabled for this view. 4267 * @see #isSoundEffectsEnabled() 4268 * @see #playSoundEffect(int) 4269 * @attr ref android.R.styleable#View_soundEffectsEnabled 4270 */ 4271 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 4272 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 4273 } 4274 4275 /** 4276 * @return whether this view should have sound effects enabled for events such as 4277 * clicking and touching. 4278 * 4279 * @see #setSoundEffectsEnabled(boolean) 4280 * @see #playSoundEffect(int) 4281 * @attr ref android.R.styleable#View_soundEffectsEnabled 4282 */ 4283 @ViewDebug.ExportedProperty 4284 public boolean isSoundEffectsEnabled() { 4285 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 4286 } 4287 4288 /** 4289 * Set whether this view should have haptic feedback for events such as 4290 * long presses. 4291 * 4292 * <p>You may wish to disable haptic feedback if your view already controls 4293 * its own haptic feedback. 4294 * 4295 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 4296 * @see #isHapticFeedbackEnabled() 4297 * @see #performHapticFeedback(int) 4298 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4299 */ 4300 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 4301 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 4302 } 4303 4304 /** 4305 * @return whether this view should have haptic feedback enabled for events 4306 * long presses. 4307 * 4308 * @see #setHapticFeedbackEnabled(boolean) 4309 * @see #performHapticFeedback(int) 4310 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4311 */ 4312 @ViewDebug.ExportedProperty 4313 public boolean isHapticFeedbackEnabled() { 4314 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 4315 } 4316 4317 /** 4318 * Returns the layout direction for this view. 4319 * 4320 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 4321 * {@link #LAYOUT_DIRECTION_RTL}, 4322 * {@link #LAYOUT_DIRECTION_INHERIT} or 4323 * {@link #LAYOUT_DIRECTION_LOCALE}. 4324 * @attr ref android.R.styleable#View_layoutDirection 4325 * 4326 * @hide 4327 */ 4328 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4329 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 4330 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 4331 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 4332 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 4333 }) 4334 public int getLayoutDirection() { 4335 return mViewFlags & LAYOUT_DIRECTION_MASK; 4336 } 4337 4338 /** 4339 * Set the layout direction for this view. 4340 * 4341 * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR}, 4342 * {@link #LAYOUT_DIRECTION_RTL}, 4343 * {@link #LAYOUT_DIRECTION_INHERIT} or 4344 * {@link #LAYOUT_DIRECTION_LOCALE}. 4345 * @attr ref android.R.styleable#View_layoutDirection 4346 * 4347 * @hide 4348 */ 4349 @RemotableViewMethod 4350 public void setLayoutDirection(int layoutDirection) { 4351 setFlags(layoutDirection, LAYOUT_DIRECTION_MASK); 4352 } 4353 4354 /** 4355 * Returns the resolved layout direction for this view. 4356 * 4357 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 4358 * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL. 4359 * 4360 * @hide 4361 */ 4362 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4363 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 4364 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 4365 }) 4366 public int getResolvedLayoutDirection() { 4367 resolveLayoutDirectionIfNeeded(); 4368 return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ? 4369 LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 4370 } 4371 4372 /** 4373 * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from 4374 * layout attribute and/or the inherited value from the parent.</p> 4375 * 4376 * @return true if the layout is right-to-left. 4377 * 4378 * @hide 4379 */ 4380 @ViewDebug.ExportedProperty(category = "layout") 4381 public boolean isLayoutRtl() { 4382 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 4383 } 4384 4385 /** 4386 * If this view doesn't do any drawing on its own, set this flag to 4387 * allow further optimizations. By default, this flag is not set on 4388 * View, but could be set on some View subclasses such as ViewGroup. 4389 * 4390 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 4391 * you should clear this flag. 4392 * 4393 * @param willNotDraw whether or not this View draw on its own 4394 */ 4395 public void setWillNotDraw(boolean willNotDraw) { 4396 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 4397 } 4398 4399 /** 4400 * Returns whether or not this View draws on its own. 4401 * 4402 * @return true if this view has nothing to draw, false otherwise 4403 */ 4404 @ViewDebug.ExportedProperty(category = "drawing") 4405 public boolean willNotDraw() { 4406 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 4407 } 4408 4409 /** 4410 * When a View's drawing cache is enabled, drawing is redirected to an 4411 * offscreen bitmap. Some views, like an ImageView, must be able to 4412 * bypass this mechanism if they already draw a single bitmap, to avoid 4413 * unnecessary usage of the memory. 4414 * 4415 * @param willNotCacheDrawing true if this view does not cache its 4416 * drawing, false otherwise 4417 */ 4418 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 4419 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 4420 } 4421 4422 /** 4423 * Returns whether or not this View can cache its drawing or not. 4424 * 4425 * @return true if this view does not cache its drawing, false otherwise 4426 */ 4427 @ViewDebug.ExportedProperty(category = "drawing") 4428 public boolean willNotCacheDrawing() { 4429 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 4430 } 4431 4432 /** 4433 * Indicates whether this view reacts to click events or not. 4434 * 4435 * @return true if the view is clickable, false otherwise 4436 * 4437 * @see #setClickable(boolean) 4438 * @attr ref android.R.styleable#View_clickable 4439 */ 4440 @ViewDebug.ExportedProperty 4441 public boolean isClickable() { 4442 return (mViewFlags & CLICKABLE) == CLICKABLE; 4443 } 4444 4445 /** 4446 * Enables or disables click events for this view. When a view 4447 * is clickable it will change its state to "pressed" on every click. 4448 * Subclasses should set the view clickable to visually react to 4449 * user's clicks. 4450 * 4451 * @param clickable true to make the view clickable, false otherwise 4452 * 4453 * @see #isClickable() 4454 * @attr ref android.R.styleable#View_clickable 4455 */ 4456 public void setClickable(boolean clickable) { 4457 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 4458 } 4459 4460 /** 4461 * Indicates whether this view reacts to long click events or not. 4462 * 4463 * @return true if the view is long clickable, false otherwise 4464 * 4465 * @see #setLongClickable(boolean) 4466 * @attr ref android.R.styleable#View_longClickable 4467 */ 4468 public boolean isLongClickable() { 4469 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 4470 } 4471 4472 /** 4473 * Enables or disables long click events for this view. When a view is long 4474 * clickable it reacts to the user holding down the button for a longer 4475 * duration than a tap. This event can either launch the listener or a 4476 * context menu. 4477 * 4478 * @param longClickable true to make the view long clickable, false otherwise 4479 * @see #isLongClickable() 4480 * @attr ref android.R.styleable#View_longClickable 4481 */ 4482 public void setLongClickable(boolean longClickable) { 4483 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 4484 } 4485 4486 /** 4487 * Sets the pressed state for this view. 4488 * 4489 * @see #isClickable() 4490 * @see #setClickable(boolean) 4491 * 4492 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 4493 * the View's internal state from a previously set "pressed" state. 4494 */ 4495 public void setPressed(boolean pressed) { 4496 if (pressed) { 4497 mPrivateFlags |= PRESSED; 4498 } else { 4499 mPrivateFlags &= ~PRESSED; 4500 } 4501 refreshDrawableState(); 4502 dispatchSetPressed(pressed); 4503 } 4504 4505 /** 4506 * Dispatch setPressed to all of this View's children. 4507 * 4508 * @see #setPressed(boolean) 4509 * 4510 * @param pressed The new pressed state 4511 */ 4512 protected void dispatchSetPressed(boolean pressed) { 4513 } 4514 4515 /** 4516 * Indicates whether the view is currently in pressed state. Unless 4517 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 4518 * the pressed state. 4519 * 4520 * @see #setPressed(boolean) 4521 * @see #isClickable() 4522 * @see #setClickable(boolean) 4523 * 4524 * @return true if the view is currently pressed, false otherwise 4525 */ 4526 public boolean isPressed() { 4527 return (mPrivateFlags & PRESSED) == PRESSED; 4528 } 4529 4530 /** 4531 * Indicates whether this view will save its state (that is, 4532 * whether its {@link #onSaveInstanceState} method will be called). 4533 * 4534 * @return Returns true if the view state saving is enabled, else false. 4535 * 4536 * @see #setSaveEnabled(boolean) 4537 * @attr ref android.R.styleable#View_saveEnabled 4538 */ 4539 public boolean isSaveEnabled() { 4540 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 4541 } 4542 4543 /** 4544 * Controls whether the saving of this view's state is 4545 * enabled (that is, whether its {@link #onSaveInstanceState} method 4546 * will be called). Note that even if freezing is enabled, the 4547 * view still must have an id assigned to it (via {@link #setId(int)}) 4548 * for its state to be saved. This flag can only disable the 4549 * saving of this view; any child views may still have their state saved. 4550 * 4551 * @param enabled Set to false to <em>disable</em> state saving, or true 4552 * (the default) to allow it. 4553 * 4554 * @see #isSaveEnabled() 4555 * @see #setId(int) 4556 * @see #onSaveInstanceState() 4557 * @attr ref android.R.styleable#View_saveEnabled 4558 */ 4559 public void setSaveEnabled(boolean enabled) { 4560 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 4561 } 4562 4563 /** 4564 * Gets whether the framework should discard touches when the view's 4565 * window is obscured by another visible window. 4566 * Refer to the {@link View} security documentation for more details. 4567 * 4568 * @return True if touch filtering is enabled. 4569 * 4570 * @see #setFilterTouchesWhenObscured(boolean) 4571 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4572 */ 4573 @ViewDebug.ExportedProperty 4574 public boolean getFilterTouchesWhenObscured() { 4575 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 4576 } 4577 4578 /** 4579 * Sets whether the framework should discard touches when the view's 4580 * window is obscured by another visible window. 4581 * Refer to the {@link View} security documentation for more details. 4582 * 4583 * @param enabled True if touch filtering should be enabled. 4584 * 4585 * @see #getFilterTouchesWhenObscured 4586 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4587 */ 4588 public void setFilterTouchesWhenObscured(boolean enabled) { 4589 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 4590 FILTER_TOUCHES_WHEN_OBSCURED); 4591 } 4592 4593 /** 4594 * Indicates whether the entire hierarchy under this view will save its 4595 * state when a state saving traversal occurs from its parent. The default 4596 * is true; if false, these views will not be saved unless 4597 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4598 * 4599 * @return Returns true if the view state saving from parent is enabled, else false. 4600 * 4601 * @see #setSaveFromParentEnabled(boolean) 4602 */ 4603 public boolean isSaveFromParentEnabled() { 4604 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 4605 } 4606 4607 /** 4608 * Controls whether the entire hierarchy under this view will save its 4609 * state when a state saving traversal occurs from its parent. The default 4610 * is true; if false, these views will not be saved unless 4611 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4612 * 4613 * @param enabled Set to false to <em>disable</em> state saving, or true 4614 * (the default) to allow it. 4615 * 4616 * @see #isSaveFromParentEnabled() 4617 * @see #setId(int) 4618 * @see #onSaveInstanceState() 4619 */ 4620 public void setSaveFromParentEnabled(boolean enabled) { 4621 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 4622 } 4623 4624 4625 /** 4626 * Returns whether this View is able to take focus. 4627 * 4628 * @return True if this view can take focus, or false otherwise. 4629 * @attr ref android.R.styleable#View_focusable 4630 */ 4631 @ViewDebug.ExportedProperty(category = "focus") 4632 public final boolean isFocusable() { 4633 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 4634 } 4635 4636 /** 4637 * When a view is focusable, it may not want to take focus when in touch mode. 4638 * For example, a button would like focus when the user is navigating via a D-pad 4639 * so that the user can click on it, but once the user starts touching the screen, 4640 * the button shouldn't take focus 4641 * @return Whether the view is focusable in touch mode. 4642 * @attr ref android.R.styleable#View_focusableInTouchMode 4643 */ 4644 @ViewDebug.ExportedProperty 4645 public final boolean isFocusableInTouchMode() { 4646 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 4647 } 4648 4649 /** 4650 * Find the nearest view in the specified direction that can take focus. 4651 * This does not actually give focus to that view. 4652 * 4653 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4654 * 4655 * @return The nearest focusable in the specified direction, or null if none 4656 * can be found. 4657 */ 4658 public View focusSearch(int direction) { 4659 if (mParent != null) { 4660 return mParent.focusSearch(this, direction); 4661 } else { 4662 return null; 4663 } 4664 } 4665 4666 /** 4667 * This method is the last chance for the focused view and its ancestors to 4668 * respond to an arrow key. This is called when the focused view did not 4669 * consume the key internally, nor could the view system find a new view in 4670 * the requested direction to give focus to. 4671 * 4672 * @param focused The currently focused view. 4673 * @param direction The direction focus wants to move. One of FOCUS_UP, 4674 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 4675 * @return True if the this view consumed this unhandled move. 4676 */ 4677 public boolean dispatchUnhandledMove(View focused, int direction) { 4678 return false; 4679 } 4680 4681 /** 4682 * If a user manually specified the next view id for a particular direction, 4683 * use the root to look up the view. 4684 * @param root The root view of the hierarchy containing this view. 4685 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 4686 * or FOCUS_BACKWARD. 4687 * @return The user specified next view, or null if there is none. 4688 */ 4689 View findUserSetNextFocus(View root, int direction) { 4690 switch (direction) { 4691 case FOCUS_LEFT: 4692 if (mNextFocusLeftId == View.NO_ID) return null; 4693 return findViewShouldExist(root, mNextFocusLeftId); 4694 case FOCUS_RIGHT: 4695 if (mNextFocusRightId == View.NO_ID) return null; 4696 return findViewShouldExist(root, mNextFocusRightId); 4697 case FOCUS_UP: 4698 if (mNextFocusUpId == View.NO_ID) return null; 4699 return findViewShouldExist(root, mNextFocusUpId); 4700 case FOCUS_DOWN: 4701 if (mNextFocusDownId == View.NO_ID) return null; 4702 return findViewShouldExist(root, mNextFocusDownId); 4703 case FOCUS_FORWARD: 4704 if (mNextFocusForwardId == View.NO_ID) return null; 4705 return findViewShouldExist(root, mNextFocusForwardId); 4706 case FOCUS_BACKWARD: { 4707 final int id = mID; 4708 return root.findViewByPredicate(new Predicate<View>() { 4709 @Override 4710 public boolean apply(View t) { 4711 return t.mNextFocusForwardId == id; 4712 } 4713 }); 4714 } 4715 } 4716 return null; 4717 } 4718 4719 private static View findViewShouldExist(View root, int childViewId) { 4720 View result = root.findViewById(childViewId); 4721 if (result == null) { 4722 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified " 4723 + "by user for id " + childViewId); 4724 } 4725 return result; 4726 } 4727 4728 /** 4729 * Find and return all focusable views that are descendants of this view, 4730 * possibly including this view if it is focusable itself. 4731 * 4732 * @param direction The direction of the focus 4733 * @return A list of focusable views 4734 */ 4735 public ArrayList<View> getFocusables(int direction) { 4736 ArrayList<View> result = new ArrayList<View>(24); 4737 addFocusables(result, direction); 4738 return result; 4739 } 4740 4741 /** 4742 * Add any focusable views that are descendants of this view (possibly 4743 * including this view if it is focusable itself) to views. If we are in touch mode, 4744 * only add views that are also focusable in touch mode. 4745 * 4746 * @param views Focusable views found so far 4747 * @param direction The direction of the focus 4748 */ 4749 public void addFocusables(ArrayList<View> views, int direction) { 4750 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 4751 } 4752 4753 /** 4754 * Adds any focusable views that are descendants of this view (possibly 4755 * including this view if it is focusable itself) to views. This method 4756 * adds all focusable views regardless if we are in touch mode or 4757 * only views focusable in touch mode if we are in touch mode depending on 4758 * the focusable mode paramater. 4759 * 4760 * @param views Focusable views found so far or null if all we are interested is 4761 * the number of focusables. 4762 * @param direction The direction of the focus. 4763 * @param focusableMode The type of focusables to be added. 4764 * 4765 * @see #FOCUSABLES_ALL 4766 * @see #FOCUSABLES_TOUCH_MODE 4767 */ 4768 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 4769 if (!isFocusable()) { 4770 return; 4771 } 4772 4773 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 4774 isInTouchMode() && !isFocusableInTouchMode()) { 4775 return; 4776 } 4777 4778 if (views != null) { 4779 views.add(this); 4780 } 4781 } 4782 4783 /** 4784 * Finds the Views that contain given text. The containment is case insensitive. 4785 * As View's text is considered any text content that View renders. 4786 * 4787 * @param outViews The output list of matching Views. 4788 * @param text The text to match against. 4789 */ 4790 public void findViewsWithText(ArrayList<View> outViews, CharSequence text) { 4791 } 4792 4793 /** 4794 * Find and return all touchable views that are descendants of this view, 4795 * possibly including this view if it is touchable itself. 4796 * 4797 * @return A list of touchable views 4798 */ 4799 public ArrayList<View> getTouchables() { 4800 ArrayList<View> result = new ArrayList<View>(); 4801 addTouchables(result); 4802 return result; 4803 } 4804 4805 /** 4806 * Add any touchable views that are descendants of this view (possibly 4807 * including this view if it is touchable itself) to views. 4808 * 4809 * @param views Touchable views found so far 4810 */ 4811 public void addTouchables(ArrayList<View> views) { 4812 final int viewFlags = mViewFlags; 4813 4814 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 4815 && (viewFlags & ENABLED_MASK) == ENABLED) { 4816 views.add(this); 4817 } 4818 } 4819 4820 /** 4821 * Call this to try to give focus to a specific view or to one of its 4822 * descendants. 4823 * 4824 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 4825 * false), or if it is focusable and it is not focusable in touch mode 4826 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 4827 * 4828 * See also {@link #focusSearch(int)}, which is what you call to say that you 4829 * have focus, and you want your parent to look for the next one. 4830 * 4831 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 4832 * {@link #FOCUS_DOWN} and <code>null</code>. 4833 * 4834 * @return Whether this view or one of its descendants actually took focus. 4835 */ 4836 public final boolean requestFocus() { 4837 return requestFocus(View.FOCUS_DOWN); 4838 } 4839 4840 4841 /** 4842 * Call this to try to give focus to a specific view or to one of its 4843 * descendants and give it a hint about what direction focus is heading. 4844 * 4845 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 4846 * false), or if it is focusable and it is not focusable in touch mode 4847 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 4848 * 4849 * See also {@link #focusSearch(int)}, which is what you call to say that you 4850 * have focus, and you want your parent to look for the next one. 4851 * 4852 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 4853 * <code>null</code> set for the previously focused rectangle. 4854 * 4855 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4856 * @return Whether this view or one of its descendants actually took focus. 4857 */ 4858 public final boolean requestFocus(int direction) { 4859 return requestFocus(direction, null); 4860 } 4861 4862 /** 4863 * Call this to try to give focus to a specific view or to one of its descendants 4864 * and give it hints about the direction and a specific rectangle that the focus 4865 * is coming from. The rectangle can help give larger views a finer grained hint 4866 * about where focus is coming from, and therefore, where to show selection, or 4867 * forward focus change internally. 4868 * 4869 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 4870 * false), or if it is focusable and it is not focusable in touch mode 4871 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 4872 * 4873 * A View will not take focus if it is not visible. 4874 * 4875 * A View will not take focus if one of its parents has 4876 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 4877 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 4878 * 4879 * See also {@link #focusSearch(int)}, which is what you call to say that you 4880 * have focus, and you want your parent to look for the next one. 4881 * 4882 * You may wish to override this method if your custom {@link View} has an internal 4883 * {@link View} that it wishes to forward the request to. 4884 * 4885 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4886 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 4887 * to give a finer grained hint about where focus is coming from. May be null 4888 * if there is no hint. 4889 * @return Whether this view or one of its descendants actually took focus. 4890 */ 4891 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 4892 // need to be focusable 4893 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 4894 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 4895 return false; 4896 } 4897 4898 // need to be focusable in touch mode if in touch mode 4899 if (isInTouchMode() && 4900 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 4901 return false; 4902 } 4903 4904 // need to not have any parents blocking us 4905 if (hasAncestorThatBlocksDescendantFocus()) { 4906 return false; 4907 } 4908 4909 handleFocusGainInternal(direction, previouslyFocusedRect); 4910 return true; 4911 } 4912 4913 /** Gets the ViewAncestor, or null if not attached. */ 4914 /*package*/ ViewAncestor getViewAncestor() { 4915 View root = getRootView(); 4916 return root != null ? (ViewAncestor)root.getParent() : null; 4917 } 4918 4919 /** 4920 * Call this to try to give focus to a specific view or to one of its descendants. This is a 4921 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 4922 * touch mode to request focus when they are touched. 4923 * 4924 * @return Whether this view or one of its descendants actually took focus. 4925 * 4926 * @see #isInTouchMode() 4927 * 4928 */ 4929 public final boolean requestFocusFromTouch() { 4930 // Leave touch mode if we need to 4931 if (isInTouchMode()) { 4932 ViewAncestor viewRoot = getViewAncestor(); 4933 if (viewRoot != null) { 4934 viewRoot.ensureTouchMode(false); 4935 } 4936 } 4937 return requestFocus(View.FOCUS_DOWN); 4938 } 4939 4940 /** 4941 * @return Whether any ancestor of this view blocks descendant focus. 4942 */ 4943 private boolean hasAncestorThatBlocksDescendantFocus() { 4944 ViewParent ancestor = mParent; 4945 while (ancestor instanceof ViewGroup) { 4946 final ViewGroup vgAncestor = (ViewGroup) ancestor; 4947 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 4948 return true; 4949 } else { 4950 ancestor = vgAncestor.getParent(); 4951 } 4952 } 4953 return false; 4954 } 4955 4956 /** 4957 * @hide 4958 */ 4959 public void dispatchStartTemporaryDetach() { 4960 onStartTemporaryDetach(); 4961 } 4962 4963 /** 4964 * This is called when a container is going to temporarily detach a child, with 4965 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 4966 * It will either be followed by {@link #onFinishTemporaryDetach()} or 4967 * {@link #onDetachedFromWindow()} when the container is done. 4968 */ 4969 public void onStartTemporaryDetach() { 4970 removeUnsetPressCallback(); 4971 mPrivateFlags |= CANCEL_NEXT_UP_EVENT; 4972 } 4973 4974 /** 4975 * @hide 4976 */ 4977 public void dispatchFinishTemporaryDetach() { 4978 onFinishTemporaryDetach(); 4979 } 4980 4981 /** 4982 * Called after {@link #onStartTemporaryDetach} when the container is done 4983 * changing the view. 4984 */ 4985 public void onFinishTemporaryDetach() { 4986 } 4987 4988 /** 4989 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 4990 * for this view's window. Returns null if the view is not currently attached 4991 * to the window. Normally you will not need to use this directly, but 4992 * just use the standard high-level event callbacks like 4993 * {@link #onKeyDown(int, KeyEvent)}. 4994 */ 4995 public KeyEvent.DispatcherState getKeyDispatcherState() { 4996 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 4997 } 4998 4999 /** 5000 * Dispatch a key event before it is processed by any input method 5001 * associated with the view hierarchy. This can be used to intercept 5002 * key events in special situations before the IME consumes them; a 5003 * typical example would be handling the BACK key to update the application's 5004 * UI instead of allowing the IME to see it and close itself. 5005 * 5006 * @param event The key event to be dispatched. 5007 * @return True if the event was handled, false otherwise. 5008 */ 5009 public boolean dispatchKeyEventPreIme(KeyEvent event) { 5010 return onKeyPreIme(event.getKeyCode(), event); 5011 } 5012 5013 /** 5014 * Dispatch a key event to the next view on the focus path. This path runs 5015 * from the top of the view tree down to the currently focused view. If this 5016 * view has focus, it will dispatch to itself. Otherwise it will dispatch 5017 * the next node down the focus path. This method also fires any key 5018 * listeners. 5019 * 5020 * @param event The key event to be dispatched. 5021 * @return True if the event was handled, false otherwise. 5022 */ 5023 public boolean dispatchKeyEvent(KeyEvent event) { 5024 if (mInputEventConsistencyVerifier != null) { 5025 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 5026 } 5027 5028 // Give any attached key listener a first crack at the event. 5029 //noinspection SimplifiableIfStatement 5030 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5031 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 5032 return true; 5033 } 5034 5035 if (event.dispatch(this, mAttachInfo != null 5036 ? mAttachInfo.mKeyDispatchState : null, this)) { 5037 return true; 5038 } 5039 5040 if (mInputEventConsistencyVerifier != null) { 5041 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5042 } 5043 return false; 5044 } 5045 5046 /** 5047 * Dispatches a key shortcut event. 5048 * 5049 * @param event The key event to be dispatched. 5050 * @return True if the event was handled by the view, false otherwise. 5051 */ 5052 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 5053 return onKeyShortcut(event.getKeyCode(), event); 5054 } 5055 5056 /** 5057 * Pass the touch screen motion event down to the target view, or this 5058 * view if it is the target. 5059 * 5060 * @param event The motion event to be dispatched. 5061 * @return True if the event was handled by the view, false otherwise. 5062 */ 5063 public boolean dispatchTouchEvent(MotionEvent event) { 5064 if (mInputEventConsistencyVerifier != null) { 5065 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 5066 } 5067 5068 if (onFilterTouchEventForSecurity(event)) { 5069 //noinspection SimplifiableIfStatement 5070 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && 5071 mOnTouchListener.onTouch(this, event)) { 5072 return true; 5073 } 5074 5075 if (onTouchEvent(event)) { 5076 return true; 5077 } 5078 } 5079 5080 if (mInputEventConsistencyVerifier != null) { 5081 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5082 } 5083 return false; 5084 } 5085 5086 /** 5087 * Filter the touch event to apply security policies. 5088 * 5089 * @param event The motion event to be filtered. 5090 * @return True if the event should be dispatched, false if the event should be dropped. 5091 * 5092 * @see #getFilterTouchesWhenObscured 5093 */ 5094 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 5095 //noinspection RedundantIfStatement 5096 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 5097 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 5098 // Window is obscured, drop this touch. 5099 return false; 5100 } 5101 return true; 5102 } 5103 5104 /** 5105 * Pass a trackball motion event down to the focused view. 5106 * 5107 * @param event The motion event to be dispatched. 5108 * @return True if the event was handled by the view, false otherwise. 5109 */ 5110 public boolean dispatchTrackballEvent(MotionEvent event) { 5111 if (mInputEventConsistencyVerifier != null) { 5112 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 5113 } 5114 5115 //Log.i("view", "view=" + this + ", " + event.toString()); 5116 if (onTrackballEvent(event)) { 5117 return true; 5118 } 5119 5120 if (mInputEventConsistencyVerifier != null) { 5121 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5122 } 5123 return false; 5124 } 5125 5126 /** 5127 * Dispatch a generic motion event. 5128 * <p> 5129 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5130 * are delivered to the view under the pointer. All other generic motion events are 5131 * delivered to the focused view. Hover events are handled specially and are delivered 5132 * to {@link #onHoverEvent(MotionEvent)}. 5133 * </p> 5134 * 5135 * @param event The motion event to be dispatched. 5136 * @return True if the event was handled by the view, false otherwise. 5137 */ 5138 public boolean dispatchGenericMotionEvent(MotionEvent event) { 5139 if (mInputEventConsistencyVerifier != null) { 5140 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 5141 } 5142 5143 final int source = event.getSource(); 5144 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5145 final int action = event.getAction(); 5146 if (action == MotionEvent.ACTION_HOVER_ENTER 5147 || action == MotionEvent.ACTION_HOVER_MOVE 5148 || action == MotionEvent.ACTION_HOVER_EXIT) { 5149 if (dispatchHoverEvent(event)) { 5150 return true; 5151 } 5152 } else if (dispatchGenericPointerEvent(event)) { 5153 return true; 5154 } 5155 } else if (dispatchGenericFocusedEvent(event)) { 5156 return true; 5157 } 5158 5159 //noinspection SimplifiableIfStatement 5160 if (mOnGenericMotionListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5161 && mOnGenericMotionListener.onGenericMotion(this, event)) { 5162 return true; 5163 } 5164 5165 if (onGenericMotionEvent(event)) { 5166 return true; 5167 } 5168 5169 if (mInputEventConsistencyVerifier != null) { 5170 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5171 } 5172 return false; 5173 } 5174 5175 /** 5176 * Dispatch a hover event. 5177 * <p> 5178 * Do not call this method directly. 5179 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5180 * </p> 5181 * 5182 * @param event The motion event to be dispatched. 5183 * @return True if the event was handled by the view, false otherwise. 5184 * @hide 5185 */ 5186 protected boolean dispatchHoverEvent(MotionEvent event) { 5187 return onHoverEvent(event); 5188 } 5189 5190 /** 5191 * Dispatch a generic motion event to the view under the first pointer. 5192 * <p> 5193 * Do not call this method directly. 5194 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5195 * </p> 5196 * 5197 * @param event The motion event to be dispatched. 5198 * @return True if the event was handled by the view, false otherwise. 5199 * @hide 5200 */ 5201 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 5202 return false; 5203 } 5204 5205 /** 5206 * Dispatch a generic motion event to the currently focused view. 5207 * <p> 5208 * Do not call this method directly. 5209 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5210 * </p> 5211 * 5212 * @param event The motion event to be dispatched. 5213 * @return True if the event was handled by the view, false otherwise. 5214 * @hide 5215 */ 5216 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 5217 return false; 5218 } 5219 5220 /** 5221 * Dispatch a pointer event. 5222 * <p> 5223 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 5224 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 5225 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 5226 * and should not be expected to handle other pointing device features. 5227 * </p> 5228 * 5229 * @param event The motion event to be dispatched. 5230 * @return True if the event was handled by the view, false otherwise. 5231 * @hide 5232 */ 5233 public final boolean dispatchPointerEvent(MotionEvent event) { 5234 if (event.isTouchEvent()) { 5235 return dispatchTouchEvent(event); 5236 } else { 5237 return dispatchGenericMotionEvent(event); 5238 } 5239 } 5240 5241 /** 5242 * Called when the window containing this view gains or loses window focus. 5243 * ViewGroups should override to route to their children. 5244 * 5245 * @param hasFocus True if the window containing this view now has focus, 5246 * false otherwise. 5247 */ 5248 public void dispatchWindowFocusChanged(boolean hasFocus) { 5249 onWindowFocusChanged(hasFocus); 5250 } 5251 5252 /** 5253 * Called when the window containing this view gains or loses focus. Note 5254 * that this is separate from view focus: to receive key events, both 5255 * your view and its window must have focus. If a window is displayed 5256 * on top of yours that takes input focus, then your own window will lose 5257 * focus but the view focus will remain unchanged. 5258 * 5259 * @param hasWindowFocus True if the window containing this view now has 5260 * focus, false otherwise. 5261 */ 5262 public void onWindowFocusChanged(boolean hasWindowFocus) { 5263 InputMethodManager imm = InputMethodManager.peekInstance(); 5264 if (!hasWindowFocus) { 5265 if (isPressed()) { 5266 setPressed(false); 5267 } 5268 if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5269 imm.focusOut(this); 5270 } 5271 removeLongPressCallback(); 5272 removeTapCallback(); 5273 onFocusLost(); 5274 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5275 imm.focusIn(this); 5276 } 5277 refreshDrawableState(); 5278 } 5279 5280 /** 5281 * Returns true if this view is in a window that currently has window focus. 5282 * Note that this is not the same as the view itself having focus. 5283 * 5284 * @return True if this view is in a window that currently has window focus. 5285 */ 5286 public boolean hasWindowFocus() { 5287 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 5288 } 5289 5290 /** 5291 * Dispatch a view visibility change down the view hierarchy. 5292 * ViewGroups should override to route to their children. 5293 * @param changedView The view whose visibility changed. Could be 'this' or 5294 * an ancestor view. 5295 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5296 * {@link #INVISIBLE} or {@link #GONE}. 5297 */ 5298 protected void dispatchVisibilityChanged(View changedView, int visibility) { 5299 onVisibilityChanged(changedView, visibility); 5300 } 5301 5302 /** 5303 * Called when the visibility of the view or an ancestor of the view is changed. 5304 * @param changedView The view whose visibility changed. Could be 'this' or 5305 * an ancestor view. 5306 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5307 * {@link #INVISIBLE} or {@link #GONE}. 5308 */ 5309 protected void onVisibilityChanged(View changedView, int visibility) { 5310 if (visibility == VISIBLE) { 5311 if (mAttachInfo != null) { 5312 initialAwakenScrollBars(); 5313 } else { 5314 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH; 5315 } 5316 } 5317 } 5318 5319 /** 5320 * Dispatch a hint about whether this view is displayed. For instance, when 5321 * a View moves out of the screen, it might receives a display hint indicating 5322 * the view is not displayed. Applications should not <em>rely</em> on this hint 5323 * as there is no guarantee that they will receive one. 5324 * 5325 * @param hint A hint about whether or not this view is displayed: 5326 * {@link #VISIBLE} or {@link #INVISIBLE}. 5327 */ 5328 public void dispatchDisplayHint(int hint) { 5329 onDisplayHint(hint); 5330 } 5331 5332 /** 5333 * Gives this view a hint about whether is displayed or not. For instance, when 5334 * a View moves out of the screen, it might receives a display hint indicating 5335 * the view is not displayed. Applications should not <em>rely</em> on this hint 5336 * as there is no guarantee that they will receive one. 5337 * 5338 * @param hint A hint about whether or not this view is displayed: 5339 * {@link #VISIBLE} or {@link #INVISIBLE}. 5340 */ 5341 protected void onDisplayHint(int hint) { 5342 } 5343 5344 /** 5345 * Dispatch a window visibility change down the view hierarchy. 5346 * ViewGroups should override to route to their children. 5347 * 5348 * @param visibility The new visibility of the window. 5349 * 5350 * @see #onWindowVisibilityChanged(int) 5351 */ 5352 public void dispatchWindowVisibilityChanged(int visibility) { 5353 onWindowVisibilityChanged(visibility); 5354 } 5355 5356 /** 5357 * Called when the window containing has change its visibility 5358 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 5359 * that this tells you whether or not your window is being made visible 5360 * to the window manager; this does <em>not</em> tell you whether or not 5361 * your window is obscured by other windows on the screen, even if it 5362 * is itself visible. 5363 * 5364 * @param visibility The new visibility of the window. 5365 */ 5366 protected void onWindowVisibilityChanged(int visibility) { 5367 if (visibility == VISIBLE) { 5368 initialAwakenScrollBars(); 5369 } 5370 } 5371 5372 /** 5373 * Returns the current visibility of the window this view is attached to 5374 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 5375 * 5376 * @return Returns the current visibility of the view's window. 5377 */ 5378 public int getWindowVisibility() { 5379 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 5380 } 5381 5382 /** 5383 * Retrieve the overall visible display size in which the window this view is 5384 * attached to has been positioned in. This takes into account screen 5385 * decorations above the window, for both cases where the window itself 5386 * is being position inside of them or the window is being placed under 5387 * then and covered insets are used for the window to position its content 5388 * inside. In effect, this tells you the available area where content can 5389 * be placed and remain visible to users. 5390 * 5391 * <p>This function requires an IPC back to the window manager to retrieve 5392 * the requested information, so should not be used in performance critical 5393 * code like drawing. 5394 * 5395 * @param outRect Filled in with the visible display frame. If the view 5396 * is not attached to a window, this is simply the raw display size. 5397 */ 5398 public void getWindowVisibleDisplayFrame(Rect outRect) { 5399 if (mAttachInfo != null) { 5400 try { 5401 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 5402 } catch (RemoteException e) { 5403 return; 5404 } 5405 // XXX This is really broken, and probably all needs to be done 5406 // in the window manager, and we need to know more about whether 5407 // we want the area behind or in front of the IME. 5408 final Rect insets = mAttachInfo.mVisibleInsets; 5409 outRect.left += insets.left; 5410 outRect.top += insets.top; 5411 outRect.right -= insets.right; 5412 outRect.bottom -= insets.bottom; 5413 return; 5414 } 5415 Display d = WindowManagerImpl.getDefault().getDefaultDisplay(); 5416 d.getRectSize(outRect); 5417 } 5418 5419 /** 5420 * Dispatch a notification about a resource configuration change down 5421 * the view hierarchy. 5422 * ViewGroups should override to route to their children. 5423 * 5424 * @param newConfig The new resource configuration. 5425 * 5426 * @see #onConfigurationChanged(android.content.res.Configuration) 5427 */ 5428 public void dispatchConfigurationChanged(Configuration newConfig) { 5429 onConfigurationChanged(newConfig); 5430 } 5431 5432 /** 5433 * Called when the current configuration of the resources being used 5434 * by the application have changed. You can use this to decide when 5435 * to reload resources that can changed based on orientation and other 5436 * configuration characterstics. You only need to use this if you are 5437 * not relying on the normal {@link android.app.Activity} mechanism of 5438 * recreating the activity instance upon a configuration change. 5439 * 5440 * @param newConfig The new resource configuration. 5441 */ 5442 protected void onConfigurationChanged(Configuration newConfig) { 5443 } 5444 5445 /** 5446 * Private function to aggregate all per-view attributes in to the view 5447 * root. 5448 */ 5449 void dispatchCollectViewAttributes(int visibility) { 5450 performCollectViewAttributes(visibility); 5451 } 5452 5453 void performCollectViewAttributes(int visibility) { 5454 if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) { 5455 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 5456 mAttachInfo.mKeepScreenOn = true; 5457 } 5458 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility; 5459 if (mOnSystemUiVisibilityChangeListener != null) { 5460 mAttachInfo.mHasSystemUiListeners = true; 5461 } 5462 } 5463 } 5464 5465 void needGlobalAttributesUpdate(boolean force) { 5466 final AttachInfo ai = mAttachInfo; 5467 if (ai != null) { 5468 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 5469 || ai.mHasSystemUiListeners) { 5470 ai.mRecomputeGlobalAttributes = true; 5471 } 5472 } 5473 } 5474 5475 /** 5476 * Returns whether the device is currently in touch mode. Touch mode is entered 5477 * once the user begins interacting with the device by touch, and affects various 5478 * things like whether focus is always visible to the user. 5479 * 5480 * @return Whether the device is in touch mode. 5481 */ 5482 @ViewDebug.ExportedProperty 5483 public boolean isInTouchMode() { 5484 if (mAttachInfo != null) { 5485 return mAttachInfo.mInTouchMode; 5486 } else { 5487 return ViewAncestor.isInTouchMode(); 5488 } 5489 } 5490 5491 /** 5492 * Returns the context the view is running in, through which it can 5493 * access the current theme, resources, etc. 5494 * 5495 * @return The view's Context. 5496 */ 5497 @ViewDebug.CapturedViewProperty 5498 public final Context getContext() { 5499 return mContext; 5500 } 5501 5502 /** 5503 * Handle a key event before it is processed by any input method 5504 * associated with the view hierarchy. This can be used to intercept 5505 * key events in special situations before the IME consumes them; a 5506 * typical example would be handling the BACK key to update the application's 5507 * UI instead of allowing the IME to see it and close itself. 5508 * 5509 * @param keyCode The value in event.getKeyCode(). 5510 * @param event Description of the key event. 5511 * @return If you handled the event, return true. If you want to allow the 5512 * event to be handled by the next receiver, return false. 5513 */ 5514 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 5515 return false; 5516 } 5517 5518 /** 5519 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 5520 * KeyEvent.Callback.onKeyDown()}: perform press of the view 5521 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 5522 * is released, if the view is enabled and clickable. 5523 * 5524 * @param keyCode A key code that represents the button pressed, from 5525 * {@link android.view.KeyEvent}. 5526 * @param event The KeyEvent object that defines the button action. 5527 */ 5528 public boolean onKeyDown(int keyCode, KeyEvent event) { 5529 boolean result = false; 5530 5531 switch (keyCode) { 5532 case KeyEvent.KEYCODE_DPAD_CENTER: 5533 case KeyEvent.KEYCODE_ENTER: { 5534 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5535 return true; 5536 } 5537 // Long clickable items don't necessarily have to be clickable 5538 if (((mViewFlags & CLICKABLE) == CLICKABLE || 5539 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 5540 (event.getRepeatCount() == 0)) { 5541 setPressed(true); 5542 checkForLongClick(0); 5543 return true; 5544 } 5545 break; 5546 } 5547 } 5548 return result; 5549 } 5550 5551 /** 5552 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 5553 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 5554 * the event). 5555 */ 5556 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 5557 return false; 5558 } 5559 5560 /** 5561 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 5562 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 5563 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 5564 * {@link KeyEvent#KEYCODE_ENTER} is released. 5565 * 5566 * @param keyCode A key code that represents the button pressed, from 5567 * {@link android.view.KeyEvent}. 5568 * @param event The KeyEvent object that defines the button action. 5569 */ 5570 public boolean onKeyUp(int keyCode, KeyEvent event) { 5571 boolean result = false; 5572 5573 switch (keyCode) { 5574 case KeyEvent.KEYCODE_DPAD_CENTER: 5575 case KeyEvent.KEYCODE_ENTER: { 5576 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5577 return true; 5578 } 5579 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 5580 setPressed(false); 5581 5582 if (!mHasPerformedLongPress) { 5583 // This is a tap, so remove the longpress check 5584 removeLongPressCallback(); 5585 5586 result = performClick(); 5587 } 5588 } 5589 break; 5590 } 5591 } 5592 return result; 5593 } 5594 5595 /** 5596 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 5597 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 5598 * the event). 5599 * 5600 * @param keyCode A key code that represents the button pressed, from 5601 * {@link android.view.KeyEvent}. 5602 * @param repeatCount The number of times the action was made. 5603 * @param event The KeyEvent object that defines the button action. 5604 */ 5605 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 5606 return false; 5607 } 5608 5609 /** 5610 * Called on the focused view when a key shortcut event is not handled. 5611 * Override this method to implement local key shortcuts for the View. 5612 * Key shortcuts can also be implemented by setting the 5613 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 5614 * 5615 * @param keyCode The value in event.getKeyCode(). 5616 * @param event Description of the key event. 5617 * @return If you handled the event, return true. If you want to allow the 5618 * event to be handled by the next receiver, return false. 5619 */ 5620 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 5621 return false; 5622 } 5623 5624 /** 5625 * Check whether the called view is a text editor, in which case it 5626 * would make sense to automatically display a soft input window for 5627 * it. Subclasses should override this if they implement 5628 * {@link #onCreateInputConnection(EditorInfo)} to return true if 5629 * a call on that method would return a non-null InputConnection, and 5630 * they are really a first-class editor that the user would normally 5631 * start typing on when the go into a window containing your view. 5632 * 5633 * <p>The default implementation always returns false. This does 5634 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 5635 * will not be called or the user can not otherwise perform edits on your 5636 * view; it is just a hint to the system that this is not the primary 5637 * purpose of this view. 5638 * 5639 * @return Returns true if this view is a text editor, else false. 5640 */ 5641 public boolean onCheckIsTextEditor() { 5642 return false; 5643 } 5644 5645 /** 5646 * Create a new InputConnection for an InputMethod to interact 5647 * with the view. The default implementation returns null, since it doesn't 5648 * support input methods. You can override this to implement such support. 5649 * This is only needed for views that take focus and text input. 5650 * 5651 * <p>When implementing this, you probably also want to implement 5652 * {@link #onCheckIsTextEditor()} to indicate you will return a 5653 * non-null InputConnection. 5654 * 5655 * @param outAttrs Fill in with attribute information about the connection. 5656 */ 5657 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 5658 return null; 5659 } 5660 5661 /** 5662 * Called by the {@link android.view.inputmethod.InputMethodManager} 5663 * when a view who is not the current 5664 * input connection target is trying to make a call on the manager. The 5665 * default implementation returns false; you can override this to return 5666 * true for certain views if you are performing InputConnection proxying 5667 * to them. 5668 * @param view The View that is making the InputMethodManager call. 5669 * @return Return true to allow the call, false to reject. 5670 */ 5671 public boolean checkInputConnectionProxy(View view) { 5672 return false; 5673 } 5674 5675 /** 5676 * Show the context menu for this view. It is not safe to hold on to the 5677 * menu after returning from this method. 5678 * 5679 * You should normally not overload this method. Overload 5680 * {@link #onCreateContextMenu(ContextMenu)} or define an 5681 * {@link OnCreateContextMenuListener} to add items to the context menu. 5682 * 5683 * @param menu The context menu to populate 5684 */ 5685 public void createContextMenu(ContextMenu menu) { 5686 ContextMenuInfo menuInfo = getContextMenuInfo(); 5687 5688 // Sets the current menu info so all items added to menu will have 5689 // my extra info set. 5690 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 5691 5692 onCreateContextMenu(menu); 5693 if (mOnCreateContextMenuListener != null) { 5694 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 5695 } 5696 5697 // Clear the extra information so subsequent items that aren't mine don't 5698 // have my extra info. 5699 ((MenuBuilder)menu).setCurrentMenuInfo(null); 5700 5701 if (mParent != null) { 5702 mParent.createContextMenu(menu); 5703 } 5704 } 5705 5706 /** 5707 * Views should implement this if they have extra information to associate 5708 * with the context menu. The return result is supplied as a parameter to 5709 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 5710 * callback. 5711 * 5712 * @return Extra information about the item for which the context menu 5713 * should be shown. This information will vary across different 5714 * subclasses of View. 5715 */ 5716 protected ContextMenuInfo getContextMenuInfo() { 5717 return null; 5718 } 5719 5720 /** 5721 * Views should implement this if the view itself is going to add items to 5722 * the context menu. 5723 * 5724 * @param menu the context menu to populate 5725 */ 5726 protected void onCreateContextMenu(ContextMenu menu) { 5727 } 5728 5729 /** 5730 * Implement this method to handle trackball motion events. The 5731 * <em>relative</em> movement of the trackball since the last event 5732 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 5733 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 5734 * that a movement of 1 corresponds to the user pressing one DPAD key (so 5735 * they will often be fractional values, representing the more fine-grained 5736 * movement information available from a trackball). 5737 * 5738 * @param event The motion event. 5739 * @return True if the event was handled, false otherwise. 5740 */ 5741 public boolean onTrackballEvent(MotionEvent event) { 5742 return false; 5743 } 5744 5745 /** 5746 * Implement this method to handle generic motion events. 5747 * <p> 5748 * Generic motion events describe joystick movements, mouse hovers, track pad 5749 * touches, scroll wheel movements and other input events. The 5750 * {@link MotionEvent#getSource() source} of the motion event specifies 5751 * the class of input that was received. Implementations of this method 5752 * must examine the bits in the source before processing the event. 5753 * The following code example shows how this is done. 5754 * </p><p> 5755 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5756 * are delivered to the view under the pointer. All other generic motion events are 5757 * delivered to the focused view. 5758 * </p> 5759 * <code> 5760 * public boolean onGenericMotionEvent(MotionEvent event) { 5761 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 5762 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 5763 * // process the joystick movement... 5764 * return true; 5765 * } 5766 * } 5767 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5768 * switch (event.getAction()) { 5769 * case MotionEvent.ACTION_HOVER_MOVE: 5770 * // process the mouse hover movement... 5771 * return true; 5772 * case MotionEvent.ACTION_SCROLL: 5773 * // process the scroll wheel movement... 5774 * return true; 5775 * } 5776 * } 5777 * return super.onGenericMotionEvent(event); 5778 * } 5779 * </code> 5780 * 5781 * @param event The generic motion event being processed. 5782 * @return True if the event was handled, false otherwise. 5783 */ 5784 public boolean onGenericMotionEvent(MotionEvent event) { 5785 return false; 5786 } 5787 5788 /** 5789 * Implement this method to handle hover events. 5790 * <p> 5791 * Hover events are pointer events with action {@link MotionEvent#ACTION_HOVER_ENTER}, 5792 * {@link MotionEvent#ACTION_HOVER_MOVE}, or {@link MotionEvent#ACTION_HOVER_EXIT}. 5793 * </p><p> 5794 * The view receives hover enter as the pointer enters the bounds of the view and hover 5795 * exit as the pointer exits the bound of the view or just before the pointer goes down 5796 * (which implies that {@link #onTouchEvent(MotionEvent)} will be called soon). 5797 * </p><p> 5798 * If the view would like to handle the hover event itself and prevent its children 5799 * from receiving hover, it should return true from this method. If this method returns 5800 * true and a child has already received a hover enter event, the child will 5801 * automatically receive a hover exit event. 5802 * </p><p> 5803 * The default implementation sets the hovered state of the view if the view is 5804 * clickable. 5805 * </p> 5806 * 5807 * @param event The motion event that describes the hover. 5808 * @return True if this view handled the hover event and does not want its children 5809 * to receive the hover event. 5810 */ 5811 public boolean onHoverEvent(MotionEvent event) { 5812 switch (event.getAction()) { 5813 case MotionEvent.ACTION_HOVER_ENTER: 5814 setHovered(true); 5815 break; 5816 5817 case MotionEvent.ACTION_HOVER_EXIT: 5818 setHovered(false); 5819 break; 5820 } 5821 5822 return false; 5823 } 5824 5825 /** 5826 * Returns true if the view is currently hovered. 5827 * 5828 * @return True if the view is currently hovered. 5829 */ 5830 public boolean isHovered() { 5831 return (mPrivateFlags & HOVERED) != 0; 5832 } 5833 5834 /** 5835 * Sets whether the view is currently hovered. 5836 * 5837 * @param hovered True if the view is hovered. 5838 */ 5839 public void setHovered(boolean hovered) { 5840 if (hovered) { 5841 if ((mPrivateFlags & HOVERED) == 0) { 5842 mPrivateFlags |= HOVERED; 5843 refreshDrawableState(); 5844 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 5845 } 5846 } else { 5847 if ((mPrivateFlags & HOVERED) != 0) { 5848 mPrivateFlags &= ~HOVERED; 5849 refreshDrawableState(); 5850 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 5851 } 5852 } 5853 } 5854 5855 /** 5856 * Implement this method to handle touch screen motion events. 5857 * 5858 * @param event The motion event. 5859 * @return True if the event was handled, false otherwise. 5860 */ 5861 public boolean onTouchEvent(MotionEvent event) { 5862 final int viewFlags = mViewFlags; 5863 5864 if ((viewFlags & ENABLED_MASK) == DISABLED) { 5865 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) { 5866 mPrivateFlags &= ~PRESSED; 5867 refreshDrawableState(); 5868 } 5869 // A disabled view that is clickable still consumes the touch 5870 // events, it just doesn't respond to them. 5871 return (((viewFlags & CLICKABLE) == CLICKABLE || 5872 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 5873 } 5874 5875 if (mTouchDelegate != null) { 5876 if (mTouchDelegate.onTouchEvent(event)) { 5877 return true; 5878 } 5879 } 5880 5881 if (((viewFlags & CLICKABLE) == CLICKABLE || 5882 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 5883 switch (event.getAction()) { 5884 case MotionEvent.ACTION_UP: 5885 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; 5886 if ((mPrivateFlags & PRESSED) != 0 || prepressed) { 5887 // take focus if we don't have it already and we should in 5888 // touch mode. 5889 boolean focusTaken = false; 5890 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 5891 focusTaken = requestFocus(); 5892 } 5893 5894 if (prepressed) { 5895 // The button is being released before we actually 5896 // showed it as pressed. Make it show the pressed 5897 // state now (before scheduling the click) to ensure 5898 // the user sees it. 5899 mPrivateFlags |= PRESSED; 5900 refreshDrawableState(); 5901 } 5902 5903 if (!mHasPerformedLongPress) { 5904 // This is a tap, so remove the longpress check 5905 removeLongPressCallback(); 5906 5907 // Only perform take click actions if we were in the pressed state 5908 if (!focusTaken) { 5909 // Use a Runnable and post this rather than calling 5910 // performClick directly. This lets other visual state 5911 // of the view update before click actions start. 5912 if (mPerformClick == null) { 5913 mPerformClick = new PerformClick(); 5914 } 5915 if (!post(mPerformClick)) { 5916 performClick(); 5917 } 5918 } 5919 } 5920 5921 if (mUnsetPressedState == null) { 5922 mUnsetPressedState = new UnsetPressedState(); 5923 } 5924 5925 if (prepressed) { 5926 postDelayed(mUnsetPressedState, 5927 ViewConfiguration.getPressedStateDuration()); 5928 } else if (!post(mUnsetPressedState)) { 5929 // If the post failed, unpress right now 5930 mUnsetPressedState.run(); 5931 } 5932 removeTapCallback(); 5933 } 5934 break; 5935 5936 case MotionEvent.ACTION_DOWN: 5937 mHasPerformedLongPress = false; 5938 5939 if (performButtonActionOnTouchDown(event)) { 5940 break; 5941 } 5942 5943 // Walk up the hierarchy to determine if we're inside a scrolling container. 5944 boolean isInScrollingContainer = false; 5945 ViewParent p = getParent(); 5946 while (p != null && p instanceof ViewGroup) { 5947 if (((ViewGroup) p).shouldDelayChildPressedState()) { 5948 isInScrollingContainer = true; 5949 break; 5950 } 5951 p = p.getParent(); 5952 } 5953 5954 // For views inside a scrolling container, delay the pressed feedback for 5955 // a short period in case this is a scroll. 5956 if (isInScrollingContainer) { 5957 mPrivateFlags |= PREPRESSED; 5958 if (mPendingCheckForTap == null) { 5959 mPendingCheckForTap = new CheckForTap(); 5960 } 5961 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 5962 } else { 5963 // Not inside a scrolling container, so show the feedback right away 5964 mPrivateFlags |= PRESSED; 5965 refreshDrawableState(); 5966 checkForLongClick(0); 5967 } 5968 break; 5969 5970 case MotionEvent.ACTION_CANCEL: 5971 mPrivateFlags &= ~PRESSED; 5972 refreshDrawableState(); 5973 removeTapCallback(); 5974 break; 5975 5976 case MotionEvent.ACTION_MOVE: 5977 final int x = (int) event.getX(); 5978 final int y = (int) event.getY(); 5979 5980 // Be lenient about moving outside of buttons 5981 if (!pointInView(x, y, mTouchSlop)) { 5982 // Outside button 5983 removeTapCallback(); 5984 if ((mPrivateFlags & PRESSED) != 0) { 5985 // Remove any future long press/tap checks 5986 removeLongPressCallback(); 5987 5988 // Need to switch from pressed to not pressed 5989 mPrivateFlags &= ~PRESSED; 5990 refreshDrawableState(); 5991 } 5992 } 5993 break; 5994 } 5995 return true; 5996 } 5997 5998 return false; 5999 } 6000 6001 /** 6002 * Remove the longpress detection timer. 6003 */ 6004 private void removeLongPressCallback() { 6005 if (mPendingCheckForLongPress != null) { 6006 removeCallbacks(mPendingCheckForLongPress); 6007 } 6008 } 6009 6010 /** 6011 * Remove the pending click action 6012 */ 6013 private void removePerformClickCallback() { 6014 if (mPerformClick != null) { 6015 removeCallbacks(mPerformClick); 6016 } 6017 } 6018 6019 /** 6020 * Remove the prepress detection timer. 6021 */ 6022 private void removeUnsetPressCallback() { 6023 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) { 6024 setPressed(false); 6025 removeCallbacks(mUnsetPressedState); 6026 } 6027 } 6028 6029 /** 6030 * Remove the tap detection timer. 6031 */ 6032 private void removeTapCallback() { 6033 if (mPendingCheckForTap != null) { 6034 mPrivateFlags &= ~PREPRESSED; 6035 removeCallbacks(mPendingCheckForTap); 6036 } 6037 } 6038 6039 /** 6040 * Cancels a pending long press. Your subclass can use this if you 6041 * want the context menu to come up if the user presses and holds 6042 * at the same place, but you don't want it to come up if they press 6043 * and then move around enough to cause scrolling. 6044 */ 6045 public void cancelLongPress() { 6046 removeLongPressCallback(); 6047 6048 /* 6049 * The prepressed state handled by the tap callback is a display 6050 * construct, but the tap callback will post a long press callback 6051 * less its own timeout. Remove it here. 6052 */ 6053 removeTapCallback(); 6054 } 6055 6056 /** 6057 * Sets the TouchDelegate for this View. 6058 */ 6059 public void setTouchDelegate(TouchDelegate delegate) { 6060 mTouchDelegate = delegate; 6061 } 6062 6063 /** 6064 * Gets the TouchDelegate for this View. 6065 */ 6066 public TouchDelegate getTouchDelegate() { 6067 return mTouchDelegate; 6068 } 6069 6070 /** 6071 * Set flags controlling behavior of this view. 6072 * 6073 * @param flags Constant indicating the value which should be set 6074 * @param mask Constant indicating the bit range that should be changed 6075 */ 6076 void setFlags(int flags, int mask) { 6077 int old = mViewFlags; 6078 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 6079 6080 int changed = mViewFlags ^ old; 6081 if (changed == 0) { 6082 return; 6083 } 6084 int privateFlags = mPrivateFlags; 6085 6086 /* Check if the FOCUSABLE bit has changed */ 6087 if (((changed & FOCUSABLE_MASK) != 0) && 6088 ((privateFlags & HAS_BOUNDS) !=0)) { 6089 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 6090 && ((privateFlags & FOCUSED) != 0)) { 6091 /* Give up focus if we are no longer focusable */ 6092 clearFocus(); 6093 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 6094 && ((privateFlags & FOCUSED) == 0)) { 6095 /* 6096 * Tell the view system that we are now available to take focus 6097 * if no one else already has it. 6098 */ 6099 if (mParent != null) mParent.focusableViewAvailable(this); 6100 } 6101 } 6102 6103 if ((flags & VISIBILITY_MASK) == VISIBLE) { 6104 if ((changed & VISIBILITY_MASK) != 0) { 6105 /* 6106 * If this view is becoming visible, set the DRAWN flag so that 6107 * the next invalidate() will not be skipped. 6108 */ 6109 mPrivateFlags |= DRAWN; 6110 6111 needGlobalAttributesUpdate(true); 6112 6113 // a view becoming visible is worth notifying the parent 6114 // about in case nothing has focus. even if this specific view 6115 // isn't focusable, it may contain something that is, so let 6116 // the root view try to give this focus if nothing else does. 6117 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 6118 mParent.focusableViewAvailable(this); 6119 } 6120 } 6121 } 6122 6123 /* Check if the GONE bit has changed */ 6124 if ((changed & GONE) != 0) { 6125 needGlobalAttributesUpdate(false); 6126 requestLayout(); 6127 invalidate(true); 6128 6129 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 6130 if (hasFocus()) clearFocus(); 6131 destroyDrawingCache(); 6132 } 6133 if (mAttachInfo != null) { 6134 mAttachInfo.mViewVisibilityChanged = true; 6135 } 6136 } 6137 6138 /* Check if the VISIBLE bit has changed */ 6139 if ((changed & INVISIBLE) != 0) { 6140 needGlobalAttributesUpdate(false); 6141 /* 6142 * If this view is becoming invisible, set the DRAWN flag so that 6143 * the next invalidate() will not be skipped. 6144 */ 6145 mPrivateFlags |= DRAWN; 6146 6147 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 6148 // root view becoming invisible shouldn't clear focus 6149 if (getRootView() != this) { 6150 clearFocus(); 6151 } 6152 } 6153 if (mAttachInfo != null) { 6154 mAttachInfo.mViewVisibilityChanged = true; 6155 } 6156 } 6157 6158 if ((changed & VISIBILITY_MASK) != 0) { 6159 if (mParent instanceof ViewGroup) { 6160 ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6161 ((View) mParent).invalidate(true); 6162 } 6163 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6164 } 6165 6166 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 6167 destroyDrawingCache(); 6168 } 6169 6170 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 6171 destroyDrawingCache(); 6172 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6173 invalidateParentCaches(); 6174 } 6175 6176 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 6177 destroyDrawingCache(); 6178 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6179 } 6180 6181 if ((changed & DRAW_MASK) != 0) { 6182 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 6183 if (mBGDrawable != null) { 6184 mPrivateFlags &= ~SKIP_DRAW; 6185 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 6186 } else { 6187 mPrivateFlags |= SKIP_DRAW; 6188 } 6189 } else { 6190 mPrivateFlags &= ~SKIP_DRAW; 6191 } 6192 requestLayout(); 6193 invalidate(true); 6194 } 6195 6196 if ((changed & KEEP_SCREEN_ON) != 0) { 6197 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 6198 mParent.recomputeViewAttributes(this); 6199 } 6200 } 6201 6202 if ((changed & LAYOUT_DIRECTION_MASK) != 0) { 6203 requestLayout(); 6204 } 6205 } 6206 6207 /** 6208 * Change the view's z order in the tree, so it's on top of other sibling 6209 * views 6210 */ 6211 public void bringToFront() { 6212 if (mParent != null) { 6213 mParent.bringChildToFront(this); 6214 } 6215 } 6216 6217 /** 6218 * This is called in response to an internal scroll in this view (i.e., the 6219 * view scrolled its own contents). This is typically as a result of 6220 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 6221 * called. 6222 * 6223 * @param l Current horizontal scroll origin. 6224 * @param t Current vertical scroll origin. 6225 * @param oldl Previous horizontal scroll origin. 6226 * @param oldt Previous vertical scroll origin. 6227 */ 6228 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 6229 mBackgroundSizeChanged = true; 6230 6231 final AttachInfo ai = mAttachInfo; 6232 if (ai != null) { 6233 ai.mViewScrollChanged = true; 6234 } 6235 } 6236 6237 /** 6238 * Interface definition for a callback to be invoked when the layout bounds of a view 6239 * changes due to layout processing. 6240 */ 6241 public interface OnLayoutChangeListener { 6242 /** 6243 * Called when the focus state of a view has changed. 6244 * 6245 * @param v The view whose state has changed. 6246 * @param left The new value of the view's left property. 6247 * @param top The new value of the view's top property. 6248 * @param right The new value of the view's right property. 6249 * @param bottom The new value of the view's bottom property. 6250 * @param oldLeft The previous value of the view's left property. 6251 * @param oldTop The previous value of the view's top property. 6252 * @param oldRight The previous value of the view's right property. 6253 * @param oldBottom The previous value of the view's bottom property. 6254 */ 6255 void onLayoutChange(View v, int left, int top, int right, int bottom, 6256 int oldLeft, int oldTop, int oldRight, int oldBottom); 6257 } 6258 6259 /** 6260 * This is called during layout when the size of this view has changed. If 6261 * you were just added to the view hierarchy, you're called with the old 6262 * values of 0. 6263 * 6264 * @param w Current width of this view. 6265 * @param h Current height of this view. 6266 * @param oldw Old width of this view. 6267 * @param oldh Old height of this view. 6268 */ 6269 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 6270 } 6271 6272 /** 6273 * Called by draw to draw the child views. This may be overridden 6274 * by derived classes to gain control just before its children are drawn 6275 * (but after its own view has been drawn). 6276 * @param canvas the canvas on which to draw the view 6277 */ 6278 protected void dispatchDraw(Canvas canvas) { 6279 } 6280 6281 /** 6282 * Gets the parent of this view. Note that the parent is a 6283 * ViewParent and not necessarily a View. 6284 * 6285 * @return Parent of this view. 6286 */ 6287 public final ViewParent getParent() { 6288 return mParent; 6289 } 6290 6291 /** 6292 * Set the horizontal scrolled position of your view. This will cause a call to 6293 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6294 * invalidated. 6295 * @param value the x position to scroll to 6296 */ 6297 public void setScrollX(int value) { 6298 scrollTo(value, mScrollY); 6299 } 6300 6301 /** 6302 * Set the vertical scrolled position of your view. This will cause a call to 6303 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6304 * invalidated. 6305 * @param value the y position to scroll to 6306 */ 6307 public void setScrollY(int value) { 6308 scrollTo(mScrollX, value); 6309 } 6310 6311 /** 6312 * Return the scrolled left position of this view. This is the left edge of 6313 * the displayed part of your view. You do not need to draw any pixels 6314 * farther left, since those are outside of the frame of your view on 6315 * screen. 6316 * 6317 * @return The left edge of the displayed part of your view, in pixels. 6318 */ 6319 public final int getScrollX() { 6320 return mScrollX; 6321 } 6322 6323 /** 6324 * Return the scrolled top position of this view. This is the top edge of 6325 * the displayed part of your view. You do not need to draw any pixels above 6326 * it, since those are outside of the frame of your view on screen. 6327 * 6328 * @return The top edge of the displayed part of your view, in pixels. 6329 */ 6330 public final int getScrollY() { 6331 return mScrollY; 6332 } 6333 6334 /** 6335 * Return the width of the your view. 6336 * 6337 * @return The width of your view, in pixels. 6338 */ 6339 @ViewDebug.ExportedProperty(category = "layout") 6340 public final int getWidth() { 6341 return mRight - mLeft; 6342 } 6343 6344 /** 6345 * Return the height of your view. 6346 * 6347 * @return The height of your view, in pixels. 6348 */ 6349 @ViewDebug.ExportedProperty(category = "layout") 6350 public final int getHeight() { 6351 return mBottom - mTop; 6352 } 6353 6354 /** 6355 * Return the visible drawing bounds of your view. Fills in the output 6356 * rectangle with the values from getScrollX(), getScrollY(), 6357 * getWidth(), and getHeight(). 6358 * 6359 * @param outRect The (scrolled) drawing bounds of the view. 6360 */ 6361 public void getDrawingRect(Rect outRect) { 6362 outRect.left = mScrollX; 6363 outRect.top = mScrollY; 6364 outRect.right = mScrollX + (mRight - mLeft); 6365 outRect.bottom = mScrollY + (mBottom - mTop); 6366 } 6367 6368 /** 6369 * Like {@link #getMeasuredWidthAndState()}, but only returns the 6370 * raw width component (that is the result is masked by 6371 * {@link #MEASURED_SIZE_MASK}). 6372 * 6373 * @return The raw measured width of this view. 6374 */ 6375 public final int getMeasuredWidth() { 6376 return mMeasuredWidth & MEASURED_SIZE_MASK; 6377 } 6378 6379 /** 6380 * Return the full width measurement information for this view as computed 6381 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6382 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6383 * This should be used during measurement and layout calculations only. Use 6384 * {@link #getWidth()} to see how wide a view is after layout. 6385 * 6386 * @return The measured width of this view as a bit mask. 6387 */ 6388 public final int getMeasuredWidthAndState() { 6389 return mMeasuredWidth; 6390 } 6391 6392 /** 6393 * Like {@link #getMeasuredHeightAndState()}, but only returns the 6394 * raw width component (that is the result is masked by 6395 * {@link #MEASURED_SIZE_MASK}). 6396 * 6397 * @return The raw measured height of this view. 6398 */ 6399 public final int getMeasuredHeight() { 6400 return mMeasuredHeight & MEASURED_SIZE_MASK; 6401 } 6402 6403 /** 6404 * Return the full height measurement information for this view as computed 6405 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6406 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6407 * This should be used during measurement and layout calculations only. Use 6408 * {@link #getHeight()} to see how wide a view is after layout. 6409 * 6410 * @return The measured width of this view as a bit mask. 6411 */ 6412 public final int getMeasuredHeightAndState() { 6413 return mMeasuredHeight; 6414 } 6415 6416 /** 6417 * Return only the state bits of {@link #getMeasuredWidthAndState()} 6418 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 6419 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 6420 * and the height component is at the shifted bits 6421 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 6422 */ 6423 public final int getMeasuredState() { 6424 return (mMeasuredWidth&MEASURED_STATE_MASK) 6425 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 6426 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 6427 } 6428 6429 /** 6430 * The transform matrix of this view, which is calculated based on the current 6431 * roation, scale, and pivot properties. 6432 * 6433 * @see #getRotation() 6434 * @see #getScaleX() 6435 * @see #getScaleY() 6436 * @see #getPivotX() 6437 * @see #getPivotY() 6438 * @return The current transform matrix for the view 6439 */ 6440 public Matrix getMatrix() { 6441 updateMatrix(); 6442 return mMatrix; 6443 } 6444 6445 /** 6446 * Utility function to determine if the value is far enough away from zero to be 6447 * considered non-zero. 6448 * @param value A floating point value to check for zero-ness 6449 * @return whether the passed-in value is far enough away from zero to be considered non-zero 6450 */ 6451 private static boolean nonzero(float value) { 6452 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 6453 } 6454 6455 /** 6456 * Returns true if the transform matrix is the identity matrix. 6457 * Recomputes the matrix if necessary. 6458 * 6459 * @return True if the transform matrix is the identity matrix, false otherwise. 6460 */ 6461 final boolean hasIdentityMatrix() { 6462 updateMatrix(); 6463 return mMatrixIsIdentity; 6464 } 6465 6466 /** 6467 * Recomputes the transform matrix if necessary. 6468 */ 6469 private void updateMatrix() { 6470 if (mMatrixDirty) { 6471 // transform-related properties have changed since the last time someone 6472 // asked for the matrix; recalculate it with the current values 6473 6474 // Figure out if we need to update the pivot point 6475 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6476 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) { 6477 mPrevWidth = mRight - mLeft; 6478 mPrevHeight = mBottom - mTop; 6479 mPivotX = mPrevWidth / 2f; 6480 mPivotY = mPrevHeight / 2f; 6481 } 6482 } 6483 mMatrix.reset(); 6484 if (!nonzero(mRotationX) && !nonzero(mRotationY)) { 6485 mMatrix.setTranslate(mTranslationX, mTranslationY); 6486 mMatrix.preRotate(mRotation, mPivotX, mPivotY); 6487 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY); 6488 } else { 6489 if (mCamera == null) { 6490 mCamera = new Camera(); 6491 matrix3D = new Matrix(); 6492 } 6493 mCamera.save(); 6494 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY); 6495 mCamera.rotate(mRotationX, mRotationY, -mRotation); 6496 mCamera.getMatrix(matrix3D); 6497 matrix3D.preTranslate(-mPivotX, -mPivotY); 6498 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY); 6499 mMatrix.postConcat(matrix3D); 6500 mCamera.restore(); 6501 } 6502 mMatrixDirty = false; 6503 mMatrixIsIdentity = mMatrix.isIdentity(); 6504 mInverseMatrixDirty = true; 6505 } 6506 } 6507 6508 /** 6509 * Utility method to retrieve the inverse of the current mMatrix property. 6510 * We cache the matrix to avoid recalculating it when transform properties 6511 * have not changed. 6512 * 6513 * @return The inverse of the current matrix of this view. 6514 */ 6515 final Matrix getInverseMatrix() { 6516 updateMatrix(); 6517 if (mInverseMatrixDirty) { 6518 if (mInverseMatrix == null) { 6519 mInverseMatrix = new Matrix(); 6520 } 6521 mMatrix.invert(mInverseMatrix); 6522 mInverseMatrixDirty = false; 6523 } 6524 return mInverseMatrix; 6525 } 6526 6527 /** 6528 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 6529 * views are drawn) from the camera to this view. The camera's distance 6530 * affects 3D transformations, for instance rotations around the X and Y 6531 * axis. If the rotationX or rotationY properties are changed and this view is 6532 * large (more than half the size of the screen), it is recommended to always 6533 * use a camera distance that's greater than the height (X axis rotation) or 6534 * the width (Y axis rotation) of this view.</p> 6535 * 6536 * <p>The distance of the camera from the view plane can have an affect on the 6537 * perspective distortion of the view when it is rotated around the x or y axis. 6538 * For example, a large distance will result in a large viewing angle, and there 6539 * will not be much perspective distortion of the view as it rotates. A short 6540 * distance may cause much more perspective distortion upon rotation, and can 6541 * also result in some drawing artifacts if the rotated view ends up partially 6542 * behind the camera (which is why the recommendation is to use a distance at 6543 * least as far as the size of the view, if the view is to be rotated.)</p> 6544 * 6545 * <p>The distance is expressed in "depth pixels." The default distance depends 6546 * on the screen density. For instance, on a medium density display, the 6547 * default distance is 1280. On a high density display, the default distance 6548 * is 1920.</p> 6549 * 6550 * <p>If you want to specify a distance that leads to visually consistent 6551 * results across various densities, use the following formula:</p> 6552 * <pre> 6553 * float scale = context.getResources().getDisplayMetrics().density; 6554 * view.setCameraDistance(distance * scale); 6555 * </pre> 6556 * 6557 * <p>The density scale factor of a high density display is 1.5, 6558 * and 1920 = 1280 * 1.5.</p> 6559 * 6560 * @param distance The distance in "depth pixels", if negative the opposite 6561 * value is used 6562 * 6563 * @see #setRotationX(float) 6564 * @see #setRotationY(float) 6565 */ 6566 public void setCameraDistance(float distance) { 6567 invalidateParentCaches(); 6568 invalidate(false); 6569 6570 final float dpi = mResources.getDisplayMetrics().densityDpi; 6571 if (mCamera == null) { 6572 mCamera = new Camera(); 6573 matrix3D = new Matrix(); 6574 } 6575 6576 mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 6577 mMatrixDirty = true; 6578 6579 invalidate(false); 6580 } 6581 6582 /** 6583 * The degrees that the view is rotated around the pivot point. 6584 * 6585 * @see #setRotation(float) 6586 * @see #getPivotX() 6587 * @see #getPivotY() 6588 * 6589 * @return The degrees of rotation. 6590 */ 6591 public float getRotation() { 6592 return mRotation; 6593 } 6594 6595 /** 6596 * Sets the degrees that the view is rotated around the pivot point. Increasing values 6597 * result in clockwise rotation. 6598 * 6599 * @param rotation The degrees of rotation. 6600 * 6601 * @see #getRotation() 6602 * @see #getPivotX() 6603 * @see #getPivotY() 6604 * @see #setRotationX(float) 6605 * @see #setRotationY(float) 6606 * 6607 * @attr ref android.R.styleable#View_rotation 6608 */ 6609 public void setRotation(float rotation) { 6610 if (mRotation != rotation) { 6611 invalidateParentCaches(); 6612 // Double-invalidation is necessary to capture view's old and new areas 6613 invalidate(false); 6614 mRotation = rotation; 6615 mMatrixDirty = true; 6616 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6617 invalidate(false); 6618 } 6619 } 6620 6621 /** 6622 * The degrees that the view is rotated around the vertical axis through the pivot point. 6623 * 6624 * @see #getPivotX() 6625 * @see #getPivotY() 6626 * @see #setRotationY(float) 6627 * 6628 * @return The degrees of Y rotation. 6629 */ 6630 public float getRotationY() { 6631 return mRotationY; 6632 } 6633 6634 /** 6635 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 6636 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 6637 * down the y axis. 6638 * 6639 * When rotating large views, it is recommended to adjust the camera distance 6640 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 6641 * 6642 * @param rotationY The degrees of Y rotation. 6643 * 6644 * @see #getRotationY() 6645 * @see #getPivotX() 6646 * @see #getPivotY() 6647 * @see #setRotation(float) 6648 * @see #setRotationX(float) 6649 * @see #setCameraDistance(float) 6650 * 6651 * @attr ref android.R.styleable#View_rotationY 6652 */ 6653 public void setRotationY(float rotationY) { 6654 if (mRotationY != rotationY) { 6655 invalidateParentCaches(); 6656 // Double-invalidation is necessary to capture view's old and new areas 6657 invalidate(false); 6658 mRotationY = rotationY; 6659 mMatrixDirty = true; 6660 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6661 invalidate(false); 6662 } 6663 } 6664 6665 /** 6666 * The degrees that the view is rotated around the horizontal axis through the pivot point. 6667 * 6668 * @see #getPivotX() 6669 * @see #getPivotY() 6670 * @see #setRotationX(float) 6671 * 6672 * @return The degrees of X rotation. 6673 */ 6674 public float getRotationX() { 6675 return mRotationX; 6676 } 6677 6678 /** 6679 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 6680 * Increasing values result in clockwise rotation from the viewpoint of looking down the 6681 * x axis. 6682 * 6683 * When rotating large views, it is recommended to adjust the camera distance 6684 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 6685 * 6686 * @param rotationX The degrees of X rotation. 6687 * 6688 * @see #getRotationX() 6689 * @see #getPivotX() 6690 * @see #getPivotY() 6691 * @see #setRotation(float) 6692 * @see #setRotationY(float) 6693 * @see #setCameraDistance(float) 6694 * 6695 * @attr ref android.R.styleable#View_rotationX 6696 */ 6697 public void setRotationX(float rotationX) { 6698 if (mRotationX != rotationX) { 6699 invalidateParentCaches(); 6700 // Double-invalidation is necessary to capture view's old and new areas 6701 invalidate(false); 6702 mRotationX = rotationX; 6703 mMatrixDirty = true; 6704 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6705 invalidate(false); 6706 } 6707 } 6708 6709 /** 6710 * The amount that the view is scaled in x around the pivot point, as a proportion of 6711 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 6712 * 6713 * <p>By default, this is 1.0f. 6714 * 6715 * @see #getPivotX() 6716 * @see #getPivotY() 6717 * @return The scaling factor. 6718 */ 6719 public float getScaleX() { 6720 return mScaleX; 6721 } 6722 6723 /** 6724 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 6725 * the view's unscaled width. A value of 1 means that no scaling is applied. 6726 * 6727 * @param scaleX The scaling factor. 6728 * @see #getPivotX() 6729 * @see #getPivotY() 6730 * 6731 * @attr ref android.R.styleable#View_scaleX 6732 */ 6733 public void setScaleX(float scaleX) { 6734 if (mScaleX != scaleX) { 6735 invalidateParentCaches(); 6736 // Double-invalidation is necessary to capture view's old and new areas 6737 invalidate(false); 6738 mScaleX = scaleX; 6739 mMatrixDirty = true; 6740 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6741 invalidate(false); 6742 } 6743 } 6744 6745 /** 6746 * The amount that the view is scaled in y around the pivot point, as a proportion of 6747 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 6748 * 6749 * <p>By default, this is 1.0f. 6750 * 6751 * @see #getPivotX() 6752 * @see #getPivotY() 6753 * @return The scaling factor. 6754 */ 6755 public float getScaleY() { 6756 return mScaleY; 6757 } 6758 6759 /** 6760 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 6761 * the view's unscaled width. A value of 1 means that no scaling is applied. 6762 * 6763 * @param scaleY The scaling factor. 6764 * @see #getPivotX() 6765 * @see #getPivotY() 6766 * 6767 * @attr ref android.R.styleable#View_scaleY 6768 */ 6769 public void setScaleY(float scaleY) { 6770 if (mScaleY != scaleY) { 6771 invalidateParentCaches(); 6772 // Double-invalidation is necessary to capture view's old and new areas 6773 invalidate(false); 6774 mScaleY = scaleY; 6775 mMatrixDirty = true; 6776 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6777 invalidate(false); 6778 } 6779 } 6780 6781 /** 6782 * The x location of the point around which the view is {@link #setRotation(float) rotated} 6783 * and {@link #setScaleX(float) scaled}. 6784 * 6785 * @see #getRotation() 6786 * @see #getScaleX() 6787 * @see #getScaleY() 6788 * @see #getPivotY() 6789 * @return The x location of the pivot point. 6790 */ 6791 public float getPivotX() { 6792 return mPivotX; 6793 } 6794 6795 /** 6796 * Sets the x location of the point around which the view is 6797 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 6798 * By default, the pivot point is centered on the object. 6799 * Setting this property disables this behavior and causes the view to use only the 6800 * explicitly set pivotX and pivotY values. 6801 * 6802 * @param pivotX The x location of the pivot point. 6803 * @see #getRotation() 6804 * @see #getScaleX() 6805 * @see #getScaleY() 6806 * @see #getPivotY() 6807 * 6808 * @attr ref android.R.styleable#View_transformPivotX 6809 */ 6810 public void setPivotX(float pivotX) { 6811 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 6812 if (mPivotX != pivotX) { 6813 invalidateParentCaches(); 6814 // Double-invalidation is necessary to capture view's old and new areas 6815 invalidate(false); 6816 mPivotX = pivotX; 6817 mMatrixDirty = true; 6818 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6819 invalidate(false); 6820 } 6821 } 6822 6823 /** 6824 * The y location of the point around which the view is {@link #setRotation(float) rotated} 6825 * and {@link #setScaleY(float) scaled}. 6826 * 6827 * @see #getRotation() 6828 * @see #getScaleX() 6829 * @see #getScaleY() 6830 * @see #getPivotY() 6831 * @return The y location of the pivot point. 6832 */ 6833 public float getPivotY() { 6834 return mPivotY; 6835 } 6836 6837 /** 6838 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 6839 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 6840 * Setting this property disables this behavior and causes the view to use only the 6841 * explicitly set pivotX and pivotY values. 6842 * 6843 * @param pivotY The y location of the pivot point. 6844 * @see #getRotation() 6845 * @see #getScaleX() 6846 * @see #getScaleY() 6847 * @see #getPivotY() 6848 * 6849 * @attr ref android.R.styleable#View_transformPivotY 6850 */ 6851 public void setPivotY(float pivotY) { 6852 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 6853 if (mPivotY != pivotY) { 6854 invalidateParentCaches(); 6855 // Double-invalidation is necessary to capture view's old and new areas 6856 invalidate(false); 6857 mPivotY = pivotY; 6858 mMatrixDirty = true; 6859 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6860 invalidate(false); 6861 } 6862 } 6863 6864 /** 6865 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 6866 * completely transparent and 1 means the view is completely opaque. 6867 * 6868 * <p>By default this is 1.0f. 6869 * @return The opacity of the view. 6870 */ 6871 public float getAlpha() { 6872 return mAlpha; 6873 } 6874 6875 /** 6876 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 6877 * completely transparent and 1 means the view is completely opaque.</p> 6878 * 6879 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 6880 * responsible for applying the opacity itself. Otherwise, calling this method is 6881 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 6882 * setting a hardware layer.</p> 6883 * 6884 * @param alpha The opacity of the view. 6885 * 6886 * @see #setLayerType(int, android.graphics.Paint) 6887 * 6888 * @attr ref android.R.styleable#View_alpha 6889 */ 6890 public void setAlpha(float alpha) { 6891 mAlpha = alpha; 6892 invalidateParentCaches(); 6893 if (onSetAlpha((int) (alpha * 255))) { 6894 mPrivateFlags |= ALPHA_SET; 6895 // subclass is handling alpha - don't optimize rendering cache invalidation 6896 invalidate(true); 6897 } else { 6898 mPrivateFlags &= ~ALPHA_SET; 6899 invalidate(false); 6900 } 6901 } 6902 6903 /** 6904 * Faster version of setAlpha() which performs the same steps except there are 6905 * no calls to invalidate(). The caller of this function should perform proper invalidation 6906 * on the parent and this object. The return value indicates whether the subclass handles 6907 * alpha (the return value for onSetAlpha()). 6908 * 6909 * @param alpha The new value for the alpha property 6910 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) 6911 */ 6912 boolean setAlphaNoInvalidation(float alpha) { 6913 mAlpha = alpha; 6914 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 6915 if (subclassHandlesAlpha) { 6916 mPrivateFlags |= ALPHA_SET; 6917 } else { 6918 mPrivateFlags &= ~ALPHA_SET; 6919 } 6920 return subclassHandlesAlpha; 6921 } 6922 6923 /** 6924 * Top position of this view relative to its parent. 6925 * 6926 * @return The top of this view, in pixels. 6927 */ 6928 @ViewDebug.CapturedViewProperty 6929 public final int getTop() { 6930 return mTop; 6931 } 6932 6933 /** 6934 * Sets the top position of this view relative to its parent. This method is meant to be called 6935 * by the layout system and should not generally be called otherwise, because the property 6936 * may be changed at any time by the layout. 6937 * 6938 * @param top The top of this view, in pixels. 6939 */ 6940 public final void setTop(int top) { 6941 if (top != mTop) { 6942 updateMatrix(); 6943 if (mMatrixIsIdentity) { 6944 if (mAttachInfo != null) { 6945 int minTop; 6946 int yLoc; 6947 if (top < mTop) { 6948 minTop = top; 6949 yLoc = top - mTop; 6950 } else { 6951 minTop = mTop; 6952 yLoc = 0; 6953 } 6954 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 6955 } 6956 } else { 6957 // Double-invalidation is necessary to capture view's old and new areas 6958 invalidate(true); 6959 } 6960 6961 int width = mRight - mLeft; 6962 int oldHeight = mBottom - mTop; 6963 6964 mTop = top; 6965 6966 onSizeChanged(width, mBottom - mTop, width, oldHeight); 6967 6968 if (!mMatrixIsIdentity) { 6969 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6970 // A change in dimension means an auto-centered pivot point changes, too 6971 mMatrixDirty = true; 6972 } 6973 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6974 invalidate(true); 6975 } 6976 mBackgroundSizeChanged = true; 6977 invalidateParentIfNeeded(); 6978 } 6979 } 6980 6981 /** 6982 * Bottom position of this view relative to its parent. 6983 * 6984 * @return The bottom of this view, in pixels. 6985 */ 6986 @ViewDebug.CapturedViewProperty 6987 public final int getBottom() { 6988 return mBottom; 6989 } 6990 6991 /** 6992 * True if this view has changed since the last time being drawn. 6993 * 6994 * @return The dirty state of this view. 6995 */ 6996 public boolean isDirty() { 6997 return (mPrivateFlags & DIRTY_MASK) != 0; 6998 } 6999 7000 /** 7001 * Sets the bottom position of this view relative to its parent. This method is meant to be 7002 * called by the layout system and should not generally be called otherwise, because the 7003 * property may be changed at any time by the layout. 7004 * 7005 * @param bottom The bottom of this view, in pixels. 7006 */ 7007 public final void setBottom(int bottom) { 7008 if (bottom != mBottom) { 7009 updateMatrix(); 7010 if (mMatrixIsIdentity) { 7011 if (mAttachInfo != null) { 7012 int maxBottom; 7013 if (bottom < mBottom) { 7014 maxBottom = mBottom; 7015 } else { 7016 maxBottom = bottom; 7017 } 7018 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 7019 } 7020 } else { 7021 // Double-invalidation is necessary to capture view's old and new areas 7022 invalidate(true); 7023 } 7024 7025 int width = mRight - mLeft; 7026 int oldHeight = mBottom - mTop; 7027 7028 mBottom = bottom; 7029 7030 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7031 7032 if (!mMatrixIsIdentity) { 7033 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7034 // A change in dimension means an auto-centered pivot point changes, too 7035 mMatrixDirty = true; 7036 } 7037 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7038 invalidate(true); 7039 } 7040 mBackgroundSizeChanged = true; 7041 invalidateParentIfNeeded(); 7042 } 7043 } 7044 7045 /** 7046 * Left position of this view relative to its parent. 7047 * 7048 * @return The left edge of this view, in pixels. 7049 */ 7050 @ViewDebug.CapturedViewProperty 7051 public final int getLeft() { 7052 return mLeft; 7053 } 7054 7055 /** 7056 * Sets the left position of this view relative to its parent. This method is meant to be called 7057 * by the layout system and should not generally be called otherwise, because the property 7058 * may be changed at any time by the layout. 7059 * 7060 * @param left The bottom of this view, in pixels. 7061 */ 7062 public final void setLeft(int left) { 7063 if (left != mLeft) { 7064 updateMatrix(); 7065 if (mMatrixIsIdentity) { 7066 if (mAttachInfo != null) { 7067 int minLeft; 7068 int xLoc; 7069 if (left < mLeft) { 7070 minLeft = left; 7071 xLoc = left - mLeft; 7072 } else { 7073 minLeft = mLeft; 7074 xLoc = 0; 7075 } 7076 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 7077 } 7078 } else { 7079 // Double-invalidation is necessary to capture view's old and new areas 7080 invalidate(true); 7081 } 7082 7083 int oldWidth = mRight - mLeft; 7084 int height = mBottom - mTop; 7085 7086 mLeft = left; 7087 7088 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7089 7090 if (!mMatrixIsIdentity) { 7091 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7092 // A change in dimension means an auto-centered pivot point changes, too 7093 mMatrixDirty = true; 7094 } 7095 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7096 invalidate(true); 7097 } 7098 mBackgroundSizeChanged = true; 7099 invalidateParentIfNeeded(); 7100 } 7101 } 7102 7103 /** 7104 * Right position of this view relative to its parent. 7105 * 7106 * @return The right edge of this view, in pixels. 7107 */ 7108 @ViewDebug.CapturedViewProperty 7109 public final int getRight() { 7110 return mRight; 7111 } 7112 7113 /** 7114 * Sets the right position of this view relative to its parent. This method is meant to be called 7115 * by the layout system and should not generally be called otherwise, because the property 7116 * may be changed at any time by the layout. 7117 * 7118 * @param right The bottom of this view, in pixels. 7119 */ 7120 public final void setRight(int right) { 7121 if (right != mRight) { 7122 updateMatrix(); 7123 if (mMatrixIsIdentity) { 7124 if (mAttachInfo != null) { 7125 int maxRight; 7126 if (right < mRight) { 7127 maxRight = mRight; 7128 } else { 7129 maxRight = right; 7130 } 7131 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 7132 } 7133 } else { 7134 // Double-invalidation is necessary to capture view's old and new areas 7135 invalidate(true); 7136 } 7137 7138 int oldWidth = mRight - mLeft; 7139 int height = mBottom - mTop; 7140 7141 mRight = right; 7142 7143 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7144 7145 if (!mMatrixIsIdentity) { 7146 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7147 // A change in dimension means an auto-centered pivot point changes, too 7148 mMatrixDirty = true; 7149 } 7150 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7151 invalidate(true); 7152 } 7153 mBackgroundSizeChanged = true; 7154 invalidateParentIfNeeded(); 7155 } 7156 } 7157 7158 /** 7159 * The visual x position of this view, in pixels. This is equivalent to the 7160 * {@link #setTranslationX(float) translationX} property plus the current 7161 * {@link #getLeft() left} property. 7162 * 7163 * @return The visual x position of this view, in pixels. 7164 */ 7165 public float getX() { 7166 return mLeft + mTranslationX; 7167 } 7168 7169 /** 7170 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 7171 * {@link #setTranslationX(float) translationX} property to be the difference between 7172 * the x value passed in and the current {@link #getLeft() left} property. 7173 * 7174 * @param x The visual x position of this view, in pixels. 7175 */ 7176 public void setX(float x) { 7177 setTranslationX(x - mLeft); 7178 } 7179 7180 /** 7181 * The visual y position of this view, in pixels. This is equivalent to the 7182 * {@link #setTranslationY(float) translationY} property plus the current 7183 * {@link #getTop() top} property. 7184 * 7185 * @return The visual y position of this view, in pixels. 7186 */ 7187 public float getY() { 7188 return mTop + mTranslationY; 7189 } 7190 7191 /** 7192 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 7193 * {@link #setTranslationY(float) translationY} property to be the difference between 7194 * the y value passed in and the current {@link #getTop() top} property. 7195 * 7196 * @param y The visual y position of this view, in pixels. 7197 */ 7198 public void setY(float y) { 7199 setTranslationY(y - mTop); 7200 } 7201 7202 7203 /** 7204 * The horizontal location of this view relative to its {@link #getLeft() left} position. 7205 * This position is post-layout, in addition to wherever the object's 7206 * layout placed it. 7207 * 7208 * @return The horizontal position of this view relative to its left position, in pixels. 7209 */ 7210 public float getTranslationX() { 7211 return mTranslationX; 7212 } 7213 7214 /** 7215 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 7216 * This effectively positions the object post-layout, in addition to wherever the object's 7217 * layout placed it. 7218 * 7219 * @param translationX The horizontal position of this view relative to its left position, 7220 * in pixels. 7221 * 7222 * @attr ref android.R.styleable#View_translationX 7223 */ 7224 public void setTranslationX(float translationX) { 7225 if (mTranslationX != translationX) { 7226 invalidateParentCaches(); 7227 // Double-invalidation is necessary to capture view's old and new areas 7228 invalidate(false); 7229 mTranslationX = translationX; 7230 mMatrixDirty = true; 7231 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7232 invalidate(false); 7233 } 7234 } 7235 7236 /** 7237 * The horizontal location of this view relative to its {@link #getTop() top} position. 7238 * This position is post-layout, in addition to wherever the object's 7239 * layout placed it. 7240 * 7241 * @return The vertical position of this view relative to its top position, 7242 * in pixels. 7243 */ 7244 public float getTranslationY() { 7245 return mTranslationY; 7246 } 7247 7248 /** 7249 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 7250 * This effectively positions the object post-layout, in addition to wherever the object's 7251 * layout placed it. 7252 * 7253 * @param translationY The vertical position of this view relative to its top position, 7254 * in pixels. 7255 * 7256 * @attr ref android.R.styleable#View_translationY 7257 */ 7258 public void setTranslationY(float translationY) { 7259 if (mTranslationY != translationY) { 7260 invalidateParentCaches(); 7261 // Double-invalidation is necessary to capture view's old and new areas 7262 invalidate(false); 7263 mTranslationY = translationY; 7264 mMatrixDirty = true; 7265 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7266 invalidate(false); 7267 } 7268 } 7269 7270 /** 7271 * @hide 7272 */ 7273 public void setFastTranslationX(float x) { 7274 mTranslationX = x; 7275 mMatrixDirty = true; 7276 } 7277 7278 /** 7279 * @hide 7280 */ 7281 public void setFastTranslationY(float y) { 7282 mTranslationY = y; 7283 mMatrixDirty = true; 7284 } 7285 7286 /** 7287 * @hide 7288 */ 7289 public void setFastX(float x) { 7290 mTranslationX = x - mLeft; 7291 mMatrixDirty = true; 7292 } 7293 7294 /** 7295 * @hide 7296 */ 7297 public void setFastY(float y) { 7298 mTranslationY = y - mTop; 7299 mMatrixDirty = true; 7300 } 7301 7302 /** 7303 * @hide 7304 */ 7305 public void setFastScaleX(float x) { 7306 mScaleX = x; 7307 mMatrixDirty = true; 7308 } 7309 7310 /** 7311 * @hide 7312 */ 7313 public void setFastScaleY(float y) { 7314 mScaleY = y; 7315 mMatrixDirty = true; 7316 } 7317 7318 /** 7319 * @hide 7320 */ 7321 public void setFastAlpha(float alpha) { 7322 mAlpha = alpha; 7323 } 7324 7325 /** 7326 * @hide 7327 */ 7328 public void setFastRotationY(float y) { 7329 mRotationY = y; 7330 mMatrixDirty = true; 7331 } 7332 7333 /** 7334 * Hit rectangle in parent's coordinates 7335 * 7336 * @param outRect The hit rectangle of the view. 7337 */ 7338 public void getHitRect(Rect outRect) { 7339 updateMatrix(); 7340 if (mMatrixIsIdentity || mAttachInfo == null) { 7341 outRect.set(mLeft, mTop, mRight, mBottom); 7342 } else { 7343 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 7344 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY); 7345 mMatrix.mapRect(tmpRect); 7346 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 7347 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 7348 } 7349 } 7350 7351 /** 7352 * Determines whether the given point, in local coordinates is inside the view. 7353 */ 7354 /*package*/ final boolean pointInView(float localX, float localY) { 7355 return localX >= 0 && localX < (mRight - mLeft) 7356 && localY >= 0 && localY < (mBottom - mTop); 7357 } 7358 7359 /** 7360 * Utility method to determine whether the given point, in local coordinates, 7361 * is inside the view, where the area of the view is expanded by the slop factor. 7362 * This method is called while processing touch-move events to determine if the event 7363 * is still within the view. 7364 */ 7365 private boolean pointInView(float localX, float localY, float slop) { 7366 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 7367 localY < ((mBottom - mTop) + slop); 7368 } 7369 7370 /** 7371 * When a view has focus and the user navigates away from it, the next view is searched for 7372 * starting from the rectangle filled in by this method. 7373 * 7374 * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)}) 7375 * of the view. However, if your view maintains some idea of internal selection, 7376 * such as a cursor, or a selected row or column, you should override this method and 7377 * fill in a more specific rectangle. 7378 * 7379 * @param r The rectangle to fill in, in this view's coordinates. 7380 */ 7381 public void getFocusedRect(Rect r) { 7382 getDrawingRect(r); 7383 } 7384 7385 /** 7386 * If some part of this view is not clipped by any of its parents, then 7387 * return that area in r in global (root) coordinates. To convert r to local 7388 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x, 7389 * -globalOffset.y)) If the view is completely clipped or translated out, 7390 * return false. 7391 * 7392 * @param r If true is returned, r holds the global coordinates of the 7393 * visible portion of this view. 7394 * @param globalOffset If true is returned, globalOffset holds the dx,dy 7395 * between this view and its root. globalOffet may be null. 7396 * @return true if r is non-empty (i.e. part of the view is visible at the 7397 * root level. 7398 */ 7399 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 7400 int width = mRight - mLeft; 7401 int height = mBottom - mTop; 7402 if (width > 0 && height > 0) { 7403 r.set(0, 0, width, height); 7404 if (globalOffset != null) { 7405 globalOffset.set(-mScrollX, -mScrollY); 7406 } 7407 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 7408 } 7409 return false; 7410 } 7411 7412 public final boolean getGlobalVisibleRect(Rect r) { 7413 return getGlobalVisibleRect(r, null); 7414 } 7415 7416 public final boolean getLocalVisibleRect(Rect r) { 7417 Point offset = new Point(); 7418 if (getGlobalVisibleRect(r, offset)) { 7419 r.offset(-offset.x, -offset.y); // make r local 7420 return true; 7421 } 7422 return false; 7423 } 7424 7425 /** 7426 * Offset this view's vertical location by the specified number of pixels. 7427 * 7428 * @param offset the number of pixels to offset the view by 7429 */ 7430 public void offsetTopAndBottom(int offset) { 7431 if (offset != 0) { 7432 updateMatrix(); 7433 if (mMatrixIsIdentity) { 7434 final ViewParent p = mParent; 7435 if (p != null && mAttachInfo != null) { 7436 final Rect r = mAttachInfo.mTmpInvalRect; 7437 int minTop; 7438 int maxBottom; 7439 int yLoc; 7440 if (offset < 0) { 7441 minTop = mTop + offset; 7442 maxBottom = mBottom; 7443 yLoc = offset; 7444 } else { 7445 minTop = mTop; 7446 maxBottom = mBottom + offset; 7447 yLoc = 0; 7448 } 7449 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 7450 p.invalidateChild(this, r); 7451 } 7452 } else { 7453 invalidate(false); 7454 } 7455 7456 mTop += offset; 7457 mBottom += offset; 7458 7459 if (!mMatrixIsIdentity) { 7460 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7461 invalidate(false); 7462 } 7463 invalidateParentIfNeeded(); 7464 } 7465 } 7466 7467 /** 7468 * Offset this view's horizontal location by the specified amount of pixels. 7469 * 7470 * @param offset the numer of pixels to offset the view by 7471 */ 7472 public void offsetLeftAndRight(int offset) { 7473 if (offset != 0) { 7474 updateMatrix(); 7475 if (mMatrixIsIdentity) { 7476 final ViewParent p = mParent; 7477 if (p != null && mAttachInfo != null) { 7478 final Rect r = mAttachInfo.mTmpInvalRect; 7479 int minLeft; 7480 int maxRight; 7481 if (offset < 0) { 7482 minLeft = mLeft + offset; 7483 maxRight = mRight; 7484 } else { 7485 minLeft = mLeft; 7486 maxRight = mRight + offset; 7487 } 7488 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 7489 p.invalidateChild(this, r); 7490 } 7491 } else { 7492 invalidate(false); 7493 } 7494 7495 mLeft += offset; 7496 mRight += offset; 7497 7498 if (!mMatrixIsIdentity) { 7499 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7500 invalidate(false); 7501 } 7502 invalidateParentIfNeeded(); 7503 } 7504 } 7505 7506 /** 7507 * Get the LayoutParams associated with this view. All views should have 7508 * layout parameters. These supply parameters to the <i>parent</i> of this 7509 * view specifying how it should be arranged. There are many subclasses of 7510 * ViewGroup.LayoutParams, and these correspond to the different subclasses 7511 * of ViewGroup that are responsible for arranging their children. 7512 * 7513 * This method may return null if this View is not attached to a parent 7514 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 7515 * was not invoked successfully. When a View is attached to a parent 7516 * ViewGroup, this method must not return null. 7517 * 7518 * @return The LayoutParams associated with this view, or null if no 7519 * parameters have been set yet 7520 */ 7521 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 7522 public ViewGroup.LayoutParams getLayoutParams() { 7523 return mLayoutParams; 7524 } 7525 7526 /** 7527 * Set the layout parameters associated with this view. These supply 7528 * parameters to the <i>parent</i> of this view specifying how it should be 7529 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 7530 * correspond to the different subclasses of ViewGroup that are responsible 7531 * for arranging their children. 7532 * 7533 * @param params The layout parameters for this view, cannot be null 7534 */ 7535 public void setLayoutParams(ViewGroup.LayoutParams params) { 7536 if (params == null) { 7537 throw new NullPointerException("Layout parameters cannot be null"); 7538 } 7539 mLayoutParams = params; 7540 requestLayout(); 7541 } 7542 7543 /** 7544 * Set the scrolled position of your view. This will cause a call to 7545 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7546 * invalidated. 7547 * @param x the x position to scroll to 7548 * @param y the y position to scroll to 7549 */ 7550 public void scrollTo(int x, int y) { 7551 if (mScrollX != x || mScrollY != y) { 7552 int oldX = mScrollX; 7553 int oldY = mScrollY; 7554 mScrollX = x; 7555 mScrollY = y; 7556 invalidateParentCaches(); 7557 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 7558 if (!awakenScrollBars()) { 7559 invalidate(true); 7560 } 7561 } 7562 } 7563 7564 /** 7565 * Move the scrolled position of your view. This will cause a call to 7566 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7567 * invalidated. 7568 * @param x the amount of pixels to scroll by horizontally 7569 * @param y the amount of pixels to scroll by vertically 7570 */ 7571 public void scrollBy(int x, int y) { 7572 scrollTo(mScrollX + x, mScrollY + y); 7573 } 7574 7575 /** 7576 * <p>Trigger the scrollbars to draw. When invoked this method starts an 7577 * animation to fade the scrollbars out after a default delay. If a subclass 7578 * provides animated scrolling, the start delay should equal the duration 7579 * of the scrolling animation.</p> 7580 * 7581 * <p>The animation starts only if at least one of the scrollbars is 7582 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 7583 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 7584 * this method returns true, and false otherwise. If the animation is 7585 * started, this method calls {@link #invalidate()}; in that case the 7586 * caller should not call {@link #invalidate()}.</p> 7587 * 7588 * <p>This method should be invoked every time a subclass directly updates 7589 * the scroll parameters.</p> 7590 * 7591 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 7592 * and {@link #scrollTo(int, int)}.</p> 7593 * 7594 * @return true if the animation is played, false otherwise 7595 * 7596 * @see #awakenScrollBars(int) 7597 * @see #scrollBy(int, int) 7598 * @see #scrollTo(int, int) 7599 * @see #isHorizontalScrollBarEnabled() 7600 * @see #isVerticalScrollBarEnabled() 7601 * @see #setHorizontalScrollBarEnabled(boolean) 7602 * @see #setVerticalScrollBarEnabled(boolean) 7603 */ 7604 protected boolean awakenScrollBars() { 7605 return mScrollCache != null && 7606 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 7607 } 7608 7609 /** 7610 * Trigger the scrollbars to draw. 7611 * This method differs from awakenScrollBars() only in its default duration. 7612 * initialAwakenScrollBars() will show the scroll bars for longer than 7613 * usual to give the user more of a chance to notice them. 7614 * 7615 * @return true if the animation is played, false otherwise. 7616 */ 7617 private boolean initialAwakenScrollBars() { 7618 return mScrollCache != null && 7619 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 7620 } 7621 7622 /** 7623 * <p> 7624 * Trigger the scrollbars to draw. When invoked this method starts an 7625 * animation to fade the scrollbars out after a fixed delay. If a subclass 7626 * provides animated scrolling, the start delay should equal the duration of 7627 * the scrolling animation. 7628 * </p> 7629 * 7630 * <p> 7631 * The animation starts only if at least one of the scrollbars is enabled, 7632 * as specified by {@link #isHorizontalScrollBarEnabled()} and 7633 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 7634 * this method returns true, and false otherwise. If the animation is 7635 * started, this method calls {@link #invalidate()}; in that case the caller 7636 * should not call {@link #invalidate()}. 7637 * </p> 7638 * 7639 * <p> 7640 * This method should be invoked everytime a subclass directly updates the 7641 * scroll parameters. 7642 * </p> 7643 * 7644 * @param startDelay the delay, in milliseconds, after which the animation 7645 * should start; when the delay is 0, the animation starts 7646 * immediately 7647 * @return true if the animation is played, false otherwise 7648 * 7649 * @see #scrollBy(int, int) 7650 * @see #scrollTo(int, int) 7651 * @see #isHorizontalScrollBarEnabled() 7652 * @see #isVerticalScrollBarEnabled() 7653 * @see #setHorizontalScrollBarEnabled(boolean) 7654 * @see #setVerticalScrollBarEnabled(boolean) 7655 */ 7656 protected boolean awakenScrollBars(int startDelay) { 7657 return awakenScrollBars(startDelay, true); 7658 } 7659 7660 /** 7661 * <p> 7662 * Trigger the scrollbars to draw. When invoked this method starts an 7663 * animation to fade the scrollbars out after a fixed delay. If a subclass 7664 * provides animated scrolling, the start delay should equal the duration of 7665 * the scrolling animation. 7666 * </p> 7667 * 7668 * <p> 7669 * The animation starts only if at least one of the scrollbars is enabled, 7670 * as specified by {@link #isHorizontalScrollBarEnabled()} and 7671 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 7672 * this method returns true, and false otherwise. If the animation is 7673 * started, this method calls {@link #invalidate()} if the invalidate parameter 7674 * is set to true; in that case the caller 7675 * should not call {@link #invalidate()}. 7676 * </p> 7677 * 7678 * <p> 7679 * This method should be invoked everytime a subclass directly updates the 7680 * scroll parameters. 7681 * </p> 7682 * 7683 * @param startDelay the delay, in milliseconds, after which the animation 7684 * should start; when the delay is 0, the animation starts 7685 * immediately 7686 * 7687 * @param invalidate Wheter this method should call invalidate 7688 * 7689 * @return true if the animation is played, false otherwise 7690 * 7691 * @see #scrollBy(int, int) 7692 * @see #scrollTo(int, int) 7693 * @see #isHorizontalScrollBarEnabled() 7694 * @see #isVerticalScrollBarEnabled() 7695 * @see #setHorizontalScrollBarEnabled(boolean) 7696 * @see #setVerticalScrollBarEnabled(boolean) 7697 */ 7698 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 7699 final ScrollabilityCache scrollCache = mScrollCache; 7700 7701 if (scrollCache == null || !scrollCache.fadeScrollBars) { 7702 return false; 7703 } 7704 7705 if (scrollCache.scrollBar == null) { 7706 scrollCache.scrollBar = new ScrollBarDrawable(); 7707 } 7708 7709 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 7710 7711 if (invalidate) { 7712 // Invalidate to show the scrollbars 7713 invalidate(true); 7714 } 7715 7716 if (scrollCache.state == ScrollabilityCache.OFF) { 7717 // FIXME: this is copied from WindowManagerService. 7718 // We should get this value from the system when it 7719 // is possible to do so. 7720 final int KEY_REPEAT_FIRST_DELAY = 750; 7721 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 7722 } 7723 7724 // Tell mScrollCache when we should start fading. This may 7725 // extend the fade start time if one was already scheduled 7726 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 7727 scrollCache.fadeStartTime = fadeStartTime; 7728 scrollCache.state = ScrollabilityCache.ON; 7729 7730 // Schedule our fader to run, unscheduling any old ones first 7731 if (mAttachInfo != null) { 7732 mAttachInfo.mHandler.removeCallbacks(scrollCache); 7733 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 7734 } 7735 7736 return true; 7737 } 7738 7739 return false; 7740 } 7741 7742 /** 7743 * Mark the the area defined by dirty as needing to be drawn. If the view is 7744 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 7745 * in the future. This must be called from a UI thread. To call from a non-UI 7746 * thread, call {@link #postInvalidate()}. 7747 * 7748 * WARNING: This method is destructive to dirty. 7749 * @param dirty the rectangle representing the bounds of the dirty region 7750 */ 7751 public void invalidate(Rect dirty) { 7752 if (ViewDebug.TRACE_HIERARCHY) { 7753 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 7754 } 7755 7756 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 7757 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 7758 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 7759 mPrivateFlags &= ~DRAWING_CACHE_VALID; 7760 mPrivateFlags |= INVALIDATED; 7761 final ViewParent p = mParent; 7762 final AttachInfo ai = mAttachInfo; 7763 //noinspection PointlessBooleanExpression,ConstantConditions 7764 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 7765 if (p != null && ai != null && ai.mHardwareAccelerated) { 7766 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 7767 // with a null dirty rect, which tells the ViewAncestor to redraw everything 7768 p.invalidateChild(this, null); 7769 return; 7770 } 7771 } 7772 if (p != null && ai != null) { 7773 final int scrollX = mScrollX; 7774 final int scrollY = mScrollY; 7775 final Rect r = ai.mTmpInvalRect; 7776 r.set(dirty.left - scrollX, dirty.top - scrollY, 7777 dirty.right - scrollX, dirty.bottom - scrollY); 7778 mParent.invalidateChild(this, r); 7779 } 7780 } 7781 } 7782 7783 /** 7784 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn. 7785 * The coordinates of the dirty rect are relative to the view. 7786 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 7787 * will be called at some point in the future. This must be called from 7788 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 7789 * @param l the left position of the dirty region 7790 * @param t the top position of the dirty region 7791 * @param r the right position of the dirty region 7792 * @param b the bottom position of the dirty region 7793 */ 7794 public void invalidate(int l, int t, int r, int b) { 7795 if (ViewDebug.TRACE_HIERARCHY) { 7796 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 7797 } 7798 7799 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 7800 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 7801 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 7802 mPrivateFlags &= ~DRAWING_CACHE_VALID; 7803 mPrivateFlags |= INVALIDATED; 7804 final ViewParent p = mParent; 7805 final AttachInfo ai = mAttachInfo; 7806 //noinspection PointlessBooleanExpression,ConstantConditions 7807 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 7808 if (p != null && ai != null && ai.mHardwareAccelerated) { 7809 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 7810 // with a null dirty rect, which tells the ViewAncestor to redraw everything 7811 p.invalidateChild(this, null); 7812 return; 7813 } 7814 } 7815 if (p != null && ai != null && l < r && t < b) { 7816 final int scrollX = mScrollX; 7817 final int scrollY = mScrollY; 7818 final Rect tmpr = ai.mTmpInvalRect; 7819 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 7820 p.invalidateChild(this, tmpr); 7821 } 7822 } 7823 } 7824 7825 /** 7826 * Invalidate the whole view. If the view is visible, 7827 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 7828 * the future. This must be called from a UI thread. To call from a non-UI thread, 7829 * call {@link #postInvalidate()}. 7830 */ 7831 public void invalidate() { 7832 invalidate(true); 7833 } 7834 7835 /** 7836 * This is where the invalidate() work actually happens. A full invalidate() 7837 * causes the drawing cache to be invalidated, but this function can be called with 7838 * invalidateCache set to false to skip that invalidation step for cases that do not 7839 * need it (for example, a component that remains at the same dimensions with the same 7840 * content). 7841 * 7842 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 7843 * well. This is usually true for a full invalidate, but may be set to false if the 7844 * View's contents or dimensions have not changed. 7845 */ 7846 void invalidate(boolean invalidateCache) { 7847 if (ViewDebug.TRACE_HIERARCHY) { 7848 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 7849 } 7850 7851 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 7852 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) || 7853 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) { 7854 mLastIsOpaque = isOpaque(); 7855 mPrivateFlags &= ~DRAWN; 7856 if (invalidateCache) { 7857 mPrivateFlags |= INVALIDATED; 7858 mPrivateFlags &= ~DRAWING_CACHE_VALID; 7859 } 7860 final AttachInfo ai = mAttachInfo; 7861 final ViewParent p = mParent; 7862 //noinspection PointlessBooleanExpression,ConstantConditions 7863 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 7864 if (p != null && ai != null && ai.mHardwareAccelerated) { 7865 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 7866 // with a null dirty rect, which tells the ViewAncestor to redraw everything 7867 p.invalidateChild(this, null); 7868 return; 7869 } 7870 } 7871 7872 if (p != null && ai != null) { 7873 final Rect r = ai.mTmpInvalRect; 7874 r.set(0, 0, mRight - mLeft, mBottom - mTop); 7875 // Don't call invalidate -- we don't want to internally scroll 7876 // our own bounds 7877 p.invalidateChild(this, r); 7878 } 7879 } 7880 } 7881 7882 /** 7883 * @hide 7884 */ 7885 public void fastInvalidate() { 7886 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 7887 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 7888 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 7889 if (mParent instanceof View) { 7890 ((View) mParent).mPrivateFlags |= INVALIDATED; 7891 } 7892 mPrivateFlags &= ~DRAWN; 7893 mPrivateFlags |= INVALIDATED; 7894 mPrivateFlags &= ~DRAWING_CACHE_VALID; 7895 if (mParent != null && mAttachInfo != null) { 7896 if (mAttachInfo.mHardwareAccelerated) { 7897 mParent.invalidateChild(this, null); 7898 } else { 7899 final Rect r = mAttachInfo.mTmpInvalRect; 7900 r.set(0, 0, mRight - mLeft, mBottom - mTop); 7901 // Don't call invalidate -- we don't want to internally scroll 7902 // our own bounds 7903 mParent.invalidateChild(this, r); 7904 } 7905 } 7906 } 7907 } 7908 7909 /** 7910 * Used to indicate that the parent of this view should clear its caches. This functionality 7911 * is used to force the parent to rebuild its display list (when hardware-accelerated), 7912 * which is necessary when various parent-managed properties of the view change, such as 7913 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 7914 * clears the parent caches and does not causes an invalidate event. 7915 * 7916 * @hide 7917 */ 7918 protected void invalidateParentCaches() { 7919 if (mParent instanceof View) { 7920 ((View) mParent).mPrivateFlags |= INVALIDATED; 7921 } 7922 } 7923 7924 /** 7925 * Used to indicate that the parent of this view should be invalidated. This functionality 7926 * is used to force the parent to rebuild its display list (when hardware-accelerated), 7927 * which is necessary when various parent-managed properties of the view change, such as 7928 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 7929 * an invalidation event to the parent. 7930 * 7931 * @hide 7932 */ 7933 protected void invalidateParentIfNeeded() { 7934 if (isHardwareAccelerated() && mParent instanceof View) { 7935 ((View) mParent).invalidate(true); 7936 } 7937 } 7938 7939 /** 7940 * Indicates whether this View is opaque. An opaque View guarantees that it will 7941 * draw all the pixels overlapping its bounds using a fully opaque color. 7942 * 7943 * Subclasses of View should override this method whenever possible to indicate 7944 * whether an instance is opaque. Opaque Views are treated in a special way by 7945 * the View hierarchy, possibly allowing it to perform optimizations during 7946 * invalidate/draw passes. 7947 * 7948 * @return True if this View is guaranteed to be fully opaque, false otherwise. 7949 */ 7950 @ViewDebug.ExportedProperty(category = "drawing") 7951 public boolean isOpaque() { 7952 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK && 7953 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD); 7954 } 7955 7956 /** 7957 * @hide 7958 */ 7959 protected void computeOpaqueFlags() { 7960 // Opaque if: 7961 // - Has a background 7962 // - Background is opaque 7963 // - Doesn't have scrollbars or scrollbars are inside overlay 7964 7965 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) { 7966 mPrivateFlags |= OPAQUE_BACKGROUND; 7967 } else { 7968 mPrivateFlags &= ~OPAQUE_BACKGROUND; 7969 } 7970 7971 final int flags = mViewFlags; 7972 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 7973 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 7974 mPrivateFlags |= OPAQUE_SCROLLBARS; 7975 } else { 7976 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 7977 } 7978 } 7979 7980 /** 7981 * @hide 7982 */ 7983 protected boolean hasOpaqueScrollbars() { 7984 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 7985 } 7986 7987 /** 7988 * @return A handler associated with the thread running the View. This 7989 * handler can be used to pump events in the UI events queue. 7990 */ 7991 public Handler getHandler() { 7992 if (mAttachInfo != null) { 7993 return mAttachInfo.mHandler; 7994 } 7995 return null; 7996 } 7997 7998 /** 7999 * Causes the Runnable to be added to the message queue. 8000 * The runnable will be run on the user interface thread. 8001 * 8002 * @param action The Runnable that will be executed. 8003 * 8004 * @return Returns true if the Runnable was successfully placed in to the 8005 * message queue. Returns false on failure, usually because the 8006 * looper processing the message queue is exiting. 8007 */ 8008 public boolean post(Runnable action) { 8009 Handler handler; 8010 AttachInfo attachInfo = mAttachInfo; 8011 if (attachInfo != null) { 8012 handler = attachInfo.mHandler; 8013 } else { 8014 // Assume that post will succeed later 8015 ViewAncestor.getRunQueue().post(action); 8016 return true; 8017 } 8018 8019 return handler.post(action); 8020 } 8021 8022 /** 8023 * Causes the Runnable to be added to the message queue, to be run 8024 * after the specified amount of time elapses. 8025 * The runnable will be run on the user interface thread. 8026 * 8027 * @param action The Runnable that will be executed. 8028 * @param delayMillis The delay (in milliseconds) until the Runnable 8029 * will be executed. 8030 * 8031 * @return true if the Runnable was successfully placed in to the 8032 * message queue. Returns false on failure, usually because the 8033 * looper processing the message queue is exiting. Note that a 8034 * result of true does not mean the Runnable will be processed -- 8035 * if the looper is quit before the delivery time of the message 8036 * occurs then the message will be dropped. 8037 */ 8038 public boolean postDelayed(Runnable action, long delayMillis) { 8039 Handler handler; 8040 AttachInfo attachInfo = mAttachInfo; 8041 if (attachInfo != null) { 8042 handler = attachInfo.mHandler; 8043 } else { 8044 // Assume that post will succeed later 8045 ViewAncestor.getRunQueue().postDelayed(action, delayMillis); 8046 return true; 8047 } 8048 8049 return handler.postDelayed(action, delayMillis); 8050 } 8051 8052 /** 8053 * Removes the specified Runnable from the message queue. 8054 * 8055 * @param action The Runnable to remove from the message handling queue 8056 * 8057 * @return true if this view could ask the Handler to remove the Runnable, 8058 * false otherwise. When the returned value is true, the Runnable 8059 * may or may not have been actually removed from the message queue 8060 * (for instance, if the Runnable was not in the queue already.) 8061 */ 8062 public boolean removeCallbacks(Runnable action) { 8063 Handler handler; 8064 AttachInfo attachInfo = mAttachInfo; 8065 if (attachInfo != null) { 8066 handler = attachInfo.mHandler; 8067 } else { 8068 // Assume that post will succeed later 8069 ViewAncestor.getRunQueue().removeCallbacks(action); 8070 return true; 8071 } 8072 8073 handler.removeCallbacks(action); 8074 return true; 8075 } 8076 8077 /** 8078 * Cause an invalidate to happen on a subsequent cycle through the event loop. 8079 * Use this to invalidate the View from a non-UI thread. 8080 * 8081 * @see #invalidate() 8082 */ 8083 public void postInvalidate() { 8084 postInvalidateDelayed(0); 8085 } 8086 8087 /** 8088 * Cause an invalidate of the specified area to happen on a subsequent cycle 8089 * through the event loop. Use this to invalidate the View from a non-UI thread. 8090 * 8091 * @param left The left coordinate of the rectangle to invalidate. 8092 * @param top The top coordinate of the rectangle to invalidate. 8093 * @param right The right coordinate of the rectangle to invalidate. 8094 * @param bottom The bottom coordinate of the rectangle to invalidate. 8095 * 8096 * @see #invalidate(int, int, int, int) 8097 * @see #invalidate(Rect) 8098 */ 8099 public void postInvalidate(int left, int top, int right, int bottom) { 8100 postInvalidateDelayed(0, left, top, right, bottom); 8101 } 8102 8103 /** 8104 * Cause an invalidate to happen on a subsequent cycle through the event 8105 * loop. Waits for the specified amount of time. 8106 * 8107 * @param delayMilliseconds the duration in milliseconds to delay the 8108 * invalidation by 8109 */ 8110 public void postInvalidateDelayed(long delayMilliseconds) { 8111 // We try only with the AttachInfo because there's no point in invalidating 8112 // if we are not attached to our window 8113 AttachInfo attachInfo = mAttachInfo; 8114 if (attachInfo != null) { 8115 Message msg = Message.obtain(); 8116 msg.what = AttachInfo.INVALIDATE_MSG; 8117 msg.obj = this; 8118 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8119 } 8120 } 8121 8122 /** 8123 * Cause an invalidate of the specified area to happen on a subsequent cycle 8124 * through the event loop. Waits for the specified amount of time. 8125 * 8126 * @param delayMilliseconds the duration in milliseconds to delay the 8127 * invalidation by 8128 * @param left The left coordinate of the rectangle to invalidate. 8129 * @param top The top coordinate of the rectangle to invalidate. 8130 * @param right The right coordinate of the rectangle to invalidate. 8131 * @param bottom The bottom coordinate of the rectangle to invalidate. 8132 */ 8133 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 8134 int right, int bottom) { 8135 8136 // We try only with the AttachInfo because there's no point in invalidating 8137 // if we are not attached to our window 8138 AttachInfo attachInfo = mAttachInfo; 8139 if (attachInfo != null) { 8140 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 8141 info.target = this; 8142 info.left = left; 8143 info.top = top; 8144 info.right = right; 8145 info.bottom = bottom; 8146 8147 final Message msg = Message.obtain(); 8148 msg.what = AttachInfo.INVALIDATE_RECT_MSG; 8149 msg.obj = info; 8150 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8151 } 8152 } 8153 8154 /** 8155 * Called by a parent to request that a child update its values for mScrollX 8156 * and mScrollY if necessary. This will typically be done if the child is 8157 * animating a scroll using a {@link android.widget.Scroller Scroller} 8158 * object. 8159 */ 8160 public void computeScroll() { 8161 } 8162 8163 /** 8164 * <p>Indicate whether the horizontal edges are faded when the view is 8165 * scrolled horizontally.</p> 8166 * 8167 * @return true if the horizontal edges should are faded on scroll, false 8168 * otherwise 8169 * 8170 * @see #setHorizontalFadingEdgeEnabled(boolean) 8171 * @attr ref android.R.styleable#View_fadingEdge 8172 */ 8173 public boolean isHorizontalFadingEdgeEnabled() { 8174 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 8175 } 8176 8177 /** 8178 * <p>Define whether the horizontal edges should be faded when this view 8179 * is scrolled horizontally.</p> 8180 * 8181 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 8182 * be faded when the view is scrolled 8183 * horizontally 8184 * 8185 * @see #isHorizontalFadingEdgeEnabled() 8186 * @attr ref android.R.styleable#View_fadingEdge 8187 */ 8188 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 8189 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 8190 if (horizontalFadingEdgeEnabled) { 8191 initScrollCache(); 8192 } 8193 8194 mViewFlags ^= FADING_EDGE_HORIZONTAL; 8195 } 8196 } 8197 8198 /** 8199 * <p>Indicate whether the vertical edges are faded when the view is 8200 * scrolled horizontally.</p> 8201 * 8202 * @return true if the vertical edges should are faded on scroll, false 8203 * otherwise 8204 * 8205 * @see #setVerticalFadingEdgeEnabled(boolean) 8206 * @attr ref android.R.styleable#View_fadingEdge 8207 */ 8208 public boolean isVerticalFadingEdgeEnabled() { 8209 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 8210 } 8211 8212 /** 8213 * <p>Define whether the vertical edges should be faded when this view 8214 * is scrolled vertically.</p> 8215 * 8216 * @param verticalFadingEdgeEnabled true if the vertical edges should 8217 * be faded when the view is scrolled 8218 * vertically 8219 * 8220 * @see #isVerticalFadingEdgeEnabled() 8221 * @attr ref android.R.styleable#View_fadingEdge 8222 */ 8223 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 8224 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 8225 if (verticalFadingEdgeEnabled) { 8226 initScrollCache(); 8227 } 8228 8229 mViewFlags ^= FADING_EDGE_VERTICAL; 8230 } 8231 } 8232 8233 /** 8234 * Returns the strength, or intensity, of the top faded edge. The strength is 8235 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8236 * returns 0.0 or 1.0 but no value in between. 8237 * 8238 * Subclasses should override this method to provide a smoother fade transition 8239 * when scrolling occurs. 8240 * 8241 * @return the intensity of the top fade as a float between 0.0f and 1.0f 8242 */ 8243 protected float getTopFadingEdgeStrength() { 8244 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 8245 } 8246 8247 /** 8248 * Returns the strength, or intensity, of the bottom faded edge. The strength is 8249 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8250 * returns 0.0 or 1.0 but no value in between. 8251 * 8252 * Subclasses should override this method to provide a smoother fade transition 8253 * when scrolling occurs. 8254 * 8255 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 8256 */ 8257 protected float getBottomFadingEdgeStrength() { 8258 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 8259 computeVerticalScrollRange() ? 1.0f : 0.0f; 8260 } 8261 8262 /** 8263 * Returns the strength, or intensity, of the left faded edge. The strength is 8264 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8265 * returns 0.0 or 1.0 but no value in between. 8266 * 8267 * Subclasses should override this method to provide a smoother fade transition 8268 * when scrolling occurs. 8269 * 8270 * @return the intensity of the left fade as a float between 0.0f and 1.0f 8271 */ 8272 protected float getLeftFadingEdgeStrength() { 8273 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 8274 } 8275 8276 /** 8277 * Returns the strength, or intensity, of the right faded edge. The strength is 8278 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8279 * returns 0.0 or 1.0 but no value in between. 8280 * 8281 * Subclasses should override this method to provide a smoother fade transition 8282 * when scrolling occurs. 8283 * 8284 * @return the intensity of the right fade as a float between 0.0f and 1.0f 8285 */ 8286 protected float getRightFadingEdgeStrength() { 8287 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 8288 computeHorizontalScrollRange() ? 1.0f : 0.0f; 8289 } 8290 8291 /** 8292 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 8293 * scrollbar is not drawn by default.</p> 8294 * 8295 * @return true if the horizontal scrollbar should be painted, false 8296 * otherwise 8297 * 8298 * @see #setHorizontalScrollBarEnabled(boolean) 8299 */ 8300 public boolean isHorizontalScrollBarEnabled() { 8301 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 8302 } 8303 8304 /** 8305 * <p>Define whether the horizontal scrollbar should be drawn or not. The 8306 * scrollbar is not drawn by default.</p> 8307 * 8308 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 8309 * be painted 8310 * 8311 * @see #isHorizontalScrollBarEnabled() 8312 */ 8313 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 8314 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 8315 mViewFlags ^= SCROLLBARS_HORIZONTAL; 8316 computeOpaqueFlags(); 8317 resolvePadding(); 8318 } 8319 } 8320 8321 /** 8322 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 8323 * scrollbar is not drawn by default.</p> 8324 * 8325 * @return true if the vertical scrollbar should be painted, false 8326 * otherwise 8327 * 8328 * @see #setVerticalScrollBarEnabled(boolean) 8329 */ 8330 public boolean isVerticalScrollBarEnabled() { 8331 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 8332 } 8333 8334 /** 8335 * <p>Define whether the vertical scrollbar should be drawn or not. The 8336 * scrollbar is not drawn by default.</p> 8337 * 8338 * @param verticalScrollBarEnabled true if the vertical scrollbar should 8339 * be painted 8340 * 8341 * @see #isVerticalScrollBarEnabled() 8342 */ 8343 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 8344 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 8345 mViewFlags ^= SCROLLBARS_VERTICAL; 8346 computeOpaqueFlags(); 8347 resolvePadding(); 8348 } 8349 } 8350 8351 /** 8352 * @hide 8353 */ 8354 protected void recomputePadding() { 8355 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 8356 } 8357 8358 /** 8359 * Define whether scrollbars will fade when the view is not scrolling. 8360 * 8361 * @param fadeScrollbars wheter to enable fading 8362 * 8363 */ 8364 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 8365 initScrollCache(); 8366 final ScrollabilityCache scrollabilityCache = mScrollCache; 8367 scrollabilityCache.fadeScrollBars = fadeScrollbars; 8368 if (fadeScrollbars) { 8369 scrollabilityCache.state = ScrollabilityCache.OFF; 8370 } else { 8371 scrollabilityCache.state = ScrollabilityCache.ON; 8372 } 8373 } 8374 8375 /** 8376 * 8377 * Returns true if scrollbars will fade when this view is not scrolling 8378 * 8379 * @return true if scrollbar fading is enabled 8380 */ 8381 public boolean isScrollbarFadingEnabled() { 8382 return mScrollCache != null && mScrollCache.fadeScrollBars; 8383 } 8384 8385 /** 8386 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 8387 * inset. When inset, they add to the padding of the view. And the scrollbars 8388 * can be drawn inside the padding area or on the edge of the view. For example, 8389 * if a view has a background drawable and you want to draw the scrollbars 8390 * inside the padding specified by the drawable, you can use 8391 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 8392 * appear at the edge of the view, ignoring the padding, then you can use 8393 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 8394 * @param style the style of the scrollbars. Should be one of 8395 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 8396 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 8397 * @see #SCROLLBARS_INSIDE_OVERLAY 8398 * @see #SCROLLBARS_INSIDE_INSET 8399 * @see #SCROLLBARS_OUTSIDE_OVERLAY 8400 * @see #SCROLLBARS_OUTSIDE_INSET 8401 */ 8402 public void setScrollBarStyle(int style) { 8403 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 8404 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 8405 computeOpaqueFlags(); 8406 resolvePadding(); 8407 } 8408 } 8409 8410 /** 8411 * <p>Returns the current scrollbar style.</p> 8412 * @return the current scrollbar style 8413 * @see #SCROLLBARS_INSIDE_OVERLAY 8414 * @see #SCROLLBARS_INSIDE_INSET 8415 * @see #SCROLLBARS_OUTSIDE_OVERLAY 8416 * @see #SCROLLBARS_OUTSIDE_INSET 8417 */ 8418 public int getScrollBarStyle() { 8419 return mViewFlags & SCROLLBARS_STYLE_MASK; 8420 } 8421 8422 /** 8423 * <p>Compute the horizontal range that the horizontal scrollbar 8424 * represents.</p> 8425 * 8426 * <p>The range is expressed in arbitrary units that must be the same as the 8427 * units used by {@link #computeHorizontalScrollExtent()} and 8428 * {@link #computeHorizontalScrollOffset()}.</p> 8429 * 8430 * <p>The default range is the drawing width of this view.</p> 8431 * 8432 * @return the total horizontal range represented by the horizontal 8433 * scrollbar 8434 * 8435 * @see #computeHorizontalScrollExtent() 8436 * @see #computeHorizontalScrollOffset() 8437 * @see android.widget.ScrollBarDrawable 8438 */ 8439 protected int computeHorizontalScrollRange() { 8440 return getWidth(); 8441 } 8442 8443 /** 8444 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 8445 * within the horizontal range. This value is used to compute the position 8446 * of the thumb within the scrollbar's track.</p> 8447 * 8448 * <p>The range is expressed in arbitrary units that must be the same as the 8449 * units used by {@link #computeHorizontalScrollRange()} and 8450 * {@link #computeHorizontalScrollExtent()}.</p> 8451 * 8452 * <p>The default offset is the scroll offset of this view.</p> 8453 * 8454 * @return the horizontal offset of the scrollbar's thumb 8455 * 8456 * @see #computeHorizontalScrollRange() 8457 * @see #computeHorizontalScrollExtent() 8458 * @see android.widget.ScrollBarDrawable 8459 */ 8460 protected int computeHorizontalScrollOffset() { 8461 return mScrollX; 8462 } 8463 8464 /** 8465 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 8466 * within the horizontal range. This value is used to compute the length 8467 * of the thumb within the scrollbar's track.</p> 8468 * 8469 * <p>The range is expressed in arbitrary units that must be the same as the 8470 * units used by {@link #computeHorizontalScrollRange()} and 8471 * {@link #computeHorizontalScrollOffset()}.</p> 8472 * 8473 * <p>The default extent is the drawing width of this view.</p> 8474 * 8475 * @return the horizontal extent of the scrollbar's thumb 8476 * 8477 * @see #computeHorizontalScrollRange() 8478 * @see #computeHorizontalScrollOffset() 8479 * @see android.widget.ScrollBarDrawable 8480 */ 8481 protected int computeHorizontalScrollExtent() { 8482 return getWidth(); 8483 } 8484 8485 /** 8486 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 8487 * 8488 * <p>The range is expressed in arbitrary units that must be the same as the 8489 * units used by {@link #computeVerticalScrollExtent()} and 8490 * {@link #computeVerticalScrollOffset()}.</p> 8491 * 8492 * @return the total vertical range represented by the vertical scrollbar 8493 * 8494 * <p>The default range is the drawing height of this view.</p> 8495 * 8496 * @see #computeVerticalScrollExtent() 8497 * @see #computeVerticalScrollOffset() 8498 * @see android.widget.ScrollBarDrawable 8499 */ 8500 protected int computeVerticalScrollRange() { 8501 return getHeight(); 8502 } 8503 8504 /** 8505 * <p>Compute the vertical offset of the vertical scrollbar's thumb 8506 * within the horizontal range. This value is used to compute the position 8507 * of the thumb within the scrollbar's track.</p> 8508 * 8509 * <p>The range is expressed in arbitrary units that must be the same as the 8510 * units used by {@link #computeVerticalScrollRange()} and 8511 * {@link #computeVerticalScrollExtent()}.</p> 8512 * 8513 * <p>The default offset is the scroll offset of this view.</p> 8514 * 8515 * @return the vertical offset of the scrollbar's thumb 8516 * 8517 * @see #computeVerticalScrollRange() 8518 * @see #computeVerticalScrollExtent() 8519 * @see android.widget.ScrollBarDrawable 8520 */ 8521 protected int computeVerticalScrollOffset() { 8522 return mScrollY; 8523 } 8524 8525 /** 8526 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 8527 * within the vertical range. This value is used to compute the length 8528 * of the thumb within the scrollbar's track.</p> 8529 * 8530 * <p>The range is expressed in arbitrary units that must be the same as the 8531 * units used by {@link #computeVerticalScrollRange()} and 8532 * {@link #computeVerticalScrollOffset()}.</p> 8533 * 8534 * <p>The default extent is the drawing height of this view.</p> 8535 * 8536 * @return the vertical extent of the scrollbar's thumb 8537 * 8538 * @see #computeVerticalScrollRange() 8539 * @see #computeVerticalScrollOffset() 8540 * @see android.widget.ScrollBarDrawable 8541 */ 8542 protected int computeVerticalScrollExtent() { 8543 return getHeight(); 8544 } 8545 8546 /** 8547 * Check if this view can be scrolled horizontally in a certain direction. 8548 * 8549 * @param direction Negative to check scrolling left, positive to check scrolling right. 8550 * @return true if this view can be scrolled in the specified direction, false otherwise. 8551 */ 8552 public boolean canScrollHorizontally(int direction) { 8553 final int offset = computeHorizontalScrollOffset(); 8554 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 8555 if (range == 0) return false; 8556 if (direction < 0) { 8557 return offset > 0; 8558 } else { 8559 return offset < range - 1; 8560 } 8561 } 8562 8563 /** 8564 * Check if this view can be scrolled vertically in a certain direction. 8565 * 8566 * @param direction Negative to check scrolling up, positive to check scrolling down. 8567 * @return true if this view can be scrolled in the specified direction, false otherwise. 8568 */ 8569 public boolean canScrollVertically(int direction) { 8570 final int offset = computeVerticalScrollOffset(); 8571 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 8572 if (range == 0) return false; 8573 if (direction < 0) { 8574 return offset > 0; 8575 } else { 8576 return offset < range - 1; 8577 } 8578 } 8579 8580 /** 8581 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 8582 * scrollbars are painted only if they have been awakened first.</p> 8583 * 8584 * @param canvas the canvas on which to draw the scrollbars 8585 * 8586 * @see #awakenScrollBars(int) 8587 */ 8588 protected final void onDrawScrollBars(Canvas canvas) { 8589 // scrollbars are drawn only when the animation is running 8590 final ScrollabilityCache cache = mScrollCache; 8591 if (cache != null) { 8592 8593 int state = cache.state; 8594 8595 if (state == ScrollabilityCache.OFF) { 8596 return; 8597 } 8598 8599 boolean invalidate = false; 8600 8601 if (state == ScrollabilityCache.FADING) { 8602 // We're fading -- get our fade interpolation 8603 if (cache.interpolatorValues == null) { 8604 cache.interpolatorValues = new float[1]; 8605 } 8606 8607 float[] values = cache.interpolatorValues; 8608 8609 // Stops the animation if we're done 8610 if (cache.scrollBarInterpolator.timeToValues(values) == 8611 Interpolator.Result.FREEZE_END) { 8612 cache.state = ScrollabilityCache.OFF; 8613 } else { 8614 cache.scrollBar.setAlpha(Math.round(values[0])); 8615 } 8616 8617 // This will make the scroll bars inval themselves after 8618 // drawing. We only want this when we're fading so that 8619 // we prevent excessive redraws 8620 invalidate = true; 8621 } else { 8622 // We're just on -- but we may have been fading before so 8623 // reset alpha 8624 cache.scrollBar.setAlpha(255); 8625 } 8626 8627 8628 final int viewFlags = mViewFlags; 8629 8630 final boolean drawHorizontalScrollBar = 8631 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 8632 final boolean drawVerticalScrollBar = 8633 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 8634 && !isVerticalScrollBarHidden(); 8635 8636 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 8637 final int width = mRight - mLeft; 8638 final int height = mBottom - mTop; 8639 8640 final ScrollBarDrawable scrollBar = cache.scrollBar; 8641 8642 final int scrollX = mScrollX; 8643 final int scrollY = mScrollY; 8644 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 8645 8646 int left, top, right, bottom; 8647 8648 if (drawHorizontalScrollBar) { 8649 int size = scrollBar.getSize(false); 8650 if (size <= 0) { 8651 size = cache.scrollBarSize; 8652 } 8653 8654 scrollBar.setParameters(computeHorizontalScrollRange(), 8655 computeHorizontalScrollOffset(), 8656 computeHorizontalScrollExtent(), false); 8657 final int verticalScrollBarGap = drawVerticalScrollBar ? 8658 getVerticalScrollbarWidth() : 0; 8659 top = scrollY + height - size - (mUserPaddingBottom & inside); 8660 left = scrollX + (mPaddingLeft & inside); 8661 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 8662 bottom = top + size; 8663 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 8664 if (invalidate) { 8665 invalidate(left, top, right, bottom); 8666 } 8667 } 8668 8669 if (drawVerticalScrollBar) { 8670 int size = scrollBar.getSize(true); 8671 if (size <= 0) { 8672 size = cache.scrollBarSize; 8673 } 8674 8675 scrollBar.setParameters(computeVerticalScrollRange(), 8676 computeVerticalScrollOffset(), 8677 computeVerticalScrollExtent(), true); 8678 switch (mVerticalScrollbarPosition) { 8679 default: 8680 case SCROLLBAR_POSITION_DEFAULT: 8681 case SCROLLBAR_POSITION_RIGHT: 8682 left = scrollX + width - size - (mUserPaddingRight & inside); 8683 break; 8684 case SCROLLBAR_POSITION_LEFT: 8685 left = scrollX + (mUserPaddingLeft & inside); 8686 break; 8687 } 8688 top = scrollY + (mPaddingTop & inside); 8689 right = left + size; 8690 bottom = scrollY + height - (mUserPaddingBottom & inside); 8691 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 8692 if (invalidate) { 8693 invalidate(left, top, right, bottom); 8694 } 8695 } 8696 } 8697 } 8698 } 8699 8700 /** 8701 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 8702 * FastScroller is visible. 8703 * @return whether to temporarily hide the vertical scrollbar 8704 * @hide 8705 */ 8706 protected boolean isVerticalScrollBarHidden() { 8707 return false; 8708 } 8709 8710 /** 8711 * <p>Draw the horizontal scrollbar if 8712 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 8713 * 8714 * @param canvas the canvas on which to draw the scrollbar 8715 * @param scrollBar the scrollbar's drawable 8716 * 8717 * @see #isHorizontalScrollBarEnabled() 8718 * @see #computeHorizontalScrollRange() 8719 * @see #computeHorizontalScrollExtent() 8720 * @see #computeHorizontalScrollOffset() 8721 * @see android.widget.ScrollBarDrawable 8722 * @hide 8723 */ 8724 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 8725 int l, int t, int r, int b) { 8726 scrollBar.setBounds(l, t, r, b); 8727 scrollBar.draw(canvas); 8728 } 8729 8730 /** 8731 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 8732 * returns true.</p> 8733 * 8734 * @param canvas the canvas on which to draw the scrollbar 8735 * @param scrollBar the scrollbar's drawable 8736 * 8737 * @see #isVerticalScrollBarEnabled() 8738 * @see #computeVerticalScrollRange() 8739 * @see #computeVerticalScrollExtent() 8740 * @see #computeVerticalScrollOffset() 8741 * @see android.widget.ScrollBarDrawable 8742 * @hide 8743 */ 8744 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 8745 int l, int t, int r, int b) { 8746 scrollBar.setBounds(l, t, r, b); 8747 scrollBar.draw(canvas); 8748 } 8749 8750 /** 8751 * Implement this to do your drawing. 8752 * 8753 * @param canvas the canvas on which the background will be drawn 8754 */ 8755 protected void onDraw(Canvas canvas) { 8756 } 8757 8758 /* 8759 * Caller is responsible for calling requestLayout if necessary. 8760 * (This allows addViewInLayout to not request a new layout.) 8761 */ 8762 void assignParent(ViewParent parent) { 8763 if (mParent == null) { 8764 mParent = parent; 8765 } else if (parent == null) { 8766 mParent = null; 8767 } else { 8768 throw new RuntimeException("view " + this + " being added, but" 8769 + " it already has a parent"); 8770 } 8771 } 8772 8773 /** 8774 * This is called when the view is attached to a window. At this point it 8775 * has a Surface and will start drawing. Note that this function is 8776 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 8777 * however it may be called any time before the first onDraw -- including 8778 * before or after {@link #onMeasure(int, int)}. 8779 * 8780 * @see #onDetachedFromWindow() 8781 */ 8782 protected void onAttachedToWindow() { 8783 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 8784 mParent.requestTransparentRegion(this); 8785 } 8786 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 8787 initialAwakenScrollBars(); 8788 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH; 8789 } 8790 jumpDrawablesToCurrentState(); 8791 resetLayoutDirectionResolution(); 8792 resolveLayoutDirectionIfNeeded(); 8793 resolvePadding(); 8794 if (isFocused()) { 8795 InputMethodManager imm = InputMethodManager.peekInstance(); 8796 imm.focusIn(this); 8797 } 8798 } 8799 8800 /** 8801 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 8802 * that the parent directionality can and will be resolved before its children. 8803 */ 8804 private void resolveLayoutDirectionIfNeeded() { 8805 // Do not resolve if it is not needed 8806 if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return; 8807 8808 // Clear any previous layout direction resolution 8809 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL; 8810 8811 // Set resolved depending on layout direction 8812 switch (getLayoutDirection()) { 8813 case LAYOUT_DIRECTION_INHERIT: 8814 // If this is root view, no need to look at parent's layout dir. 8815 if (mParent != null && 8816 mParent instanceof ViewGroup && 8817 ((ViewGroup) mParent).getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 8818 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 8819 } 8820 break; 8821 case LAYOUT_DIRECTION_RTL: 8822 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 8823 break; 8824 case LAYOUT_DIRECTION_LOCALE: 8825 if(isLayoutDirectionRtl(Locale.getDefault())) { 8826 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 8827 } 8828 break; 8829 default: 8830 // Nothing to do, LTR by default 8831 } 8832 8833 // Set to resolved 8834 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED; 8835 } 8836 8837 private void resolvePadding() { 8838 // If the user specified the absolute padding (either with android:padding or 8839 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 8840 // use the default padding or the padding from the background drawable 8841 // (stored at this point in mPadding*) 8842 switch (getResolvedLayoutDirection()) { 8843 case LAYOUT_DIRECTION_RTL: 8844 // Start user padding override Right user padding. Otherwise, if Right user 8845 // padding is not defined, use the default Right padding. If Right user padding 8846 // is defined, just use it. 8847 if (mUserPaddingStart >= 0) { 8848 mUserPaddingRight = mUserPaddingStart; 8849 } else if (mUserPaddingRight < 0) { 8850 mUserPaddingRight = mPaddingRight; 8851 } 8852 if (mUserPaddingEnd >= 0) { 8853 mUserPaddingLeft = mUserPaddingEnd; 8854 } else if (mUserPaddingLeft < 0) { 8855 mUserPaddingLeft = mPaddingLeft; 8856 } 8857 break; 8858 case LAYOUT_DIRECTION_LTR: 8859 default: 8860 // Start user padding override Left user padding. Otherwise, if Left user 8861 // padding is not defined, use the default left padding. If Left user padding 8862 // is defined, just use it. 8863 if (mUserPaddingStart > 0) { 8864 mUserPaddingLeft = mUserPaddingStart; 8865 } else if (mUserPaddingLeft < 0) { 8866 mUserPaddingLeft = mPaddingLeft; 8867 } 8868 if (mUserPaddingEnd > 0) { 8869 mUserPaddingRight = mUserPaddingEnd; 8870 } else if (mUserPaddingRight < 0) { 8871 mUserPaddingRight = mPaddingRight; 8872 } 8873 } 8874 8875 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 8876 8877 recomputePadding(); 8878 } 8879 8880 /** 8881 * Reset the resolved layout direction by clearing the corresponding flag 8882 */ 8883 private void resetLayoutDirectionResolution() { 8884 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED; 8885 } 8886 8887 /** 8888 * Check if a Locale is corresponding to a RTL script. 8889 * 8890 * @param locale Locale to check 8891 * @return true if a Locale is corresponding to a RTL script. 8892 */ 8893 private static boolean isLayoutDirectionRtl(Locale locale) { 8894 return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE == 8895 LocaleUtil.getLayoutDirectionFromLocale(locale)); 8896 } 8897 8898 /** 8899 * This is called when the view is detached from a window. At this point it 8900 * no longer has a surface for drawing. 8901 * 8902 * @see #onAttachedToWindow() 8903 */ 8904 protected void onDetachedFromWindow() { 8905 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 8906 8907 removeUnsetPressCallback(); 8908 removeLongPressCallback(); 8909 removePerformClickCallback(); 8910 8911 destroyDrawingCache(); 8912 8913 if (mHardwareLayer != null) { 8914 mHardwareLayer.destroy(); 8915 mHardwareLayer = null; 8916 } 8917 8918 if (mDisplayList != null) { 8919 mDisplayList.invalidate(); 8920 } 8921 8922 if (mAttachInfo != null) { 8923 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this); 8924 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_RECT_MSG, this); 8925 } 8926 8927 mCurrentAnimation = null; 8928 } 8929 8930 /** 8931 * @return The number of times this view has been attached to a window 8932 */ 8933 protected int getWindowAttachCount() { 8934 return mWindowAttachCount; 8935 } 8936 8937 /** 8938 * Retrieve a unique token identifying the window this view is attached to. 8939 * @return Return the window's token for use in 8940 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 8941 */ 8942 public IBinder getWindowToken() { 8943 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 8944 } 8945 8946 /** 8947 * Retrieve a unique token identifying the top-level "real" window of 8948 * the window that this view is attached to. That is, this is like 8949 * {@link #getWindowToken}, except if the window this view in is a panel 8950 * window (attached to another containing window), then the token of 8951 * the containing window is returned instead. 8952 * 8953 * @return Returns the associated window token, either 8954 * {@link #getWindowToken()} or the containing window's token. 8955 */ 8956 public IBinder getApplicationWindowToken() { 8957 AttachInfo ai = mAttachInfo; 8958 if (ai != null) { 8959 IBinder appWindowToken = ai.mPanelParentWindowToken; 8960 if (appWindowToken == null) { 8961 appWindowToken = ai.mWindowToken; 8962 } 8963 return appWindowToken; 8964 } 8965 return null; 8966 } 8967 8968 /** 8969 * Retrieve private session object this view hierarchy is using to 8970 * communicate with the window manager. 8971 * @return the session object to communicate with the window manager 8972 */ 8973 /*package*/ IWindowSession getWindowSession() { 8974 return mAttachInfo != null ? mAttachInfo.mSession : null; 8975 } 8976 8977 /** 8978 * @param info the {@link android.view.View.AttachInfo} to associated with 8979 * this view 8980 */ 8981 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 8982 //System.out.println("Attached! " + this); 8983 mAttachInfo = info; 8984 mWindowAttachCount++; 8985 // We will need to evaluate the drawable state at least once. 8986 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 8987 if (mFloatingTreeObserver != null) { 8988 info.mTreeObserver.merge(mFloatingTreeObserver); 8989 mFloatingTreeObserver = null; 8990 } 8991 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 8992 mAttachInfo.mScrollContainers.add(this); 8993 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 8994 } 8995 performCollectViewAttributes(visibility); 8996 onAttachedToWindow(); 8997 8998 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 8999 mOnAttachStateChangeListeners; 9000 if (listeners != null && listeners.size() > 0) { 9001 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9002 // perform the dispatching. The iterator is a safe guard against listeners that 9003 // could mutate the list by calling the various add/remove methods. This prevents 9004 // the array from being modified while we iterate it. 9005 for (OnAttachStateChangeListener listener : listeners) { 9006 listener.onViewAttachedToWindow(this); 9007 } 9008 } 9009 9010 int vis = info.mWindowVisibility; 9011 if (vis != GONE) { 9012 onWindowVisibilityChanged(vis); 9013 } 9014 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 9015 // If nobody has evaluated the drawable state yet, then do it now. 9016 refreshDrawableState(); 9017 } 9018 } 9019 9020 void dispatchDetachedFromWindow() { 9021 AttachInfo info = mAttachInfo; 9022 if (info != null) { 9023 int vis = info.mWindowVisibility; 9024 if (vis != GONE) { 9025 onWindowVisibilityChanged(GONE); 9026 } 9027 } 9028 9029 onDetachedFromWindow(); 9030 9031 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9032 mOnAttachStateChangeListeners; 9033 if (listeners != null && listeners.size() > 0) { 9034 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9035 // perform the dispatching. The iterator is a safe guard against listeners that 9036 // could mutate the list by calling the various add/remove methods. This prevents 9037 // the array from being modified while we iterate it. 9038 for (OnAttachStateChangeListener listener : listeners) { 9039 listener.onViewDetachedFromWindow(this); 9040 } 9041 } 9042 9043 if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) { 9044 mAttachInfo.mScrollContainers.remove(this); 9045 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 9046 } 9047 9048 mAttachInfo = null; 9049 } 9050 9051 /** 9052 * Store this view hierarchy's frozen state into the given container. 9053 * 9054 * @param container The SparseArray in which to save the view's state. 9055 * 9056 * @see #restoreHierarchyState(android.util.SparseArray) 9057 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9058 * @see #onSaveInstanceState() 9059 */ 9060 public void saveHierarchyState(SparseArray<Parcelable> container) { 9061 dispatchSaveInstanceState(container); 9062 } 9063 9064 /** 9065 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 9066 * this view and its children. May be overridden to modify how freezing happens to a 9067 * view's children; for example, some views may want to not store state for their children. 9068 * 9069 * @param container The SparseArray in which to save the view's state. 9070 * 9071 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9072 * @see #saveHierarchyState(android.util.SparseArray) 9073 * @see #onSaveInstanceState() 9074 */ 9075 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 9076 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 9077 mPrivateFlags &= ~SAVE_STATE_CALLED; 9078 Parcelable state = onSaveInstanceState(); 9079 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9080 throw new IllegalStateException( 9081 "Derived class did not call super.onSaveInstanceState()"); 9082 } 9083 if (state != null) { 9084 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 9085 // + ": " + state); 9086 container.put(mID, state); 9087 } 9088 } 9089 } 9090 9091 /** 9092 * Hook allowing a view to generate a representation of its internal state 9093 * that can later be used to create a new instance with that same state. 9094 * This state should only contain information that is not persistent or can 9095 * not be reconstructed later. For example, you will never store your 9096 * current position on screen because that will be computed again when a 9097 * new instance of the view is placed in its view hierarchy. 9098 * <p> 9099 * Some examples of things you may store here: the current cursor position 9100 * in a text view (but usually not the text itself since that is stored in a 9101 * content provider or other persistent storage), the currently selected 9102 * item in a list view. 9103 * 9104 * @return Returns a Parcelable object containing the view's current dynamic 9105 * state, or null if there is nothing interesting to save. The 9106 * default implementation returns null. 9107 * @see #onRestoreInstanceState(android.os.Parcelable) 9108 * @see #saveHierarchyState(android.util.SparseArray) 9109 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9110 * @see #setSaveEnabled(boolean) 9111 */ 9112 protected Parcelable onSaveInstanceState() { 9113 mPrivateFlags |= SAVE_STATE_CALLED; 9114 return BaseSavedState.EMPTY_STATE; 9115 } 9116 9117 /** 9118 * Restore this view hierarchy's frozen state from the given container. 9119 * 9120 * @param container The SparseArray which holds previously frozen states. 9121 * 9122 * @see #saveHierarchyState(android.util.SparseArray) 9123 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9124 * @see #onRestoreInstanceState(android.os.Parcelable) 9125 */ 9126 public void restoreHierarchyState(SparseArray<Parcelable> container) { 9127 dispatchRestoreInstanceState(container); 9128 } 9129 9130 /** 9131 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 9132 * state for this view and its children. May be overridden to modify how restoring 9133 * happens to a view's children; for example, some views may want to not store state 9134 * for their children. 9135 * 9136 * @param container The SparseArray which holds previously saved state. 9137 * 9138 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9139 * @see #restoreHierarchyState(android.util.SparseArray) 9140 * @see #onRestoreInstanceState(android.os.Parcelable) 9141 */ 9142 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 9143 if (mID != NO_ID) { 9144 Parcelable state = container.get(mID); 9145 if (state != null) { 9146 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 9147 // + ": " + state); 9148 mPrivateFlags &= ~SAVE_STATE_CALLED; 9149 onRestoreInstanceState(state); 9150 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9151 throw new IllegalStateException( 9152 "Derived class did not call super.onRestoreInstanceState()"); 9153 } 9154 } 9155 } 9156 } 9157 9158 /** 9159 * Hook allowing a view to re-apply a representation of its internal state that had previously 9160 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 9161 * null state. 9162 * 9163 * @param state The frozen state that had previously been returned by 9164 * {@link #onSaveInstanceState}. 9165 * 9166 * @see #onSaveInstanceState() 9167 * @see #restoreHierarchyState(android.util.SparseArray) 9168 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9169 */ 9170 protected void onRestoreInstanceState(Parcelable state) { 9171 mPrivateFlags |= SAVE_STATE_CALLED; 9172 if (state != BaseSavedState.EMPTY_STATE && state != null) { 9173 throw new IllegalArgumentException("Wrong state class, expecting View State but " 9174 + "received " + state.getClass().toString() + " instead. This usually happens " 9175 + "when two views of different type have the same id in the same hierarchy. " 9176 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 9177 + "other views do not use the same id."); 9178 } 9179 } 9180 9181 /** 9182 * <p>Return the time at which the drawing of the view hierarchy started.</p> 9183 * 9184 * @return the drawing start time in milliseconds 9185 */ 9186 public long getDrawingTime() { 9187 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 9188 } 9189 9190 /** 9191 * <p>Enables or disables the duplication of the parent's state into this view. When 9192 * duplication is enabled, this view gets its drawable state from its parent rather 9193 * than from its own internal properties.</p> 9194 * 9195 * <p>Note: in the current implementation, setting this property to true after the 9196 * view was added to a ViewGroup might have no effect at all. This property should 9197 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 9198 * 9199 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 9200 * property is enabled, an exception will be thrown.</p> 9201 * 9202 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 9203 * parent, these states should not be affected by this method.</p> 9204 * 9205 * @param enabled True to enable duplication of the parent's drawable state, false 9206 * to disable it. 9207 * 9208 * @see #getDrawableState() 9209 * @see #isDuplicateParentStateEnabled() 9210 */ 9211 public void setDuplicateParentStateEnabled(boolean enabled) { 9212 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 9213 } 9214 9215 /** 9216 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 9217 * 9218 * @return True if this view's drawable state is duplicated from the parent, 9219 * false otherwise 9220 * 9221 * @see #getDrawableState() 9222 * @see #setDuplicateParentStateEnabled(boolean) 9223 */ 9224 public boolean isDuplicateParentStateEnabled() { 9225 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 9226 } 9227 9228 /** 9229 * <p>Specifies the type of layer backing this view. The layer can be 9230 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 9231 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 9232 * 9233 * <p>A layer is associated with an optional {@link android.graphics.Paint} 9234 * instance that controls how the layer is composed on screen. The following 9235 * properties of the paint are taken into account when composing the layer:</p> 9236 * <ul> 9237 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 9238 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 9239 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 9240 * </ul> 9241 * 9242 * <p>If this view has an alpha value set to < 1.0 by calling 9243 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 9244 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 9245 * equivalent to setting a hardware layer on this view and providing a paint with 9246 * the desired alpha value.<p> 9247 * 9248 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 9249 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 9250 * for more information on when and how to use layers.</p> 9251 * 9252 * @param layerType The ype of layer to use with this view, must be one of 9253 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 9254 * {@link #LAYER_TYPE_HARDWARE} 9255 * @param paint The paint used to compose the layer. This argument is optional 9256 * and can be null. It is ignored when the layer type is 9257 * {@link #LAYER_TYPE_NONE} 9258 * 9259 * @see #getLayerType() 9260 * @see #LAYER_TYPE_NONE 9261 * @see #LAYER_TYPE_SOFTWARE 9262 * @see #LAYER_TYPE_HARDWARE 9263 * @see #setAlpha(float) 9264 * 9265 * @attr ref android.R.styleable#View_layerType 9266 */ 9267 public void setLayerType(int layerType, Paint paint) { 9268 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 9269 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 9270 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 9271 } 9272 9273 if (layerType == mLayerType) { 9274 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 9275 mLayerPaint = paint == null ? new Paint() : paint; 9276 invalidateParentCaches(); 9277 invalidate(true); 9278 } 9279 return; 9280 } 9281 9282 // Destroy any previous software drawing cache if needed 9283 switch (mLayerType) { 9284 case LAYER_TYPE_HARDWARE: 9285 if (mHardwareLayer != null) { 9286 mHardwareLayer.destroy(); 9287 mHardwareLayer = null; 9288 } 9289 // fall through - unaccelerated views may use software layer mechanism instead 9290 case LAYER_TYPE_SOFTWARE: 9291 if (mDrawingCache != null) { 9292 mDrawingCache.recycle(); 9293 mDrawingCache = null; 9294 } 9295 9296 if (mUnscaledDrawingCache != null) { 9297 mUnscaledDrawingCache.recycle(); 9298 mUnscaledDrawingCache = null; 9299 } 9300 break; 9301 default: 9302 break; 9303 } 9304 9305 mLayerType = layerType; 9306 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 9307 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 9308 mLocalDirtyRect = layerDisabled ? null : new Rect(); 9309 9310 invalidateParentCaches(); 9311 invalidate(true); 9312 } 9313 9314 /** 9315 * Indicates what type of layer is currently associated with this view. By default 9316 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 9317 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 9318 * for more information on the different types of layers. 9319 * 9320 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 9321 * {@link #LAYER_TYPE_HARDWARE} 9322 * 9323 * @see #setLayerType(int, android.graphics.Paint) 9324 * @see #buildLayer() 9325 * @see #LAYER_TYPE_NONE 9326 * @see #LAYER_TYPE_SOFTWARE 9327 * @see #LAYER_TYPE_HARDWARE 9328 */ 9329 public int getLayerType() { 9330 return mLayerType; 9331 } 9332 9333 /** 9334 * Forces this view's layer to be created and this view to be rendered 9335 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 9336 * invoking this method will have no effect. 9337 * 9338 * This method can for instance be used to render a view into its layer before 9339 * starting an animation. If this view is complex, rendering into the layer 9340 * before starting the animation will avoid skipping frames. 9341 * 9342 * @throws IllegalStateException If this view is not attached to a window 9343 * 9344 * @see #setLayerType(int, android.graphics.Paint) 9345 */ 9346 public void buildLayer() { 9347 if (mLayerType == LAYER_TYPE_NONE) return; 9348 9349 if (mAttachInfo == null) { 9350 throw new IllegalStateException("This view must be attached to a window first"); 9351 } 9352 9353 switch (mLayerType) { 9354 case LAYER_TYPE_HARDWARE: 9355 getHardwareLayer(); 9356 break; 9357 case LAYER_TYPE_SOFTWARE: 9358 buildDrawingCache(true); 9359 break; 9360 } 9361 } 9362 9363 /** 9364 * <p>Returns a hardware layer that can be used to draw this view again 9365 * without executing its draw method.</p> 9366 * 9367 * @return A HardwareLayer ready to render, or null if an error occurred. 9368 */ 9369 HardwareLayer getHardwareLayer() { 9370 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) { 9371 return null; 9372 } 9373 9374 final int width = mRight - mLeft; 9375 final int height = mBottom - mTop; 9376 9377 if (width == 0 || height == 0) { 9378 return null; 9379 } 9380 9381 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 9382 if (mHardwareLayer == null) { 9383 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 9384 width, height, isOpaque()); 9385 mLocalDirtyRect.setEmpty(); 9386 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 9387 mHardwareLayer.resize(width, height); 9388 mLocalDirtyRect.setEmpty(); 9389 } 9390 9391 HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas; 9392 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas); 9393 mAttachInfo.mHardwareCanvas = canvas; 9394 try { 9395 canvas.setViewport(width, height); 9396 canvas.onPreDraw(mLocalDirtyRect); 9397 mLocalDirtyRect.setEmpty(); 9398 9399 final int restoreCount = canvas.save(); 9400 9401 computeScroll(); 9402 canvas.translate(-mScrollX, -mScrollY); 9403 9404 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9405 9406 // Fast path for layouts with no backgrounds 9407 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 9408 mPrivateFlags &= ~DIRTY_MASK; 9409 dispatchDraw(canvas); 9410 } else { 9411 draw(canvas); 9412 } 9413 9414 canvas.restoreToCount(restoreCount); 9415 } finally { 9416 canvas.onPostDraw(); 9417 mHardwareLayer.end(currentCanvas); 9418 mAttachInfo.mHardwareCanvas = currentCanvas; 9419 } 9420 } 9421 9422 return mHardwareLayer; 9423 } 9424 9425 /** 9426 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 9427 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 9428 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 9429 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 9430 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 9431 * null.</p> 9432 * 9433 * <p>Enabling the drawing cache is similar to 9434 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 9435 * acceleration is turned off. When hardware acceleration is turned on, enabling the 9436 * drawing cache has no effect on rendering because the system uses a different mechanism 9437 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 9438 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 9439 * for information on how to enable software and hardware layers.</p> 9440 * 9441 * <p>This API can be used to manually generate 9442 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 9443 * {@link #getDrawingCache()}.</p> 9444 * 9445 * @param enabled true to enable the drawing cache, false otherwise 9446 * 9447 * @see #isDrawingCacheEnabled() 9448 * @see #getDrawingCache() 9449 * @see #buildDrawingCache() 9450 * @see #setLayerType(int, android.graphics.Paint) 9451 */ 9452 public void setDrawingCacheEnabled(boolean enabled) { 9453 mCachingFailed = false; 9454 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 9455 } 9456 9457 /** 9458 * <p>Indicates whether the drawing cache is enabled for this view.</p> 9459 * 9460 * @return true if the drawing cache is enabled 9461 * 9462 * @see #setDrawingCacheEnabled(boolean) 9463 * @see #getDrawingCache() 9464 */ 9465 @ViewDebug.ExportedProperty(category = "drawing") 9466 public boolean isDrawingCacheEnabled() { 9467 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 9468 } 9469 9470 /** 9471 * Debugging utility which recursively outputs the dirty state of a view and its 9472 * descendants. 9473 * 9474 * @hide 9475 */ 9476 @SuppressWarnings({"UnusedDeclaration"}) 9477 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 9478 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) + 9479 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" + 9480 (mPrivateFlags & View.DRAWING_CACHE_VALID) + 9481 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")"); 9482 if (clear) { 9483 mPrivateFlags &= clearMask; 9484 } 9485 if (this instanceof ViewGroup) { 9486 ViewGroup parent = (ViewGroup) this; 9487 final int count = parent.getChildCount(); 9488 for (int i = 0; i < count; i++) { 9489 final View child = parent.getChildAt(i); 9490 child.outputDirtyFlags(indent + " ", clear, clearMask); 9491 } 9492 } 9493 } 9494 9495 /** 9496 * This method is used by ViewGroup to cause its children to restore or recreate their 9497 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 9498 * to recreate its own display list, which would happen if it went through the normal 9499 * draw/dispatchDraw mechanisms. 9500 * 9501 * @hide 9502 */ 9503 protected void dispatchGetDisplayList() {} 9504 9505 /** 9506 * A view that is not attached or hardware accelerated cannot create a display list. 9507 * This method checks these conditions and returns the appropriate result. 9508 * 9509 * @return true if view has the ability to create a display list, false otherwise. 9510 * 9511 * @hide 9512 */ 9513 public boolean canHaveDisplayList() { 9514 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 9515 } 9516 9517 /** 9518 * <p>Returns a display list that can be used to draw this view again 9519 * without executing its draw method.</p> 9520 * 9521 * @return A DisplayList ready to replay, or null if caching is not enabled. 9522 * 9523 * @hide 9524 */ 9525 public DisplayList getDisplayList() { 9526 if (!canHaveDisplayList()) { 9527 return null; 9528 } 9529 9530 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || 9531 mDisplayList == null || !mDisplayList.isValid() || 9532 mRecreateDisplayList)) { 9533 // Don't need to recreate the display list, just need to tell our 9534 // children to restore/recreate theirs 9535 if (mDisplayList != null && mDisplayList.isValid() && 9536 !mRecreateDisplayList) { 9537 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9538 mPrivateFlags &= ~DIRTY_MASK; 9539 dispatchGetDisplayList(); 9540 9541 return mDisplayList; 9542 } 9543 9544 // If we got here, we're recreating it. Mark it as such to ensure that 9545 // we copy in child display lists into ours in drawChild() 9546 mRecreateDisplayList = true; 9547 if (mDisplayList == null) { 9548 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(this); 9549 // If we're creating a new display list, make sure our parent gets invalidated 9550 // since they will need to recreate their display list to account for this 9551 // new child display list. 9552 invalidateParentCaches(); 9553 } 9554 9555 final HardwareCanvas canvas = mDisplayList.start(); 9556 try { 9557 int width = mRight - mLeft; 9558 int height = mBottom - mTop; 9559 9560 canvas.setViewport(width, height); 9561 // The dirty rect should always be null for a display list 9562 canvas.onPreDraw(null); 9563 9564 final int restoreCount = canvas.save(); 9565 9566 computeScroll(); 9567 canvas.translate(-mScrollX, -mScrollY); 9568 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9569 9570 // Fast path for layouts with no backgrounds 9571 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 9572 mPrivateFlags &= ~DIRTY_MASK; 9573 dispatchDraw(canvas); 9574 } else { 9575 draw(canvas); 9576 } 9577 9578 canvas.restoreToCount(restoreCount); 9579 } finally { 9580 canvas.onPostDraw(); 9581 9582 mDisplayList.end(); 9583 } 9584 } else { 9585 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9586 mPrivateFlags &= ~DIRTY_MASK; 9587 } 9588 9589 return mDisplayList; 9590 } 9591 9592 /** 9593 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 9594 * 9595 * @return A non-scaled bitmap representing this view or null if cache is disabled. 9596 * 9597 * @see #getDrawingCache(boolean) 9598 */ 9599 public Bitmap getDrawingCache() { 9600 return getDrawingCache(false); 9601 } 9602 9603 /** 9604 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 9605 * is null when caching is disabled. If caching is enabled and the cache is not ready, 9606 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 9607 * draw from the cache when the cache is enabled. To benefit from the cache, you must 9608 * request the drawing cache by calling this method and draw it on screen if the 9609 * returned bitmap is not null.</p> 9610 * 9611 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 9612 * this method will create a bitmap of the same size as this view. Because this bitmap 9613 * will be drawn scaled by the parent ViewGroup, the result on screen might show 9614 * scaling artifacts. To avoid such artifacts, you should call this method by setting 9615 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 9616 * size than the view. This implies that your application must be able to handle this 9617 * size.</p> 9618 * 9619 * @param autoScale Indicates whether the generated bitmap should be scaled based on 9620 * the current density of the screen when the application is in compatibility 9621 * mode. 9622 * 9623 * @return A bitmap representing this view or null if cache is disabled. 9624 * 9625 * @see #setDrawingCacheEnabled(boolean) 9626 * @see #isDrawingCacheEnabled() 9627 * @see #buildDrawingCache(boolean) 9628 * @see #destroyDrawingCache() 9629 */ 9630 public Bitmap getDrawingCache(boolean autoScale) { 9631 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 9632 return null; 9633 } 9634 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 9635 buildDrawingCache(autoScale); 9636 } 9637 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 9638 } 9639 9640 /** 9641 * <p>Frees the resources used by the drawing cache. If you call 9642 * {@link #buildDrawingCache()} manually without calling 9643 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 9644 * should cleanup the cache with this method afterwards.</p> 9645 * 9646 * @see #setDrawingCacheEnabled(boolean) 9647 * @see #buildDrawingCache() 9648 * @see #getDrawingCache() 9649 */ 9650 public void destroyDrawingCache() { 9651 if (mDrawingCache != null) { 9652 mDrawingCache.recycle(); 9653 mDrawingCache = null; 9654 } 9655 if (mUnscaledDrawingCache != null) { 9656 mUnscaledDrawingCache.recycle(); 9657 mUnscaledDrawingCache = null; 9658 } 9659 } 9660 9661 /** 9662 * Setting a solid background color for the drawing cache's bitmaps will improve 9663 * perfromance and memory usage. Note, though that this should only be used if this 9664 * view will always be drawn on top of a solid color. 9665 * 9666 * @param color The background color to use for the drawing cache's bitmap 9667 * 9668 * @see #setDrawingCacheEnabled(boolean) 9669 * @see #buildDrawingCache() 9670 * @see #getDrawingCache() 9671 */ 9672 public void setDrawingCacheBackgroundColor(int color) { 9673 if (color != mDrawingCacheBackgroundColor) { 9674 mDrawingCacheBackgroundColor = color; 9675 mPrivateFlags &= ~DRAWING_CACHE_VALID; 9676 } 9677 } 9678 9679 /** 9680 * @see #setDrawingCacheBackgroundColor(int) 9681 * 9682 * @return The background color to used for the drawing cache's bitmap 9683 */ 9684 public int getDrawingCacheBackgroundColor() { 9685 return mDrawingCacheBackgroundColor; 9686 } 9687 9688 /** 9689 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 9690 * 9691 * @see #buildDrawingCache(boolean) 9692 */ 9693 public void buildDrawingCache() { 9694 buildDrawingCache(false); 9695 } 9696 9697 /** 9698 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 9699 * 9700 * <p>If you call {@link #buildDrawingCache()} manually without calling 9701 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 9702 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 9703 * 9704 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 9705 * this method will create a bitmap of the same size as this view. Because this bitmap 9706 * will be drawn scaled by the parent ViewGroup, the result on screen might show 9707 * scaling artifacts. To avoid such artifacts, you should call this method by setting 9708 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 9709 * size than the view. This implies that your application must be able to handle this 9710 * size.</p> 9711 * 9712 * <p>You should avoid calling this method when hardware acceleration is enabled. If 9713 * you do not need the drawing cache bitmap, calling this method will increase memory 9714 * usage and cause the view to be rendered in software once, thus negatively impacting 9715 * performance.</p> 9716 * 9717 * @see #getDrawingCache() 9718 * @see #destroyDrawingCache() 9719 */ 9720 public void buildDrawingCache(boolean autoScale) { 9721 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 9722 mDrawingCache == null : mUnscaledDrawingCache == null)) { 9723 mCachingFailed = false; 9724 9725 if (ViewDebug.TRACE_HIERARCHY) { 9726 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 9727 } 9728 9729 int width = mRight - mLeft; 9730 int height = mBottom - mTop; 9731 9732 final AttachInfo attachInfo = mAttachInfo; 9733 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 9734 9735 if (autoScale && scalingRequired) { 9736 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 9737 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 9738 } 9739 9740 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 9741 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 9742 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 9743 9744 if (width <= 0 || height <= 0 || 9745 // Projected bitmap size in bytes 9746 (width * height * (opaque && !use32BitCache ? 2 : 4) > 9747 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 9748 destroyDrawingCache(); 9749 mCachingFailed = true; 9750 return; 9751 } 9752 9753 boolean clear = true; 9754 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 9755 9756 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 9757 Bitmap.Config quality; 9758 if (!opaque) { 9759 // Never pick ARGB_4444 because it looks awful 9760 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 9761 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 9762 case DRAWING_CACHE_QUALITY_AUTO: 9763 quality = Bitmap.Config.ARGB_8888; 9764 break; 9765 case DRAWING_CACHE_QUALITY_LOW: 9766 quality = Bitmap.Config.ARGB_8888; 9767 break; 9768 case DRAWING_CACHE_QUALITY_HIGH: 9769 quality = Bitmap.Config.ARGB_8888; 9770 break; 9771 default: 9772 quality = Bitmap.Config.ARGB_8888; 9773 break; 9774 } 9775 } else { 9776 // Optimization for translucent windows 9777 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 9778 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 9779 } 9780 9781 // Try to cleanup memory 9782 if (bitmap != null) bitmap.recycle(); 9783 9784 try { 9785 bitmap = Bitmap.createBitmap(width, height, quality); 9786 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 9787 if (autoScale) { 9788 mDrawingCache = bitmap; 9789 } else { 9790 mUnscaledDrawingCache = bitmap; 9791 } 9792 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 9793 } catch (OutOfMemoryError e) { 9794 // If there is not enough memory to create the bitmap cache, just 9795 // ignore the issue as bitmap caches are not required to draw the 9796 // view hierarchy 9797 if (autoScale) { 9798 mDrawingCache = null; 9799 } else { 9800 mUnscaledDrawingCache = null; 9801 } 9802 mCachingFailed = true; 9803 return; 9804 } 9805 9806 clear = drawingCacheBackgroundColor != 0; 9807 } 9808 9809 Canvas canvas; 9810 if (attachInfo != null) { 9811 canvas = attachInfo.mCanvas; 9812 if (canvas == null) { 9813 canvas = new Canvas(); 9814 } 9815 canvas.setBitmap(bitmap); 9816 // Temporarily clobber the cached Canvas in case one of our children 9817 // is also using a drawing cache. Without this, the children would 9818 // steal the canvas by attaching their own bitmap to it and bad, bad 9819 // thing would happen (invisible views, corrupted drawings, etc.) 9820 attachInfo.mCanvas = null; 9821 } else { 9822 // This case should hopefully never or seldom happen 9823 canvas = new Canvas(bitmap); 9824 } 9825 9826 if (clear) { 9827 bitmap.eraseColor(drawingCacheBackgroundColor); 9828 } 9829 9830 computeScroll(); 9831 final int restoreCount = canvas.save(); 9832 9833 if (autoScale && scalingRequired) { 9834 final float scale = attachInfo.mApplicationScale; 9835 canvas.scale(scale, scale); 9836 } 9837 9838 canvas.translate(-mScrollX, -mScrollY); 9839 9840 mPrivateFlags |= DRAWN; 9841 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 9842 mLayerType != LAYER_TYPE_NONE) { 9843 mPrivateFlags |= DRAWING_CACHE_VALID; 9844 } 9845 9846 // Fast path for layouts with no backgrounds 9847 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 9848 if (ViewDebug.TRACE_HIERARCHY) { 9849 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 9850 } 9851 mPrivateFlags &= ~DIRTY_MASK; 9852 dispatchDraw(canvas); 9853 } else { 9854 draw(canvas); 9855 } 9856 9857 canvas.restoreToCount(restoreCount); 9858 9859 if (attachInfo != null) { 9860 // Restore the cached Canvas for our siblings 9861 attachInfo.mCanvas = canvas; 9862 } 9863 } 9864 } 9865 9866 /** 9867 * Create a snapshot of the view into a bitmap. We should probably make 9868 * some form of this public, but should think about the API. 9869 */ 9870 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 9871 int width = mRight - mLeft; 9872 int height = mBottom - mTop; 9873 9874 final AttachInfo attachInfo = mAttachInfo; 9875 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 9876 width = (int) ((width * scale) + 0.5f); 9877 height = (int) ((height * scale) + 0.5f); 9878 9879 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 9880 if (bitmap == null) { 9881 throw new OutOfMemoryError(); 9882 } 9883 9884 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 9885 9886 Canvas canvas; 9887 if (attachInfo != null) { 9888 canvas = attachInfo.mCanvas; 9889 if (canvas == null) { 9890 canvas = new Canvas(); 9891 } 9892 canvas.setBitmap(bitmap); 9893 // Temporarily clobber the cached Canvas in case one of our children 9894 // is also using a drawing cache. Without this, the children would 9895 // steal the canvas by attaching their own bitmap to it and bad, bad 9896 // things would happen (invisible views, corrupted drawings, etc.) 9897 attachInfo.mCanvas = null; 9898 } else { 9899 // This case should hopefully never or seldom happen 9900 canvas = new Canvas(bitmap); 9901 } 9902 9903 if ((backgroundColor & 0xff000000) != 0) { 9904 bitmap.eraseColor(backgroundColor); 9905 } 9906 9907 computeScroll(); 9908 final int restoreCount = canvas.save(); 9909 canvas.scale(scale, scale); 9910 canvas.translate(-mScrollX, -mScrollY); 9911 9912 // Temporarily remove the dirty mask 9913 int flags = mPrivateFlags; 9914 mPrivateFlags &= ~DIRTY_MASK; 9915 9916 // Fast path for layouts with no backgrounds 9917 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 9918 dispatchDraw(canvas); 9919 } else { 9920 draw(canvas); 9921 } 9922 9923 mPrivateFlags = flags; 9924 9925 canvas.restoreToCount(restoreCount); 9926 9927 if (attachInfo != null) { 9928 // Restore the cached Canvas for our siblings 9929 attachInfo.mCanvas = canvas; 9930 } 9931 9932 return bitmap; 9933 } 9934 9935 /** 9936 * Indicates whether this View is currently in edit mode. A View is usually 9937 * in edit mode when displayed within a developer tool. For instance, if 9938 * this View is being drawn by a visual user interface builder, this method 9939 * should return true. 9940 * 9941 * Subclasses should check the return value of this method to provide 9942 * different behaviors if their normal behavior might interfere with the 9943 * host environment. For instance: the class spawns a thread in its 9944 * constructor, the drawing code relies on device-specific features, etc. 9945 * 9946 * This method is usually checked in the drawing code of custom widgets. 9947 * 9948 * @return True if this View is in edit mode, false otherwise. 9949 */ 9950 public boolean isInEditMode() { 9951 return false; 9952 } 9953 9954 /** 9955 * If the View draws content inside its padding and enables fading edges, 9956 * it needs to support padding offsets. Padding offsets are added to the 9957 * fading edges to extend the length of the fade so that it covers pixels 9958 * drawn inside the padding. 9959 * 9960 * Subclasses of this class should override this method if they need 9961 * to draw content inside the padding. 9962 * 9963 * @return True if padding offset must be applied, false otherwise. 9964 * 9965 * @see #getLeftPaddingOffset() 9966 * @see #getRightPaddingOffset() 9967 * @see #getTopPaddingOffset() 9968 * @see #getBottomPaddingOffset() 9969 * 9970 * @since CURRENT 9971 */ 9972 protected boolean isPaddingOffsetRequired() { 9973 return false; 9974 } 9975 9976 /** 9977 * Amount by which to extend the left fading region. Called only when 9978 * {@link #isPaddingOffsetRequired()} returns true. 9979 * 9980 * @return The left padding offset in pixels. 9981 * 9982 * @see #isPaddingOffsetRequired() 9983 * 9984 * @since CURRENT 9985 */ 9986 protected int getLeftPaddingOffset() { 9987 return 0; 9988 } 9989 9990 /** 9991 * Amount by which to extend the right fading region. Called only when 9992 * {@link #isPaddingOffsetRequired()} returns true. 9993 * 9994 * @return The right padding offset in pixels. 9995 * 9996 * @see #isPaddingOffsetRequired() 9997 * 9998 * @since CURRENT 9999 */ 10000 protected int getRightPaddingOffset() { 10001 return 0; 10002 } 10003 10004 /** 10005 * Amount by which to extend the top fading region. Called only when 10006 * {@link #isPaddingOffsetRequired()} returns true. 10007 * 10008 * @return The top padding offset in pixels. 10009 * 10010 * @see #isPaddingOffsetRequired() 10011 * 10012 * @since CURRENT 10013 */ 10014 protected int getTopPaddingOffset() { 10015 return 0; 10016 } 10017 10018 /** 10019 * Amount by which to extend the bottom fading region. Called only when 10020 * {@link #isPaddingOffsetRequired()} returns true. 10021 * 10022 * @return The bottom padding offset in pixels. 10023 * 10024 * @see #isPaddingOffsetRequired() 10025 * 10026 * @since CURRENT 10027 */ 10028 protected int getBottomPaddingOffset() { 10029 return 0; 10030 } 10031 10032 /** 10033 * <p>Indicates whether this view is attached to an hardware accelerated 10034 * window or not.</p> 10035 * 10036 * <p>Even if this method returns true, it does not mean that every call 10037 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 10038 * accelerated {@link android.graphics.Canvas}. For instance, if this view 10039 * is drawn onto an offscren {@link android.graphics.Bitmap} and its 10040 * window is hardware accelerated, 10041 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 10042 * return false, and this method will return true.</p> 10043 * 10044 * @return True if the view is attached to a window and the window is 10045 * hardware accelerated; false in any other case. 10046 */ 10047 public boolean isHardwareAccelerated() { 10048 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 10049 } 10050 10051 /** 10052 * Manually render this view (and all of its children) to the given Canvas. 10053 * The view must have already done a full layout before this function is 10054 * called. When implementing a view, implement 10055 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 10056 * If you do need to override this method, call the superclass version. 10057 * 10058 * @param canvas The Canvas to which the View is rendered. 10059 */ 10060 public void draw(Canvas canvas) { 10061 if (ViewDebug.TRACE_HIERARCHY) { 10062 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 10063 } 10064 10065 final int privateFlags = mPrivateFlags; 10066 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 10067 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 10068 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 10069 10070 /* 10071 * Draw traversal performs several drawing steps which must be executed 10072 * in the appropriate order: 10073 * 10074 * 1. Draw the background 10075 * 2. If necessary, save the canvas' layers to prepare for fading 10076 * 3. Draw view's content 10077 * 4. Draw children 10078 * 5. If necessary, draw the fading edges and restore layers 10079 * 6. Draw decorations (scrollbars for instance) 10080 */ 10081 10082 // Step 1, draw the background, if needed 10083 int saveCount; 10084 10085 if (!dirtyOpaque) { 10086 final Drawable background = mBGDrawable; 10087 if (background != null) { 10088 final int scrollX = mScrollX; 10089 final int scrollY = mScrollY; 10090 10091 if (mBackgroundSizeChanged) { 10092 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 10093 mBackgroundSizeChanged = false; 10094 } 10095 10096 if ((scrollX | scrollY) == 0) { 10097 background.draw(canvas); 10098 } else { 10099 canvas.translate(scrollX, scrollY); 10100 background.draw(canvas); 10101 canvas.translate(-scrollX, -scrollY); 10102 } 10103 } 10104 } 10105 10106 // skip step 2 & 5 if possible (common case) 10107 final int viewFlags = mViewFlags; 10108 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 10109 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 10110 if (!verticalEdges && !horizontalEdges) { 10111 // Step 3, draw the content 10112 if (!dirtyOpaque) onDraw(canvas); 10113 10114 // Step 4, draw the children 10115 dispatchDraw(canvas); 10116 10117 // Step 6, draw decorations (scrollbars) 10118 onDrawScrollBars(canvas); 10119 10120 // we're done... 10121 return; 10122 } 10123 10124 /* 10125 * Here we do the full fledged routine... 10126 * (this is an uncommon case where speed matters less, 10127 * this is why we repeat some of the tests that have been 10128 * done above) 10129 */ 10130 10131 boolean drawTop = false; 10132 boolean drawBottom = false; 10133 boolean drawLeft = false; 10134 boolean drawRight = false; 10135 10136 float topFadeStrength = 0.0f; 10137 float bottomFadeStrength = 0.0f; 10138 float leftFadeStrength = 0.0f; 10139 float rightFadeStrength = 0.0f; 10140 10141 // Step 2, save the canvas' layers 10142 int paddingLeft = mPaddingLeft; 10143 int paddingTop = mPaddingTop; 10144 10145 final boolean offsetRequired = isPaddingOffsetRequired(); 10146 if (offsetRequired) { 10147 paddingLeft += getLeftPaddingOffset(); 10148 paddingTop += getTopPaddingOffset(); 10149 } 10150 10151 int left = mScrollX + paddingLeft; 10152 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 10153 int top = mScrollY + paddingTop; 10154 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop; 10155 10156 if (offsetRequired) { 10157 right += getRightPaddingOffset(); 10158 bottom += getBottomPaddingOffset(); 10159 } 10160 10161 final ScrollabilityCache scrollabilityCache = mScrollCache; 10162 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 10163 int length = (int) fadeHeight; 10164 10165 // clip the fade length if top and bottom fades overlap 10166 // overlapping fades produce odd-looking artifacts 10167 if (verticalEdges && (top + length > bottom - length)) { 10168 length = (bottom - top) / 2; 10169 } 10170 10171 // also clip horizontal fades if necessary 10172 if (horizontalEdges && (left + length > right - length)) { 10173 length = (right - left) / 2; 10174 } 10175 10176 if (verticalEdges) { 10177 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 10178 drawTop = topFadeStrength * fadeHeight > 1.0f; 10179 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 10180 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 10181 } 10182 10183 if (horizontalEdges) { 10184 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 10185 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 10186 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 10187 drawRight = rightFadeStrength * fadeHeight > 1.0f; 10188 } 10189 10190 saveCount = canvas.getSaveCount(); 10191 10192 int solidColor = getSolidColor(); 10193 if (solidColor == 0) { 10194 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 10195 10196 if (drawTop) { 10197 canvas.saveLayer(left, top, right, top + length, null, flags); 10198 } 10199 10200 if (drawBottom) { 10201 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 10202 } 10203 10204 if (drawLeft) { 10205 canvas.saveLayer(left, top, left + length, bottom, null, flags); 10206 } 10207 10208 if (drawRight) { 10209 canvas.saveLayer(right - length, top, right, bottom, null, flags); 10210 } 10211 } else { 10212 scrollabilityCache.setFadeColor(solidColor); 10213 } 10214 10215 // Step 3, draw the content 10216 if (!dirtyOpaque) onDraw(canvas); 10217 10218 // Step 4, draw the children 10219 dispatchDraw(canvas); 10220 10221 // Step 5, draw the fade effect and restore layers 10222 final Paint p = scrollabilityCache.paint; 10223 final Matrix matrix = scrollabilityCache.matrix; 10224 final Shader fade = scrollabilityCache.shader; 10225 10226 if (drawTop) { 10227 matrix.setScale(1, fadeHeight * topFadeStrength); 10228 matrix.postTranslate(left, top); 10229 fade.setLocalMatrix(matrix); 10230 canvas.drawRect(left, top, right, top + length, p); 10231 } 10232 10233 if (drawBottom) { 10234 matrix.setScale(1, fadeHeight * bottomFadeStrength); 10235 matrix.postRotate(180); 10236 matrix.postTranslate(left, bottom); 10237 fade.setLocalMatrix(matrix); 10238 canvas.drawRect(left, bottom - length, right, bottom, p); 10239 } 10240 10241 if (drawLeft) { 10242 matrix.setScale(1, fadeHeight * leftFadeStrength); 10243 matrix.postRotate(-90); 10244 matrix.postTranslate(left, top); 10245 fade.setLocalMatrix(matrix); 10246 canvas.drawRect(left, top, left + length, bottom, p); 10247 } 10248 10249 if (drawRight) { 10250 matrix.setScale(1, fadeHeight * rightFadeStrength); 10251 matrix.postRotate(90); 10252 matrix.postTranslate(right, top); 10253 fade.setLocalMatrix(matrix); 10254 canvas.drawRect(right - length, top, right, bottom, p); 10255 } 10256 10257 canvas.restoreToCount(saveCount); 10258 10259 // Step 6, draw decorations (scrollbars) 10260 onDrawScrollBars(canvas); 10261 } 10262 10263 /** 10264 * Override this if your view is known to always be drawn on top of a solid color background, 10265 * and needs to draw fading edges. Returning a non-zero color enables the view system to 10266 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 10267 * should be set to 0xFF. 10268 * 10269 * @see #setVerticalFadingEdgeEnabled(boolean) 10270 * @see #setHorizontalFadingEdgeEnabled(boolean) 10271 * 10272 * @return The known solid color background for this view, or 0 if the color may vary 10273 */ 10274 @ViewDebug.ExportedProperty(category = "drawing") 10275 public int getSolidColor() { 10276 return 0; 10277 } 10278 10279 /** 10280 * Build a human readable string representation of the specified view flags. 10281 * 10282 * @param flags the view flags to convert to a string 10283 * @return a String representing the supplied flags 10284 */ 10285 private static String printFlags(int flags) { 10286 String output = ""; 10287 int numFlags = 0; 10288 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 10289 output += "TAKES_FOCUS"; 10290 numFlags++; 10291 } 10292 10293 switch (flags & VISIBILITY_MASK) { 10294 case INVISIBLE: 10295 if (numFlags > 0) { 10296 output += " "; 10297 } 10298 output += "INVISIBLE"; 10299 // USELESS HERE numFlags++; 10300 break; 10301 case GONE: 10302 if (numFlags > 0) { 10303 output += " "; 10304 } 10305 output += "GONE"; 10306 // USELESS HERE numFlags++; 10307 break; 10308 default: 10309 break; 10310 } 10311 return output; 10312 } 10313 10314 /** 10315 * Build a human readable string representation of the specified private 10316 * view flags. 10317 * 10318 * @param privateFlags the private view flags to convert to a string 10319 * @return a String representing the supplied flags 10320 */ 10321 private static String printPrivateFlags(int privateFlags) { 10322 String output = ""; 10323 int numFlags = 0; 10324 10325 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 10326 output += "WANTS_FOCUS"; 10327 numFlags++; 10328 } 10329 10330 if ((privateFlags & FOCUSED) == FOCUSED) { 10331 if (numFlags > 0) { 10332 output += " "; 10333 } 10334 output += "FOCUSED"; 10335 numFlags++; 10336 } 10337 10338 if ((privateFlags & SELECTED) == SELECTED) { 10339 if (numFlags > 0) { 10340 output += " "; 10341 } 10342 output += "SELECTED"; 10343 numFlags++; 10344 } 10345 10346 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 10347 if (numFlags > 0) { 10348 output += " "; 10349 } 10350 output += "IS_ROOT_NAMESPACE"; 10351 numFlags++; 10352 } 10353 10354 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 10355 if (numFlags > 0) { 10356 output += " "; 10357 } 10358 output += "HAS_BOUNDS"; 10359 numFlags++; 10360 } 10361 10362 if ((privateFlags & DRAWN) == DRAWN) { 10363 if (numFlags > 0) { 10364 output += " "; 10365 } 10366 output += "DRAWN"; 10367 // USELESS HERE numFlags++; 10368 } 10369 return output; 10370 } 10371 10372 /** 10373 * <p>Indicates whether or not this view's layout will be requested during 10374 * the next hierarchy layout pass.</p> 10375 * 10376 * @return true if the layout will be forced during next layout pass 10377 */ 10378 public boolean isLayoutRequested() { 10379 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 10380 } 10381 10382 /** 10383 * Assign a size and position to a view and all of its 10384 * descendants 10385 * 10386 * <p>This is the second phase of the layout mechanism. 10387 * (The first is measuring). In this phase, each parent calls 10388 * layout on all of its children to position them. 10389 * This is typically done using the child measurements 10390 * that were stored in the measure pass().</p> 10391 * 10392 * <p>Derived classes should not override this method. 10393 * Derived classes with children should override 10394 * onLayout. In that method, they should 10395 * call layout on each of their children.</p> 10396 * 10397 * @param l Left position, relative to parent 10398 * @param t Top position, relative to parent 10399 * @param r Right position, relative to parent 10400 * @param b Bottom position, relative to parent 10401 */ 10402 @SuppressWarnings({"unchecked"}) 10403 public void layout(int l, int t, int r, int b) { 10404 int oldL = mLeft; 10405 int oldT = mTop; 10406 int oldB = mBottom; 10407 int oldR = mRight; 10408 boolean changed = setFrame(l, t, r, b); 10409 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 10410 if (ViewDebug.TRACE_HIERARCHY) { 10411 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 10412 } 10413 10414 onLayout(changed, l, t, r, b); 10415 mPrivateFlags &= ~LAYOUT_REQUIRED; 10416 10417 if (mOnLayoutChangeListeners != null) { 10418 ArrayList<OnLayoutChangeListener> listenersCopy = 10419 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone(); 10420 int numListeners = listenersCopy.size(); 10421 for (int i = 0; i < numListeners; ++i) { 10422 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 10423 } 10424 } 10425 } 10426 mPrivateFlags &= ~FORCE_LAYOUT; 10427 } 10428 10429 /** 10430 * Called from layout when this view should 10431 * assign a size and position to each of its children. 10432 * 10433 * Derived classes with children should override 10434 * this method and call layout on each of 10435 * their children. 10436 * @param changed This is a new size or position for this view 10437 * @param left Left position, relative to parent 10438 * @param top Top position, relative to parent 10439 * @param right Right position, relative to parent 10440 * @param bottom Bottom position, relative to parent 10441 */ 10442 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 10443 } 10444 10445 /** 10446 * Assign a size and position to this view. 10447 * 10448 * This is called from layout. 10449 * 10450 * @param left Left position, relative to parent 10451 * @param top Top position, relative to parent 10452 * @param right Right position, relative to parent 10453 * @param bottom Bottom position, relative to parent 10454 * @return true if the new size and position are different than the 10455 * previous ones 10456 * {@hide} 10457 */ 10458 protected boolean setFrame(int left, int top, int right, int bottom) { 10459 boolean changed = false; 10460 10461 if (DBG) { 10462 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 10463 + right + "," + bottom + ")"); 10464 } 10465 10466 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 10467 changed = true; 10468 10469 // Remember our drawn bit 10470 int drawn = mPrivateFlags & DRAWN; 10471 10472 // Invalidate our old position 10473 invalidate(true); 10474 10475 10476 int oldWidth = mRight - mLeft; 10477 int oldHeight = mBottom - mTop; 10478 10479 mLeft = left; 10480 mTop = top; 10481 mRight = right; 10482 mBottom = bottom; 10483 10484 mPrivateFlags |= HAS_BOUNDS; 10485 10486 int newWidth = right - left; 10487 int newHeight = bottom - top; 10488 10489 if (newWidth != oldWidth || newHeight != oldHeight) { 10490 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 10491 // A change in dimension means an auto-centered pivot point changes, too 10492 mMatrixDirty = true; 10493 } 10494 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 10495 } 10496 10497 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 10498 // If we are visible, force the DRAWN bit to on so that 10499 // this invalidate will go through (at least to our parent). 10500 // This is because someone may have invalidated this view 10501 // before this call to setFrame came in, thereby clearing 10502 // the DRAWN bit. 10503 mPrivateFlags |= DRAWN; 10504 invalidate(true); 10505 // parent display list may need to be recreated based on a change in the bounds 10506 // of any child 10507 invalidateParentCaches(); 10508 } 10509 10510 // Reset drawn bit to original value (invalidate turns it off) 10511 mPrivateFlags |= drawn; 10512 10513 mBackgroundSizeChanged = true; 10514 } 10515 return changed; 10516 } 10517 10518 /** 10519 * Finalize inflating a view from XML. This is called as the last phase 10520 * of inflation, after all child views have been added. 10521 * 10522 * <p>Even if the subclass overrides onFinishInflate, they should always be 10523 * sure to call the super method, so that we get called. 10524 */ 10525 protected void onFinishInflate() { 10526 } 10527 10528 /** 10529 * Returns the resources associated with this view. 10530 * 10531 * @return Resources object. 10532 */ 10533 public Resources getResources() { 10534 return mResources; 10535 } 10536 10537 /** 10538 * Invalidates the specified Drawable. 10539 * 10540 * @param drawable the drawable to invalidate 10541 */ 10542 public void invalidateDrawable(Drawable drawable) { 10543 if (verifyDrawable(drawable)) { 10544 final Rect dirty = drawable.getBounds(); 10545 final int scrollX = mScrollX; 10546 final int scrollY = mScrollY; 10547 10548 invalidate(dirty.left + scrollX, dirty.top + scrollY, 10549 dirty.right + scrollX, dirty.bottom + scrollY); 10550 } 10551 } 10552 10553 /** 10554 * Schedules an action on a drawable to occur at a specified time. 10555 * 10556 * @param who the recipient of the action 10557 * @param what the action to run on the drawable 10558 * @param when the time at which the action must occur. Uses the 10559 * {@link SystemClock#uptimeMillis} timebase. 10560 */ 10561 public void scheduleDrawable(Drawable who, Runnable what, long when) { 10562 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 10563 mAttachInfo.mHandler.postAtTime(what, who, when); 10564 } 10565 } 10566 10567 /** 10568 * Cancels a scheduled action on a drawable. 10569 * 10570 * @param who the recipient of the action 10571 * @param what the action to cancel 10572 */ 10573 public void unscheduleDrawable(Drawable who, Runnable what) { 10574 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 10575 mAttachInfo.mHandler.removeCallbacks(what, who); 10576 } 10577 } 10578 10579 /** 10580 * Unschedule any events associated with the given Drawable. This can be 10581 * used when selecting a new Drawable into a view, so that the previous 10582 * one is completely unscheduled. 10583 * 10584 * @param who The Drawable to unschedule. 10585 * 10586 * @see #drawableStateChanged 10587 */ 10588 public void unscheduleDrawable(Drawable who) { 10589 if (mAttachInfo != null) { 10590 mAttachInfo.mHandler.removeCallbacksAndMessages(who); 10591 } 10592 } 10593 10594 /** 10595 * Return the layout direction of a given Drawable. 10596 * 10597 * @param who the Drawable to query 10598 * 10599 * @hide 10600 */ 10601 public int getResolvedLayoutDirection(Drawable who) { 10602 return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT; 10603 } 10604 10605 /** 10606 * If your view subclass is displaying its own Drawable objects, it should 10607 * override this function and return true for any Drawable it is 10608 * displaying. This allows animations for those drawables to be 10609 * scheduled. 10610 * 10611 * <p>Be sure to call through to the super class when overriding this 10612 * function. 10613 * 10614 * @param who The Drawable to verify. Return true if it is one you are 10615 * displaying, else return the result of calling through to the 10616 * super class. 10617 * 10618 * @return boolean If true than the Drawable is being displayed in the 10619 * view; else false and it is not allowed to animate. 10620 * 10621 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 10622 * @see #drawableStateChanged() 10623 */ 10624 protected boolean verifyDrawable(Drawable who) { 10625 return who == mBGDrawable; 10626 } 10627 10628 /** 10629 * This function is called whenever the state of the view changes in such 10630 * a way that it impacts the state of drawables being shown. 10631 * 10632 * <p>Be sure to call through to the superclass when overriding this 10633 * function. 10634 * 10635 * @see Drawable#setState(int[]) 10636 */ 10637 protected void drawableStateChanged() { 10638 Drawable d = mBGDrawable; 10639 if (d != null && d.isStateful()) { 10640 d.setState(getDrawableState()); 10641 } 10642 } 10643 10644 /** 10645 * Call this to force a view to update its drawable state. This will cause 10646 * drawableStateChanged to be called on this view. Views that are interested 10647 * in the new state should call getDrawableState. 10648 * 10649 * @see #drawableStateChanged 10650 * @see #getDrawableState 10651 */ 10652 public void refreshDrawableState() { 10653 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 10654 drawableStateChanged(); 10655 10656 ViewParent parent = mParent; 10657 if (parent != null) { 10658 parent.childDrawableStateChanged(this); 10659 } 10660 } 10661 10662 /** 10663 * Return an array of resource IDs of the drawable states representing the 10664 * current state of the view. 10665 * 10666 * @return The current drawable state 10667 * 10668 * @see Drawable#setState(int[]) 10669 * @see #drawableStateChanged() 10670 * @see #onCreateDrawableState(int) 10671 */ 10672 public final int[] getDrawableState() { 10673 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 10674 return mDrawableState; 10675 } else { 10676 mDrawableState = onCreateDrawableState(0); 10677 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 10678 return mDrawableState; 10679 } 10680 } 10681 10682 /** 10683 * Generate the new {@link android.graphics.drawable.Drawable} state for 10684 * this view. This is called by the view 10685 * system when the cached Drawable state is determined to be invalid. To 10686 * retrieve the current state, you should use {@link #getDrawableState}. 10687 * 10688 * @param extraSpace if non-zero, this is the number of extra entries you 10689 * would like in the returned array in which you can place your own 10690 * states. 10691 * 10692 * @return Returns an array holding the current {@link Drawable} state of 10693 * the view. 10694 * 10695 * @see #mergeDrawableStates(int[], int[]) 10696 */ 10697 protected int[] onCreateDrawableState(int extraSpace) { 10698 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 10699 mParent instanceof View) { 10700 return ((View) mParent).onCreateDrawableState(extraSpace); 10701 } 10702 10703 int[] drawableState; 10704 10705 int privateFlags = mPrivateFlags; 10706 10707 int viewStateIndex = 0; 10708 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 10709 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 10710 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 10711 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 10712 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 10713 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 10714 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 10715 HardwareRenderer.isAvailable()) { 10716 // This is set if HW acceleration is requested, even if the current 10717 // process doesn't allow it. This is just to allow app preview 10718 // windows to better match their app. 10719 viewStateIndex |= VIEW_STATE_ACCELERATED; 10720 } 10721 if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 10722 10723 final int privateFlags2 = mPrivateFlags2; 10724 if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 10725 if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 10726 10727 drawableState = VIEW_STATE_SETS[viewStateIndex]; 10728 10729 //noinspection ConstantIfStatement 10730 if (false) { 10731 Log.i("View", "drawableStateIndex=" + viewStateIndex); 10732 Log.i("View", toString() 10733 + " pressed=" + ((privateFlags & PRESSED) != 0) 10734 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 10735 + " fo=" + hasFocus() 10736 + " sl=" + ((privateFlags & SELECTED) != 0) 10737 + " wf=" + hasWindowFocus() 10738 + ": " + Arrays.toString(drawableState)); 10739 } 10740 10741 if (extraSpace == 0) { 10742 return drawableState; 10743 } 10744 10745 final int[] fullState; 10746 if (drawableState != null) { 10747 fullState = new int[drawableState.length + extraSpace]; 10748 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 10749 } else { 10750 fullState = new int[extraSpace]; 10751 } 10752 10753 return fullState; 10754 } 10755 10756 /** 10757 * Merge your own state values in <var>additionalState</var> into the base 10758 * state values <var>baseState</var> that were returned by 10759 * {@link #onCreateDrawableState(int)}. 10760 * 10761 * @param baseState The base state values returned by 10762 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 10763 * own additional state values. 10764 * 10765 * @param additionalState The additional state values you would like 10766 * added to <var>baseState</var>; this array is not modified. 10767 * 10768 * @return As a convenience, the <var>baseState</var> array you originally 10769 * passed into the function is returned. 10770 * 10771 * @see #onCreateDrawableState(int) 10772 */ 10773 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 10774 final int N = baseState.length; 10775 int i = N - 1; 10776 while (i >= 0 && baseState[i] == 0) { 10777 i--; 10778 } 10779 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 10780 return baseState; 10781 } 10782 10783 /** 10784 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 10785 * on all Drawable objects associated with this view. 10786 */ 10787 public void jumpDrawablesToCurrentState() { 10788 if (mBGDrawable != null) { 10789 mBGDrawable.jumpToCurrentState(); 10790 } 10791 } 10792 10793 /** 10794 * Sets the background color for this view. 10795 * @param color the color of the background 10796 */ 10797 @RemotableViewMethod 10798 public void setBackgroundColor(int color) { 10799 if (mBGDrawable instanceof ColorDrawable) { 10800 ((ColorDrawable) mBGDrawable).setColor(color); 10801 } else { 10802 setBackgroundDrawable(new ColorDrawable(color)); 10803 } 10804 } 10805 10806 /** 10807 * Set the background to a given resource. The resource should refer to 10808 * a Drawable object or 0 to remove the background. 10809 * @param resid The identifier of the resource. 10810 * @attr ref android.R.styleable#View_background 10811 */ 10812 @RemotableViewMethod 10813 public void setBackgroundResource(int resid) { 10814 if (resid != 0 && resid == mBackgroundResource) { 10815 return; 10816 } 10817 10818 Drawable d= null; 10819 if (resid != 0) { 10820 d = mResources.getDrawable(resid); 10821 } 10822 setBackgroundDrawable(d); 10823 10824 mBackgroundResource = resid; 10825 } 10826 10827 /** 10828 * Set the background to a given Drawable, or remove the background. If the 10829 * background has padding, this View's padding is set to the background's 10830 * padding. However, when a background is removed, this View's padding isn't 10831 * touched. If setting the padding is desired, please use 10832 * {@link #setPadding(int, int, int, int)}. 10833 * 10834 * @param d The Drawable to use as the background, or null to remove the 10835 * background 10836 */ 10837 public void setBackgroundDrawable(Drawable d) { 10838 boolean requestLayout = false; 10839 10840 mBackgroundResource = 0; 10841 10842 /* 10843 * Regardless of whether we're setting a new background or not, we want 10844 * to clear the previous drawable. 10845 */ 10846 if (mBGDrawable != null) { 10847 mBGDrawable.setCallback(null); 10848 unscheduleDrawable(mBGDrawable); 10849 } 10850 10851 if (d != null) { 10852 Rect padding = sThreadLocal.get(); 10853 if (padding == null) { 10854 padding = new Rect(); 10855 sThreadLocal.set(padding); 10856 } 10857 if (d.getPadding(padding)) { 10858 switch (d.getResolvedLayoutDirectionSelf()) { 10859 case LAYOUT_DIRECTION_RTL: 10860 setPadding(padding.right, padding.top, padding.left, padding.bottom); 10861 break; 10862 case LAYOUT_DIRECTION_LTR: 10863 default: 10864 setPadding(padding.left, padding.top, padding.right, padding.bottom); 10865 } 10866 } 10867 10868 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 10869 // if it has a different minimum size, we should layout again 10870 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 10871 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 10872 requestLayout = true; 10873 } 10874 10875 d.setCallback(this); 10876 if (d.isStateful()) { 10877 d.setState(getDrawableState()); 10878 } 10879 d.setVisible(getVisibility() == VISIBLE, false); 10880 mBGDrawable = d; 10881 10882 if ((mPrivateFlags & SKIP_DRAW) != 0) { 10883 mPrivateFlags &= ~SKIP_DRAW; 10884 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 10885 requestLayout = true; 10886 } 10887 } else { 10888 /* Remove the background */ 10889 mBGDrawable = null; 10890 10891 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 10892 /* 10893 * This view ONLY drew the background before and we're removing 10894 * the background, so now it won't draw anything 10895 * (hence we SKIP_DRAW) 10896 */ 10897 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 10898 mPrivateFlags |= SKIP_DRAW; 10899 } 10900 10901 /* 10902 * When the background is set, we try to apply its padding to this 10903 * View. When the background is removed, we don't touch this View's 10904 * padding. This is noted in the Javadocs. Hence, we don't need to 10905 * requestLayout(), the invalidate() below is sufficient. 10906 */ 10907 10908 // The old background's minimum size could have affected this 10909 // View's layout, so let's requestLayout 10910 requestLayout = true; 10911 } 10912 10913 computeOpaqueFlags(); 10914 10915 if (requestLayout) { 10916 requestLayout(); 10917 } 10918 10919 mBackgroundSizeChanged = true; 10920 invalidate(true); 10921 } 10922 10923 /** 10924 * Gets the background drawable 10925 * @return The drawable used as the background for this view, if any. 10926 */ 10927 public Drawable getBackground() { 10928 return mBGDrawable; 10929 } 10930 10931 /** 10932 * Sets the padding. The view may add on the space required to display 10933 * the scrollbars, depending on the style and visibility of the scrollbars. 10934 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 10935 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 10936 * from the values set in this call. 10937 * 10938 * @attr ref android.R.styleable#View_padding 10939 * @attr ref android.R.styleable#View_paddingBottom 10940 * @attr ref android.R.styleable#View_paddingLeft 10941 * @attr ref android.R.styleable#View_paddingRight 10942 * @attr ref android.R.styleable#View_paddingTop 10943 * @param left the left padding in pixels 10944 * @param top the top padding in pixels 10945 * @param right the right padding in pixels 10946 * @param bottom the bottom padding in pixels 10947 */ 10948 public void setPadding(int left, int top, int right, int bottom) { 10949 boolean changed = false; 10950 10951 mUserPaddingRelative = false; 10952 10953 mUserPaddingLeft = left; 10954 mUserPaddingRight = right; 10955 mUserPaddingBottom = bottom; 10956 10957 final int viewFlags = mViewFlags; 10958 10959 // Common case is there are no scroll bars. 10960 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 10961 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 10962 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 10963 ? 0 : getVerticalScrollbarWidth(); 10964 switch (mVerticalScrollbarPosition) { 10965 case SCROLLBAR_POSITION_DEFAULT: 10966 if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 10967 left += offset; 10968 } else { 10969 right += offset; 10970 } 10971 break; 10972 case SCROLLBAR_POSITION_RIGHT: 10973 right += offset; 10974 break; 10975 case SCROLLBAR_POSITION_LEFT: 10976 left += offset; 10977 break; 10978 } 10979 } 10980 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 10981 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 10982 ? 0 : getHorizontalScrollbarHeight(); 10983 } 10984 } 10985 10986 if (mPaddingLeft != left) { 10987 changed = true; 10988 mPaddingLeft = left; 10989 } 10990 if (mPaddingTop != top) { 10991 changed = true; 10992 mPaddingTop = top; 10993 } 10994 if (mPaddingRight != right) { 10995 changed = true; 10996 mPaddingRight = right; 10997 } 10998 if (mPaddingBottom != bottom) { 10999 changed = true; 11000 mPaddingBottom = bottom; 11001 } 11002 11003 if (changed) { 11004 requestLayout(); 11005 } 11006 } 11007 11008 /** 11009 * Sets the relative padding. The view may add on the space required to display 11010 * the scrollbars, depending on the style and visibility of the scrollbars. 11011 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 11012 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 11013 * from the values set in this call. 11014 * 11015 * @attr ref android.R.styleable#View_padding 11016 * @attr ref android.R.styleable#View_paddingBottom 11017 * @attr ref android.R.styleable#View_paddingStart 11018 * @attr ref android.R.styleable#View_paddingEnd 11019 * @attr ref android.R.styleable#View_paddingTop 11020 * @param start the start padding in pixels 11021 * @param top the top padding in pixels 11022 * @param end the end padding in pixels 11023 * @param bottom the bottom padding in pixels 11024 * 11025 * @hide 11026 */ 11027 public void setPaddingRelative(int start, int top, int end, int bottom) { 11028 mUserPaddingRelative = true; 11029 switch(getResolvedLayoutDirection()) { 11030 case LAYOUT_DIRECTION_RTL: 11031 setPadding(end, top, start, bottom); 11032 break; 11033 case LAYOUT_DIRECTION_LTR: 11034 default: 11035 setPadding(start, top, end, bottom); 11036 } 11037 } 11038 11039 /** 11040 * Returns the top padding of this view. 11041 * 11042 * @return the top padding in pixels 11043 */ 11044 public int getPaddingTop() { 11045 return mPaddingTop; 11046 } 11047 11048 /** 11049 * Returns the bottom padding of this view. If there are inset and enabled 11050 * scrollbars, this value may include the space required to display the 11051 * scrollbars as well. 11052 * 11053 * @return the bottom padding in pixels 11054 */ 11055 public int getPaddingBottom() { 11056 return mPaddingBottom; 11057 } 11058 11059 /** 11060 * Returns the left padding of this view. If there are inset and enabled 11061 * scrollbars, this value may include the space required to display the 11062 * scrollbars as well. 11063 * 11064 * @return the left padding in pixels 11065 */ 11066 public int getPaddingLeft() { 11067 return mPaddingLeft; 11068 } 11069 11070 /** 11071 * Returns the start padding of this view. If there are inset and enabled 11072 * scrollbars, this value may include the space required to display the 11073 * scrollbars as well. 11074 * 11075 * @return the start padding in pixels 11076 * 11077 * @hide 11078 */ 11079 public int getPaddingStart() { 11080 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 11081 mPaddingRight : mPaddingLeft; 11082 } 11083 11084 /** 11085 * Returns the right padding of this view. If there are inset and enabled 11086 * scrollbars, this value may include the space required to display the 11087 * scrollbars as well. 11088 * 11089 * @return the right padding in pixels 11090 */ 11091 public int getPaddingRight() { 11092 return mPaddingRight; 11093 } 11094 11095 /** 11096 * Returns the end padding of this view. If there are inset and enabled 11097 * scrollbars, this value may include the space required to display the 11098 * scrollbars as well. 11099 * 11100 * @return the end padding in pixels 11101 * 11102 * @hide 11103 */ 11104 public int getPaddingEnd() { 11105 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 11106 mPaddingLeft : mPaddingRight; 11107 } 11108 11109 /** 11110 * Return if the padding as been set thru relative values 11111 * {@link #setPaddingRelative(int, int, int, int)} or thru 11112 * @attr ref android.R.styleable#View_paddingStart or 11113 * @attr ref android.R.styleable#View_paddingEnd 11114 * 11115 * @return true if the padding is relative or false if it is not. 11116 * 11117 * @hide 11118 */ 11119 public boolean isPaddingRelative() { 11120 return mUserPaddingRelative; 11121 } 11122 11123 /** 11124 * Changes the selection state of this view. A view can be selected or not. 11125 * Note that selection is not the same as focus. Views are typically 11126 * selected in the context of an AdapterView like ListView or GridView; 11127 * the selected view is the view that is highlighted. 11128 * 11129 * @param selected true if the view must be selected, false otherwise 11130 */ 11131 public void setSelected(boolean selected) { 11132 if (((mPrivateFlags & SELECTED) != 0) != selected) { 11133 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 11134 if (!selected) resetPressedState(); 11135 invalidate(true); 11136 refreshDrawableState(); 11137 dispatchSetSelected(selected); 11138 } 11139 } 11140 11141 /** 11142 * Dispatch setSelected to all of this View's children. 11143 * 11144 * @see #setSelected(boolean) 11145 * 11146 * @param selected The new selected state 11147 */ 11148 protected void dispatchSetSelected(boolean selected) { 11149 } 11150 11151 /** 11152 * Indicates the selection state of this view. 11153 * 11154 * @return true if the view is selected, false otherwise 11155 */ 11156 @ViewDebug.ExportedProperty 11157 public boolean isSelected() { 11158 return (mPrivateFlags & SELECTED) != 0; 11159 } 11160 11161 /** 11162 * Changes the activated state of this view. A view can be activated or not. 11163 * Note that activation is not the same as selection. Selection is 11164 * a transient property, representing the view (hierarchy) the user is 11165 * currently interacting with. Activation is a longer-term state that the 11166 * user can move views in and out of. For example, in a list view with 11167 * single or multiple selection enabled, the views in the current selection 11168 * set are activated. (Um, yeah, we are deeply sorry about the terminology 11169 * here.) The activated state is propagated down to children of the view it 11170 * is set on. 11171 * 11172 * @param activated true if the view must be activated, false otherwise 11173 */ 11174 public void setActivated(boolean activated) { 11175 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 11176 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 11177 invalidate(true); 11178 refreshDrawableState(); 11179 dispatchSetActivated(activated); 11180 } 11181 } 11182 11183 /** 11184 * Dispatch setActivated to all of this View's children. 11185 * 11186 * @see #setActivated(boolean) 11187 * 11188 * @param activated The new activated state 11189 */ 11190 protected void dispatchSetActivated(boolean activated) { 11191 } 11192 11193 /** 11194 * Indicates the activation state of this view. 11195 * 11196 * @return true if the view is activated, false otherwise 11197 */ 11198 @ViewDebug.ExportedProperty 11199 public boolean isActivated() { 11200 return (mPrivateFlags & ACTIVATED) != 0; 11201 } 11202 11203 /** 11204 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 11205 * observer can be used to get notifications when global events, like 11206 * layout, happen. 11207 * 11208 * The returned ViewTreeObserver observer is not guaranteed to remain 11209 * valid for the lifetime of this View. If the caller of this method keeps 11210 * a long-lived reference to ViewTreeObserver, it should always check for 11211 * the return value of {@link ViewTreeObserver#isAlive()}. 11212 * 11213 * @return The ViewTreeObserver for this view's hierarchy. 11214 */ 11215 public ViewTreeObserver getViewTreeObserver() { 11216 if (mAttachInfo != null) { 11217 return mAttachInfo.mTreeObserver; 11218 } 11219 if (mFloatingTreeObserver == null) { 11220 mFloatingTreeObserver = new ViewTreeObserver(); 11221 } 11222 return mFloatingTreeObserver; 11223 } 11224 11225 /** 11226 * <p>Finds the topmost view in the current view hierarchy.</p> 11227 * 11228 * @return the topmost view containing this view 11229 */ 11230 public View getRootView() { 11231 if (mAttachInfo != null) { 11232 final View v = mAttachInfo.mRootView; 11233 if (v != null) { 11234 return v; 11235 } 11236 } 11237 11238 View parent = this; 11239 11240 while (parent.mParent != null && parent.mParent instanceof View) { 11241 parent = (View) parent.mParent; 11242 } 11243 11244 return parent; 11245 } 11246 11247 /** 11248 * <p>Computes the coordinates of this view on the screen. The argument 11249 * must be an array of two integers. After the method returns, the array 11250 * contains the x and y location in that order.</p> 11251 * 11252 * @param location an array of two integers in which to hold the coordinates 11253 */ 11254 public void getLocationOnScreen(int[] location) { 11255 getLocationInWindow(location); 11256 11257 final AttachInfo info = mAttachInfo; 11258 if (info != null) { 11259 location[0] += info.mWindowLeft; 11260 location[1] += info.mWindowTop; 11261 } 11262 } 11263 11264 /** 11265 * <p>Computes the coordinates of this view in its window. The argument 11266 * must be an array of two integers. After the method returns, the array 11267 * contains the x and y location in that order.</p> 11268 * 11269 * @param location an array of two integers in which to hold the coordinates 11270 */ 11271 public void getLocationInWindow(int[] location) { 11272 if (location == null || location.length < 2) { 11273 throw new IllegalArgumentException("location must be an array of " 11274 + "two integers"); 11275 } 11276 11277 location[0] = mLeft + (int) (mTranslationX + 0.5f); 11278 location[1] = mTop + (int) (mTranslationY + 0.5f); 11279 11280 ViewParent viewParent = mParent; 11281 while (viewParent instanceof View) { 11282 final View view = (View)viewParent; 11283 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX; 11284 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY; 11285 viewParent = view.mParent; 11286 } 11287 11288 if (viewParent instanceof ViewAncestor) { 11289 // *cough* 11290 final ViewAncestor vr = (ViewAncestor)viewParent; 11291 location[1] -= vr.mCurScrollY; 11292 } 11293 } 11294 11295 /** 11296 * {@hide} 11297 * @param id the id of the view to be found 11298 * @return the view of the specified id, null if cannot be found 11299 */ 11300 protected View findViewTraversal(int id) { 11301 if (id == mID) { 11302 return this; 11303 } 11304 return null; 11305 } 11306 11307 /** 11308 * {@hide} 11309 * @param tag the tag of the view to be found 11310 * @return the view of specified tag, null if cannot be found 11311 */ 11312 protected View findViewWithTagTraversal(Object tag) { 11313 if (tag != null && tag.equals(mTag)) { 11314 return this; 11315 } 11316 return null; 11317 } 11318 11319 /** 11320 * {@hide} 11321 * @param predicate The predicate to evaluate. 11322 * @return The first view that matches the predicate or null. 11323 */ 11324 protected View findViewByPredicateTraversal(Predicate<View> predicate) { 11325 if (predicate.apply(this)) { 11326 return this; 11327 } 11328 return null; 11329 } 11330 11331 /** 11332 * Look for a child view with the given id. If this view has the given 11333 * id, return this view. 11334 * 11335 * @param id The id to search for. 11336 * @return The view that has the given id in the hierarchy or null 11337 */ 11338 public final View findViewById(int id) { 11339 if (id < 0) { 11340 return null; 11341 } 11342 return findViewTraversal(id); 11343 } 11344 11345 /** 11346 * Look for a child view with the given tag. If this view has the given 11347 * tag, return this view. 11348 * 11349 * @param tag The tag to search for, using "tag.equals(getTag())". 11350 * @return The View that has the given tag in the hierarchy or null 11351 */ 11352 public final View findViewWithTag(Object tag) { 11353 if (tag == null) { 11354 return null; 11355 } 11356 return findViewWithTagTraversal(tag); 11357 } 11358 11359 /** 11360 * {@hide} 11361 * Look for a child view that matches the specified predicate. 11362 * If this view matches the predicate, return this view. 11363 * 11364 * @param predicate The predicate to evaluate. 11365 * @return The first view that matches the predicate or null. 11366 */ 11367 public final View findViewByPredicate(Predicate<View> predicate) { 11368 return findViewByPredicateTraversal(predicate); 11369 } 11370 11371 /** 11372 * Sets the identifier for this view. The identifier does not have to be 11373 * unique in this view's hierarchy. The identifier should be a positive 11374 * number. 11375 * 11376 * @see #NO_ID 11377 * @see #getId() 11378 * @see #findViewById(int) 11379 * 11380 * @param id a number used to identify the view 11381 * 11382 * @attr ref android.R.styleable#View_id 11383 */ 11384 public void setId(int id) { 11385 mID = id; 11386 } 11387 11388 /** 11389 * {@hide} 11390 * 11391 * @param isRoot true if the view belongs to the root namespace, false 11392 * otherwise 11393 */ 11394 public void setIsRootNamespace(boolean isRoot) { 11395 if (isRoot) { 11396 mPrivateFlags |= IS_ROOT_NAMESPACE; 11397 } else { 11398 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 11399 } 11400 } 11401 11402 /** 11403 * {@hide} 11404 * 11405 * @return true if the view belongs to the root namespace, false otherwise 11406 */ 11407 public boolean isRootNamespace() { 11408 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 11409 } 11410 11411 /** 11412 * Returns this view's identifier. 11413 * 11414 * @return a positive integer used to identify the view or {@link #NO_ID} 11415 * if the view has no ID 11416 * 11417 * @see #setId(int) 11418 * @see #findViewById(int) 11419 * @attr ref android.R.styleable#View_id 11420 */ 11421 @ViewDebug.CapturedViewProperty 11422 public int getId() { 11423 return mID; 11424 } 11425 11426 /** 11427 * Returns this view's tag. 11428 * 11429 * @return the Object stored in this view as a tag 11430 * 11431 * @see #setTag(Object) 11432 * @see #getTag(int) 11433 */ 11434 @ViewDebug.ExportedProperty 11435 public Object getTag() { 11436 return mTag; 11437 } 11438 11439 /** 11440 * Sets the tag associated with this view. A tag can be used to mark 11441 * a view in its hierarchy and does not have to be unique within the 11442 * hierarchy. Tags can also be used to store data within a view without 11443 * resorting to another data structure. 11444 * 11445 * @param tag an Object to tag the view with 11446 * 11447 * @see #getTag() 11448 * @see #setTag(int, Object) 11449 */ 11450 public void setTag(final Object tag) { 11451 mTag = tag; 11452 } 11453 11454 /** 11455 * Returns the tag associated with this view and the specified key. 11456 * 11457 * @param key The key identifying the tag 11458 * 11459 * @return the Object stored in this view as a tag 11460 * 11461 * @see #setTag(int, Object) 11462 * @see #getTag() 11463 */ 11464 public Object getTag(int key) { 11465 SparseArray<Object> tags = null; 11466 synchronized (sTagsLock) { 11467 if (sTags != null) { 11468 tags = sTags.get(this); 11469 } 11470 } 11471 11472 if (tags != null) return tags.get(key); 11473 return null; 11474 } 11475 11476 /** 11477 * Sets a tag associated with this view and a key. A tag can be used 11478 * to mark a view in its hierarchy and does not have to be unique within 11479 * the hierarchy. Tags can also be used to store data within a view 11480 * without resorting to another data structure. 11481 * 11482 * The specified key should be an id declared in the resources of the 11483 * application to ensure it is unique (see the <a 11484 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 11485 * Keys identified as belonging to 11486 * the Android framework or not associated with any package will cause 11487 * an {@link IllegalArgumentException} to be thrown. 11488 * 11489 * @param key The key identifying the tag 11490 * @param tag An Object to tag the view with 11491 * 11492 * @throws IllegalArgumentException If they specified key is not valid 11493 * 11494 * @see #setTag(Object) 11495 * @see #getTag(int) 11496 */ 11497 public void setTag(int key, final Object tag) { 11498 // If the package id is 0x00 or 0x01, it's either an undefined package 11499 // or a framework id 11500 if ((key >>> 24) < 2) { 11501 throw new IllegalArgumentException("The key must be an application-specific " 11502 + "resource id."); 11503 } 11504 11505 setTagInternal(this, key, tag); 11506 } 11507 11508 /** 11509 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 11510 * framework id. 11511 * 11512 * @hide 11513 */ 11514 public void setTagInternal(int key, Object tag) { 11515 if ((key >>> 24) != 0x1) { 11516 throw new IllegalArgumentException("The key must be a framework-specific " 11517 + "resource id."); 11518 } 11519 11520 setTagInternal(this, key, tag); 11521 } 11522 11523 private static void setTagInternal(View view, int key, Object tag) { 11524 SparseArray<Object> tags = null; 11525 synchronized (sTagsLock) { 11526 if (sTags == null) { 11527 sTags = new WeakHashMap<View, SparseArray<Object>>(); 11528 } else { 11529 tags = sTags.get(view); 11530 } 11531 } 11532 11533 if (tags == null) { 11534 tags = new SparseArray<Object>(2); 11535 synchronized (sTagsLock) { 11536 sTags.put(view, tags); 11537 } 11538 } 11539 11540 tags.put(key, tag); 11541 } 11542 11543 /** 11544 * @param consistency The type of consistency. See ViewDebug for more information. 11545 * 11546 * @hide 11547 */ 11548 protected boolean dispatchConsistencyCheck(int consistency) { 11549 return onConsistencyCheck(consistency); 11550 } 11551 11552 /** 11553 * Method that subclasses should implement to check their consistency. The type of 11554 * consistency check is indicated by the bit field passed as a parameter. 11555 * 11556 * @param consistency The type of consistency. See ViewDebug for more information. 11557 * 11558 * @throws IllegalStateException if the view is in an inconsistent state. 11559 * 11560 * @hide 11561 */ 11562 protected boolean onConsistencyCheck(int consistency) { 11563 boolean result = true; 11564 11565 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 11566 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 11567 11568 if (checkLayout) { 11569 if (getParent() == null) { 11570 result = false; 11571 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 11572 "View " + this + " does not have a parent."); 11573 } 11574 11575 if (mAttachInfo == null) { 11576 result = false; 11577 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 11578 "View " + this + " is not attached to a window."); 11579 } 11580 } 11581 11582 if (checkDrawing) { 11583 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 11584 // from their draw() method 11585 11586 if ((mPrivateFlags & DRAWN) != DRAWN && 11587 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 11588 result = false; 11589 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 11590 "View " + this + " was invalidated but its drawing cache is valid."); 11591 } 11592 } 11593 11594 return result; 11595 } 11596 11597 /** 11598 * Prints information about this view in the log output, with the tag 11599 * {@link #VIEW_LOG_TAG}. 11600 * 11601 * @hide 11602 */ 11603 public void debug() { 11604 debug(0); 11605 } 11606 11607 /** 11608 * Prints information about this view in the log output, with the tag 11609 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 11610 * indentation defined by the <code>depth</code>. 11611 * 11612 * @param depth the indentation level 11613 * 11614 * @hide 11615 */ 11616 protected void debug(int depth) { 11617 String output = debugIndent(depth - 1); 11618 11619 output += "+ " + this; 11620 int id = getId(); 11621 if (id != -1) { 11622 output += " (id=" + id + ")"; 11623 } 11624 Object tag = getTag(); 11625 if (tag != null) { 11626 output += " (tag=" + tag + ")"; 11627 } 11628 Log.d(VIEW_LOG_TAG, output); 11629 11630 if ((mPrivateFlags & FOCUSED) != 0) { 11631 output = debugIndent(depth) + " FOCUSED"; 11632 Log.d(VIEW_LOG_TAG, output); 11633 } 11634 11635 output = debugIndent(depth); 11636 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 11637 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 11638 + "} "; 11639 Log.d(VIEW_LOG_TAG, output); 11640 11641 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 11642 || mPaddingBottom != 0) { 11643 output = debugIndent(depth); 11644 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 11645 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 11646 Log.d(VIEW_LOG_TAG, output); 11647 } 11648 11649 output = debugIndent(depth); 11650 output += "mMeasureWidth=" + mMeasuredWidth + 11651 " mMeasureHeight=" + mMeasuredHeight; 11652 Log.d(VIEW_LOG_TAG, output); 11653 11654 output = debugIndent(depth); 11655 if (mLayoutParams == null) { 11656 output += "BAD! no layout params"; 11657 } else { 11658 output = mLayoutParams.debug(output); 11659 } 11660 Log.d(VIEW_LOG_TAG, output); 11661 11662 output = debugIndent(depth); 11663 output += "flags={"; 11664 output += View.printFlags(mViewFlags); 11665 output += "}"; 11666 Log.d(VIEW_LOG_TAG, output); 11667 11668 output = debugIndent(depth); 11669 output += "privateFlags={"; 11670 output += View.printPrivateFlags(mPrivateFlags); 11671 output += "}"; 11672 Log.d(VIEW_LOG_TAG, output); 11673 } 11674 11675 /** 11676 * Creates an string of whitespaces used for indentation. 11677 * 11678 * @param depth the indentation level 11679 * @return a String containing (depth * 2 + 3) * 2 white spaces 11680 * 11681 * @hide 11682 */ 11683 protected static String debugIndent(int depth) { 11684 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 11685 for (int i = 0; i < (depth * 2) + 3; i++) { 11686 spaces.append(' ').append(' '); 11687 } 11688 return spaces.toString(); 11689 } 11690 11691 /** 11692 * <p>Return the offset of the widget's text baseline from the widget's top 11693 * boundary. If this widget does not support baseline alignment, this 11694 * method returns -1. </p> 11695 * 11696 * @return the offset of the baseline within the widget's bounds or -1 11697 * if baseline alignment is not supported 11698 */ 11699 @ViewDebug.ExportedProperty(category = "layout") 11700 public int getBaseline() { 11701 return -1; 11702 } 11703 11704 /** 11705 * Call this when something has changed which has invalidated the 11706 * layout of this view. This will schedule a layout pass of the view 11707 * tree. 11708 */ 11709 public void requestLayout() { 11710 if (ViewDebug.TRACE_HIERARCHY) { 11711 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 11712 } 11713 11714 mPrivateFlags |= FORCE_LAYOUT; 11715 mPrivateFlags |= INVALIDATED; 11716 11717 if (mParent != null && !mParent.isLayoutRequested()) { 11718 mParent.requestLayout(); 11719 } 11720 } 11721 11722 /** 11723 * Forces this view to be laid out during the next layout pass. 11724 * This method does not call requestLayout() or forceLayout() 11725 * on the parent. 11726 */ 11727 public void forceLayout() { 11728 mPrivateFlags |= FORCE_LAYOUT; 11729 mPrivateFlags |= INVALIDATED; 11730 } 11731 11732 /** 11733 * <p> 11734 * This is called to find out how big a view should be. The parent 11735 * supplies constraint information in the width and height parameters. 11736 * </p> 11737 * 11738 * <p> 11739 * The actual mesurement work of a view is performed in 11740 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 11741 * {@link #onMeasure(int, int)} can and must be overriden by subclasses. 11742 * </p> 11743 * 11744 * 11745 * @param widthMeasureSpec Horizontal space requirements as imposed by the 11746 * parent 11747 * @param heightMeasureSpec Vertical space requirements as imposed by the 11748 * parent 11749 * 11750 * @see #onMeasure(int, int) 11751 */ 11752 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 11753 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 11754 widthMeasureSpec != mOldWidthMeasureSpec || 11755 heightMeasureSpec != mOldHeightMeasureSpec) { 11756 11757 // first clears the measured dimension flag 11758 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 11759 11760 if (ViewDebug.TRACE_HIERARCHY) { 11761 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 11762 } 11763 11764 // measure ourselves, this should set the measured dimension flag back 11765 onMeasure(widthMeasureSpec, heightMeasureSpec); 11766 11767 // flag not set, setMeasuredDimension() was not invoked, we raise 11768 // an exception to warn the developer 11769 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 11770 throw new IllegalStateException("onMeasure() did not set the" 11771 + " measured dimension by calling" 11772 + " setMeasuredDimension()"); 11773 } 11774 11775 mPrivateFlags |= LAYOUT_REQUIRED; 11776 } 11777 11778 mOldWidthMeasureSpec = widthMeasureSpec; 11779 mOldHeightMeasureSpec = heightMeasureSpec; 11780 } 11781 11782 /** 11783 * <p> 11784 * Measure the view and its content to determine the measured width and the 11785 * measured height. This method is invoked by {@link #measure(int, int)} and 11786 * should be overriden by subclasses to provide accurate and efficient 11787 * measurement of their contents. 11788 * </p> 11789 * 11790 * <p> 11791 * <strong>CONTRACT:</strong> When overriding this method, you 11792 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 11793 * measured width and height of this view. Failure to do so will trigger an 11794 * <code>IllegalStateException</code>, thrown by 11795 * {@link #measure(int, int)}. Calling the superclass' 11796 * {@link #onMeasure(int, int)} is a valid use. 11797 * </p> 11798 * 11799 * <p> 11800 * The base class implementation of measure defaults to the background size, 11801 * unless a larger size is allowed by the MeasureSpec. Subclasses should 11802 * override {@link #onMeasure(int, int)} to provide better measurements of 11803 * their content. 11804 * </p> 11805 * 11806 * <p> 11807 * If this method is overridden, it is the subclass's responsibility to make 11808 * sure the measured height and width are at least the view's minimum height 11809 * and width ({@link #getSuggestedMinimumHeight()} and 11810 * {@link #getSuggestedMinimumWidth()}). 11811 * </p> 11812 * 11813 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 11814 * The requirements are encoded with 11815 * {@link android.view.View.MeasureSpec}. 11816 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 11817 * The requirements are encoded with 11818 * {@link android.view.View.MeasureSpec}. 11819 * 11820 * @see #getMeasuredWidth() 11821 * @see #getMeasuredHeight() 11822 * @see #setMeasuredDimension(int, int) 11823 * @see #getSuggestedMinimumHeight() 11824 * @see #getSuggestedMinimumWidth() 11825 * @see android.view.View.MeasureSpec#getMode(int) 11826 * @see android.view.View.MeasureSpec#getSize(int) 11827 */ 11828 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 11829 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 11830 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 11831 } 11832 11833 /** 11834 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 11835 * measured width and measured height. Failing to do so will trigger an 11836 * exception at measurement time.</p> 11837 * 11838 * @param measuredWidth The measured width of this view. May be a complex 11839 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 11840 * {@link #MEASURED_STATE_TOO_SMALL}. 11841 * @param measuredHeight The measured height of this view. May be a complex 11842 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 11843 * {@link #MEASURED_STATE_TOO_SMALL}. 11844 */ 11845 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 11846 mMeasuredWidth = measuredWidth; 11847 mMeasuredHeight = measuredHeight; 11848 11849 mPrivateFlags |= MEASURED_DIMENSION_SET; 11850 } 11851 11852 /** 11853 * Merge two states as returned by {@link #getMeasuredState()}. 11854 * @param curState The current state as returned from a view or the result 11855 * of combining multiple views. 11856 * @param newState The new view state to combine. 11857 * @return Returns a new integer reflecting the combination of the two 11858 * states. 11859 */ 11860 public static int combineMeasuredStates(int curState, int newState) { 11861 return curState | newState; 11862 } 11863 11864 /** 11865 * Version of {@link #resolveSizeAndState(int, int, int)} 11866 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 11867 */ 11868 public static int resolveSize(int size, int measureSpec) { 11869 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 11870 } 11871 11872 /** 11873 * Utility to reconcile a desired size and state, with constraints imposed 11874 * by a MeasureSpec. Will take the desired size, unless a different size 11875 * is imposed by the constraints. The returned value is a compound integer, 11876 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 11877 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 11878 * size is smaller than the size the view wants to be. 11879 * 11880 * @param size How big the view wants to be 11881 * @param measureSpec Constraints imposed by the parent 11882 * @return Size information bit mask as defined by 11883 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11884 */ 11885 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 11886 int result = size; 11887 int specMode = MeasureSpec.getMode(measureSpec); 11888 int specSize = MeasureSpec.getSize(measureSpec); 11889 switch (specMode) { 11890 case MeasureSpec.UNSPECIFIED: 11891 result = size; 11892 break; 11893 case MeasureSpec.AT_MOST: 11894 if (specSize < size) { 11895 result = specSize | MEASURED_STATE_TOO_SMALL; 11896 } else { 11897 result = size; 11898 } 11899 break; 11900 case MeasureSpec.EXACTLY: 11901 result = specSize; 11902 break; 11903 } 11904 return result | (childMeasuredState&MEASURED_STATE_MASK); 11905 } 11906 11907 /** 11908 * Utility to return a default size. Uses the supplied size if the 11909 * MeasureSpec imposed no constraints. Will get larger if allowed 11910 * by the MeasureSpec. 11911 * 11912 * @param size Default size for this view 11913 * @param measureSpec Constraints imposed by the parent 11914 * @return The size this view should be. 11915 */ 11916 public static int getDefaultSize(int size, int measureSpec) { 11917 int result = size; 11918 int specMode = MeasureSpec.getMode(measureSpec); 11919 int specSize = MeasureSpec.getSize(measureSpec); 11920 11921 switch (specMode) { 11922 case MeasureSpec.UNSPECIFIED: 11923 result = size; 11924 break; 11925 case MeasureSpec.AT_MOST: 11926 case MeasureSpec.EXACTLY: 11927 result = specSize; 11928 break; 11929 } 11930 return result; 11931 } 11932 11933 /** 11934 * Returns the suggested minimum height that the view should use. This 11935 * returns the maximum of the view's minimum height 11936 * and the background's minimum height 11937 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 11938 * <p> 11939 * When being used in {@link #onMeasure(int, int)}, the caller should still 11940 * ensure the returned height is within the requirements of the parent. 11941 * 11942 * @return The suggested minimum height of the view. 11943 */ 11944 protected int getSuggestedMinimumHeight() { 11945 int suggestedMinHeight = mMinHeight; 11946 11947 if (mBGDrawable != null) { 11948 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 11949 if (suggestedMinHeight < bgMinHeight) { 11950 suggestedMinHeight = bgMinHeight; 11951 } 11952 } 11953 11954 return suggestedMinHeight; 11955 } 11956 11957 /** 11958 * Returns the suggested minimum width that the view should use. This 11959 * returns the maximum of the view's minimum width) 11960 * and the background's minimum width 11961 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 11962 * <p> 11963 * When being used in {@link #onMeasure(int, int)}, the caller should still 11964 * ensure the returned width is within the requirements of the parent. 11965 * 11966 * @return The suggested minimum width of the view. 11967 */ 11968 protected int getSuggestedMinimumWidth() { 11969 int suggestedMinWidth = mMinWidth; 11970 11971 if (mBGDrawable != null) { 11972 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 11973 if (suggestedMinWidth < bgMinWidth) { 11974 suggestedMinWidth = bgMinWidth; 11975 } 11976 } 11977 11978 return suggestedMinWidth; 11979 } 11980 11981 /** 11982 * Sets the minimum height of the view. It is not guaranteed the view will 11983 * be able to achieve this minimum height (for example, if its parent layout 11984 * constrains it with less available height). 11985 * 11986 * @param minHeight The minimum height the view will try to be. 11987 */ 11988 public void setMinimumHeight(int minHeight) { 11989 mMinHeight = minHeight; 11990 } 11991 11992 /** 11993 * Sets the minimum width of the view. It is not guaranteed the view will 11994 * be able to achieve this minimum width (for example, if its parent layout 11995 * constrains it with less available width). 11996 * 11997 * @param minWidth The minimum width the view will try to be. 11998 */ 11999 public void setMinimumWidth(int minWidth) { 12000 mMinWidth = minWidth; 12001 } 12002 12003 /** 12004 * Get the animation currently associated with this view. 12005 * 12006 * @return The animation that is currently playing or 12007 * scheduled to play for this view. 12008 */ 12009 public Animation getAnimation() { 12010 return mCurrentAnimation; 12011 } 12012 12013 /** 12014 * Start the specified animation now. 12015 * 12016 * @param animation the animation to start now 12017 */ 12018 public void startAnimation(Animation animation) { 12019 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 12020 setAnimation(animation); 12021 invalidateParentCaches(); 12022 invalidate(true); 12023 } 12024 12025 /** 12026 * Cancels any animations for this view. 12027 */ 12028 public void clearAnimation() { 12029 if (mCurrentAnimation != null) { 12030 mCurrentAnimation.detach(); 12031 } 12032 mCurrentAnimation = null; 12033 invalidateParentIfNeeded(); 12034 } 12035 12036 /** 12037 * Sets the next animation to play for this view. 12038 * If you want the animation to play immediately, use 12039 * startAnimation. This method provides allows fine-grained 12040 * control over the start time and invalidation, but you 12041 * must make sure that 1) the animation has a start time set, and 12042 * 2) the view will be invalidated when the animation is supposed to 12043 * start. 12044 * 12045 * @param animation The next animation, or null. 12046 */ 12047 public void setAnimation(Animation animation) { 12048 mCurrentAnimation = animation; 12049 if (animation != null) { 12050 animation.reset(); 12051 } 12052 } 12053 12054 /** 12055 * Invoked by a parent ViewGroup to notify the start of the animation 12056 * currently associated with this view. If you override this method, 12057 * always call super.onAnimationStart(); 12058 * 12059 * @see #setAnimation(android.view.animation.Animation) 12060 * @see #getAnimation() 12061 */ 12062 protected void onAnimationStart() { 12063 mPrivateFlags |= ANIMATION_STARTED; 12064 } 12065 12066 /** 12067 * Invoked by a parent ViewGroup to notify the end of the animation 12068 * currently associated with this view. If you override this method, 12069 * always call super.onAnimationEnd(); 12070 * 12071 * @see #setAnimation(android.view.animation.Animation) 12072 * @see #getAnimation() 12073 */ 12074 protected void onAnimationEnd() { 12075 mPrivateFlags &= ~ANIMATION_STARTED; 12076 } 12077 12078 /** 12079 * Invoked if there is a Transform that involves alpha. Subclass that can 12080 * draw themselves with the specified alpha should return true, and then 12081 * respect that alpha when their onDraw() is called. If this returns false 12082 * then the view may be redirected to draw into an offscreen buffer to 12083 * fulfill the request, which will look fine, but may be slower than if the 12084 * subclass handles it internally. The default implementation returns false. 12085 * 12086 * @param alpha The alpha (0..255) to apply to the view's drawing 12087 * @return true if the view can draw with the specified alpha. 12088 */ 12089 protected boolean onSetAlpha(int alpha) { 12090 return false; 12091 } 12092 12093 /** 12094 * This is used by the RootView to perform an optimization when 12095 * the view hierarchy contains one or several SurfaceView. 12096 * SurfaceView is always considered transparent, but its children are not, 12097 * therefore all View objects remove themselves from the global transparent 12098 * region (passed as a parameter to this function). 12099 * 12100 * @param region The transparent region for this ViewAncestor (window). 12101 * 12102 * @return Returns true if the effective visibility of the view at this 12103 * point is opaque, regardless of the transparent region; returns false 12104 * if it is possible for underlying windows to be seen behind the view. 12105 * 12106 * {@hide} 12107 */ 12108 public boolean gatherTransparentRegion(Region region) { 12109 final AttachInfo attachInfo = mAttachInfo; 12110 if (region != null && attachInfo != null) { 12111 final int pflags = mPrivateFlags; 12112 if ((pflags & SKIP_DRAW) == 0) { 12113 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 12114 // remove it from the transparent region. 12115 final int[] location = attachInfo.mTransparentLocation; 12116 getLocationInWindow(location); 12117 region.op(location[0], location[1], location[0] + mRight - mLeft, 12118 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 12119 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 12120 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 12121 // exists, so we remove the background drawable's non-transparent 12122 // parts from this transparent region. 12123 applyDrawableToTransparentRegion(mBGDrawable, region); 12124 } 12125 } 12126 return true; 12127 } 12128 12129 /** 12130 * Play a sound effect for this view. 12131 * 12132 * <p>The framework will play sound effects for some built in actions, such as 12133 * clicking, but you may wish to play these effects in your widget, 12134 * for instance, for internal navigation. 12135 * 12136 * <p>The sound effect will only be played if sound effects are enabled by the user, and 12137 * {@link #isSoundEffectsEnabled()} is true. 12138 * 12139 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 12140 */ 12141 public void playSoundEffect(int soundConstant) { 12142 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 12143 return; 12144 } 12145 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 12146 } 12147 12148 /** 12149 * BZZZTT!!1! 12150 * 12151 * <p>Provide haptic feedback to the user for this view. 12152 * 12153 * <p>The framework will provide haptic feedback for some built in actions, 12154 * such as long presses, but you may wish to provide feedback for your 12155 * own widget. 12156 * 12157 * <p>The feedback will only be performed if 12158 * {@link #isHapticFeedbackEnabled()} is true. 12159 * 12160 * @param feedbackConstant One of the constants defined in 12161 * {@link HapticFeedbackConstants} 12162 */ 12163 public boolean performHapticFeedback(int feedbackConstant) { 12164 return performHapticFeedback(feedbackConstant, 0); 12165 } 12166 12167 /** 12168 * BZZZTT!!1! 12169 * 12170 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 12171 * 12172 * @param feedbackConstant One of the constants defined in 12173 * {@link HapticFeedbackConstants} 12174 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 12175 */ 12176 public boolean performHapticFeedback(int feedbackConstant, int flags) { 12177 if (mAttachInfo == null) { 12178 return false; 12179 } 12180 //noinspection SimplifiableIfStatement 12181 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 12182 && !isHapticFeedbackEnabled()) { 12183 return false; 12184 } 12185 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 12186 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 12187 } 12188 12189 /** 12190 * Request that the visibility of the status bar be changed. 12191 * @param visibility Either {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}. 12192 */ 12193 public void setSystemUiVisibility(int visibility) { 12194 if (visibility != mSystemUiVisibility) { 12195 mSystemUiVisibility = visibility; 12196 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 12197 mParent.recomputeViewAttributes(this); 12198 } 12199 } 12200 } 12201 12202 /** 12203 * Returns the status bar visibility that this view has requested. 12204 * @return Either {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}. 12205 */ 12206 public int getSystemUiVisibility() { 12207 return mSystemUiVisibility; 12208 } 12209 12210 /** 12211 * Set a listener to receive callbacks when the visibility of the system bar changes. 12212 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 12213 */ 12214 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 12215 mOnSystemUiVisibilityChangeListener = l; 12216 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 12217 mParent.recomputeViewAttributes(this); 12218 } 12219 } 12220 12221 /** 12222 */ 12223 public void dispatchSystemUiVisibilityChanged(int visibility) { 12224 if (mOnSystemUiVisibilityChangeListener != null) { 12225 mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 12226 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 12227 } 12228 } 12229 12230 /** 12231 * Creates an image that the system displays during the drag and drop 12232 * operation. This is called a "drag shadow". The default implementation 12233 * for a DragShadowBuilder based on a View returns an image that has exactly the same 12234 * appearance as the given View. The default also positions the center of the drag shadow 12235 * directly under the touch point. If no View is provided (the constructor with no parameters 12236 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 12237 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 12238 * default is an invisible drag shadow. 12239 * <p> 12240 * You are not required to use the View you provide to the constructor as the basis of the 12241 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 12242 * anything you want as the drag shadow. 12243 * </p> 12244 * <p> 12245 * You pass a DragShadowBuilder object to the system when you start the drag. The system 12246 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 12247 * size and position of the drag shadow. It uses this data to construct a 12248 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 12249 * so that your application can draw the shadow image in the Canvas. 12250 * </p> 12251 */ 12252 public static class DragShadowBuilder { 12253 private final WeakReference<View> mView; 12254 12255 /** 12256 * Constructs a shadow image builder based on a View. By default, the resulting drag 12257 * shadow will have the same appearance and dimensions as the View, with the touch point 12258 * over the center of the View. 12259 * @param view A View. Any View in scope can be used. 12260 */ 12261 public DragShadowBuilder(View view) { 12262 mView = new WeakReference<View>(view); 12263 } 12264 12265 /** 12266 * Construct a shadow builder object with no associated View. This 12267 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 12268 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 12269 * to supply the drag shadow's dimensions and appearance without 12270 * reference to any View object. If they are not overridden, then the result is an 12271 * invisible drag shadow. 12272 */ 12273 public DragShadowBuilder() { 12274 mView = new WeakReference<View>(null); 12275 } 12276 12277 /** 12278 * Returns the View object that had been passed to the 12279 * {@link #View.DragShadowBuilder(View)} 12280 * constructor. If that View parameter was {@code null} or if the 12281 * {@link #View.DragShadowBuilder()} 12282 * constructor was used to instantiate the builder object, this method will return 12283 * null. 12284 * 12285 * @return The View object associate with this builder object. 12286 */ 12287 @SuppressWarnings({"JavadocReference"}) 12288 final public View getView() { 12289 return mView.get(); 12290 } 12291 12292 /** 12293 * Provides the metrics for the shadow image. These include the dimensions of 12294 * the shadow image, and the point within that shadow that should 12295 * be centered under the touch location while dragging. 12296 * <p> 12297 * The default implementation sets the dimensions of the shadow to be the 12298 * same as the dimensions of the View itself and centers the shadow under 12299 * the touch point. 12300 * </p> 12301 * 12302 * @param shadowSize A {@link android.graphics.Point} containing the width and height 12303 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 12304 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 12305 * image. 12306 * 12307 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 12308 * shadow image that should be underneath the touch point during the drag and drop 12309 * operation. Your application must set {@link android.graphics.Point#x} to the 12310 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 12311 */ 12312 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 12313 final View view = mView.get(); 12314 if (view != null) { 12315 shadowSize.set(view.getWidth(), view.getHeight()); 12316 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 12317 } else { 12318 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 12319 } 12320 } 12321 12322 /** 12323 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 12324 * based on the dimensions it received from the 12325 * {@link #onProvideShadowMetrics(Point, Point)} callback. 12326 * 12327 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 12328 */ 12329 public void onDrawShadow(Canvas canvas) { 12330 final View view = mView.get(); 12331 if (view != null) { 12332 view.draw(canvas); 12333 } else { 12334 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 12335 } 12336 } 12337 } 12338 12339 /** 12340 * Starts a drag and drop operation. When your application calls this method, it passes a 12341 * {@link android.view.View.DragShadowBuilder} object to the system. The 12342 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 12343 * to get metrics for the drag shadow, and then calls the object's 12344 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 12345 * <p> 12346 * Once the system has the drag shadow, it begins the drag and drop operation by sending 12347 * drag events to all the View objects in your application that are currently visible. It does 12348 * this either by calling the View object's drag listener (an implementation of 12349 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 12350 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 12351 * Both are passed a {@link android.view.DragEvent} object that has a 12352 * {@link android.view.DragEvent#getAction()} value of 12353 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 12354 * </p> 12355 * <p> 12356 * Your application can invoke startDrag() on any attached View object. The View object does not 12357 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 12358 * be related to the View the user selected for dragging. 12359 * </p> 12360 * @param data A {@link android.content.ClipData} object pointing to the data to be 12361 * transferred by the drag and drop operation. 12362 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 12363 * drag shadow. 12364 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 12365 * drop operation. This Object is put into every DragEvent object sent by the system during the 12366 * current drag. 12367 * <p> 12368 * myLocalState is a lightweight mechanism for the sending information from the dragged View 12369 * to the target Views. For example, it can contain flags that differentiate between a 12370 * a copy operation and a move operation. 12371 * </p> 12372 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 12373 * so the parameter should be set to 0. 12374 * @return {@code true} if the method completes successfully, or 12375 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 12376 * do a drag, and so no drag operation is in progress. 12377 */ 12378 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 12379 Object myLocalState, int flags) { 12380 if (ViewDebug.DEBUG_DRAG) { 12381 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 12382 } 12383 boolean okay = false; 12384 12385 Point shadowSize = new Point(); 12386 Point shadowTouchPoint = new Point(); 12387 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 12388 12389 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 12390 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 12391 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 12392 } 12393 12394 if (ViewDebug.DEBUG_DRAG) { 12395 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 12396 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 12397 } 12398 Surface surface = new Surface(); 12399 try { 12400 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 12401 flags, shadowSize.x, shadowSize.y, surface); 12402 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 12403 + " surface=" + surface); 12404 if (token != null) { 12405 Canvas canvas = surface.lockCanvas(null); 12406 try { 12407 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 12408 shadowBuilder.onDrawShadow(canvas); 12409 } finally { 12410 surface.unlockCanvasAndPost(canvas); 12411 } 12412 12413 final ViewAncestor root = getViewAncestor(); 12414 12415 // Cache the local state object for delivery with DragEvents 12416 root.setLocalDragState(myLocalState); 12417 12418 // repurpose 'shadowSize' for the last touch point 12419 root.getLastTouchPoint(shadowSize); 12420 12421 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 12422 shadowSize.x, shadowSize.y, 12423 shadowTouchPoint.x, shadowTouchPoint.y, data); 12424 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 12425 } 12426 } catch (Exception e) { 12427 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 12428 surface.destroy(); 12429 } 12430 12431 return okay; 12432 } 12433 12434 /** 12435 * Handles drag events sent by the system following a call to 12436 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 12437 *<p> 12438 * When the system calls this method, it passes a 12439 * {@link android.view.DragEvent} object. A call to 12440 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 12441 * in DragEvent. The method uses these to determine what is happening in the drag and drop 12442 * operation. 12443 * @param event The {@link android.view.DragEvent} sent by the system. 12444 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 12445 * in DragEvent, indicating the type of drag event represented by this object. 12446 * @return {@code true} if the method was successful, otherwise {@code false}. 12447 * <p> 12448 * The method should return {@code true} in response to an action type of 12449 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 12450 * operation. 12451 * </p> 12452 * <p> 12453 * The method should also return {@code true} in response to an action type of 12454 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 12455 * {@code false} if it didn't. 12456 * </p> 12457 */ 12458 public boolean onDragEvent(DragEvent event) { 12459 return false; 12460 } 12461 12462 /** 12463 * Detects if this View is enabled and has a drag event listener. 12464 * If both are true, then it calls the drag event listener with the 12465 * {@link android.view.DragEvent} it received. If the drag event listener returns 12466 * {@code true}, then dispatchDragEvent() returns {@code true}. 12467 * <p> 12468 * For all other cases, the method calls the 12469 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 12470 * method and returns its result. 12471 * </p> 12472 * <p> 12473 * This ensures that a drag event is always consumed, even if the View does not have a drag 12474 * event listener. However, if the View has a listener and the listener returns true, then 12475 * onDragEvent() is not called. 12476 * </p> 12477 */ 12478 public boolean dispatchDragEvent(DragEvent event) { 12479 //noinspection SimplifiableIfStatement 12480 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 12481 && mOnDragListener.onDrag(this, event)) { 12482 return true; 12483 } 12484 return onDragEvent(event); 12485 } 12486 12487 boolean canAcceptDrag() { 12488 return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0; 12489 } 12490 12491 /** 12492 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 12493 * it is ever exposed at all. 12494 * @hide 12495 */ 12496 public void onCloseSystemDialogs(String reason) { 12497 } 12498 12499 /** 12500 * Given a Drawable whose bounds have been set to draw into this view, 12501 * update a Region being computed for 12502 * {@link #gatherTransparentRegion(android.graphics.Region)} so 12503 * that any non-transparent parts of the Drawable are removed from the 12504 * given transparent region. 12505 * 12506 * @param dr The Drawable whose transparency is to be applied to the region. 12507 * @param region A Region holding the current transparency information, 12508 * where any parts of the region that are set are considered to be 12509 * transparent. On return, this region will be modified to have the 12510 * transparency information reduced by the corresponding parts of the 12511 * Drawable that are not transparent. 12512 * {@hide} 12513 */ 12514 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 12515 if (DBG) { 12516 Log.i("View", "Getting transparent region for: " + this); 12517 } 12518 final Region r = dr.getTransparentRegion(); 12519 final Rect db = dr.getBounds(); 12520 final AttachInfo attachInfo = mAttachInfo; 12521 if (r != null && attachInfo != null) { 12522 final int w = getRight()-getLeft(); 12523 final int h = getBottom()-getTop(); 12524 if (db.left > 0) { 12525 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 12526 r.op(0, 0, db.left, h, Region.Op.UNION); 12527 } 12528 if (db.right < w) { 12529 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 12530 r.op(db.right, 0, w, h, Region.Op.UNION); 12531 } 12532 if (db.top > 0) { 12533 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 12534 r.op(0, 0, w, db.top, Region.Op.UNION); 12535 } 12536 if (db.bottom < h) { 12537 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 12538 r.op(0, db.bottom, w, h, Region.Op.UNION); 12539 } 12540 final int[] location = attachInfo.mTransparentLocation; 12541 getLocationInWindow(location); 12542 r.translate(location[0], location[1]); 12543 region.op(r, Region.Op.INTERSECT); 12544 } else { 12545 region.op(db, Region.Op.DIFFERENCE); 12546 } 12547 } 12548 12549 private void checkForLongClick(int delayOffset) { 12550 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 12551 mHasPerformedLongPress = false; 12552 12553 if (mPendingCheckForLongPress == null) { 12554 mPendingCheckForLongPress = new CheckForLongPress(); 12555 } 12556 mPendingCheckForLongPress.rememberWindowAttachCount(); 12557 postDelayed(mPendingCheckForLongPress, 12558 ViewConfiguration.getLongPressTimeout() - delayOffset); 12559 } 12560 } 12561 12562 /** 12563 * Inflate a view from an XML resource. This convenience method wraps the {@link 12564 * LayoutInflater} class, which provides a full range of options for view inflation. 12565 * 12566 * @param context The Context object for your activity or application. 12567 * @param resource The resource ID to inflate 12568 * @param root A view group that will be the parent. Used to properly inflate the 12569 * layout_* parameters. 12570 * @see LayoutInflater 12571 */ 12572 public static View inflate(Context context, int resource, ViewGroup root) { 12573 LayoutInflater factory = LayoutInflater.from(context); 12574 return factory.inflate(resource, root); 12575 } 12576 12577 /** 12578 * Scroll the view with standard behavior for scrolling beyond the normal 12579 * content boundaries. Views that call this method should override 12580 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 12581 * results of an over-scroll operation. 12582 * 12583 * Views can use this method to handle any touch or fling-based scrolling. 12584 * 12585 * @param deltaX Change in X in pixels 12586 * @param deltaY Change in Y in pixels 12587 * @param scrollX Current X scroll value in pixels before applying deltaX 12588 * @param scrollY Current Y scroll value in pixels before applying deltaY 12589 * @param scrollRangeX Maximum content scroll range along the X axis 12590 * @param scrollRangeY Maximum content scroll range along the Y axis 12591 * @param maxOverScrollX Number of pixels to overscroll by in either direction 12592 * along the X axis. 12593 * @param maxOverScrollY Number of pixels to overscroll by in either direction 12594 * along the Y axis. 12595 * @param isTouchEvent true if this scroll operation is the result of a touch event. 12596 * @return true if scrolling was clamped to an over-scroll boundary along either 12597 * axis, false otherwise. 12598 */ 12599 @SuppressWarnings({"UnusedParameters"}) 12600 protected boolean overScrollBy(int deltaX, int deltaY, 12601 int scrollX, int scrollY, 12602 int scrollRangeX, int scrollRangeY, 12603 int maxOverScrollX, int maxOverScrollY, 12604 boolean isTouchEvent) { 12605 final int overScrollMode = mOverScrollMode; 12606 final boolean canScrollHorizontal = 12607 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 12608 final boolean canScrollVertical = 12609 computeVerticalScrollRange() > computeVerticalScrollExtent(); 12610 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 12611 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 12612 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 12613 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 12614 12615 int newScrollX = scrollX + deltaX; 12616 if (!overScrollHorizontal) { 12617 maxOverScrollX = 0; 12618 } 12619 12620 int newScrollY = scrollY + deltaY; 12621 if (!overScrollVertical) { 12622 maxOverScrollY = 0; 12623 } 12624 12625 // Clamp values if at the limits and record 12626 final int left = -maxOverScrollX; 12627 final int right = maxOverScrollX + scrollRangeX; 12628 final int top = -maxOverScrollY; 12629 final int bottom = maxOverScrollY + scrollRangeY; 12630 12631 boolean clampedX = false; 12632 if (newScrollX > right) { 12633 newScrollX = right; 12634 clampedX = true; 12635 } else if (newScrollX < left) { 12636 newScrollX = left; 12637 clampedX = true; 12638 } 12639 12640 boolean clampedY = false; 12641 if (newScrollY > bottom) { 12642 newScrollY = bottom; 12643 clampedY = true; 12644 } else if (newScrollY < top) { 12645 newScrollY = top; 12646 clampedY = true; 12647 } 12648 12649 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 12650 12651 return clampedX || clampedY; 12652 } 12653 12654 /** 12655 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 12656 * respond to the results of an over-scroll operation. 12657 * 12658 * @param scrollX New X scroll value in pixels 12659 * @param scrollY New Y scroll value in pixels 12660 * @param clampedX True if scrollX was clamped to an over-scroll boundary 12661 * @param clampedY True if scrollY was clamped to an over-scroll boundary 12662 */ 12663 protected void onOverScrolled(int scrollX, int scrollY, 12664 boolean clampedX, boolean clampedY) { 12665 // Intentionally empty. 12666 } 12667 12668 /** 12669 * Returns the over-scroll mode for this view. The result will be 12670 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 12671 * (allow over-scrolling only if the view content is larger than the container), 12672 * or {@link #OVER_SCROLL_NEVER}. 12673 * 12674 * @return This view's over-scroll mode. 12675 */ 12676 public int getOverScrollMode() { 12677 return mOverScrollMode; 12678 } 12679 12680 /** 12681 * Set the over-scroll mode for this view. Valid over-scroll modes are 12682 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 12683 * (allow over-scrolling only if the view content is larger than the container), 12684 * or {@link #OVER_SCROLL_NEVER}. 12685 * 12686 * Setting the over-scroll mode of a view will have an effect only if the 12687 * view is capable of scrolling. 12688 * 12689 * @param overScrollMode The new over-scroll mode for this view. 12690 */ 12691 public void setOverScrollMode(int overScrollMode) { 12692 if (overScrollMode != OVER_SCROLL_ALWAYS && 12693 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 12694 overScrollMode != OVER_SCROLL_NEVER) { 12695 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 12696 } 12697 mOverScrollMode = overScrollMode; 12698 } 12699 12700 /** 12701 * Gets a scale factor that determines the distance the view should scroll 12702 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 12703 * @return The vertical scroll scale factor. 12704 * @hide 12705 */ 12706 protected float getVerticalScrollFactor() { 12707 if (mVerticalScrollFactor == 0) { 12708 TypedValue outValue = new TypedValue(); 12709 if (!mContext.getTheme().resolveAttribute( 12710 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 12711 throw new IllegalStateException( 12712 "Expected theme to define listPreferredItemHeight."); 12713 } 12714 mVerticalScrollFactor = outValue.getDimension( 12715 mContext.getResources().getDisplayMetrics()); 12716 } 12717 return mVerticalScrollFactor; 12718 } 12719 12720 /** 12721 * Gets a scale factor that determines the distance the view should scroll 12722 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 12723 * @return The horizontal scroll scale factor. 12724 * @hide 12725 */ 12726 protected float getHorizontalScrollFactor() { 12727 // TODO: Should use something else. 12728 return getVerticalScrollFactor(); 12729 } 12730 12731 // 12732 // Properties 12733 // 12734 /** 12735 * A Property wrapper around the <code>alpha</code> functionality handled by the 12736 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 12737 */ 12738 static Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 12739 @Override 12740 public void setValue(View object, float value) { 12741 object.setAlpha(value); 12742 } 12743 12744 @Override 12745 public Float get(View object) { 12746 return object.getAlpha(); 12747 } 12748 }; 12749 12750 /** 12751 * A Property wrapper around the <code>translationX</code> functionality handled by the 12752 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 12753 */ 12754 public static Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 12755 @Override 12756 public void setValue(View object, float value) { 12757 object.setTranslationX(value); 12758 } 12759 12760 @Override 12761 public Float get(View object) { 12762 return object.getTranslationX(); 12763 } 12764 }; 12765 12766 /** 12767 * A Property wrapper around the <code>translationY</code> functionality handled by the 12768 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 12769 */ 12770 public static Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 12771 @Override 12772 public void setValue(View object, float value) { 12773 object.setTranslationY(value); 12774 } 12775 12776 @Override 12777 public Float get(View object) { 12778 return object.getTranslationY(); 12779 } 12780 }; 12781 12782 /** 12783 * A Property wrapper around the <code>x</code> functionality handled by the 12784 * {@link View#setX(float)} and {@link View#getX()} methods. 12785 */ 12786 public static Property<View, Float> X = new FloatProperty<View>("x") { 12787 @Override 12788 public void setValue(View object, float value) { 12789 object.setX(value); 12790 } 12791 12792 @Override 12793 public Float get(View object) { 12794 return object.getX(); 12795 } 12796 }; 12797 12798 /** 12799 * A Property wrapper around the <code>y</code> functionality handled by the 12800 * {@link View#setY(float)} and {@link View#getY()} methods. 12801 */ 12802 public static Property<View, Float> Y = new FloatProperty<View>("y") { 12803 @Override 12804 public void setValue(View object, float value) { 12805 object.setY(value); 12806 } 12807 12808 @Override 12809 public Float get(View object) { 12810 return object.getY(); 12811 } 12812 }; 12813 12814 /** 12815 * A Property wrapper around the <code>rotation</code> functionality handled by the 12816 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 12817 */ 12818 public static Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 12819 @Override 12820 public void setValue(View object, float value) { 12821 object.setRotation(value); 12822 } 12823 12824 @Override 12825 public Float get(View object) { 12826 return object.getRotation(); 12827 } 12828 }; 12829 12830 /** 12831 * A Property wrapper around the <code>rotationX</code> functionality handled by the 12832 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 12833 */ 12834 public static Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 12835 @Override 12836 public void setValue(View object, float value) { 12837 object.setRotationX(value); 12838 } 12839 12840 @Override 12841 public Float get(View object) { 12842 return object.getRotationX(); 12843 } 12844 }; 12845 12846 /** 12847 * A Property wrapper around the <code>rotationY</code> functionality handled by the 12848 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 12849 */ 12850 public static Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 12851 @Override 12852 public void setValue(View object, float value) { 12853 object.setRotationY(value); 12854 } 12855 12856 @Override 12857 public Float get(View object) { 12858 return object.getRotationY(); 12859 } 12860 }; 12861 12862 /** 12863 * A Property wrapper around the <code>scaleX</code> functionality handled by the 12864 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 12865 */ 12866 public static Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 12867 @Override 12868 public void setValue(View object, float value) { 12869 object.setScaleX(value); 12870 } 12871 12872 @Override 12873 public Float get(View object) { 12874 return object.getScaleX(); 12875 } 12876 }; 12877 12878 /** 12879 * A Property wrapper around the <code>scaleY</code> functionality handled by the 12880 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 12881 */ 12882 public static Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 12883 @Override 12884 public void setValue(View object, float value) { 12885 object.setScaleY(value); 12886 } 12887 12888 @Override 12889 public Float get(View object) { 12890 return object.getScaleY(); 12891 } 12892 }; 12893 12894 /** 12895 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 12896 * Each MeasureSpec represents a requirement for either the width or the height. 12897 * A MeasureSpec is comprised of a size and a mode. There are three possible 12898 * modes: 12899 * <dl> 12900 * <dt>UNSPECIFIED</dt> 12901 * <dd> 12902 * The parent has not imposed any constraint on the child. It can be whatever size 12903 * it wants. 12904 * </dd> 12905 * 12906 * <dt>EXACTLY</dt> 12907 * <dd> 12908 * The parent has determined an exact size for the child. The child is going to be 12909 * given those bounds regardless of how big it wants to be. 12910 * </dd> 12911 * 12912 * <dt>AT_MOST</dt> 12913 * <dd> 12914 * The child can be as large as it wants up to the specified size. 12915 * </dd> 12916 * </dl> 12917 * 12918 * MeasureSpecs are implemented as ints to reduce object allocation. This class 12919 * is provided to pack and unpack the <size, mode> tuple into the int. 12920 */ 12921 public static class MeasureSpec { 12922 private static final int MODE_SHIFT = 30; 12923 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 12924 12925 /** 12926 * Measure specification mode: The parent has not imposed any constraint 12927 * on the child. It can be whatever size it wants. 12928 */ 12929 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 12930 12931 /** 12932 * Measure specification mode: The parent has determined an exact size 12933 * for the child. The child is going to be given those bounds regardless 12934 * of how big it wants to be. 12935 */ 12936 public static final int EXACTLY = 1 << MODE_SHIFT; 12937 12938 /** 12939 * Measure specification mode: The child can be as large as it wants up 12940 * to the specified size. 12941 */ 12942 public static final int AT_MOST = 2 << MODE_SHIFT; 12943 12944 /** 12945 * Creates a measure specification based on the supplied size and mode. 12946 * 12947 * The mode must always be one of the following: 12948 * <ul> 12949 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 12950 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 12951 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 12952 * </ul> 12953 * 12954 * @param size the size of the measure specification 12955 * @param mode the mode of the measure specification 12956 * @return the measure specification based on size and mode 12957 */ 12958 public static int makeMeasureSpec(int size, int mode) { 12959 return size + mode; 12960 } 12961 12962 /** 12963 * Extracts the mode from the supplied measure specification. 12964 * 12965 * @param measureSpec the measure specification to extract the mode from 12966 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 12967 * {@link android.view.View.MeasureSpec#AT_MOST} or 12968 * {@link android.view.View.MeasureSpec#EXACTLY} 12969 */ 12970 public static int getMode(int measureSpec) { 12971 return (measureSpec & MODE_MASK); 12972 } 12973 12974 /** 12975 * Extracts the size from the supplied measure specification. 12976 * 12977 * @param measureSpec the measure specification to extract the size from 12978 * @return the size in pixels defined in the supplied measure specification 12979 */ 12980 public static int getSize(int measureSpec) { 12981 return (measureSpec & ~MODE_MASK); 12982 } 12983 12984 /** 12985 * Returns a String representation of the specified measure 12986 * specification. 12987 * 12988 * @param measureSpec the measure specification to convert to a String 12989 * @return a String with the following format: "MeasureSpec: MODE SIZE" 12990 */ 12991 public static String toString(int measureSpec) { 12992 int mode = getMode(measureSpec); 12993 int size = getSize(measureSpec); 12994 12995 StringBuilder sb = new StringBuilder("MeasureSpec: "); 12996 12997 if (mode == UNSPECIFIED) 12998 sb.append("UNSPECIFIED "); 12999 else if (mode == EXACTLY) 13000 sb.append("EXACTLY "); 13001 else if (mode == AT_MOST) 13002 sb.append("AT_MOST "); 13003 else 13004 sb.append(mode).append(" "); 13005 13006 sb.append(size); 13007 return sb.toString(); 13008 } 13009 } 13010 13011 class CheckForLongPress implements Runnable { 13012 13013 private int mOriginalWindowAttachCount; 13014 13015 public void run() { 13016 if (isPressed() && (mParent != null) 13017 && mOriginalWindowAttachCount == mWindowAttachCount) { 13018 if (performLongClick()) { 13019 mHasPerformedLongPress = true; 13020 } 13021 } 13022 } 13023 13024 public void rememberWindowAttachCount() { 13025 mOriginalWindowAttachCount = mWindowAttachCount; 13026 } 13027 } 13028 13029 private final class CheckForTap implements Runnable { 13030 public void run() { 13031 mPrivateFlags &= ~PREPRESSED; 13032 mPrivateFlags |= PRESSED; 13033 refreshDrawableState(); 13034 checkForLongClick(ViewConfiguration.getTapTimeout()); 13035 } 13036 } 13037 13038 private final class PerformClick implements Runnable { 13039 public void run() { 13040 performClick(); 13041 } 13042 } 13043 13044 /** @hide */ 13045 public void hackTurnOffWindowResizeAnim(boolean off) { 13046 mAttachInfo.mTurnOffWindowResizeAnim = off; 13047 } 13048 13049 /** 13050 * This method returns a ViewPropertyAnimator object, which can be used to animate 13051 * specific properties on this View. 13052 * 13053 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 13054 */ 13055 public ViewPropertyAnimator animate() { 13056 if (mAnimator == null) { 13057 mAnimator = new ViewPropertyAnimator(this); 13058 } 13059 return mAnimator; 13060 } 13061 13062 /** 13063 * Interface definition for a callback to be invoked when a key event is 13064 * dispatched to this view. The callback will be invoked before the key 13065 * event is given to the view. 13066 */ 13067 public interface OnKeyListener { 13068 /** 13069 * Called when a key is dispatched to a view. This allows listeners to 13070 * get a chance to respond before the target view. 13071 * 13072 * @param v The view the key has been dispatched to. 13073 * @param keyCode The code for the physical key that was pressed 13074 * @param event The KeyEvent object containing full information about 13075 * the event. 13076 * @return True if the listener has consumed the event, false otherwise. 13077 */ 13078 boolean onKey(View v, int keyCode, KeyEvent event); 13079 } 13080 13081 /** 13082 * Interface definition for a callback to be invoked when a touch event is 13083 * dispatched to this view. The callback will be invoked before the touch 13084 * event is given to the view. 13085 */ 13086 public interface OnTouchListener { 13087 /** 13088 * Called when a touch event is dispatched to a view. This allows listeners to 13089 * get a chance to respond before the target view. 13090 * 13091 * @param v The view the touch event has been dispatched to. 13092 * @param event The MotionEvent object containing full information about 13093 * the event. 13094 * @return True if the listener has consumed the event, false otherwise. 13095 */ 13096 boolean onTouch(View v, MotionEvent event); 13097 } 13098 13099 /** 13100 * Interface definition for a callback to be invoked when a generic motion event is 13101 * dispatched to this view. The callback will be invoked before the generic motion 13102 * event is given to the view. 13103 */ 13104 public interface OnGenericMotionListener { 13105 /** 13106 * Called when a generic motion event is dispatched to a view. This allows listeners to 13107 * get a chance to respond before the target view. 13108 * 13109 * @param v The view the generic motion event has been dispatched to. 13110 * @param event The MotionEvent object containing full information about 13111 * the event. 13112 * @return True if the listener has consumed the event, false otherwise. 13113 */ 13114 boolean onGenericMotion(View v, MotionEvent event); 13115 } 13116 13117 /** 13118 * Interface definition for a callback to be invoked when a view has been clicked and held. 13119 */ 13120 public interface OnLongClickListener { 13121 /** 13122 * Called when a view has been clicked and held. 13123 * 13124 * @param v The view that was clicked and held. 13125 * 13126 * @return true if the callback consumed the long click, false otherwise. 13127 */ 13128 boolean onLongClick(View v); 13129 } 13130 13131 /** 13132 * Interface definition for a callback to be invoked when a drag is being dispatched 13133 * to this view. The callback will be invoked before the hosting view's own 13134 * onDrag(event) method. If the listener wants to fall back to the hosting view's 13135 * onDrag(event) behavior, it should return 'false' from this callback. 13136 */ 13137 public interface OnDragListener { 13138 /** 13139 * Called when a drag event is dispatched to a view. This allows listeners 13140 * to get a chance to override base View behavior. 13141 * 13142 * @param v The View that received the drag event. 13143 * @param event The {@link android.view.DragEvent} object for the drag event. 13144 * @return {@code true} if the drag event was handled successfully, or {@code false} 13145 * if the drag event was not handled. Note that {@code false} will trigger the View 13146 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 13147 */ 13148 boolean onDrag(View v, DragEvent event); 13149 } 13150 13151 /** 13152 * Interface definition for a callback to be invoked when the focus state of 13153 * a view changed. 13154 */ 13155 public interface OnFocusChangeListener { 13156 /** 13157 * Called when the focus state of a view has changed. 13158 * 13159 * @param v The view whose state has changed. 13160 * @param hasFocus The new focus state of v. 13161 */ 13162 void onFocusChange(View v, boolean hasFocus); 13163 } 13164 13165 /** 13166 * Interface definition for a callback to be invoked when a view is clicked. 13167 */ 13168 public interface OnClickListener { 13169 /** 13170 * Called when a view has been clicked. 13171 * 13172 * @param v The view that was clicked. 13173 */ 13174 void onClick(View v); 13175 } 13176 13177 /** 13178 * Interface definition for a callback to be invoked when the context menu 13179 * for this view is being built. 13180 */ 13181 public interface OnCreateContextMenuListener { 13182 /** 13183 * Called when the context menu for this view is being built. It is not 13184 * safe to hold onto the menu after this method returns. 13185 * 13186 * @param menu The context menu that is being built 13187 * @param v The view for which the context menu is being built 13188 * @param menuInfo Extra information about the item for which the 13189 * context menu should be shown. This information will vary 13190 * depending on the class of v. 13191 */ 13192 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 13193 } 13194 13195 /** 13196 * Interface definition for a callback to be invoked when the status bar changes 13197 * visibility. 13198 * 13199 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 13200 */ 13201 public interface OnSystemUiVisibilityChangeListener { 13202 /** 13203 * Called when the status bar changes visibility because of a call to 13204 * {@link View#setSystemUiVisibility(int)}. 13205 * 13206 * @param visibility {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}. 13207 */ 13208 public void onSystemUiVisibilityChange(int visibility); 13209 } 13210 13211 /** 13212 * Interface definition for a callback to be invoked when this view is attached 13213 * or detached from its window. 13214 */ 13215 public interface OnAttachStateChangeListener { 13216 /** 13217 * Called when the view is attached to a window. 13218 * @param v The view that was attached 13219 */ 13220 public void onViewAttachedToWindow(View v); 13221 /** 13222 * Called when the view is detached from a window. 13223 * @param v The view that was detached 13224 */ 13225 public void onViewDetachedFromWindow(View v); 13226 } 13227 13228 private final class UnsetPressedState implements Runnable { 13229 public void run() { 13230 setPressed(false); 13231 } 13232 } 13233 13234 /** 13235 * Base class for derived classes that want to save and restore their own 13236 * state in {@link android.view.View#onSaveInstanceState()}. 13237 */ 13238 public static class BaseSavedState extends AbsSavedState { 13239 /** 13240 * Constructor used when reading from a parcel. Reads the state of the superclass. 13241 * 13242 * @param source 13243 */ 13244 public BaseSavedState(Parcel source) { 13245 super(source); 13246 } 13247 13248 /** 13249 * Constructor called by derived classes when creating their SavedState objects 13250 * 13251 * @param superState The state of the superclass of this view 13252 */ 13253 public BaseSavedState(Parcelable superState) { 13254 super(superState); 13255 } 13256 13257 public static final Parcelable.Creator<BaseSavedState> CREATOR = 13258 new Parcelable.Creator<BaseSavedState>() { 13259 public BaseSavedState createFromParcel(Parcel in) { 13260 return new BaseSavedState(in); 13261 } 13262 13263 public BaseSavedState[] newArray(int size) { 13264 return new BaseSavedState[size]; 13265 } 13266 }; 13267 } 13268 13269 /** 13270 * A set of information given to a view when it is attached to its parent 13271 * window. 13272 */ 13273 static class AttachInfo { 13274 interface Callbacks { 13275 void playSoundEffect(int effectId); 13276 boolean performHapticFeedback(int effectId, boolean always); 13277 } 13278 13279 /** 13280 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 13281 * to a Handler. This class contains the target (View) to invalidate and 13282 * the coordinates of the dirty rectangle. 13283 * 13284 * For performance purposes, this class also implements a pool of up to 13285 * POOL_LIMIT objects that get reused. This reduces memory allocations 13286 * whenever possible. 13287 */ 13288 static class InvalidateInfo implements Poolable<InvalidateInfo> { 13289 private static final int POOL_LIMIT = 10; 13290 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 13291 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 13292 public InvalidateInfo newInstance() { 13293 return new InvalidateInfo(); 13294 } 13295 13296 public void onAcquired(InvalidateInfo element) { 13297 } 13298 13299 public void onReleased(InvalidateInfo element) { 13300 } 13301 }, POOL_LIMIT) 13302 ); 13303 13304 private InvalidateInfo mNext; 13305 private boolean mIsPooled; 13306 13307 View target; 13308 13309 int left; 13310 int top; 13311 int right; 13312 int bottom; 13313 13314 public void setNextPoolable(InvalidateInfo element) { 13315 mNext = element; 13316 } 13317 13318 public InvalidateInfo getNextPoolable() { 13319 return mNext; 13320 } 13321 13322 static InvalidateInfo acquire() { 13323 return sPool.acquire(); 13324 } 13325 13326 void release() { 13327 sPool.release(this); 13328 } 13329 13330 public boolean isPooled() { 13331 return mIsPooled; 13332 } 13333 13334 public void setPooled(boolean isPooled) { 13335 mIsPooled = isPooled; 13336 } 13337 } 13338 13339 final IWindowSession mSession; 13340 13341 final IWindow mWindow; 13342 13343 final IBinder mWindowToken; 13344 13345 final Callbacks mRootCallbacks; 13346 13347 HardwareCanvas mHardwareCanvas; 13348 13349 /** 13350 * The top view of the hierarchy. 13351 */ 13352 View mRootView; 13353 13354 IBinder mPanelParentWindowToken; 13355 Surface mSurface; 13356 13357 boolean mHardwareAccelerated; 13358 boolean mHardwareAccelerationRequested; 13359 HardwareRenderer mHardwareRenderer; 13360 13361 /** 13362 * Scale factor used by the compatibility mode 13363 */ 13364 float mApplicationScale; 13365 13366 /** 13367 * Indicates whether the application is in compatibility mode 13368 */ 13369 boolean mScalingRequired; 13370 13371 /** 13372 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 13373 */ 13374 boolean mTurnOffWindowResizeAnim; 13375 13376 /** 13377 * Left position of this view's window 13378 */ 13379 int mWindowLeft; 13380 13381 /** 13382 * Top position of this view's window 13383 */ 13384 int mWindowTop; 13385 13386 /** 13387 * Indicates whether views need to use 32-bit drawing caches 13388 */ 13389 boolean mUse32BitDrawingCache; 13390 13391 /** 13392 * For windows that are full-screen but using insets to layout inside 13393 * of the screen decorations, these are the current insets for the 13394 * content of the window. 13395 */ 13396 final Rect mContentInsets = new Rect(); 13397 13398 /** 13399 * For windows that are full-screen but using insets to layout inside 13400 * of the screen decorations, these are the current insets for the 13401 * actual visible parts of the window. 13402 */ 13403 final Rect mVisibleInsets = new Rect(); 13404 13405 /** 13406 * The internal insets given by this window. This value is 13407 * supplied by the client (through 13408 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 13409 * be given to the window manager when changed to be used in laying 13410 * out windows behind it. 13411 */ 13412 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 13413 = new ViewTreeObserver.InternalInsetsInfo(); 13414 13415 /** 13416 * All views in the window's hierarchy that serve as scroll containers, 13417 * used to determine if the window can be resized or must be panned 13418 * to adjust for a soft input area. 13419 */ 13420 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 13421 13422 final KeyEvent.DispatcherState mKeyDispatchState 13423 = new KeyEvent.DispatcherState(); 13424 13425 /** 13426 * Indicates whether the view's window currently has the focus. 13427 */ 13428 boolean mHasWindowFocus; 13429 13430 /** 13431 * The current visibility of the window. 13432 */ 13433 int mWindowVisibility; 13434 13435 /** 13436 * Indicates the time at which drawing started to occur. 13437 */ 13438 long mDrawingTime; 13439 13440 /** 13441 * Indicates whether or not ignoring the DIRTY_MASK flags. 13442 */ 13443 boolean mIgnoreDirtyState; 13444 13445 /** 13446 * Indicates whether the view's window is currently in touch mode. 13447 */ 13448 boolean mInTouchMode; 13449 13450 /** 13451 * Indicates that ViewAncestor should trigger a global layout change 13452 * the next time it performs a traversal 13453 */ 13454 boolean mRecomputeGlobalAttributes; 13455 13456 /** 13457 * Set during a traveral if any views want to keep the screen on. 13458 */ 13459 boolean mKeepScreenOn; 13460 13461 /** 13462 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 13463 */ 13464 int mSystemUiVisibility; 13465 13466 /** 13467 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 13468 * attached. 13469 */ 13470 boolean mHasSystemUiListeners; 13471 13472 /** 13473 * Set if the visibility of any views has changed. 13474 */ 13475 boolean mViewVisibilityChanged; 13476 13477 /** 13478 * Set to true if a view has been scrolled. 13479 */ 13480 boolean mViewScrollChanged; 13481 13482 /** 13483 * Global to the view hierarchy used as a temporary for dealing with 13484 * x/y points in the transparent region computations. 13485 */ 13486 final int[] mTransparentLocation = new int[2]; 13487 13488 /** 13489 * Global to the view hierarchy used as a temporary for dealing with 13490 * x/y points in the ViewGroup.invalidateChild implementation. 13491 */ 13492 final int[] mInvalidateChildLocation = new int[2]; 13493 13494 13495 /** 13496 * Global to the view hierarchy used as a temporary for dealing with 13497 * x/y location when view is transformed. 13498 */ 13499 final float[] mTmpTransformLocation = new float[2]; 13500 13501 /** 13502 * The view tree observer used to dispatch global events like 13503 * layout, pre-draw, touch mode change, etc. 13504 */ 13505 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 13506 13507 /** 13508 * A Canvas used by the view hierarchy to perform bitmap caching. 13509 */ 13510 Canvas mCanvas; 13511 13512 /** 13513 * A Handler supplied by a view's {@link android.view.ViewAncestor}. This 13514 * handler can be used to pump events in the UI events queue. 13515 */ 13516 final Handler mHandler; 13517 13518 /** 13519 * Identifier for messages requesting the view to be invalidated. 13520 * Such messages should be sent to {@link #mHandler}. 13521 */ 13522 static final int INVALIDATE_MSG = 0x1; 13523 13524 /** 13525 * Identifier for messages requesting the view to invalidate a region. 13526 * Such messages should be sent to {@link #mHandler}. 13527 */ 13528 static final int INVALIDATE_RECT_MSG = 0x2; 13529 13530 /** 13531 * Temporary for use in computing invalidate rectangles while 13532 * calling up the hierarchy. 13533 */ 13534 final Rect mTmpInvalRect = new Rect(); 13535 13536 /** 13537 * Temporary for use in computing hit areas with transformed views 13538 */ 13539 final RectF mTmpTransformRect = new RectF(); 13540 13541 /** 13542 * Temporary list for use in collecting focusable descendents of a view. 13543 */ 13544 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 13545 13546 /** 13547 * The id of the window for accessibility purposes. 13548 */ 13549 int mAccessibilityWindowId = View.NO_ID; 13550 13551 /** 13552 * Creates a new set of attachment information with the specified 13553 * events handler and thread. 13554 * 13555 * @param handler the events handler the view must use 13556 */ 13557 AttachInfo(IWindowSession session, IWindow window, 13558 Handler handler, Callbacks effectPlayer) { 13559 mSession = session; 13560 mWindow = window; 13561 mWindowToken = window.asBinder(); 13562 mHandler = handler; 13563 mRootCallbacks = effectPlayer; 13564 } 13565 } 13566 13567 /** 13568 * <p>ScrollabilityCache holds various fields used by a View when scrolling 13569 * is supported. This avoids keeping too many unused fields in most 13570 * instances of View.</p> 13571 */ 13572 private static class ScrollabilityCache implements Runnable { 13573 13574 /** 13575 * Scrollbars are not visible 13576 */ 13577 public static final int OFF = 0; 13578 13579 /** 13580 * Scrollbars are visible 13581 */ 13582 public static final int ON = 1; 13583 13584 /** 13585 * Scrollbars are fading away 13586 */ 13587 public static final int FADING = 2; 13588 13589 public boolean fadeScrollBars; 13590 13591 public int fadingEdgeLength; 13592 public int scrollBarDefaultDelayBeforeFade; 13593 public int scrollBarFadeDuration; 13594 13595 public int scrollBarSize; 13596 public ScrollBarDrawable scrollBar; 13597 public float[] interpolatorValues; 13598 public View host; 13599 13600 public final Paint paint; 13601 public final Matrix matrix; 13602 public Shader shader; 13603 13604 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 13605 13606 private static final float[] OPAQUE = { 255 }; 13607 private static final float[] TRANSPARENT = { 0.0f }; 13608 13609 /** 13610 * When fading should start. This time moves into the future every time 13611 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 13612 */ 13613 public long fadeStartTime; 13614 13615 13616 /** 13617 * The current state of the scrollbars: ON, OFF, or FADING 13618 */ 13619 public int state = OFF; 13620 13621 private int mLastColor; 13622 13623 public ScrollabilityCache(ViewConfiguration configuration, View host) { 13624 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 13625 scrollBarSize = configuration.getScaledScrollBarSize(); 13626 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 13627 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 13628 13629 paint = new Paint(); 13630 matrix = new Matrix(); 13631 // use use a height of 1, and then wack the matrix each time we 13632 // actually use it. 13633 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 13634 13635 paint.setShader(shader); 13636 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 13637 this.host = host; 13638 } 13639 13640 public void setFadeColor(int color) { 13641 if (color != 0 && color != mLastColor) { 13642 mLastColor = color; 13643 color |= 0xFF000000; 13644 13645 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 13646 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 13647 13648 paint.setShader(shader); 13649 // Restore the default transfer mode (src_over) 13650 paint.setXfermode(null); 13651 } 13652 } 13653 13654 public void run() { 13655 long now = AnimationUtils.currentAnimationTimeMillis(); 13656 if (now >= fadeStartTime) { 13657 13658 // the animation fades the scrollbars out by changing 13659 // the opacity (alpha) from fully opaque to fully 13660 // transparent 13661 int nextFrame = (int) now; 13662 int framesCount = 0; 13663 13664 Interpolator interpolator = scrollBarInterpolator; 13665 13666 // Start opaque 13667 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 13668 13669 // End transparent 13670 nextFrame += scrollBarFadeDuration; 13671 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 13672 13673 state = FADING; 13674 13675 // Kick off the fade animation 13676 host.invalidate(true); 13677 } 13678 } 13679 13680 } 13681} 13682